@loopkit/javascript
Version:
JavaScript SDK for LoopKit analytics platform
2 lines (1 loc) • 31.9 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LoopKit={})}(this,(function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function n(e,t,n,r,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise((function(i,o){var s=e.apply(t,r);function a(e){n(s,i,o,a,u,"next",e)}function u(e){n(s,i,o,a,u,"throw",e)}a(void 0)}))}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,f(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function a(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function l(){var e,t,n="function"==typeof Symbol?Symbol:{},r=n.iterator||"@@iterator",i=n.toStringTag||"@@toStringTag";function o(n,r,i,o){var u=r&&r.prototype instanceof a?r:a,c=Object.create(u.prototype);return g(c,"_invoke",function(n,r,i){var o,a,u,c=0,l=i||[],g=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,a=0,u=e,h.n=n,s}};function f(n,r){for(a=n,u=r,t=0;!g&&c&&!i&&t<l.length;t++){var i,o=l[t],f=h.p,d=o[2];n>3?(i=d===r)&&(u=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=f&&((i=n<2&&f<o[1])?(a=0,h.v=r,h.n=o[1]):f<d&&(i=n<3||o[0]>r||r>d)&&(o[4]=n,o[5]=r,h.n=d,a=0))}if(i||n>1)return s;throw g=!0,r}return function(i,l,d){if(c>1)throw TypeError("Generator is already running");for(g&&1===l&&f(l,d),a=l,u=d;(t=a<2?e:u)||!g;){o||(a?a<3?(a>1&&(h.n=-1),f(a,u)):h.n=u:h.v=u);try{if(c=2,o){if(a||(i="next"),t=o[i]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,a<2&&(a=0)}else 1===a&&(t=o.return)&&t.call(o),a<2&&(u=TypeError("The iterator does not provide a '"+i+"' method"),a=1);o=e}else if((t=(g=h.n<0)?u:n.call(r,h))!==s)break}catch(t){o=e,a=1,u=t}finally{c=1}}return{value:t,done:g}}}(n,i,o),!0),c}var s={};function a(){}function u(){}function c(){}t=Object.getPrototypeOf;var h=[][r]?t(t([][r]())):(g(t={},r,(function(){return this})),t),f=c.prototype=a.prototype=Object.create(h);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,c):(e.__proto__=c,g(e,i,"GeneratorFunction")),e.prototype=Object.create(f),e}return u.prototype=c,g(f,"constructor",c),g(c,"constructor",u),u.displayName="GeneratorFunction",g(c,i,"GeneratorFunction"),g(f),g(f,i,"Generator"),g(f,r,(function(){return this})),g(f,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:o,m:d}})()}function g(e,t,n,r){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}g=function(e,t,n,r){if(t)i?i(e,t,{value:n,enumerable:!r,configurable:!r,writable:!r}):e[t]=n;else{function o(t,n){g(e,t,(function(e){return this._invoke(t,n,e)}))}o("next",0),o("throw",1),o("return",2)}},g(e,t,n,r)}function h(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,n){if(e){if("string"==typeof e)return t(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function d(e){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},d(e)}var v=function(){return s((function e(){i(this,e)}),null,[{key:"validate",value:function(e){if(void 0!==e.batchSize&&e.batchSize<=0)throw new Error("batchSize must be greater than 0");if(void 0!==e.flushInterval&&e.flushInterval<0)throw new Error("flushInterval must be >= 0");if(void 0!==e.maxQueueSize&&e.maxQueueSize<=0)throw new Error("maxQueueSize must be greater than 0");if(void 0!==e.requestTimeout&&e.requestTimeout<=0)throw new Error("requestTimeout must be greater than 0");if(void 0!==e.maxRetries&&e.maxRetries<0)throw new Error("maxRetries must be >= 0");if(void 0!==e.sessionTimeout&&e.sessionTimeout<=0)throw new Error("sessionTimeout must be greater than 0")}}])}(),p=function(){return s((function e(t){i(this,e),this.config=t}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"error",value:function(e,t){this.log("error",e,t)}},{key:"warn",value:function(e,t){this.log("warn",e,t)}},{key:"info",value:function(e,t){this.log("info",e,t)}},{key:"debug",value:function(e,t){this.log("debug",e,t)}},{key:"log",value:function(e,t,n){if(this.shouldLog(e)){var r=new Date,i=r.toLocaleDateString("en-US")+" "+r.toLocaleTimeString("en-US")+"."+r.getMilliseconds();if(n){var o=c(c({},n),{},{timestamp:i,version:"1.1.5"}),s="[LoopKit] ".concat(t);console[e](s,o)}else console[e]("[LoopKit] ".concat(t),{timestamp:i,version:"1.1.5"})}}},{key:"shouldLog",value:function(e){if(!this.config.debug)return!1;var t=["error","warn","info","debug"],n=this.config.logLevel||"debug",r=t.indexOf(n);return t.indexOf(e)<=r}}])}(),y=function(){return s((function e(){i(this,e)}),[{key:"generateSessionId",value:function(){return"sess_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"generateAnonymousId",value:function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"generateEventId",value:function(){return"evt_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}}])}(),k=function(){return s((function e(t,n){i(this,e),this.config=t,this.logger=n}),[{key:"updateConfig",value:function(e){this.config=e}},{key:"getStorage",value:function(){return"undefined"!=typeof global&&global.localStorage?global.localStorage:"undefined"!=typeof localStorage?localStorage:null}},{key:"persistQueue",value:function(e){if(this.config.enableLocalStorage){var t=this.getStorage();if(t)try{var n={version:"1.1.5",events:e,timestamp:Date.now()};t.setItem("loopkit_queue",JSON.stringify(n))}catch(e){this.logger.warn("Failed to persist queue",{error:e})}}}},{key:"loadQueue",value:function(){if(!this.config.enableLocalStorage)return[];var e=this.getStorage();if(e)try{var t=e.getItem("loopkit_queue");if(t){var n=JSON.parse(t);if(Array.isArray(n)){if(this.logger.debug("Legacy event format detected, clearing queue"),e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",{error:e})}return[]}if(n&&"object"===d(n)&&n.version&&n.events){var r="1.1.5";if(n.version!==r){if(this.logger.debug("Version mismatch detected (stored: ".concat(n.version,", current: ").concat(r,"), clearing queue")),e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",{error:e})}return[]}if(Array.isArray(n.events))return this.logger.debug("Loaded ".concat(n.events.length," events from storage (version: ").concat(n.version,")")),n.events}}}catch(e){this.logger.warn("Failed to load persisted queue, clearing corrupted data",{error:e}),this.clearQueue()}return[]}},{key:"clearQueue",value:function(){if(this.config.enableLocalStorage){var e=this.getStorage();if(e)try{e.removeItem("loopkit_queue")}catch(e){this.logger.warn("Failed to clear persisted queue",{error:e})}}}},{key:"loadAnonymousId",value:function(){if(!this.config.enableLocalStorage)return null;var e=this.getStorage();if(e)try{var t=e.getItem("loopkit_anonymousId");if(t)return t}catch(e){this.logger.warn("Failed to load anonymous ID",{error:e})}return null}},{key:"saveAnonymousId",value:function(e){if(this.config.enableLocalStorage){var t=this.getStorage();if(t)try{t.setItem("loopkit_anonymousId",e)}catch(e){this.logger.warn("Failed to save anonymous ID",{error:e})}}}},{key:"clearAnonymousId",value:function(){if(this.config.enableLocalStorage){var e=this.getStorage();if(e)try{e.removeItem("loopkit_anonymousId")}catch(e){this.logger.warn("Failed to clear anonymous ID",{error:e})}}}},{key:"clearAll",value:function(){this.clearQueue(),this.clearAnonymousId()}}])}(),m=function(){return s((function e(t,n,r,o){i(this,e),this.config=t,this.logger=n,this.idGenerator=r,this.storageManager=o,this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now(),this.anonymousId=this.loadOrCreateAnonymousId(),this.sessionId=this.idGenerator.generateSessionId(),this.startSession(),this.logger.debug("Session initialized",{sessionId:this.sessionId,anonymousId:this.anonymousId})}),[{key:"setSessionEventCallback",value:function(e){this.sessionEventCallback=e}},{key:"getSessionId",value:function(){return this.updateActivity(),this.sessionId}},{key:"getAnonymousId",value:function(){return this.updateActivity(),this.anonymousId}},{key:"startSession",value:function(){var e=this.sessionId;this.sessionId=this.idGenerator.generateSessionId(),this.sessionStartTime=Date.now(),this.lastActivityTime=this.sessionStartTime,this.logger.debug("New session started: ".concat(this.sessionId)),this.config.enableSessionTracking&&this.sessionEventCallback&&this.sessionEventCallback("session_start",{sessionId:this.sessionId,previousSessionId:e!==this.sessionId?e:void 0})}},{key:"endSession",value:function(){var e=Date.now()-this.sessionStartTime,t=this.sessionId;this.logger.debug("Session ended: ".concat(t)),this.config.enableSessionTracking&&this.sessionEventCallback&&this.sessionEventCallback("session_end",{sessionId:t,duration:Math.round(e/1e3)}),this.startSession()}},{key:"isSessionActive",value:function(){return!this.config.enableSessionTracking||Date.now()-this.lastActivityTime<1e3*this.config.sessionTimeout}},{key:"updateActivity",value:function(){var e=Date.now(),t=e-this.lastActivityTime,n=1e3*this.config.sessionTimeout;this.config.enableSessionTracking&&t>=n?(this.logger.debug("Session timeout detected, ending current session and starting new one"),this.endSession()):this.lastActivityTime=e}},{key:"updateConfig",value:function(e){this.config=e}},{key:"reset",value:function(){if(this.logger.debug("Resetting session manager"),this.config.enableSessionTracking&&this.sessionEventCallback){var e=Date.now()-this.sessionStartTime;this.sessionEventCallback("session_end",{sessionId:this.sessionId,duration:Math.round(e/1e3),reason:"reset"})}this.startSession()}},{key:"loadOrCreateAnonymousId",value:function(){var e=this.storageManager.loadAnonymousId();return e?this.logger.debug("Loaded existing anonymous ID: ".concat(e)):(e=this.idGenerator.generateAnonymousId(),this.storageManager.saveAnonymousId(e),this.logger.debug("Generated new anonymous ID: ".concat(e))),e}}])}(),b=function(){return s((function e(t,n,r){i(this,e),this.eventQueue=[],this.isInitialized=!1,this.config=t,this.logger=n,this.storageManager=r,this.loadPersistedQueue(),this.isInitialized=!0}),[{key:"enqueueEvent",value:function(e){if(this.isInitialized){var t={type:"name"in e?"track":"groupId"in e?"group":"identify",event:e};this.eventQueue.length>=this.config.maxQueueSize&&(this.logger.warn("Queue size limit reached (".concat(this.config.maxQueueSize,"), dropping oldest event")),this.eventQueue.shift()),this.eventQueue.push(t),this.logger.debug("Event queued. Queue size: ".concat(this.eventQueue.length)),this.persistQueue(),this.eventQueue.length>=this.config.batchSize&&(this.logger.debug("Batch size reached (".concat(this.config.batchSize,"), auto-flushing")),this.flush(this.networkManager))}else this.logger.warn("QueueManager not initialized")}},{key:"flush",value:(e=r(l().m((function e(t){var n,r,i,o,s,a,u,c,g,f,d,v,p=this;return l().w((function(e){for(;;)switch(e.n){case 0:if(t){e.n=1;break}return this.logger.warn("NetworkManager not set, cannot flush"),e.a(2);case 1:if(0!==this.eventQueue.length){e.n=2;break}return this.logger.debug("No events to flush"),e.a(2);case 2:return n=h(this.eventQueue),this.eventQueue=[],this.persistQueue(),e.p=3,r=[],i=[],o=[],n.forEach((function(e){var t=e.type,n=e.event;switch(t){case"track":r.push(n);break;case"identify":i.push(n);break;case"group":o.push(n)}})),s=[],r.length>0&&(a="".concat(this.config.baseURL,"/tracks"),u={tracks:r},s.push(t.sendEvents(a,u))),i.length>0&&(c="".concat(this.config.baseURL,"/identifies"),g={identifies:i},s.push(t.sendEvents(c,g))),o.length>0&&(f="".concat(this.config.baseURL,"/groups"),d={groups:o},s.push(t.sendEvents(f,d))),e.n=4,Promise.all(s);case 4:this.logger.debug("Successfully flushed ".concat(n.length," events")),this.config.onAfterTrack&&n.forEach((function(e){var t=e.type,n=e.event;"track"===t&&p.config.onAfterTrack(n,!0)})),e.n=6;break;case 5:throw e.p=5,v=e.v,this.logger.error("Failed to flush events",{error:v}),this.eventQueue=[].concat(h(n),h(this.eventQueue)),this.persistQueue(),this.config.onAfterTrack&&n.forEach((function(e){var t=e.type,n=e.event;"track"===t&&p.config.onAfterTrack(n,!1)})),this.config.onError&&this.config.onError(v),v;case 6:return e.a(2)}}),e,this,[[3,5]])}))),function(t){return e.apply(this,arguments)})},{key:"getQueue",value:function(){return h(this.eventQueue)}},{key:"getQueueSize",value:function(){return this.eventQueue.length}},{key:"clearQueue",value:function(){this.eventQueue=[],this.persistQueue(),this.logger.debug("Queue cleared")}},{key:"reset",value:function(){this.clearQueue(),this.stopAutoFlush(),this.storageManager.clearQueue()}},{key:"updateConfig",value:function(e){this.config=e}},{key:"setNetworkManager",value:function(e){this.networkManager=e}},{key:"scheduleFlush",value:function(){var e=this;this.config.flushInterval>0&&(this.flushTimer=setInterval((function(){e.eventQueue.length>0&&e.networkManager&&(e.logger.debug("Auto-flush triggered"),e.flush(e.networkManager))}),1e3*this.config.flushInterval))}},{key:"restartAutoFlush",value:function(){this.stopAutoFlush(),this.scheduleFlush()}},{key:"stopAutoFlush",value:function(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}},{key:"persistQueue",value:function(){if(this.config.enableLocalStorage)try{this.storageManager.persistQueue(this.eventQueue)}catch(e){this.logger.warn("Failed to persist queue",{error:e})}}},{key:"loadPersistedQueue",value:function(){if(this.config.enableLocalStorage)try{var e=this.storageManager.loadQueue();Array.isArray(e)&&e.length>0&&(this.eventQueue=e,this.logger.debug("Loaded ".concat(this.eventQueue.length," persisted events")))}catch(e){this.logger.warn("Failed to load persisted queue",{error:e})}}}]);var e}(),w=function(){return s((function e(){i(this,e)}),null,[{key:"isDoNotTrackEnabled",value:function(){if("undefined"==typeof navigator)return!1;var e=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===e||"yes"===e||!0===e}}])}(),S=function(){return s((function e(t,n,r,o,s){i(this,e),this.config=t,this.logger=n,this.queueManager=r,this.sessionManager=o,this.idGenerator=s}),[{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e&&"string"==typeof e)if(this.config.respectDoNotTrack&&w.isDoNotTrackEnabled())this.logger.debug("Do Not Track is enabled, skipping event tracking");else try{var i=c(c({},this.createBaseEvent(n.timestamp)),{},{name:e,properties:c({},t)},r.userId&&{userId:r.userId}),o=i;if(this.config.onBeforeTrack)try{var s=this.config.onBeforeTrack(i);s&&(o=s)}catch(e){this.logger.error("Error in onBeforeTrack callback",{error:e})}this.queueManager.enqueueEvent(o),this.logger.debug("Tracked event: ".concat(e),o)}catch(t){this.logger.error("Failed to track event",{eventName:e,error:t}),this.config.onError&&this.config.onError(t)}else this.logger.warn("Event name is required and must be a string")}},{key:"identify",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e&&"string"==typeof e)if(this.config.respectDoNotTrack&&w.isDoNotTrackEnabled())this.logger.debug("Do Not Track is enabled, skipping user identification");else try{var n=c(c({},this.createBaseEvent()),{},{userId:e,properties:c({},t)});this.queueManager.enqueueEvent(n),this.logger.debug("Identified user: ".concat(e),n)}catch(t){this.logger.error("Failed to identify user",{userId:e,error:t}),this.config.onError&&this.config.onError(t)}else this.logger.warn("User ID is required and must be a string")}},{key:"group",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"organization",r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e&&"string"==typeof e)if(this.config.respectDoNotTrack&&w.isDoNotTrackEnabled())this.logger.debug("Do Not Track is enabled, skipping group association");else try{var i=c(c({},this.createBaseEvent()),{},{groupId:e,groupType:n,properties:c({},t)},r.userId&&{userId:r.userId});this.queueManager.enqueueEvent(i),this.logger.debug("Associated with group: ".concat(e),i)}catch(t){this.logger.error("Failed to associate with group",{groupId:e,error:t}),this.config.onError&&this.config.onError(t)}else this.logger.warn("Group ID is required and must be a string")}},{key:"updateConfig",value:function(e){this.config=e}},{key:"createBaseEvent",value:function(e){var t=e||(new Date).toISOString();return{anonymousId:this.sessionManager.getAnonymousId(),timestamp:t,system:this.createSystemInfo()}}},{key:"createSystemInfo",value:function(){var e={sdk:{name:"@loopkit/javascript",version:"1.1.5"},sessionId:this.sessionManager.getSessionId()};return"undefined"!=typeof window&&(e.context={page:{url:window.location.href,path:window.location.pathname,search:window.location.search,title:document.title,referrer:document.referrer},userAgent:navigator.userAgent,screen:{width:window.screen.width,height:window.screen.height},viewport:{width:window.innerWidth,height:window.innerHeight}}),e}}])}(),T=function(){return s((function e(t,n){i(this,e),this.config=t,this.logger=n}),[{key:"sendEvents",value:(e=r(l().m((function e(t,n){var r,i,o,s,a,u,c,g,h,f,d,v,p,y,k=arguments;return l().w((function(e){for(;;)switch(e.n){case 0:return r=k.length>2&&void 0!==k[2]?k[2]:0,e.p=1,i={"Content-Type":"application/json",Authorization:"Bearer ".concat(this.config.apiKey)},this.config.enableCompression&&(i["Accept-Encoding"]="gzip, deflate"),o={method:"POST",headers:i,body:JSON.stringify(n),keepalive:!0},this.config.requestTimeout&&this.config.requestTimeout>0&&(s=new AbortController,o.signal=s.signal,setTimeout((function(){return s.abort()}),this.config.requestTimeout)),a=this.getEventCountFromPayload(n),this.logger.debug("Sending ".concat(a," event(s) to ").concat(t),{retryCount:r,payload:n}),u=null,e.p=2,e.n=3,fetch(t,o);case 3:u=e.v,e.n=7;break;case 4:if(e.p=4,p=e.v,this.logger.error("Network error during sendEvents (attempt ".concat(r+1,")"),{endpoint:t,error:p instanceof Error?p.message:p,retryCount:r}),!(r<this.config.maxRetries)){e.n=6;break}return c=this.calculateRetryDelay(r),this.logger.debug("Retrying in ".concat(c,"ms (attempt ").concat(r+2,")")),e.n=5,this.sleep(c);case 5:return e.a(2,this.sendEvents(t,n,r+1));case 6:throw p;case 7:if(u&&u.ok){e.n=10;break}if(g=(null==u?void 0:u.status)||"unknown",h=(null==u?void 0:u.statusText)||"unknown error",f=new Error("HTTP ".concat(g,": ").concat(h)),this.logger.error("HTTP error during sendEvents (attempt ".concat(r+1,")"),{endpoint:t,status:g,statusText:h,retryCount:r}),!(r<this.config.maxRetries)){e.n=9;break}return d=this.calculateRetryDelay(r),this.logger.debug("Retrying in ".concat(d,"ms (attempt ").concat(r+2,")")),e.n=8,this.sleep(d);case 8:return e.a(2,this.sendEvents(t,n,r+1));case 9:throw f;case 10:return e.p=10,e.n=11,u.json();case 11:v=e.v,e.n=13;break;case 12:e.p=12,e.v,v={};case 13:return this.logger.debug("Events sent successfully",{result:v}),e.a(2,v);case 14:throw e.p=14,y=e.v,this.logger.error("Unexpected error in sendEvents",{endpoint:t,error:y instanceof Error?y.message:y,retryCount:r}),y;case 15:return e.a(2)}}),e,this,[[10,12],[2,4],[1,14]])}))),function(t,n){return e.apply(this,arguments)})},{key:"updateConfig",value:function(e){this.config=e}},{key:"calculateRetryDelay",value:function(e){return"linear"===this.config.retryBackoff?1e3*(e+1):1e3*Math.pow(2,e)}},{key:"sleep",value:function(e){return new Promise((function(t){return setTimeout(t,e)}))}},{key:"getEventCountFromPayload",value:function(e){return e&&"object"===d(e)?e.tracks&&Array.isArray(e.tracks)?e.tracks.length:e.identifies&&Array.isArray(e.identifies)?e.identifies.length:e.groups&&Array.isArray(e.groups)?e.groups.length:1:0}}]);var e}(),I=function(){return s((function e(t,n,r,o,s){i(this,e),this.config=t,this.logger=n,this.eventTracker=r,this.sessionManager=o,this.queueManager=s}),[{key:"setupFeatures",value:function(){"undefined"!=typeof window?(this.config.enableAutoClickTracking&&this.setupAutoClickTracking(),this.config.enableAutoCapture&&this.setupAutoPageViews(),this.config.enableErrorTracking&&this.setupErrorTracking(),this.setupPageUnloadHandling(),this.logger.debug("Browser features setup complete")):this.logger.debug("Not in browser environment, skipping browser features")}},{key:"setupAutoClickTracking",value:function(){var e=this;"undefined"!=typeof document&&(this.clickHandler=function(t){try{var n=t.target;if(!n)return;var r=e.findClickableElement(n);if(!r)return;var i=e.extractClickProperties(r,t);e.eventTracker.track("click",i)}catch(t){e.logger.error("Error in click tracking",{error:t})}},document.addEventListener("click",this.clickHandler,{capture:!0}),this.logger.debug("Auto-click tracking enabled"))}},{key:"setupAutoPageViews",value:function(){var e=this;if("undefined"!=typeof window){this.trackPageView();var t=history.pushState,n=history.replaceState;history.pushState=function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];t.apply(history,r),setTimeout((function(){return e.trackPageView()}),0)},history.replaceState=function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];n.apply(history,r),setTimeout((function(){return e.trackPageView()}),0)},window.addEventListener("popstate",(function(){setTimeout((function(){return e.trackPageView()}),0)})),this.logger.debug("Auto page view tracking enabled")}}},{key:"setupErrorTracking",value:function(){var e=this;"undefined"!=typeof window&&(this.errorHandler=function(t){var n;try{e.eventTracker.track("error",{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno,stack:null===(n=t.error)||void 0===n?void 0:n.stack,timestamp:(new Date).toISOString()})}catch(t){e.logger.error("Error in error tracking",{error:t})}},window.addEventListener("error",this.errorHandler),this.logger.debug("Error tracking enabled"))}},{key:"setupPageUnloadHandling",value:function(){var e=this;"undefined"!=typeof window&&(this.unloadHandler=function(){try{e.queueManager.getQueueSize()>0&&e.networkManager&&e.queueManager.flush(e.networkManager)}catch(t){e.logger.error("Error in unload handler",{error:t})}},window.addEventListener("beforeunload",this.unloadHandler),this.logger.debug("Page unload handling enabled"))}},{key:"updateConfig",value:function(e){this.config=e}},{key:"setNetworkManager",value:function(e){this.networkManager=e}},{key:"trackPageView",value:function(){this.eventTracker.track("page_view",{url:window.location.href,path:window.location.pathname,search:window.location.search,title:document.title,referrer:document.referrer})}},{key:"findClickableElement",value:function(e){for(var t=e,n=0;t&&n<5;){var r=t.tagName.toLowerCase();if("a"===r||"button"===r||"button"===t.getAttribute("role")||t.onclick||"pointer"===t.style.cursor)return t;t=t.parentElement,n++}return e}},{key:"extractClickProperties",value:function(e,t){return e.getBoundingClientRect(),{element_type:this.getElementType(e),element_text:this.getElementText(e),element_id:e.id||null,element_class:e.className||null,element_tag:e.tagName.toLowerCase(),element_href:e.href||void 0,element_aria_label:e.getAttribute("aria-label")||void 0,page:window.location.pathname,page_title:document.title,page_url:window.location.href,position:{x:Math.round(t.clientX),y:Math.round(t.clientY)}}}},{key:"getElementType",value:function(e){var t=e.tagName.toLowerCase();return"a"===t?"link":"button"===t||"button"===e.getAttribute("role")?"button":"input"===t?"input":"form"===t?"form":"element"}},{key:"getElementText",value:function(e){return(e.innerText||e.textContent||e.getAttribute("aria-label")||e.getAttribute("title")||e.getAttribute("alt")||"").trim().substring(0,255)}}])}(),E=function(){return s((function e(){i(this,e),this.version="1.1.5",this.config={apiKey:"",baseURL:"https://drain.loopkit.ai/v1",batchSize:50,flushInterval:5,maxQueueSize:1e3,enableCompression:!0,requestTimeout:1e4,debug:!1,logLevel:"debug",enableAutoCapture:!0,enableAutoClickTracking:!0,enableErrorTracking:!0,enableSessionTracking:!0,sessionTimeout:1800,respectDoNotTrack:!0,enableLocalStorage:!0,maxRetries:3,retryBackoff:"exponential"},this.initialized=!1,this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={}}),[{key:"init",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||"string"!=typeof e)throw new Error("LoopKit: API key is required and must be a string");return this.config=c(c(c({},this.config),n),{},{apiKey:e}),v.validate(this.config),this.logger=new p(this.config),this.idGenerator=new y,this.storageManager=new k(this.config,this.logger),this.sessionManager=new m(this.config,this.logger,this.idGenerator,this.storageManager),this.queueManager=new b(this.config,this.logger,this.storageManager),this.eventTracker=new S(this.config,this.logger,this.queueManager,this.sessionManager,this.idGenerator),this.networkManager=new T(this.config,this.logger),"undefined"!=typeof window&&(this.browserFeatures=new I(this.config,this.logger,this.eventTracker,this.sessionManager,this.queueManager)),this.queueManager.setNetworkManager(this.networkManager),this.queueManager.scheduleFlush(),this.sessionManager.setSessionEventCallback((function(e,n){t.eventTracker.track(e,n,{},{userId:t.userId,userProperties:t.userProperties,groupId:t.groupId,groupProperties:t.groupProperties})})),this.browserFeatures&&(this.browserFeatures.setNetworkManager(this.networkManager),this.browserFeatures.setupFeatures()),this.initialized=!0,this.logger.debug("LoopKit configured",this.config),this.logger.info("LoopKit initialized",{apiKey:this.config.apiKey.substring(0,8)+"...",version:this.version}),this}},{key:"configure",value:function(e){var t,n,r,i,o,s,a,u;return v.validate(e),this.config=c(c({},this.config),e),this.initialized&&(null===(t=this.logger)||void 0===t||t.updateConfig(this.config),null===(n=this.storageManager)||void 0===n||n.updateConfig(this.config),null===(r=this.sessionManager)||void 0===r||r.updateConfig(this.config),null===(i=this.queueManager)||void 0===i||i.updateConfig(this.config),null===(o=this.eventTracker)||void 0===o||o.updateConfig(this.config),null===(s=this.networkManager)||void 0===s||s.updateConfig(this.config),null===(a=this.browserFeatures)||void 0===a||a.updateConfig(this.config),null===(u=this.queueManager)||void 0===u||u.restartAutoFlush()),this}},{key:"getConfig",value:function(){return c({},this.config)}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.initialized?e&&"string"==typeof e?(this.eventTracker.track(e,t,n,{userId:this.userId,userProperties:this.userProperties,groupId:this.groupId,groupProperties:this.groupProperties}),this):(this.logger.warn("Event name is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"trackBatch",value:function(e){var t=this;return this.initialized?Array.isArray(e)?(e.forEach((function(e){e&&"object"===d(e)&&e.name&&t.track(e.name,e.properties||{},e.options||{})})),this):(this.logger.error("trackBatch expects an array of events"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"identify",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initialized?e&&"string"==typeof e?(this.userId=e,this.userProperties=c(c({},this.userProperties),t),this.eventTracker.identify(e,t),this):(this.logger.error("User ID is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"group",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"organization";return this.initialized?e&&"string"==typeof e?(this.groupId=e,this.groupProperties=c(c({},this.groupProperties),t),this.eventTracker.group(e,t,n,{userId:this.userId}),this):(this.logger.error("Group ID is required and must be a string"),this):(this.logger.warn("LoopKit not initialized. Call init() first."),this)}},{key:"flush",value:(e=r(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:if(this.initialized){e.n=1;break}return this.logger.warn("LoopKit not initialized. Call init() first."),e.a(2);case 1:return e.a(2,this.queueManager.flush(this.networkManager))}}),e,this)}))),function(){return e.apply(this,arguments)})},{key:"getQueueSize",value:function(){return this.initialized?this.queueManager.getQueueSize():0}},{key:"reset",value:function(){var e,t,n;this.initialized&&(this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={},null===(e=this.queueManager)||void 0===e||e.reset(),null===(t=this.storageManager)||void 0===t||t.clearAll(),null===(n=this.sessionManager)||void 0===n||n.reset(),this.logger.debug("SDK state reset"))}},{key:"resetForTesting",value:function(){var e,t,n;this.initialized&&(null===(e=this.queueManager)||void 0===e||e.reset(),null===(t=this.storageManager)||void 0===t||t.clearAll(),null===(n=this.sessionManager)||void 0===n||n.reset()),this.initialized=!1,this.userId=null,this.userProperties={},this.groupId=null,this.groupProperties={},this.config={apiKey:"",baseURL:"https://drain.loopkit.ai/v1",batchSize:50,flushInterval:30,maxQueueSize:1e3,enableCompression:!0,requestTimeout:1e4,debug:!1,logLevel:"debug",enableAutoCapture:!0,enableAutoClickTracking:!0,enableErrorTracking:!0,enableSessionTracking:!0,sessionTimeout:1800,respectDoNotTrack:!0,enableLocalStorage:!0,maxRetries:3,retryBackoff:"exponential"}}}]);var e}(),A=new E;"undefined"!=typeof module&&module.exports?module.exports=A:"undefined"!=typeof window&&(window.LoopKit=A),e.LoopKit=E,e.default=A,Object.defineProperty(e,"__esModule",{value:!0})}));