UNPKG

@calico/analytics

Version:

Analytics SDK for Calico Dashboard - Easy integration for tracking user interactions and configurations

4 lines 4.03 kB
'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* Calico Analytics SDK - (c) 2024 Calico Media */ var r=class{constructor(e){this.queue=[];this.initialized=false;this.apiKey=e.apiKey,this.endpoint=e.endpoint||"http://localhost:3011/api/analytics/track",this.debug=e.debug||false,this.batchSize=e.batchSize||10,this.flushInterval=e.flushInterval||3e4,this.sessionId=this.generateSessionId(),e.autoTrack!==false&&this.setupAutoTracking(),this.startFlushTimer(),this.initialized=true,this.debug&&console.log("[Calico Analytics] Initialized");}generateSessionId(){if(typeof window<"u"&&window.sessionStorage){let e=window.sessionStorage.getItem("calico_session_id");if(e)return e;let t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return window.sessionStorage.setItem("calico_session_id",t),t}return `session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}setupAutoTracking(){typeof window>"u"||(this.track("VIEW"),document.addEventListener("click",e=>{let t=e.target;if(t.matches('button, a, [role="button"]')){let s={element:t.tagName.toLowerCase(),text:t.textContent?.slice(0,50)};t.id&&(s.id=t.id),t.className&&(s.className=t.className),this.track("INTERACT",s);}}),document.addEventListener("visibilitychange",()=>{document.hidden&&this.flush();}),window.addEventListener("beforeunload",()=>{this.flush(true);}));}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush();},this.flushInterval);}track(e,t,s){if(!this.initialized)return;let i={event:e,metadata:t,value:s,sessionId:this.sessionId};this.queue.push(i),this.queue.length>=this.batchSize&&this.flush();}async flush(e=false){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];let s={apiKey:this.apiKey,events:t,timestamp:new Date().toISOString()};try{if(e&&typeof navigator<"u"&&navigator.sendBeacon){let i=new Blob([JSON.stringify(s)],{type:"application/json"});navigator.sendBeacon(this.endpoint,i);}else {let i=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify(s)});if(!i.ok)throw new Error(`Failed to send analytics: ${i.statusText}`)}}catch(i){this.debug&&console.warn("[Calico Analytics] Failed to send events:",i),this.queue.unshift(...t);}}identify(e,t){typeof window<"u"&&window.localStorage&&(window.localStorage.setItem("calico_user_id",e),t&&window.localStorage.setItem("calico_user_traits",JSON.stringify(t))),this.track("INTERACT",{action:"identify",userId:e,...t});}reset(){typeof window<"u"&&(window.sessionStorage.removeItem("calico_session_id"),window.localStorage.removeItem("calico_user_id"),window.localStorage.removeItem("calico_user_traits")),this.sessionId=this.generateSessionId(),this.queue=[];}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush(true),this.initialized=false;}},n=null;function l(a){return n&&(console.warn("[Calico Analytics] Already initialized. Destroying previous instance."),n.destroy()),n=new r(a),n}function c(a,e,t){n&&n.track(a,e,t);}function d(a,e){n&&n.identify(a,e);}function u(){return n?n.flush():Promise.resolve()}function h(){n&&n.reset();}async function f(a,e,t){let s=t?.replace("/track","/register")||"https://dashboard.calico.media/api/analytics/register";try{let i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,url:e})});if(!i.ok)throw new Error(`Registration failed: ${i.statusText}`);let o=await i.json();if(o.apiKey)return console.log(`[Calico Analytics] Registered successfully. API Key: ${o.apiKey}`),o.apiKey;throw new Error("No API key received from registration")}catch(i){throw console.error("[Calico Analytics] Auto-registration failed:",i),i}}var p={init:l,track:c,identify:d,flush:u,reset:h,autoRegister:f}; exports.autoRegister=f;exports.default=p;exports.flush=u;exports.identify=d;exports.init=l;exports.reset=h;exports.track=c;//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map