ainamika-sdk 1.2.7 → 1.2.8
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.
- package/README.md +56 -1
- package/dist/ainamika-sdk.js +1 -1
- package/dist/ainamika-sdk.js.map +1 -1
- package/dist/sdk.d.ts +7 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
## Features
|
|
9
9
|
|
|
10
10
|
- **AI-Powered Auto-Configuration**: Automatically analyzes your DOM and generates semantic tracking configurations
|
|
11
|
+
- **Session Start Tracking**: Captures device info, landing page, referrer, and UTM params immediately on load
|
|
11
12
|
- **Web Vitals & Performance Tracking**: Core Web Vitals (LCP, FCP, FID, CLS, TTFB) and page load metrics
|
|
12
13
|
- **Engagement Analytics**: Scroll depth, rage clicks, time on page, active/idle time tracking
|
|
13
14
|
- **API Response Tracking**: Track and analyze API calls with timing and response data
|
|
@@ -15,6 +16,7 @@
|
|
|
15
16
|
- **Page Context & Query Params**: Automatic capture of URL, path, query parameters, referrer with every event
|
|
16
17
|
- **Extra Config Support**: Pass custom data (userId, deviceId, appVersion) that's included in all events
|
|
17
18
|
- **Smart Event Naming**: AI generates semantic event names like `game_launch_cubeform` instead of generic names
|
|
19
|
+
- **Framework Detection**: Detects click handlers from React, Vue, Angular, Svelte, and jQuery components
|
|
18
20
|
- **User Journey Analysis**: Track complete user journeys for funnel optimization
|
|
19
21
|
- **Sampling Support**: Server-side sampling to control data volume and costs
|
|
20
22
|
- **Offline Support**: Queue events when offline and sync when back online
|
|
@@ -141,6 +143,58 @@ console.log(metrics);
|
|
|
141
143
|
// }
|
|
142
144
|
```
|
|
143
145
|
|
|
146
|
+
## Session Tracking
|
|
147
|
+
|
|
148
|
+
The SDK automatically sends a `session_start` event immediately when it loads, before any other processing. This ensures you capture data from the moment a user lands on your app.
|
|
149
|
+
|
|
150
|
+
### Session Start Event Data
|
|
151
|
+
|
|
152
|
+
```javascript
|
|
153
|
+
// Automatically sent on SDK initialization
|
|
154
|
+
{
|
|
155
|
+
event: "session_start",
|
|
156
|
+
properties: {
|
|
157
|
+
// Device Information
|
|
158
|
+
userAgent: "Mozilla/5.0...",
|
|
159
|
+
language: "en-US",
|
|
160
|
+
languages: ["en-US", "en"],
|
|
161
|
+
platform: "MacIntel",
|
|
162
|
+
screenWidth: 1920,
|
|
163
|
+
screenHeight: 1080,
|
|
164
|
+
viewportWidth: 1440,
|
|
165
|
+
viewportHeight: 900,
|
|
166
|
+
devicePixelRatio: 2,
|
|
167
|
+
timezone: "America/New_York",
|
|
168
|
+
timezoneOffset: -300,
|
|
169
|
+
cookieEnabled: true,
|
|
170
|
+
onLine: true,
|
|
171
|
+
|
|
172
|
+
// Session Info
|
|
173
|
+
sessionId: "sess_abc123",
|
|
174
|
+
userIdentifier: "anon_xyz789",
|
|
175
|
+
isNewSession: true,
|
|
176
|
+
sdkVersion: "1.2.7",
|
|
177
|
+
|
|
178
|
+
// Landing Page
|
|
179
|
+
landingPage: "/products",
|
|
180
|
+
landingUrl: "https://example.com/products?ref=google",
|
|
181
|
+
referrer: "https://google.com",
|
|
182
|
+
entryTitle: "Products - My Store",
|
|
183
|
+
|
|
184
|
+
// UTM Parameters (if present)
|
|
185
|
+
utmSource: "google",
|
|
186
|
+
utmMedium: "cpc",
|
|
187
|
+
utmCampaign: "summer_sale"
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
This gives you complete visibility into:
|
|
193
|
+
- **Traffic sources**: Where users come from (referrer, UTM params)
|
|
194
|
+
- **Device landscape**: Screen sizes, browsers, platforms
|
|
195
|
+
- **Geographic distribution**: Timezone data
|
|
196
|
+
- **Entry points**: Which pages users land on first
|
|
197
|
+
|
|
144
198
|
## Engagement Tracking
|
|
145
199
|
|
|
146
200
|
Track how users interact with your pages:
|
|
@@ -492,10 +546,11 @@ new AInamikaSDK(config: AnalyticsConfig)
|
|
|
492
546
|
|
|
493
547
|
| Category | Events |
|
|
494
548
|
|----------|--------|
|
|
549
|
+
| **Session** | `session_start` - Fires immediately on SDK load with device info, landing page, referrer, UTM params |
|
|
495
550
|
| **Performance** | `performance_lcp`, `performance_fcp`, `performance_fid`, `performance_cls`, `performance_page_load` |
|
|
496
551
|
| **Engagement** | `engagement_scroll_depth`, `engagement_rage_click`, `page_exit` |
|
|
497
552
|
| **API** | `api_call` (when enabled) |
|
|
498
|
-
| **DOM** | Click, submit, view, focus events based on auto-config |
|
|
553
|
+
| **DOM** | Click, submit, view, focus, change events based on auto-config |
|
|
499
554
|
|
|
500
555
|
## Dashboard Queries
|
|
501
556
|
|
package/dist/ainamika-sdk.js
CHANGED
|
@@ -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,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return I}});var r=function(){return r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},n=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},i=function(e,t){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=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,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||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=r({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=r({},console),this.initialize()}return e.prototype.loadHtml2Canvas=function(){return n(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 r=document.createElement("script");r.src="https://html2canvas.hertzen.com/dist/html2canvas.min.js",r.async=!0,r.onload=function(){console.log("[AInamika Error Tracker] html2canvas loaded successfully"),e.html2canvasLoaded=!0,t(!0)},r.onerror=function(){console.error("[AInamika Error Tracker] Failed to load html2canvas"),t(!1)},document.head.appendChild(r)})),[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 r;e.handleError({type:"unhandled",message:(null===(r=t.reason)||void 0===r?void 0:r.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(r(r({},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),r=Date.now();if(this.errorDebounceMap.has(t)&&r-this.errorDebounceMap.get(t)<this.config.debounceMs)return;this.errorDebounceMap.set(t,r),this.errorCount++,this.captureError(e)}},e.prototype.captureError=function(e){return n(this,void 0,void 0,function(){var t,r,n;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?(r=t,[4,this.captureScreenshot()]):[3,2];case 1:r.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 n=i.sent(),console.error("[AInamika Error Tracker] Failed to capture error:",n),[3,5];case 5:return[2]}})})},e.prototype.extractStackTrace=function(e){if(!e||!e.stack)return"";var t=e.stack.split("\n"),r=this.config.maxStackTraceDepth;return t.slice(0,r).join("\n")},e.prototype.assessSeverity=function(e){var t,r=(null===(t=e.message)||void 0===t?void 0:t.toLowerCase())||"";return r.includes("out of memory")||r.includes("security")||r.includes("permission denied")||"unhandled"===e.type?"critical":r.includes("network")||r.includes("timeout")||r.includes("failed to fetch")||r.includes("cors")?"high":r.includes("undefined")||r.includes("null")||r.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(r){try{var n=document.querySelectorAll(r);Array.from(n).slice(0,100-t.length).forEach(function(r){var n;t.push({tagName:r.tagName,id:r.id,className:r.className,textContent:null===(n=r.textContent)||void 0===n?void 0:n.substring(0,100),attributes:e.getElementAttributes(r)})})}catch(e){}}),t},e.prototype.getElementAttributes=function(e){var t={};return["id","class","type","name","value","href","src"].forEach(function(r){var n=e.getAttribute(r);n&&(t[r]=n)}),t},e.prototype.captureScreenshot=function(){return n(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 r="Unknown",n="";/windows/i.test(e)?(r="Windows",(a=e.match(/Windows NT (\d+\.\d+)/))&&(n=a[1])):/macintosh|mac os x/i.test(e)?(r="macOS",(a=e.match(/Mac OS X (\d+[._]\d+)/))&&(n=a[1].replace("_","."))):/android/i.test(e)?(r="Android",(a=e.match(/Android (\d+(\.\d+)?)/))&&(n=a[1])):/iphone|ipad|ipod/i.test(e)?(r="iOS",(a=e.match(/OS (\d+[._]\d+)/))&&(n=a[1].replace("_","."))):/linux/i.test(e)&&(r="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:r,osVersion:n,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 r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];return n(e,void 0,void 0,function(){var e,n,o,a;return i(this,function(i){switch(i.label){case 0:e=Date.now(),n=r[0]instanceof Request?r[0].url:String(r[0]),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,t.apply(void 0,r)];case 2:return o=i.sent(),this.addBreadcrumb({type:"network",message:"Fetch ".concat(o.status," ").concat(n),data:{url:n,status:o.status,duration:Date.now()-e}}),o.ok||this.handleError({type:"network",message:"Network request failed: ".concat(o.status," ").concat(o.statusText),url:n,status:o.status}),[2,o];case 3:throw a=i.sent(),this.addBreadcrumb({type:"network",message:"Fetch failed ".concat(n),data:{url:n,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:n,error:a}),a;case 4:return[2]}})})};var r=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,n,i,o){return this._errorTracker={method:e,url:t,startTime:Date.now()},r.call(this,e,t,n||!0,i,o)},XMLHttpRequest.prototype.send=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=this._errorTracker;return this.addEventListener("loadend",function(){if(n){var t=Date.now()-n.startTime;e.status>=400&&e.dispatchEvent(new CustomEvent("networkerror",{detail:{type:"network",message:"XHR request failed: ".concat(e.status," ").concat(e.statusText),url:n.url,status:e.status}})),e.dispatchEvent(new CustomEvent("networkbreadcrumb",{detail:{type:"network",message:"XHR ".concat(e.status," ").concat(n.url),data:{method:n.method,url:n.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 r=e.originalConsole[t];console[t]=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];"function"==typeof r&&r.call.apply(r,o([console],n,!1)),"error"===t&&e.handleError({type:"console",message:n.map(function(e){return String(e)}).join(" "),consoleMethod:t}),e.addBreadcrumb({type:"console",message:"Console ".concat(t,": ").concat(n.map(function(e){return String(e)}).join(" ")),data:{level:t}})}})},e.prototype.setupNavigationTracking=function(){var e=this,t=window.location.href,r=function(){var r=window.location.href;r!==t&&(e.addBreadcrumb({type:"navigation",message:"Navigation from ".concat(t," to ").concat(r),data:{from:t,to:r}}),t=r)};window.addEventListener("popstate",r),window.addEventListener("hashchange",r);var n=history.pushState,i=history.replaceState;history.pushState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];n.apply(this,e),setTimeout(r,0)},history.replaceState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];i.apply(this,e),setTimeout(r,0)}},e.prototype.setupClickTracking=function(){var e=this;document.addEventListener("click",function(t){var r,n=t.target;if(n){var i=e.getElementSelector(n),o=(null===(r=n.textContent)||void 0===r?void 0:r.trim().substring(0,50))||"";e.addBreadcrumb({type:"click",message:"Clicked ".concat(i).concat(o?": ".concat(o):""),data:{selector:i,text:o,tagName:n.tagName,id:n.id,className:n.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 n(this,void 0,void 0,function(){var t,n,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 n=i.sent(),t=r(r({},t),n),[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")||"[]",r=JSON.parse(t);r.push(e),r.length>50&&r.splice(0,r.length-50),localStorage.setItem("ainamika_errors",JSON.stringify(r))}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 n(this,void 0,void 0,function(){var e,t,r,n,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")),r=0,n=t,i.label=1;case 1:return r<n.length?(o=n[r],[4,this.sendError(o)]):[3,4];case 2:i.sent(),i.label=3;case 3:return r++,[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,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},s.apply(this,arguments)},c=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},l=function(e,t){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=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,r,n,i=this;return l(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),t=this.generateErrorId(),r={id:t,errorData:this.config.compressionEnabled?this.compressData(e):e,timestamp:Date.now(),retryCount:0},[4,this.addToQueue(r)];case 1:return o.sent(),this.updateMetadata(),setTimeout(function(){return i.processQueue()},100),[2,t];case 2:throw n=o.sent(),console.error("[AInamika Error Storage] Failed to store error:",n),n;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(),r=t.filter(function(t){return t.id!==e});return r.length!==t.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(r)),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,r=e.map(function(e){return e.timestamp}).sort();return{errorCount:e.length,totalSize:t,oldestError:r[0],newestError:r[r.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,r,n,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,r=e,o.label=2;case 2:if(!(t<r.length))return[3,7];if((n=r[t]).retryCount>=this.config.maxRetries)return console.warn("[AInamika Error Storage] Max retries reached for error ".concat(n.id)),this.removeError(n.id),[3,6];if(n.lastRetry&&Date.now()-n.lastRetry<this.config.retryInterval)return[3,6];o.label=3;case 3:return o.trys.push([3,5,,6]),[4,this.sendError(n)];case 4:return o.sent()?(this.removeError(n.id),console.log("[AInamika Error Storage] Successfully sent error ".concat(n.id))):this.incrementRetryCount(n.id),[3,6];case 5:return i=o.sent(),console.error("[AInamika Error Storage] Failed to send error ".concat(n.id,":"),i),this.incrementRetryCount(n.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,r,n;return l(this,function(i){switch(i.label){case 0:if(t=this.getQueueRaw(),!(r=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(r)];case 2:return i.sent()?(this.removeError(e),[2,!0]):(this.incrementRetryCount(e),[2,!1]);case 3:return n=i.sent(),console.error("[AInamika Error Storage] Failed to retry error ".concat(e,":"),n),this.incrementRetryCount(e),[2,!1];case 4:return[2]}})})},e.prototype.addToQueue=function(e){return c(this,void 0,void 0,function(){var t,r;return l(this,function(n){if((t=this.getQueueRaw()).push(e),r=JSON.stringify(t),new Blob([r]).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(),r=t.findIndex(function(t){return t.id===e});-1!==r&&(t[r].retryCount++,t[r].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,r,n,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,(r=this.config.endpoint||t.endpoint)?(n=t.apiKey||"",[4,fetch("".concat(r,"/api/v1/errors"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:n?"Bearer ".concat(n):""},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,r=e.filter(function(e){return e.timestamp>t});r.length!==e.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(r)),console.log("[AInamika Error Storage] Cleaned up ".concat(e.length-r.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 r=0,n=t.errors;r<n.length;r++){var i=n[r];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,r=0;for(var n in localStorage)if(localStorage.hasOwnProperty(n)){var i=new Blob([localStorage.getItem(n)||""]).size;e+=i,n.startsWith("ainamika_error")?t+=i:n.startsWith("ainamika_")&&(r+=i)}return{totalSize:e,errorSize:t,otherSize:r}},e.checkStorageSpace=function(e){try{var t="ainamika_storage_test",r="x".repeat(Math.min(e,1048576));return localStorage.setItem(t,r),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,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])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 r=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(r," → ").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,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])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 r=Date.now(),n=this.lastEventTime?r-this.lastEventTime:0,i={eventName:e,timestamp:r,properties:f(f({},t),{timeSinceLastEvent:n,journeyPosition:this.sequenceIndex}),sequenceIndex:this.sequenceIndex++};this.userJourney.push(i),this.lastEventTime=r,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,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||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 r=this.userJourney.slice(t,t+3).map(function(e){return e.eventName}).join(" → ");e[r]=(e[r]||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,r=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<r.length;t++){var n=r[t],i=n[0];if(n[1].filter(function(t){return e.includes(t)}).length>=2)return i}return null},e}(),m=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},v=function(e,t){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=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,r){void 0===r&&(r=!1),this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.clientId=e,this.apiEndpoint=t,this.debug=r,this.loadTokens()}return e.prototype.initialize=function(){return m(this,void 0,void 0,function(){var e,t;return v(this,function(r){switch(r.label){case 0:return r.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(r.sent())return[2,!0];r.label=2;case 2:return[4,this.requestTokens()];case 3:return(e=r.sent())?(this.setTokens(e),[2,!0]):[2,!1];case 4:return t=r.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(r){switch(r.label){case 0:return r.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=r.sent()).ok)throw new Error("Token request failed: ".concat(e.status));return[4,e.json()];case 2:return[2,r.sent()];case 3:return t=r.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,r;return v(this,function(n){switch(n.label){case 0:if(!this.refreshToken)return[2,!1];n.label=1;case 1:return n.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=n.sent()).ok?[4,e.json()]:(this.clearTokens(),[2,!1]);case 3:return t=n.sent(),this.setTokens(t),[2,!0];case 4:return r=n.sent(),this.debugLog("Token refresh error:",r),[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 r=[],n=0;n<localStorage.length;n++){var i=localStorage.key(n);i&&i.startsWith("ainamika_auth_")&&i!==e.STORAGE_KEY&&r.push(i)}r.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 r=JSON.parse(t);if(r.clientId&&r.clientId!==this.clientId)return this.debugLog("Stored token is for different clientId, clearing"),void localStorage.removeItem(e.STORAGE_KEY);this.accessToken=r.accessToken,this.refreshToken=r.refreshToken,this.tokenExpiry=r.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,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||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,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);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 r,n=t.getEntries(),i=n[n.length-1];e.performanceMetrics.lcp=i.startTime,e.onEvent("performance_lcp",{value:i.startTime,element:null===(r=i.element)||void 0===r?void 0:r.tagName})}).observe({type:"largest-contentful-paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] LCP not supported")}try{new PerformanceObserver(function(t){var r=t.getEntries()[0];e.performanceMetrics.fid=r.processingStart-r.startTime,e.onEvent("performance_fid",{value:e.performanceMetrics.fid,eventType:r.name})}).observe({type:"first-input",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FID not supported")}try{var t=0;new PerformanceObserver(function(r){for(var n=0,i=r.getEntries();n<i.length;n++){var o=i[n];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 r=t.getEntries().find(function(e){return"first-contentful-paint"===e.name});r&&(e.performanceMetrics.fcp=r.startTime,e.onEvent("performance_fcp",{value:r.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 r=performance.getEntriesByType("resource");e.performanceMetrics.resourceCount=r.length,e.performanceMetrics.transferSize=r.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,r=function(){var r=window.scrollY||document.documentElement.scrollTop,n=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-window.innerHeight,i=n>0?Math.round(r/n*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(r),t=!0)},{passive:!0})},e.prototype.initRageClickTracking=function(){var e=this;document.addEventListener("click",function(t){var r,n=Date.now();if(e.clickHistory.push(n),e.clickHistory=e.clickHistory.filter(function(t){return n-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===(r=i.textContent)||void 0===r?void 0:r.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=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return n=e,i=void 0,a=function(){var e,r,n,i,o,a,s;return function(e,t){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=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(),r=t[0]instanceof Request?t[0].url:String(t[0]),n=(null===(s=t[1])||void 0===s?void 0:s.method)||"GET",!this.shouldTrackAPI(r))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:r,method:n,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:r,method:n,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 r(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(r,s)}c((a=a.apply(n,i||[])).next())});var n,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(r){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,r,n){this.onEvent("api_response_tracked",k({endpoint:e,method:t,responseType:typeof r,responseKeys:r&&"object"==typeof r?Object.keys(r):[],hasData:!!r,dataCount:Array.isArray(r)?r.length:void 0},n))},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,r){this.onEvent("conversion",k(k({goal:e,value:t},r),{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,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},w.apply(this,arguments)},S=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},T=function(e,t){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},_=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||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=w({endpoint:h.API_BASE_URL,batchInterval:5e3,useWebWorker:!0,debug:h.DEBUG,errorTracking:{enabled:!0,captureScreenshots:!1,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"}),r=URL.createObjectURL(t);this.worker=new Worker(r),this.initialize()}return e.prototype.initialize=function(){return S(this,void 0,void 0,function(){var e,t,r,n,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===(r=this.config.errorTracking)||void 0===r?void 0:r.enabled)&&this.shouldSampleErrors()?this.initializeErrorTracking():(null===(n=this.config.errorTracking)||void 0===n?void 0:n.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,r;return T(this,function(n){switch(n.label){case 0:if(!this.config.projectKey)return[2];n.label=1;case 1:return n.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=n.sent()).ok)throw new Error("Project lookup failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.projectSettings=n.sent(),this.log("Project settings loaded:",this.projectSettings),[3,5];case 4:throw r=n.sent(),this.log("Failed to load project settings:",r),r;case 5:return[2]}})})},e.prototype.initializeSamplingDecision=function(){return S(this,void 0,void 0,function(){var e,t,r;return T(this,function(n){switch(n.label){case 0:if(!this.config.projectKey)return[2];n.label=1;case 1:return n.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=n.sent()).ok)throw new Error("Sampling check failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.samplingDecision=n.sent(),this.log("Sampling decision received:",this.samplingDecision),this.cacheSamplingDecision(),[3,5];case 4:return r=n.sent(),this.log("Failed to get sampling decision, using cached or defaults:",r),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 r=JSON.parse(t);if(r.projectKey&&r.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());r.projectKey;var n=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(r,["projectKey"]);this.samplingDecision=n,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 r=[],n=0;n<localStorage.length;n++){var i=localStorage.key(n);i&&i.startsWith("ainamika_sampling_")&&i!==e.SAMPLING_STORAGE_KEY&&r.push(i)}r.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")||"{}"),r=Object.keys(t);return{domConfigCacheSize:r.length,cachedDomHashes:r,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,r,n,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===(n=null===(r=this.config.errorTracking)||void 0===r?void 0:r.captureDomSnapshots)||void 0===n||n,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,r,n,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===(n=null===(r=this.config.advancedTracking)||void 0===r?void 0:r.trackEngagement)||void 0===n||n,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 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,r,n){this.advancedTracker?this.advancedTracker.trackAPI(e,t,r,n):this.track("api_response_tracked",w({endpoint:e,method:t,responseType:typeof r,hasData:!!r},n))},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,r){this.advancedTracker?this.advancedTracker.trackConversion(e,t,r):this.track("conversion",w({goal:e,value:t},r))},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(r){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,r,n,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(),r=this.computeDomHash(t),this.lastDomHash=r,(t.elements||[]).forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Tracking ".concat(this.knownElementSelectors.size," initial element selectors")),n=this.getCachedConfigForDomHash(r),i=e,e?[3,4]:n&&n.events_to_track?(this.log("Applying cached config for DOM hash:",r),this.mergedConfig={events_to_track:_([],n.events_to_track,!0),tracking_config:n.tracking_config},this.applyGeneratedConfig(n),i=!0,this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:n}),[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,r,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,r){return S(this,void 0,void 0,function(){var n,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(n=c.sent())&&n.events_to_track?(r?(i=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),(o=n.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:n.tracking_config})):this.log("Fresh config has no new events, cache was up-to-date"),n.tracking_config&&(this.mergedConfig.tracking_config=w(w({},this.mergedConfig.tracking_config),n.tracking_config))):(this.mergedConfig={events_to_track:_([],n.events_to_track,!0),tracking_config:n.tracking_config},this.applyGeneratedConfig(n),this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:n})),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=n.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,r,n,i,o,a=this;return T(this,function(s){switch(s.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 r=e.className.split(" ").filter(function(e){return e.trim()}).join(".");return r?".".concat(r):e.tagName.toLowerCase()}return e.tagName.toLowerCase()},[4,new Promise(function(e){return setTimeout(e,500)})];case 1:return s.sent(),t=Array.from(document.body.querySelectorAll('\n button, a, input, select, textarea, form,\n [role=button], [role=link], [onclick], [tabindex], [data-analytics], [data-track],\n [customdata], [data-customdata],\n .card, .btn, .btn-primary, .btn-secondary,\n [id*="card"], [class*="card"], [class*="btn"]\n ')),r=new Set(["img","svg","path","circle","rect","line","polygon","polyline","ellipse","br","hr","meta","link","style","script","noscript","iframe","embed","object","video","audio","source","track","canvas","picture","figure","figcaption","h1","h2","h3","h4","h5","h6","p","span","div","section","article","header","footer","main","nav","aside"]),n=t.filter(function(e){var t=e.tagName.toLowerCase(),n=window.getComputedStyle(e),i="none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity;if(r.has(t)&&!Array.from(e.attributes).some(function(e){var t=e.name.toLowerCase();return t.startsWith("on")||t.startsWith("@")||t.startsWith("v-on:")||t.startsWith("ng-")||t.startsWith("hx-")||t.startsWith("data")||"customdata"===t||"tabindex"===t||"role"===t&&"button"===e.value})&&!e.hasAttribute("onclick"))return!1;var o="button"===t||"a"===t||"input"===t||"select"===t||"textarea"===t||e.hasAttribute("onclick")||"button"===e.getAttribute("role")||e.classList.contains("btn")||e.classList.contains("card")||e.hasAttribute("customdata");return i&&o}),i=new Set,o=n.map(function(t){var r,n,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 o=a.generateElementFingerprint(t);return{tagName:t.tagName.toLowerCase(),selector:e(t),fingerprint:o,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===(r=t.parentElement)||void 0===r?void 0:r.tagName.toLowerCase())||"",index:Array.from((null===(n=t.parentElement)||void 0===n?void 0:n.children)||[]).indexOf(t)}}).filter(function(e){return!i.has(e.fingerprint)&&(i.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 r,n,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]):(r={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()]);case 1:return n=s.sent(),r=w(w({},r),n),i={structure:e},this.config.projectKey&&(i.project_key=this.config.projectKey),t&&(i.domHash=t,i.lastConfigHash=this.lastConfigHash),[4,fetch("".concat(this.config.endpoint,"/api/v1/sdk/config"),{method:"POST",headers:r,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 r={view:{_clicked:"_viewed",_click:"_view"},focus:{_clicked:"_focused",_click:"_focus"},blur:{_clicked:"_blurred",_click:"_blur"}}[t];if(!r)return e;for(var n=0,i=Object.entries(r);n<i.length;n++){var o=i[n],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 r=t.includes('"')?t.replace(/"/g,'\\"'):t;return'[id="'.concat(r,'"]')}}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 r=t.sanitizeSelector(e.element_selector);try{var n=document.querySelectorAll(r),i=e.metadata_rules||{extract_customdata:!0,extract_text:!0};n.length>0?n.forEach(function(r){var o=t.attachedListeners.get(r);o||(o=new Set,t.attachedListeners.set(r,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&&(r.addEventListener("click",function(r){var n,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===(n=e.element_selector)||void 0===n?void 0:n.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=r.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(n).indexOf(r),c=r.id||r.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(r){r.forEach(function(r){if(r.isIntersecting&&r.intersectionRatio>=.5){var n=r.target;if(t.viewedElements.has(l))return;t.viewedElements.add(l);var o=t.extractElementData(n,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:r.intersectionRatio,timestamp:(new Date).toISOString()}),u.unobserve(n),t.log('View event sent and unobserved: "'.concat(a,'" for "').concat(l,'"'))}})},{threshold:.5});u.observe(r),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||(r.addEventListener(a,function(){var n=r,o=t.extractElementData(n,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(r,'" (original: "').concat(e.element_selector,'")'))}catch(n){t.log('Error applying selector "'.concat(r,'" (original: "').concat(e.element_selector,'"):'),n)}}),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 r=e.getBoundingClientRect(),n={tagName:e.tagName.toLowerCase(),id:e.id||"",className:e.className||"",textContent:(e.textContent||"").trim().substring(0,100),position:{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(r.width),height:Math.round(r.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,r={},n=e.getAttribute("customdata")||e.dataset.customdata;if(n)try{var i=JSON.parse(n);r.customdata=i,i.name&&(r.itemName=i.name),i.displayedTitle&&(r.section=i.displayedTitle),i.title&&(r.title=i.title),i.category&&(r.category=i.category),i.id&&(r.itemId=i.id)}catch(e){var o=n.match(/"name"\s*:\s*"([^"]+)"/);o&&(r.itemName=o[1]);var a=n.match(/"(?:displayedTitle|title)"\s*:\s*"([^"]+)"/);a&&(r.section=a[1])}var s=e.id;if(s){r.elementId=s;var c=s.split("_");if(c.length>=2){var l=c.slice(1).join("_");!r.itemName&&l&&(r.itemName=l)}}var u=null===(t=e.textContent)||void 0===t?void 0:t.trim();u&&u.length<100&&(r.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];!r[p]&&m&&(r["data_".concat(p)]=m)}return r}(e);Object.keys(i).length>0&&(n.enriched=i,i.itemName&&(n.itemName=i.itemName),i.section&&(n.section=i.section),i.category&&(n.category=i.category))}return this.config.debug&&(n.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},{})),n},e.prototype.sendToWorker=function(e,t){var r;if(this.shouldSampleEvents()){var n=new Date,i=this.getCommonEventData(),o=w({event:e,properties:t,timestamp:n.getTime(),created_at:n.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===(r=this.projectSettings)||void 0===r?void 0:r.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,r,n,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===(r=this.config.workerConfig)||void 0===r?void 0:r.batchSize)||10,batchInterval:(null===(n=this.config.workerConfig)||void 0===n?void 0:n.batchInterval)||5e3,headers:w(w({"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 r;if(void 0===t&&(t={}),this.shouldSampleEvents()){this.journeyTracker.trackEvent(e,t);var n=this.journeyTracker.getContext(),i=new Date,o=this.getCommonEventData(),a=w({event:e,properties:w(w({},t),{journeyContext:{sequenceIndex:n.eventCount-1,timeSinceLastEvent:n.timeSinceLastEvent,journeyDuration:Date.now()-n.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===(r=this.projectSettings)||void 0===r?void 0:r.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,r;return T(this,function(n){switch(n.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];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.sendBatch(e)];case 2:return n.sent(),this.batchRetryCount=0,[3,4];case 3:return t=n.sent(),this.batchRetryCount++,this.log("Batch send failed. Retry attempt ".concat(this.batchRetryCount," of ").concat(this.maxBatchRetries,"."),t),(r=this.eventQueue).unshift.apply(r,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,r,n,i,o,a,s;return T(this,function(c){switch(c.label){case 0:return t="".concat(this.config.endpoint,"/api/v1/events"),r={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()];case 1:n=c.sent(),r=w(w({},r),n),this.config.apiDetails&&this.config.apiDetails.apiEndPoint&&(t=this.config.apiDetails.apiEndPoint,this.config.apiDetails.headers&&(r=w(w({},r),this.config.apiDetails.headers))),i=this.config.clientId||"5288aa7d-1b7c-481e-958d-eb9b8e951f14",o=e.map(function(e){return w({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:r,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,r=window.location.hash,n=document.referrer,i={};return new URLSearchParams(window.location.search).forEach(function(e,t){i[t]=e}),{url:e,path:t,hash:r||void 0,referrer:n||void 0,queryParams:Object.keys(i).length>0?i: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 r=this.userManager.getUserIdentificationEvent(e);this.userManager.identifyUser(e,t),this.track("user_identified",r),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,r,n,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 r=o.sent(),[4,fetch(t,{method:"POST",headers:w({"Content-Type":"application/json"},r),body:JSON.stringify({client_id:this.config.clientId,user_id:this.userManager.getUserId(),session_id:this.sessionId,journey:e})})];case 2:return(n=o.sent()).ok||console.error("[AInamika SDK] Failed to send journey for analysis:",n.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),r=2166136261,n=0;n<t.length;n++)r^=t.charCodeAt(n),r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);return(r>>>0).toString(16)},e.prototype.generateElementFingerprint=function(e){var t=[],r=e.getAttribute("data-testid"),n=e.getAttribute("data-track"),i=e.getAttribute("data-analytics");r&&t.push("testid:".concat(r)),n&&t.push("track:".concat(n)),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,r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),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")||"{}"),r=t[e];return r?r.events_to_track?(t[e]={config:r,lastAccessed:Date.now(),createdAt:Date.now()},localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),r):(r.lastAccessed=Date.now(),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),r.config):null}catch(e){return null}},e.prototype.setCachedConfigForDomHash=function(e,t){var r=this;try{var n=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}");n[e]={config:t,lastAccessed:Date.now(),createdAt:Date.now()};var i=Object.keys(n);i.length>this.MAX_CACHED_CONFIGS&&i.sort(function(e,t){return(n[e].lastAccessed||n[e].createdAt||0)-(n[t].lastAccessed||n[t].createdAt||0)}).slice(0,i.length-this.MAX_CACHED_CONFIGS).forEach(function(e){delete n[e],r.log("Evicted old config cache: ".concat(e))}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(n))}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 r=t.sort(function(t,r){var n=e[t].lastAccessed||e[t].createdAt||0;return(e[r].lastAccessed||e[r].createdAt||0)-n}),n={};r.slice(0,5).forEach(function(t){n[t]=e[t]}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(n)),this.log("Cleared config cache, kept ".concat(Object.keys(n).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,r,n,i,o,a,s,c=this;return T(this,function(l){switch(l.label){case 0:return[4,this.getDOMStructure()];case 1:return e=l.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,r=e.elements||[],0===(n=r.filter(function(e){var t=e.selector||"";return!(!t||c.knownElementSelectors.has(t))})).length?(this.log("No new elements detected, skipping config fetch."),[2]):(i=n.filter(function(e){var t=(e.tagName||"").toLowerCase();return!!["button","a","input","select","textarea"].includes(t)||!0===e.isInteractive||!!e.attributes&&Object.keys(e.attributes).some(function(t){var r=t.toLowerCase();return r.startsWith("on")||r.startsWith("@")||r.startsWith("v-on:")||r.startsWith("ng-")||r.startsWith("hx-")||r.startsWith("data")||"customdata"===r||"tabindex"===r||"role"===r&&"button"===e.attributes[t]})}),n.forEach(function(e){e.selector&&c.knownElementSelectors.add(e.selector)}),0===i.length?(this.log("No interactive elements among ".concat(n.length," new elements, skipping config fetch.")),[2]):(this.log("Found ".concat(i.length," interactive elements out of ").concat(n.length," new elements")),(o=this.getCachedConfigForDomHash(t))?(this.log("Reusing cached config for DOM hash",t),this.mergeAndApplyConfig(o),[2]):(a={elements:i},this.log("Fetching config for interactive elements only:",i.length),[4,this.fetchGeneratedConfig(a,t)]))));case 2:return(s=l.sent())&&s.events_to_track?(this.mergeAndApplyConfig(s),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=s.config_hash||"",this.log("Fetched and merged config for interactive elements",{newEvents:s.events_to_track.length,totalEvents:this.mergedConfig.events_to_track.length})):this.log("No valid config returned for interactive 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 r=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),n=e.events_to_track.filter(function(e){return!r.has(e.element_selector)});n.length>0&&((t=this.mergedConfig.events_to_track).push.apply(t,n),this.log("Merged ".concat(n.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)),n.length>0&&this.applyGeneratedConfig({events_to_track:n,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())})},_=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])}}},T=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:!1,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 _(this,function(o){switch(o.label){case 0:if(this.isInitialized)return[2];if(this.isInitialized=!0,this.sendSessionStartEvent(),!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 _(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 _(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 _(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 _(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([],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 _(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:T([],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:T([],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 _(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:T([],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,a=this;return _(this,function(s){switch(s.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 s.sent(),t=Array.from(document.body.querySelectorAll('\n button, a, input, select, textarea, form,\n [role=button], [role=link], [onclick], [tabindex], [data-analytics], [data-track],\n [customdata], [data-customdata],\n .card, .btn, .btn-primary, .btn-secondary,\n [id*="card"], [class*="card"], [class*="btn"]\n ')),n=new Set(["img","svg","path","circle","rect","line","polygon","polyline","ellipse","br","hr","meta","link","style","script","noscript","iframe","embed","object","video","audio","source","track","canvas","picture","figure","figcaption","h1","h2","h3","h4","h5","h6","p","span","div","section","article","header","footer","main","nav","aside"]),r=t.filter(function(e){var t=e.tagName.toLowerCase(),r=window.getComputedStyle(e),i="none"!==r.display&&"hidden"!==r.visibility&&"0"!==r.opacity;if(n.has(t)&&!(Array.from(e.attributes).some(function(e){var t=e.name.toLowerCase();return t.startsWith("on")||t.startsWith("@")||t.startsWith("v-on:")||t.startsWith("ng-")||t.startsWith("hx-")||t.startsWith("data")||"customdata"===t||"tabindex"===t||"role"===t&&"button"===e.value})||e.hasAttribute("onclick")||a.hasFrameworkClickHandler(e)))return!1;var o="button"===t||"a"===t||"input"===t||"select"===t||"textarea"===t||e.hasAttribute("onclick")||"button"===e.getAttribute("role")||e.classList.contains("btn")||e.classList.contains("card")||e.hasAttribute("customdata")||a.hasFrameworkClickHandler(e);return i&&o}),i=new Set,o=r.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 o=a.generateElementFingerprint(t);return{tagName:t.tagName.toLowerCase(),selector:e(t),fingerprint:o,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!i.has(e.fingerprint)&&(i.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,i,o,a;return _(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},this.config.projectKey&&(i.project_key=this.config.projectKey),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,'"'))),"change"!==a&&"input"!==a||(n.addEventListener(a,function(){var r=n,o=t.extractElementData(r,i);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:a,category:e.category||"uncategorized",element:o,value:r.value||"",timestamp:(new Date).toISOString()})}),t.log("Attached ".concat(a,' listener for "').concat(e.event_name,'" on "').concat(e.element_selector,'"'))),"submit"===a&&(n.addEventListener("submit",function(r){var o=n,a=t.extractElementData(o,i);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"submit",category:e.category||"uncategorized",element:a,timestamp:(new Date).toISOString()})}),t.log('Attached submit listener for "'.concat(e.event_name,'" 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 _(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 _(this,function(t){switch(t.label){case 0:return 0===this.eventQueue.length?[2]:(e=T([],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 _(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 _(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.sendSessionStartEvent=function(){var e,t,n,r,i,o,a,s;try{var c=new Date,l=this.getPageContext(),u={userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?T([],navigator.languages,!0):[navigator.language],platform:navigator.platform,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,screenWidth:null===(e=window.screen)||void 0===e?void 0:e.width,screenHeight:null===(t=window.screen)||void 0===t?void 0:t.height,screenColorDepth:null===(n=window.screen)||void 0===n?void 0:n.colorDepth,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:c.getTimezoneOffset()},h={sessionId:this.sessionId,userIdentifier:this.userIdentifier,isNewSession:!0,sdkVersion:"1.2.7",initTimestamp:c.toISOString()},d=b({event:"session_start",properties:b(b(b({},u),h),{landingPage:l.path,landingUrl:l.url,referrer:l.referrer||"direct",entryTitle:l.title,utmSource:null===(r=l.queryParams)||void 0===r?void 0:r.utm_source,utmMedium:null===(i=l.queryParams)||void 0===i?void 0:i.utm_medium,utmCampaign:null===(o=l.queryParams)||void 0===o?void 0:o.utm_campaign,utmTerm:null===(a=l.queryParams)||void 0===a?void 0:a.utm_term,utmContent:null===(s=l.queryParams)||void 0===s?void 0:s.utm_content}),timestamp:c.getTime(),created_at:c.toISOString(),userId:this.userManager.getUserId(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,pageContext:l},this.config.extraConfig||{});this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:d}):this.eventQueue.push(d),this.log("Session start event sent",d)}catch(e){this.log("Failed to send session_start event:",e)}},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 _(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 _(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 _(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 _(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 _(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 _(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.hasFrameworkClickHandler=function(e){var t,n,r,i,o,a,s,c,l;try{var u=window.getComputedStyle(e);if("pointer"===u.cursor)return!0;for(var h=Object.keys(e),d=0,g=h;d<g.length;d++){if((w=g[d]).startsWith("__reactProps$")){var f=e[w];if(f&&("function"==typeof f.onClick||"function"==typeof f.onMouseDown||"function"==typeof f.onPointerDown||"function"==typeof f.onTouchStart))return!0}if(w.startsWith("__reactFiber$")||w.startsWith("__reactInternalInstance$")){var p=e[w];if((null===(t=null==p?void 0:p.memoizedProps)||void 0===t?void 0:t.onClick)||(null===(n=null==p?void 0:p.memoizedProps)||void 0===n?void 0:n.onMouseDown)||(null===(r=null==p?void 0:p.memoizedProps)||void 0===r?void 0:r.onPointerDown))return!0}}var m=e.__vue__;if(m&&((null===(i=m.$listeners)||void 0===i?void 0:i.click)||(null===(o=m.$props)||void 0===o?void 0:o.onClick)||(null===(a=m._events)||void 0===a?void 0:a.click)))return!0;var v=e.__vueParentComponent;if(null===(s=null==v?void 0:v.props)||void 0===s?void 0:s.onClick)return!0;if(e.__ngContext__)return!0;for(var y=0,k=h;y<k.length;y++){var w;if((w=k[y]).startsWith("__svelte")){var b=e[w];if(b&&"object"==typeof b)return!0}}if(window.jQuery){window.jQuery(e);var S=null===(l=(c=window.jQuery)._data)||void 0===l?void 0:l.call(c,e,"events");if((null==S?void 0:S.click)||(null==S?void 0:S.mousedown)||(null==S?void 0:S.pointerdown))return!0}if("none"!==u.pointerEvents&&"transparent"!==u.backgroundColor&&"rgba(0, 0, 0, 0)"!==u.backgroundColor&&"0px"!==u.borderRadius){var _=(e.textContent||"").trim().toLowerCase();if(["submit","save","cancel","ok","confirm","delete","edit","update","add","remove","buy","order","next","prev","back","continue","close","open","click","tap"].some(function(e){return _.includes(e)}))return!0}return!1}catch(e){return this.log("Error checking framework click handler:",e),!1}},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,c=this;return _(this,function(l){switch(l.label){case 0:return[4,this.getDOMStructure()];case 1:return e=l.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||c.knownElementSelectors.has(t))})).length?(this.log("No new elements detected, skipping config fetch."),[2]):(i=r.filter(function(e){var t=(e.tagName||"").toLowerCase();if(["button","a","input","select","textarea"].includes(t))return!0;if(!0===e.isInteractive)return!0;if(e.attributes&&Object.keys(e.attributes).some(function(t){var n=t.toLowerCase();return n.startsWith("on")||n.startsWith("@")||n.startsWith("v-on:")||n.startsWith("ng-")||n.startsWith("hx-")||n.startsWith("data")||"customdata"===n||"tabindex"===n||"role"===n&&"button"===e.attributes[t]}))return!0;if(e.selector)try{var n=c.sanitizeSelector(e.selector),r=document.querySelector(n);if(r&&c.hasFrameworkClickHandler(r))return!0}catch(e){}return!1}),r.forEach(function(e){e.selector&&c.knownElementSelectors.add(e.selector)}),0===i.length?(this.log("No interactive elements among ".concat(r.length," new elements, skipping config fetch.")),[2]):(this.log("Found ".concat(i.length," interactive elements out of ").concat(r.length," new elements")),(o=this.getCachedConfigForDomHash(t))?(this.log("Reusing cached config for DOM hash",t),this.mergeAndApplyConfig(o),[2]):(a={elements:i},this.log("Fetching config for interactive elements only:",i.length),[4,this.fetchGeneratedConfig(a,t)]))));case 2:return(s=l.sent())&&s.events_to_track?(this.mergeAndApplyConfig(s),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=s.config_hash||"",this.log("Fetched and merged config for interactive elements",{newEvents:s.events_to_track.length,totalEvents:this.mergedConfig.events_to_track.length})):this.log("No valid config returned for interactive 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
|