blinker-sdk 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- "use strict";var BlinkerSDK=(()=>{var _=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var ge=(i,e)=>{for(var t in e)_(i,t,{get:e[t],enumerable:!0})},he=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ue(e))!ce.call(i,n)&&n!==t&&_(i,n,{get:()=>e[n],enumerable:!(r=de(e,n))||r.enumerable});return i};var pe=i=>he(_({},"__esModule",{value:!0}),i);var xe={};ge(xe,{Blinker:()=>m,DEFAULT_FILTERS:()=>p,DEFAULT_WIDGET_CONFIG:()=>R,blinker:()=>ae,default:()=>ke});var z="https://api.blinker.live",w={EVENT_QUEUE:"blinker_event_queue",SESSION:"blinker_session",USER_CONTEXT:"blinker_user_context"},h={captureErrors:!0,captureRejections:!0,enableBatching:!0,batchSize:10,flushInterval:5e3,enableOfflineStorage:!0,maxStoredEvents:100,enableDeduplication:!0,deduplicationWindow:6e4,maxEventsPerMinute:100,sampleRate:1,debug:!1},x={OFFLINE_RETRY_TIMEOUT:3e4,MIN_FLUSH_INTERVAL:1e3,MAX_FLUSH_INTERVAL:6e4};var p={ignoreHttpCodes:[401,403],ignoreErrorTypes:[],ignoreMessagePatterns:["ResizeObserver loop","Script error","ResizeObserver loop completed"],captureAll:!1};var D="[Blinker]";function U(i){let e=()=>{};return i?{log:(...t)=>console.log(D,...t),warn:(...t)=>console.warn(D,...t),error:(...t)=>console.error(D,...t)}:{log:e,warn:e,error:e}}var Q=U(!1);function B(i){Q=U(i)}function d(){return Q}var E=class{constructor(e){var t,r,n,o;this.filters={ignoreHttpCodes:(t=e==null?void 0:e.ignoreHttpCodes)!=null?t:p.ignoreHttpCodes,ignoreErrorTypes:(r=e==null?void 0:e.ignoreErrorTypes)!=null?r:p.ignoreErrorTypes,ignoreMessagePatterns:(n=e==null?void 0:e.ignoreMessagePatterns)!=null?n:p.ignoreMessagePatterns,captureAll:(o=e==null?void 0:e.captureAll)!=null?o:p.captureAll}}shouldCapture(e,t,r){let n=d();if(this.filters.captureAll)return!0;if(r!==void 0&&this.filters.ignoreHttpCodes.includes(r))return n.log("Event filtered out by HTTP code:",r),!1;if(t&&this.filters.ignoreErrorTypes.includes(t))return n.log("Event filtered out by error type:",t),!1;for(let o of this.filters.ignoreMessagePatterns)if(e.toLowerCase().includes(o.toLowerCase()))return n.log("Event filtered out by message pattern:",o),!1;if(r===void 0){let o=e.match(/(?:HTTP\s*|status[:\s]*)?(\d{3})(?:\s|$|:)/i);if(o){let s=parseInt(o[1],10);if(s>=100&&s<600&&this.filters.ignoreHttpCodes.includes(s))return n.log("Event filtered out by extracted HTTP code:",s),!1}}return!0}getFilters(){return{...this.filters}}updateFilters(e){var t,r,n,o;this.filters={ignoreHttpCodes:(t=e.ignoreHttpCodes)!=null?t:this.filters.ignoreHttpCodes,ignoreErrorTypes:(r=e.ignoreErrorTypes)!=null?r:this.filters.ignoreErrorTypes,ignoreMessagePatterns:(n=e.ignoreMessagePatterns)!=null?n:this.filters.ignoreMessagePatterns,captureAll:(o=e.captureAll)!=null?o:this.filters.captureAll}}};function g(){return typeof window!="undefined"}function H(){if(!g())return!1;try{let i="__blinker_test__";return localStorage.setItem(i,"test"),localStorage.removeItem(i),!0}catch(i){return!1}}function N(){if(!g())return!1;try{let i="__blinker_test__";return sessionStorage.setItem(i,"test"),sessionStorage.removeItem(i),!0}catch(i){return!1}}function f(){var i;return g()&&(i=navigator.onLine)!=null?i:!0}function V(){if(g())return window.location.href}function G(){return g()?window.location.pathname:"unknown"}function j(){if(g())return navigator.userAgent}function Y(){if(g())return document.referrer||void 0}var C=class{constructor(e=100){this.storageKey=w.EVENT_QUEUE;this.maxEvents=e,this.available=H()}isAvailable(){return this.available}store(e){if(!this.available)return!1;let t=d();try{let r=this.getAll(),n={event:e,storedAt:new Date().toISOString(),retries:0};for(r.push(n);r.length>this.maxEvents;)r.shift();return localStorage.setItem(this.storageKey,JSON.stringify(r)),t.log(`Event stored offline. Total stored: ${r.length}`),!0}catch(r){return t.error("Failed to store event offline:",r),!1}}storeMany(e){if(!this.available||e.length===0)return 0;let t=d(),r=0;try{let n=this.getAll();for(let o of e){let s={event:o,storedAt:new Date().toISOString(),retries:0};n.push(s),r++}for(;n.length>this.maxEvents;)n.shift();return localStorage.setItem(this.storageKey,JSON.stringify(n)),t.log(`Stored ${r} events offline. Total stored: ${n.length}`),r}catch(n){return t.error("Failed to store events offline:",n),r}}getAll(){if(!this.available)return[];try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return[]}}retrieveAll(){if(!this.available)return[];let e=d();try{let t=this.getAll();return t.length===0?[]:(localStorage.removeItem(this.storageKey),e.log(`Retrieved ${t.length} stored events`),t.map(r=>r.event))}catch(t){return e.error("Failed to retrieve stored events:",t),[]}}count(){return this.getAll().length}clear(){if(this.available)try{localStorage.removeItem(this.storageKey)}catch(e){}}};async function J(i,e,t){let r=d(),n=`${i.replace(/\/$/,"")}/events`;if(t.length===0)return{success:!0,count:0};let o=async()=>{try{let a=t.length===1?K(t[0]):{events:t.map(K)},l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-blinker-token":e},body:JSON.stringify(a)});if(!l.ok){let u=await l.text().catch(()=>"Unknown error");return r.error(`Failed to send events: ${l.status} - ${u}`),{success:!1,error:`HTTP ${l.status}: ${u}`}}return r.log(`Events sent successfully: ${t.length} event(s)`),{success:!0,count:t.length}}catch(a){let l=a instanceof Error?a.message:"Unknown error";return r.error("Error sending events:",l),{success:!1,error:l}}},s=await o();return!s.success&&g()&&!f()&&(r.log("Offline, waiting for connection to retry..."),await fe(x.OFFLINE_RETRY_TIMEOUT))?(r.log("Back online, retrying..."),o()):s}function K(i){return{type:i.type,message:i.message,payload:i.payload||{},timestamp:i.timestamp,url:i.url,userAgent:i.userAgent,sessionId:i.sessionId,userId:i.userId,userTraits:i.userTraits,context:i.context,count:i.count}}function fe(i){return new Promise(e=>{if(!g()){e(!1);return}let t=setTimeout(()=>e(!1),i),r=()=>{clearTimeout(t),window.removeEventListener("online",r),e(!0)};window.addEventListener("online",r)})}var T=class{constructor(e,t){this.queue=[];this.flushTimer=null;this.isFlushing=!1;this.handleOnline=()=>{d().log("Back online, flushing stored events"),this.flush()};var r,n,o,s,a;this.token=e,this.config={enableBatching:(r=t==null?void 0:t.enableBatching)!=null?r:h.enableBatching,batchSize:(n=t==null?void 0:t.batchSize)!=null?n:h.batchSize,flushInterval:Math.max(x.MIN_FLUSH_INTERVAL,Math.min((o=t==null?void 0:t.flushInterval)!=null?o:h.flushInterval,x.MAX_FLUSH_INTERVAL)),enableOfflineStorage:(s=t==null?void 0:t.enableOfflineStorage)!=null?s:h.enableOfflineStorage,maxStoredEvents:(a=t==null?void 0:t.maxStoredEvents)!=null?a:h.maxStoredEvents},this.storage=new C(this.config.maxStoredEvents),this.config.enableBatching&&this.startFlushTimer(),g()&&this.config.enableOfflineStorage&&window.addEventListener("online",this.handleOnline)}async add(e){let t=d();return this.config.enableBatching?(this.queue.push(e),t.log(`Event queued. Queue size: ${this.queue.length}`),this.queue.length>=this.config.batchSize?this.flush():{success:!0}):this.sendImmediately([e])}async flush(){let e=d();if(this.isFlushing)return e.log("Flush already in progress, skipping"),{success:!0};let t=[...this.queue];if(this.queue=[],this.config.enableOfflineStorage&&f()){let r=this.storage.retrieveAll();r.length>0&&(t.unshift(...r),e.log(`Including ${r.length} stored offline events`))}if(t.length===0)return{success:!0,count:0};this.isFlushing=!0;try{let r=await this.sendImmediately(t);return!r.success&&this.config.enableOfflineStorage&&!f()&&(e.log("Send failed while offline, storing events"),this.storage.storeMany(t)),r}finally{this.isFlushing=!1}}async sendImmediately(e){let t=d();return!f()&&this.config.enableOfflineStorage?(t.log("Offline, storing events for later"),{success:!0,count:this.storage.storeMany(e)}):J(z,this.token,e)}getStats(){let e=this.queue.length,t=this.storage.count();return{queueSize:e,storedSize:t,totalPending:e+t}}size(){return this.queue.length}startFlushTimer(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushInterval))}stopFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}destroy(){this.stopFlushTimer(),g()&&window.removeEventListener("online",this.handleOnline),this.queue.length>0&&f()?this.flush():this.queue.length>0&&this.config.enableOfflineStorage&&this.storage.storeMany(this.queue),this.queue=[]}};function me(i){let e=5381;for(let t=0;t<i.length;t++)e=(e<<5)+e^i.charCodeAt(t);return(e>>>0).toString(16)}function X(i,e){let t=i;if(e){let n=e.split(`
2
- `).slice(1,4).map(o=>o.replace(/:\d+:\d+\)?$/,"").trim()).join("|");t+="|"+n}return me(t)}function v(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`${i}-${e}`}var I=class{constructor(){this.session=null;this.storageKey=w.SESSION;this.storageAvailable=N(),this.initSession()}initSession(){let e=d();if(this.storageAvailable)try{let t=sessionStorage.getItem(this.storageKey);if(t){this.session=JSON.parse(t),e.log("Session restored:",this.session.id);return}}catch(t){}this.session={id:v(),startedAt:new Date().toISOString(),pageViews:0,lastActivityAt:new Date().toISOString()},this.persist(),e.log("New session created:",this.session.id)}getSessionId(){var e,t;return(t=(e=this.session)==null?void 0:e.id)!=null?t:v()}getSession(){return this.session||this.initSession(),{...this.session}}recordPageView(){this.session&&(this.session.pageViews++,this.session.lastActivityAt=new Date().toISOString(),this.persist())}touch(){this.session&&(this.session.lastActivityAt=new Date().toISOString(),this.persist())}getDuration(){if(!this.session)return 0;let e=new Date(this.session.startedAt).getTime();return Date.now()-e}persist(){if(!(!this.storageAvailable||!this.session))try{sessionStorage.setItem(this.storageKey,JSON.stringify(this.session))}catch(e){}}endSession(){if(this.storageAvailable)try{sessionStorage.removeItem(this.storageKey)}catch(e){}this.session=null}};var L=class{constructor(e){this.user=null;this.customContext={};this.sessionManager=e}identify(e,t){let r=d();this.user={userId:e,traits:t?{...t}:void 0,identifiedAt:new Date().toISOString()},r.log("User identified:",e)}getUserId(){var e;return(e=this.user)==null?void 0:e.userId}getUserTraits(){var e;return(e=this.user)!=null&&e.traits?{...this.user.traits}:void 0}isIdentified(){return this.user!==null}setContext(e,t){let r=d();this.customContext[e]=t,r.log("Context set:",e)}getContextValue(e){return this.customContext[e]}getCustomContext(){return{...this.customContext}}getEventContext(){var e,t;return{sessionId:this.sessionManager.getSessionId(),userId:(e=this.user)==null?void 0:e.userId,userTraits:(t=this.user)!=null&&t.traits?{...this.user.traits}:void 0,custom:{...this.customContext}}}clearIdentity(){let e=d();this.user=null,e.log("User identity cleared")}clearAll(){let e=d();this.user=null,this.customContext={},e.log("All context cleared")}};var Z=60*1e3,M=class{constructor(e){this.maxPerMinute=e!=null?e:h.maxEventsPerMinute,this.state={count:0,windowStart:Date.now(),dropped:0}}allow(){let e=d();if(this.maxPerMinute===0)return!0;let t=Date.now();return t-this.state.windowStart>=Z&&(this.state.dropped>0&&e.warn(`Rate limit: ${this.state.dropped} events dropped in last minute`),this.state={count:0,windowStart:t,dropped:0}),this.state.count<this.maxPerMinute?(this.state.count++,!0):(this.state.dropped++,this.state.dropped===1&&e.warn(`Rate limit reached: ${this.maxPerMinute} events/minute`),!1)}getState(){return{...this.state}}getRemaining(){return this.maxPerMinute===0?1/0:Date.now()-this.state.windowStart>=Z?this.maxPerMinute:Math.max(0,this.maxPerMinute-this.state.count)}reset(){this.state={count:0,windowStart:Date.now(),dropped:0}}setLimit(e){this.maxPerMinute=e}};var q=class{constructor(e){this.sampled=0;this.dropped=0;this.sampleRate=Math.max(0,Math.min(1,e!=null?e:h.sampleRate))}shouldSample(e=!1){let t=d();return e?(this.sampled++,!0):this.sampleRate>=1?(this.sampled++,!0):this.sampleRate<=0?(this.dropped++,!1):Math.random()<this.sampleRate?(this.sampled++,!0):(this.dropped++,t.log("Event sampled out"),!1)}getStats(){return{sampled:this.sampled,dropped:this.dropped,rate:this.sampleRate}}setRate(e){this.sampleRate=Math.max(0,Math.min(1,e))}getRate(){return this.sampleRate}resetStats(){this.sampled=0,this.dropped=0}};var A=class{constructor(e,t){this.entries=new Map;this.cleanupTimer=null;this.enabled=e!=null?e:h.enableDeduplication,this.windowMs=t!=null?t:h.deduplicationWindow,this.enabled&&this.startCleanup()}check(e,t){let r=X(e,t);if(!this.enabled)return{shouldSend:!0,fingerprint:r,count:1,isDuplicate:!1};let n=d(),o=Date.now(),s=this.entries.get(r);if(s){if(o-s.firstSeen<this.windowMs)return s.count++,s.lastSeen=o,n.log(`Duplicate error detected (count: ${s.count}):`,e.substring(0,50)),{shouldSend:!1,fingerprint:r,count:s.count,isDuplicate:!0};this.entries.delete(r)}return this.entries.set(r,{fingerprint:r,firstSeen:o,count:1,lastSeen:o}),{shouldSend:!0,fingerprint:r,count:1,isDuplicate:!1}}getCount(e){var t,r;return(r=(t=this.entries.get(e))==null?void 0:t.count)!=null?r:1}flush(){let e=Array.from(this.entries.values()).filter(t=>t.count>1);return this.entries.clear(),e}startCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanup()},this.windowMs)}cleanup(){let e=Date.now(),t=d(),r=0;for(let[n,o]of this.entries)e-o.firstSeen>=this.windowMs&&(this.entries.delete(n),r++);r>0&&t.log(`Deduplication cleanup: removed ${r} expired entries`)}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.entries.clear()}getStats(){return{entries:this.entries.size,enabled:this.enabled,windowMs:this.windowMs}}};var y=null,k=null,P=!1;function ee(i,e={}){let{captureErrors:t=!0,captureRejections:r=!0}=e,n=d();if(P){n.warn("Error handlers already set up");return}if(!g()){n.log("Not in browser environment, skipping error handlers");return}t&&(y=window.onerror,window.onerror=function(o,s,a,l,u){let c=typeof o=="string"?o:o.type||"Unknown error",b={source:s,lineno:a,colno:l,stack:u==null?void 0:u.stack,errorType:u==null?void 0:u.name};return n.log("Captured error:",c),i("error",c,b),typeof y=="function"?y.call(window,o,s,a,l,u):!1}),r&&(k=window.onunhandledrejection,window.onunhandledrejection=function(o){let s="Unhandled Rejection",a={},l=o.reason;if(l instanceof Error)s=l.message||s,a.stack=l.stack,a.errorType=l.name;else if(typeof l=="string")s=l;else if(l!=null)try{s=JSON.stringify(l)}catch(u){s=String(l)}n.log("Captured unhandled rejection:",s),i("error",s,a),typeof k=="function"&&k.call(window,o)}),P=!0,n.log("Error handlers set up")}function te(){let i=d();g()&&(y!==void 0&&(window.onerror=y),k!==void 0&&(window.onunhandledrejection=k),y=null,k=null,P=!1,i.log("Error handlers torn down"))}var R={enabled:!1,theme:{primary:"#6366f1",background:"#ffffff",text:"#1f2937",accent:"#10b981"},messages:{greeting:"Opa! Algo n\xE3o saiu como esperado.",subtext:"Pode nos ajudar a entender o que aconteceu?",thankYou:"Valeu! J\xE1 estamos olhando isso.",buttonSend:"Enviar",buttonSkip:"Agora n\xE3o"},position:"bottom-right",delay:2e3,maxShowsPerSession:2,cooldownMinutes:30};var $=class{constructor(e,t){this.element=null;this.pupilLeft=null;this.pupilRight=null;this.mouseTrackingEnabled=!0;this.theme=e,this.onClick=t,this.handleMouseMove=this.handleMouseMove.bind(this)}create(){let e=document.createElementNS("http://www.w3.org/2000/svg","svg");return e.setAttribute("viewBox","0 0 100 100"),e.setAttribute("class","blinker-avatar"),e.innerHTML=this.getSVGContent(),e.addEventListener("click",this.onClick),e.addEventListener("mouseenter",()=>this.setState("hover")),e.addEventListener("mouseleave",()=>this.setState("idle")),this.element=e,this.pupilLeft=e.querySelector(".blinker-pupil-left"),this.pupilRight=e.querySelector(".blinker-pupil-right"),document.addEventListener("mousemove",this.handleMouseMove),e}getSVGContent(){return`
1
+ "use strict";var BlinkerSDK=(()=>{var B=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var ge=(r,e)=>{for(var t in e)B(r,t,{get:e[t],enumerable:!0})},he=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ue(e))!ce.call(r,n)&&n!==t&&B(r,n,{get:()=>e[n],enumerable:!(i=de(e,n))||i.enumerable});return r};var pe=r=>he(B({},"__esModule",{value:!0}),r);var Se={};ge(Se,{Blinker:()=>m,DEFAULT_FILTERS:()=>p,DEFAULT_WIDGET_CONFIG:()=>W,SDK_VERSION:()=>w,blinker:()=>ae,default:()=>xe});var fe="https://api.blinker.live",w="2.0.1",E={EVENT_QUEUE:"blinker_event_queue",SESSION:"blinker_session",USER_CONTEXT:"blinker_user_context"},g={endpoint:fe,enabled:!0,captureErrors:!0,captureRejections:!0,enableBatching:!0,batchSize:10,flushInterval:5e3,enableOfflineStorage:!0,maxStoredEvents:100,enableDeduplication:!0,deduplicationWindow:6e4,maxEventsPerMinute:100,sampleRate:1,debug:!1},x={OFFLINE_RETRY_TIMEOUT:3e4,MIN_FLUSH_INTERVAL:1e3,MAX_FLUSH_INTERVAL:6e4};var p={ignoreHttpCodes:[401,403],ignoreErrorTypes:[],ignoreMessagePatterns:["ResizeObserver loop","Script error","ResizeObserver loop completed"],captureAll:!1};var P="[Blinker]";function U(r){let e=()=>{};return r?{log:(...t)=>console.log(P,...t),warn:(...t)=>console.warn(P,...t),error:(...t)=>console.error(P,...t)}:{log:e,warn:e,error:e}}var Q=U(!1);function C(r){Q=U(r)}function d(){return Q}var T=class{constructor(e){var t,i,n,s;this.filters={ignoreHttpCodes:(t=e==null?void 0:e.ignoreHttpCodes)!=null?t:p.ignoreHttpCodes,ignoreErrorTypes:(i=e==null?void 0:e.ignoreErrorTypes)!=null?i:p.ignoreErrorTypes,ignoreMessagePatterns:(n=e==null?void 0:e.ignoreMessagePatterns)!=null?n:p.ignoreMessagePatterns,captureAll:(s=e==null?void 0:e.captureAll)!=null?s:p.captureAll}}shouldCapture(e,t,i){let n=d();if(this.filters.captureAll)return!0;if(i!==void 0&&this.filters.ignoreHttpCodes.includes(i))return n.log("Event filtered out by HTTP code:",i),!1;if(t&&this.filters.ignoreErrorTypes.includes(t))return n.log("Event filtered out by error type:",t),!1;for(let s of this.filters.ignoreMessagePatterns)if(e.toLowerCase().includes(s.toLowerCase()))return n.log("Event filtered out by message pattern:",s),!1;if(i===void 0){let s=e.match(/(?:HTTP\s*|status[:\s]*)?(\d{3})(?:\s|$|:)/i);if(s){let o=parseInt(s[1],10);if(o>=100&&o<600&&this.filters.ignoreHttpCodes.includes(o))return n.log("Event filtered out by extracted HTTP code:",o),!1}}return!0}getFilters(){return{...this.filters}}updateFilters(e){var t,i,n,s;this.filters={ignoreHttpCodes:(t=e.ignoreHttpCodes)!=null?t:this.filters.ignoreHttpCodes,ignoreErrorTypes:(i=e.ignoreErrorTypes)!=null?i:this.filters.ignoreErrorTypes,ignoreMessagePatterns:(n=e.ignoreMessagePatterns)!=null?n:this.filters.ignoreMessagePatterns,captureAll:(s=e.captureAll)!=null?s:this.filters.captureAll}}};function h(){return typeof window!="undefined"}function N(){if(!h())return!1;try{let r="__blinker_test__";return localStorage.setItem(r,"test"),localStorage.removeItem(r),!0}catch(r){return!1}}function H(){if(!h())return!1;try{let r="__blinker_test__";return sessionStorage.setItem(r,"test"),sessionStorage.removeItem(r),!0}catch(r){return!1}}function f(){var r;return h()&&(r=navigator.onLine)!=null?r:!0}function V(){if(h())return window.location.href}function G(){return h()?window.location.pathname:"unknown"}function j(){if(h())return navigator.userAgent}function K(){if(h())return document.referrer||void 0}var I=class{constructor(e=100){this.storageKey=E.EVENT_QUEUE;this.maxEvents=e,this.available=N()}isAvailable(){return this.available}store(e){if(!this.available)return!1;let t=d();try{let i=this.getAll(),n={event:e,storedAt:new Date().toISOString(),retries:0};for(i.push(n);i.length>this.maxEvents;)i.shift();return localStorage.setItem(this.storageKey,JSON.stringify(i)),t.log(`Event stored offline. Total stored: ${i.length}`),!0}catch(i){return t.error("Failed to store event offline:",i),!1}}storeMany(e){if(!this.available||e.length===0)return 0;let t=d(),i=0;try{let n=this.getAll();for(let s of e){let o={event:s,storedAt:new Date().toISOString(),retries:0};n.push(o),i++}for(;n.length>this.maxEvents;)n.shift();return localStorage.setItem(this.storageKey,JSON.stringify(n)),t.log(`Stored ${i} events offline. Total stored: ${n.length}`),i}catch(n){return t.error("Failed to store events offline:",n),i}}getAll(){if(!this.available)return[];try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return[]}}retrieveAll(){if(!this.available)return[];let e=d();try{let t=this.getAll();return t.length===0?[]:(localStorage.removeItem(this.storageKey),e.log(`Retrieved ${t.length} stored events`),t.map(i=>i.event))}catch(t){return e.error("Failed to retrieve stored events:",t),[]}}count(){return this.getAll().length}clear(){if(this.available)try{localStorage.removeItem(this.storageKey)}catch(e){}}};async function J(r,e,t){let i=d(),n=`${r.replace(/\/$/,"")}/events`;if(t.length===0)return{success:!0,count:0};let s=async()=>{try{let a=t.length===1?Y(t[0]):{events:t.map(Y)},l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-blinker-token":e},body:JSON.stringify(a)});if(!l.ok){let u=await l.text().catch(()=>"Unknown error");return i.error(`Failed to send events: ${l.status} - ${u}`),{success:!1,error:`HTTP ${l.status}: ${u}`}}return i.log(`Events sent successfully: ${t.length} event(s)`),{success:!0,count:t.length}}catch(a){let l=a instanceof Error?a.message:"Unknown error";return i.error("Error sending events:",l),{success:!1,error:l}}},o=await s();return!o.success&&h()&&!f()&&(i.log("Offline, waiting for connection to retry..."),await me(x.OFFLINE_RETRY_TIMEOUT))?(i.log("Back online, retrying..."),s()):o}function Y(r){return{type:r.type,message:r.message,payload:r.payload||{},timestamp:r.timestamp,url:r.url,userAgent:r.userAgent,sessionId:r.sessionId,userId:r.userId,userTraits:r.userTraits,context:r.context,count:r.count}}function me(r){return new Promise(e=>{if(!h()){e(!1);return}let t=setTimeout(()=>e(!1),r),i=()=>{clearTimeout(t),window.removeEventListener("online",i),e(!0)};window.addEventListener("online",i)})}var L=class{constructor(e,t){this.queue=[];this.flushTimer=null;this.isFlushing=!1;this.handleOnline=()=>{d().log("Back online, flushing stored events"),this.flush()};var i,n,s,o,a,l;this.token=e,this.config={endpoint:(i=t==null?void 0:t.endpoint)!=null?i:g.endpoint,enableBatching:(n=t==null?void 0:t.enableBatching)!=null?n:g.enableBatching,batchSize:(s=t==null?void 0:t.batchSize)!=null?s:g.batchSize,flushInterval:Math.max(x.MIN_FLUSH_INTERVAL,Math.min((o=t==null?void 0:t.flushInterval)!=null?o:g.flushInterval,x.MAX_FLUSH_INTERVAL)),enableOfflineStorage:(a=t==null?void 0:t.enableOfflineStorage)!=null?a:g.enableOfflineStorage,maxStoredEvents:(l=t==null?void 0:t.maxStoredEvents)!=null?l:g.maxStoredEvents,onError:t==null?void 0:t.onError},this.storage=new I(this.config.maxStoredEvents),this.config.enableBatching&&this.startFlushTimer(),h()&&this.config.enableOfflineStorage&&window.addEventListener("online",this.handleOnline)}async add(e){let t=d();return this.config.enableBatching?(this.queue.push(e),t.log(`Event queued. Queue size: ${this.queue.length}`),this.queue.length>=this.config.batchSize?this.flush():{success:!0}):this.sendImmediately([e])}async flush(){let e=d();if(this.isFlushing)return e.log("Flush already in progress, skipping"),{success:!0};let t=[...this.queue];if(this.queue=[],this.config.enableOfflineStorage&&f()){let i=this.storage.retrieveAll();i.length>0&&(t.unshift(...i),e.log(`Including ${i.length} stored offline events`))}if(t.length===0)return{success:!0,count:0};this.isFlushing=!0;try{let i=await this.sendImmediately(t);return!i.success&&this.config.enableOfflineStorage&&!f()&&(e.log("Send failed while offline, storing events"),this.storage.storeMany(t)),i}finally{this.isFlushing=!1}}async sendImmediately(e){let t=d();if(!f()&&this.config.enableOfflineStorage)return t.log("Offline, storing events for later"),{success:!0,count:this.storage.storeMany(e)};let i=await J(this.config.endpoint,this.token,e);return!i.success&&this.config.onError&&this.config.onError(i.error||"Unknown error sending events"),i}getStats(){let e=this.queue.length,t=this.storage.count();return{queueSize:e,storedSize:t,totalPending:e+t}}size(){return this.queue.length}startFlushTimer(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushInterval))}stopFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}destroy(){this.stopFlushTimer(),h()&&window.removeEventListener("online",this.handleOnline),this.queue.length>0&&f()?this.flush():this.queue.length>0&&this.config.enableOfflineStorage&&this.storage.storeMany(this.queue),this.queue=[]}};function be(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e^r.charCodeAt(t);return(e>>>0).toString(16)}function X(r,e){let t=r;if(e){let n=e.split(`
2
+ `).slice(1,4).map(s=>s.replace(/:\d+:\d+\)?$/,"").trim()).join("|");t+="|"+n}return be(t)}function v(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`${r}-${e}`}var M=class{constructor(){this.session=null;this.storageKey=E.SESSION;this.storageAvailable=H(),this.initSession()}initSession(){let e=d();if(this.storageAvailable)try{let t=sessionStorage.getItem(this.storageKey);if(t){this.session=JSON.parse(t),e.log("Session restored:",this.session.id);return}}catch(t){}this.session={id:v(),startedAt:new Date().toISOString(),pageViews:0,lastActivityAt:new Date().toISOString()},this.persist(),e.log("New session created:",this.session.id)}getSessionId(){var e,t;return(t=(e=this.session)==null?void 0:e.id)!=null?t:v()}getSession(){return this.session||this.initSession(),{...this.session}}recordPageView(){this.session&&(this.session.pageViews++,this.session.lastActivityAt=new Date().toISOString(),this.persist())}touch(){this.session&&(this.session.lastActivityAt=new Date().toISOString(),this.persist())}getDuration(){if(!this.session)return 0;let e=new Date(this.session.startedAt).getTime();return Date.now()-e}persist(){if(!(!this.storageAvailable||!this.session))try{sessionStorage.setItem(this.storageKey,JSON.stringify(this.session))}catch(e){}}endSession(){if(this.storageAvailable)try{sessionStorage.removeItem(this.storageKey)}catch(e){}this.session=null}};var q=class{constructor(e){this.user=null;this.customContext={};this.sessionManager=e}identify(e,t){let i=d();this.user={userId:e,traits:t?{...t}:void 0,identifiedAt:new Date().toISOString()},i.log("User identified:",e)}getUserId(){var e;return(e=this.user)==null?void 0:e.userId}getUserTraits(){var e;return(e=this.user)!=null&&e.traits?{...this.user.traits}:void 0}isIdentified(){return this.user!==null}setContext(e,t){let i=d();this.customContext[e]=t,i.log("Context set:",e)}getContextValue(e){return this.customContext[e]}getCustomContext(){return{...this.customContext}}getEventContext(){var e,t;return{sessionId:this.sessionManager.getSessionId(),userId:(e=this.user)==null?void 0:e.userId,userTraits:(t=this.user)!=null&&t.traits?{...this.user.traits}:void 0,custom:{...this.customContext}}}clearIdentity(){let e=d();this.user=null,e.log("User identity cleared")}clearAll(){let e=d();this.user=null,this.customContext={},e.log("All context cleared")}};var Z=60*1e3,A=class{constructor(e){this.maxPerMinute=e!=null?e:g.maxEventsPerMinute,this.state={count:0,windowStart:Date.now(),dropped:0}}allow(){let e=d();if(this.maxPerMinute===0)return!0;let t=Date.now();return t-this.state.windowStart>=Z&&(this.state.dropped>0&&e.warn(`Rate limit: ${this.state.dropped} events dropped in last minute`),this.state={count:0,windowStart:t,dropped:0}),this.state.count<this.maxPerMinute?(this.state.count++,!0):(this.state.dropped++,this.state.dropped===1&&e.warn(`Rate limit reached: ${this.maxPerMinute} events/minute`),!1)}getState(){return{...this.state}}getRemaining(){return this.maxPerMinute===0?1/0:Date.now()-this.state.windowStart>=Z?this.maxPerMinute:Math.max(0,this.maxPerMinute-this.state.count)}reset(){this.state={count:0,windowStart:Date.now(),dropped:0}}setLimit(e){this.maxPerMinute=e}};var R=class{constructor(e){this.sampled=0;this.dropped=0;this.sampleRate=Math.max(0,Math.min(1,e!=null?e:g.sampleRate))}shouldSample(e=!1){let t=d();return e?(this.sampled++,!0):this.sampleRate>=1?(this.sampled++,!0):this.sampleRate<=0?(this.dropped++,!1):Math.random()<this.sampleRate?(this.sampled++,!0):(this.dropped++,t.log("Event sampled out"),!1)}getStats(){return{sampled:this.sampled,dropped:this.dropped,rate:this.sampleRate}}setRate(e){this.sampleRate=Math.max(0,Math.min(1,e))}getRate(){return this.sampleRate}resetStats(){this.sampled=0,this.dropped=0}};var $=class{constructor(e,t){this.entries=new Map;this.cleanupTimer=null;this.enabled=e!=null?e:g.enableDeduplication,this.windowMs=t!=null?t:g.deduplicationWindow,this.enabled&&this.startCleanup()}check(e,t){let i=X(e,t);if(!this.enabled)return{shouldSend:!0,fingerprint:i,count:1,isDuplicate:!1};let n=d(),s=Date.now(),o=this.entries.get(i);if(o){if(s-o.firstSeen<this.windowMs)return o.count++,o.lastSeen=s,n.log(`Duplicate error detected (count: ${o.count}):`,e.substring(0,50)),{shouldSend:!1,fingerprint:i,count:o.count,isDuplicate:!0};this.entries.delete(i)}return this.entries.set(i,{fingerprint:i,firstSeen:s,count:1,lastSeen:s}),{shouldSend:!0,fingerprint:i,count:1,isDuplicate:!1}}getCount(e){var t,i;return(i=(t=this.entries.get(e))==null?void 0:t.count)!=null?i:1}flush(){let e=Array.from(this.entries.values()).filter(t=>t.count>1);return this.entries.clear(),e}startCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanup()},this.windowMs)}cleanup(){let e=Date.now(),t=d(),i=0;for(let[n,s]of this.entries)e-s.firstSeen>=this.windowMs&&(this.entries.delete(n),i++);i>0&&t.log(`Deduplication cleanup: removed ${i} expired entries`)}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.entries.clear()}getStats(){return{entries:this.entries.size,enabled:this.enabled,windowMs:this.windowMs}}};var y=null,k=null,z=!1;function ee(r,e={}){let{captureErrors:t=!0,captureRejections:i=!0}=e,n=d();if(z){n.warn("Error handlers already set up");return}if(!h()){n.log("Not in browser environment, skipping error handlers");return}t&&(y=window.onerror,window.onerror=function(s,o,a,l,u){let c=typeof s=="string"?s:s.type||"Unknown error",b={source:o,lineno:a,colno:l,stack:u==null?void 0:u.stack,errorType:u==null?void 0:u.name};return n.log("Captured error:",c),r("error",c,b),typeof y=="function"?y.call(window,s,o,a,l,u):!1}),i&&(k=window.onunhandledrejection,window.onunhandledrejection=function(s){let o="Unhandled Rejection",a={},l=s.reason;if(l instanceof Error)o=l.message||o,a.stack=l.stack,a.errorType=l.name;else if(typeof l=="string")o=l;else if(l!=null)try{o=JSON.stringify(l)}catch(u){o=String(l)}n.log("Captured unhandled rejection:",o),r("error",o,a),typeof k=="function"&&k.call(window,s)}),z=!0,n.log("Error handlers set up")}function te(){let r=d();h()&&(y!==void 0&&(window.onerror=y),k!==void 0&&(window.onunhandledrejection=k),y=null,k=null,z=!1,r.log("Error handlers torn down"))}var W={enabled:!1,theme:{primary:"#6366f1",background:"#ffffff",text:"#1f2937",accent:"#10b981"},messages:{greeting:"Opa! Algo n\xE3o saiu como esperado.",subtext:"Pode nos ajudar a entender o que aconteceu?",thankYou:"Valeu! J\xE1 estamos olhando isso.",buttonSend:"Enviar",buttonSkip:"Agora n\xE3o"},position:"bottom-right",delay:2e3,maxShowsPerSession:2,cooldownMinutes:30};var O=class{constructor(e,t){this.element=null;this.pupilLeft=null;this.pupilRight=null;this.mouseTrackingEnabled=!0;this.theme=e,this.onClick=t,this.handleMouseMove=this.handleMouseMove.bind(this)}create(){let e=document.createElementNS("http://www.w3.org/2000/svg","svg");return e.setAttribute("viewBox","0 0 100 100"),e.setAttribute("class","blinker-avatar"),e.innerHTML=this.getSVGContent(),e.addEventListener("click",this.onClick),e.addEventListener("mouseenter",()=>this.setState("hover")),e.addEventListener("mouseleave",()=>this.setState("idle")),this.element=e,this.pupilLeft=e.querySelector(".blinker-pupil-left"),this.pupilRight=e.querySelector(".blinker-pupil-right"),document.addEventListener("mousemove",this.handleMouseMove),e}getSVGContent(){return`
3
3
  <defs>
4
4
  <linearGradient id="blinker-body-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
5
5
  <stop offset="0%" style="stop-color:${this.theme.primary};stop-opacity:1" />
@@ -54,7 +54,7 @@
54
54
  <!-- Decorative elements -->
55
55
  <circle cx="30" cy="55" r="3" fill="${this.theme.primary}" opacity="0.3" />
56
56
  <circle cx="70" cy="55" r="3" fill="${this.theme.primary}" opacity="0.3" />
57
- `}handleMouseMove(e){if(!this.mouseTrackingEnabled||!this.element||!this.pupilLeft||!this.pupilRight)return;let t=this.element.getBoundingClientRect(),r=t.left+t.width/2,n=t.top+t.height/2,o=(e.clientX-r)/50,s=(e.clientY-n)/50,a=3,l=Math.max(-a,Math.min(a,o)),u=Math.max(-a,Math.min(a,s));this.pupilLeft.setAttribute("transform",`translate(${l}, ${u})`),this.pupilRight.setAttribute("transform",`translate(${l}, ${u})`)}setState(e){this.element&&(this.element.classList.remove("idle","hover","minimized","talking"),this.element.classList.add(e))}setMinimized(e){this.element&&(e?(this.element.classList.add("minimized"),this.mouseTrackingEnabled=!1):(this.element.classList.remove("minimized"),this.mouseTrackingEnabled=!0))}updateTheme(e){this.theme=e,this.element&&(this.element.innerHTML=this.getSVGContent(),this.pupilLeft=this.element.querySelector(".blinker-pupil-left"),this.pupilRight=this.element.querySelector(".blinker-pupil-right"))}adjustColor(e,t){let r=parseInt(e.replace("#",""),16),n=Math.max(0,Math.min(255,(r>>16)+t)),o=Math.max(0,Math.min(255,(r>>8&255)+t)),s=Math.max(0,Math.min(255,(r&255)+t));return`#${(n<<16|o<<8|s).toString(16).padStart(6,"0")}`}getElement(){return this.element}destroy(){document.removeEventListener("mousemove",this.handleMouseMove),this.element&&(this.element.removeEventListener("click",this.onClick),this.element.remove(),this.element=null)}};var W=class{constructor(e,t,r){this.overlay=null;this.dialog=null;this.questions=[];this.answers={};this.errorId="";this.state="questions";this.config=e,this.onSubmit=t,this.onClose=r}open(e,t){this.errorId=e,this.questions=t,this.answers={},this.state="questions",this.render()}close(){this.overlay&&(this.overlay.remove(),this.overlay=null),this.dialog&&(this.dialog.remove(),this.dialog=null),this.onClose()}render(){this.close(),this.overlay=document.createElement("div"),this.overlay.className="blinker-dialog-overlay",this.overlay.addEventListener("click",()=>this.close()),this.dialog=document.createElement("div"),this.dialog.className=`blinker-dialog ${this.config.position}`,this.dialog.innerHTML=this.state==="questions"?this.getQuestionsHTML():this.getThankYouHTML(),document.body.appendChild(this.overlay),document.body.appendChild(this.dialog),this.attachEventListeners()}getQuestionsHTML(){let{messages:e}=this.config;return`
57
+ `}handleMouseMove(e){if(!this.mouseTrackingEnabled||!this.element||!this.pupilLeft||!this.pupilRight)return;let t=this.element.getBoundingClientRect(),i=t.left+t.width/2,n=t.top+t.height/2,s=(e.clientX-i)/50,o=(e.clientY-n)/50,a=3,l=Math.max(-a,Math.min(a,s)),u=Math.max(-a,Math.min(a,o));this.pupilLeft.setAttribute("transform",`translate(${l}, ${u})`),this.pupilRight.setAttribute("transform",`translate(${l}, ${u})`)}setState(e){this.element&&(this.element.classList.remove("idle","hover","minimized","talking"),this.element.classList.add(e))}setMinimized(e){this.element&&(e?(this.element.classList.add("minimized"),this.mouseTrackingEnabled=!1):(this.element.classList.remove("minimized"),this.mouseTrackingEnabled=!0))}updateTheme(e){this.theme=e,this.element&&(this.element.innerHTML=this.getSVGContent(),this.pupilLeft=this.element.querySelector(".blinker-pupil-left"),this.pupilRight=this.element.querySelector(".blinker-pupil-right"))}adjustColor(e,t){let i=parseInt(e.replace("#",""),16),n=Math.max(0,Math.min(255,(i>>16)+t)),s=Math.max(0,Math.min(255,(i>>8&255)+t)),o=Math.max(0,Math.min(255,(i&255)+t));return`#${(n<<16|s<<8|o).toString(16).padStart(6,"0")}`}getElement(){return this.element}destroy(){document.removeEventListener("mousemove",this.handleMouseMove),this.element&&(this.element.removeEventListener("click",this.onClick),this.element.remove(),this.element=null)}};var D=class{constructor(e,t,i){this.overlay=null;this.dialog=null;this.questions=[];this.answers={};this.errorId="";this.state="questions";this.config=e,this.onSubmit=t,this.onClose=i}open(e,t){this.errorId=e,this.questions=t,this.answers={},this.state="questions",this.render()}close(){this.overlay&&(this.overlay.remove(),this.overlay=null),this.dialog&&(this.dialog.remove(),this.dialog=null),this.onClose()}render(){this.close(),this.overlay=document.createElement("div"),this.overlay.className="blinker-dialog-overlay",this.overlay.addEventListener("click",()=>this.close()),this.dialog=document.createElement("div"),this.dialog.className=`blinker-dialog ${this.config.position}`,this.dialog.innerHTML=this.state==="questions"?this.getQuestionsHTML():this.getThankYouHTML(),document.body.appendChild(this.overlay),document.body.appendChild(this.dialog),this.attachEventListeners()}getQuestionsHTML(){let{messages:e}=this.config;return`
58
58
  <div class="blinker-dialog-header">
59
59
  <svg class="blinker-dialog-avatar" viewBox="0 0 100 100">
60
60
  <defs>
@@ -91,7 +91,7 @@
91
91
  ${e.buttonSend}
92
92
  </button>
93
93
  </div>
94
- `}getQuestionHTML(e){var r;let t=e.required?" *":"";switch(e.type){case"text":return`
94
+ `}getQuestionHTML(e){var i;let t=e.required?" *":"";switch(e.type){case"text":return`
95
95
  <div class="blinker-question" data-question-id="${e.id}">
96
96
  <label class="blinker-question-label">${e.text}${t}</label>
97
97
  <textarea
@@ -105,7 +105,7 @@
105
105
  <label class="blinker-question-label">${e.text}${t}</label>
106
106
  <select class="blinker-question-input blinker-question-select" data-question-id="${e.id}">
107
107
  <option value="">Selecione...</option>
108
- ${(r=e.options)==null?void 0:r.map(n=>`<option value="${n}">${n}</option>`).join("")}
108
+ ${(i=e.options)==null?void 0:i.map(n=>`<option value="${n}">${n}</option>`).join("")}
109
109
  </select>
110
110
  </div>
111
111
  `;case"boolean":return`
@@ -124,7 +124,7 @@
124
124
  </svg>
125
125
  <p class="blinker-thank-you-text">${this.config.messages.thankYou}</p>
126
126
  </div>
127
- `}attachEventListeners(){if(!this.dialog)return;let e=this.dialog.querySelector(".blinker-dialog-close");e==null||e.addEventListener("click",()=>this.close());let t=this.dialog.querySelector('[data-action="submit"]');t==null||t.addEventListener("click",()=>this.handleSubmit());let r=this.dialog.querySelector('[data-action="skip"]');r==null||r.addEventListener("click",()=>this.close()),this.dialog.querySelectorAll("textarea").forEach(a=>{a.addEventListener("input",l=>{let u=l.target,c=u.dataset.questionId;c&&(this.answers[c]=u.value)})}),this.dialog.querySelectorAll("select").forEach(a=>{a.addEventListener("change",l=>{let u=l.target,c=u.dataset.questionId;c&&(this.answers[c]=u.value)})}),this.dialog.querySelectorAll(".blinker-question-boolean button").forEach(a=>{a.addEventListener("click",l=>{let u=l.target,c=u.dataset.questionId,b=u.dataset.value==="true";if(c){this.answers[c]=b;let F=u.parentElement;F==null||F.querySelectorAll("button").forEach(le=>le.classList.remove("selected")),u.classList.add("selected")}})})}handleSubmit(){var n;let e=this.questions.filter(o=>o.required);if(e.some(o=>{let s=this.answers[o.id];return s===void 0||s===""})){let o=e.find(s=>!this.answers[s.id]);if(o){let s=(n=this.dialog)==null?void 0:n.querySelector(`[data-question-id="${o.id}"]`);s instanceof HTMLElement&&(s.focus(),s.style.borderColor="#ef4444",setTimeout(()=>{s.style.borderColor=""},2e3))}return}let r={errorId:this.errorId,answers:{...this.answers},submittedAt:new Date().toISOString()};this.onSubmit(r),this.state="thankyou",this.render(),setTimeout(()=>{this.close()},2500)}updateConfig(e){this.config=e}adjustColor(e,t){let r=parseInt(e.replace("#",""),16),n=Math.max(0,Math.min(255,(r>>16)+t)),o=Math.max(0,Math.min(255,(r>>8&255)+t)),s=Math.max(0,Math.min(255,(r&255)+t));return`#${(n<<16|o<<8|s).toString(16).padStart(6,"0")}`}isOpen(){return this.dialog!==null}};var be=[{id:"what_doing",text:"O que voc\xEA estava tentando fazer?",type:"text",required:!0}],ve=[{id:"server_error",condition:i=>i.httpCode!==void 0&&i.httpCode>=500,priority:10,questions:[{id:"form_filled",text:"Voc\xEA preencheu algum formul\xE1rio antes disso?",type:"boolean"},{id:"data_lost",text:"Voc\xEA perdeu algum dado importante?",type:"boolean"}]},{id:"network_error",condition:i=>i.message.toLowerCase().includes("network")||i.message.toLowerCase().includes("fetch")||i.message.toLowerCase().includes("failed to fetch")||i.errorType==="TypeError"&&i.message.includes("fetch"),priority:9,questions:[{id:"internet_working",text:"Sua internet est\xE1 funcionando normalmente?",type:"boolean"},{id:"using_vpn",text:"Voc\xEA est\xE1 usando VPN ou proxy?",type:"boolean"}]},{id:"timeout_error",condition:i=>i.message.toLowerCase().includes("timeout")||i.message.toLowerCase().includes("timed out"),priority:8,questions:[{id:"page_slow",text:"A p\xE1gina estava lenta antes do erro?",type:"boolean"},{id:"first_time",text:"\xC9 a primeira vez que isso acontece?",type:"boolean"}]},{id:"auth_error",condition:i=>i.httpCode===401||i.httpCode===403||i.message.toLowerCase().includes("unauthorized")||i.message.toLowerCase().includes("forbidden"),priority:7,questions:[{id:"logged_in",text:"Voc\xEA estava logado no sistema?",type:"boolean"},{id:"session_expired",text:"Ficou muito tempo sem usar o sistema?",type:"boolean"}]},{id:"not_found",condition:i=>i.httpCode===404,priority:6,questions:[{id:"how_arrived",text:"Como voc\xEA chegou nessa p\xE1gina?",type:"select",options:["Digitei o link","Cliquei em um bot\xE3o","Usei o menu","Outro"]}]},{id:"validation_error",condition:i=>i.httpCode===400||i.httpCode===422||i.message.toLowerCase().includes("validation")||i.message.toLowerCase().includes("invalid"),priority:5,questions:[{id:"what_filled",text:"O que voc\xEA preencheu no formul\xE1rio?",type:"text"},{id:"special_chars",text:"Usou caracteres especiais ou emojis?",type:"boolean"}]},{id:"ui_error",condition:i=>i.errorType==="TypeError"||i.message.toLowerCase().includes("undefined")||i.message.toLowerCase().includes("null"),priority:4,questions:[{id:"clicked_what",text:"Voc\xEA clicou em algo espec\xEDfico?",type:"text"},{id:"page_loaded",text:"A p\xE1gina tinha carregado completamente?",type:"boolean"}]},{id:"load_error",condition:i=>i.message.toLowerCase().includes("chunk")||i.message.toLowerCase().includes("loading")||i.message.toLowerCase().includes("script"),priority:3,questions:[{id:"refreshed",text:"Voc\xEA tentou atualizar a p\xE1gina?",type:"boolean"},{id:"browser",text:"Qual navegador voc\xEA est\xE1 usando?",type:"select",options:["Chrome","Firefox","Safari","Edge","Outro"]}]}],ye=[{id:"happened_before",text:"Isso j\xE1 aconteceu antes?",type:"boolean"},{id:"additional_info",text:"Algo mais que possa nos ajudar?",type:"text",required:!1}],O=class{inferQuestions(e,t){let r={message:e,type:"error",httpCode:t==null?void 0:t.httpCode,errorType:t==null?void 0:t.errorType,stack:t==null?void 0:t.stack},n=ve.filter(a=>a.condition(r)).sort((a,l)=>l.priority-a.priority),o=[...be],s=new Set(o.map(a=>a.id));for(let a of n.slice(0,2))for(let l of a.questions)s.has(l.id)||(o.push(l),s.add(l.id));if(o.length<3)for(let a of ye)!s.has(a.id)&&o.length<4&&(o.push(a),s.add(a.id));return o.slice(0,4)}shouldShowWidget(e,t,r){if(r!==void 0)return r;if((t==null?void 0:t.httpCode)!==void 0&&(t.httpCode>=500||t.httpCode===400||t.httpCode===422))return!0;let n=["unexpected","critical","fatal","crash","failed to","cannot read","cannot access","undefined is not","null is not"],o=e.toLowerCase();return n.some(s=>o.includes(s))}};function ie(i){if(document.getElementById("blinker-widget-styles"))return;let e=document.createElement("style");e.id="blinker-widget-styles",e.textContent=oe(i),document.head.appendChild(e)}function re(){let i=document.getElementById("blinker-widget-styles");i&&i.remove()}function ne(i){let e=document.getElementById("blinker-widget-styles");e&&(e.textContent=oe(i))}function oe(i){return`
127
+ `}attachEventListeners(){if(!this.dialog)return;let e=this.dialog.querySelector(".blinker-dialog-close");e==null||e.addEventListener("click",()=>this.close());let t=this.dialog.querySelector('[data-action="submit"]');t==null||t.addEventListener("click",()=>this.handleSubmit());let i=this.dialog.querySelector('[data-action="skip"]');i==null||i.addEventListener("click",()=>this.close()),this.dialog.querySelectorAll("textarea").forEach(a=>{a.addEventListener("input",l=>{let u=l.target,c=u.dataset.questionId;c&&(this.answers[c]=u.value)})}),this.dialog.querySelectorAll("select").forEach(a=>{a.addEventListener("change",l=>{let u=l.target,c=u.dataset.questionId;c&&(this.answers[c]=u.value)})}),this.dialog.querySelectorAll(".blinker-question-boolean button").forEach(a=>{a.addEventListener("click",l=>{let u=l.target,c=u.dataset.questionId,b=u.dataset.value==="true";if(c){this.answers[c]=b;let _=u.parentElement;_==null||_.querySelectorAll("button").forEach(le=>le.classList.remove("selected")),u.classList.add("selected")}})})}handleSubmit(){var n;let e=this.questions.filter(s=>s.required);if(e.some(s=>{let o=this.answers[s.id];return o===void 0||o===""})){let s=e.find(o=>!this.answers[o.id]);if(s){let o=(n=this.dialog)==null?void 0:n.querySelector(`[data-question-id="${s.id}"]`);o instanceof HTMLElement&&(o.focus(),o.style.borderColor="#ef4444",setTimeout(()=>{o.style.borderColor=""},2e3))}return}let i={errorId:this.errorId,answers:{...this.answers},submittedAt:new Date().toISOString()};this.onSubmit(i),this.state="thankyou",this.render(),setTimeout(()=>{this.close()},2500)}updateConfig(e){this.config=e}adjustColor(e,t){let i=parseInt(e.replace("#",""),16),n=Math.max(0,Math.min(255,(i>>16)+t)),s=Math.max(0,Math.min(255,(i>>8&255)+t)),o=Math.max(0,Math.min(255,(i&255)+t));return`#${(n<<16|s<<8|o).toString(16).padStart(6,"0")}`}isOpen(){return this.dialog!==null}};var ve=[{id:"what_doing",text:"O que voc\xEA estava tentando fazer?",type:"text",required:!0}],ye=[{id:"server_error",condition:r=>r.httpCode!==void 0&&r.httpCode>=500,priority:10,questions:[{id:"form_filled",text:"Voc\xEA preencheu algum formul\xE1rio antes disso?",type:"boolean"},{id:"data_lost",text:"Voc\xEA perdeu algum dado importante?",type:"boolean"}]},{id:"network_error",condition:r=>r.message.toLowerCase().includes("network")||r.message.toLowerCase().includes("fetch")||r.message.toLowerCase().includes("failed to fetch")||r.errorType==="TypeError"&&r.message.includes("fetch"),priority:9,questions:[{id:"internet_working",text:"Sua internet est\xE1 funcionando normalmente?",type:"boolean"},{id:"using_vpn",text:"Voc\xEA est\xE1 usando VPN ou proxy?",type:"boolean"}]},{id:"timeout_error",condition:r=>r.message.toLowerCase().includes("timeout")||r.message.toLowerCase().includes("timed out"),priority:8,questions:[{id:"page_slow",text:"A p\xE1gina estava lenta antes do erro?",type:"boolean"},{id:"first_time",text:"\xC9 a primeira vez que isso acontece?",type:"boolean"}]},{id:"auth_error",condition:r=>r.httpCode===401||r.httpCode===403||r.message.toLowerCase().includes("unauthorized")||r.message.toLowerCase().includes("forbidden"),priority:7,questions:[{id:"logged_in",text:"Voc\xEA estava logado no sistema?",type:"boolean"},{id:"session_expired",text:"Ficou muito tempo sem usar o sistema?",type:"boolean"}]},{id:"not_found",condition:r=>r.httpCode===404,priority:6,questions:[{id:"how_arrived",text:"Como voc\xEA chegou nessa p\xE1gina?",type:"select",options:["Digitei o link","Cliquei em um bot\xE3o","Usei o menu","Outro"]}]},{id:"validation_error",condition:r=>r.httpCode===400||r.httpCode===422||r.message.toLowerCase().includes("validation")||r.message.toLowerCase().includes("invalid"),priority:5,questions:[{id:"what_filled",text:"O que voc\xEA preencheu no formul\xE1rio?",type:"text"},{id:"special_chars",text:"Usou caracteres especiais ou emojis?",type:"boolean"}]},{id:"ui_error",condition:r=>r.errorType==="TypeError"||r.message.toLowerCase().includes("undefined")||r.message.toLowerCase().includes("null"),priority:4,questions:[{id:"clicked_what",text:"Voc\xEA clicou em algo espec\xEDfico?",type:"text"},{id:"page_loaded",text:"A p\xE1gina tinha carregado completamente?",type:"boolean"}]},{id:"load_error",condition:r=>r.message.toLowerCase().includes("chunk")||r.message.toLowerCase().includes("loading")||r.message.toLowerCase().includes("script"),priority:3,questions:[{id:"refreshed",text:"Voc\xEA tentou atualizar a p\xE1gina?",type:"boolean"},{id:"browser",text:"Qual navegador voc\xEA est\xE1 usando?",type:"select",options:["Chrome","Firefox","Safari","Edge","Outro"]}]}],ke=[{id:"happened_before",text:"Isso j\xE1 aconteceu antes?",type:"boolean"},{id:"additional_info",text:"Algo mais que possa nos ajudar?",type:"text",required:!1}],F=class{inferQuestions(e,t){let i={message:e,type:"error",httpCode:t==null?void 0:t.httpCode,errorType:t==null?void 0:t.errorType,stack:t==null?void 0:t.stack},n=ye.filter(a=>a.condition(i)).sort((a,l)=>l.priority-a.priority),s=[...ve],o=new Set(s.map(a=>a.id));for(let a of n.slice(0,2))for(let l of a.questions)o.has(l.id)||(s.push(l),o.add(l.id));if(s.length<3)for(let a of ke)!o.has(a.id)&&s.length<4&&(s.push(a),o.add(a.id));return s.slice(0,4)}shouldShowWidget(e,t,i){if(i!==void 0)return i;if((t==null?void 0:t.httpCode)!==void 0&&(t.httpCode>=500||t.httpCode===400||t.httpCode===422))return!0;let n=["unexpected","critical","fatal","crash","failed to","cannot read","cannot access","undefined is not","null is not"],s=e.toLowerCase();return n.some(o=>s.includes(o))}};function ie(r){if(document.getElementById("blinker-widget-styles"))return;let e=document.createElement("style");e.id="blinker-widget-styles",e.textContent=oe(r),document.head.appendChild(e)}function re(){let r=document.getElementById("blinker-widget-styles");r&&r.remove()}function ne(r){let e=document.getElementById("blinker-widget-styles");e&&(e.textContent=oe(r))}function oe(r){return`
128
128
  @keyframes blinker-breathe {
129
129
  0%, 100% { transform: scale(1); }
130
130
  50% { transform: scale(1.05); }
@@ -161,8 +161,8 @@
161
161
  }
162
162
 
163
163
  @keyframes blinker-glow {
164
- 0%, 100% { filter: drop-shadow(0 0 8px ${i.primary}40); }
165
- 50% { filter: drop-shadow(0 0 15px ${i.primary}60); }
164
+ 0%, 100% { filter: drop-shadow(0 0 8px ${r.primary}40); }
165
+ 50% { filter: drop-shadow(0 0 15px ${r.primary}60); }
166
166
  }
167
167
 
168
168
  .blinker-widget-container {
@@ -199,13 +199,13 @@
199
199
  }
200
200
 
201
201
  .blinker-avatar-body {
202
- fill: ${i.primary};
202
+ fill: ${r.primary};
203
203
  animation: blinker-breathe 4s ease-in-out infinite;
204
204
  transform-origin: center;
205
205
  }
206
206
 
207
207
  .blinker-avatar-eye {
208
- fill: ${i.background};
208
+ fill: ${r.background};
209
209
  animation: blinker-eye-blink 4s ease-in-out infinite;
210
210
  transform-origin: center;
211
211
  }
@@ -215,19 +215,19 @@
215
215
  }
216
216
 
217
217
  .blinker-avatar-pupil {
218
- fill: ${i.text};
218
+ fill: ${r.text};
219
219
  transition: transform 0.1s ease;
220
220
  }
221
221
 
222
222
  .blinker-avatar-mouth {
223
- stroke: ${i.background};
223
+ stroke: ${r.background};
224
224
  stroke-width: 2;
225
225
  fill: none;
226
226
  stroke-linecap: round;
227
227
  }
228
228
 
229
229
  .blinker-avatar-glow {
230
- fill: ${i.primary};
230
+ fill: ${r.primary};
231
231
  opacity: 0.3;
232
232
  animation: blinker-pulse 2s ease-in-out infinite;
233
233
  }
@@ -248,7 +248,7 @@
248
248
  z-index: 999999;
249
249
  width: 340px;
250
250
  max-width: calc(100vw - 40px);
251
- background: ${i.background};
251
+ background: ${r.background};
252
252
  border-radius: 16px;
253
253
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
254
254
  animation: blinker-slide-up 0.4s ease;
@@ -285,13 +285,13 @@
285
285
  .blinker-dialog-greeting {
286
286
  font-size: 16px;
287
287
  font-weight: 600;
288
- color: ${i.text};
288
+ color: ${r.text};
289
289
  margin: 0 0 4px;
290
290
  }
291
291
 
292
292
  .blinker-dialog-subtext {
293
293
  font-size: 13px;
294
- color: ${i.text}99;
294
+ color: ${r.text}99;
295
295
  margin: 0;
296
296
  }
297
297
 
@@ -300,14 +300,14 @@
300
300
  border: none;
301
301
  padding: 4px;
302
302
  cursor: pointer;
303
- color: ${i.text}66;
303
+ color: ${r.text}66;
304
304
  border-radius: 6px;
305
305
  transition: all 0.2s;
306
306
  }
307
307
 
308
308
  .blinker-dialog-close:hover {
309
- background: ${i.text}10;
310
- color: ${i.text};
309
+ background: ${r.text}10;
310
+ color: ${r.text};
311
311
  }
312
312
 
313
313
  .blinker-dialog-body {
@@ -326,30 +326,30 @@
326
326
  display: block;
327
327
  font-size: 14px;
328
328
  font-weight: 500;
329
- color: ${i.text};
329
+ color: ${r.text};
330
330
  margin-bottom: 8px;
331
331
  }
332
332
 
333
333
  .blinker-question-input {
334
334
  width: 100%;
335
335
  padding: 10px 12px;
336
- border: 1px solid ${i.text}20;
336
+ border: 1px solid ${r.text}20;
337
337
  border-radius: 8px;
338
338
  font-size: 14px;
339
- color: ${i.text};
340
- background: ${i.background};
339
+ color: ${r.text};
340
+ background: ${r.background};
341
341
  transition: border-color 0.2s, box-shadow 0.2s;
342
342
  box-sizing: border-box;
343
343
  }
344
344
 
345
345
  .blinker-question-input:focus {
346
346
  outline: none;
347
- border-color: ${i.primary};
348
- box-shadow: 0 0 0 3px ${i.primary}20;
347
+ border-color: ${r.primary};
348
+ box-shadow: 0 0 0 3px ${r.primary}20;
349
349
  }
350
350
 
351
351
  .blinker-question-input::placeholder {
352
- color: ${i.text}50;
352
+ color: ${r.text}50;
353
353
  }
354
354
 
355
355
  .blinker-question-textarea {
@@ -373,22 +373,22 @@
373
373
  .blinker-question-boolean button {
374
374
  flex: 1;
375
375
  padding: 10px;
376
- border: 1px solid ${i.text}20;
376
+ border: 1px solid ${r.text}20;
377
377
  border-radius: 8px;
378
- background: ${i.background};
379
- color: ${i.text};
378
+ background: ${r.background};
379
+ color: ${r.text};
380
380
  font-size: 14px;
381
381
  cursor: pointer;
382
382
  transition: all 0.2s;
383
383
  }
384
384
 
385
385
  .blinker-question-boolean button:hover {
386
- border-color: ${i.primary};
386
+ border-color: ${r.primary};
387
387
  }
388
388
 
389
389
  .blinker-question-boolean button.selected {
390
- background: ${i.primary};
391
- border-color: ${i.primary};
390
+ background: ${r.primary};
391
+ border-color: ${r.primary};
392
392
  color: white;
393
393
  }
394
394
 
@@ -410,7 +410,7 @@
410
410
  }
411
411
 
412
412
  .blinker-btn-primary {
413
- background: ${i.accent};
413
+ background: ${r.accent};
414
414
  color: white;
415
415
  }
416
416
 
@@ -424,12 +424,12 @@
424
424
  }
425
425
 
426
426
  .blinker-btn-secondary {
427
- background: ${i.text}10;
428
- color: ${i.text}99;
427
+ background: ${r.text}10;
428
+ color: ${r.text}99;
429
429
  }
430
430
 
431
431
  .blinker-btn-secondary:hover {
432
- background: ${i.text}20;
432
+ background: ${r.text}20;
433
433
  }
434
434
 
435
435
  .blinker-thank-you {
@@ -441,12 +441,12 @@
441
441
  width: 48px;
442
442
  height: 48px;
443
443
  margin: 0 auto 16px;
444
- color: ${i.accent};
444
+ color: ${r.accent};
445
445
  }
446
446
 
447
447
  .blinker-thank-you-text {
448
448
  font-size: 16px;
449
- color: ${i.text};
449
+ color: ${r.text};
450
450
  margin: 0;
451
451
  }
452
- `}var se="blinker_widget_state",S=class{constructor(e){this.container=null;this.avatar=null;this.dialog=null;this.onFeedbackSubmit=null;this.config={...R,...e},this.state=this.loadState(),this.questionEngine=new O}init(e){this.config.enabled&&typeof document!="undefined"&&(this.onFeedbackSubmit=e||null,ie(this.config.theme),this.createContainer())}createContainer(){if(this.container)return;this.container=document.createElement("div"),this.container.className=`blinker-widget-container ${this.config.position}`,document.body.appendChild(this.container),this.avatar=new $(this.config.theme,()=>this.handleAvatarClick());let e=this.avatar.create();this.container.appendChild(e),this.dialog=new W(this.config,t=>this.handleFeedbackSubmit(t),()=>this.handleDialogClose()),this.hide()}show(e,t,r,n){if(!this.config.enabled||!this.container||!this.avatar||!this.questionEngine.shouldShowWidget(t,r,n)||!this.canShowWidget())return;let s=this.questionEngine.inferQuestions(t,r);this.state.currentErrorId=e,this.state.questions=s,this.state.isVisible=!0,this.state.showCount++,this.state.lastShowTime=Date.now(),this.saveState(),this.container.style.display="block",this.avatar.setMinimized(!1)}hide(){this.container&&(this.state.isVisible=!1,this.state.isDialogOpen=!1,this.container.style.display="none")}handleAvatarClick(){var e;!this.dialog||!this.state.currentErrorId||(this.state.isDialogOpen?this.dialog.close():(this.state.isDialogOpen=!0,this.dialog.open(this.state.currentErrorId,this.state.questions),(e=this.avatar)==null||e.setMinimized(!0)))}handleFeedbackSubmit(e){this.onFeedbackSubmit&&this.onFeedbackSubmit(e)}handleDialogClose(){var e;this.state.isDialogOpen=!1,(e=this.avatar)==null||e.setMinimized(!1),setTimeout(()=>{this.hide()},500)}canShowWidget(){if(this.state.showCount>=this.config.maxShowsPerSession)return!1;if(this.state.lastShowTime){let e=this.config.cooldownMinutes*60*1e3;if(Date.now()-this.state.lastShowTime<e)return!1}return!0}loadState(){let e={isVisible:!1,isMinimized:!1,isDialogOpen:!1,currentErrorId:null,questions:[],showCount:0,lastShowTime:null};if(typeof sessionStorage=="undefined")return e;try{let t=sessionStorage.getItem(se);if(t){let r=JSON.parse(t);return{...e,showCount:r.showCount||0,lastShowTime:r.lastShowTime||null}}}catch(t){}return e}saveState(){if(typeof sessionStorage!="undefined")try{sessionStorage.setItem(se,JSON.stringify({showCount:this.state.showCount,lastShowTime:this.state.lastShowTime}))}catch(e){}}updateConfig(e){var t,r;this.config={...this.config,...e},e.theme&&(ne(this.config.theme),(t=this.avatar)==null||t.updateTheme(this.config.theme)),(r=this.dialog)==null||r.updateConfig(this.config)}getConfig(){return{...this.config}}isVisible(){return this.state.isVisible}isDialogOpen(){return this.state.isDialogOpen}destroy(){var e,t;(e=this.avatar)==null||e.destroy(),(t=this.dialog)==null||t.close(),this.container&&(this.container.remove(),this.container=null),re(),this.avatar=null,this.dialog=null}};var m=class{constructor(){this.config=null;this.initialized=!1;this.filterEngine=null;this.queue=null;this.sessionManager=null;this.userContext=null;this.rateLimiter=null;this.sampler=null;this.deduplicator=null;this.widget=null}init(e){var r,n;if(this.initialized){d().warn("SDK already initialized");return}if(!e.token)throw new Error("[Blinker] Token is required");this.config={...h,...e},B((r=this.config.debug)!=null?r:!1);let t=d();this.filterEngine=new E(e.filters),t.log("Filter engine initialized"),this.queue=new T(e.token,{enableBatching:this.config.enableBatching,batchSize:this.config.batchSize,flushInterval:this.config.flushInterval,enableOfflineStorage:this.config.enableOfflineStorage,maxStoredEvents:this.config.maxStoredEvents}),t.log("Event queue initialized"),this.sessionManager=new I,this.userContext=new L(this.sessionManager),t.log("Context managers initialized"),this.rateLimiter=new M(this.config.maxEventsPerMinute),this.sampler=new q(this.config.sampleRate),t.log("Sampling modules initialized"),this.deduplicator=new A(this.config.enableDeduplication,this.config.deduplicationWindow),t.log("Deduplicator initialized"),(this.config.captureErrors||this.config.captureRejections)&&(ee((o,s,a)=>this.handleCapturedError(o,s,a),{captureErrors:this.config.captureErrors,captureRejections:this.config.captureRejections}),t.log("Error handlers set up")),(n=this.config.widget)!=null&&n.enabled&&(this.widget=new S(this.config.widget),this.widget.init(o=>this.handleWidgetFeedback(o)),t.log("Widget initialized")),this.initialized=!0,t.log("SDK initialized successfully")}handleCapturedError(e,t,r){var s,a,l,u,c;if(!((s=this.filterEngine)!=null&&s.shouldCapture(t,r.errorType,r.httpCode)))return;let n=(a=this.deduplicator)==null?void 0:a.check(t,r.stack);if(n&&!n.shouldSend)return;let o=v();this.track(e,t,{...r,errorId:o,count:n==null?void 0:n.count}),this.widget&&((u=(l=this.config)==null?void 0:l.widget)!=null&&u.enabled)&&setTimeout(()=>{var b;(b=this.widget)==null||b.show(o,t,r)},(c=this.config.widget.delay)!=null?c:2e3)}handleWidgetFeedback(e){d().log("Widget feedback received:",e.errorId),this.track("feedback","User feedback submitted",{errorId:e.errorId,answers:e.answers,submittedAt:e.submittedAt})}track(e,t,r){var l,u,c;if(!this.initialized||!this.config)return Promise.resolve({success:!1,error:"SDK not initialized"});let n=d(),o=e==="error";if(!((l=this.rateLimiter)!=null&&l.allow()))return n.log("Event dropped due to rate limit"),Promise.resolve({success:!1,error:"Rate limited"});if(!((u=this.sampler)!=null&&u.shouldSample(o)))return Promise.resolve({success:!0,error:"Sampled out"});let s=(c=this.userContext)==null?void 0:c.getEventContext(),a={id:v(),type:e,message:t,payload:r,timestamp:new Date().toISOString(),url:V(),userAgent:j(),sessionId:s==null?void 0:s.sessionId,userId:s==null?void 0:s.userId,userTraits:s==null?void 0:s.userTraits,context:s==null?void 0:s.custom};return n.log("Tracking event:",e,t.substring(0,50)),this.queue.add(a)}captureError(e,t){var u,c;let r=e instanceof Error?e.message:e,n=e instanceof Error?e.name:void 0,o=e instanceof Error?e.stack:void 0,s=t==null?void 0:t.httpCode;if(!((u=this.filterEngine)!=null&&u.shouldCapture(r,n,s)))return Promise.resolve({success:!0,error:"Filtered out"});let a=(c=this.deduplicator)==null?void 0:c.check(r,o);if(a&&!a.shouldSend)return Promise.resolve({success:!0,error:"Deduplicated"});let l={...t,errorType:n,stack:o,count:a==null?void 0:a.count};return this.track("error",r,l)}trackPageView(e,t){var n;let r=e||G();return(n=this.sessionManager)==null||n.recordPageView(),this.track("pageview",r,{...t,referrer:Y()})}identify(e,t){var r;(r=this.userContext)==null||r.identify(e,t)}setContext(e,t){var r;(r=this.userContext)==null||r.setContext(e,t)}getContext(){var e,t;return(t=(e=this.userContext)==null?void 0:e.getCustomContext())!=null?t:{}}clearContext(){var e;(e=this.userContext)==null||e.clearAll()}getSessionId(){var e,t;return(t=(e=this.sessionManager)==null?void 0:e.getSessionId())!=null?t:""}getSession(){var e,t;return(t=(e=this.sessionManager)==null?void 0:e.getSession())!=null?t:null}async flush(){var e;await((e=this.queue)==null?void 0:e.flush())}getQueueSize(){var e,t;return(t=(e=this.queue)==null?void 0:e.size())!=null?t:0}isInitialized(){return this.initialized}getConfig(){if(!this.config)return null;let{token:e,...t}=this.config;return t}getFilters(){var e,t;return(t=(e=this.filterEngine)==null?void 0:e.getFilters())!=null?t:{...p}}showWidget(e,t,r){var n;(n=this.widget)==null||n.show(e,t,r)}hideWidget(){var e;(e=this.widget)==null||e.hide()}getWidgetConfig(){var e,t;return(t=(e=this.widget)==null?void 0:e.getConfig())!=null?t:null}updateWidgetConfig(e){var t;(t=this.widget)==null||t.updateConfig(e)}isWidgetVisible(){var e,t;return(t=(e=this.widget)==null?void 0:e.isVisible())!=null?t:!1}destroy(){var t,r,n,o;let e=d();(t=this.queue)==null||t.destroy(),te(),(r=this.deduplicator)==null||r.destroy(),(n=this.sessionManager)==null||n.endSession(),(o=this.widget)==null||o.destroy(),this.config=null,this.initialized=!1,this.filterEngine=null,this.queue=null,this.sessionManager=null,this.userContext=null,this.rateLimiter=null,this.sampler=null,this.deduplicator=null,this.widget=null,e.log("SDK destroyed"),B(!1)}};var ae=new m;var ke=ae;return pe(xe);})();
452
+ `}var se="blinker_widget_state",S=class{constructor(e){this.container=null;this.avatar=null;this.dialog=null;this.onFeedbackSubmit=null;this.config={...W,...e},this.state=this.loadState(),this.questionEngine=new F}init(e){this.config.enabled&&typeof document!="undefined"&&(this.onFeedbackSubmit=e||null,ie(this.config.theme),this.createContainer())}createContainer(){if(this.container)return;this.container=document.createElement("div"),this.container.className=`blinker-widget-container ${this.config.position}`,document.body.appendChild(this.container),this.avatar=new O(this.config.theme,()=>this.handleAvatarClick());let e=this.avatar.create();this.container.appendChild(e),this.dialog=new D(this.config,t=>this.handleFeedbackSubmit(t),()=>this.handleDialogClose()),this.hide()}show(e,t,i,n){if(!this.config.enabled||!this.container||!this.avatar||!this.questionEngine.shouldShowWidget(t,i,n)||!this.canShowWidget())return;let o=this.questionEngine.inferQuestions(t,i);this.state.currentErrorId=e,this.state.questions=o,this.state.isVisible=!0,this.state.showCount++,this.state.lastShowTime=Date.now(),this.saveState(),this.container.style.display="block",this.avatar.setMinimized(!1)}hide(){this.container&&(this.state.isVisible=!1,this.state.isDialogOpen=!1,this.container.style.display="none")}handleAvatarClick(){var e;!this.dialog||!this.state.currentErrorId||(this.state.isDialogOpen?this.dialog.close():(this.state.isDialogOpen=!0,this.dialog.open(this.state.currentErrorId,this.state.questions),(e=this.avatar)==null||e.setMinimized(!0)))}handleFeedbackSubmit(e){this.onFeedbackSubmit&&this.onFeedbackSubmit(e)}handleDialogClose(){var e;this.state.isDialogOpen=!1,(e=this.avatar)==null||e.setMinimized(!1),setTimeout(()=>{this.hide()},500)}canShowWidget(){if(this.state.showCount>=this.config.maxShowsPerSession)return!1;if(this.state.lastShowTime){let e=this.config.cooldownMinutes*60*1e3;if(Date.now()-this.state.lastShowTime<e)return!1}return!0}loadState(){let e={isVisible:!1,isMinimized:!1,isDialogOpen:!1,currentErrorId:null,questions:[],showCount:0,lastShowTime:null};if(typeof sessionStorage=="undefined")return e;try{let t=sessionStorage.getItem(se);if(t){let i=JSON.parse(t);return{...e,showCount:i.showCount||0,lastShowTime:i.lastShowTime||null}}}catch(t){}return e}saveState(){if(typeof sessionStorage!="undefined")try{sessionStorage.setItem(se,JSON.stringify({showCount:this.state.showCount,lastShowTime:this.state.lastShowTime}))}catch(e){}}updateConfig(e){var t,i;this.config={...this.config,...e},e.theme&&(ne(this.config.theme),(t=this.avatar)==null||t.updateTheme(this.config.theme)),(i=this.dialog)==null||i.updateConfig(this.config)}getConfig(){return{...this.config}}isVisible(){return this.state.isVisible}isDialogOpen(){return this.state.isDialogOpen}destroy(){var e,t;(e=this.avatar)==null||e.destroy(),(t=this.dialog)==null||t.close(),this.container&&(this.container.remove(),this.container=null),re(),this.avatar=null,this.dialog=null}};var m=class{constructor(){this.config=null;this.initialized=!1;this.filterEngine=null;this.queue=null;this.sessionManager=null;this.userContext=null;this.rateLimiter=null;this.sampler=null;this.deduplicator=null;this.widget=null}get version(){return w}init(e){var n,s,o,a;if(this.initialized){d().warn("SDK already initialized");return}if(!e.token)throw new Error("[Blinker] Token is required");if(!((n=e.enabled)!=null?n:g.enabled)){C((s=e.debug)!=null?s:!1),d().log("SDK disabled via config"),this.config={...g,...e};return}this.config={...g,...e},C((o=this.config.debug)!=null?o:!1);let i=d();this.filterEngine=new T(e.filters),i.log("Filter engine initialized"),this.queue=new L(e.token,{endpoint:this.config.endpoint,enableBatching:this.config.enableBatching,batchSize:this.config.batchSize,flushInterval:this.config.flushInterval,enableOfflineStorage:this.config.enableOfflineStorage,maxStoredEvents:this.config.maxStoredEvents,onError:this.config.onError}),i.log("Event queue initialized"),this.sessionManager=new M,this.userContext=new q(this.sessionManager),i.log("Context managers initialized"),this.rateLimiter=new A(this.config.maxEventsPerMinute),this.sampler=new R(this.config.sampleRate),i.log("Sampling modules initialized"),this.deduplicator=new $(this.config.enableDeduplication,this.config.deduplicationWindow),i.log("Deduplicator initialized"),(this.config.captureErrors||this.config.captureRejections)&&(ee((l,u,c)=>this.handleCapturedError(l,u,c),{captureErrors:this.config.captureErrors,captureRejections:this.config.captureRejections}),i.log("Error handlers set up")),(a=this.config.widget)!=null&&a.enabled&&(this.widget=new S(this.config.widget),this.widget.init(l=>this.handleWidgetFeedback(l)),i.log("Widget initialized")),this.initialized=!0,i.log("SDK initialized successfully")}handleCapturedError(e,t,i){var o,a,l,u,c;if(!((o=this.filterEngine)!=null&&o.shouldCapture(t,i.errorType,i.httpCode)))return;let n=(a=this.deduplicator)==null?void 0:a.check(t,i.stack);if(n&&!n.shouldSend)return;let s=v();this.track(e,t,{...i,errorId:s,count:n==null?void 0:n.count}),this.widget&&((u=(l=this.config)==null?void 0:l.widget)!=null&&u.enabled)&&setTimeout(()=>{var b;(b=this.widget)==null||b.show(s,t,i)},(c=this.config.widget.delay)!=null?c:2e3)}handleWidgetFeedback(e){d().log("Widget feedback received:",e.errorId),this.track("feedback","User feedback submitted",{errorId:e.errorId,answers:e.answers,submittedAt:e.submittedAt})}track(e,t,i){var l,u,c;if(!this.config)return Promise.resolve({success:!1,error:"SDK not initialized"});if(!this.config.enabled)return Promise.resolve({success:!0,error:"SDK disabled"});if(!this.initialized)return Promise.resolve({success:!1,error:"SDK not initialized"});let n=d(),s=e==="error";if(!((l=this.rateLimiter)!=null&&l.allow()))return n.log("Event dropped due to rate limit"),Promise.resolve({success:!1,error:"Rate limited"});if(!((u=this.sampler)!=null&&u.shouldSample(s)))return Promise.resolve({success:!0,error:"Sampled out"});let o=(c=this.userContext)==null?void 0:c.getEventContext(),a={id:v(),type:e,message:t,payload:i,timestamp:new Date().toISOString(),url:V(),userAgent:j(),sessionId:o==null?void 0:o.sessionId,userId:o==null?void 0:o.userId,userTraits:o==null?void 0:o.userTraits,context:o==null?void 0:o.custom};return this.config.onBeforeSend&&(a=this.config.onBeforeSend(a),!a)?(n.log("Event filtered by onBeforeSend"),Promise.resolve({success:!0,error:"Filtered by onBeforeSend"})):(n.log("Tracking event:",e,t.substring(0,50)),this.queue.add(a))}captureError(e,t){var u,c;let i=e instanceof Error?e.message:e,n=e instanceof Error?e.name:void 0,s=e instanceof Error?e.stack:void 0,o=t==null?void 0:t.httpCode;if(!((u=this.filterEngine)!=null&&u.shouldCapture(i,n,o)))return Promise.resolve({success:!0,error:"Filtered out"});let a=(c=this.deduplicator)==null?void 0:c.check(i,s);if(a&&!a.shouldSend)return Promise.resolve({success:!0,error:"Deduplicated"});let l={...t,errorType:n,stack:s,count:a==null?void 0:a.count};return this.track("error",i,l)}trackPageView(e,t){var n;let i=e||G();return(n=this.sessionManager)==null||n.recordPageView(),this.track("pageview",i,{...t,referrer:K()})}identify(e,t){var i;(i=this.userContext)==null||i.identify(e,t)}setContext(e,t){var i;(i=this.userContext)==null||i.setContext(e,t)}getContext(){var e,t;return(t=(e=this.userContext)==null?void 0:e.getCustomContext())!=null?t:{}}clearContext(){var e;(e=this.userContext)==null||e.clearAll()}getSessionId(){var e,t;return(t=(e=this.sessionManager)==null?void 0:e.getSessionId())!=null?t:""}getSession(){var e,t;return(t=(e=this.sessionManager)==null?void 0:e.getSession())!=null?t:null}async flush(){var e;await((e=this.queue)==null?void 0:e.flush())}getQueueSize(){var e,t;return(t=(e=this.queue)==null?void 0:e.size())!=null?t:0}isInitialized(){return this.initialized}getConfig(){if(!this.config)return null;let{token:e,...t}=this.config;return t}getFilters(){var e,t;return(t=(e=this.filterEngine)==null?void 0:e.getFilters())!=null?t:{...p}}showWidget(e,t,i){var n;(n=this.widget)==null||n.show(e,t,i)}hideWidget(){var e;(e=this.widget)==null||e.hide()}getWidgetConfig(){var e,t;return(t=(e=this.widget)==null?void 0:e.getConfig())!=null?t:null}updateWidgetConfig(e){var t;(t=this.widget)==null||t.updateConfig(e)}isWidgetVisible(){var e,t;return(t=(e=this.widget)==null?void 0:e.isVisible())!=null?t:!1}destroy(){var t,i,n,s;let e=d();(t=this.queue)==null||t.destroy(),te(),(i=this.deduplicator)==null||i.destroy(),(n=this.sessionManager)==null||n.endSession(),(s=this.widget)==null||s.destroy(),this.config=null,this.initialized=!1,this.filterEngine=null,this.queue=null,this.sessionManager=null,this.userContext=null,this.rateLimiter=null,this.sampler=null,this.deduplicator=null,this.widget=null,e.log("SDK destroyed"),C(!1)}};var ae=new m;var xe=ae;return pe(Se);})();
@@ -2,8 +2,10 @@ import type { BlinkerConfig, SafeConfig, SendResult, BlinkerErrorPayload } from
2
2
  import type { SessionInfo } from '../context/types';
3
3
  import type { FilterSettings } from '../filters/types';
4
4
  import type { WidgetConfig } from '../widget/types';
5
+ import { SDK_VERSION } from './config';
5
6
  import { DEFAULT_FILTERS } from '../filters';
6
7
  export { DEFAULT_FILTERS };
8
+ export { SDK_VERSION };
7
9
  export declare class Blinker {
8
10
  private config;
9
11
  private initialized;
@@ -15,6 +17,7 @@ export declare class Blinker {
15
17
  private sampler;
16
18
  private deduplicator;
17
19
  private widget;
20
+ get version(): string;
18
21
  init(config: BlinkerConfig): void;
19
22
  private handleCapturedError;
20
23
  private handleWidgetFeedback;
@@ -1 +1 @@
1
- {"version":3,"file":"Blinker.d.ts","sourceRoot":"","sources":["../../src/core/Blinker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAwB,UAAU,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAChH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,iBAAiB,CAAC;AAGpE,OAAO,EAAgB,eAAe,EAAE,MAAM,YAAY,CAAC;AAW3D,OAAO,EAAE,eAAe,EAAE,CAAC;AAE3B,qBAAa,OAAO;IAClB,OAAO,CAAC,MAAM,CAA8B;IAC5C,OAAO,CAAC,WAAW,CAAkB;IACrC,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,KAAK,CAA2B;IACxC,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,WAAW,CAA4B;IAC/C,OAAO,CAAC,WAAW,CAA4B;IAC/C,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,MAAM,CAAuB;IAErC,IAAI,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IAkEjC,OAAO,CAAC,mBAAmB;IAyB3B,OAAO,CAAC,oBAAoB;IAW5B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAsC5F,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,EAAE,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAyBrG,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAWlG,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAIhE,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAI7C,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIrC,YAAY,IAAI,IAAI;IAIpB,YAAY,IAAI,MAAM;IAItB,UAAU,IAAI,WAAW,GAAG,IAAI;IAI1B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,YAAY,IAAI,MAAM;IAItB,aAAa,IAAI,OAAO;IAIxB,SAAS,IAAI,UAAU,GAAG,IAAI;IAM9B,UAAU,IAAI,cAAc;IAI5B,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,IAAI;IAIjF,UAAU,IAAI,IAAI;IAIlB,eAAe,IAAI,YAAY,GAAG,IAAI;IAItC,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI;IAIvD,eAAe,IAAI,OAAO;IAI1B,OAAO,IAAI,IAAI;CAuBhB"}
1
+ {"version":3,"file":"Blinker.d.ts","sourceRoot":"","sources":["../../src/core/Blinker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAwB,UAAU,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAChH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,iBAAiB,CAAC;AAEpE,OAAO,EAAY,WAAW,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAgB,eAAe,EAAE,MAAM,YAAY,CAAC;AAW3D,OAAO,EAAE,eAAe,EAAE,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,CAAC;AAEvB,qBAAa,OAAO;IAClB,OAAO,CAAC,MAAM,CAA8B;IAC5C,OAAO,CAAC,WAAW,CAAkB;IACrC,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,KAAK,CAA2B;IACxC,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,WAAW,CAA4B;IAC/C,OAAO,CAAC,WAAW,CAA4B;IAC/C,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,MAAM,CAAuB;IAErC,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;IA6EjC,OAAO,CAAC,mBAAmB;IAyB3B,OAAO,CAAC,oBAAoB;IAW5B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAsD5F,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,EAAE,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAyBrG,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAWlG,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAIhE,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAI7C,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIrC,YAAY,IAAI,IAAI;IAIpB,YAAY,IAAI,MAAM;IAItB,UAAU,IAAI,WAAW,GAAG,IAAI;IAI1B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,YAAY,IAAI,MAAM;IAItB,aAAa,IAAI,OAAO;IAIxB,SAAS,IAAI,UAAU,GAAG,IAAI;IAM9B,UAAU,IAAI,cAAc;IAI5B,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,IAAI;IAIjF,UAAU,IAAI,IAAI;IAIlB,eAAe,IAAI,YAAY,GAAG,IAAI;IAItC,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI;IAIvD,eAAe,IAAI,OAAO;IAI1B,OAAO,IAAI,IAAI;CAuBhB"}
@@ -1,10 +1,13 @@
1
1
  export declare const BLINKER_API = "https://api.blinker.live";
2
+ export declare const SDK_VERSION = "2.0.1";
2
3
  export declare const STORAGE_KEYS: {
3
4
  readonly EVENT_QUEUE: "blinker_event_queue";
4
5
  readonly SESSION: "blinker_session";
5
6
  readonly USER_CONTEXT: "blinker_user_context";
6
7
  };
7
8
  export declare const DEFAULTS: {
9
+ readonly endpoint: "https://api.blinker.live";
10
+ readonly enabled: true;
8
11
  readonly captureErrors: true;
9
12
  readonly captureRejections: true;
10
13
  readonly enableBatching: true;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/core/config.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,6BAA6B,CAAC;AAEtD,eAAO,MAAM,YAAY;;;;CAIf,CAAC;AAEX,eAAO,MAAM,QAAQ;;;;;;;;;;;;;CAaX,CAAC;AAEX,eAAO,MAAM,MAAM;;;;CAIT,CAAC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/core/config.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,6BAA6B,CAAC;AAEtD,eAAO,MAAM,WAAW,UAAU,CAAC;AAEnC,eAAO,MAAM,YAAY;;;;CAIf,CAAC;AAEX,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;CAeX,CAAC;AAEX,eAAO,MAAM,MAAM;;;;CAIT,CAAC"}
@@ -2,6 +2,8 @@ import type { FilterSettings } from '../filters/types';
2
2
  import type { WidgetConfig } from '../widget/types';
3
3
  export interface BlinkerConfig {
4
4
  token: string;
5
+ endpoint?: string;
6
+ enabled?: boolean;
5
7
  captureErrors?: boolean;
6
8
  captureRejections?: boolean;
7
9
  enableBatching?: boolean;
@@ -16,6 +18,8 @@ export interface BlinkerConfig {
16
18
  filters?: FilterSettings;
17
19
  widget?: Partial<WidgetConfig>;
18
20
  debug?: boolean;
21
+ onBeforeSend?: (event: BlinkerEventInternal) => BlinkerEventInternal | null;
22
+ onError?: (error: Error | string) => void;
19
23
  }
20
24
  export type SafeConfig = Omit<BlinkerConfig, 'token'>;
21
25
  export interface BlinkerEvent {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;IAC/B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEtD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACxD,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAoB,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAClE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;IAC/B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,oBAAoB,GAAG,IAAI,CAAC;IAC5E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,KAAK,IAAI,CAAC;CAC3C;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEtD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACxD,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAoB,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAClE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
package/dist/index.cjs.js CHANGED
@@ -23,6 +23,7 @@ __export(index_exports, {
23
23
  Blinker: () => Blinker,
24
24
  DEFAULT_FILTERS: () => DEFAULT_FILTERS,
25
25
  DEFAULT_WIDGET_CONFIG: () => DEFAULT_WIDGET_CONFIG,
26
+ SDK_VERSION: () => SDK_VERSION,
26
27
  blinker: () => blinker,
27
28
  default: () => index_default
28
29
  });
@@ -30,12 +31,15 @@ module.exports = __toCommonJS(index_exports);
30
31
 
31
32
  // src/core/config.ts
32
33
  var BLINKER_API = "https://api.blinker.live";
34
+ var SDK_VERSION = "2.0.1";
33
35
  var STORAGE_KEYS = {
34
36
  EVENT_QUEUE: "blinker_event_queue",
35
37
  SESSION: "blinker_session",
36
38
  USER_CONTEXT: "blinker_user_context"
37
39
  };
38
40
  var DEFAULTS = {
41
+ endpoint: BLINKER_API,
42
+ enabled: true,
39
43
  captureErrors: true,
40
44
  captureRejections: true,
41
45
  enableBatching: true,
@@ -377,17 +381,19 @@ var EventQueue = class {
377
381
  logger.log("Back online, flushing stored events");
378
382
  this.flush();
379
383
  };
380
- var _a, _b, _c, _d, _e;
384
+ var _a, _b, _c, _d, _e, _f;
381
385
  this.token = token;
382
386
  this.config = {
383
- enableBatching: (_a = config == null ? void 0 : config.enableBatching) != null ? _a : DEFAULTS.enableBatching,
384
- batchSize: (_b = config == null ? void 0 : config.batchSize) != null ? _b : DEFAULTS.batchSize,
387
+ endpoint: (_a = config == null ? void 0 : config.endpoint) != null ? _a : DEFAULTS.endpoint,
388
+ enableBatching: (_b = config == null ? void 0 : config.enableBatching) != null ? _b : DEFAULTS.enableBatching,
389
+ batchSize: (_c = config == null ? void 0 : config.batchSize) != null ? _c : DEFAULTS.batchSize,
385
390
  flushInterval: Math.max(
386
391
  TIMING.MIN_FLUSH_INTERVAL,
387
- Math.min((_c = config == null ? void 0 : config.flushInterval) != null ? _c : DEFAULTS.flushInterval, TIMING.MAX_FLUSH_INTERVAL)
392
+ Math.min((_d = config == null ? void 0 : config.flushInterval) != null ? _d : DEFAULTS.flushInterval, TIMING.MAX_FLUSH_INTERVAL)
388
393
  ),
389
- enableOfflineStorage: (_d = config == null ? void 0 : config.enableOfflineStorage) != null ? _d : DEFAULTS.enableOfflineStorage,
390
- maxStoredEvents: (_e = config == null ? void 0 : config.maxStoredEvents) != null ? _e : DEFAULTS.maxStoredEvents
394
+ enableOfflineStorage: (_e = config == null ? void 0 : config.enableOfflineStorage) != null ? _e : DEFAULTS.enableOfflineStorage,
395
+ maxStoredEvents: (_f = config == null ? void 0 : config.maxStoredEvents) != null ? _f : DEFAULTS.maxStoredEvents,
396
+ onError: config == null ? void 0 : config.onError
391
397
  };
392
398
  this.storage = new OfflineStorage(this.config.maxStoredEvents);
393
399
  if (this.config.enableBatching) {
@@ -446,7 +452,11 @@ var EventQueue = class {
446
452
  const stored = this.storage.storeMany(events);
447
453
  return { success: true, count: stored };
448
454
  }
449
- return sendBatch(BLINKER_API, this.token, events);
455
+ const result = await sendBatch(this.config.endpoint, this.token, events);
456
+ if (!result.success && this.config.onError) {
457
+ this.config.onError(result.error || "Unknown error sending events");
458
+ }
459
+ return result;
450
460
  }
451
461
  getStats() {
452
462
  const queueSize = this.queue.length;
@@ -2047,8 +2057,11 @@ var Blinker = class {
2047
2057
  this.deduplicator = null;
2048
2058
  this.widget = null;
2049
2059
  }
2060
+ get version() {
2061
+ return SDK_VERSION;
2062
+ }
2050
2063
  init(config) {
2051
- var _a, _b;
2064
+ var _a, _b, _c, _d;
2052
2065
  if (this.initialized) {
2053
2066
  const logger2 = getLogger();
2054
2067
  logger2.warn("SDK already initialized");
@@ -2057,20 +2070,30 @@ var Blinker = class {
2057
2070
  if (!config.token) {
2058
2071
  throw new Error("[Blinker] Token is required");
2059
2072
  }
2073
+ const enabled = (_a = config.enabled) != null ? _a : DEFAULTS.enabled;
2074
+ if (!enabled) {
2075
+ setGlobalLogger((_b = config.debug) != null ? _b : false);
2076
+ const logger2 = getLogger();
2077
+ logger2.log("SDK disabled via config");
2078
+ this.config = { ...DEFAULTS, ...config };
2079
+ return;
2080
+ }
2060
2081
  this.config = {
2061
2082
  ...DEFAULTS,
2062
2083
  ...config
2063
2084
  };
2064
- setGlobalLogger((_a = this.config.debug) != null ? _a : false);
2085
+ setGlobalLogger((_c = this.config.debug) != null ? _c : false);
2065
2086
  const logger = getLogger();
2066
2087
  this.filterEngine = new FilterEngine(config.filters);
2067
2088
  logger.log("Filter engine initialized");
2068
2089
  this.queue = new EventQueue(config.token, {
2090
+ endpoint: this.config.endpoint,
2069
2091
  enableBatching: this.config.enableBatching,
2070
2092
  batchSize: this.config.batchSize,
2071
2093
  flushInterval: this.config.flushInterval,
2072
2094
  enableOfflineStorage: this.config.enableOfflineStorage,
2073
- maxStoredEvents: this.config.maxStoredEvents
2095
+ maxStoredEvents: this.config.maxStoredEvents,
2096
+ onError: this.config.onError
2074
2097
  });
2075
2098
  logger.log("Event queue initialized");
2076
2099
  this.sessionManager = new SessionManager();
@@ -2094,7 +2117,7 @@ var Blinker = class {
2094
2117
  );
2095
2118
  logger.log("Error handlers set up");
2096
2119
  }
2097
- if ((_b = this.config.widget) == null ? void 0 : _b.enabled) {
2120
+ if ((_d = this.config.widget) == null ? void 0 : _d.enabled) {
2098
2121
  this.widget = new Widget(this.config.widget);
2099
2122
  this.widget.init((feedback) => this.handleWidgetFeedback(feedback));
2100
2123
  logger.log("Widget initialized");
@@ -2135,7 +2158,13 @@ var Blinker = class {
2135
2158
  }
2136
2159
  track(type, message, payload) {
2137
2160
  var _a, _b, _c;
2138
- if (!this.initialized || !this.config) {
2161
+ if (!this.config) {
2162
+ return Promise.resolve({ success: false, error: "SDK not initialized" });
2163
+ }
2164
+ if (!this.config.enabled) {
2165
+ return Promise.resolve({ success: true, error: "SDK disabled" });
2166
+ }
2167
+ if (!this.initialized) {
2139
2168
  return Promise.resolve({ success: false, error: "SDK not initialized" });
2140
2169
  }
2141
2170
  const logger = getLogger();
@@ -2148,7 +2177,7 @@ var Blinker = class {
2148
2177
  return Promise.resolve({ success: true, error: "Sampled out" });
2149
2178
  }
2150
2179
  const context = (_c = this.userContext) == null ? void 0 : _c.getEventContext();
2151
- const event = {
2180
+ let event = {
2152
2181
  id: generateUniqueId(),
2153
2182
  type,
2154
2183
  message,
@@ -2161,6 +2190,13 @@ var Blinker = class {
2161
2190
  userTraits: context == null ? void 0 : context.userTraits,
2162
2191
  context: context == null ? void 0 : context.custom
2163
2192
  };
2193
+ if (this.config.onBeforeSend) {
2194
+ event = this.config.onBeforeSend(event);
2195
+ if (!event) {
2196
+ logger.log("Event filtered by onBeforeSend");
2197
+ return Promise.resolve({ success: true, error: "Filtered by onBeforeSend" });
2198
+ }
2199
+ }
2164
2200
  logger.log("Tracking event:", type, message.substring(0, 50));
2165
2201
  return this.queue.add(event);
2166
2202
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Blinker, DEFAULT_FILTERS } from './core';
1
+ export { Blinker, DEFAULT_FILTERS, SDK_VERSION } from './core';
2
2
  export type { BlinkerConfig, BlinkerEvent, BlinkerEventInternal, BlinkerErrorPayload, SendResult, SafeConfig, } from './core/types';
3
3
  export type { FilterSettings } from './filters/types';
4
4
  export type { SessionInfo } from './context/types';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAElD,YAAY,EACV,aAAa,EACb,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,EACnB,UAAU,EACV,UAAU,GACX,MAAM,cAAc,CAAC;AAEtB,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,YAAY,EACV,YAAY,EACZ,WAAW,EACX,cAAc,EACd,cAAc,EACd,cAAc,EACd,WAAW,EACX,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,QAAA,MAAM,OAAO,SAAgB,CAAC;AAE9B,OAAO,EAAE,OAAO,EAAE,CAAC;AAEnB,eAAe,OAAO,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE/D,YAAY,EACV,aAAa,EACb,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,EACnB,UAAU,EACV,UAAU,GACX,MAAM,cAAc,CAAC;AAEtB,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,YAAY,EACV,YAAY,EACZ,WAAW,EACX,cAAc,EACd,cAAc,EACd,cAAc,EACd,WAAW,EACX,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,QAAA,MAAM,OAAO,SAAgB,CAAC;AAE9B,OAAO,EAAE,OAAO,EAAE,CAAC;AAEnB,eAAe,OAAO,CAAC"}
package/dist/index.esm.js CHANGED
@@ -1,11 +1,14 @@
1
1
  // src/core/config.ts
2
2
  var BLINKER_API = "https://api.blinker.live";
3
+ var SDK_VERSION = "2.0.1";
3
4
  var STORAGE_KEYS = {
4
5
  EVENT_QUEUE: "blinker_event_queue",
5
6
  SESSION: "blinker_session",
6
7
  USER_CONTEXT: "blinker_user_context"
7
8
  };
8
9
  var DEFAULTS = {
10
+ endpoint: BLINKER_API,
11
+ enabled: true,
9
12
  captureErrors: true,
10
13
  captureRejections: true,
11
14
  enableBatching: true,
@@ -347,17 +350,19 @@ var EventQueue = class {
347
350
  logger.log("Back online, flushing stored events");
348
351
  this.flush();
349
352
  };
350
- var _a, _b, _c, _d, _e;
353
+ var _a, _b, _c, _d, _e, _f;
351
354
  this.token = token;
352
355
  this.config = {
353
- enableBatching: (_a = config == null ? void 0 : config.enableBatching) != null ? _a : DEFAULTS.enableBatching,
354
- batchSize: (_b = config == null ? void 0 : config.batchSize) != null ? _b : DEFAULTS.batchSize,
356
+ endpoint: (_a = config == null ? void 0 : config.endpoint) != null ? _a : DEFAULTS.endpoint,
357
+ enableBatching: (_b = config == null ? void 0 : config.enableBatching) != null ? _b : DEFAULTS.enableBatching,
358
+ batchSize: (_c = config == null ? void 0 : config.batchSize) != null ? _c : DEFAULTS.batchSize,
355
359
  flushInterval: Math.max(
356
360
  TIMING.MIN_FLUSH_INTERVAL,
357
- Math.min((_c = config == null ? void 0 : config.flushInterval) != null ? _c : DEFAULTS.flushInterval, TIMING.MAX_FLUSH_INTERVAL)
361
+ Math.min((_d = config == null ? void 0 : config.flushInterval) != null ? _d : DEFAULTS.flushInterval, TIMING.MAX_FLUSH_INTERVAL)
358
362
  ),
359
- enableOfflineStorage: (_d = config == null ? void 0 : config.enableOfflineStorage) != null ? _d : DEFAULTS.enableOfflineStorage,
360
- maxStoredEvents: (_e = config == null ? void 0 : config.maxStoredEvents) != null ? _e : DEFAULTS.maxStoredEvents
363
+ enableOfflineStorage: (_e = config == null ? void 0 : config.enableOfflineStorage) != null ? _e : DEFAULTS.enableOfflineStorage,
364
+ maxStoredEvents: (_f = config == null ? void 0 : config.maxStoredEvents) != null ? _f : DEFAULTS.maxStoredEvents,
365
+ onError: config == null ? void 0 : config.onError
361
366
  };
362
367
  this.storage = new OfflineStorage(this.config.maxStoredEvents);
363
368
  if (this.config.enableBatching) {
@@ -416,7 +421,11 @@ var EventQueue = class {
416
421
  const stored = this.storage.storeMany(events);
417
422
  return { success: true, count: stored };
418
423
  }
419
- return sendBatch(BLINKER_API, this.token, events);
424
+ const result = await sendBatch(this.config.endpoint, this.token, events);
425
+ if (!result.success && this.config.onError) {
426
+ this.config.onError(result.error || "Unknown error sending events");
427
+ }
428
+ return result;
420
429
  }
421
430
  getStats() {
422
431
  const queueSize = this.queue.length;
@@ -2017,8 +2026,11 @@ var Blinker = class {
2017
2026
  this.deduplicator = null;
2018
2027
  this.widget = null;
2019
2028
  }
2029
+ get version() {
2030
+ return SDK_VERSION;
2031
+ }
2020
2032
  init(config) {
2021
- var _a, _b;
2033
+ var _a, _b, _c, _d;
2022
2034
  if (this.initialized) {
2023
2035
  const logger2 = getLogger();
2024
2036
  logger2.warn("SDK already initialized");
@@ -2027,20 +2039,30 @@ var Blinker = class {
2027
2039
  if (!config.token) {
2028
2040
  throw new Error("[Blinker] Token is required");
2029
2041
  }
2042
+ const enabled = (_a = config.enabled) != null ? _a : DEFAULTS.enabled;
2043
+ if (!enabled) {
2044
+ setGlobalLogger((_b = config.debug) != null ? _b : false);
2045
+ const logger2 = getLogger();
2046
+ logger2.log("SDK disabled via config");
2047
+ this.config = { ...DEFAULTS, ...config };
2048
+ return;
2049
+ }
2030
2050
  this.config = {
2031
2051
  ...DEFAULTS,
2032
2052
  ...config
2033
2053
  };
2034
- setGlobalLogger((_a = this.config.debug) != null ? _a : false);
2054
+ setGlobalLogger((_c = this.config.debug) != null ? _c : false);
2035
2055
  const logger = getLogger();
2036
2056
  this.filterEngine = new FilterEngine(config.filters);
2037
2057
  logger.log("Filter engine initialized");
2038
2058
  this.queue = new EventQueue(config.token, {
2059
+ endpoint: this.config.endpoint,
2039
2060
  enableBatching: this.config.enableBatching,
2040
2061
  batchSize: this.config.batchSize,
2041
2062
  flushInterval: this.config.flushInterval,
2042
2063
  enableOfflineStorage: this.config.enableOfflineStorage,
2043
- maxStoredEvents: this.config.maxStoredEvents
2064
+ maxStoredEvents: this.config.maxStoredEvents,
2065
+ onError: this.config.onError
2044
2066
  });
2045
2067
  logger.log("Event queue initialized");
2046
2068
  this.sessionManager = new SessionManager();
@@ -2064,7 +2086,7 @@ var Blinker = class {
2064
2086
  );
2065
2087
  logger.log("Error handlers set up");
2066
2088
  }
2067
- if ((_b = this.config.widget) == null ? void 0 : _b.enabled) {
2089
+ if ((_d = this.config.widget) == null ? void 0 : _d.enabled) {
2068
2090
  this.widget = new Widget(this.config.widget);
2069
2091
  this.widget.init((feedback) => this.handleWidgetFeedback(feedback));
2070
2092
  logger.log("Widget initialized");
@@ -2105,7 +2127,13 @@ var Blinker = class {
2105
2127
  }
2106
2128
  track(type, message, payload) {
2107
2129
  var _a, _b, _c;
2108
- if (!this.initialized || !this.config) {
2130
+ if (!this.config) {
2131
+ return Promise.resolve({ success: false, error: "SDK not initialized" });
2132
+ }
2133
+ if (!this.config.enabled) {
2134
+ return Promise.resolve({ success: true, error: "SDK disabled" });
2135
+ }
2136
+ if (!this.initialized) {
2109
2137
  return Promise.resolve({ success: false, error: "SDK not initialized" });
2110
2138
  }
2111
2139
  const logger = getLogger();
@@ -2118,7 +2146,7 @@ var Blinker = class {
2118
2146
  return Promise.resolve({ success: true, error: "Sampled out" });
2119
2147
  }
2120
2148
  const context = (_c = this.userContext) == null ? void 0 : _c.getEventContext();
2121
- const event = {
2149
+ let event = {
2122
2150
  id: generateUniqueId(),
2123
2151
  type,
2124
2152
  message,
@@ -2131,6 +2159,13 @@ var Blinker = class {
2131
2159
  userTraits: context == null ? void 0 : context.userTraits,
2132
2160
  context: context == null ? void 0 : context.custom
2133
2161
  };
2162
+ if (this.config.onBeforeSend) {
2163
+ event = this.config.onBeforeSend(event);
2164
+ if (!event) {
2165
+ logger.log("Event filtered by onBeforeSend");
2166
+ return Promise.resolve({ success: true, error: "Filtered by onBeforeSend" });
2167
+ }
2168
+ }
2134
2169
  logger.log("Tracking event:", type, message.substring(0, 50));
2135
2170
  return this.queue.add(event);
2136
2171
  }
@@ -2258,6 +2293,7 @@ export {
2258
2293
  Blinker,
2259
2294
  DEFAULT_FILTERS,
2260
2295
  DEFAULT_WIDGET_CONFIG,
2296
+ SDK_VERSION,
2261
2297
  blinker,
2262
2298
  index_default as default
2263
2299
  };
@@ -1 +1 @@
1
- {"version":3,"file":"EventQueue.d.ts","sourceRoot":"","sources":["../../src/queue/EventQueue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAOvD,qBAAa,UAAU;IACrB,OAAO,CAAC,KAAK,CAA8B;IAC3C,OAAO,CAAC,OAAO,CAAiB;IAChC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,UAAU,CAA+C;IACjE,OAAO,CAAC,UAAU,CAAkB;gBAExB,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC;IAwBlD,GAAG,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,UAAU,CAAC;IAiBrD,KAAK,IAAI,OAAO,CAAC,UAAU,CAAC;YAuCpB,eAAe;IAY7B,QAAQ,IAAI,UAAU;IAUtB,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,YAAY,CAIlB;IAEF,OAAO,IAAI,IAAI;CAehB"}
1
+ {"version":3,"file":"EventQueue.d.ts","sourceRoot":"","sources":["../../src/queue/EventQueue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAOvD,qBAAa,UAAU;IACrB,OAAO,CAAC,KAAK,CAA8B;IAC3C,OAAO,CAAC,OAAO,CAAiB;IAChC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,UAAU,CAA+C;IACjE,OAAO,CAAC,UAAU,CAAkB;gBAExB,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC;IA0BlD,GAAG,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,UAAU,CAAC;IAiBrD,KAAK,IAAI,OAAO,CAAC,UAAU,CAAC;YAuCpB,eAAe;IAkB7B,QAAQ,IAAI,UAAU;IAUtB,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,YAAY,CAIlB;IAEF,OAAO,IAAI,IAAI;CAehB"}
@@ -1,10 +1,12 @@
1
1
  import type { BlinkerEventInternal } from '../core/types';
2
2
  export interface QueueConfig {
3
+ endpoint: string;
3
4
  enableBatching: boolean;
4
5
  batchSize: number;
5
6
  flushInterval: number;
6
7
  enableOfflineStorage: boolean;
7
8
  maxStoredEvents: number;
9
+ onError?: (error: Error | string) => void;
8
10
  }
9
11
  export interface StoredEvent {
10
12
  event: BlinkerEventInternal;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/queue/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAE1D,MAAM,WAAW,WAAW;IAC1B,cAAc,EAAE,OAAO,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,OAAO,CAAC;IAC9B,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,oBAAoB,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;CACtB"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/queue/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAE1D,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,OAAO,CAAC;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,KAAK,IAAI,CAAC;CAC3C;AAED,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,oBAAoB,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;CACtB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blinker-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Universal JavaScript SDK for error tracking and event capture - works with any framework",
5
5
  "author": "Blinker",
6
6
  "license": "MIT",