ainamika-sdk 1.2.2 → 1.2.4

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,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AInamikaSDKPro=t():e.AInamikaSDKPro=t()}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,function(){return function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return I}});var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},n.apply(this,arguments)},r=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},o=function(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},i=function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},a=function(){function e(e){this.breadcrumbs=[],this.errorCount=0,this.errorDebounceMap=new Map,this.html2canvasLoaded=!1,this.html2canvasLoading=null,this.isCapturingScreenshot=!1,this.config=n({captureScreenshots:!1,captureDomSnapshots:!1,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},e),this.authManager=e.authManager,this.sessionId=this.generateSessionId(),this.originalConsole=n({},console),this.initialize()}return e.prototype.loadHtml2Canvas=function(){return r(this,void 0,void 0,function(){var e=this;return o(this,function(t){return this.html2canvasLoaded||"function"==typeof window.html2canvas?(this.html2canvasLoaded=!0,[2,!0]):(this.html2canvasLoading||(this.html2canvasLoading=new Promise(function(t){var n=document.createElement("script");n.src="https://html2canvas.hertzen.com/dist/html2canvas.min.js",n.async=!0,n.onload=function(){console.log("[AInamika Error Tracker] html2canvas loaded successfully"),e.html2canvasLoaded=!0,t(!0)},n.onerror=function(){console.error("[AInamika Error Tracker] Failed to load html2canvas"),t(!1)},document.head.appendChild(n)})),[2,this.html2canvasLoading])})})},e.prototype.initialize=function(){var e=this;window.addEventListener("error",function(t){e.handleError({type:"javascript",message:t.message,filename:t.filename,line:t.lineno,column:t.colno,error:t.error})}),window.addEventListener("unhandledrejection",function(t){var n;e.handleError({type:"unhandled",message:(null===(n=t.reason)||void 0===n?void 0:n.message)||"Unhandled Promise Rejection",error:t.reason,promise:!0})}),this.config.enableNetworkTracking&&this.setupNetworkTracking(),this.config.enableConsoleCapture&&this.setupConsoleCapture(),this.setupNavigationTracking(),this.setupClickTracking(),this.config.captureScreenshots&&this.loadHtml2Canvas(),console.log("[AInamika Error Tracker] Initialized successfully")},e.prototype.generateSessionId=function(){return"session_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.addBreadcrumb=function(e){this.breadcrumbs.push(n(n({},e),{timestamp:Date.now()})),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))},e.prototype.handleError=function(e){if(this.errorCount>=this.config.maxErrorsPerSession)console.warn("[AInamika Error Tracker] Max errors per session reached");else{var t="".concat(e.message,"_").concat(e.filename,"_").concat(e.line),n=Date.now();if(this.errorDebounceMap.has(t)&&n-this.errorDebounceMap.get(t)<this.config.debounceMs)return;this.errorDebounceMap.set(t,n),this.errorCount++,this.captureError(e)}},e.prototype.captureError=function(e){return r(this,void 0,void 0,function(){var t,n,r;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),t={client_id:this.config.clientId,project_key:this.config.projectKey,error_type:e.type||"javascript",message:e.message||"Unknown error",stack_trace:this.extractStackTrace(e.error),url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),error_metadata:{line:e.line,column:e.column,filename:e.filename,userId:this.userId,sessionId:this.sessionId,breadcrumbs:i([],this.breadcrumbs,!0),networkInfo:this.getNetworkInfo(),performance:this.getPerformanceInfo(),deviceInfo:this.getDeviceInfo()},severity:this.assessSeverity(e),session_id:this.sessionId,user_id:this.userId},this.config.captureScreenshots?(n=t,[4,this.captureScreenshot()]):[3,2];case 1:n.screen_snapshot=o.sent(),o.label=2;case 2:return[4,this.sendError(t)];case 3:return o.sent(),this.addBreadcrumb({type:"error",message:"".concat(t.error_type,": ").concat(t.message),data:{severity:t.severity}}),[3,5];case 4:return r=o.sent(),console.error("[AInamika Error Tracker] Failed to capture error:",r),[3,5];case 5:return[2]}})})},e.prototype.extractStackTrace=function(e){if(!e||!e.stack)return"";var t=e.stack.split("\n"),n=this.config.maxStackTraceDepth;return t.slice(0,n).join("\n")},e.prototype.assessSeverity=function(e){var t,n=(null===(t=e.message)||void 0===t?void 0:t.toLowerCase())||"";return n.includes("out of memory")||n.includes("security")||n.includes("permission denied")||"unhandled"===e.type?"critical":n.includes("network")||n.includes("timeout")||n.includes("failed to fetch")||n.includes("cors")?"high":n.includes("undefined")||n.includes("null")||n.includes("cannot read property")?"medium":"low"},e.prototype.captureDomSnapshot=function(){try{var e={url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},elements:this.extractDomElements()};return JSON.stringify(e)}catch(e){return console.error("[AInamika Error Tracker] Failed to capture DOM snapshot:",e),""}},e.prototype.extractDomElements=function(){var e=this,t=[];return["body > *","[id]",'[class*="error"]','[class*="modal"]',"form","button",'input[type="submit"]'].forEach(function(n){try{var r=document.querySelectorAll(n);Array.from(r).slice(0,100-t.length).forEach(function(n){var r;t.push({tagName:n.tagName,id:n.id,className:n.className,textContent:null===(r=n.textContent)||void 0===r?void 0:r.substring(0,100),attributes:e.getElementAttributes(n)})})}catch(e){}}),t},e.prototype.getElementAttributes=function(e){var t={};return["id","class","type","name","value","href","src"].forEach(function(n){var r=e.getAttribute(n);r&&(t[n]=r)}),t},e.prototype.captureScreenshot=function(){return r(this,void 0,void 0,function(){var e;return o(this,function(t){switch(t.label){case 0:if(this.isCapturingScreenshot)return[2,""];this.isCapturingScreenshot=!0,t.label=1;case 1:return t.trys.push([1,5,6,7]),[4,this.loadHtml2Canvas()];case 2:return t.sent()?"function"!=typeof window.html2canvas?[3,4]:[4,window.html2canvas(document.body,{height:Math.min(window.innerHeight,1e3),width:Math.min(window.innerWidth,1e3),useCORS:!0,logging:!1})]:(console.warn("[AInamika Error Tracker] html2canvas not available, skipping screenshot"),[2,""]);case 3:return[2,t.sent().toDataURL("image/jpeg",.7)];case 4:return[2,""];case 5:return e=t.sent(),console.error("[AInamika Error Tracker] Failed to capture screenshot:",e),[2,""];case 6:return this.isCapturingScreenshot=!1,[7];case 7:return[2]}})})},e.prototype.getNetworkInfo=function(){var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}:{}},e.prototype.getPerformanceInfo=function(){var e={};if(performance.memory&&(e.memory={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),performance.timing){var t=performance.timing;e.timing={domContentLoaded:t.domContentLoadedEventEnd-t.navigationStart,load:t.loadEventEnd-t.navigationStart},performance.getEntriesByType&&performance.getEntriesByType("paint").forEach(function(t){"first-paint"===t.name?e.timing.firstPaint=t.startTime:"first-contentful-paint"===t.name&&(e.timing.firstContentfulPaint=t.startTime)})}return e},e.prototype.getDeviceInfo=function(){var e=navigator.userAgent,t="desktop";/tablet|ipad|playbook|silk/i.test(e)?t="tablet":/mobile|iphone|ipod|android|blackberry|opera mini|iemobile/i.test(e)&&(t="mobile");var n="Unknown",r="";/windows/i.test(e)?(n="Windows",(a=e.match(/Windows NT (\d+\.\d+)/))&&(r=a[1])):/macintosh|mac os x/i.test(e)?(n="macOS",(a=e.match(/Mac OS X (\d+[._]\d+)/))&&(r=a[1].replace("_","."))):/android/i.test(e)?(n="Android",(a=e.match(/Android (\d+(\.\d+)?)/))&&(r=a[1])):/iphone|ipad|ipod/i.test(e)?(n="iOS",(a=e.match(/OS (\d+[._]\d+)/))&&(r=a[1].replace("_","."))):/linux/i.test(e)&&(n="Linux");var o="Unknown",i="";if(/edg/i.test(e))o="Edge",(a=e.match(/Edg\/(\d+(\.\d+)?)/))&&(i=a[1]);else if(/chrome/i.test(e)&&!/edg/i.test(e))o="Chrome",(a=e.match(/Chrome\/(\d+(\.\d+)?)/))&&(i=a[1]);else if(/safari/i.test(e)&&!/chrome/i.test(e))o="Safari",(a=e.match(/Version\/(\d+(\.\d+)?)/))&&(i=a[1]);else if(/firefox/i.test(e)){var a;o="Firefox",(a=e.match(/Firefox\/(\d+(\.\d+)?)/))&&(i=a[1])}return{deviceType:t,os:n,osVersion:r,browser:o,browserVersion:i,screenWidth:window.screen.width,screenHeight:window.screen.height,language:navigator.language||"",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||""}},e.prototype.setupNetworkTracking=function(){var e=this,t=window.fetch;window.fetch=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];return r(e,void 0,void 0,function(){var e,r,i,a;return o(this,function(o){switch(o.label){case 0:e=Date.now(),r=n[0]instanceof Request?n[0].url:String(n[0]),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,t.apply(void 0,n)];case 2:return i=o.sent(),this.addBreadcrumb({type:"network",message:"Fetch ".concat(i.status," ").concat(r),data:{url:r,status:i.status,duration:Date.now()-e}}),i.ok||this.handleError({type:"network",message:"Network request failed: ".concat(i.status," ").concat(i.statusText),url:r,status:i.status}),[2,i];case 3:throw a=o.sent(),this.addBreadcrumb({type:"network",message:"Fetch failed ".concat(r),data:{url:r,error:(null==a?void 0:a.message)||"Unknown error"}}),this.handleError({type:"network",message:"Network request failed: ".concat((null==a?void 0:a.message)||"Unknown error"),url:r,error:a}),a;case 4:return[2]}})})};var n=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,r,o,i){return this._errorTracker={method:e,url:t,startTime:Date.now()},n.call(this,e,t,r||!0,o,i)},XMLHttpRequest.prototype.send=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=this._errorTracker;return this.addEventListener("loadend",function(){if(r){var t=Date.now()-r.startTime;e.status>=400&&e.dispatchEvent(new CustomEvent("networkerror",{detail:{type:"network",message:"XHR request failed: ".concat(e.status," ").concat(e.statusText),url:r.url,status:e.status}})),e.dispatchEvent(new CustomEvent("networkbreadcrumb",{detail:{type:"network",message:"XHR ".concat(e.status," ").concat(r.url),data:{method:r.method,url:r.url,status:e.status,duration:t}}}))}}),a.call.apply(a,i([this],t,!1))},document.addEventListener("networkerror",function(t){e.handleError(t.detail)}),document.addEventListener("networkbreadcrumb",function(t){e.addBreadcrumb(t.detail)})},e.prototype.setupConsoleCapture=function(){var e=this;["error","warn"].forEach(function(t){var n=e.originalConsole[t];console[t]=function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];"function"==typeof n&&n.call.apply(n,i([console],r,!1)),"error"===t&&e.handleError({type:"console",message:r.map(function(e){return String(e)}).join(" "),consoleMethod:t}),e.addBreadcrumb({type:"console",message:"Console ".concat(t,": ").concat(r.map(function(e){return String(e)}).join(" ")),data:{level:t}})}})},e.prototype.setupNavigationTracking=function(){var e=this,t=window.location.href,n=function(){var n=window.location.href;n!==t&&(e.addBreadcrumb({type:"navigation",message:"Navigation from ".concat(t," to ").concat(n),data:{from:t,to:n}}),t=n)};window.addEventListener("popstate",n),window.addEventListener("hashchange",n);var r=history.pushState,o=history.replaceState;history.pushState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r.apply(this,e),setTimeout(n,0)},history.replaceState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];o.apply(this,e),setTimeout(n,0)}},e.prototype.setupClickTracking=function(){var e=this;document.addEventListener("click",function(t){var n,r=t.target;if(r){var o=e.getElementSelector(r),i=(null===(n=r.textContent)||void 0===n?void 0:n.trim().substring(0,50))||"";e.addBreadcrumb({type:"click",message:"Clicked ".concat(o).concat(i?": ".concat(i):""),data:{selector:o,text:i,tagName:r.tagName,id:r.id,className:r.className}})}})},e.prototype.getElementSelector=function(e){if(e.id)return"#".concat(e.id);if(e.className){var t=e.className.split(" ").filter(function(e){return e}).slice(0,2);if(t.length)return".".concat(t.join("."))}return e.tagName.toLowerCase()},e.prototype.sendError=function(e){return r(this,void 0,void 0,function(){var t,r,i,a;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,5,,6]),t={"Content-Type":"application/json"},this.authManager?[4,this.authManager.getAuthHeaders()]:[3,2];case 1:return r=o.sent(),t=n(n({},t),r),[3,3];case 2:this.config.apiKey&&(t.Authorization="Bearer ".concat(this.config.apiKey)),o.label=3;case 3:return[4,fetch("".concat(this.config.endpoint,"/api/v1/errors"),{method:"POST",headers:t,body:JSON.stringify(e)})];case 4:if(!(i=o.sent()).ok)throw new Error("Failed to send error: ".concat(i.status," ").concat(i.statusText));return console.log("[AInamika Error Tracker] Error sent successfully"),[3,6];case 5:return a=o.sent(),console.error("[AInamika Error Tracker] Failed to send error:",a),this.storeErrorLocally(e),[3,6];case 6:return[2]}})})},e.prototype.storeErrorLocally=function(e){try{var t=localStorage.getItem("ainamika_errors")||"[]",n=JSON.parse(t);n.push(e),n.length>50&&n.splice(0,n.length-50),localStorage.setItem("ainamika_errors",JSON.stringify(n))}catch(e){console.error("[AInamika Error Tracker] Failed to store error locally:",e)}},e.prototype.captureException=function(e,t){this.handleError({type:"custom",message:e.message,error:e,context:t})},e.prototype.setUser=function(e){this.userId=e},e.prototype.addTag=function(e,t){this.config.clientId||(this.config.clientId+="_".concat(e,":").concat(t))},e.prototype.flushStoredErrors=function(){return r(this,void 0,void 0,function(){var e,t,n,r,i,a;return o(this,function(o){switch(o.label){case 0:if(o.trys.push([0,5,,6]),!(e=localStorage.getItem("ainamika_errors")))return[2];if(0===(t=JSON.parse(e)).length)return[2];console.log("[AInamika Error Tracker] Flushing ".concat(t.length," stored errors")),n=0,r=t,o.label=1;case 1:return n<r.length?(i=r[n],[4,this.sendError(i)]):[3,4];case 2:o.sent(),o.label=3;case 3:return n++,[3,1];case 4:return localStorage.removeItem("ainamika_errors"),[3,6];case 5:return a=o.sent(),console.error("[AInamika Error Tracker] Failed to flush stored errors:",a),[3,6];case 6:return[2]}})})},e}(),s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},s.apply(this,arguments)},c=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},l=function(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},u=function(){function e(e){void 0===e&&(e={}),this.STORAGE_KEY="ainamika_error_queue",this.METADATA_KEY="ainamika_error_metadata",this.isProcessing=!1,this.config=s({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1},e),this.initialize()}return e.prototype.initialize=function(){var e=this;this.cleanupOldErrors(),this.startRetryTimer(),this.setupStorageListener(),setTimeout(function(){return e.processQueue()},1e3)},e.prototype.storeError=function(e){return c(this,void 0,void 0,function(){var t,n,r,o=this;return l(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=this.generateErrorId(),n={id:t,errorData:this.config.compressionEnabled?this.compressData(e):e,timestamp:Date.now(),retryCount:0},[4,this.addToQueue(n)];case 1:return i.sent(),this.updateMetadata(),setTimeout(function(){return o.processQueue()},100),[2,t];case 2:throw r=i.sent(),console.error("[AInamika Error Storage] Failed to store error:",r),r;case 3:return[2]}})})},e.prototype.getStoredErrors=function(){var e=this;try{var t=localStorage.getItem(this.STORAGE_KEY);return t?JSON.parse(t).map(function(t){return s(s({},t),{errorData:e.config.compressionEnabled?e.decompressData(t.errorData):t.errorData})}):[]}catch(e){return console.error("[AInamika Error Storage] Failed to get stored errors:",e),[]}},e.prototype.removeError=function(e){try{var t=this.getQueueRaw(),n=t.filter(function(t){return t.id!==e});return n.length!==t.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(n)),this.updateMetadata(),!0)}catch(e){return console.error("[AInamika Error Storage] Failed to remove error:",e),!1}},e.prototype.clearAll=function(){try{localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.METADATA_KEY),console.log("[AInamika Error Storage] All errors cleared")}catch(e){console.error("[AInamika Error Storage] Failed to clear errors:",e)}},e.prototype.getStorageStats=function(){try{var e=this.getQueueRaw(),t=new Blob([localStorage.getItem(this.STORAGE_KEY)||""]).size,n=e.map(function(e){return e.timestamp}).sort();return{errorCount:e.length,totalSize:t,oldestError:n[0],newestError:n[n.length-1]}}catch(e){return console.error("[AInamika Error Storage] Failed to get storage stats:",e),{errorCount:0,totalSize:0}}},e.prototype.processQueue=function(){return c(this,void 0,void 0,function(){var e,t,n,r,o;return l(this,function(i){switch(i.label){case 0:if(this.isProcessing)return[2];this.isProcessing=!0,i.label=1;case 1:if(i.trys.push([1,,8,9]),0===(e=this.getQueueRaw()).length)return[2];console.log("[AInamika Error Storage] Processing ".concat(e.length," queued errors")),t=0,n=e,i.label=2;case 2:if(!(t<n.length))return[3,7];if((r=n[t]).retryCount>=this.config.maxRetries)return console.warn("[AInamika Error Storage] Max retries reached for error ".concat(r.id)),this.removeError(r.id),[3,6];if(r.lastRetry&&Date.now()-r.lastRetry<this.config.retryInterval)return[3,6];i.label=3;case 3:return i.trys.push([3,5,,6]),[4,this.sendError(r)];case 4:return i.sent()?(this.removeError(r.id),console.log("[AInamika Error Storage] Successfully sent error ".concat(r.id))):this.incrementRetryCount(r.id),[3,6];case 5:return o=i.sent(),console.error("[AInamika Error Storage] Failed to send error ".concat(r.id,":"),o),this.incrementRetryCount(r.id),[3,6];case 6:return t++,[3,2];case 7:return[3,9];case 8:return this.isProcessing=!1,[7];case 9:return[2]}})})},e.prototype.retryError=function(e){return c(this,void 0,void 0,function(){var t,n,r;return l(this,function(o){switch(o.label){case 0:if(t=this.getQueueRaw(),!(n=t.find(function(t){return t.id===e})))return[2,!1];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.sendError(n)];case 2:return o.sent()?(this.removeError(e),[2,!0]):(this.incrementRetryCount(e),[2,!1]);case 3:return r=o.sent(),console.error("[AInamika Error Storage] Failed to retry error ".concat(e,":"),r),this.incrementRetryCount(e),[2,!1];case 4:return[2]}})})},e.prototype.addToQueue=function(e){return c(this,void 0,void 0,function(){var t,n;return l(this,function(r){if((t=this.getQueueRaw()).push(e),n=JSON.stringify(t),new Blob([n]).size>this.config.maxStorageSize)for(;t.length>0&&new Blob([JSON.stringify(t)]).size>this.config.maxStorageSize;)t.shift(),console.warn("[AInamika Error Storage] Removed old error due to size limit");return localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)),[2]})})},e.prototype.getQueueRaw=function(){try{var e=localStorage.getItem(this.STORAGE_KEY);return e?JSON.parse(e):[]}catch(e){return console.error("[AInamika Error Storage] Failed to parse stored errors:",e),[]}},e.prototype.incrementRetryCount=function(e){try{var t=this.getQueueRaw(),n=t.findIndex(function(t){return t.id===e});-1!==n&&(t[n].retryCount++,t[n].lastRetry=Date.now(),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)))}catch(e){console.error("[AInamika Error Storage] Failed to increment retry count:",e)}},e.prototype.sendError=function(e){return c(this,void 0,void 0,function(){var t,n,r,o;return l(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=this.config.compressionEnabled?this.decompressData(e.errorData):e.errorData,(n=this.config.endpoint||t.endpoint)?(r=t.apiKey||"",[4,fetch("".concat(n,"/api/v1/errors"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:r?"Bearer ".concat(r):""},body:JSON.stringify(t)})]):(console.error("[AInamika Error Storage] No endpoint configured for sending errors"),[2,!1]);case 1:return[2,i.sent().ok];case 2:return o=i.sent(),console.error("[AInamika Error Storage] Network error sending stored error:",o),[2,!1];case 3:return[2]}})})},e.prototype.compressData=function(e){try{var t=JSON.stringify(e);return btoa(t)}catch(t){return console.warn("[AInamika Error Storage] Compression failed, storing uncompressed:",t),e}},e.prototype.decompressData=function(e){try{if("string"==typeof e&&e.length>0){var t=atob(e);return JSON.parse(t)}return e}catch(t){return console.warn("[AInamika Error Storage] Decompression failed, returning raw data:",t),e}},e.prototype.generateErrorId=function(){return"error_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.cleanupOldErrors=function(){try{var e=this.getQueueRaw(),t=Date.now()-6048e5,n=e.filter(function(e){return e.timestamp>t});n.length!==e.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(n)),console.log("[AInamika Error Storage] Cleaned up ".concat(e.length-n.length," old errors")))}catch(e){console.error("[AInamika Error Storage] Failed to cleanup old errors:",e)}},e.prototype.startRetryTimer=function(){var e=this;this.retryTimer=window.setInterval(function(){e.processQueue()},this.config.retryInterval)},e.prototype.setupStorageListener=function(){var e=this;window.addEventListener("storage",function(t){t.key===e.STORAGE_KEY&&(console.log("[AInamika Error Storage] Storage updated from another tab"),setTimeout(function(){return e.processQueue()},1e3))}),window.addEventListener("online",function(){console.log("[AInamika Error Storage] Network back online, processing queue"),setTimeout(function(){return e.processQueue()},1e3)}),window.addEventListener("offline",function(){console.log("[AInamika Error Storage] Network offline, errors will be queued")})},e.prototype.updateMetadata=function(){try{var e=this.getStorageStats(),t=s({lastUpdate:Date.now()},e);localStorage.setItem(this.METADATA_KEY,JSON.stringify(t))}catch(e){console.error("[AInamika Error Storage] Failed to update metadata:",e)}},e.prototype.exportErrors=function(){try{var e=this.getStoredErrors(),t={timestamp:Date.now(),version:"1.0",stats:this.getStorageStats(),errors:e};return JSON.stringify(t,null,2)}catch(e){return console.error("[AInamika Error Storage] Failed to export errors:",e),"{}"}},e.prototype.importErrors=function(e){try{var t=JSON.parse(e);if(!t.errors||!Array.isArray(t.errors))throw new Error("Invalid export format");this.clearAll();for(var n=0,r=t.errors;n<r.length;n++){var o=r[n];this.storeError(o.errorData)}return console.log("[AInamika Error Storage] Imported ".concat(t.errors.length," errors")),!0}catch(e){return console.error("[AInamika Error Storage] Failed to import errors:",e),!1}},e.prototype.destroy=function(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=void 0),this.processQueue(),console.log("[AInamika Error Storage] Storage instance destroyed")},e}();!function(){function e(){}e.getAinamikaStorageUsage=function(){var e=0,t=0,n=0;for(var r in localStorage)if(localStorage.hasOwnProperty(r)){var o=new Blob([localStorage.getItem(r)||""]).size;e+=o,r.startsWith("ainamika_error")?t+=o:r.startsWith("ainamika_")&&(n+=o)}return{totalSize:e,errorSize:t,otherSize:n}},e.checkStorageSpace=function(e){try{var t="ainamika_storage_test",n="x".repeat(Math.min(e,1048576));return localStorage.setItem(t,n),localStorage.removeItem(t),!0}catch(e){return!1}},e.cleanupAllAinamikaStorage=function(){var e=[];for(var t in localStorage)t.startsWith("ainamika_")&&e.push(t);e.forEach(function(e){return localStorage.removeItem(e)}),console.log("[AInamika Storage Utils] Cleaned up ".concat(e.length," storage keys"))},e.generateStorageReport=function(){var t=new u;return{usage:e.getAinamikaStorageUsage(),errors:t.getStoredErrors(),metadata:t.getStorageStats()}}}();var h="undefined"!=typeof window&&window.__AINAMIKA_CONFIG__?window.__AINAMIKA_CONFIG__:{API_BASE_URL:"https://ainamika-webhook-proxy-366651516847.asia-south1.run.app",APP_ENV:"production",DEBUG:!1};"".concat(h.API_BASE_URL,"/api/v1/events"),"".concat(h.API_BASE_URL,"/api/errors/report"),"".concat(h.API_BASE_URL,"/api/v1/sdk/config"),"".concat(h.API_BASE_URL,"/api/v1/debug/events"),"".concat(h.API_BASE_URL,"/api/v1/projects/lookup"),"".concat(h.API_BASE_URL,"/api/v1/projects/sampling/check");var d=function(){return d=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},d.apply(this,arguments)},g=function(){function e(){this.userId=null,this.userProperties={},this.initializeUser()}return e.prototype.initializeUser=function(){this.userId=this.getOrCreateUserId()},e.prototype.getOrCreateUserId=function(){try{var e=localStorage.getItem("ainamika_user_id");return e||(e=this.generateAnonymousId(),localStorage.setItem("ainamika_user_id",e)),e}catch(e){return console.warn("[UserManager] localStorage not available, using session ID"),this.generateAnonymousId()}},e.prototype.generateAnonymousId=function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()},e.prototype.getUserId=function(){return this.userId||(this.userId=this.getOrCreateUserId()),this.userId},e.prototype.getUserProperties=function(){return d({},this.userProperties)},e.prototype.identifyUser=function(e,t){var n=this.getUserId();try{localStorage.setItem("ainamika_user_id",e),this.userId=e,t&&(this.userProperties=d(d({},this.userProperties),t)),console.log("[UserManager] User identified: ".concat(n," → ").concat(e))}catch(e){console.error("[UserManager] Error identifying user:",e)}},e.prototype.updateUserProperties=function(e){this.userProperties=d(d({},this.userProperties),e)},e.prototype.clearUser=function(){try{localStorage.removeItem("ainamika_user_id"),this.userId=null,this.userProperties={},this.initializeUser()}catch(e){console.error("[UserManager] Error clearing user:",e)}},e.prototype.getUserIdentificationEvent=function(e){return{event:"user_identified",previous_id:this.getUserId(),user_id:e,timestamp:Date.now(),properties:this.userProperties}},e.prototype.isAnonymousUser=function(){return this.getUserId().startsWith("anon_")},e.prototype.getUserType=function(){return this.isAnonymousUser()?"anonymous":"authenticated"},e}(),f=function(){return f=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},f.apply(this,arguments)},p=function(){function e(){this.userJourney=[],this.lastEventTime=0,this.sequenceIndex=0,this.maxJourneyLength=50,this.journeyAnalysisThreshold=5,this.journeyStartTime=Date.now()}return e.prototype.trackEvent=function(e,t){var n=Date.now(),r=this.lastEventTime?n-this.lastEventTime:0,o={eventName:e,timestamp:n,properties:f(f({},t),{timeSinceLastEvent:r,journeyPosition:this.sequenceIndex}),sequenceIndex:this.sequenceIndex++};this.userJourney.push(o),this.lastEventTime=n,this.userJourney.length>this.maxJourneyLength&&(this.userJourney=this.userJourney.slice(-this.maxJourneyLength)),console.log("[JourneyTracker] Event tracked: ".concat(e," (position: ").concat(o.sequenceIndex,")"))},e.prototype.getContext=function(){var e=Date.now();return{journeySequence:this.getJourneySequence(),eventCount:this.userJourney.length,lastEventTime:this.lastEventTime,journeyStartTime:this.journeyStartTime,timeSinceLastEvent:this.lastEventTime?e-this.lastEventTime:0}},e.prototype.getJourneySequence=function(){return this.userJourney.map(function(e){return e.eventName})},e.prototype.getJourneyData=function(){return function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}([],this.userJourney,!0)},e.prototype.shouldAnalyzeJourney=function(){return this.userJourney.length>=this.journeyAnalysisThreshold&&this.userJourney.length%this.journeyAnalysisThreshold===0},e.prototype.getJourneyForAnalysis=function(){var e=Date.now()-this.journeyStartTime,t=this.calculateAverageTimeBetweenEvents();return{journey:this.userJourney.map(function(e){return{name:e.eventName,timestamp:e.timestamp,properties:e.properties}}),metadata:{journeyLength:this.userJourney.length,journeyDuration:e,avgTimeBetweenEvents:t,startTime:this.journeyStartTime,endTime:this.lastEventTime}}},e.prototype.calculateAverageTimeBetweenEvents=function(){if(this.userJourney.length<2)return 0;for(var e=0,t=1;t<this.userJourney.length;t++)e+=this.userJourney[t].timestamp-this.userJourney[t-1].timestamp;return Math.round(e/(this.userJourney.length-1))},e.prototype.findPatterns=function(){var e={};if(this.userJourney.length<3)return e;for(var t=0;t<=this.userJourney.length-3;t++){var n=this.userJourney.slice(t,t+3).map(function(e){return e.eventName}).join(" → ");e[n]=(e[n]||0)+1}return Object.fromEntries(Object.entries(e).filter(function(e){return e[0],e[1]>1}))},e.prototype.clearJourney=function(){this.userJourney=[],this.sequenceIndex=0,this.lastEventTime=0,this.journeyStartTime=Date.now()},e.prototype.getJourneySegment=function(e){return this.userJourney.slice(-e)},e.prototype.detectPotentialFunnel=function(){for(var e=this.getJourneySequence().slice(-5),t=0,n=Object.entries({signup_flow:["view_pricing","click_signup","enter_email"],purchase_flow:["view_product","add_to_cart","view_cart"],onboarding_flow:["user_signup","profile_setup","tutorial_start"]});t<n.length;t++){var r=n[t],o=r[0];if(r[1].filter(function(t){return e.includes(t)}).length>=2)return o}return null},e}(),m=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},v=function(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},y=function(){function e(e,t,n){void 0===n&&(n=!1),this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.clientId=e,this.apiEndpoint=t,this.debug=n,this.loadTokens()}return e.prototype.initialize=function(){return m(this,void 0,void 0,function(){var e,t;return v(this,function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),this.isTokenValid()?(this.debugLog("Using existing valid token"),[2,!0]):this.refreshToken?[4,this.refreshAccessToken()]:[3,2];case 1:if(n.sent())return[2,!0];n.label=2;case 2:return[4,this.requestTokens()];case 3:return(e=n.sent())?(this.setTokens(e),[2,!0]):[2,!1];case 4:return t=n.sent(),this.debugLog("Authentication initialization failed:",t),[2,!1];case 5:return[2]}})})},e.prototype.requestTokens=function(){return m(this,void 0,void 0,function(){var e,t;return v(this,function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/token"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId})})];case 1:if(!(e=n.sent()).ok)throw new Error("Token request failed: ".concat(e.status));return[4,e.json()];case 2:return[2,n.sent()];case 3:return t=n.sent(),this.debugLog("Token request error:",t),[2,null];case 4:return[2]}})})},e.prototype.refreshAccessToken=function(){return m(this,void 0,void 0,function(){var e,t,n;return v(this,function(r){switch(r.label){case 0:if(!this.refreshToken)return[2,!1];r.label=1;case 1:return r.trys.push([1,4,,5]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/refresh"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:this.refreshToken})})];case 2:return(e=r.sent()).ok?[4,e.json()]:(this.clearTokens(),[2,!1]);case 3:return t=r.sent(),this.setTokens(t),[2,!0];case 4:return n=r.sent(),this.debugLog("Token refresh error:",n),[2,!1];case 5:return[2]}})})},e.prototype.getAccessToken=function(){return m(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return this.shouldRefreshToken()?[4,this.refreshAccessToken()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.isTokenValid()?[3,4]:[4,this.initialize()];case 3:if(!e.sent())return[2,null];e.label=4;case 4:return[2,this.accessToken]}})})},e.prototype.getAuthHeaders=function(){return m(this,void 0,void 0,function(){var e;return v(this,function(t){switch(t.label){case 0:return[4,this.getAccessToken()];case 1:return(e=t.sent())?[2,{Authorization:"Bearer ".concat(e)}]:[2,{"X-Client-ID":this.clientId}]}})})},e.prototype.isTokenValid=function(){return!(!this.accessToken||!this.tokenExpiry)&&Date.now()<this.tokenExpiry},e.prototype.shouldRefreshToken=function(){return!(!this.tokenExpiry||!this.refreshToken)&&Date.now()>this.tokenExpiry-3e5},e.prototype.setTokens=function(e){this.accessToken=e.access_token,this.refreshToken=e.refresh_token||this.refreshToken,this.tokenExpiry=Date.now()+1e3*e.expires_in,this.saveTokens(),this.scheduleTokenRefresh(),this.debugLog("Tokens set successfully")},e.prototype.scheduleTokenRefresh=function(){var e=this;this.refreshTimer&&clearTimeout(this.refreshTimer);var t=Math.max(0,this.tokenExpiry-Date.now()-3e5);this.refreshTimer=setTimeout(function(){e.refreshAccessToken()},t)},e.prototype.saveTokens=function(){if("undefined"!=typeof window&&window.localStorage){var t={clientId:this.clientId,accessToken:this.accessToken,refreshToken:this.refreshToken,tokenExpiry:this.tokenExpiry};localStorage.setItem(e.STORAGE_KEY,JSON.stringify(t)),this.cleanupLegacyTokens()}},e.prototype.cleanupLegacyTokens=function(){var t=this;if("undefined"!=typeof window&&window.localStorage){for(var n=[],r=0;r<localStorage.length;r++){var o=localStorage.key(r);o&&o.startsWith("ainamika_auth_")&&o!==e.STORAGE_KEY&&n.push(o)}n.forEach(function(e){localStorage.removeItem(e),t.debugLog("Removed legacy token key:",e)})}},e.prototype.loadTokens=function(){if("undefined"!=typeof window&&window.localStorage){this.cleanupLegacyTokens();var t=localStorage.getItem(e.STORAGE_KEY);if(t)try{var n=JSON.parse(t);if(n.clientId&&n.clientId!==this.clientId)return this.debugLog("Stored token is for different clientId, clearing"),void localStorage.removeItem(e.STORAGE_KEY);this.accessToken=n.accessToken,this.refreshToken=n.refreshToken,this.tokenExpiry=n.tokenExpiry,this.isTokenValid()&&this.scheduleTokenRefresh()}catch(e){this.debugLog("Failed to load stored tokens:",e)}}},e.prototype.clearTokens=function(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,"undefined"!=typeof window&&window.localStorage&&(localStorage.removeItem(e.STORAGE_KEY),this.cleanupLegacyTokens()),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},e.prototype.logout=function(){return m(this,void 0,void 0,function(){var e;return v(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,4,5]),this.accessToken?[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/logout"),{method:"POST",headers:{Authorization:"Bearer ".concat(this.accessToken)}})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[3,5];case 3:return e=t.sent(),this.debugLog("Logout error:",e),[3,5];case 4:return this.clearTokens(),[7];case 5:return[2]}})})},e.prototype.debugLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.debug&&console.log.apply(console,function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}(["[Ainamika Auth]"],e,!1))},e.STORAGE_KEY="ainamika_auth_token",e}(),k=function(){return k=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},k.apply(this,arguments)},b=function(){function e(e,t){this.performanceMetrics={},this.scrollDepthReached=new Set,this.clickHistory=[],this.isPageVisible=!0,this.visibilityChangeCount=0,this.config=k({trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100],rageClickThreshold:3,rageClickWindow:1e3,apiTrackingPatterns:[]},e),this.onEvent=t,this.pageStartTime=Date.now(),this.lastActivityTime=Date.now(),this.originalFetch=window.fetch.bind(window),this.originalXHR=XMLHttpRequest.prototype.open,this.engagementMetrics={timeOnPage:0,scrollDepth:0,scrollDepthMilestones:[],rageClicks:0,totalClicks:0,activeTime:0,idleTime:0,pageVisibilityChanges:0},this.initialize()}return e.prototype.initialize=function(){var e=this;this.config.trackPerformance&&this.initPerformanceTracking(),this.config.trackEngagement&&this.initEngagementTracking(),this.config.trackScrollDepth&&this.initScrollTracking(),this.config.trackRageClicks&&this.initRageClickTracking(),this.config.trackTimeOnPage&&this.initTimeTracking(),this.config.trackAPIResponses&&this.initAPITracking(),window.addEventListener("beforeunload",function(){e.trackPageExit()}),console.log("[AInamika Advanced Tracker] Initialized")},e.prototype.initPerformanceTracking=function(){var e=this;if("PerformanceObserver"in window){try{new PerformanceObserver(function(t){var n,r=t.getEntries(),o=r[r.length-1];e.performanceMetrics.lcp=o.startTime,e.onEvent("performance_lcp",{value:o.startTime,element:null===(n=o.element)||void 0===n?void 0:n.tagName})}).observe({type:"largest-contentful-paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] LCP not supported")}try{new PerformanceObserver(function(t){var n=t.getEntries()[0];e.performanceMetrics.fid=n.processingStart-n.startTime,e.onEvent("performance_fid",{value:e.performanceMetrics.fid,eventType:n.name})}).observe({type:"first-input",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FID not supported")}try{var t=0;new PerformanceObserver(function(n){for(var r=0,o=n.getEntries();r<o.length;r++){var i=o[r];i.hadRecentInput||(t+=i.value)}e.performanceMetrics.cls=t}).observe({type:"layout-shift",buffered:!0}),document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.onEvent("performance_cls",{value:t})})}catch(e){console.debug("[Advanced Tracker] CLS not supported")}try{new PerformanceObserver(function(t){var n=t.getEntries().find(function(e){return"first-contentful-paint"===e.name});n&&(e.performanceMetrics.fcp=n.startTime,e.onEvent("performance_fcp",{value:n.startTime}))}).observe({type:"paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FCP not supported")}}window.addEventListener("load",function(){setTimeout(function(){var t=performance.timing;e.performanceMetrics.ttfb=t.responseStart-t.navigationStart,e.performanceMetrics.domContentLoaded=t.domContentLoadedEventEnd-t.navigationStart,e.performanceMetrics.pageLoad=t.loadEventEnd-t.navigationStart;var n=performance.getEntriesByType("resource");e.performanceMetrics.resourceCount=n.length,e.performanceMetrics.transferSize=n.reduce(function(e,t){return e+(t.transferSize||0)},0),e.onEvent("performance_page_load",{ttfb:e.performanceMetrics.ttfb,domContentLoaded:e.performanceMetrics.domContentLoaded,pageLoad:e.performanceMetrics.pageLoad,resourceCount:e.performanceMetrics.resourceCount,transferSizeKB:Math.round((e.performanceMetrics.transferSize||0)/1024)})},0)})},e.prototype.initEngagementTracking=function(){var e=this;document.addEventListener("visibilitychange",function(){e.isPageVisible="visible"===document.visibilityState,e.visibilityChangeCount++,e.engagementMetrics.pageVisibilityChanges=e.visibilityChangeCount,e.isPageVisible?e.lastActivityTime=Date.now():e.updateActiveTime()}),["mousemove","keydown","touchstart","scroll"].forEach(function(t){document.addEventListener(t,function(){e.lastActivityTime=Date.now()},{passive:!0})}),document.addEventListener("click",function(){e.engagementMetrics.totalClicks++})},e.prototype.initScrollTracking=function(){var e=this,t=!1,n=function(){var n=window.scrollY||document.documentElement.scrollTop,r=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-window.innerHeight,o=r>0?Math.round(n/r*100):0;e.engagementMetrics.scrollDepth=Math.max(e.engagementMetrics.scrollDepth,o);for(var i=0,a=e.config.scrollDepthThresholds;i<a.length;i++){var s=a[i];o>=s&&!e.scrollDepthReached.has(s)&&(e.scrollDepthReached.add(s),e.engagementMetrics.scrollDepthMilestones.push(s),e.onEvent("engagement_scroll_depth",{depth:s,maxDepth:e.engagementMetrics.scrollDepth,timeToReach:Date.now()-e.pageStartTime}))}t=!1};window.addEventListener("scroll",function(){t||(requestAnimationFrame(n),t=!0)},{passive:!0})},e.prototype.initRageClickTracking=function(){var e=this;document.addEventListener("click",function(t){var n,r=Date.now();if(e.clickHistory.push(r),e.clickHistory=e.clickHistory.filter(function(t){return r-t<e.config.rageClickWindow}),e.clickHistory.length>=e.config.rageClickThreshold){e.engagementMetrics.rageClicks++;var o=t.target;e.onEvent("engagement_rage_click",{clickCount:e.clickHistory.length,element:{tagName:o.tagName,id:o.id,className:o.className,textContent:null===(n=o.textContent)||void 0===n?void 0:n.substring(0,50)},position:{x:t.clientX,y:t.clientY},totalRageClicks:e.engagementMetrics.rageClicks}),e.clickHistory=[]}})},e.prototype.initTimeTracking=function(){var e=this;setInterval(function(){e.updateActiveTime()},3e4)},e.prototype.updateActiveTime=function(){var e=Date.now(),t=e-this.lastActivityTime;this.engagementMetrics.timeOnPage=e-this.pageStartTime,t<3e4?this.engagementMetrics.activeTime+=Math.min(t,3e4):this.engagementMetrics.idleTime+=t},e.prototype.initAPITracking=function(){var e=this;window.fetch=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return r=e,o=void 0,a=function(){var e,n,r,o,i,a,s;return function(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}(this,function(c){switch(c.label){case 0:if(e=Date.now(),n=t[0]instanceof Request?t[0].url:String(t[0]),r=(null===(s=t[1])||void 0===s?void 0:s.method)||"GET",!this.shouldTrackAPI(n))return[2,this.originalFetch.apply(this,t)];c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this.originalFetch.apply(this,t)];case 2:return o=c.sent(),a=Date.now()-e,this.trackAPICall({url:n,method:r,status:o.status,duration:a,success:o.ok,timestamp:Date.now()}),[2,o];case 3:throw i=c.sent(),a=Date.now()-e,this.trackAPICall({url:n,method:r,status:0,duration:a,success:!1,error:(null==i?void 0:i.message)||"Network error",timestamp:Date.now()}),i;case 4:return[2]}})},new((i=void 0)||(i=Promise))(function(e,t){function n(e){try{c(a.next(e))}catch(e){t(e)}}function s(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i(function(e){e(r)})).then(n,s)}c((a=a.apply(r,o||[])).next())});var r,o,i,a},console.log("[Advanced Tracker] API tracking initialized")},e.prototype.shouldTrackAPI=function(e){return!this.config.apiTrackingPatterns||0===this.config.apiTrackingPatterns.length||this.config.apiTrackingPatterns.some(function(t){try{return new RegExp(t).test(e)}catch(n){return e.includes(t)}})},e.prototype.trackAPICall=function(e){this.onEvent("api_call",{url:e.url,method:e.method,status:e.status,duration:e.duration,success:e.success,error:e.error})},e.prototype.trackAPI=function(e,t,n,r){this.onEvent("api_response_tracked",k({endpoint:e,method:t,responseType:typeof n,responseKeys:n&&"object"==typeof n?Object.keys(n):[],hasData:!!n,dataCount:Array.isArray(n)?n.length:void 0},r))},e.prototype.trackEngagement=function(e,t){this.onEvent("engagement_".concat(e),k(k({},t),{timeOnPage:Date.now()-this.pageStartTime,scrollDepth:this.engagementMetrics.scrollDepth}))},e.prototype.trackConversion=function(e,t,n){this.onEvent("conversion",k(k({goal:e,value:t},n),{timeToConvert:Date.now()-this.pageStartTime,scrollDepthAtConversion:this.engagementMetrics.scrollDepth,clicksBeforeConversion:this.engagementMetrics.totalClicks}))},e.prototype.getPerformanceMetrics=function(){return k({},this.performanceMetrics)},e.prototype.getEngagementMetrics=function(){return this.updateActiveTime(),k(k({},this.engagementMetrics),{timeOnPage:Date.now()-this.pageStartTime})},e.prototype.trackPageExit=function(){this.updateActiveTime(),this.onEvent("page_exit",{timeOnPage:Date.now()-this.pageStartTime,activeTime:this.engagementMetrics.activeTime,idleTime:this.engagementMetrics.idleTime,scrollDepth:this.engagementMetrics.scrollDepth,scrollMilestones:this.engagementMetrics.scrollDepthMilestones,totalClicks:this.engagementMetrics.totalClicks,rageClicks:this.engagementMetrics.rageClicks,visibilityChanges:this.engagementMetrics.pageVisibilityChanges,performance:this.performanceMetrics})},e}(),w=function(){return w=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},w.apply(this,arguments)},S=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},T=function(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},_=function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},E=function(){function e(e){if(this.eventQueue=[],this.isInitialized=!1,this.batchRetryCount=0,this.maxBatchRetries=5,this.lastDomHash="",this.lastConfigHash="",this.mutationDebounceTimer=null,this.mutationDebounceMs=2e3,this.attachedListeners=new WeakMap,this.knownElementSelectors=new Set,this.handledClicks=new Map,this.CLICK_DEDUP_WINDOW_MS=50,this.mergedConfig={events_to_track:[]},this.MAX_CACHED_CONFIGS=15,!e.projectKey&&!e.clientId&&!e.apiKey)throw new Error("[AInamika SDK] Either projectKey or clientId is required for initialization");this.config=w({endpoint:h.API_BASE_URL,batchInterval:5e3,useWebWorker:!0,debug:h.DEBUG,errorTracking:{enabled:!0,captureScreenshots:!0,captureDomSnapshots:!0,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},advancedTracking:{enabled:!0,trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100]}},e),this.sessionId=this.generateSessionId(),this.userIdentifier=this.getOrCreateUserIdentifier(),this.userManager=new g,this.journeyTracker=new p,this.authManager=new y(this.config.clientId||this.config.apiKey||"",this.config.endpoint,this.config.debug);var t=new Blob(["\n self.eventQueue = [];\n self.config = {\n apiUrl: '',\n batchSize: 10,\n batchInterval: 5000,\n headers: { 'Content-Type': 'application/json' }\n };\n let batchTimer = null;\n function flushQueue() {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] flushQueue called', eventQueue: self.eventQueue, config: self.config });\n if (self.eventQueue.length === 0) return;\n const batch = self.eventQueue.splice(0, self.config.batchSize);\n fetch(self.config.apiUrl, {\n method: 'POST',\n headers: self.config.headers,\n body: JSON.stringify({ events: batch })\n }).then(r => {\n if (r.ok) {\n self.postMessage({ status: 'success' });\n } else {\n self.postMessage({ status: 'error', error: r.statusText, failedEvents: batch });\n }\n }).catch(e => {\n self.postMessage({ status: 'error', error: e.message, failedEvents: batch });\n });\n }\n self.onmessage = function(e) {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] onmessage', data: e.data });\n if (e.data.type === 'config') {\n self.config = { ...self.config, ...e.data.payload };\n if (batchTimer) clearInterval(batchTimer);\n batchTimer = setInterval(flushQueue, self.config.batchInterval);\n self.postMessage({ status: 'debug', message: '[AInamika Worker] config set', config: self.config });\n } else if (e.data.type === 'track') {\n self.eventQueue.push(e.data.payload);\n // Only send when timer triggers, not when batch size is reached\n // This ensures true batching behavior\n } else if (e.data.type === 'batch') {\n // Handle batch flush from main thread\n self.postMessage({ status: 'debug', message: '[AInamika Worker] Received batch from main thread', events: e.data.events });\n self.eventQueue.push(...e.data.events);\n flushQueue();\n } else if (e.data.type === 'initConfig') {\n // No-op for now, can be used for advanced config\n }\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(t);this.worker=new Worker(n),this.initialize()}return e.prototype.initialize=function(){return S(this,void 0,void 0,function(){var e,t,n,r,o;return T(this,function(i){switch(i.label){case 0:if(this.isInitialized)return[2];if(this.isInitialized=!0,!this.config.projectKey)return[3,5];i.label=1;case 1:return i.trys.push([1,4,,5]),[4,this.initializeProjectSettings()];case 2:return i.sent(),[4,this.initializeSamplingDecision()];case 3:return i.sent(),this.log("Project-based initialization complete",{projectKey:this.config.projectKey,projectSettings:this.projectSettings,samplingDecision:this.samplingDecision}),[3,5];case 4:return e=i.sent(),this.log("Project initialization failed:",e),console.warn("[AInamika SDK] Failed to initialize project settings. Some features may be limited."),[3,5];case 5:if(!this.config.clientId&&!this.config.apiKey)return[3,9];i.label=6;case 6:return i.trys.push([6,8,,9]),[4,this.authManager.initialize()];case 7:return i.sent(),this.log("Authentication initialized"),[3,9];case 8:return t=i.sent(),this.log("Authentication initialization failed:",t),this.config.debug||console.warn("[Ainamika] Running without authentication. Some features may be limited."),[3,9];case 9:return(null===(n=this.config.errorTracking)||void 0===n?void 0:n.enabled)&&this.shouldSampleErrors()?this.initializeErrorTracking():(null===(r=this.config.errorTracking)||void 0===r?void 0:r.enabled)&&!this.shouldSampleErrors()&&this.log("Error tracking disabled due to sampling decision"),(null===(o=this.config.advancedTracking)||void 0===o?void 0:o.enabled)&&this.initializeAdvancedTracking(),this.config.autoConfig?[4,this.setupAutoConfiguration()]:[3,11];case 10:i.sent(),this.setupDynamicDomTracking(),i.label=11;case 11:return this.config.useWebWorker&&"undefined"!=typeof Worker?[4,this.setupWebWorker()]:[3,13];case 12:return i.sent(),[3,14];case 13:this.startBatchTimer(),i.label=14;case 14:return this.log("AnalyticsPro SDK initialized",{config:this.config,projectKey:this.config.projectKey,sampling:this.samplingDecision}),[2]}})})},e.prototype.getOrCreateUserIdentifier=function(){var e="ainamika_user_identifier",t=localStorage.getItem(e);return t||(t="anon_"+Math.random().toString(36).substr(2,16)+Date.now().toString(36),localStorage.setItem(e,t),this.log("Created new user identifier:",t)),t},e.prototype.initializeProjectSettings=function(){return S(this,void 0,void 0,function(){var e,t,n;return T(this,function(r){switch(r.label){case 0:if(!this.config.projectKey)return[2];r.label=1;case 1:return r.trys.push([1,4,,5]),[4,fetch("".concat(this.config.endpoint,"/api/v1/projects/lookup"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey})})];case 2:if(!(e=r.sent()).ok)throw new Error("Project lookup failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.projectSettings=r.sent(),this.log("Project settings loaded:",this.projectSettings),[3,5];case 4:throw n=r.sent(),this.log("Failed to load project settings:",n),n;case 5:return[2]}})})},e.prototype.initializeSamplingDecision=function(){return S(this,void 0,void 0,function(){var e,t,n;return T(this,function(r){switch(r.label){case 0:if(!this.config.projectKey)return[2];r.label=1;case 1:return r.trys.push([1,4,,5]),[4,fetch("".concat(this.config.endpoint,"/api/v1/projects/sampling/check"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey,user_identifier:this.userIdentifier})})];case 2:if(!(e=r.sent()).ok)throw new Error("Sampling check failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.samplingDecision=r.sent(),this.log("Sampling decision received:",this.samplingDecision),this.cacheSamplingDecision(),[3,5];case 4:return n=r.sent(),this.log("Failed to get sampling decision, using cached or defaults:",n),this.loadCachedSamplingDecision(),[3,5];case 5:return[2]}})})},e.prototype.cacheSamplingDecision=function(){if(this.samplingDecision){var t=w({projectKey:this.config.projectKey},this.samplingDecision);localStorage.setItem(e.SAMPLING_STORAGE_KEY,JSON.stringify(t)),this.cleanupLegacySamplingKeys()}},e.prototype.loadCachedSamplingDecision=function(){this.cleanupLegacySamplingKeys();var t=localStorage.getItem(e.SAMPLING_STORAGE_KEY);if(t)try{var n=JSON.parse(t);if(n.projectKey&&n.projectKey!==this.config.projectKey)return this.log("Cached sampling is for different projectKey, clearing"),localStorage.removeItem(e.SAMPLING_STORAGE_KEY),void(this.samplingDecision=this.getDefaultSamplingDecision());n.projectKey;var r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(n,["projectKey"]);this.samplingDecision=r,this.log("Loaded cached sampling decision:",this.samplingDecision)}catch(e){this.samplingDecision=this.getDefaultSamplingDecision()}else this.samplingDecision=this.getDefaultSamplingDecision()},e.prototype.getDefaultSamplingDecision=function(){return{should_sample:{events:!0,errors:!0,session_replay:!1},rates:{events:100,errors:100,session_replay:0},decision:"existing"}},e.prototype.cleanupLegacySamplingKeys=function(){var t=this;if("undefined"!=typeof window&&window.localStorage){for(var n=[],r=0;r<localStorage.length;r++){var o=localStorage.key(r);o&&o.startsWith("ainamika_sampling_")&&o!==e.SAMPLING_STORAGE_KEY&&n.push(o)}n.forEach(function(e){localStorage.removeItem(e),t.log("Removed legacy sampling key:",e)})}},e.prototype.shouldSampleEvents=function(){return!this.samplingDecision||this.samplingDecision.should_sample.events},e.prototype.shouldSampleErrors=function(){return!this.samplingDecision||this.samplingDecision.should_sample.errors},e.prototype.shouldSampleSessionReplay=function(){return!!this.samplingDecision&&this.samplingDecision.should_sample.session_replay},e.prototype.getSamplingStatus=function(){return this.samplingDecision||null},e.prototype.getProjectInfo=function(){return this.projectSettings||null},e.prototype.getTrackingStatus=function(){return{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size,mergedConfig:this.mergedConfig}},e.prototype.resetDomTracking=function(){this.knownElementSelectors.clear(),this.mergedConfig={events_to_track:[]},this.lastDomHash="",this.attachedListeners=new WeakMap,this.log("DOM tracking reset - will re-analyze on next mutation")},e.prototype.clearAllCaches=function(t){void 0===t&&(t=!1);try{localStorage.removeItem("ainamika_dom_config_cache"),this.log("Cleared DOM config cache"),localStorage.removeItem("ainamika_last_known_config"),this.log("Cleared last-known config cache"),localStorage.removeItem(e.SAMPLING_STORAGE_KEY),this.cleanupLegacySamplingKeys(),this.log("Cleared sampling decision cache"),t&&(localStorage.removeItem("ainamika_user_identifier"),this.log("Cleared user identifier")),this.resetDomTracking(),this.samplingDecision=void 0,this.log("All caches cleared successfully")}catch(e){console.error("[AInamika SDK] Error clearing caches:",e)}},e.prototype.getCacheStats=function(){try{var t=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),n=Object.keys(t);return{domConfigCacheSize:n.length,cachedDomHashes:n,hasSamplingCache:!!localStorage.getItem(e.SAMPLING_STORAGE_KEY),hasUserIdentifier:!!localStorage.getItem("ainamika_user_identifier"),hasLastKnownConfig:!!localStorage.getItem("ainamika_last_known_config")}}catch(e){return{domConfigCacheSize:0,cachedDomHashes:[],hasSamplingCache:!1,hasUserIdentifier:!1,hasLastKnownConfig:!1}}},e.prototype.initializeErrorTracking=function(){var e,t,n,r,o,i,s,c,l,h,d,g,f,p;try{this.errorStorage=new u({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1,endpoint:this.config.endpoint});var m={endpoint:this.config.endpoint,clientId:this.config.clientId||"",apiKey:this.config.apiKey,authManager:this.authManager,projectKey:this.config.projectKey,captureScreenshots:null===(t=null===(e=this.config.errorTracking)||void 0===e?void 0:e.captureScreenshots)||void 0===t||t,captureDomSnapshots:null===(r=null===(n=this.config.errorTracking)||void 0===n?void 0:n.captureDomSnapshots)||void 0===r||r,maxStackTraceDepth:null!==(i=null===(o=this.config.errorTracking)||void 0===o?void 0:o.maxStackTraceDepth)&&void 0!==i?i:50,maxErrorsPerSession:null!==(c=null===(s=this.config.errorTracking)||void 0===s?void 0:s.maxErrorsPerSession)&&void 0!==c?c:100,debounceMs:null!==(h=null===(l=this.config.errorTracking)||void 0===l?void 0:l.debounceMs)&&void 0!==h?h:1e3,enableNetworkTracking:null===(g=null===(d=this.config.errorTracking)||void 0===d?void 0:d.enableNetworkTracking)||void 0===g||g,enableConsoleCapture:null===(p=null===(f=this.config.errorTracking)||void 0===f?void 0:f.enableConsoleCapture)||void 0===p||p};this.errorTracker=new a(m);var v=this.getUserId();v&&this.errorTracker&&this.errorTracker.setUser(v),this.log("Error tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize error tracking:",e)}},e.prototype.captureException=function(e,t){this.errorTracker&&this.errorTracker.captureException(e,t)},e.prototype.setUser=function(e){console.warn("[AInamika SDK] setUser is deprecated. Please use identifyUser() instead."),this.identifyUser(e)},e.prototype.flushStoredErrors=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return this.errorStorage?[4,this.errorStorage.processQueue()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.errorTracker?[4,this.errorTracker.flushStoredErrors()]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}})})},e.prototype.initializeAdvancedTracking=function(){var e,t,n,r,o,i,a,s,c,l,u,h,d,g,f=this;try{var p={trackPerformance:null===(t=null===(e=this.config.advancedTracking)||void 0===e?void 0:e.trackPerformance)||void 0===t||t,trackEngagement:null===(r=null===(n=this.config.advancedTracking)||void 0===n?void 0:n.trackEngagement)||void 0===r||r,trackScrollDepth:null===(i=null===(o=this.config.advancedTracking)||void 0===o?void 0:o.trackScrollDepth)||void 0===i||i,trackRageClicks:null===(s=null===(a=this.config.advancedTracking)||void 0===a?void 0:a.trackRageClicks)||void 0===s||s,trackTimeOnPage:null===(l=null===(c=this.config.advancedTracking)||void 0===c?void 0:c.trackTimeOnPage)||void 0===l||l,trackAPIResponses:null!==(h=null===(u=this.config.advancedTracking)||void 0===u?void 0:u.trackAPIResponses)&&void 0!==h&&h,scrollDepthThresholds:(null===(d=this.config.advancedTracking)||void 0===d?void 0:d.scrollDepthThresholds)||[25,50,75,90,100],apiTrackingPatterns:(null===(g=this.config.advancedTracking)||void 0===g?void 0:g.apiTrackingPatterns)||[]};this.advancedTracker=new b(p,function(e,t){f.sendToWorker(e,t)}),this.log("Advanced tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize advanced tracking:",e)}},e.prototype.trackAPI=function(e,t,n,r){this.advancedTracker?this.advancedTracker.trackAPI(e,t,n,r):this.track("api_response_tracked",w({endpoint:e,method:t,responseType:typeof n,hasData:!!n},r))},e.prototype.trackEngagement=function(e,t){this.advancedTracker?this.advancedTracker.trackEngagement(e,t):this.track("engagement_".concat(e),t||{})},e.prototype.trackConversion=function(e,t,n){this.advancedTracker?this.advancedTracker.trackConversion(e,t,n):this.track("conversion",w({goal:e,value:t},n))},e.prototype.getPerformanceMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getPerformanceMetrics())||null},e.prototype.getEngagementMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getEngagementMetrics())||null},e.prototype.setupAutoConfiguration=function(){return S(this,void 0,void 0,function(){var e,t;return T(this,function(n){try{this.log("Starting auto-configuration..."),e=!1,(t=this.getLastKnownConfig())&&t.events_to_track&&t.events_to_track.length>0&&(this.log("Applying last-known config IMMEDIATELY (zero delay)",{eventsCount:t.events_to_track.length}),this.mergedConfig={events_to_track:_([],t.events_to_track,!0),tracking_config:t.tracking_config},this.applyGeneratedConfig(t),e=!0,this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:t})),this.setupAutoConfigurationBackground(e)}catch(e){this.log("Auto-configuration failed with error",e)}return[2]})})},e.prototype.setupAutoConfigurationBackground=function(e){return S(this,void 0,void 0,function(){var t,n,r,o,i,a,s=this;return T(this,function(c){switch(c.label){case 0:return c.trys.push([0,5,,6]),[4,this.getDOMStructure()];case 1:return t=c.sent(),n=this.computeDomHash(t),this.lastDomHash=n,(t.elements||[]).forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Tracking ".concat(this.knownElementSelectors.size," initial element selectors")),r=this.getCachedConfigForDomHash(n),o=e,e?[3,4]:r&&r.events_to_track?(this.log("Applying cached config for DOM hash:",n),this.mergedConfig={events_to_track:_([],r.events_to_track,!0),tracking_config:r.tracking_config},this.applyGeneratedConfig(r),o=!0,this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:r}),[3,4]):[3,2];case 2:return[4,this.loadConfigFromFile()];case 3:(i=c.sent())&&i.events_to_track&&(this.log("Applying config from file"),this.mergedConfig={events_to_track:_([],i.events_to_track,!0),tracking_config:i.tracking_config},this.applyGeneratedConfig(i),o=!0),c.label=4;case 4:return this.fetchAndMergeFreshConfig(t,n,o),[3,6];case 5:return a=c.sent(),this.log("Background auto-configuration failed:",a),[3,6];case 6:return[2]}})})},e.prototype.fetchAndMergeFreshConfig=function(e,t,n){return S(this,void 0,void 0,function(){var r,o,i,a,s;return T(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),this.log("Fetching fresh config from backend (background)..."),[4,this.fetchGeneratedConfig(e,t)];case 1:return(r=c.sent())&&r.events_to_track?(n?(o=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),(i=r.events_to_track.filter(function(e){return!o.has(e.element_selector)})).length>0?(this.log("Found ".concat(i.length," new events from fresh config, merging...")),(s=this.mergedConfig.events_to_track).push.apply(s,i),this.applyGeneratedConfig({events_to_track:i,tracking_config:r.tracking_config})):this.log("Fresh config has no new events, cache was up-to-date"),r.tracking_config&&(this.mergedConfig.tracking_config=w(w({},this.mergedConfig.tracking_config),r.tracking_config))):(this.mergedConfig={events_to_track:_([],r.events_to_track,!0),tracking_config:r.tracking_config},this.applyGeneratedConfig(r),this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:r})),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=r.config_hash||"",this.setLastKnownConfig(this.mergedConfig),this.log("Fresh config processed successfully",{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size}),[3,3]):(this.log("No valid config returned from API"),[2]);case 2:return a=c.sent(),this.log("Background config fetch failed:",a),[3,3];case 3:return[2]}})})},e.prototype.getDOMStructure=function(){return S(this,void 0,void 0,function(){var e,t,n,r,o,i=this;return T(this,function(a){switch(a.label){case 0:return e=function(e){if(e.id)return/[\s!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/.test(e.id)?'[id="'.concat(e.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"]'):"#".concat(e.id);if(e.className&&"string"==typeof e.className){var t=e.className.split(" ").filter(function(e){return e.trim()}).join(".");return t?".".concat(t):e.tagName.toLowerCase()}return e.tagName.toLowerCase()},[4,new Promise(function(e){return setTimeout(e,500)})];case 1:return a.sent(),t=Array.from(document.body.querySelectorAll('\n button, a, input, select, textarea, form, img, h1, h2, h3, h4, h5, h6,\n [role=button], [role=link], [onclick], [tabindex], [data-analytics], [data-track],\n .card, .btn, .btn-primary, .btn-secondary, .card-title, .card-description, .card-price, .card-actions,\n [id*="card"], [class*="card"], [class*="btn"], [class*="price"], [class*="title"],\n div, span, p\n ')),n=t.filter(function(e){var t=window.getComputedStyle(e),n="none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity,r="button"===e.tagName.toLowerCase()||"a"===e.tagName.toLowerCase()||e.hasAttribute("onclick")||"button"===e.getAttribute("role")||e.classList.contains("btn")||e.classList.contains("card"),o="cardsContainer"===e.id||e.classList.contains("cards-grid")||e.classList.contains("card")||"img"===e.tagName.toLowerCase()||-1!==["h1","h2","h3"].indexOf(e.tagName.toLowerCase());return n&&(r||o)||"cardsContainer"===e.id}),r=new Set,o=n.map(function(t){var n,r,o={};Array.from(t.attributes).forEach(function(e){-1===["style","data-timestamp","data-rendered"].indexOf(e.name)&&(o[e.name]=e.value.length>25?e.value.substring(0,25):e.value)});var a=i.generateElementFingerprint(t);return{tagName:t.tagName.toLowerCase(),selector:e(t),fingerprint:a,id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().substring(0,100),attributes:o,isInteractive:"button"===t.tagName.toLowerCase()||"a"===t.tagName.toLowerCase()||t.hasAttribute("onclick")||"button"===t.getAttribute("role")||t.classList.contains("btn"),hasChildren:t.children.length>0,childCount:t.children.length,parentTagName:(null===(n=t.parentElement)||void 0===n?void 0:n.tagName.toLowerCase())||"",index:Array.from((null===(r=t.parentElement)||void 0===r?void 0:r.children)||[]).indexOf(t)}}).filter(function(e){return!r.has(e.fingerprint)&&(r.add(e.fingerprint),!0)}),this.log("DOM structure analyzed",{elementCount:o.length,elements:o}),[2,{elements:o}]}})})},e.prototype.fetchGeneratedConfig=function(e,t){return S(this,void 0,void 0,function(){var n,r,o,i,a;return T(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),e&&e.elements&&0===e.elements.length?(this.log("No elements found in DOM structure, skipping config fetch."),[2,null]):(n={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()]);case 1:return r=s.sent(),n=w(w({},n),r),o={structure:e},t&&(o.domHash=t,o.lastConfigHash=this.lastConfigHash),[4,fetch("".concat(this.config.endpoint,"/api/v1/sdk/config"),{method:"POST",headers:n,body:JSON.stringify(o)})];case 2:if(!(i=s.sent()).ok)throw new Error("Backend returned ".concat(i.status));return[4,i.json()];case 3:return[2,s.sent()];case 4:return a=s.sent(),this.log("Error fetching generated config:",a),[2,null];case 5:return[2]}})})},e.prototype.transformEventNameForType=function(e,t){if(!e||!t)return e;var n={view:{_clicked:"_viewed",_click:"_view"},focus:{_clicked:"_focused",_click:"_focus"},blur:{_clicked:"_blurred",_click:"_blur"}}[t];if(!n)return e;for(var r=0,o=Object.entries(n);r<o.length;r++){var i=o[r],a=i[0],s=i[1];if(e.endsWith(a))return e.slice(0,-a.length)+s}return"view"!==t||e.endsWith("_viewed")||e.endsWith("_view")?e:e+"_viewed"},e.prototype.sanitizeSelector=function(e){if(!e)return e;if(e.startsWith("#")&&!e.startsWith("[")){var t=e.substring(1);if(/[\s!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/.test(t)){var n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'[id="'.concat(n,'"]')}}return e},e.prototype.applyGeneratedConfig=function(e){var t=this;e.tracking_config&&this.log("Applying tracking config:",e.tracking_config),e.events_to_track.forEach(function(e){var n=t.sanitizeSelector(e.element_selector);try{var r=document.querySelectorAll(n),o=e.metadata_rules||{extract_customdata:!0,extract_text:!0};r.length>0?r.forEach(function(n){var r=t.attachedListeners.get(n);r||(r=new Set,t.attachedListeners.set(n,r)),(Array.isArray(e.event_type)?e.event_type:[e.event_type]).forEach(function(i){r.has(i)||(r.add(i),"click"===i&&(n.addEventListener("click",function(n){var r,i=Date.now(),a="interactive_element_clicked"===e.event_name,s=["div","span","p","section","article","header","footer","main","aside","nav","ul","ol","li","table","tr","td","th","tbody","thead","figure","figcaption","blockquote","pre","code","label","fieldset","legend","details","summary"].includes(null===(r=e.element_selector)||void 0===r?void 0:r.toLowerCase());if(a||s)for(var c=Array.from(t.handledClicks.entries()),l=0;l<c.length;l++){var u=c[l][0];if(Math.abs(i-u)<=t.CLICK_DEDUP_WINDOW_MS)return void t.log('Skipping generic event "'.concat(e.event_name,'" - specific event already sent'))}var h=n.target,d=t.extractElementData(h,o);if(!a&&!s){t.handledClicks.set(i,new Set([e.event_name]));var g=i-1e3,f=Array.from(t.handledClicks.keys());for(l=0;l<f.length;l++)f[l]<g&&t.handledClicks.delete(f[l])}t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"click",category:e.category||"uncategorized",element:d,itemName:d.itemName,section:d.section,timestamp:(new Date).toISOString()})}),t.log('Attached click listener for "'.concat(e.event_name,'" on "').concat(e.element_selector,'" (category: ').concat(e.category||"uncategorized",")"))),"view"===i&&"IntersectionObserver"in window&&(new IntersectionObserver(function(n){n.forEach(function(n){if(n.isIntersecting){var r=n.target,i=t.extractElementData(r,o),a=t.transformEventNameForType(e.event_name,"view");t.sendToWorker(a,{selector:e.element_selector,eventType:"view",category:e.category||"uncategorized",element:i,itemName:i.itemName,section:i.section,intersectionRatio:n.intersectionRatio,timestamp:(new Date).toISOString()})}})},{threshold:[.1,.5,1]}).observe(n),t.log('Attached IntersectionObserver for "'.concat(e.event_name,'" (as "').concat(t.transformEventNameForType(e.event_name,"view"),'") on "').concat(e.element_selector,'"'))),"focus"!==i&&"blur"!==i||(n.addEventListener(i,function(){var r=n,a=t.extractElementData(r,o),s=t.transformEventNameForType(e.event_name,i);t.sendToWorker(s,{selector:e.element_selector,eventType:i,category:e.category||"uncategorized",element:a,timestamp:(new Date).toISOString()})}),t.log("Attached ".concat(i,' listener for "').concat(e.event_name,'" (as "').concat(t.transformEventNameForType(e.event_name,i),'") on "').concat(e.element_selector,'"'))))})}):t.log('No elements found for selector: "'.concat(n,'" (original: "').concat(e.element_selector,'")'))}catch(r){t.log('Error applying selector "'.concat(n,'" (original: "').concat(e.element_selector,'"):'),r)}}),e.observe_mutations&&"MutationObserver"in window&&(new MutationObserver(function(e){e.forEach(function(e){t.sendToWorker("dom_mutation",{type:e.type,target:e.target.outerHTML,timestamp:(new Date).toISOString()})})}).observe(document.body,{childList:!0,subtree:!0}),this.log("MutationObserver attached for DOM changes"))},e.prototype.extractElementData=function(e,t){var n=e.getBoundingClientRect(),r={tagName:e.tagName.toLowerCase(),id:e.id||"",className:e.className||"",textContent:(e.textContent||"").trim().substring(0,100),position:{x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height)},href:e.href||void 0,value:e.value||void 0};if(!1!==(null==t?void 0:t.extract_customdata)){var o=function(e){var t,n={},r=e.getAttribute("customdata")||e.dataset.customdata;if(r)try{var o=JSON.parse(r);n.customdata=o,o.name&&(n.itemName=o.name),o.displayedTitle&&(n.section=o.displayedTitle),o.title&&(n.title=o.title),o.category&&(n.category=o.category),o.id&&(n.itemId=o.id)}catch(e){var i=r.match(/"name"\s*:\s*"([^"]+)"/);i&&(n.itemName=i[1]);var a=r.match(/"(?:displayedTitle|title)"\s*:\s*"([^"]+)"/);a&&(n.section=a[1])}var s=e.id;if(s){n.elementId=s;var c=s.split("_");if(c.length>=2){var l=c.slice(1).join("_");!n.itemName&&l&&(n.itemName=l)}}var u=null===(t=e.textContent)||void 0===t?void 0:t.trim();u&&u.length<100&&(n.displayText=u);for(var h=e.dataset,d=0,g=Object.entries(h);d<g.length;d++){var f=g[d],p=f[0],m=f[1];!n[p]&&m&&(n["data_".concat(p)]=m)}return n}(e);Object.keys(o).length>0&&(r.enriched=o,o.itemName&&(r.itemName=o.itemName),o.section&&(r.section=o.section),o.category&&(r.category=o.category))}return this.config.debug&&(r.attributes=Array.from(e.attributes).reduce(function(e,t){return e[t.name]=t.value.length>100?t.value.substring(0,100)+"...":t.value,e},{})),r},e.prototype.sendToWorker=function(e,t){var n;if(this.shouldSampleEvents()){var r=new Date,o=this.getCommonEventData(),i=w({event:e,properties:t,timestamp:r.getTime(),created_at:r.toISOString(),userId:this.getUserId(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(n=this.projectSettings)||void 0===n?void 0:n.project_id)||void 0},o);this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:i}):this.eventQueue.push(i),this.log("Event tracked:",i)}else this.log("Event skipped due to sampling:",e)},e.prototype.setupWebWorker=function(){return S(this,void 0,void 0,function(){var e,t,n,r,o,i=this;return T(this,function(a){switch(a.label){case 0:return[4,this.authManager.getAuthHeaders()];case 1:return e=a.sent(),this.worker.postMessage({type:"config",payload:{apiUrl:(null===(t=this.config.apiDetails)||void 0===t?void 0:t.apiEndPoint)||"".concat(this.config.endpoint,"/api/v1/events"),batchSize:(null===(n=this.config.workerConfig)||void 0===n?void 0:n.batchSize)||10,batchInterval:(null===(r=this.config.workerConfig)||void 0===r?void 0:r.batchInterval)||5e3,headers:w(w({"Content-Type":"application/json"},e),(null===(o=this.config.apiDetails)||void 0===o?void 0:o.headers)||{})}}),this.worker.onmessage=function(e){var t;"success"===e.data.status?i.log("Batch sent successfully by worker"):"debug"===e.data.status?i.log(e.data.message,e.data):"error"===e.data.status&&(i.log("Worker failed to send batch",e.data.error),e.data.failedEvents&&e.data.failedEvents.length>0&&(t=i.eventQueue).unshift.apply(t,e.data.failedEvents))},this.log("Web worker setup complete."),[2]}})})},e.prototype.track=function(e,t){var n;if(void 0===t&&(t={}),this.shouldSampleEvents()){this.journeyTracker.trackEvent(e,t);var r=this.journeyTracker.getContext(),o=new Date,i=this.getCommonEventData(),a=w({event:e,properties:w(w({},t),{journeyContext:{sequenceIndex:r.eventCount-1,timeSinceLastEvent:r.timeSinceLastEvent,journeyDuration:Date.now()-r.journeyStartTime}}),timestamp:o.getTime(),created_at:o.toISOString(),userId:this.userManager.getUserId(),userType:this.userManager.getUserType(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(n=this.projectSettings)||void 0===n?void 0:n.project_id)||void 0},i);this.journeyTracker.shouldAnalyzeJourney()&&this.sendJourneyForAnalysis(),this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:a}):this.eventQueue.push(a),this.log("Event tracked public:",a)}else this.log("Event skipped due to sampling:",e)},e.prototype.startBatchTimer=function(){var e=this;this.batchTimer=window.setInterval(function(){e.flushQueue()},this.config.batchInterval)},e.prototype.flushQueue=function(){return S(this,void 0,void 0,function(){var e;return T(this,function(t){switch(t.label){case 0:return 0===this.eventQueue.length?[2]:(e=_([],this.eventQueue,!0),this.eventQueue=[],this.config.useWebWorker&&"undefined"!=typeof Worker?(this.worker.postMessage({type:"batch",events:e,endpoint:"".concat(this.config.endpoint,"/api/v1/events")}),[3,3]):[3,1]);case 1:return[4,this.sendBatchWithRetry(e)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},e.prototype.sendBatchWithRetry=function(e){return S(this,void 0,void 0,function(){var t,n;return T(this,function(r){switch(r.label){case 0:if(this.batchRetryCount>=this.maxBatchRetries)return this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[2];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.sendBatch(e)];case 2:return r.sent(),this.batchRetryCount=0,[3,4];case 3:return t=r.sent(),this.batchRetryCount++,this.log("Batch send failed. Retry attempt ".concat(this.batchRetryCount," of ").concat(this.maxBatchRetries,"."),t),(n=this.eventQueue).unshift.apply(n,e),this.batchRetryCount>=this.maxBatchRetries&&this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[3,4];case 4:return[2]}})})},e.prototype.sendBatch=function(e){return S(this,void 0,void 0,function(){var t,n,r,o,i,a,s;return T(this,function(c){switch(c.label){case 0:return t="".concat(this.config.endpoint,"/api/v1/events"),n={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()];case 1:r=c.sent(),n=w(w({},n),r),this.config.apiDetails&&this.config.apiDetails.apiEndPoint&&(t=this.config.apiDetails.apiEndPoint,this.config.apiDetails.headers&&(n=w(w({},n),this.config.apiDetails.headers))),o=this.config.clientId||"5288aa7d-1b7c-481e-958d-eb9b8e951f14",i=e.map(function(e){return w({event:e.event,userId:e.userId,client_id:o,timestamp:new Date(e.timestamp).toISOString()},e.properties||{})}),c.label=2;case 2:return c.trys.push([2,4,,5]),[4,fetch(t,{method:"POST",headers:n,body:JSON.stringify({events:i})})];case 3:if(!(a=c.sent()).ok)throw new Error("Failed to send batch: ".concat(a.status));return this.log("Batch sent successfully:",i),[3,5];case 4:throw s=c.sent(),this.log("Error sending batch:",s),s;case 5:return[2]}})})},e.prototype.generateSessionId=function(){return"sess_"+Math.random().toString(36).substr(2,9)},e.prototype.getPageContext=function(){var e=window.location.href,t=window.location.pathname,n=window.location.hash,r=document.referrer,o={};return new URLSearchParams(window.location.search).forEach(function(e,t){o[t]=e}),{url:e,path:t,hash:n||void 0,referrer:r||void 0,queryParams:Object.keys(o).length>0?o:void 0,title:document.title||void 0}},e.prototype.getCommonEventData=function(){return w({pageContext:this.getPageContext()},this.config.extraConfig||{})},e.prototype.getUserId=function(){return this.userManager.getUserId()},e.prototype.identifyUser=function(e,t){var n=this.userManager.getUserIdentificationEvent(e);this.userManager.identifyUser(e,t),this.track("user_identified",n),this.errorTracker&&this.errorTracker.setUser(e),this.log("User identified:",{userId:e,properties:t})},e.prototype.setExtraConfig=function(e,t){void 0===t&&(t=!0),t&&this.config.extraConfig?this.config.extraConfig=w(w({},this.config.extraConfig),e):this.config.extraConfig=e,this.log("Extra config updated:",this.config.extraConfig)},e.prototype.getExtraConfig=function(){return this.config.extraConfig},e.prototype.isAuthenticated=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return[4,this.authManager.getAccessToken()];case 1:return[2,null!==e.sent()]}})})},e.prototype.authenticate=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return[4,this.authManager.initialize()];case 1:return[2,e.sent()]}})})},e.prototype.logout=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return[4,this.authManager.logout()];case 1:return e.sent(),[2]}})})},e.prototype.sendJourneyForAnalysis=function(){return S(this,void 0,void 0,function(){var e,t,n,r,o;return T(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),e=this.journeyTracker.getJourneyForAnalysis(),t="".concat(this.config.endpoint,"/api/v1/journeys/analyze"),[4,this.authManager.getAuthHeaders()];case 1:return n=i.sent(),[4,fetch(t,{method:"POST",headers:w({"Content-Type":"application/json"},n),body:JSON.stringify({client_id:this.config.clientId,user_id:this.userManager.getUserId(),session_id:this.sessionId,journey:e})})];case 2:return(r=i.sent()).ok||console.error("[AInamika SDK] Failed to send journey for analysis:",r.statusText),[3,4];case 3:return o=i.sent(),console.error("[AInamika SDK] Error sending journey for analysis:",o),[3,4];case 4:return[2]}})})},e.prototype.log=function(e,t){this.config.debug&&console.log("[AnalyticsPro SDK] ".concat(e),t||"")},e.prototype.loadConfigFromFile=function(){return S(this,void 0,void 0,function(){var e;return T(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch("/AInamika_config.json",{cache:"reload"})];case 1:return(e=t.sent()).ok?[4,e.json()]:[2,null];case 2:return[2,t.sent()];case 3:return t.sent(),[2,null];case 4:return[2]}})})},e.prototype.setupDynamicDomTracking=function(){return S(this,void 0,void 0,function(){var e=this;return T(this,function(t){return"MutationObserver"in window&&(new MutationObserver(function(){e.mutationDebounceTimer&&clearTimeout(e.mutationDebounceTimer),e.mutationDebounceTimer=window.setTimeout(function(){e.handleDomMutation()},e.mutationDebounceMs)}).observe(document.body,{childList:!0,subtree:!0,attributes:!0}),this.log("Dynamic DOM MutationObserver attached")),[2]})})},e.prototype.computeDomHash=function(e){for(var t=JSON.stringify(e),n=2166136261,r=0;r<t.length;r++)n^=t.charCodeAt(r),n+=(n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24);return(n>>>0).toString(16)},e.prototype.generateElementFingerprint=function(e){var t=[],n=e.getAttribute("data-testid"),r=e.getAttribute("data-track"),o=e.getAttribute("data-analytics");n&&t.push("testid:".concat(n)),r&&t.push("track:".concat(r)),o&&t.push("analytics:".concat(o));var i=e.id;i&&!i.match(/^(jsc|css|ember|react|ng)-|^\d+$|^[a-f0-9]{8,}$/i)&&t.push("id:".concat(i));var a=e.getAttribute("name");a&&t.push("name:".concat(a));var s=e.getAttribute("aria-label");s&&t.push("aria:".concat(s.substring(0,50)));var c=e.tagName.toLowerCase(),l=e.getAttribute("role"),u=e.getAttribute("type");if(t.push("tag:".concat(c)),l&&t.push("role:".concat(l)),u&&t.push("type:".concat(u)),["button","a","span","div"].includes(c)){var h=(e.textContent||"").trim().substring(0,30).toLowerCase().replace(/\s+/g,"_");h&&t.push("text:".concat(h))}var d=e.getAttribute("customdata");if(d)try{var g=JSON.parse(d);g.name&&t.push("customname:".concat(g.name)),g.id&&t.push("customid:".concat(g.id))}catch(e){t.push("customdata:".concat(d.substring(0,30)))}var f=e.closest('[data-testid], [id]:not([id^="jsc-"]):not([id^="css-"])');if(f&&f!==e){var p=f.getAttribute("data-testid")||f.id;p&&t.push("parent:".concat(p))}if(e.className&&"string"==typeof e.className){var m=e.className.split(" ").filter(function(e){return e.trim()&&!e.match(/^(jsc|css|ember|react|ng|active|hover|focus|selected|open|closed)-|^[a-f0-9]{6,}$/i)}).slice(0,3).join(".");m&&t.push("class:".concat(m))}var v=t.join("|");return this.hashString(v)},e.prototype.hashString=function(e){for(var t=0,n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t&=t;return Math.abs(t).toString(16).padStart(8,"0").substring(0,16)},e.prototype.getLastKnownConfig=function(){try{var e=localStorage.getItem("ainamika_last_known_config");if(!e)return null;var t=JSON.parse(e);return t&&t.events_to_track&&t.events_to_track.length>0?t:null}catch(e){return null}},e.prototype.setLastKnownConfig=function(e){try{e&&e.events_to_track&&e.events_to_track.length>0&&localStorage.setItem("ainamika_last_known_config",JSON.stringify(e))}catch(e){}},e.prototype.getCachedConfigForDomHash=function(e){try{var t=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),n=t[e];return n?n.events_to_track?(t[e]={config:n,lastAccessed:Date.now(),createdAt:Date.now()},localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),n):(n.lastAccessed=Date.now(),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),n.config):null}catch(e){return null}},e.prototype.setCachedConfigForDomHash=function(e,t){var n=this;try{var r=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}");r[e]={config:t,lastAccessed:Date.now(),createdAt:Date.now()};var o=Object.keys(r);o.length>this.MAX_CACHED_CONFIGS&&o.sort(function(e,t){return(r[e].lastAccessed||r[e].createdAt||0)-(r[t].lastAccessed||r[t].createdAt||0)}).slice(0,o.length-this.MAX_CACHED_CONFIGS).forEach(function(e){delete r[e],n.log("Evicted old config cache: ".concat(e))}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(r))}catch(e){this.log("Cache storage error, clearing old entries:",e),this.clearOldConfigCache()}},e.prototype.clearOldConfigCache=function(){try{var e=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),t=Object.keys(e);if(0===t.length)return;var n=t.sort(function(t,n){var r=e[t].lastAccessed||e[t].createdAt||0;return(e[n].lastAccessed||e[n].createdAt||0)-r}),r={};n.slice(0,5).forEach(function(t){r[t]=e[t]}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(r)),this.log("Cleared config cache, kept ".concat(Object.keys(r).length," entries"))}catch(e){localStorage.removeItem("ainamika_dom_config_cache")}},e.prototype.handleDomMutation=function(){return S(this,void 0,void 0,function(){var e,t,n,r,o,i,a,s=this;return T(this,function(c){switch(c.label){case 0:return[4,this.getDOMStructure()];case 1:return e=c.sent(),(t=this.computeDomHash(e))===this.lastDomHash?(this.log("DOM hash unchanged after mutation, skipping config fetch."),[2]):(this.log("DOM hash changed, detecting new elements...",{oldHash:this.lastDomHash,newHash:t}),this.lastDomHash=t,n=e.elements||[],0===(r=n.filter(function(e){var t=e.selector||"";return!(!t||s.knownElementSelectors.has(t))})).length?(this.log("No new elements detected, skipping config fetch."),[2]):(this.log("Found ".concat(r.length," new elements out of ").concat(n.length," total")),(o=this.getCachedConfigForDomHash(t))?(this.log("Reusing cached config for DOM hash",t),this.mergeAndApplyConfig(o),n.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),[2]):(i={elements:r},this.log("Fetching config for new elements only:",r.length),[4,this.fetchGeneratedConfig(i,t)])));case 2:return(a=c.sent())&&a.events_to_track?(this.mergeAndApplyConfig(a),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=a.config_hash||"",r.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Fetched and merged config for new elements",{newEvents:a.events_to_track.length,totalEvents:this.mergedConfig.events_to_track.length})):this.log("No valid config returned for new elements"),[2]}})})},e.prototype.mergeAndApplyConfig=function(e){var t;if(e&&e.events_to_track){var n=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),r=e.events_to_track.filter(function(e){return!n.has(e.element_selector)});r.length>0&&((t=this.mergedConfig.events_to_track).push.apply(t,r),this.log("Merged ".concat(r.length," new events, total: ").concat(this.mergedConfig.events_to_track.length))),e.tracking_config&&(this.mergedConfig.tracking_config=w(w({},this.mergedConfig.tracking_config),e.tracking_config)),r.length>0&&this.applyGeneratedConfig({events_to_track:r,tracking_config:e.tracking_config})}},e.SAMPLING_STORAGE_KEY="ainamika_sampling",e}();"undefined"!=typeof window&&(window.AInamikaSDKPro=E);var I=E;return t.default}()});
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AInamikaSDKPro=t():e.AInamikaSDKPro=t()}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,function(){return function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return I}});var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)},r=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},i=function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},o=function(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))},a=function(){function e(e){this.breadcrumbs=[],this.errorCount=0,this.errorDebounceMap=new Map,this.html2canvasLoaded=!1,this.html2canvasLoading=null,this.isCapturingScreenshot=!1,this.config=n({captureScreenshots:!1,captureDomSnapshots:!1,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},e),this.authManager=e.authManager,this.sessionId=this.generateSessionId(),this.originalConsole=n({},console),this.initialize()}return e.prototype.loadHtml2Canvas=function(){return r(this,void 0,void 0,function(){var e=this;return i(this,function(t){return this.html2canvasLoaded||"function"==typeof window.html2canvas?(this.html2canvasLoaded=!0,[2,!0]):(this.html2canvasLoading||(this.html2canvasLoading=new Promise(function(t){var n=document.createElement("script");n.src="https://html2canvas.hertzen.com/dist/html2canvas.min.js",n.async=!0,n.onload=function(){console.log("[AInamika Error Tracker] html2canvas loaded successfully"),e.html2canvasLoaded=!0,t(!0)},n.onerror=function(){console.error("[AInamika Error Tracker] Failed to load html2canvas"),t(!1)},document.head.appendChild(n)})),[2,this.html2canvasLoading])})})},e.prototype.initialize=function(){var e=this;window.addEventListener("error",function(t){e.handleError({type:"javascript",message:t.message,filename:t.filename,line:t.lineno,column:t.colno,error:t.error})}),window.addEventListener("unhandledrejection",function(t){var n;e.handleError({type:"unhandled",message:(null===(n=t.reason)||void 0===n?void 0:n.message)||"Unhandled Promise Rejection",error:t.reason,promise:!0})}),this.config.enableNetworkTracking&&this.setupNetworkTracking(),this.config.enableConsoleCapture&&this.setupConsoleCapture(),this.setupNavigationTracking(),this.setupClickTracking(),this.config.captureScreenshots&&this.loadHtml2Canvas(),console.log("[AInamika Error Tracker] Initialized successfully")},e.prototype.generateSessionId=function(){return"session_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.addBreadcrumb=function(e){this.breadcrumbs.push(n(n({},e),{timestamp:Date.now()})),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))},e.prototype.handleError=function(e){if(this.errorCount>=this.config.maxErrorsPerSession)console.warn("[AInamika Error Tracker] Max errors per session reached");else{var t="".concat(e.message,"_").concat(e.filename,"_").concat(e.line),n=Date.now();if(this.errorDebounceMap.has(t)&&n-this.errorDebounceMap.get(t)<this.config.debounceMs)return;this.errorDebounceMap.set(t,n),this.errorCount++,this.captureError(e)}},e.prototype.captureError=function(e){return r(this,void 0,void 0,function(){var t,n,r;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),t={client_id:this.config.clientId,project_key:this.config.projectKey,error_type:e.type||"javascript",message:e.message||"Unknown error",stack_trace:this.extractStackTrace(e.error),url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),error_metadata:{line:e.line,column:e.column,filename:e.filename,userId:this.userId,sessionId:this.sessionId,breadcrumbs:o([],this.breadcrumbs,!0),networkInfo:this.getNetworkInfo(),performance:this.getPerformanceInfo(),deviceInfo:this.getDeviceInfo()},severity:this.assessSeverity(e),session_id:this.sessionId,user_id:this.userId},this.config.captureScreenshots?(n=t,[4,this.captureScreenshot()]):[3,2];case 1:n.screen_snapshot=i.sent(),i.label=2;case 2:return[4,this.sendError(t)];case 3:return i.sent(),this.addBreadcrumb({type:"error",message:"".concat(t.error_type,": ").concat(t.message),data:{severity:t.severity}}),[3,5];case 4:return r=i.sent(),console.error("[AInamika Error Tracker] Failed to capture error:",r),[3,5];case 5:return[2]}})})},e.prototype.extractStackTrace=function(e){if(!e||!e.stack)return"";var t=e.stack.split("\n"),n=this.config.maxStackTraceDepth;return t.slice(0,n).join("\n")},e.prototype.assessSeverity=function(e){var t,n=(null===(t=e.message)||void 0===t?void 0:t.toLowerCase())||"";return n.includes("out of memory")||n.includes("security")||n.includes("permission denied")||"unhandled"===e.type?"critical":n.includes("network")||n.includes("timeout")||n.includes("failed to fetch")||n.includes("cors")?"high":n.includes("undefined")||n.includes("null")||n.includes("cannot read property")?"medium":"low"},e.prototype.captureDomSnapshot=function(){try{var e={url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},elements:this.extractDomElements()};return JSON.stringify(e)}catch(e){return console.error("[AInamika Error Tracker] Failed to capture DOM snapshot:",e),""}},e.prototype.extractDomElements=function(){var e=this,t=[];return["body > *","[id]",'[class*="error"]','[class*="modal"]',"form","button",'input[type="submit"]'].forEach(function(n){try{var r=document.querySelectorAll(n);Array.from(r).slice(0,100-t.length).forEach(function(n){var r;t.push({tagName:n.tagName,id:n.id,className:n.className,textContent:null===(r=n.textContent)||void 0===r?void 0:r.substring(0,100),attributes:e.getElementAttributes(n)})})}catch(e){}}),t},e.prototype.getElementAttributes=function(e){var t={};return["id","class","type","name","value","href","src"].forEach(function(n){var r=e.getAttribute(n);r&&(t[n]=r)}),t},e.prototype.captureScreenshot=function(){return r(this,void 0,void 0,function(){var e;return i(this,function(t){switch(t.label){case 0:if(this.isCapturingScreenshot)return[2,""];this.isCapturingScreenshot=!0,t.label=1;case 1:return t.trys.push([1,5,6,7]),[4,this.loadHtml2Canvas()];case 2:return t.sent()?"function"!=typeof window.html2canvas?[3,4]:[4,window.html2canvas(document.body,{height:Math.min(window.innerHeight,1e3),width:Math.min(window.innerWidth,1e3),useCORS:!0,logging:!1})]:(console.warn("[AInamika Error Tracker] html2canvas not available, skipping screenshot"),[2,""]);case 3:return[2,t.sent().toDataURL("image/jpeg",.7)];case 4:return[2,""];case 5:return e=t.sent(),console.error("[AInamika Error Tracker] Failed to capture screenshot:",e),[2,""];case 6:return this.isCapturingScreenshot=!1,[7];case 7:return[2]}})})},e.prototype.getNetworkInfo=function(){var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}:{}},e.prototype.getPerformanceInfo=function(){var e={};if(performance.memory&&(e.memory={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),performance.timing){var t=performance.timing;e.timing={domContentLoaded:t.domContentLoadedEventEnd-t.navigationStart,load:t.loadEventEnd-t.navigationStart},performance.getEntriesByType&&performance.getEntriesByType("paint").forEach(function(t){"first-paint"===t.name?e.timing.firstPaint=t.startTime:"first-contentful-paint"===t.name&&(e.timing.firstContentfulPaint=t.startTime)})}return e},e.prototype.getDeviceInfo=function(){var e=navigator.userAgent,t="desktop";/tablet|ipad|playbook|silk/i.test(e)?t="tablet":/mobile|iphone|ipod|android|blackberry|opera mini|iemobile/i.test(e)&&(t="mobile");var n="Unknown",r="";/windows/i.test(e)?(n="Windows",(a=e.match(/Windows NT (\d+\.\d+)/))&&(r=a[1])):/macintosh|mac os x/i.test(e)?(n="macOS",(a=e.match(/Mac OS X (\d+[._]\d+)/))&&(r=a[1].replace("_","."))):/android/i.test(e)?(n="Android",(a=e.match(/Android (\d+(\.\d+)?)/))&&(r=a[1])):/iphone|ipad|ipod/i.test(e)?(n="iOS",(a=e.match(/OS (\d+[._]\d+)/))&&(r=a[1].replace("_","."))):/linux/i.test(e)&&(n="Linux");var i="Unknown",o="";if(/edg/i.test(e))i="Edge",(a=e.match(/Edg\/(\d+(\.\d+)?)/))&&(o=a[1]);else if(/chrome/i.test(e)&&!/edg/i.test(e))i="Chrome",(a=e.match(/Chrome\/(\d+(\.\d+)?)/))&&(o=a[1]);else if(/safari/i.test(e)&&!/chrome/i.test(e))i="Safari",(a=e.match(/Version\/(\d+(\.\d+)?)/))&&(o=a[1]);else if(/firefox/i.test(e)){var a;i="Firefox",(a=e.match(/Firefox\/(\d+(\.\d+)?)/))&&(o=a[1])}return{deviceType:t,os:n,osVersion:r,browser:i,browserVersion:o,screenWidth:window.screen.width,screenHeight:window.screen.height,language:navigator.language||"",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||""}},e.prototype.setupNetworkTracking=function(){var e=this,t=window.fetch;window.fetch=function(){for(var n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return r(e,void 0,void 0,function(){var e,r,o,a;return i(this,function(i){switch(i.label){case 0:e=Date.now(),r=n[0]instanceof Request?n[0].url:String(n[0]),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,t.apply(void 0,n)];case 2:return o=i.sent(),this.addBreadcrumb({type:"network",message:"Fetch ".concat(o.status," ").concat(r),data:{url:r,status:o.status,duration:Date.now()-e}}),o.ok||this.handleError({type:"network",message:"Network request failed: ".concat(o.status," ").concat(o.statusText),url:r,status:o.status}),[2,o];case 3:throw a=i.sent(),this.addBreadcrumb({type:"network",message:"Fetch failed ".concat(r),data:{url:r,error:(null==a?void 0:a.message)||"Unknown error"}}),this.handleError({type:"network",message:"Network request failed: ".concat((null==a?void 0:a.message)||"Unknown error"),url:r,error:a}),a;case 4:return[2]}})})};var n=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,r,i,o){return this._errorTracker={method:e,url:t,startTime:Date.now()},n.call(this,e,t,r||!0,i,o)},XMLHttpRequest.prototype.send=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=this._errorTracker;return this.addEventListener("loadend",function(){if(r){var t=Date.now()-r.startTime;e.status>=400&&e.dispatchEvent(new CustomEvent("networkerror",{detail:{type:"network",message:"XHR request failed: ".concat(e.status," ").concat(e.statusText),url:r.url,status:e.status}})),e.dispatchEvent(new CustomEvent("networkbreadcrumb",{detail:{type:"network",message:"XHR ".concat(e.status," ").concat(r.url),data:{method:r.method,url:r.url,status:e.status,duration:t}}}))}}),a.call.apply(a,o([this],t,!1))},document.addEventListener("networkerror",function(t){e.handleError(t.detail)}),document.addEventListener("networkbreadcrumb",function(t){e.addBreadcrumb(t.detail)})},e.prototype.setupConsoleCapture=function(){var e=this;["error","warn"].forEach(function(t){var n=e.originalConsole[t];console[t]=function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];"function"==typeof n&&n.call.apply(n,o([console],r,!1)),"error"===t&&e.handleError({type:"console",message:r.map(function(e){return String(e)}).join(" "),consoleMethod:t}),e.addBreadcrumb({type:"console",message:"Console ".concat(t,": ").concat(r.map(function(e){return String(e)}).join(" ")),data:{level:t}})}})},e.prototype.setupNavigationTracking=function(){var e=this,t=window.location.href,n=function(){var n=window.location.href;n!==t&&(e.addBreadcrumb({type:"navigation",message:"Navigation from ".concat(t," to ").concat(n),data:{from:t,to:n}}),t=n)};window.addEventListener("popstate",n),window.addEventListener("hashchange",n);var r=history.pushState,i=history.replaceState;history.pushState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r.apply(this,e),setTimeout(n,0)},history.replaceState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];i.apply(this,e),setTimeout(n,0)}},e.prototype.setupClickTracking=function(){var e=this;document.addEventListener("click",function(t){var n,r=t.target;if(r){var i=e.getElementSelector(r),o=(null===(n=r.textContent)||void 0===n?void 0:n.trim().substring(0,50))||"";e.addBreadcrumb({type:"click",message:"Clicked ".concat(i).concat(o?": ".concat(o):""),data:{selector:i,text:o,tagName:r.tagName,id:r.id,className:r.className}})}})},e.prototype.getElementSelector=function(e){if(e.id)return"#".concat(e.id);if(e.className){var t=e.className.split(" ").filter(function(e){return e}).slice(0,2);if(t.length)return".".concat(t.join("."))}return e.tagName.toLowerCase()},e.prototype.sendError=function(e){return r(this,void 0,void 0,function(){var t,r,o,a;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,5,,6]),t={"Content-Type":"application/json"},this.authManager?[4,this.authManager.getAuthHeaders()]:[3,2];case 1:return r=i.sent(),t=n(n({},t),r),[3,3];case 2:this.config.apiKey&&(t.Authorization="Bearer ".concat(this.config.apiKey)),i.label=3;case 3:return[4,fetch("".concat(this.config.endpoint,"/api/v1/errors"),{method:"POST",headers:t,body:JSON.stringify(e)})];case 4:if(!(o=i.sent()).ok)throw new Error("Failed to send error: ".concat(o.status," ").concat(o.statusText));return console.log("[AInamika Error Tracker] Error sent successfully"),[3,6];case 5:return a=i.sent(),console.error("[AInamika Error Tracker] Failed to send error:",a),this.storeErrorLocally(e),[3,6];case 6:return[2]}})})},e.prototype.storeErrorLocally=function(e){try{var t=localStorage.getItem("ainamika_errors")||"[]",n=JSON.parse(t);n.push(e),n.length>50&&n.splice(0,n.length-50),localStorage.setItem("ainamika_errors",JSON.stringify(n))}catch(e){console.error("[AInamika Error Tracker] Failed to store error locally:",e)}},e.prototype.captureException=function(e,t){this.handleError({type:"custom",message:e.message,error:e,context:t})},e.prototype.setUser=function(e){this.userId=e},e.prototype.addTag=function(e,t){this.config.clientId||(this.config.clientId+="_".concat(e,":").concat(t))},e.prototype.flushStoredErrors=function(){return r(this,void 0,void 0,function(){var e,t,n,r,o,a;return i(this,function(i){switch(i.label){case 0:if(i.trys.push([0,5,,6]),!(e=localStorage.getItem("ainamika_errors")))return[2];if(0===(t=JSON.parse(e)).length)return[2];console.log("[AInamika Error Tracker] Flushing ".concat(t.length," stored errors")),n=0,r=t,i.label=1;case 1:return n<r.length?(o=r[n],[4,this.sendError(o)]):[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return localStorage.removeItem("ainamika_errors"),[3,6];case 5:return a=i.sent(),console.error("[AInamika Error Tracker] Failed to flush stored errors:",a),[3,6];case 6:return[2]}})})},e}(),s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},s.apply(this,arguments)},c=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},l=function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},u=function(){function e(e){void 0===e&&(e={}),this.STORAGE_KEY="ainamika_error_queue",this.METADATA_KEY="ainamika_error_metadata",this.isProcessing=!1,this.config=s({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1},e),this.initialize()}return e.prototype.initialize=function(){var e=this;this.cleanupOldErrors(),this.startRetryTimer(),this.setupStorageListener(),setTimeout(function(){return e.processQueue()},1e3)},e.prototype.storeError=function(e){return c(this,void 0,void 0,function(){var t,n,r,i=this;return l(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),t=this.generateErrorId(),n={id:t,errorData:this.config.compressionEnabled?this.compressData(e):e,timestamp:Date.now(),retryCount:0},[4,this.addToQueue(n)];case 1:return o.sent(),this.updateMetadata(),setTimeout(function(){return i.processQueue()},100),[2,t];case 2:throw r=o.sent(),console.error("[AInamika Error Storage] Failed to store error:",r),r;case 3:return[2]}})})},e.prototype.getStoredErrors=function(){var e=this;try{var t=localStorage.getItem(this.STORAGE_KEY);return t?JSON.parse(t).map(function(t){return s(s({},t),{errorData:e.config.compressionEnabled?e.decompressData(t.errorData):t.errorData})}):[]}catch(e){return console.error("[AInamika Error Storage] Failed to get stored errors:",e),[]}},e.prototype.removeError=function(e){try{var t=this.getQueueRaw(),n=t.filter(function(t){return t.id!==e});return n.length!==t.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(n)),this.updateMetadata(),!0)}catch(e){return console.error("[AInamika Error Storage] Failed to remove error:",e),!1}},e.prototype.clearAll=function(){try{localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.METADATA_KEY),console.log("[AInamika Error Storage] All errors cleared")}catch(e){console.error("[AInamika Error Storage] Failed to clear errors:",e)}},e.prototype.getStorageStats=function(){try{var e=this.getQueueRaw(),t=new Blob([localStorage.getItem(this.STORAGE_KEY)||""]).size,n=e.map(function(e){return e.timestamp}).sort();return{errorCount:e.length,totalSize:t,oldestError:n[0],newestError:n[n.length-1]}}catch(e){return console.error("[AInamika Error Storage] Failed to get storage stats:",e),{errorCount:0,totalSize:0}}},e.prototype.processQueue=function(){return c(this,void 0,void 0,function(){var e,t,n,r,i;return l(this,function(o){switch(o.label){case 0:if(this.isProcessing)return[2];this.isProcessing=!0,o.label=1;case 1:if(o.trys.push([1,,8,9]),0===(e=this.getQueueRaw()).length)return[2];console.log("[AInamika Error Storage] Processing ".concat(e.length," queued errors")),t=0,n=e,o.label=2;case 2:if(!(t<n.length))return[3,7];if((r=n[t]).retryCount>=this.config.maxRetries)return console.warn("[AInamika Error Storage] Max retries reached for error ".concat(r.id)),this.removeError(r.id),[3,6];if(r.lastRetry&&Date.now()-r.lastRetry<this.config.retryInterval)return[3,6];o.label=3;case 3:return o.trys.push([3,5,,6]),[4,this.sendError(r)];case 4:return o.sent()?(this.removeError(r.id),console.log("[AInamika Error Storage] Successfully sent error ".concat(r.id))):this.incrementRetryCount(r.id),[3,6];case 5:return i=o.sent(),console.error("[AInamika Error Storage] Failed to send error ".concat(r.id,":"),i),this.incrementRetryCount(r.id),[3,6];case 6:return t++,[3,2];case 7:return[3,9];case 8:return this.isProcessing=!1,[7];case 9:return[2]}})})},e.prototype.retryError=function(e){return c(this,void 0,void 0,function(){var t,n,r;return l(this,function(i){switch(i.label){case 0:if(t=this.getQueueRaw(),!(n=t.find(function(t){return t.id===e})))return[2,!1];i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.sendError(n)];case 2:return i.sent()?(this.removeError(e),[2,!0]):(this.incrementRetryCount(e),[2,!1]);case 3:return r=i.sent(),console.error("[AInamika Error Storage] Failed to retry error ".concat(e,":"),r),this.incrementRetryCount(e),[2,!1];case 4:return[2]}})})},e.prototype.addToQueue=function(e){return c(this,void 0,void 0,function(){var t,n;return l(this,function(r){if((t=this.getQueueRaw()).push(e),n=JSON.stringify(t),new Blob([n]).size>this.config.maxStorageSize)for(;t.length>0&&new Blob([JSON.stringify(t)]).size>this.config.maxStorageSize;)t.shift(),console.warn("[AInamika Error Storage] Removed old error due to size limit");return localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)),[2]})})},e.prototype.getQueueRaw=function(){try{var e=localStorage.getItem(this.STORAGE_KEY);return e?JSON.parse(e):[]}catch(e){return console.error("[AInamika Error Storage] Failed to parse stored errors:",e),[]}},e.prototype.incrementRetryCount=function(e){try{var t=this.getQueueRaw(),n=t.findIndex(function(t){return t.id===e});-1!==n&&(t[n].retryCount++,t[n].lastRetry=Date.now(),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)))}catch(e){console.error("[AInamika Error Storage] Failed to increment retry count:",e)}},e.prototype.sendError=function(e){return c(this,void 0,void 0,function(){var t,n,r,i;return l(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),t=this.config.compressionEnabled?this.decompressData(e.errorData):e.errorData,(n=this.config.endpoint||t.endpoint)?(r=t.apiKey||"",[4,fetch("".concat(n,"/api/v1/errors"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:r?"Bearer ".concat(r):""},body:JSON.stringify(t)})]):(console.error("[AInamika Error Storage] No endpoint configured for sending errors"),[2,!1]);case 1:return[2,o.sent().ok];case 2:return i=o.sent(),console.error("[AInamika Error Storage] Network error sending stored error:",i),[2,!1];case 3:return[2]}})})},e.prototype.compressData=function(e){try{var t=JSON.stringify(e);return btoa(t)}catch(t){return console.warn("[AInamika Error Storage] Compression failed, storing uncompressed:",t),e}},e.prototype.decompressData=function(e){try{if("string"==typeof e&&e.length>0){var t=atob(e);return JSON.parse(t)}return e}catch(t){return console.warn("[AInamika Error Storage] Decompression failed, returning raw data:",t),e}},e.prototype.generateErrorId=function(){return"error_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.cleanupOldErrors=function(){try{var e=this.getQueueRaw(),t=Date.now()-6048e5,n=e.filter(function(e){return e.timestamp>t});n.length!==e.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(n)),console.log("[AInamika Error Storage] Cleaned up ".concat(e.length-n.length," old errors")))}catch(e){console.error("[AInamika Error Storage] Failed to cleanup old errors:",e)}},e.prototype.startRetryTimer=function(){var e=this;this.retryTimer=window.setInterval(function(){e.processQueue()},this.config.retryInterval)},e.prototype.setupStorageListener=function(){var e=this;window.addEventListener("storage",function(t){t.key===e.STORAGE_KEY&&(console.log("[AInamika Error Storage] Storage updated from another tab"),setTimeout(function(){return e.processQueue()},1e3))}),window.addEventListener("online",function(){console.log("[AInamika Error Storage] Network back online, processing queue"),setTimeout(function(){return e.processQueue()},1e3)}),window.addEventListener("offline",function(){console.log("[AInamika Error Storage] Network offline, errors will be queued")})},e.prototype.updateMetadata=function(){try{var e=this.getStorageStats(),t=s({lastUpdate:Date.now()},e);localStorage.setItem(this.METADATA_KEY,JSON.stringify(t))}catch(e){console.error("[AInamika Error Storage] Failed to update metadata:",e)}},e.prototype.exportErrors=function(){try{var e=this.getStoredErrors(),t={timestamp:Date.now(),version:"1.0",stats:this.getStorageStats(),errors:e};return JSON.stringify(t,null,2)}catch(e){return console.error("[AInamika Error Storage] Failed to export errors:",e),"{}"}},e.prototype.importErrors=function(e){try{var t=JSON.parse(e);if(!t.errors||!Array.isArray(t.errors))throw new Error("Invalid export format");this.clearAll();for(var n=0,r=t.errors;n<r.length;n++){var i=r[n];this.storeError(i.errorData)}return console.log("[AInamika Error Storage] Imported ".concat(t.errors.length," errors")),!0}catch(e){return console.error("[AInamika Error Storage] Failed to import errors:",e),!1}},e.prototype.destroy=function(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=void 0),this.processQueue(),console.log("[AInamika Error Storage] Storage instance destroyed")},e}();!function(){function e(){}e.getAinamikaStorageUsage=function(){var e=0,t=0,n=0;for(var r in localStorage)if(localStorage.hasOwnProperty(r)){var i=new Blob([localStorage.getItem(r)||""]).size;e+=i,r.startsWith("ainamika_error")?t+=i:r.startsWith("ainamika_")&&(n+=i)}return{totalSize:e,errorSize:t,otherSize:n}},e.checkStorageSpace=function(e){try{var t="ainamika_storage_test",n="x".repeat(Math.min(e,1048576));return localStorage.setItem(t,n),localStorage.removeItem(t),!0}catch(e){return!1}},e.cleanupAllAinamikaStorage=function(){var e=[];for(var t in localStorage)t.startsWith("ainamika_")&&e.push(t);e.forEach(function(e){return localStorage.removeItem(e)}),console.log("[AInamika Storage Utils] Cleaned up ".concat(e.length," storage keys"))},e.generateStorageReport=function(){var t=new u;return{usage:e.getAinamikaStorageUsage(),errors:t.getStoredErrors(),metadata:t.getStorageStats()}}}();var h="undefined"!=typeof window&&window.__AINAMIKA_CONFIG__?window.__AINAMIKA_CONFIG__:{API_BASE_URL:"https://ainamika-webhook-proxy-366651516847.asia-south1.run.app",APP_ENV:"production",DEBUG:!1};"".concat(h.API_BASE_URL,"/api/v1/events"),"".concat(h.API_BASE_URL,"/api/errors/report"),"".concat(h.API_BASE_URL,"/api/v1/sdk/config"),"".concat(h.API_BASE_URL,"/api/v1/debug/events"),"".concat(h.API_BASE_URL,"/api/v1/projects/lookup"),"".concat(h.API_BASE_URL,"/api/v1/projects/sampling/check");var d=function(){return d=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},d.apply(this,arguments)},g=function(){function e(){this.userId=null,this.userProperties={},this.initializeUser()}return e.prototype.initializeUser=function(){this.userId=this.getOrCreateUserId()},e.prototype.getOrCreateUserId=function(){try{var e=localStorage.getItem("ainamika_user_id");return e||(e=this.generateAnonymousId(),localStorage.setItem("ainamika_user_id",e)),e}catch(e){return console.warn("[UserManager] localStorage not available, using session ID"),this.generateAnonymousId()}},e.prototype.generateAnonymousId=function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()},e.prototype.getUserId=function(){return this.userId||(this.userId=this.getOrCreateUserId()),this.userId},e.prototype.getUserProperties=function(){return d({},this.userProperties)},e.prototype.identifyUser=function(e,t){var n=this.getUserId();try{localStorage.setItem("ainamika_user_id",e),this.userId=e,t&&(this.userProperties=d(d({},this.userProperties),t)),console.log("[UserManager] User identified: ".concat(n," → ").concat(e))}catch(e){console.error("[UserManager] Error identifying user:",e)}},e.prototype.updateUserProperties=function(e){this.userProperties=d(d({},this.userProperties),e)},e.prototype.clearUser=function(){try{localStorage.removeItem("ainamika_user_id"),this.userId=null,this.userProperties={},this.initializeUser()}catch(e){console.error("[UserManager] Error clearing user:",e)}},e.prototype.getUserIdentificationEvent=function(e){return{event:"user_identified",previous_id:this.getUserId(),user_id:e,timestamp:Date.now(),properties:this.userProperties}},e.prototype.isAnonymousUser=function(){return this.getUserId().startsWith("anon_")},e.prototype.getUserType=function(){return this.isAnonymousUser()?"anonymous":"authenticated"},e}(),f=function(){return f=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},f.apply(this,arguments)},p=function(){function e(){this.userJourney=[],this.lastEventTime=0,this.sequenceIndex=0,this.maxJourneyLength=50,this.journeyAnalysisThreshold=5,this.journeyStartTime=Date.now()}return e.prototype.trackEvent=function(e,t){var n=Date.now(),r=this.lastEventTime?n-this.lastEventTime:0,i={eventName:e,timestamp:n,properties:f(f({},t),{timeSinceLastEvent:r,journeyPosition:this.sequenceIndex}),sequenceIndex:this.sequenceIndex++};this.userJourney.push(i),this.lastEventTime=n,this.userJourney.length>this.maxJourneyLength&&(this.userJourney=this.userJourney.slice(-this.maxJourneyLength)),console.log("[JourneyTracker] Event tracked: ".concat(e," (position: ").concat(i.sequenceIndex,")"))},e.prototype.getContext=function(){var e=Date.now();return{journeySequence:this.getJourneySequence(),eventCount:this.userJourney.length,lastEventTime:this.lastEventTime,journeyStartTime:this.journeyStartTime,timeSinceLastEvent:this.lastEventTime?e-this.lastEventTime:0}},e.prototype.getJourneySequence=function(){return this.userJourney.map(function(e){return e.eventName})},e.prototype.getJourneyData=function(){return function(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}([],this.userJourney,!0)},e.prototype.shouldAnalyzeJourney=function(){return this.userJourney.length>=this.journeyAnalysisThreshold&&this.userJourney.length%this.journeyAnalysisThreshold===0},e.prototype.getJourneyForAnalysis=function(){var e=Date.now()-this.journeyStartTime,t=this.calculateAverageTimeBetweenEvents();return{journey:this.userJourney.map(function(e){return{name:e.eventName,timestamp:e.timestamp,properties:e.properties}}),metadata:{journeyLength:this.userJourney.length,journeyDuration:e,avgTimeBetweenEvents:t,startTime:this.journeyStartTime,endTime:this.lastEventTime}}},e.prototype.calculateAverageTimeBetweenEvents=function(){if(this.userJourney.length<2)return 0;for(var e=0,t=1;t<this.userJourney.length;t++)e+=this.userJourney[t].timestamp-this.userJourney[t-1].timestamp;return Math.round(e/(this.userJourney.length-1))},e.prototype.findPatterns=function(){var e={};if(this.userJourney.length<3)return e;for(var t=0;t<=this.userJourney.length-3;t++){var n=this.userJourney.slice(t,t+3).map(function(e){return e.eventName}).join(" → ");e[n]=(e[n]||0)+1}return Object.fromEntries(Object.entries(e).filter(function(e){return e[0],e[1]>1}))},e.prototype.clearJourney=function(){this.userJourney=[],this.sequenceIndex=0,this.lastEventTime=0,this.journeyStartTime=Date.now()},e.prototype.getJourneySegment=function(e){return this.userJourney.slice(-e)},e.prototype.detectPotentialFunnel=function(){for(var e=this.getJourneySequence().slice(-5),t=0,n=Object.entries({signup_flow:["view_pricing","click_signup","enter_email"],purchase_flow:["view_product","add_to_cart","view_cart"],onboarding_flow:["user_signup","profile_setup","tutorial_start"]});t<n.length;t++){var r=n[t],i=r[0];if(r[1].filter(function(t){return e.includes(t)}).length>=2)return i}return null},e}(),m=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},v=function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},y=function(){function e(e,t,n){void 0===n&&(n=!1),this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.clientId=e,this.apiEndpoint=t,this.debug=n,this.loadTokens()}return e.prototype.initialize=function(){return m(this,void 0,void 0,function(){var e,t;return v(this,function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),this.isTokenValid()?(this.debugLog("Using existing valid token"),[2,!0]):this.refreshToken?[4,this.refreshAccessToken()]:[3,2];case 1:if(n.sent())return[2,!0];n.label=2;case 2:return[4,this.requestTokens()];case 3:return(e=n.sent())?(this.setTokens(e),[2,!0]):[2,!1];case 4:return t=n.sent(),this.debugLog("Authentication initialization failed:",t),[2,!1];case 5:return[2]}})})},e.prototype.requestTokens=function(){return m(this,void 0,void 0,function(){var e,t;return v(this,function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/token"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId})})];case 1:if(!(e=n.sent()).ok)throw new Error("Token request failed: ".concat(e.status));return[4,e.json()];case 2:return[2,n.sent()];case 3:return t=n.sent(),this.debugLog("Token request error:",t),[2,null];case 4:return[2]}})})},e.prototype.refreshAccessToken=function(){return m(this,void 0,void 0,function(){var e,t,n;return v(this,function(r){switch(r.label){case 0:if(!this.refreshToken)return[2,!1];r.label=1;case 1:return r.trys.push([1,4,,5]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/refresh"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:this.refreshToken})})];case 2:return(e=r.sent()).ok?[4,e.json()]:(this.clearTokens(),[2,!1]);case 3:return t=r.sent(),this.setTokens(t),[2,!0];case 4:return n=r.sent(),this.debugLog("Token refresh error:",n),[2,!1];case 5:return[2]}})})},e.prototype.getAccessToken=function(){return m(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return this.shouldRefreshToken()?[4,this.refreshAccessToken()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.isTokenValid()?[3,4]:[4,this.initialize()];case 3:if(!e.sent())return[2,null];e.label=4;case 4:return[2,this.accessToken]}})})},e.prototype.getAuthHeaders=function(){return m(this,void 0,void 0,function(){var e;return v(this,function(t){switch(t.label){case 0:return[4,this.getAccessToken()];case 1:return(e=t.sent())?[2,{Authorization:"Bearer ".concat(e)}]:[2,{"X-Client-ID":this.clientId}]}})})},e.prototype.isTokenValid=function(){return!(!this.accessToken||!this.tokenExpiry)&&Date.now()<this.tokenExpiry},e.prototype.shouldRefreshToken=function(){return!(!this.tokenExpiry||!this.refreshToken)&&Date.now()>this.tokenExpiry-3e5},e.prototype.setTokens=function(e){this.accessToken=e.access_token,this.refreshToken=e.refresh_token||this.refreshToken,this.tokenExpiry=Date.now()+1e3*e.expires_in,this.saveTokens(),this.scheduleTokenRefresh(),this.debugLog("Tokens set successfully")},e.prototype.scheduleTokenRefresh=function(){var e=this;this.refreshTimer&&clearTimeout(this.refreshTimer);var t=Math.max(0,this.tokenExpiry-Date.now()-3e5);this.refreshTimer=setTimeout(function(){e.refreshAccessToken()},t)},e.prototype.saveTokens=function(){if("undefined"!=typeof window&&window.localStorage){var t={clientId:this.clientId,accessToken:this.accessToken,refreshToken:this.refreshToken,tokenExpiry:this.tokenExpiry};localStorage.setItem(e.STORAGE_KEY,JSON.stringify(t)),this.cleanupLegacyTokens()}},e.prototype.cleanupLegacyTokens=function(){var t=this;if("undefined"!=typeof window&&window.localStorage){for(var n=[],r=0;r<localStorage.length;r++){var i=localStorage.key(r);i&&i.startsWith("ainamika_auth_")&&i!==e.STORAGE_KEY&&n.push(i)}n.forEach(function(e){localStorage.removeItem(e),t.debugLog("Removed legacy token key:",e)})}},e.prototype.loadTokens=function(){if("undefined"!=typeof window&&window.localStorage){this.cleanupLegacyTokens();var t=localStorage.getItem(e.STORAGE_KEY);if(t)try{var n=JSON.parse(t);if(n.clientId&&n.clientId!==this.clientId)return this.debugLog("Stored token is for different clientId, clearing"),void localStorage.removeItem(e.STORAGE_KEY);this.accessToken=n.accessToken,this.refreshToken=n.refreshToken,this.tokenExpiry=n.tokenExpiry,this.isTokenValid()&&this.scheduleTokenRefresh()}catch(e){this.debugLog("Failed to load stored tokens:",e)}}},e.prototype.clearTokens=function(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,"undefined"!=typeof window&&window.localStorage&&(localStorage.removeItem(e.STORAGE_KEY),this.cleanupLegacyTokens()),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},e.prototype.logout=function(){return m(this,void 0,void 0,function(){var e;return v(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,4,5]),this.accessToken?[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/logout"),{method:"POST",headers:{Authorization:"Bearer ".concat(this.accessToken)}})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[3,5];case 3:return e=t.sent(),this.debugLog("Logout error:",e),[3,5];case 4:return this.clearTokens(),[7];case 5:return[2]}})})},e.prototype.debugLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.debug&&console.log.apply(console,function(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}(["[Ainamika Auth]"],e,!1))},e.STORAGE_KEY="ainamika_auth_token",e}(),k=function(){return k=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},k.apply(this,arguments)},w=function(){function e(e,t){this.performanceMetrics={},this.scrollDepthReached=new Set,this.clickHistory=[],this.isPageVisible=!0,this.visibilityChangeCount=0,this.config=k({trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100],rageClickThreshold:3,rageClickWindow:1e3,apiTrackingPatterns:[]},e),this.onEvent=t,this.pageStartTime=Date.now(),this.lastActivityTime=Date.now(),this.originalFetch=window.fetch.bind(window),this.originalXHR=XMLHttpRequest.prototype.open,this.engagementMetrics={timeOnPage:0,scrollDepth:0,scrollDepthMilestones:[],rageClicks:0,totalClicks:0,activeTime:0,idleTime:0,pageVisibilityChanges:0},this.initialize()}return e.prototype.initialize=function(){var e=this;this.config.trackPerformance&&this.initPerformanceTracking(),this.config.trackEngagement&&this.initEngagementTracking(),this.config.trackScrollDepth&&this.initScrollTracking(),this.config.trackRageClicks&&this.initRageClickTracking(),this.config.trackTimeOnPage&&this.initTimeTracking(),this.config.trackAPIResponses&&this.initAPITracking(),window.addEventListener("beforeunload",function(){e.trackPageExit()}),console.log("[AInamika Advanced Tracker] Initialized")},e.prototype.initPerformanceTracking=function(){var e=this;if("PerformanceObserver"in window){try{new PerformanceObserver(function(t){var n,r=t.getEntries(),i=r[r.length-1];e.performanceMetrics.lcp=i.startTime,e.onEvent("performance_lcp",{value:i.startTime,element:null===(n=i.element)||void 0===n?void 0:n.tagName})}).observe({type:"largest-contentful-paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] LCP not supported")}try{new PerformanceObserver(function(t){var n=t.getEntries()[0];e.performanceMetrics.fid=n.processingStart-n.startTime,e.onEvent("performance_fid",{value:e.performanceMetrics.fid,eventType:n.name})}).observe({type:"first-input",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FID not supported")}try{var t=0;new PerformanceObserver(function(n){for(var r=0,i=n.getEntries();r<i.length;r++){var o=i[r];o.hadRecentInput||(t+=o.value)}e.performanceMetrics.cls=t}).observe({type:"layout-shift",buffered:!0}),document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.onEvent("performance_cls",{value:t})})}catch(e){console.debug("[Advanced Tracker] CLS not supported")}try{new PerformanceObserver(function(t){var n=t.getEntries().find(function(e){return"first-contentful-paint"===e.name});n&&(e.performanceMetrics.fcp=n.startTime,e.onEvent("performance_fcp",{value:n.startTime}))}).observe({type:"paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FCP not supported")}}window.addEventListener("load",function(){setTimeout(function(){var t=performance.timing;e.performanceMetrics.ttfb=t.responseStart-t.navigationStart,e.performanceMetrics.domContentLoaded=t.domContentLoadedEventEnd-t.navigationStart,e.performanceMetrics.pageLoad=t.loadEventEnd-t.navigationStart;var n=performance.getEntriesByType("resource");e.performanceMetrics.resourceCount=n.length,e.performanceMetrics.transferSize=n.reduce(function(e,t){return e+(t.transferSize||0)},0),e.onEvent("performance_page_load",{ttfb:e.performanceMetrics.ttfb,domContentLoaded:e.performanceMetrics.domContentLoaded,pageLoad:e.performanceMetrics.pageLoad,resourceCount:e.performanceMetrics.resourceCount,transferSizeKB:Math.round((e.performanceMetrics.transferSize||0)/1024)})},0)})},e.prototype.initEngagementTracking=function(){var e=this;document.addEventListener("visibilitychange",function(){e.isPageVisible="visible"===document.visibilityState,e.visibilityChangeCount++,e.engagementMetrics.pageVisibilityChanges=e.visibilityChangeCount,e.isPageVisible?e.lastActivityTime=Date.now():e.updateActiveTime()}),["mousemove","keydown","touchstart","scroll"].forEach(function(t){document.addEventListener(t,function(){e.lastActivityTime=Date.now()},{passive:!0})}),document.addEventListener("click",function(){e.engagementMetrics.totalClicks++})},e.prototype.initScrollTracking=function(){var e=this,t=!1,n=function(){var n=window.scrollY||document.documentElement.scrollTop,r=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-window.innerHeight,i=r>0?Math.round(n/r*100):0;e.engagementMetrics.scrollDepth=Math.max(e.engagementMetrics.scrollDepth,i);for(var o=0,a=e.config.scrollDepthThresholds;o<a.length;o++){var s=a[o];i>=s&&!e.scrollDepthReached.has(s)&&(e.scrollDepthReached.add(s),e.engagementMetrics.scrollDepthMilestones.push(s),e.onEvent("engagement_scroll_depth",{depth:s,maxDepth:e.engagementMetrics.scrollDepth,timeToReach:Date.now()-e.pageStartTime}))}t=!1};window.addEventListener("scroll",function(){t||(requestAnimationFrame(n),t=!0)},{passive:!0})},e.prototype.initRageClickTracking=function(){var e=this;document.addEventListener("click",function(t){var n,r=Date.now();if(e.clickHistory.push(r),e.clickHistory=e.clickHistory.filter(function(t){return r-t<e.config.rageClickWindow}),e.clickHistory.length>=e.config.rageClickThreshold){e.engagementMetrics.rageClicks++;var i=t.target;e.onEvent("engagement_rage_click",{clickCount:e.clickHistory.length,element:{tagName:i.tagName,id:i.id,className:i.className,textContent:null===(n=i.textContent)||void 0===n?void 0:n.substring(0,50)},position:{x:t.clientX,y:t.clientY},totalRageClicks:e.engagementMetrics.rageClicks}),e.clickHistory=[]}})},e.prototype.initTimeTracking=function(){var e=this;setInterval(function(){e.updateActiveTime()},3e4)},e.prototype.updateActiveTime=function(){var e=Date.now(),t=e-this.lastActivityTime;this.engagementMetrics.timeOnPage=e-this.pageStartTime,t<3e4?this.engagementMetrics.activeTime+=Math.min(t,3e4):this.engagementMetrics.idleTime+=t},e.prototype.initAPITracking=function(){var e=this;window.fetch=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return r=e,i=void 0,a=function(){var e,n,r,i,o,a,s;return function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}(this,function(c){switch(c.label){case 0:if(e=Date.now(),n=t[0]instanceof Request?t[0].url:String(t[0]),r=(null===(s=t[1])||void 0===s?void 0:s.method)||"GET",!this.shouldTrackAPI(n))return[2,this.originalFetch.apply(this,t)];c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this.originalFetch.apply(this,t)];case 2:return i=c.sent(),a=Date.now()-e,this.trackAPICall({url:n,method:r,status:i.status,duration:a,success:i.ok,timestamp:Date.now()}),[2,i];case 3:throw o=c.sent(),a=Date.now()-e,this.trackAPICall({url:n,method:r,status:0,duration:a,success:!1,error:(null==o?void 0:o.message)||"Network error",timestamp:Date.now()}),o;case 4:return[2]}})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{c(a.next(e))}catch(e){t(e)}}function s(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o(function(e){e(r)})).then(n,s)}c((a=a.apply(r,i||[])).next())});var r,i,o,a},console.log("[Advanced Tracker] API tracking initialized")},e.prototype.shouldTrackAPI=function(e){return!this.config.apiTrackingPatterns||0===this.config.apiTrackingPatterns.length||this.config.apiTrackingPatterns.some(function(t){try{return new RegExp(t).test(e)}catch(n){return e.includes(t)}})},e.prototype.trackAPICall=function(e){this.onEvent("api_call",{url:e.url,method:e.method,status:e.status,duration:e.duration,success:e.success,error:e.error})},e.prototype.trackAPI=function(e,t,n,r){this.onEvent("api_response_tracked",k({endpoint:e,method:t,responseType:typeof n,responseKeys:n&&"object"==typeof n?Object.keys(n):[],hasData:!!n,dataCount:Array.isArray(n)?n.length:void 0},r))},e.prototype.trackEngagement=function(e,t){this.onEvent("engagement_".concat(e),k(k({},t),{timeOnPage:Date.now()-this.pageStartTime,scrollDepth:this.engagementMetrics.scrollDepth}))},e.prototype.trackConversion=function(e,t,n){this.onEvent("conversion",k(k({goal:e,value:t},n),{timeToConvert:Date.now()-this.pageStartTime,scrollDepthAtConversion:this.engagementMetrics.scrollDepth,clicksBeforeConversion:this.engagementMetrics.totalClicks}))},e.prototype.getPerformanceMetrics=function(){return k({},this.performanceMetrics)},e.prototype.getEngagementMetrics=function(){return this.updateActiveTime(),k(k({},this.engagementMetrics),{timeOnPage:Date.now()-this.pageStartTime})},e.prototype.trackPageExit=function(){this.updateActiveTime(),this.onEvent("page_exit",{timeOnPage:Date.now()-this.pageStartTime,activeTime:this.engagementMetrics.activeTime,idleTime:this.engagementMetrics.idleTime,scrollDepth:this.engagementMetrics.scrollDepth,scrollMilestones:this.engagementMetrics.scrollDepthMilestones,totalClicks:this.engagementMetrics.totalClicks,rageClicks:this.engagementMetrics.rageClicks,visibilityChanges:this.engagementMetrics.pageVisibilityChanges,performance:this.performanceMetrics})},e}(),b=function(){return b=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},b.apply(this,arguments)},S=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((r=r.apply(e,t||[])).next())})},T=function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},_=function(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))},E=function(){function e(e){if(this.eventQueue=[],this.isInitialized=!1,this.batchRetryCount=0,this.maxBatchRetries=5,this.lastDomHash="",this.lastConfigHash="",this.mutationDebounceTimer=null,this.mutationDebounceMs=2e3,this.attachedListeners=new WeakMap,this.knownElementSelectors=new Set,this.handledClicks=new Map,this.CLICK_DEDUP_WINDOW_MS=50,this.viewedElements=new Set,this.viewObservers=new Map,this.mergedConfig={events_to_track:[]},this.MAX_CACHED_CONFIGS=15,!e.projectKey&&!e.clientId&&!e.apiKey)throw new Error("[AInamika SDK] Either projectKey or clientId is required for initialization");this.config=b({endpoint:h.API_BASE_URL,batchInterval:5e3,useWebWorker:!0,debug:h.DEBUG,errorTracking:{enabled:!0,captureScreenshots:!0,captureDomSnapshots:!0,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},advancedTracking:{enabled:!0,trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100]}},e),this.sessionId=this.generateSessionId(),this.userIdentifier=this.getOrCreateUserIdentifier(),this.userManager=new g,this.journeyTracker=new p,this.authManager=new y(this.config.clientId||this.config.apiKey||"",this.config.endpoint,this.config.debug);var t=new Blob(["\n self.eventQueue = [];\n self.config = {\n apiUrl: '',\n batchSize: 10,\n batchInterval: 5000,\n headers: { 'Content-Type': 'application/json' }\n };\n let batchTimer = null;\n function flushQueue() {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] flushQueue called', eventQueue: self.eventQueue, config: self.config });\n if (self.eventQueue.length === 0) return;\n const batch = self.eventQueue.splice(0, self.config.batchSize);\n fetch(self.config.apiUrl, {\n method: 'POST',\n headers: self.config.headers,\n body: JSON.stringify({ events: batch })\n }).then(r => {\n if (r.ok) {\n self.postMessage({ status: 'success' });\n } else {\n self.postMessage({ status: 'error', error: r.statusText, failedEvents: batch });\n }\n }).catch(e => {\n self.postMessage({ status: 'error', error: e.message, failedEvents: batch });\n });\n }\n self.onmessage = function(e) {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] onmessage', data: e.data });\n if (e.data.type === 'config') {\n self.config = { ...self.config, ...e.data.payload };\n if (batchTimer) clearInterval(batchTimer);\n batchTimer = setInterval(flushQueue, self.config.batchInterval);\n self.postMessage({ status: 'debug', message: '[AInamika Worker] config set', config: self.config });\n } else if (e.data.type === 'track') {\n self.eventQueue.push(e.data.payload);\n // Only send when timer triggers, not when batch size is reached\n // This ensures true batching behavior\n } else if (e.data.type === 'batch') {\n // Handle batch flush from main thread\n self.postMessage({ status: 'debug', message: '[AInamika Worker] Received batch from main thread', events: e.data.events });\n self.eventQueue.push(...e.data.events);\n flushQueue();\n } else if (e.data.type === 'initConfig') {\n // No-op for now, can be used for advanced config\n }\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(t);this.worker=new Worker(n),this.initialize()}return e.prototype.initialize=function(){return S(this,void 0,void 0,function(){var e,t,n,r,i;return T(this,function(o){switch(o.label){case 0:if(this.isInitialized)return[2];if(this.isInitialized=!0,!this.config.projectKey)return[3,5];o.label=1;case 1:return o.trys.push([1,4,,5]),[4,this.initializeProjectSettings()];case 2:return o.sent(),[4,this.initializeSamplingDecision()];case 3:return o.sent(),this.log("Project-based initialization complete",{projectKey:this.config.projectKey,projectSettings:this.projectSettings,samplingDecision:this.samplingDecision}),[3,5];case 4:return e=o.sent(),this.log("Project initialization failed:",e),console.warn("[AInamika SDK] Failed to initialize project settings. Some features may be limited."),[3,5];case 5:if(!this.config.clientId&&!this.config.apiKey)return[3,9];o.label=6;case 6:return o.trys.push([6,8,,9]),[4,this.authManager.initialize()];case 7:return o.sent(),this.log("Authentication initialized"),[3,9];case 8:return t=o.sent(),this.log("Authentication initialization failed:",t),this.config.debug||console.warn("[Ainamika] Running without authentication. Some features may be limited."),[3,9];case 9:return(null===(n=this.config.errorTracking)||void 0===n?void 0:n.enabled)&&this.shouldSampleErrors()?this.initializeErrorTracking():(null===(r=this.config.errorTracking)||void 0===r?void 0:r.enabled)&&!this.shouldSampleErrors()&&this.log("Error tracking disabled due to sampling decision"),(null===(i=this.config.advancedTracking)||void 0===i?void 0:i.enabled)&&this.initializeAdvancedTracking(),this.config.autoConfig?[4,this.setupAutoConfiguration()]:[3,11];case 10:o.sent(),this.setupDynamicDomTracking(),o.label=11;case 11:return this.config.useWebWorker&&"undefined"!=typeof Worker?[4,this.setupWebWorker()]:[3,13];case 12:return o.sent(),[3,14];case 13:this.startBatchTimer(),o.label=14;case 14:return this.log("AnalyticsPro SDK initialized",{config:this.config,projectKey:this.config.projectKey,sampling:this.samplingDecision}),[2]}})})},e.prototype.getOrCreateUserIdentifier=function(){var e="ainamika_user_identifier",t=localStorage.getItem(e);return t||(t="anon_"+Math.random().toString(36).substr(2,16)+Date.now().toString(36),localStorage.setItem(e,t),this.log("Created new user identifier:",t)),t},e.prototype.initializeProjectSettings=function(){return S(this,void 0,void 0,function(){var e,t,n;return T(this,function(r){switch(r.label){case 0:if(!this.config.projectKey)return[2];r.label=1;case 1:return r.trys.push([1,4,,5]),[4,fetch("".concat(this.config.endpoint,"/api/v1/projects/lookup"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey})})];case 2:if(!(e=r.sent()).ok)throw new Error("Project lookup failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.projectSettings=r.sent(),this.log("Project settings loaded:",this.projectSettings),[3,5];case 4:throw n=r.sent(),this.log("Failed to load project settings:",n),n;case 5:return[2]}})})},e.prototype.initializeSamplingDecision=function(){return S(this,void 0,void 0,function(){var e,t,n;return T(this,function(r){switch(r.label){case 0:if(!this.config.projectKey)return[2];r.label=1;case 1:return r.trys.push([1,4,,5]),[4,fetch("".concat(this.config.endpoint,"/api/v1/projects/sampling/check"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey,user_identifier:this.userIdentifier})})];case 2:if(!(e=r.sent()).ok)throw new Error("Sampling check failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.samplingDecision=r.sent(),this.log("Sampling decision received:",this.samplingDecision),this.cacheSamplingDecision(),[3,5];case 4:return n=r.sent(),this.log("Failed to get sampling decision, using cached or defaults:",n),this.loadCachedSamplingDecision(),[3,5];case 5:return[2]}})})},e.prototype.cacheSamplingDecision=function(){if(this.samplingDecision){var t=b({projectKey:this.config.projectKey},this.samplingDecision);localStorage.setItem(e.SAMPLING_STORAGE_KEY,JSON.stringify(t)),this.cleanupLegacySamplingKeys()}},e.prototype.loadCachedSamplingDecision=function(){this.cleanupLegacySamplingKeys();var t=localStorage.getItem(e.SAMPLING_STORAGE_KEY);if(t)try{var n=JSON.parse(t);if(n.projectKey&&n.projectKey!==this.config.projectKey)return this.log("Cached sampling is for different projectKey, clearing"),localStorage.removeItem(e.SAMPLING_STORAGE_KEY),void(this.samplingDecision=this.getDefaultSamplingDecision());n.projectKey;var r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(n,["projectKey"]);this.samplingDecision=r,this.log("Loaded cached sampling decision:",this.samplingDecision)}catch(e){this.samplingDecision=this.getDefaultSamplingDecision()}else this.samplingDecision=this.getDefaultSamplingDecision()},e.prototype.getDefaultSamplingDecision=function(){return{should_sample:{events:!0,errors:!0,session_replay:!1},rates:{events:100,errors:100,session_replay:0},decision:"existing"}},e.prototype.cleanupLegacySamplingKeys=function(){var t=this;if("undefined"!=typeof window&&window.localStorage){for(var n=[],r=0;r<localStorage.length;r++){var i=localStorage.key(r);i&&i.startsWith("ainamika_sampling_")&&i!==e.SAMPLING_STORAGE_KEY&&n.push(i)}n.forEach(function(e){localStorage.removeItem(e),t.log("Removed legacy sampling key:",e)})}},e.prototype.shouldSampleEvents=function(){return!this.samplingDecision||this.samplingDecision.should_sample.events},e.prototype.shouldSampleErrors=function(){return!this.samplingDecision||this.samplingDecision.should_sample.errors},e.prototype.shouldSampleSessionReplay=function(){return!!this.samplingDecision&&this.samplingDecision.should_sample.session_replay},e.prototype.getSamplingStatus=function(){return this.samplingDecision||null},e.prototype.getProjectInfo=function(){return this.projectSettings||null},e.prototype.getTrackingStatus=function(){return{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size,mergedConfig:this.mergedConfig}},e.prototype.resetDomTracking=function(){this.knownElementSelectors.clear(),this.mergedConfig={events_to_track:[]},this.lastDomHash="",this.attachedListeners=new WeakMap,this.log("DOM tracking reset - will re-analyze on next mutation")},e.prototype.clearAllCaches=function(t){void 0===t&&(t=!1);try{localStorage.removeItem("ainamika_dom_config_cache"),this.log("Cleared DOM config cache"),localStorage.removeItem("ainamika_last_known_config"),this.log("Cleared last-known config cache"),localStorage.removeItem(e.SAMPLING_STORAGE_KEY),this.cleanupLegacySamplingKeys(),this.log("Cleared sampling decision cache"),t&&(localStorage.removeItem("ainamika_user_identifier"),this.log("Cleared user identifier")),this.resetDomTracking(),this.samplingDecision=void 0,this.log("All caches cleared successfully")}catch(e){console.error("[AInamika SDK] Error clearing caches:",e)}},e.prototype.getCacheStats=function(){try{var t=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),n=Object.keys(t);return{domConfigCacheSize:n.length,cachedDomHashes:n,hasSamplingCache:!!localStorage.getItem(e.SAMPLING_STORAGE_KEY),hasUserIdentifier:!!localStorage.getItem("ainamika_user_identifier"),hasLastKnownConfig:!!localStorage.getItem("ainamika_last_known_config")}}catch(e){return{domConfigCacheSize:0,cachedDomHashes:[],hasSamplingCache:!1,hasUserIdentifier:!1,hasLastKnownConfig:!1}}},e.prototype.initializeErrorTracking=function(){var e,t,n,r,i,o,s,c,l,h,d,g,f,p;try{this.errorStorage=new u({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1,endpoint:this.config.endpoint});var m={endpoint:this.config.endpoint,clientId:this.config.clientId||"",apiKey:this.config.apiKey,authManager:this.authManager,projectKey:this.config.projectKey,captureScreenshots:null===(t=null===(e=this.config.errorTracking)||void 0===e?void 0:e.captureScreenshots)||void 0===t||t,captureDomSnapshots:null===(r=null===(n=this.config.errorTracking)||void 0===n?void 0:n.captureDomSnapshots)||void 0===r||r,maxStackTraceDepth:null!==(o=null===(i=this.config.errorTracking)||void 0===i?void 0:i.maxStackTraceDepth)&&void 0!==o?o:50,maxErrorsPerSession:null!==(c=null===(s=this.config.errorTracking)||void 0===s?void 0:s.maxErrorsPerSession)&&void 0!==c?c:100,debounceMs:null!==(h=null===(l=this.config.errorTracking)||void 0===l?void 0:l.debounceMs)&&void 0!==h?h:1e3,enableNetworkTracking:null===(g=null===(d=this.config.errorTracking)||void 0===d?void 0:d.enableNetworkTracking)||void 0===g||g,enableConsoleCapture:null===(p=null===(f=this.config.errorTracking)||void 0===f?void 0:f.enableConsoleCapture)||void 0===p||p};this.errorTracker=new a(m);var v=this.getUserId();v&&this.errorTracker&&this.errorTracker.setUser(v),this.log("Error tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize error tracking:",e)}},e.prototype.captureException=function(e,t){this.errorTracker&&this.errorTracker.captureException(e,t)},e.prototype.setUser=function(e){console.warn("[AInamika SDK] setUser is deprecated. Please use identifyUser() instead."),this.identifyUser(e)},e.prototype.flushStoredErrors=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return this.errorStorage?[4,this.errorStorage.processQueue()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.errorTracker?[4,this.errorTracker.flushStoredErrors()]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}})})},e.prototype.initializeAdvancedTracking=function(){var e,t,n,r,i,o,a,s,c,l,u,h,d,g,f=this;try{var p={trackPerformance:null===(t=null===(e=this.config.advancedTracking)||void 0===e?void 0:e.trackPerformance)||void 0===t||t,trackEngagement:null===(r=null===(n=this.config.advancedTracking)||void 0===n?void 0:n.trackEngagement)||void 0===r||r,trackScrollDepth:null===(o=null===(i=this.config.advancedTracking)||void 0===i?void 0:i.trackScrollDepth)||void 0===o||o,trackRageClicks:null===(s=null===(a=this.config.advancedTracking)||void 0===a?void 0:a.trackRageClicks)||void 0===s||s,trackTimeOnPage:null===(l=null===(c=this.config.advancedTracking)||void 0===c?void 0:c.trackTimeOnPage)||void 0===l||l,trackAPIResponses:null!==(h=null===(u=this.config.advancedTracking)||void 0===u?void 0:u.trackAPIResponses)&&void 0!==h&&h,scrollDepthThresholds:(null===(d=this.config.advancedTracking)||void 0===d?void 0:d.scrollDepthThresholds)||[25,50,75,90,100],apiTrackingPatterns:(null===(g=this.config.advancedTracking)||void 0===g?void 0:g.apiTrackingPatterns)||[]};this.advancedTracker=new w(p,function(e,t){f.sendToWorker(e,t)}),this.log("Advanced tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize advanced tracking:",e)}},e.prototype.trackAPI=function(e,t,n,r){this.advancedTracker?this.advancedTracker.trackAPI(e,t,n,r):this.track("api_response_tracked",b({endpoint:e,method:t,responseType:typeof n,hasData:!!n},r))},e.prototype.trackEngagement=function(e,t){this.advancedTracker?this.advancedTracker.trackEngagement(e,t):this.track("engagement_".concat(e),t||{})},e.prototype.trackConversion=function(e,t,n){this.advancedTracker?this.advancedTracker.trackConversion(e,t,n):this.track("conversion",b({goal:e,value:t},n))},e.prototype.getPerformanceMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getPerformanceMetrics())||null},e.prototype.getEngagementMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getEngagementMetrics())||null},e.prototype.setupAutoConfiguration=function(){return S(this,void 0,void 0,function(){var e,t;return T(this,function(n){try{this.log("Starting auto-configuration..."),e=!1,(t=this.getLastKnownConfig())&&t.events_to_track&&t.events_to_track.length>0&&(this.log("Applying last-known config IMMEDIATELY (zero delay)",{eventsCount:t.events_to_track.length}),this.mergedConfig={events_to_track:_([],t.events_to_track,!0),tracking_config:t.tracking_config},this.applyGeneratedConfig(t),e=!0,this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:t})),this.setupAutoConfigurationBackground(e)}catch(e){this.log("Auto-configuration failed with error",e)}return[2]})})},e.prototype.setupAutoConfigurationBackground=function(e){return S(this,void 0,void 0,function(){var t,n,r,i,o,a,s=this;return T(this,function(c){switch(c.label){case 0:return c.trys.push([0,5,,6]),[4,this.getDOMStructure()];case 1:return t=c.sent(),n=this.computeDomHash(t),this.lastDomHash=n,(t.elements||[]).forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Tracking ".concat(this.knownElementSelectors.size," initial element selectors")),r=this.getCachedConfigForDomHash(n),i=e,e?[3,4]:r&&r.events_to_track?(this.log("Applying cached config for DOM hash:",n),this.mergedConfig={events_to_track:_([],r.events_to_track,!0),tracking_config:r.tracking_config},this.applyGeneratedConfig(r),i=!0,this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:r}),[3,4]):[3,2];case 2:return[4,this.loadConfigFromFile()];case 3:(o=c.sent())&&o.events_to_track&&(this.log("Applying config from file"),this.mergedConfig={events_to_track:_([],o.events_to_track,!0),tracking_config:o.tracking_config},this.applyGeneratedConfig(o),i=!0),c.label=4;case 4:return this.fetchAndMergeFreshConfig(t,n,i),[3,6];case 5:return a=c.sent(),this.log("Background auto-configuration failed:",a),[3,6];case 6:return[2]}})})},e.prototype.fetchAndMergeFreshConfig=function(e,t,n){return S(this,void 0,void 0,function(){var r,i,o,a,s;return T(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),this.log("Fetching fresh config from backend (background)..."),[4,this.fetchGeneratedConfig(e,t)];case 1:return(r=c.sent())&&r.events_to_track?(n?(i=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),(o=r.events_to_track.filter(function(e){return!i.has(e.element_selector)})).length>0?(this.log("Found ".concat(o.length," new events from fresh config, merging...")),(s=this.mergedConfig.events_to_track).push.apply(s,o),this.applyGeneratedConfig({events_to_track:o,tracking_config:r.tracking_config})):this.log("Fresh config has no new events, cache was up-to-date"),r.tracking_config&&(this.mergedConfig.tracking_config=b(b({},this.mergedConfig.tracking_config),r.tracking_config))):(this.mergedConfig={events_to_track:_([],r.events_to_track,!0),tracking_config:r.tracking_config},this.applyGeneratedConfig(r),this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:r})),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=r.config_hash||"",this.setLastKnownConfig(this.mergedConfig),this.log("Fresh config processed successfully",{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size}),[3,3]):(this.log("No valid config returned from API"),[2]);case 2:return a=c.sent(),this.log("Background config fetch failed:",a),[3,3];case 3:return[2]}})})},e.prototype.getDOMStructure=function(){return S(this,void 0,void 0,function(){var e,t,n,r,i,o=this;return T(this,function(a){switch(a.label){case 0:return e=function(e){if(e.id){if(/[\s!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/.test(e.id)){var t=e.id.includes('"')?e.id.replace(/"/g,'\\"'):e.id;return'[id="'.concat(t,'"]')}return"#".concat(e.id)}if(e.className&&"string"==typeof e.className){var n=e.className.split(" ").filter(function(e){return e.trim()}).join(".");return n?".".concat(n):e.tagName.toLowerCase()}return e.tagName.toLowerCase()},[4,new Promise(function(e){return setTimeout(e,500)})];case 1:return a.sent(),t=Array.from(document.body.querySelectorAll('\n button, a, input, select, textarea, form, img, h1, h2, h3, h4, h5, h6,\n [role=button], [role=link], [onclick], [tabindex], [data-analytics], [data-track],\n .card, .btn, .btn-primary, .btn-secondary, .card-title, .card-description, .card-price, .card-actions,\n [id*="card"], [class*="card"], [class*="btn"], [class*="price"], [class*="title"],\n div, span, p\n ')),n=t.filter(function(e){var t=window.getComputedStyle(e),n="none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity,r="button"===e.tagName.toLowerCase()||"a"===e.tagName.toLowerCase()||e.hasAttribute("onclick")||"button"===e.getAttribute("role")||e.classList.contains("btn")||e.classList.contains("card"),i="cardsContainer"===e.id||e.classList.contains("cards-grid")||e.classList.contains("card")||"img"===e.tagName.toLowerCase()||-1!==["h1","h2","h3"].indexOf(e.tagName.toLowerCase());return n&&(r||i)||"cardsContainer"===e.id}),r=new Set,i=n.map(function(t){var n,r,i={};Array.from(t.attributes).forEach(function(e){-1===["style","data-timestamp","data-rendered"].indexOf(e.name)&&(i[e.name]=e.value.length>25?e.value.substring(0,25):e.value)});var a=o.generateElementFingerprint(t);return{tagName:t.tagName.toLowerCase(),selector:e(t),fingerprint:a,id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().substring(0,100),attributes:i,isInteractive:"button"===t.tagName.toLowerCase()||"a"===t.tagName.toLowerCase()||t.hasAttribute("onclick")||"button"===t.getAttribute("role")||t.classList.contains("btn"),hasChildren:t.children.length>0,childCount:t.children.length,parentTagName:(null===(n=t.parentElement)||void 0===n?void 0:n.tagName.toLowerCase())||"",index:Array.from((null===(r=t.parentElement)||void 0===r?void 0:r.children)||[]).indexOf(t)}}).filter(function(e){return!r.has(e.fingerprint)&&(r.add(e.fingerprint),!0)}),this.log("DOM structure analyzed",{elementCount:i.length,elements:i}),[2,{elements:i}]}})})},e.prototype.fetchGeneratedConfig=function(e,t){return S(this,void 0,void 0,function(){var n,r,i,o,a;return T(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),e&&e.elements&&0===e.elements.length?(this.log("No elements found in DOM structure, skipping config fetch."),[2,null]):(n={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()]);case 1:return r=s.sent(),n=b(b({},n),r),i={structure:e},t&&(i.domHash=t,i.lastConfigHash=this.lastConfigHash),[4,fetch("".concat(this.config.endpoint,"/api/v1/sdk/config"),{method:"POST",headers:n,body:JSON.stringify(i)})];case 2:if(!(o=s.sent()).ok)throw new Error("Backend returned ".concat(o.status));return[4,o.json()];case 3:return[2,s.sent()];case 4:return a=s.sent(),this.log("Error fetching generated config:",a),[2,null];case 5:return[2]}})})},e.prototype.transformEventNameForType=function(e,t){if(!e||!t)return e;var n={view:{_clicked:"_viewed",_click:"_view"},focus:{_clicked:"_focused",_click:"_focus"},blur:{_clicked:"_blurred",_click:"_blur"}}[t];if(!n)return e;for(var r=0,i=Object.entries(n);r<i.length;r++){var o=i[r],a=o[0],s=o[1];if(e.endsWith(a))return e.slice(0,-a.length)+s}return"view"!==t||e.endsWith("_viewed")||e.endsWith("_view")?e:e+"_viewed"},e.prototype.sanitizeSelector=function(e){if(!e)return e;if(e.startsWith("#")&&!e.startsWith("[")){var t=e.substring(1);if(/[\s!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/.test(t)){var n=t.includes('"')?t.replace(/"/g,'\\"'):t;return'[id="'.concat(n,'"]')}}return e},e.prototype.applyGeneratedConfig=function(e){var t=this;e.tracking_config&&this.log("Applying tracking config:",e.tracking_config),e.events_to_track.forEach(function(e){var n=t.sanitizeSelector(e.element_selector);try{var r=document.querySelectorAll(n),i=e.metadata_rules||{extract_customdata:!0,extract_text:!0};r.length>0?r.forEach(function(n){var o=t.attachedListeners.get(n);o||(o=new Set,t.attachedListeners.set(n,o)),(Array.isArray(e.event_type)?e.event_type:[e.event_type]).forEach(function(a){if(!o.has(a)){if(o.add(a),"click"===a&&(n.addEventListener("click",function(n){var r,o=Date.now(),a="interactive_element_clicked"===e.event_name,s=["div","span","p","section","article","header","footer","main","aside","nav","ul","ol","li","table","tr","td","th","tbody","thead","figure","figcaption","blockquote","pre","code","label","fieldset","legend","details","summary"].includes(null===(r=e.element_selector)||void 0===r?void 0:r.toLowerCase());if(a||s)for(var c=Array.from(t.handledClicks.entries()),l=0;l<c.length;l++){var u=c[l][0];if(Math.abs(o-u)<=t.CLICK_DEDUP_WINDOW_MS)return void t.log('Skipping generic event "'.concat(e.event_name,'" - specific event already sent'))}var h=n.target,d=t.extractElementData(h,i);if(!a&&!s){t.handledClicks.set(o,new Set([e.event_name]));var g=o-1e3,f=Array.from(t.handledClicks.keys());for(l=0;l<f.length;l++)f[l]<g&&t.handledClicks.delete(f[l])}t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"click",category:e.category||"uncategorized",element:d,itemName:d.itemName,section:d.section,timestamp:(new Date).toISOString()})}),t.log('Attached click listener for "'.concat(e.event_name,'" on "').concat(e.element_selector,'" (category: ').concat(e.category||"uncategorized",")"))),"view"===a&&"IntersectionObserver"in window){var s=Array.from(r).indexOf(n),c=n.id||n.getAttribute("data-id")||"",l="".concat(e.element_selector,"::").concat(s,"::").concat(c);if(t.viewedElements.has(l))return void t.log('Skipping already viewed element: "'.concat(l,'"'));var u=new IntersectionObserver(function(n){n.forEach(function(n){if(n.isIntersecting&&n.intersectionRatio>=.5){var r=n.target;if(t.viewedElements.has(l))return;t.viewedElements.add(l);var o=t.extractElementData(r,i),a=t.transformEventNameForType(e.event_name,"view");t.sendToWorker(a,{selector:e.element_selector,eventType:"view",category:e.category||"uncategorized",element:o,itemName:o.itemName,section:o.section,intersectionRatio:n.intersectionRatio,timestamp:(new Date).toISOString()}),u.unobserve(r),t.log('View event sent and unobserved: "'.concat(a,'" for "').concat(l,'"'))}})},{threshold:.5});u.observe(n),t.viewObservers.set(l,u),t.log('Attached IntersectionObserver for "'.concat(e.event_name,'" (as "').concat(t.transformEventNameForType(e.event_name,"view"),'") on "').concat(e.element_selector,'"'))}"focus"!==a&&"blur"!==a||(n.addEventListener(a,function(){var r=n,o=t.extractElementData(r,i),s=t.transformEventNameForType(e.event_name,a);t.sendToWorker(s,{selector:e.element_selector,eventType:a,category:e.category||"uncategorized",element:o,timestamp:(new Date).toISOString()})}),t.log("Attached ".concat(a,' listener for "').concat(e.event_name,'" (as "').concat(t.transformEventNameForType(e.event_name,a),'") on "').concat(e.element_selector,'"')))}})}):t.log('No elements found for selector: "'.concat(n,'" (original: "').concat(e.element_selector,'")'))}catch(r){t.log('Error applying selector "'.concat(n,'" (original: "').concat(e.element_selector,'"):'),r)}}),e.observe_mutations&&"MutationObserver"in window&&(new MutationObserver(function(e){e.forEach(function(e){t.sendToWorker("dom_mutation",{type:e.type,target:e.target.outerHTML,timestamp:(new Date).toISOString()})})}).observe(document.body,{childList:!0,subtree:!0}),this.log("MutationObserver attached for DOM changes"))},e.prototype.extractElementData=function(e,t){var n=e.getBoundingClientRect(),r={tagName:e.tagName.toLowerCase(),id:e.id||"",className:e.className||"",textContent:(e.textContent||"").trim().substring(0,100),position:{x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height)},href:e.href||void 0,value:e.value||void 0};if(!1!==(null==t?void 0:t.extract_customdata)){var i=function(e){var t,n={},r=e.getAttribute("customdata")||e.dataset.customdata;if(r)try{var i=JSON.parse(r);n.customdata=i,i.name&&(n.itemName=i.name),i.displayedTitle&&(n.section=i.displayedTitle),i.title&&(n.title=i.title),i.category&&(n.category=i.category),i.id&&(n.itemId=i.id)}catch(e){var o=r.match(/"name"\s*:\s*"([^"]+)"/);o&&(n.itemName=o[1]);var a=r.match(/"(?:displayedTitle|title)"\s*:\s*"([^"]+)"/);a&&(n.section=a[1])}var s=e.id;if(s){n.elementId=s;var c=s.split("_");if(c.length>=2){var l=c.slice(1).join("_");!n.itemName&&l&&(n.itemName=l)}}var u=null===(t=e.textContent)||void 0===t?void 0:t.trim();u&&u.length<100&&(n.displayText=u);for(var h=e.dataset,d=0,g=Object.entries(h);d<g.length;d++){var f=g[d],p=f[0],m=f[1];!n[p]&&m&&(n["data_".concat(p)]=m)}return n}(e);Object.keys(i).length>0&&(r.enriched=i,i.itemName&&(r.itemName=i.itemName),i.section&&(r.section=i.section),i.category&&(r.category=i.category))}return this.config.debug&&(r.attributes=Array.from(e.attributes).reduce(function(e,t){return e[t.name]=t.value.length>100?t.value.substring(0,100)+"...":t.value,e},{})),r},e.prototype.sendToWorker=function(e,t){var n;if(this.shouldSampleEvents()){var r=new Date,i=this.getCommonEventData(),o=b({event:e,properties:t,timestamp:r.getTime(),created_at:r.toISOString(),userId:this.getUserId(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(n=this.projectSettings)||void 0===n?void 0:n.project_id)||void 0},i);this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:o}):this.eventQueue.push(o),this.log("Event tracked:",o)}else this.log("Event skipped due to sampling:",e)},e.prototype.setupWebWorker=function(){return S(this,void 0,void 0,function(){var e,t,n,r,i,o=this;return T(this,function(a){switch(a.label){case 0:return[4,this.authManager.getAuthHeaders()];case 1:return e=a.sent(),this.worker.postMessage({type:"config",payload:{apiUrl:(null===(t=this.config.apiDetails)||void 0===t?void 0:t.apiEndPoint)||"".concat(this.config.endpoint,"/api/v1/events"),batchSize:(null===(n=this.config.workerConfig)||void 0===n?void 0:n.batchSize)||10,batchInterval:(null===(r=this.config.workerConfig)||void 0===r?void 0:r.batchInterval)||5e3,headers:b(b({"Content-Type":"application/json"},e),(null===(i=this.config.apiDetails)||void 0===i?void 0:i.headers)||{})}}),this.worker.onmessage=function(e){var t;"success"===e.data.status?o.log("Batch sent successfully by worker"):"debug"===e.data.status?o.log(e.data.message,e.data):"error"===e.data.status&&(o.log("Worker failed to send batch",e.data.error),e.data.failedEvents&&e.data.failedEvents.length>0&&(t=o.eventQueue).unshift.apply(t,e.data.failedEvents))},this.log("Web worker setup complete."),[2]}})})},e.prototype.track=function(e,t){var n;if(void 0===t&&(t={}),this.shouldSampleEvents()){this.journeyTracker.trackEvent(e,t);var r=this.journeyTracker.getContext(),i=new Date,o=this.getCommonEventData(),a=b({event:e,properties:b(b({},t),{journeyContext:{sequenceIndex:r.eventCount-1,timeSinceLastEvent:r.timeSinceLastEvent,journeyDuration:Date.now()-r.journeyStartTime}}),timestamp:i.getTime(),created_at:i.toISOString(),userId:this.userManager.getUserId(),userType:this.userManager.getUserType(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(n=this.projectSettings)||void 0===n?void 0:n.project_id)||void 0},o);this.journeyTracker.shouldAnalyzeJourney()&&this.sendJourneyForAnalysis(),this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:a}):this.eventQueue.push(a),this.log("Event tracked public:",a)}else this.log("Event skipped due to sampling:",e)},e.prototype.startBatchTimer=function(){var e=this;this.batchTimer=window.setInterval(function(){e.flushQueue()},this.config.batchInterval)},e.prototype.flushQueue=function(){return S(this,void 0,void 0,function(){var e;return T(this,function(t){switch(t.label){case 0:return 0===this.eventQueue.length?[2]:(e=_([],this.eventQueue,!0),this.eventQueue=[],this.config.useWebWorker&&"undefined"!=typeof Worker?(this.worker.postMessage({type:"batch",events:e,endpoint:"".concat(this.config.endpoint,"/api/v1/events")}),[3,3]):[3,1]);case 1:return[4,this.sendBatchWithRetry(e)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},e.prototype.sendBatchWithRetry=function(e){return S(this,void 0,void 0,function(){var t,n;return T(this,function(r){switch(r.label){case 0:if(this.batchRetryCount>=this.maxBatchRetries)return this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[2];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.sendBatch(e)];case 2:return r.sent(),this.batchRetryCount=0,[3,4];case 3:return t=r.sent(),this.batchRetryCount++,this.log("Batch send failed. Retry attempt ".concat(this.batchRetryCount," of ").concat(this.maxBatchRetries,"."),t),(n=this.eventQueue).unshift.apply(n,e),this.batchRetryCount>=this.maxBatchRetries&&this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[3,4];case 4:return[2]}})})},e.prototype.sendBatch=function(e){return S(this,void 0,void 0,function(){var t,n,r,i,o,a,s;return T(this,function(c){switch(c.label){case 0:return t="".concat(this.config.endpoint,"/api/v1/events"),n={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()];case 1:r=c.sent(),n=b(b({},n),r),this.config.apiDetails&&this.config.apiDetails.apiEndPoint&&(t=this.config.apiDetails.apiEndPoint,this.config.apiDetails.headers&&(n=b(b({},n),this.config.apiDetails.headers))),i=this.config.clientId||"5288aa7d-1b7c-481e-958d-eb9b8e951f14",o=e.map(function(e){return b({event:e.event,userId:e.userId,client_id:i,timestamp:new Date(e.timestamp).toISOString()},e.properties||{})}),c.label=2;case 2:return c.trys.push([2,4,,5]),[4,fetch(t,{method:"POST",headers:n,body:JSON.stringify({events:o})})];case 3:if(!(a=c.sent()).ok)throw new Error("Failed to send batch: ".concat(a.status));return this.log("Batch sent successfully:",o),[3,5];case 4:throw s=c.sent(),this.log("Error sending batch:",s),s;case 5:return[2]}})})},e.prototype.generateSessionId=function(){return"sess_"+Math.random().toString(36).substr(2,9)},e.prototype.getPageContext=function(){var e=window.location.href,t=window.location.pathname,n=window.location.hash,r=document.referrer,i={};return new URLSearchParams(window.location.search).forEach(function(e,t){i[t]=e}),{url:e,path:t,hash:n||void 0,referrer:r||void 0,queryParams:Object.keys(i).length>0?i:void 0,title:document.title||void 0}},e.prototype.getCommonEventData=function(){return b({pageContext:this.getPageContext()},this.config.extraConfig||{})},e.prototype.getUserId=function(){return this.userManager.getUserId()},e.prototype.identifyUser=function(e,t){var n=this.userManager.getUserIdentificationEvent(e);this.userManager.identifyUser(e,t),this.track("user_identified",n),this.errorTracker&&this.errorTracker.setUser(e),this.log("User identified:",{userId:e,properties:t})},e.prototype.setExtraConfig=function(e,t){void 0===t&&(t=!0),t&&this.config.extraConfig?this.config.extraConfig=b(b({},this.config.extraConfig),e):this.config.extraConfig=e,this.log("Extra config updated:",this.config.extraConfig)},e.prototype.getExtraConfig=function(){return this.config.extraConfig},e.prototype.isAuthenticated=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return[4,this.authManager.getAccessToken()];case 1:return[2,null!==e.sent()]}})})},e.prototype.authenticate=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return[4,this.authManager.initialize()];case 1:return[2,e.sent()]}})})},e.prototype.logout=function(){return S(this,void 0,void 0,function(){return T(this,function(e){switch(e.label){case 0:return[4,this.authManager.logout()];case 1:return e.sent(),[2]}})})},e.prototype.sendJourneyForAnalysis=function(){return S(this,void 0,void 0,function(){var e,t,n,r,i;return T(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),e=this.journeyTracker.getJourneyForAnalysis(),t="".concat(this.config.endpoint,"/api/v1/journeys/analyze"),[4,this.authManager.getAuthHeaders()];case 1:return n=o.sent(),[4,fetch(t,{method:"POST",headers:b({"Content-Type":"application/json"},n),body:JSON.stringify({client_id:this.config.clientId,user_id:this.userManager.getUserId(),session_id:this.sessionId,journey:e})})];case 2:return(r=o.sent()).ok||console.error("[AInamika SDK] Failed to send journey for analysis:",r.statusText),[3,4];case 3:return i=o.sent(),console.error("[AInamika SDK] Error sending journey for analysis:",i),[3,4];case 4:return[2]}})})},e.prototype.log=function(e,t){this.config.debug&&console.log("[AnalyticsPro SDK] ".concat(e),t||"")},e.prototype.loadConfigFromFile=function(){return S(this,void 0,void 0,function(){var e;return T(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch("/AInamika_config.json",{cache:"reload"})];case 1:return(e=t.sent()).ok?[4,e.json()]:[2,null];case 2:return[2,t.sent()];case 3:return t.sent(),[2,null];case 4:return[2]}})})},e.prototype.setupDynamicDomTracking=function(){return S(this,void 0,void 0,function(){var e=this;return T(this,function(t){return"MutationObserver"in window&&(new MutationObserver(function(){e.mutationDebounceTimer&&clearTimeout(e.mutationDebounceTimer),e.mutationDebounceTimer=window.setTimeout(function(){e.handleDomMutation()},e.mutationDebounceMs)}).observe(document.body,{childList:!0,subtree:!0,attributes:!0}),this.log("Dynamic DOM MutationObserver attached")),[2]})})},e.prototype.computeDomHash=function(e){for(var t=JSON.stringify(e),n=2166136261,r=0;r<t.length;r++)n^=t.charCodeAt(r),n+=(n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24);return(n>>>0).toString(16)},e.prototype.generateElementFingerprint=function(e){var t=[],n=e.getAttribute("data-testid"),r=e.getAttribute("data-track"),i=e.getAttribute("data-analytics");n&&t.push("testid:".concat(n)),r&&t.push("track:".concat(r)),i&&t.push("analytics:".concat(i));var o=e.id;o&&!o.match(/^(jsc|css|ember|react|ng)-|^\d+$|^[a-f0-9]{8,}$/i)&&t.push("id:".concat(o));var a=e.getAttribute("name");a&&t.push("name:".concat(a));var s=e.getAttribute("aria-label");s&&t.push("aria:".concat(s.substring(0,50)));var c=e.tagName.toLowerCase(),l=e.getAttribute("role"),u=e.getAttribute("type");if(t.push("tag:".concat(c)),l&&t.push("role:".concat(l)),u&&t.push("type:".concat(u)),["button","a","span","div"].includes(c)){var h=(e.textContent||"").trim().substring(0,30).toLowerCase().replace(/\s+/g,"_");h&&t.push("text:".concat(h))}var d=e.getAttribute("customdata");if(d)try{var g=JSON.parse(d);g.name&&t.push("customname:".concat(g.name)),g.id&&t.push("customid:".concat(g.id))}catch(e){t.push("customdata:".concat(d.substring(0,30)))}var f=e.closest('[data-testid], [id]:not([id^="jsc-"]):not([id^="css-"])');if(f&&f!==e){var p=f.getAttribute("data-testid")||f.id;p&&t.push("parent:".concat(p))}if(e.className&&"string"==typeof e.className){var m=e.className.split(" ").filter(function(e){return e.trim()&&!e.match(/^(jsc|css|ember|react|ng|active|hover|focus|selected|open|closed)-|^[a-f0-9]{6,}$/i)}).slice(0,3).join(".");m&&t.push("class:".concat(m))}var v=t.join("|");return this.hashString(v)},e.prototype.hashString=function(e){for(var t=0,n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t&=t;return Math.abs(t).toString(16).padStart(8,"0").substring(0,16)},e.prototype.getLastKnownConfig=function(){try{var e=localStorage.getItem("ainamika_last_known_config");if(!e)return null;var t=JSON.parse(e);return t&&t.events_to_track&&t.events_to_track.length>0?t:null}catch(e){return null}},e.prototype.setLastKnownConfig=function(e){try{e&&e.events_to_track&&e.events_to_track.length>0&&localStorage.setItem("ainamika_last_known_config",JSON.stringify(e))}catch(e){}},e.prototype.getCachedConfigForDomHash=function(e){try{var t=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),n=t[e];return n?n.events_to_track?(t[e]={config:n,lastAccessed:Date.now(),createdAt:Date.now()},localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),n):(n.lastAccessed=Date.now(),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),n.config):null}catch(e){return null}},e.prototype.setCachedConfigForDomHash=function(e,t){var n=this;try{var r=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}");r[e]={config:t,lastAccessed:Date.now(),createdAt:Date.now()};var i=Object.keys(r);i.length>this.MAX_CACHED_CONFIGS&&i.sort(function(e,t){return(r[e].lastAccessed||r[e].createdAt||0)-(r[t].lastAccessed||r[t].createdAt||0)}).slice(0,i.length-this.MAX_CACHED_CONFIGS).forEach(function(e){delete r[e],n.log("Evicted old config cache: ".concat(e))}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(r))}catch(e){this.log("Cache storage error, clearing old entries:",e),this.clearOldConfigCache()}},e.prototype.clearOldConfigCache=function(){try{var e=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),t=Object.keys(e);if(0===t.length)return;var n=t.sort(function(t,n){var r=e[t].lastAccessed||e[t].createdAt||0;return(e[n].lastAccessed||e[n].createdAt||0)-r}),r={};n.slice(0,5).forEach(function(t){r[t]=e[t]}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(r)),this.log("Cleared config cache, kept ".concat(Object.keys(r).length," entries"))}catch(e){localStorage.removeItem("ainamika_dom_config_cache")}},e.prototype.handleDomMutation=function(){return S(this,void 0,void 0,function(){var e,t,n,r,i,o,a,s=this;return T(this,function(c){switch(c.label){case 0:return[4,this.getDOMStructure()];case 1:return e=c.sent(),(t=this.computeDomHash(e))===this.lastDomHash?(this.log("DOM hash unchanged after mutation, skipping config fetch."),[2]):(this.log("DOM hash changed, detecting new elements...",{oldHash:this.lastDomHash,newHash:t}),this.lastDomHash=t,n=e.elements||[],0===(r=n.filter(function(e){var t=e.selector||"";return!(!t||s.knownElementSelectors.has(t))})).length?(this.log("No new elements detected, skipping config fetch."),[2]):(this.log("Found ".concat(r.length," new elements out of ").concat(n.length," total")),(i=this.getCachedConfigForDomHash(t))?(this.log("Reusing cached config for DOM hash",t),this.mergeAndApplyConfig(i),n.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),[2]):(o={elements:r},this.log("Fetching config for new elements only:",r.length),[4,this.fetchGeneratedConfig(o,t)])));case 2:return(a=c.sent())&&a.events_to_track?(this.mergeAndApplyConfig(a),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=a.config_hash||"",r.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Fetched and merged config for new elements",{newEvents:a.events_to_track.length,totalEvents:this.mergedConfig.events_to_track.length})):this.log("No valid config returned for new elements"),[2]}})})},e.prototype.resetViewTracking=function(){this.viewedElements.clear(),this.viewObservers.forEach(function(e,t){e.disconnect()}),this.viewObservers.clear(),this.log("View tracking reset - elements can be tracked again")},e.prototype.destroy=function(){this.viewObservers.forEach(function(e){e.disconnect()}),this.viewObservers.clear(),this.viewedElements.clear(),this.eventQueue=[],this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0),this.worker&&this.worker.terminate(),this.log("SDK destroyed and all resources cleaned up")},e.prototype.flush=function(){this.config.useWebWorker&&this.worker?this.worker.postMessage({type:"flush"}):this.flushQueue(),this.log("Flush requested")},e.prototype.mergeAndApplyConfig=function(e){var t;if(e&&e.events_to_track){var n=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),r=e.events_to_track.filter(function(e){return!n.has(e.element_selector)});r.length>0&&((t=this.mergedConfig.events_to_track).push.apply(t,r),this.log("Merged ".concat(r.length," new events, total: ").concat(this.mergedConfig.events_to_track.length))),e.tracking_config&&(this.mergedConfig.tracking_config=b(b({},this.mergedConfig.tracking_config),e.tracking_config)),r.length>0&&this.applyGeneratedConfig({events_to_track:r,tracking_config:e.tracking_config})}},e.SAMPLING_STORAGE_KEY="ainamika_sampling",e}();"undefined"!=typeof window&&(window.AInamikaSDKPro=E);var I=E;return t.default}()});
2
2
  //# sourceMappingURL=ainamika-sdk.js.map