cap-hydra-web-sdk 1.0.1 → 1.0.2

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 CHANGED
@@ -2,19 +2,6 @@
2
2
 
3
3
  A comprehensive guide for integrating the Hydra WebSDK into your web application for event tracking and analytics.
4
4
 
5
- ## Table of Contents
6
-
7
- 1. [Quick Start](#quick-start)
8
- 2. [Installation](#installation)
9
- 3. [Basic Configuration](#basic-configuration)
10
- 4. [Initialization](#initialization)
11
- 5. [User Management](#user-management)
12
- 6. [Event Tracking](#event-tracking)
13
- 7. [Advanced Features](#advanced-features)
14
- 8. [Best Practices](#best-practices)
15
- 9. [Troubleshooting](#troubleshooting)
16
- 10. [Support](#support)
17
-
18
5
  ## Quick Start
19
6
 
20
7
  Here's a minimal example to get you started:
@@ -31,10 +18,10 @@ const sdk = new WebSDK({
31
18
  debugLevel: 'INFO',
32
19
  });
33
20
 
34
- // Initialize (fire-and-forget - returns immediately)
21
+ // Initialize
35
22
  sdk.init();
36
23
 
37
- // Track events (fire-and-forget - returns immediately)
24
+ // Track events
38
25
  sdk.pushEvent('button_click', {
39
26
  button_id: 'submit',
40
27
  page: 'checkout',
@@ -97,46 +84,8 @@ const config = {
97
84
  };
98
85
  ```
99
86
 
100
- ### Debug Levels
101
-
102
- - **VERBOSE**: Most detailed logging including trace information
103
- - **DEBUG**: All logs including detailed debugging information
104
- - **INFO**: General information and important events
105
- - **WARN**: Warning messages and potential issues
106
- - **ERROR**: Only error messages
107
- - **NONE**: No logging (production recommended)
108
-
109
87
  ## Initialization
110
88
 
111
- ### Fire-and-Forget Initialization
112
-
113
- ```javascript
114
- const sdk = new WebSDK(config);
115
-
116
- // Fire-and-forget initialization - returns immediately
117
- sdk.init();
118
-
119
- // You can immediately start tracking events
120
- // The SDK will queue events until initialization completes
121
- sdk.pushEvent('app_started', { timestamp: Date.now() });
122
-
123
- console.log('SDK initialization started in background');
124
- ```
125
-
126
- ### Error Handling
127
-
128
- Since initialization is fire-and-forget, errors are handled internally and logged.
129
-
130
- ```javascript
131
- const sdk = new WebSDK(config);
132
-
133
- // Start initialization
134
- sdk.init();
135
-
136
- // Events will be queued and processed once initialization completes
137
- sdk.pushEvent('page_view', { page: 'home' });
138
- ```
139
-
140
89
  ### React Integration
141
90
 
142
91
  ```jsx
@@ -145,7 +94,7 @@ import { WebSDK } from 'cap-hydra-web-sdk';
145
94
 
146
95
  function App() {
147
96
  useEffect(() => {
148
- // Initialize SDK (fire-and-forget)
97
+ // Initialize SDK
149
98
  const webSDK = new WebSDK(config);
150
99
  webSDK.init();
151
100
 
@@ -166,7 +115,6 @@ function App() {
166
115
  // In other components, use the global SDK instance
167
116
  function Dashboard() {
168
117
  const handleButtonClick = () => {
169
- // Fire-and-forget event tracking
170
118
  window.hydraSDK.pushEvent('button_click', {
171
119
  button_id: 'dashboard_action',
172
120
  timestamp: Date.now(),
@@ -181,12 +129,9 @@ function Dashboard() {
181
129
 
182
130
  ### User Lifecycle Events
183
131
 
184
- All user lifecycle methods now use the **fire-and-forget** approach for optimal performance:
185
-
186
132
  #### User Sign In
187
133
 
188
134
  ```javascript
189
- // Fire-and-forget - returns immediately
190
135
  sdk.pushUserSignin(
191
136
  'user-12345', // cuid (required)
192
137
  'John', // firstName (optional)
@@ -205,7 +150,6 @@ sdk.pushUserSignin(
205
150
  #### User Sign Up
206
151
 
207
152
  ```javascript
208
- // Fire-and-forget - returns immediately
209
153
  sdk.pushUserSignup(
210
154
  'user-12345', // cuid (required)
211
155
  'John', // firstName (required)
@@ -224,7 +168,6 @@ sdk.pushUserSignup(
224
168
  #### User Profile Update
225
169
 
226
170
  ```javascript
227
- // Fire-and-forget - returns immediately
228
171
  sdk.pushUserUpdate(
229
172
  'user-12345', // cuid (required)
230
173
  'John', // firstName (optional)
@@ -242,7 +185,6 @@ sdk.pushUserUpdate(
242
185
  #### User Sign Out
243
186
 
244
187
  ```javascript
245
- // Fire-and-forget - returns immediately
246
188
  sdk.pushUserSignOut('user-12345'); // cuid (required)
247
189
  ```
248
190
 
@@ -250,21 +192,18 @@ sdk.pushUserSignOut('user-12345'); // cuid (required)
250
192
 
251
193
  ### Behavioral Events
252
194
 
253
- Track user interactions and behaviors using the **fire-and-forget** approach for optimal performance:
254
-
255
- **Function Signature:**
195
+ **Push Event:**
256
196
 
257
197
  ```javascript
258
198
  sdk.pushEvent(eventName, attributes);
259
- // eventName: string (required) - The name of the event
260
- // attributes: Record<string, unknown> (optional) - Event attributes/properties
261
- // Returns: void (fire-and-forget - executes in background)
199
+ // eventName (required)
200
+ // attributes (optional)
262
201
  ```
263
202
 
264
203
  **Common Behavioral Events:**
265
204
 
266
205
  ```javascript
267
- // Button clicks (fire-and-forget)
206
+ // Button clicks
268
207
  sdk.pushEvent('button_click', {
269
208
  button_id: 'checkout',
270
209
  button_text: 'Complete Purchase',
@@ -272,7 +211,7 @@ sdk.pushEvent('button_click', {
272
211
  section: 'payment',
273
212
  });
274
213
 
275
- // E-commerce events (fire-and-forget)
214
+ // E-commerce events
276
215
  sdk.pushEvent('add_to_cart', {
277
216
  product_id: 'shoe-123',
278
217
  product_name: 'Nike Air Max',
@@ -282,221 +221,10 @@ sdk.pushEvent('add_to_cart', {
282
221
  cart_total: 259.98,
283
222
  });
284
223
 
285
- // Page navigation (fire-and-forget)
224
+ // Page navigation
286
225
  sdk.pushEvent('page_view', {
287
226
  page: '/dashboard',
288
227
  referrer: '/home',
289
228
  timestamp: Date.now(),
290
229
  });
291
230
  ```
292
-
293
- ## Advanced Features
294
-
295
- ### Event Batching
296
-
297
- The SDK automatically batches events for efficient network usage with the **fire-and-forget** approach:
298
-
299
- - **Batch Size**: 50 events maximum per request
300
- - **Auto Flush**: Events are automatically sent when batch is full
301
- - **Background Processing**: All batching happens in background threads
302
- - **Retry Logic**: Failed events are retried with exponential backoff
303
- - **Persistence**: Events are stored locally until successfully sent
304
- - **Race Condition Protection**: Events are queued if initialization is still in progress
305
-
306
- ### Retry Configuration
307
-
308
- The SDK includes robust retry logic that works seamlessly with fire-and-forget:
309
-
310
- - **Infinite Retries**: Events retry indefinitely until successful
311
- - **Default Retry Delays**: [60s, 120s, 240s, 480s, 900s] (customizable via config)
312
- - **Constant Delay**: After exhausting array, continues with last delay value
313
- - **Retryable Codes**: 408, 429, 500, 502, 503, 504, 401
314
- - **Background Retries**: All retry logic executes in background without blocking UI
315
-
316
- ### Configurable Retry Delays
317
-
318
- ```javascript
319
- const config = {
320
- // ... other config
321
- retryDelays: [30000, 60000, 120000], // Custom: 30s, 1min, 2min, then 2min indefinitely
322
- };
323
- ```
324
-
325
- ## Best Practices
326
-
327
- ### 1. Initialize Early with Fire-and-Forget
328
-
329
- ```javascript
330
- // Initialize SDK as early as possible in your app lifecycle
331
- document.addEventListener('DOMContentLoaded', () => {
332
- const sdk = new WebSDK(config);
333
- // Fire-and-forget initialization
334
- sdk.init();
335
-
336
- // Store globally for immediate use
337
- window.hydraSDK = sdk;
338
- });
339
- ```
340
-
341
- ### 2. Use Fire-and-Forget for All Tracking
342
-
343
- ```javascript
344
- // Good: Fire-and-forget approach
345
- const handleUserAction = () => {
346
- // Immediate return, processing happens in background
347
- sdk.pushEvent('user_action', { action: 'click' });
348
-
349
- // Continue with your app logic immediately
350
- navigateToNextPage();
351
- };
352
-
353
- // Avoid: Waiting for tracking to complete (old approach)
354
- const handleUserActionOld = async () => {
355
- await sdk.pushEvent('user_action', { action: 'click' }); // Blocks UI
356
- navigateToNextPage();
357
- };
358
- ```
359
-
360
- ### 3. Use Meaningful Event Names
361
-
362
- ```javascript
363
- // Good: Descriptive and consistent (fire-and-forget)
364
- sdk.pushEvent('checkout_step_completed', {
365
- step: 'payment_info',
366
- step_number: 3,
367
- });
368
-
369
- // Avoid: Generic or unclear names
370
- sdk.pushEvent('click', { type: 'button' });
371
- ```
372
-
373
- ### 4. Track Events Immediately
374
-
375
- ```javascript
376
- // With fire-and-forget, you can track events immediately after SDK creation
377
- const sdk = new WebSDK(config);
378
- sdk.init(); // Returns immediately
379
-
380
- // Track events right away - they'll be queued until initialization completes
381
- sdk.pushEvent('app_started', { timestamp: Date.now() });
382
- sdk.pushEvent('page_view', { page: 'home' });
383
- ```
384
-
385
- ## Fire-and-Forget Benefits
386
-
387
- The WebSDK's fire-and-forget approach provides several key advantages:
388
-
389
- ### Performance Benefits
390
-
391
- - **Non-blocking**: All SDK operations return immediately, never blocking your application's UI
392
- - **Background Processing**: Event processing, network requests, and retries happen in background
393
- - **Optimal User Experience**: No delays or freezing during event tracking
394
- - **Race Condition Protection**: Events are safely queued if called before initialization completes
395
-
396
- ### Reliability Benefits
397
-
398
- - **Automatic Queuing**: Events are queued locally until they can be processed
399
- - **Persistent Storage**: Events are stored in IndexedDB and survive page reloads
400
- - **Infinite Retries**: Failed events retry indefinitely with exponential backoff
401
- - **Error Resilience**: Network failures and API errors don't affect your application
402
-
403
- ### Developer Experience Benefits
404
-
405
- - **Simplified Integration**: No need for complex async/await handling
406
- - **Immediate Usage**: Start tracking events immediately after SDK creation
407
- - **No Error Handling Required**: All errors are handled internally with appropriate logging
408
- - **Consistent API**: All methods follow the same fire-and-forget pattern
409
-
410
- ## Troubleshooting
411
-
412
- ### Common Issues
413
-
414
- #### 1. Events Not Being Sent
415
-
416
- Since the SDK uses fire-and-forget, check the browser console for error logs:
417
-
418
- ```javascript
419
- // Enable debug logging to see what's happening
420
- const sdk = new WebSDK({
421
- ...config,
422
- debugLevel: 'DEBUG', // Enable verbose logging
423
- });
424
-
425
- sdk.init();
426
- sdk.pushEvent('test_event', { test: true });
427
-
428
- // Check browser console for logs like:
429
- // "Event queued: test_event"
430
- // "Batch sent successfully"
431
- // "Retry scheduled for failed batch"
432
- ```
433
-
434
- #### 2. Checking Event Storage
435
-
436
- Events are stored locally in IndexedDB. You can inspect them:
437
-
438
- ```javascript
439
- // Open browser DevTools → Application tab → IndexedDB → hydra-websdk
440
- // Look for 'events' object store to see queued events
441
- ```
442
-
443
- #### 3. Network Issues
444
-
445
- Monitor network requests in browser dev tools:
446
-
447
- 1. Open Developer Tools (F12)
448
- 2. Go to Network tab
449
- 3. Filter by XHR/Fetch
450
- 4. Look for requests to your API endpoint
451
- 5. Check for 4xx/5xx errors that might indicate configuration issues
452
-
453
- ### Debug Mode
454
-
455
- Enable detailed logging for troubleshooting:
456
-
457
- ```javascript
458
- const sdk = new WebSDK({
459
- ...config,
460
- debugLevel: 'DEBUG', // Enable verbose logging
461
- });
462
-
463
- // Console will show detailed logs:
464
- // - "SDK initialization started"
465
- // - "Event queued: event_name"
466
- // - "Batch processing started"
467
- // - "Network request sent"
468
- // - "Retry scheduled: attempt 1"
469
- ```
470
-
471
- ### Performance Monitoring
472
-
473
- Since the SDK is fire-and-forget, you can monitor its performance impact:
474
-
475
- ```javascript
476
- // Monitor memory usage
477
- console.log('Memory usage:', performance.memory?.usedJSHeapSize / 1024 / 1024, 'MB');
478
-
479
- // Check IndexedDB storage
480
- // DevTools → Application → Storage → IndexedDB → hydra-websdk
481
- ```
482
-
483
- ### Storage Inspection
484
-
485
- Check stored events and configuration in browser:
486
-
487
- 1. **IndexedDB**: DevTools → Application → IndexedDB → hydra-websdk
488
- - `events` store: Queued events waiting to be sent
489
- - `config` store: SDK configuration and state
490
-
491
- 2. **Console Logs**: Check for SDK activity
492
- - Event queuing messages
493
- - Batch processing status
494
- - Network request results
495
- - Retry attempt logs
496
-
497
- ## Support
498
-
499
- ### Version Information
500
-
501
- - Current Version: 1.0.0
502
- - Minimum Browser Support: Chrome 61+, Firefox 60+, Safari 10+, Edge 16+
package/dist/index.esm.js CHANGED
@@ -145,7 +145,7 @@ const USER_EVENTS = {
145
145
  USER_UPDATE: 'user_update',
146
146
  USER_SIGNOUT: 'user_signout',
147
147
  };
148
- const SDK_VERSION = "1.0.1";
148
+ const SDK_VERSION = "1.0.2";
149
149
 
150
150
  /**
151
151
  * HTTP Client
package/dist/index.js CHANGED
@@ -147,7 +147,7 @@ const USER_EVENTS = {
147
147
  USER_UPDATE: 'user_update',
148
148
  USER_SIGNOUT: 'user_signout',
149
149
  };
150
- const SDK_VERSION = "1.0.1";
150
+ const SDK_VERSION = "1.0.2";
151
151
 
152
152
  /**
153
153
  * HTTP Client
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).WebSDK=e()}(this,function(){"use strict";const t="/auth/nonce",e="/mapp/events",s=6e4,i={CATEGORIES:{USER:"USER",BEHAVIORAL:"BE"},STATUSES:{PENDING:"pending"},BATCH_SIZE:50,MAX_RETRY_ATTEMPTS:5,DEFAULT_RETRY_DELAYS:[6e4,12e4,24e4,48e4,9e5],RETRYABLE_HTTP_CODES:[408,429,500,502,503,504,401],GLOBAL_SUCCESS_CODE:200,PARTIAL_SUCCESS_CODE:201},n={NONCE_DATA:"websdk_nonce_data",USER_CONTEXT:"websdk_user_context",DEVICE_ID:"websdk_device_id",SESSION_ID:"websdk_session_id"},a=n;function r(t,e,s){const i=n[t],a=[];return e&&a.push(e),s&&a.push(s),a.length>0?`${a.join("_")}_${i}`:i}const o="websdk_storage_test",h="test_value",c="INIT_ERROR",d="AUTH_ERROR",u="NETWORK_ERROR",l="EVENT_ERROR",w="WebSDK initialized successfully",y="Failed to initialize WebSDK",f="WebSDK destroyed successfully",g="Authentication successful",m="Authentication failed",v="AuthManager initialized successfully",E="Nonce request successful",p="Nonce request failed",S="Request signature generated successfully",I="Failed to store nonce data",x="Failed to restore nonce data from storage",_="Failed to clear stored nonce data",D="EventTracker initialized successfully",b="EventTracker destroyed successfully",N="Failed to track event",k="Events sent successfully",U="Failed to send events",T="Failed to initialize storage:",A="Storage test failed:",C="Storage read/write test failed",R="StorageManager destroyed successfully",O="Error during storage cleanup:",z="Failed to track user signin event",M="Failed to track user signup event",$="Failed to track user update event",F="Failed to track user signout event",P="Failed to track behavioral event",B="web",q="",W="",L="",K="user_signin",Q="user_signup",H="user_update",X="user_signout",V="1.0.1";class J{constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,"")}async request(t,e={}){const{method:s="GET",headers:i={},body:n}=e,a=!t||t.startsWith("/")?t:`/${t}`,r=`${this.baseUrl}${a}`;try{const t={method:s,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):null},e=await fetch(r,t);if(!e.ok){const t=await e.text();throw new Error(`HTTP ${e.status}: ${e.statusText} - ${t}`)}return await e.json()}catch(t){throw this.handleError(t)}}handleError(t){return t instanceof Error?"AbortError"===t.name?{code:u,message:"Request timeout",details:t}:t.message.includes("HTTP 401")||t.message.includes("HTTP 403")?{code:d,message:"Authentication failed",details:t}:(t.message.includes("HTTP"),{code:u,message:t.message,details:t}):{code:u,message:`Unknown error: ${String(t)}`,details:t}}async get(t,e={}){return this.request(t,{...e,method:"GET"})}async post(t,e,s={}){return this.request(t,{...s,method:"POST",body:e})}async put(t,e,s={}){return this.request(t,{...s,method:"PUT",body:e})}async delete(t,e={}){return this.request(t,{...e,method:"DELETE"})}}function G(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function j(){return`session_${G()}`}async function Y(t,e,s,i){try{const n=i||Z(),a=function(t){const e=Object.keys(t).sort();return e.map(e=>`${e}=${t[e]}`).join("&")}({nonce:e,account_id:s,device_id:n,timestamp:Date.now(),payload:JSON.stringify(t,Object.keys(t).sort())}),r=await async function(t,e){const s=`${t}:${e}:cap-hydra-web-sdk`,i=(new TextEncoder).encode(s),n=await crypto.subtle.digest("SHA-256",i);return await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"])}(s,n);return await async function(t,e){const s=(new TextEncoder).encode(t),i=await crypto.subtle.sign("HMAC",e,s);return btoa(String.fromCharCode(...new Uint8Array(i)))}(a,r)}catch(t){throw new Error(`Signature generation failed: ${t instanceof Error?t.message:"Unknown error"}`)}}function Z(){const t=a.DEVICE_ID,e=localStorage.getItem(t);if(e)return e;const s=G();return localStorage.setItem(t,s),s}function tt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function et(){return window.location.hostname||"localhost"}function st(t){const e=function(){const t=navigator.userAgent;let e="Unknown",s="Unknown";if(t.includes("Chrome")){e="Chrome";const i=t.match(/Chrome\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Firefox")){e="Firefox";const i=t.match(/Firefox\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Safari")&&!t.includes("Chrome")){e="Safari";const i=t.match(/Version\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Edge")){e="Edge";const i=t.match(/Edge\/([0-9.]+)/);s=i?.[1]??"Unknown"}let i="Unknown",n="Unknown";if(t.includes("Windows"))i="Windows",t.includes("Windows NT 10.0")?n="10":t.includes("Windows NT 6.3")?n="8.1":t.includes("Windows NT 6.2")?n="8":t.includes("Windows NT 6.1")&&(n="7");else if(t.includes("Mac OS X")){i="macOS";const e=t.match(/Mac OS X ([0-9_]+)/);n=e?.[1]?.replace(/_/g,".")??"Unknown"}else if(t.includes("Linux"))i="Linux",n="Unknown";else if(t.includes("Android")){i="Android";const e=t.match(/Android ([0-9.]+)/);n=e?.[1]??"Unknown"}else if(t.includes("iPhone")||t.includes("iPad")){i="iOS";const e=t.match(/OS ([0-9_]+)/);n=e?.[1]?.replace(/_/g,".")??"Unknown"}return{browserName:e,browserVersion:s,osName:i,osVersion:n}}(),s={width:window.innerWidth||document.documentElement.clientWidth||0,height:window.innerHeight||document.documentElement.clientHeight||0},i=Z();return{os_version:e.osVersion,country_code:t.country_code,os_name:e.osName,viewport_width:s.width,country:t.country,viewport_height:s.height,device_id:i,bundle_identifier:et(),last_seen:(new Date).toISOString(),city:t.city,sdk_version:V,platform:"web",browser_name:e.browserName,browser_version:e.browserVersion,browser_language:navigator.language||navigator.languages&&navigator.languages[0]||"en-US",timezone:tt()}}class it{constructor(t,e,s){this.httpClient=new J(t),this.logger=e,this.accountId=s}async getNonce(e,s){const i=s||Z();this.logger.info("Requesting nonce",{accountId:this.accountId,bundleIdentifier:e,deviceId:i});const n={account_id:this.accountId,bundle_identifier:e,device_id:i,timestamp:Date.now(),os_name:B};try{const e=await this.httpClient.post(t,n);return this.logger.info(E,{challengeId:e.challenge_id,expiresAt:e.expires_at}),e}catch(t){throw this.logger.error(p,t),t}}async sendEvents(t,s,i,n,a,r){this.logger.info("Sending events",{eventCount:t.length,cuid:s,challengeId:a});const o=r||Z(),h={system_data:st(i),request_id:G(),events:t,cuid:s};try{const s=await Y({...h,nonce:n,challenge_id:a},n,this.accountId,o);this.logger.info(S,{requestId:h.request_id,challengeId:a});const i={"X-Cap-Nonce":n,"X-Cap-Challenge-ID":a,"X-Cap-Signature":s,"X-Cap-Device-ID":o},r=await this.httpClient.post(e,h,{headers:i});return this.logger.info(k,{requestId:h.request_id,eventCount:t.length,success:r.status.success}),r}catch(e){throw this.logger.error(U,{requestId:h.request_id,eventCount:t.length,error:e}),e}}}class nt{constructor(t="WebSDK",e=2,s="data"){this.db=null,this.dbName=t,this.version=e,this.storeName=s,this.eventsStoreName="events"}async openDB(){return this.db?this.db:new Promise((t,e)=>{const s=indexedDB.open(this.dbName,this.version);s.onerror=()=>e(s.error),s.onsuccess=()=>{this.db=s.result,t(this.db)},s.onupgradeneeded=t=>{const e=t.target.result;if(e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName),!e.objectStoreNames.contains(this.eventsStoreName)){const t=e.createObjectStore(this.eventsStoreName,{keyPath:"id"});t.createIndex("timestamp","timestamp",{unique:!1}),t.createIndex("status","status",{unique:!1})}}})}async getItem(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.storeName],"readonly").objectStore(this.storeName).get(t);n.onerror=()=>i(n.error),n.onsuccess=()=>{const t=n.result;s(null==t?null:"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):String(t))}})}async setItem(t,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(e,t);a.onerror=()=>n(a.error),a.onsuccess=()=>i()})}async removeItem(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(t);n.onerror=()=>i(n.error),n.onsuccess=()=>s()})}async clear(){const t=await this.openDB();return new Promise((e,s)=>{const i=t.transaction([this.storeName],"readwrite").objectStore(this.storeName).clear();i.onerror=()=>s(i.error),i.onsuccess=()=>e()})}async close(){this.db&&(this.db.close(),this.db=null)}async addEvent(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName).add(t);n.onerror=()=>i(n.error),n.onsuccess=()=>s()})}async getOldestPendingEvents(t=50,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).index("timestamp").openCursor(),r=[];let o=0;a.onerror=()=>n(a.error),a.onsuccess=s=>{const n=s.target.result;if(n&&o<t){const t=n.value;"pending"===t.status&&t.accountId===e&&(r.push(t),o++),n.continue()}else i(r)}})}async updateEventStatus(t,e,s,i){const n=await this.openDB();return new Promise((a,r)=>{const o=n.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName),h=o.get(t);h.onerror=()=>r(h.error),h.onsuccess=()=>{const n=h.result;if(n){n.status=e,n.lastAttempt=Date.now(),s&&(n.error=s),void 0!==i&&(n.attempts=i);const t=o.put(n);t.onerror=()=>r(t.error),t.onsuccess=()=>a()}else r(new Error(`Event with id ${t} not found`))}})}async removeEvents(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName);let a=0;const r=t.length;0!==r?t.forEach(t=>{const e=n.delete(t);e.onerror=()=>i(e.error),e.onsuccess=()=>{a++,a===r&&s()}}):s()})}async recoverOrphanedEvents(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName).openCursor();let a=0;n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;if(i){const e=i.value;if("processing"===e.status&&e.accountId===t){e.status="failed",e.lastAttempt=Date.now(),e.error="Recovered from orphaned processing state";i.update(e).onsuccess=()=>{a++}}i.continue()}else s(a)}})}async getPendingEventCount(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).openCursor();let a=0;n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;if(i){const e=i.value;"pending"===e.status&&e.accountId===t&&a++,i.continue()}else s(a)}})}async getRetryableEvents(t=5,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).openCursor(),r=[];a.onerror=()=>n(a.error),a.onsuccess=s=>{const n=s.target.result;if(n){const s=n.value;"failed"===s.status&&s.attempts<=t&&s.accountId===e&&r.push(s),n.continue()}else i(r)}})}}class at{constructor(t,e,s,n){if(this.systemDataArgs=null,this.currentAccountId=null,this.currentCuid=null,this.isProcessing=!1,this.processingPromise=null,this.BATCH_SIZE=i.BATCH_SIZE,this.authManager=t,this.logger=e,this.RETRY_DELAYS=n||i.DEFAULT_RETRY_DELAYS,s&&"getIndexedDBAdapter"in s){const t=s.getIndexedDBAdapter();t?(e.info("EventQueue: Reusing existing IndexedDB adapter from StorageManager"),this.storage=t):(e.warn("EventQueue: StorageManager has no IndexedDB adapter, creating new one"),this.storage=new nt)}else s?(e.info("EventQueue: Using provided IndexedDBStorage"),this.storage=s):(e.warn("EventQueue: No storage provided, creating new IndexedDBStorage"),this.storage=new nt)}async init(){this.logger.info("Initializing EventQueue"),await this.processQueueIfIdle(),this.logger.info("EventQueue initialized successfully")}async setUserContext(t,e,s){this.currentAccountId=t,this.currentCuid=s||null,this.systemDataArgs=e,this.logger.debug("EventQueue user context set",{accountId:t,cuid:s,systemDataArgs:e});const i=await this.storage.recoverOrphanedEvents(t);i>0&&this.logger.info(`Recovered ${i} orphaned processing events for account ${t}`)}getCurrentAccountId(){return this.currentAccountId}getCurrentCuid(){return this.currentCuid}async enqueue(t){try{if(!this.currentAccountId)throw new Error("Cannot enqueue event: No account context set");const e={id:G(),event:t,accountId:this.currentAccountId,timestamp:(new Date).toISOString(),attempts:0,status:i.STATUSES.PENDING};await this.storage.addEvent(e),this.logger.debug("Event added to queue",{eventId:e.id,eventType:t.category,eventName:t.name}),await this.processQueueIfIdle()}catch(e){throw this.logger.error("Failed to enqueue event",{event:t,error:e}),e}}async processQueueIfIdle(){if(!this.isProcessing)return this.processingPromise||(this.processingPromise=this.processQueue()),this.processingPromise;this.logger.debug("Queue processing already in progress, skipping")}async processQueue(){if(!this.isProcessing){this.isProcessing=!0,this.logger.debug("Starting queue processing");try{for(;;){if(await this.checkAndPromoteRetryEvents(),!this.currentAccountId){this.logger.debug("No account context, skipping event processing");break}const t=await this.storage.getOldestPendingEvents(this.BATCH_SIZE,this.currentAccountId);if(0===t.length){this.logger.debug("No pending events to process");break}this.logger.info("Processing batch of events",{batchSize:t.length,eventIds:t.map(t=>t.id)}),await this.markEventsAsProcessing(t),await this.sendBatch(t);if(0===await this.storage.getPendingEventCount(this.currentAccountId)){this.logger.debug("No more pending events");break}}}catch(t){this.logger.error("Queue processing failed",t)}finally{this.isProcessing=!1,this.processingPromise=null,this.logger.debug("Queue processing completed")}}}async markEventsAsProcessing(t){for(const e of t)try{await this.storage.updateEventStatus(e.id,"processing")}catch(t){this.logger.warn("Failed to mark event as processing",{eventId:e.id,error:t})}}async sendBatch(t){try{if(!this.currentAccountId)throw new Error("Missing account context for batch sending");const e=await this.authManager.getNonceData(),s=this.authManager.getApiClient(),i=t.map(t=>t.event),n=await s.sendEvents(i,this.currentCuid||"",this.systemDataArgs||{country:q,city:W,country_code:L},e.nonce,e.challengeId,e.deviceId);return await this.handleBatchResponse(t,n),!0}catch(e){const s=this.isRetryableHttpError(e);return this.logger.error("Failed to send batch",{batchSize:t.length,error:e,isRetryable:s}),s?await this.handleFailedBatch(t):await this.removeNonRetryableEvents(t),!1}}async removeSuccessfulEvents(t){const e=t.map(t=>t.id);try{await this.storage.removeEvents(e),this.logger.debug("Successfully removed events from storage",{count:e.length})}catch(t){this.logger.error("Failed to remove events from storage",{eventIds:e,error:t})}}async handleBatchResponse(t,e){const s=e.status.code;if(s===i.GLOBAL_SUCCESS_CODE)await this.removeSuccessfulEvents(t),this.logger.info("All events processed successfully",{count:t.length});else if(s===i.PARTIAL_SUCCESS_CODE)await this.handlePartialSuccess(t,e.events);else{i.RETRYABLE_HTTP_CODES.includes(parseInt(s))?(await this.handleFailedBatch(t),this.logger.warn("Batch failed with retryable error",{code:s,message:e.status.message})):(await this.removeNonRetryableEvents(t),this.logger.error("Batch failed with non-retryable error",{code:s,message:e.status.message}))}}async handlePartialSuccess(t,e){const s=new Map;e.forEach(t=>{s.set(t.event_id,t)});for(const e of t){const t=s.get(e.event.event_id);if(t)if(t.status.success)await this.storage.removeEvents([e.id]),this.logger.debug("Event processed successfully",{eventId:e.id});else{const s=parseInt(t.status.code);i.RETRYABLE_HTTP_CODES.includes(s)?(await this.markEventForRetry(e,t.status.message),this.logger.debug("Event marked for retry",{eventId:e.id,code:s,message:t.status.message})):(await this.storage.removeEvents([e.id]),this.logger.warn("Event permanently failed - removed",{eventId:e.id,code:s,message:t.status.message}))}else await this.markEventForRetry(e,"No response received")}}async markEventForRetry(t,e){const s=(t.attempts||0)+1;await this.storage.updateEventStatus(t.id,"failed",`Attempt ${s} failed: ${e}`,s);const i=Math.min(Math.max(s-1,0),this.RETRY_DELAYS.length-1),n=this.RETRY_DELAYS[i];this.logger.debug("Event marked for retry",{eventId:t.id,attempts:s,delay:n,isInfiniteRetry:s>this.RETRY_DELAYS.length})}async checkAndPromoteRetryEvents(){try{if(!this.currentAccountId)return void this.logger.debug("No account context, skipping retry check");const t=await this.storage.getRetryableEvents(Number.MAX_SAFE_INTEGER,this.currentAccountId);if(0===t.length)return;let e=0;for(const s of t){const t=Math.min(Math.max(s.attempts-1,0),this.RETRY_DELAYS.length-1),i=this.RETRY_DELAYS[t],n=Date.now()-(s.lastAttempt||0);n>=(i||0)&&(await this.storage.updateEventStatus(s.id,"pending"),e++,this.logger.debug("Failed event promoted to pending",{eventId:s.id,attempt:s.attempts+1,delay:i,timeSinceLastAttempt:n}))}e>0&&this.logger.debug(`Promoted ${e} failed events for retry`)}catch(t){this.logger.error("Failed to check retry events",t)}}isRetryableHttpError(t){if(t.code){const e=parseInt(t.code);return i.RETRYABLE_HTTP_CODES.includes(e)}return t.message?.includes("network")||t.message?.includes("timeout")||t.message?.includes("fetch")}async removeNonRetryableEvents(t){const e=t.map(t=>t.id);try{await this.storage.removeEvents(e),this.logger.warn("Non-retryable events removed permanently",{eventIds:e})}catch(t){this.logger.error("Failed to remove non-retryable events",{eventIds:e,error:t})}}async handleFailedBatch(t){for(const e of t)try{await this.markEventForRetry(e,"Batch failed")}catch(t){this.logger.error("Failed to mark event for retry",{eventId:e.id,error:t})}}async flush(){this.logger.info("Manual flush requested"),await this.processQueueIfIdle()}async destroy(){this.logger.info("Destroying EventQueue"),this.processingPromise&&await this.processingPromise,await this.storage.close(),this.logger.info("EventQueue destroyed")}async clear(){this.logger.warn("Clear method not implemented for IndexedDB queue")}}class rt{constructor(t,e,s,i){this.eventQueue=null,this.initialized=!1,this.config=t,this.logger=i,this.authManager=e,this.storageManager=s}async init(){this.initialized?this.logger.warn("EventTracker already initialized"):(this.logger.info("Initializing EventTracker with IndexedDB queue"),this.eventQueue=new at(this.authManager,this.logger,this.storageManager,this.config.retryDelays),await this.eventQueue.init(),this.initialized=!0,this.logger.info(D))}async setUserContext(t,e,s){if(!this.eventQueue)throw new Error("EventTracker not initialized");await this.eventQueue.setUserContext(t,e,s),this.logger.info("User context set",{accountId:t,systemDataArgs:e,cuid:s})}async track(t){if(!this.initialized||!this.eventQueue)throw new Error("EventTracker not initialized");this.logger.debug("Tracking event",{event:t});try{const e=this.convertToApiEvent(t);await this.eventQueue.enqueue(e)}catch(e){throw this.logger.error(N,{event:t,error:e}),new Error(`${l}: ${e}`)}}convertToApiEvent(t){const e="user"===t.type?i.CATEGORIES.USER:i.CATEGORIES.BEHAVIORAL,s={...t.data,device_id:Z()};if(!this.eventQueue)throw new Error("EventTracker not initialized");const n=this.eventQueue.getCurrentCuid();if(!n)throw new Error("User context not set. Call setUserContext() first.");return function(t,e,s,i){return{category:t,attributes:{...s,device_id:Z(),cuid:i},name:e,created_at:(new Date).toISOString(),event_id:G()}}(e,t.name||"custom",s,n)}async flush(){this.initialized&&this.eventQueue?(this.logger.info("Manual flush requested"),await this.eventQueue.flush()):this.logger.warn("Cannot flush events - EventTracker not initialized")}async destroy(){this.logger.info("Destroying EventTracker"),this.eventQueue&&await this.eventQueue.destroy(),this.initialized=!1,this.logger.info(b)}}class ot{constructor(t,e,s){this.initialized=!1,this.nonceData=null,this.config=t,this.logger=e,this.storageManager=s,this.apiClient=new it({baseUrl:t.baseURL},e,t.accountId)}async init(){this.initialized?this.logger.warn("AuthManager already initialized"):(this.logger.info("Initializing AuthManager",{accountId:this.config.accountId}),this.initialized=!0,this.logger.info(v))}async requestNonce(){if(!this.initialized)throw new Error("AuthManager not initialized");this.logger.info("Requesting nonce for authentication");try{const t=et(),e=Z(),s=await this.apiClient.getNonce(t,e);return this.nonceData={nonce:s.nonce,challengeId:s.challenge_id,expiresAt:s.expires_at,deviceId:e},await this.storeNonceData(),this.logger.info(g,{challengeId:s.challenge_id,expiresAt:s.expires_at}),this.nonceData}catch(t){throw this.logger.error(m,t),t}}async ensureValidNonce(){if(!this.initialized)throw new Error("AuthManager not initialized");this.logger.info("Ensuring valid nonce");try{return await this.restoreNonceData(),this.nonceData&&!this.isNonceExpired(this.nonceData.expiresAt)?(this.logger.info("Using existing valid nonce"),this.nonceData):(this.logger.info("No valid nonce found, requesting fresh"),await this.requestNonce())}catch(t){throw this.logger.error("Failed to ensure valid nonce",t),t}}async getNonceData(){return await this.ensureValidNonce()}isNonceExpired(t){return Date.now()>=t-s}hasValidNonce(){return!!this.nonceData&&!this.isNonceExpired(this.nonceData.expiresAt)}getApiClient(){return this.apiClient}async storeNonceData(){if(this.nonceData)try{await this.storageManager.set(a.NONCE_DATA,JSON.stringify(this.nonceData))}catch(t){this.logger.warn(I,t)}}async restoreNonceData(){try{const t=await this.storageManager.get(a.NONCE_DATA);t&&(this.nonceData=JSON.parse(t),this.logger.info("Nonce data restored from storage"))}catch(t){this.logger.warn(x,t),this.nonceData=null}}async clearNonceData(){this.nonceData=null;try{await this.storageManager.remove(a.NONCE_DATA)}catch(t){this.logger.warn(_,t)}}async destroy(){this.logger.info("Destroying AuthManager"),await this.clearNonceData(),this.initialized=!1,this.logger.info("AuthManager destroyed successfully")}}class ht{constructor(t,e,s){this.initialized=!1,this.logger=t,this.brandId=e,this.applicationId=s,this.adapter=new ct}async init(){if(this.initialized)this.logger.warn("StorageManager already initialized");else{this.logger.info("Initializing StorageManager");try{if(this.isIndexedDBSupported()){const t=["WebSDK"];this.brandId&&t.push(this.brandId),this.applicationId&&t.push(this.applicationId);const e=t.join("_"),s=new nt(e);await this.testStorageAdapter(s),this.adapter=s,this.logger.info("StorageManager initialized with IndexedDB",{dbName:e,brandId:this.brandId,applicationId:this.applicationId})}else await this.testStorageAdapter(this.adapter),this.logger.info("StorageManager initialized with localStorage");this.initialized=!0}catch(t){throw this.logger.error(T,t),new Error(`Storage initialization failed: ${t}`)}}}isIndexedDBSupported(){return"undefined"!=typeof window&&"indexedDB"in window&&null!==indexedDB}async testStorageAdapter(t){const e=o,s=h;try{await t.setItem(e,s);if(await t.getItem(e)!==s)throw new Error(C);await t.removeItem(e)}catch(t){throw new Error(`${A} ${t}`)}}async get(t){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.getItem(t)}async set(t,e){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.setItem(t,e)}async remove(t){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.removeItem(t)}async clear(){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.clear()}getIndexedDBAdapter(){return this.adapter instanceof nt?this.adapter:null}async destroy(){this.logger.info("Destroying StorageManager");try{this.adapter instanceof nt&&await this.adapter.close(),this.initialized=!1,this.logger.info(R)}catch(t){this.logger.error(O,t),this.initialized=!1}}}class ct{async getItem(t){try{return localStorage.getItem(t)}catch(t){throw new Error(`LocalStorage getItem failed: ${t}`)}}async setItem(t,e){try{localStorage.setItem(t,e)}catch(t){if(t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name))throw new Error("LocalStorage quota exceeded");throw new Error(`LocalStorage setItem failed: ${t}`)}}async removeItem(t){try{localStorage.removeItem(t)}catch(t){throw new Error(`LocalStorage removeItem failed: ${t}`)}}async clear(){try{localStorage.clear()}catch(t){throw new Error(`LocalStorage clear failed: ${t}`)}}}var dt;!function(t){t[t.VERBOSE=0]="VERBOSE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE"}(dt||(dt={}));class ut{constructor(t=!1,e=dt.INFO){this.logs=[],this.maxLogs=1e3,this.enabled=t,this.level=e}formatMessage(t,e){return`[${(new Date).toISOString()}] [WebSDK:${dt[t]}] ${e}`}log(t,e,s){if(!this.enabled||t<this.level)return;const i={level:t,message:e,timestamp:Date.now(),data:s};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift();const n=this.formatMessage(t,e),a=s?[n,s]:[n];switch(t){case dt.VERBOSE:case dt.DEBUG:break;case dt.INFO:console.info(...a);break;case dt.WARN:console.warn(...a);break;case dt.ERROR:console.error(...a)}}verbose(t,e){this.log(dt.VERBOSE,t,e)}debug(t,e){this.log(dt.DEBUG,t,e)}info(t,e){this.log(dt.INFO,t,e)}warn(t,e){this.log(dt.WARN,t,e)}error(t,e){this.log(dt.ERROR,t,e)}setLevel(t){this.level=t}setEnabled(t){this.enabled=t}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}}class lt{constructor(t){this.userContextSet=!1,this.initialized=!1,this.initializationPromise=null,this.config=t,this.logger=new ut(this.shouldEnableLogging(t.debugLevel)),this.sessionId="",this.storageManager=new ht(this.logger,t.brandId,t.applicationId),this.authManager=new ot(t,this.logger,this.storageManager),this.eventTracker=new rt(t,this.authManager,this.storageManager,this.logger)}static instanceWithConfig(t){return new lt(t)}shouldEnableLogging(t){return!(!t||"NONE"===t)&&["ERROR","WARN","INFO","DEBUG","VERBOSE"].includes(t)}async getOrCreateSessionId(){try{const t=r("SESSION_ID",this.config.brandId,this.config.applicationId),e=await this.storageManager.get(t);if(e)return e;const s=j();return await this.storageManager.set(t,s),s}catch(t){return this.logger.warn("Failed to get or create session ID",t),j()}}async restoreUserContext(){try{const t=r("USER_CONTEXT",this.config.brandId,this.config.applicationId),e=await this.storageManager.get(t);if(e){const t=JSON.parse(e),s=t.cuid;await this.eventTracker.setUserContext(this.config.accountId,t.systemDataArgs,s),this.userContextSet=!0,this.logger.info("User context restored from storage",{cuid:s,accountId:this.config.accountId})}}catch(t){this.logger.warn("Failed to restore user context from storage",t)}}async validateAndClearDifferentUserContext(t){try{const e=r("USER_CONTEXT",this.config.brandId,this.config.applicationId),s=await this.storageManager.get(e);if(s){const e=JSON.parse(s);e.cuid&&e.cuid!==t&&(this.logger.info("Different user detected, clearing previous user context",{previousCuid:e.cuid,newCuid:t}),await this.clearUserContext(),this.userContextSet=!1)}}catch(t){this.logger.warn("Error validating different user context",t),await this.clearUserContext(),this.userContextSet=!1}}async storeUserContext(t,e){try{const s={cuid:t,systemDataArgs:e,timestamp:Date.now()},i=r("USER_CONTEXT",this.config.brandId,this.config.applicationId);await this.storageManager.set(i,JSON.stringify(s))}catch(t){this.logger.warn("Failed to store user context",t)}}init(){this.initialized?this.logger.warn("WebSDK already initialized"):this.initializationPromise?this.logger.warn("WebSDK initialization already in progress"):this.initializationPromise=this.initializeAsync().catch(t=>{this.logger.error(y,t),this.initializationPromise=null})}async initializeAsync(){try{this.logger.info("Initializing WebSDK",{version:V,config:this.config}),await this.storageManager.init(),this.sessionId=await this.getOrCreateSessionId(),await this.authManager.init(),await this.eventTracker.init(),await this.authManager.ensureValidNonce(),await this.restoreUserContext(),this.initialized=!0,this.logger.info(w)}catch(t){throw new Error(`${c}: ${t}`)}}async setUserContext(t,e){if(!this.initialized)throw new Error("WebSDK must be initialized before setting user context");await this.validateAndClearDifferentUserContext(t),await this.eventTracker.setUserContext(this.config.accountId,e,t),this.userContextSet=!0,await this.storeUserContext(t,e),this.logger.info("User context set and persisted",{cuid:t,accountId:this.config.accountId})}async clearUserContext(){try{const t=r("USER_CONTEXT",this.config.brandId,this.config.applicationId);await this.storageManager.remove(t),this.userContextSet=!1,this.logger.info("User context cleared")}catch(t){this.logger.warn("Failed to clear user context",t),this.userContextSet=!1}}async track(t){if(!this.initialized)throw new Error("WebSDK must be initialized before tracking events");try{await this.eventTracker.track(t)}catch(e){throw this.logger.error(N,{event:t,error:e}),e}}async destroy(){this.logger.info("Destroying WebSDK instance");try{await this.eventTracker.flush(),await this.eventTracker.destroy(),await this.authManager.destroy(),await this.clearUserContext(),await this.storageManager.destroy(),this.initialized=!1,this.logger.info(f)}catch(t){throw this.logger.error(f,t),t}}pushUserSignin(t,e,s,i,n,a){this.pushUserSigninAsync(t,e,s,i,n,a).catch(e=>{this.logger.error(z,{cuid:t,error:e})})}async pushUserSigninAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,...e&&{first_name:e},...s&&{last_name:s},...i&&{email:i},...n&&{phone:n},...a&&{custom_data:a}},o={type:"user",name:K,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User signin event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error(z,{cuid:t,error:e}),e}}pushUserSignup(t,e,s,i,n,a){this.pushUserSignupAsync(t,e,s,i,n,a).catch(e=>{this.logger.error(M,{cuid:t,error:e})})}async pushUserSignupAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,first_name:e,last_name:s,email:i,phone:n,...a&&{custom_data:a}},o={type:"user",name:Q,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User signup event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error(M,{cuid:t,error:e}),e}}pushUserUpdate(t,e,s,i,n,a){this.pushUserUpdateAsync(t,e,s,i,n,a).catch(e=>{this.logger.error($,{cuid:t,error:e})})}async pushUserUpdateAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,...e&&{first_name:e},...s&&{last_name:s},...i&&{email:i},...n&&{phone:n},...a&&{custom_data:a}},o={type:"user",name:H,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User update event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error($,{cuid:t,error:e}),e}}pushUserSignOut(t){this.pushUserSignOutAsync(t).catch(e=>{this.logger.error(F,{cuid:t,error:e}),this.destroy().catch(t=>{this.logger.error("Failed to destroy SDK after failed signout",t)})})}async pushUserSignOutAsync(t){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const e={type:"user",name:X,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:{cuid:t}};try{await this.track(e),this.logger.info("User signout event tracked",{cuid:t}),await this.destroy()}catch(e){this.logger.error(F,{cuid:t,error:e});try{await this.destroy()}catch(t){this.logger.error("Failed to destroy SDK after failed signout",t)}throw e}}pushEvent(t,e){this.pushEventAsync(t,e).catch(e=>{this.logger.error(P,{eventName:t,error:e})})}async pushEventAsync(t,e){if(await this.ensureInitialized(),!this.userContextSet)throw new Error("User context must be set before tracking behavioral events. Call setUserContext() first.");const s={event_name:t,...e&&e},i={type:"behavioral",name:t,timestamp:Date.now(),sessionId:this.sessionId,data:s};try{await this.track(i),this.logger.info("Behavioral event tracked",{eventName:t,attributes:e})}catch(e){throw this.logger.error(P,{eventName:t,error:e}),e}}async ensureInitialized(){if(this.initializationPromise)try{await this.initializationPromise}catch(t){throw new Error(`SDK initialization failed: ${t}`)}if(!this.initialized)throw new Error("WebSDK must be initialized before tracking events. Call init() first.")}async setUserContextIfNeeded(t){if(!this.userContextSet){const e={country:this.config.country,city:this.config.city,country_code:this.config.countryCode};await this.setUserContext(t,e),this.logger.debug("User context set automatically",{cuid:t,systemDataArgs:e})}}}return lt});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).WebSDK=e()}(this,function(){"use strict";const t="/auth/nonce",e="/mapp/events",s=6e4,i={CATEGORIES:{USER:"USER",BEHAVIORAL:"BE"},STATUSES:{PENDING:"pending"},BATCH_SIZE:50,MAX_RETRY_ATTEMPTS:5,DEFAULT_RETRY_DELAYS:[6e4,12e4,24e4,48e4,9e5],RETRYABLE_HTTP_CODES:[408,429,500,502,503,504,401],GLOBAL_SUCCESS_CODE:200,PARTIAL_SUCCESS_CODE:201},n={NONCE_DATA:"websdk_nonce_data",USER_CONTEXT:"websdk_user_context",DEVICE_ID:"websdk_device_id",SESSION_ID:"websdk_session_id"},a=n;function r(t,e,s){const i=n[t],a=[];return e&&a.push(e),s&&a.push(s),a.length>0?`${a.join("_")}_${i}`:i}const o="websdk_storage_test",h="test_value",c="INIT_ERROR",d="AUTH_ERROR",u="NETWORK_ERROR",l="EVENT_ERROR",w="WebSDK initialized successfully",y="Failed to initialize WebSDK",f="WebSDK destroyed successfully",g="Authentication successful",m="Authentication failed",v="AuthManager initialized successfully",E="Nonce request successful",p="Nonce request failed",S="Request signature generated successfully",I="Failed to store nonce data",x="Failed to restore nonce data from storage",_="Failed to clear stored nonce data",D="EventTracker initialized successfully",b="EventTracker destroyed successfully",N="Failed to track event",k="Events sent successfully",U="Failed to send events",T="Failed to initialize storage:",A="Storage test failed:",C="Storage read/write test failed",R="StorageManager destroyed successfully",O="Error during storage cleanup:",z="Failed to track user signin event",M="Failed to track user signup event",$="Failed to track user update event",F="Failed to track user signout event",P="Failed to track behavioral event",B="web",q="",W="",L="",K="user_signin",Q="user_signup",H="user_update",X="user_signout",V="1.0.2";class J{constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,"")}async request(t,e={}){const{method:s="GET",headers:i={},body:n}=e,a=!t||t.startsWith("/")?t:`/${t}`,r=`${this.baseUrl}${a}`;try{const t={method:s,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):null},e=await fetch(r,t);if(!e.ok){const t=await e.text();throw new Error(`HTTP ${e.status}: ${e.statusText} - ${t}`)}return await e.json()}catch(t){throw this.handleError(t)}}handleError(t){return t instanceof Error?"AbortError"===t.name?{code:u,message:"Request timeout",details:t}:t.message.includes("HTTP 401")||t.message.includes("HTTP 403")?{code:d,message:"Authentication failed",details:t}:(t.message.includes("HTTP"),{code:u,message:t.message,details:t}):{code:u,message:`Unknown error: ${String(t)}`,details:t}}async get(t,e={}){return this.request(t,{...e,method:"GET"})}async post(t,e,s={}){return this.request(t,{...s,method:"POST",body:e})}async put(t,e,s={}){return this.request(t,{...s,method:"PUT",body:e})}async delete(t,e={}){return this.request(t,{...e,method:"DELETE"})}}function G(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function j(){return`session_${G()}`}async function Y(t,e,s,i){try{const n=i||Z(),a=function(t){const e=Object.keys(t).sort();return e.map(e=>`${e}=${t[e]}`).join("&")}({nonce:e,account_id:s,device_id:n,timestamp:Date.now(),payload:JSON.stringify(t,Object.keys(t).sort())}),r=await async function(t,e){const s=`${t}:${e}:cap-hydra-web-sdk`,i=(new TextEncoder).encode(s),n=await crypto.subtle.digest("SHA-256",i);return await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"])}(s,n);return await async function(t,e){const s=(new TextEncoder).encode(t),i=await crypto.subtle.sign("HMAC",e,s);return btoa(String.fromCharCode(...new Uint8Array(i)))}(a,r)}catch(t){throw new Error(`Signature generation failed: ${t instanceof Error?t.message:"Unknown error"}`)}}function Z(){const t=a.DEVICE_ID,e=localStorage.getItem(t);if(e)return e;const s=G();return localStorage.setItem(t,s),s}function tt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function et(){return window.location.hostname||"localhost"}function st(t){const e=function(){const t=navigator.userAgent;let e="Unknown",s="Unknown";if(t.includes("Chrome")){e="Chrome";const i=t.match(/Chrome\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Firefox")){e="Firefox";const i=t.match(/Firefox\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Safari")&&!t.includes("Chrome")){e="Safari";const i=t.match(/Version\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Edge")){e="Edge";const i=t.match(/Edge\/([0-9.]+)/);s=i?.[1]??"Unknown"}let i="Unknown",n="Unknown";if(t.includes("Windows"))i="Windows",t.includes("Windows NT 10.0")?n="10":t.includes("Windows NT 6.3")?n="8.1":t.includes("Windows NT 6.2")?n="8":t.includes("Windows NT 6.1")&&(n="7");else if(t.includes("Mac OS X")){i="macOS";const e=t.match(/Mac OS X ([0-9_]+)/);n=e?.[1]?.replace(/_/g,".")??"Unknown"}else if(t.includes("Linux"))i="Linux",n="Unknown";else if(t.includes("Android")){i="Android";const e=t.match(/Android ([0-9.]+)/);n=e?.[1]??"Unknown"}else if(t.includes("iPhone")||t.includes("iPad")){i="iOS";const e=t.match(/OS ([0-9_]+)/);n=e?.[1]?.replace(/_/g,".")??"Unknown"}return{browserName:e,browserVersion:s,osName:i,osVersion:n}}(),s={width:window.innerWidth||document.documentElement.clientWidth||0,height:window.innerHeight||document.documentElement.clientHeight||0},i=Z();return{os_version:e.osVersion,country_code:t.country_code,os_name:e.osName,viewport_width:s.width,country:t.country,viewport_height:s.height,device_id:i,bundle_identifier:et(),last_seen:(new Date).toISOString(),city:t.city,sdk_version:V,platform:"web",browser_name:e.browserName,browser_version:e.browserVersion,browser_language:navigator.language||navigator.languages&&navigator.languages[0]||"en-US",timezone:tt()}}class it{constructor(t,e,s){this.httpClient=new J(t),this.logger=e,this.accountId=s}async getNonce(e,s){const i=s||Z();this.logger.info("Requesting nonce",{accountId:this.accountId,bundleIdentifier:e,deviceId:i});const n={account_id:this.accountId,bundle_identifier:e,device_id:i,timestamp:Date.now(),os_name:B};try{const e=await this.httpClient.post(t,n);return this.logger.info(E,{challengeId:e.challenge_id,expiresAt:e.expires_at}),e}catch(t){throw this.logger.error(p,t),t}}async sendEvents(t,s,i,n,a,r){this.logger.info("Sending events",{eventCount:t.length,cuid:s,challengeId:a});const o=r||Z(),h={system_data:st(i),request_id:G(),events:t,cuid:s};try{const s=await Y({...h,nonce:n,challenge_id:a},n,this.accountId,o);this.logger.info(S,{requestId:h.request_id,challengeId:a});const i={"X-Cap-Nonce":n,"X-Cap-Challenge-ID":a,"X-Cap-Signature":s,"X-Cap-Device-ID":o},r=await this.httpClient.post(e,h,{headers:i});return this.logger.info(k,{requestId:h.request_id,eventCount:t.length,success:r.status.success}),r}catch(e){throw this.logger.error(U,{requestId:h.request_id,eventCount:t.length,error:e}),e}}}class nt{constructor(t="WebSDK",e=2,s="data"){this.db=null,this.dbName=t,this.version=e,this.storeName=s,this.eventsStoreName="events"}async openDB(){return this.db?this.db:new Promise((t,e)=>{const s=indexedDB.open(this.dbName,this.version);s.onerror=()=>e(s.error),s.onsuccess=()=>{this.db=s.result,t(this.db)},s.onupgradeneeded=t=>{const e=t.target.result;if(e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName),!e.objectStoreNames.contains(this.eventsStoreName)){const t=e.createObjectStore(this.eventsStoreName,{keyPath:"id"});t.createIndex("timestamp","timestamp",{unique:!1}),t.createIndex("status","status",{unique:!1})}}})}async getItem(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.storeName],"readonly").objectStore(this.storeName).get(t);n.onerror=()=>i(n.error),n.onsuccess=()=>{const t=n.result;s(null==t?null:"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):String(t))}})}async setItem(t,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(e,t);a.onerror=()=>n(a.error),a.onsuccess=()=>i()})}async removeItem(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(t);n.onerror=()=>i(n.error),n.onsuccess=()=>s()})}async clear(){const t=await this.openDB();return new Promise((e,s)=>{const i=t.transaction([this.storeName],"readwrite").objectStore(this.storeName).clear();i.onerror=()=>s(i.error),i.onsuccess=()=>e()})}async close(){this.db&&(this.db.close(),this.db=null)}async addEvent(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName).add(t);n.onerror=()=>i(n.error),n.onsuccess=()=>s()})}async getOldestPendingEvents(t=50,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).index("timestamp").openCursor(),r=[];let o=0;a.onerror=()=>n(a.error),a.onsuccess=s=>{const n=s.target.result;if(n&&o<t){const t=n.value;"pending"===t.status&&t.accountId===e&&(r.push(t),o++),n.continue()}else i(r)}})}async updateEventStatus(t,e,s,i){const n=await this.openDB();return new Promise((a,r)=>{const o=n.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName),h=o.get(t);h.onerror=()=>r(h.error),h.onsuccess=()=>{const n=h.result;if(n){n.status=e,n.lastAttempt=Date.now(),s&&(n.error=s),void 0!==i&&(n.attempts=i);const t=o.put(n);t.onerror=()=>r(t.error),t.onsuccess=()=>a()}else r(new Error(`Event with id ${t} not found`))}})}async removeEvents(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName);let a=0;const r=t.length;0!==r?t.forEach(t=>{const e=n.delete(t);e.onerror=()=>i(e.error),e.onsuccess=()=>{a++,a===r&&s()}}):s()})}async recoverOrphanedEvents(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName).openCursor();let a=0;n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;if(i){const e=i.value;if("processing"===e.status&&e.accountId===t){e.status="failed",e.lastAttempt=Date.now(),e.error="Recovered from orphaned processing state";i.update(e).onsuccess=()=>{a++}}i.continue()}else s(a)}})}async getPendingEventCount(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).openCursor();let a=0;n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;if(i){const e=i.value;"pending"===e.status&&e.accountId===t&&a++,i.continue()}else s(a)}})}async getRetryableEvents(t=5,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).openCursor(),r=[];a.onerror=()=>n(a.error),a.onsuccess=s=>{const n=s.target.result;if(n){const s=n.value;"failed"===s.status&&s.attempts<=t&&s.accountId===e&&r.push(s),n.continue()}else i(r)}})}}class at{constructor(t,e,s,n){if(this.systemDataArgs=null,this.currentAccountId=null,this.currentCuid=null,this.isProcessing=!1,this.processingPromise=null,this.BATCH_SIZE=i.BATCH_SIZE,this.authManager=t,this.logger=e,this.RETRY_DELAYS=n||i.DEFAULT_RETRY_DELAYS,s&&"getIndexedDBAdapter"in s){const t=s.getIndexedDBAdapter();t?(e.info("EventQueue: Reusing existing IndexedDB adapter from StorageManager"),this.storage=t):(e.warn("EventQueue: StorageManager has no IndexedDB adapter, creating new one"),this.storage=new nt)}else s?(e.info("EventQueue: Using provided IndexedDBStorage"),this.storage=s):(e.warn("EventQueue: No storage provided, creating new IndexedDBStorage"),this.storage=new nt)}async init(){this.logger.info("Initializing EventQueue"),await this.processQueueIfIdle(),this.logger.info("EventQueue initialized successfully")}async setUserContext(t,e,s){this.currentAccountId=t,this.currentCuid=s||null,this.systemDataArgs=e,this.logger.debug("EventQueue user context set",{accountId:t,cuid:s,systemDataArgs:e});const i=await this.storage.recoverOrphanedEvents(t);i>0&&this.logger.info(`Recovered ${i} orphaned processing events for account ${t}`)}getCurrentAccountId(){return this.currentAccountId}getCurrentCuid(){return this.currentCuid}async enqueue(t){try{if(!this.currentAccountId)throw new Error("Cannot enqueue event: No account context set");const e={id:G(),event:t,accountId:this.currentAccountId,timestamp:(new Date).toISOString(),attempts:0,status:i.STATUSES.PENDING};await this.storage.addEvent(e),this.logger.debug("Event added to queue",{eventId:e.id,eventType:t.category,eventName:t.name}),await this.processQueueIfIdle()}catch(e){throw this.logger.error("Failed to enqueue event",{event:t,error:e}),e}}async processQueueIfIdle(){if(!this.isProcessing)return this.processingPromise||(this.processingPromise=this.processQueue()),this.processingPromise;this.logger.debug("Queue processing already in progress, skipping")}async processQueue(){if(!this.isProcessing){this.isProcessing=!0,this.logger.debug("Starting queue processing");try{for(;;){if(await this.checkAndPromoteRetryEvents(),!this.currentAccountId){this.logger.debug("No account context, skipping event processing");break}const t=await this.storage.getOldestPendingEvents(this.BATCH_SIZE,this.currentAccountId);if(0===t.length){this.logger.debug("No pending events to process");break}this.logger.info("Processing batch of events",{batchSize:t.length,eventIds:t.map(t=>t.id)}),await this.markEventsAsProcessing(t),await this.sendBatch(t);if(0===await this.storage.getPendingEventCount(this.currentAccountId)){this.logger.debug("No more pending events");break}}}catch(t){this.logger.error("Queue processing failed",t)}finally{this.isProcessing=!1,this.processingPromise=null,this.logger.debug("Queue processing completed")}}}async markEventsAsProcessing(t){for(const e of t)try{await this.storage.updateEventStatus(e.id,"processing")}catch(t){this.logger.warn("Failed to mark event as processing",{eventId:e.id,error:t})}}async sendBatch(t){try{if(!this.currentAccountId)throw new Error("Missing account context for batch sending");const e=await this.authManager.getNonceData(),s=this.authManager.getApiClient(),i=t.map(t=>t.event),n=await s.sendEvents(i,this.currentCuid||"",this.systemDataArgs||{country:q,city:W,country_code:L},e.nonce,e.challengeId,e.deviceId);return await this.handleBatchResponse(t,n),!0}catch(e){const s=this.isRetryableHttpError(e);return this.logger.error("Failed to send batch",{batchSize:t.length,error:e,isRetryable:s}),s?await this.handleFailedBatch(t):await this.removeNonRetryableEvents(t),!1}}async removeSuccessfulEvents(t){const e=t.map(t=>t.id);try{await this.storage.removeEvents(e),this.logger.debug("Successfully removed events from storage",{count:e.length})}catch(t){this.logger.error("Failed to remove events from storage",{eventIds:e,error:t})}}async handleBatchResponse(t,e){const s=e.status.code;if(s===i.GLOBAL_SUCCESS_CODE)await this.removeSuccessfulEvents(t),this.logger.info("All events processed successfully",{count:t.length});else if(s===i.PARTIAL_SUCCESS_CODE)await this.handlePartialSuccess(t,e.events);else{i.RETRYABLE_HTTP_CODES.includes(parseInt(s))?(await this.handleFailedBatch(t),this.logger.warn("Batch failed with retryable error",{code:s,message:e.status.message})):(await this.removeNonRetryableEvents(t),this.logger.error("Batch failed with non-retryable error",{code:s,message:e.status.message}))}}async handlePartialSuccess(t,e){const s=new Map;e.forEach(t=>{s.set(t.event_id,t)});for(const e of t){const t=s.get(e.event.event_id);if(t)if(t.status.success)await this.storage.removeEvents([e.id]),this.logger.debug("Event processed successfully",{eventId:e.id});else{const s=parseInt(t.status.code);i.RETRYABLE_HTTP_CODES.includes(s)?(await this.markEventForRetry(e,t.status.message),this.logger.debug("Event marked for retry",{eventId:e.id,code:s,message:t.status.message})):(await this.storage.removeEvents([e.id]),this.logger.warn("Event permanently failed - removed",{eventId:e.id,code:s,message:t.status.message}))}else await this.markEventForRetry(e,"No response received")}}async markEventForRetry(t,e){const s=(t.attempts||0)+1;await this.storage.updateEventStatus(t.id,"failed",`Attempt ${s} failed: ${e}`,s);const i=Math.min(Math.max(s-1,0),this.RETRY_DELAYS.length-1),n=this.RETRY_DELAYS[i];this.logger.debug("Event marked for retry",{eventId:t.id,attempts:s,delay:n,isInfiniteRetry:s>this.RETRY_DELAYS.length})}async checkAndPromoteRetryEvents(){try{if(!this.currentAccountId)return void this.logger.debug("No account context, skipping retry check");const t=await this.storage.getRetryableEvents(Number.MAX_SAFE_INTEGER,this.currentAccountId);if(0===t.length)return;let e=0;for(const s of t){const t=Math.min(Math.max(s.attempts-1,0),this.RETRY_DELAYS.length-1),i=this.RETRY_DELAYS[t],n=Date.now()-(s.lastAttempt||0);n>=(i||0)&&(await this.storage.updateEventStatus(s.id,"pending"),e++,this.logger.debug("Failed event promoted to pending",{eventId:s.id,attempt:s.attempts+1,delay:i,timeSinceLastAttempt:n}))}e>0&&this.logger.debug(`Promoted ${e} failed events for retry`)}catch(t){this.logger.error("Failed to check retry events",t)}}isRetryableHttpError(t){if(t.code){const e=parseInt(t.code);return i.RETRYABLE_HTTP_CODES.includes(e)}return t.message?.includes("network")||t.message?.includes("timeout")||t.message?.includes("fetch")}async removeNonRetryableEvents(t){const e=t.map(t=>t.id);try{await this.storage.removeEvents(e),this.logger.warn("Non-retryable events removed permanently",{eventIds:e})}catch(t){this.logger.error("Failed to remove non-retryable events",{eventIds:e,error:t})}}async handleFailedBatch(t){for(const e of t)try{await this.markEventForRetry(e,"Batch failed")}catch(t){this.logger.error("Failed to mark event for retry",{eventId:e.id,error:t})}}async flush(){this.logger.info("Manual flush requested"),await this.processQueueIfIdle()}async destroy(){this.logger.info("Destroying EventQueue"),this.processingPromise&&await this.processingPromise,await this.storage.close(),this.logger.info("EventQueue destroyed")}async clear(){this.logger.warn("Clear method not implemented for IndexedDB queue")}}class rt{constructor(t,e,s,i){this.eventQueue=null,this.initialized=!1,this.config=t,this.logger=i,this.authManager=e,this.storageManager=s}async init(){this.initialized?this.logger.warn("EventTracker already initialized"):(this.logger.info("Initializing EventTracker with IndexedDB queue"),this.eventQueue=new at(this.authManager,this.logger,this.storageManager,this.config.retryDelays),await this.eventQueue.init(),this.initialized=!0,this.logger.info(D))}async setUserContext(t,e,s){if(!this.eventQueue)throw new Error("EventTracker not initialized");await this.eventQueue.setUserContext(t,e,s),this.logger.info("User context set",{accountId:t,systemDataArgs:e,cuid:s})}async track(t){if(!this.initialized||!this.eventQueue)throw new Error("EventTracker not initialized");this.logger.debug("Tracking event",{event:t});try{const e=this.convertToApiEvent(t);await this.eventQueue.enqueue(e)}catch(e){throw this.logger.error(N,{event:t,error:e}),new Error(`${l}: ${e}`)}}convertToApiEvent(t){const e="user"===t.type?i.CATEGORIES.USER:i.CATEGORIES.BEHAVIORAL,s={...t.data,device_id:Z()};if(!this.eventQueue)throw new Error("EventTracker not initialized");const n=this.eventQueue.getCurrentCuid();if(!n)throw new Error("User context not set. Call setUserContext() first.");return function(t,e,s,i){return{category:t,attributes:{...s,device_id:Z(),cuid:i},name:e,created_at:(new Date).toISOString(),event_id:G()}}(e,t.name||"custom",s,n)}async flush(){this.initialized&&this.eventQueue?(this.logger.info("Manual flush requested"),await this.eventQueue.flush()):this.logger.warn("Cannot flush events - EventTracker not initialized")}async destroy(){this.logger.info("Destroying EventTracker"),this.eventQueue&&await this.eventQueue.destroy(),this.initialized=!1,this.logger.info(b)}}class ot{constructor(t,e,s){this.initialized=!1,this.nonceData=null,this.config=t,this.logger=e,this.storageManager=s,this.apiClient=new it({baseUrl:t.baseURL},e,t.accountId)}async init(){this.initialized?this.logger.warn("AuthManager already initialized"):(this.logger.info("Initializing AuthManager",{accountId:this.config.accountId}),this.initialized=!0,this.logger.info(v))}async requestNonce(){if(!this.initialized)throw new Error("AuthManager not initialized");this.logger.info("Requesting nonce for authentication");try{const t=et(),e=Z(),s=await this.apiClient.getNonce(t,e);return this.nonceData={nonce:s.nonce,challengeId:s.challenge_id,expiresAt:s.expires_at,deviceId:e},await this.storeNonceData(),this.logger.info(g,{challengeId:s.challenge_id,expiresAt:s.expires_at}),this.nonceData}catch(t){throw this.logger.error(m,t),t}}async ensureValidNonce(){if(!this.initialized)throw new Error("AuthManager not initialized");this.logger.info("Ensuring valid nonce");try{return await this.restoreNonceData(),this.nonceData&&!this.isNonceExpired(this.nonceData.expiresAt)?(this.logger.info("Using existing valid nonce"),this.nonceData):(this.logger.info("No valid nonce found, requesting fresh"),await this.requestNonce())}catch(t){throw this.logger.error("Failed to ensure valid nonce",t),t}}async getNonceData(){return await this.ensureValidNonce()}isNonceExpired(t){return Date.now()>=t-s}hasValidNonce(){return!!this.nonceData&&!this.isNonceExpired(this.nonceData.expiresAt)}getApiClient(){return this.apiClient}async storeNonceData(){if(this.nonceData)try{await this.storageManager.set(a.NONCE_DATA,JSON.stringify(this.nonceData))}catch(t){this.logger.warn(I,t)}}async restoreNonceData(){try{const t=await this.storageManager.get(a.NONCE_DATA);t&&(this.nonceData=JSON.parse(t),this.logger.info("Nonce data restored from storage"))}catch(t){this.logger.warn(x,t),this.nonceData=null}}async clearNonceData(){this.nonceData=null;try{await this.storageManager.remove(a.NONCE_DATA)}catch(t){this.logger.warn(_,t)}}async destroy(){this.logger.info("Destroying AuthManager"),await this.clearNonceData(),this.initialized=!1,this.logger.info("AuthManager destroyed successfully")}}class ht{constructor(t,e,s){this.initialized=!1,this.logger=t,this.brandId=e,this.applicationId=s,this.adapter=new ct}async init(){if(this.initialized)this.logger.warn("StorageManager already initialized");else{this.logger.info("Initializing StorageManager");try{if(this.isIndexedDBSupported()){const t=["WebSDK"];this.brandId&&t.push(this.brandId),this.applicationId&&t.push(this.applicationId);const e=t.join("_"),s=new nt(e);await this.testStorageAdapter(s),this.adapter=s,this.logger.info("StorageManager initialized with IndexedDB",{dbName:e,brandId:this.brandId,applicationId:this.applicationId})}else await this.testStorageAdapter(this.adapter),this.logger.info("StorageManager initialized with localStorage");this.initialized=!0}catch(t){throw this.logger.error(T,t),new Error(`Storage initialization failed: ${t}`)}}}isIndexedDBSupported(){return"undefined"!=typeof window&&"indexedDB"in window&&null!==indexedDB}async testStorageAdapter(t){const e=o,s=h;try{await t.setItem(e,s);if(await t.getItem(e)!==s)throw new Error(C);await t.removeItem(e)}catch(t){throw new Error(`${A} ${t}`)}}async get(t){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.getItem(t)}async set(t,e){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.setItem(t,e)}async remove(t){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.removeItem(t)}async clear(){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.clear()}getIndexedDBAdapter(){return this.adapter instanceof nt?this.adapter:null}async destroy(){this.logger.info("Destroying StorageManager");try{this.adapter instanceof nt&&await this.adapter.close(),this.initialized=!1,this.logger.info(R)}catch(t){this.logger.error(O,t),this.initialized=!1}}}class ct{async getItem(t){try{return localStorage.getItem(t)}catch(t){throw new Error(`LocalStorage getItem failed: ${t}`)}}async setItem(t,e){try{localStorage.setItem(t,e)}catch(t){if(t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name))throw new Error("LocalStorage quota exceeded");throw new Error(`LocalStorage setItem failed: ${t}`)}}async removeItem(t){try{localStorage.removeItem(t)}catch(t){throw new Error(`LocalStorage removeItem failed: ${t}`)}}async clear(){try{localStorage.clear()}catch(t){throw new Error(`LocalStorage clear failed: ${t}`)}}}var dt;!function(t){t[t.VERBOSE=0]="VERBOSE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE"}(dt||(dt={}));class ut{constructor(t=!1,e=dt.INFO){this.logs=[],this.maxLogs=1e3,this.enabled=t,this.level=e}formatMessage(t,e){return`[${(new Date).toISOString()}] [WebSDK:${dt[t]}] ${e}`}log(t,e,s){if(!this.enabled||t<this.level)return;const i={level:t,message:e,timestamp:Date.now(),data:s};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift();const n=this.formatMessage(t,e),a=s?[n,s]:[n];switch(t){case dt.VERBOSE:case dt.DEBUG:break;case dt.INFO:console.info(...a);break;case dt.WARN:console.warn(...a);break;case dt.ERROR:console.error(...a)}}verbose(t,e){this.log(dt.VERBOSE,t,e)}debug(t,e){this.log(dt.DEBUG,t,e)}info(t,e){this.log(dt.INFO,t,e)}warn(t,e){this.log(dt.WARN,t,e)}error(t,e){this.log(dt.ERROR,t,e)}setLevel(t){this.level=t}setEnabled(t){this.enabled=t}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}}class lt{constructor(t){this.userContextSet=!1,this.initialized=!1,this.initializationPromise=null,this.config=t,this.logger=new ut(this.shouldEnableLogging(t.debugLevel)),this.sessionId="",this.storageManager=new ht(this.logger,t.brandId,t.applicationId),this.authManager=new ot(t,this.logger,this.storageManager),this.eventTracker=new rt(t,this.authManager,this.storageManager,this.logger)}static instanceWithConfig(t){return new lt(t)}shouldEnableLogging(t){return!(!t||"NONE"===t)&&["ERROR","WARN","INFO","DEBUG","VERBOSE"].includes(t)}async getOrCreateSessionId(){try{const t=r("SESSION_ID",this.config.brandId,this.config.applicationId),e=await this.storageManager.get(t);if(e)return e;const s=j();return await this.storageManager.set(t,s),s}catch(t){return this.logger.warn("Failed to get or create session ID",t),j()}}async restoreUserContext(){try{const t=r("USER_CONTEXT",this.config.brandId,this.config.applicationId),e=await this.storageManager.get(t);if(e){const t=JSON.parse(e),s=t.cuid;await this.eventTracker.setUserContext(this.config.accountId,t.systemDataArgs,s),this.userContextSet=!0,this.logger.info("User context restored from storage",{cuid:s,accountId:this.config.accountId})}}catch(t){this.logger.warn("Failed to restore user context from storage",t)}}async validateAndClearDifferentUserContext(t){try{const e=r("USER_CONTEXT",this.config.brandId,this.config.applicationId),s=await this.storageManager.get(e);if(s){const e=JSON.parse(s);e.cuid&&e.cuid!==t&&(this.logger.info("Different user detected, clearing previous user context",{previousCuid:e.cuid,newCuid:t}),await this.clearUserContext(),this.userContextSet=!1)}}catch(t){this.logger.warn("Error validating different user context",t),await this.clearUserContext(),this.userContextSet=!1}}async storeUserContext(t,e){try{const s={cuid:t,systemDataArgs:e,timestamp:Date.now()},i=r("USER_CONTEXT",this.config.brandId,this.config.applicationId);await this.storageManager.set(i,JSON.stringify(s))}catch(t){this.logger.warn("Failed to store user context",t)}}init(){this.initialized?this.logger.warn("WebSDK already initialized"):this.initializationPromise?this.logger.warn("WebSDK initialization already in progress"):this.initializationPromise=this.initializeAsync().catch(t=>{this.logger.error(y,t),this.initializationPromise=null})}async initializeAsync(){try{this.logger.info("Initializing WebSDK",{version:V,config:this.config}),await this.storageManager.init(),this.sessionId=await this.getOrCreateSessionId(),await this.authManager.init(),await this.eventTracker.init(),await this.authManager.ensureValidNonce(),await this.restoreUserContext(),this.initialized=!0,this.logger.info(w)}catch(t){throw new Error(`${c}: ${t}`)}}async setUserContext(t,e){if(!this.initialized)throw new Error("WebSDK must be initialized before setting user context");await this.validateAndClearDifferentUserContext(t),await this.eventTracker.setUserContext(this.config.accountId,e,t),this.userContextSet=!0,await this.storeUserContext(t,e),this.logger.info("User context set and persisted",{cuid:t,accountId:this.config.accountId})}async clearUserContext(){try{const t=r("USER_CONTEXT",this.config.brandId,this.config.applicationId);await this.storageManager.remove(t),this.userContextSet=!1,this.logger.info("User context cleared")}catch(t){this.logger.warn("Failed to clear user context",t),this.userContextSet=!1}}async track(t){if(!this.initialized)throw new Error("WebSDK must be initialized before tracking events");try{await this.eventTracker.track(t)}catch(e){throw this.logger.error(N,{event:t,error:e}),e}}async destroy(){this.logger.info("Destroying WebSDK instance");try{await this.eventTracker.flush(),await this.eventTracker.destroy(),await this.authManager.destroy(),await this.clearUserContext(),await this.storageManager.destroy(),this.initialized=!1,this.logger.info(f)}catch(t){throw this.logger.error(f,t),t}}pushUserSignin(t,e,s,i,n,a){this.pushUserSigninAsync(t,e,s,i,n,a).catch(e=>{this.logger.error(z,{cuid:t,error:e})})}async pushUserSigninAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,...e&&{first_name:e},...s&&{last_name:s},...i&&{email:i},...n&&{phone:n},...a&&{custom_data:a}},o={type:"user",name:K,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User signin event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error(z,{cuid:t,error:e}),e}}pushUserSignup(t,e,s,i,n,a){this.pushUserSignupAsync(t,e,s,i,n,a).catch(e=>{this.logger.error(M,{cuid:t,error:e})})}async pushUserSignupAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,first_name:e,last_name:s,email:i,phone:n,...a&&{custom_data:a}},o={type:"user",name:Q,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User signup event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error(M,{cuid:t,error:e}),e}}pushUserUpdate(t,e,s,i,n,a){this.pushUserUpdateAsync(t,e,s,i,n,a).catch(e=>{this.logger.error($,{cuid:t,error:e})})}async pushUserUpdateAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,...e&&{first_name:e},...s&&{last_name:s},...i&&{email:i},...n&&{phone:n},...a&&{custom_data:a}},o={type:"user",name:H,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User update event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error($,{cuid:t,error:e}),e}}pushUserSignOut(t){this.pushUserSignOutAsync(t).catch(e=>{this.logger.error(F,{cuid:t,error:e}),this.destroy().catch(t=>{this.logger.error("Failed to destroy SDK after failed signout",t)})})}async pushUserSignOutAsync(t){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const e={type:"user",name:X,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:{cuid:t}};try{await this.track(e),this.logger.info("User signout event tracked",{cuid:t}),await this.destroy()}catch(e){this.logger.error(F,{cuid:t,error:e});try{await this.destroy()}catch(t){this.logger.error("Failed to destroy SDK after failed signout",t)}throw e}}pushEvent(t,e){this.pushEventAsync(t,e).catch(e=>{this.logger.error(P,{eventName:t,error:e})})}async pushEventAsync(t,e){if(await this.ensureInitialized(),!this.userContextSet)throw new Error("User context must be set before tracking behavioral events. Call setUserContext() first.");const s={event_name:t,...e&&e},i={type:"behavioral",name:t,timestamp:Date.now(),sessionId:this.sessionId,data:s};try{await this.track(i),this.logger.info("Behavioral event tracked",{eventName:t,attributes:e})}catch(e){throw this.logger.error(P,{eventName:t,error:e}),e}}async ensureInitialized(){if(this.initializationPromise)try{await this.initializationPromise}catch(t){throw new Error(`SDK initialization failed: ${t}`)}if(!this.initialized)throw new Error("WebSDK must be initialized before tracking events. Call init() first.")}async setUserContextIfNeeded(t){if(!this.userContextSet){const e={country:this.config.country,city:this.config.city,country_code:this.config.countryCode};await this.setUserContext(t,e),this.logger.debug("User context set automatically",{cuid:t,systemDataArgs:e})}}}return lt});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cap-hydra-web-sdk",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "type": "module",
5
5
  "description": "Capillary Hydra WebSDK - JavaScript/TypeScript SDK for web applications",
6
6
  "main": "dist/index.js",