cap-hydra-web-sdk 1.0.0

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.
@@ -0,0 +1,2314 @@
1
+ /**
2
+ * WebSDK Constants
3
+ * All hardcoded strings and configuration values centralized here
4
+ */
5
+ // ===== API CONFIGURATION =====
6
+ const API_ENDPOINTS = {
7
+ // Nonce-based authentication endpoints
8
+ NONCE_REQUEST: '/auth/nonce',
9
+ // Event endpoints
10
+ MAPP_EVENTS: '/mapp/events',
11
+ };
12
+ // ===== AUTHENTICATION CONSTANTS =====
13
+ const AUTH_CONFIG = {
14
+ // Nonce expiry buffer
15
+ NONCE_EXPIRY_BUFFER_MS: 60000};
16
+ // ===== EVENT SYSTEM CONSTANTS =====
17
+ const EVENT_CONFIG = {
18
+ // Event categories
19
+ CATEGORIES: {
20
+ USER: 'USER',
21
+ BEHAVIORAL: 'BE',
22
+ },
23
+ // Event statuses
24
+ STATUSES: {
25
+ PENDING: 'pending',
26
+ },
27
+ // Processing configuration
28
+ BATCH_SIZE: 50,
29
+ MAX_RETRY_ATTEMPTS: 5,
30
+ // Retry logic configuration
31
+ DEFAULT_RETRY_DELAYS: [60000, 120000, 240000, 480000, 900000], // Default retry delays in milliseconds
32
+ RETRYABLE_HTTP_CODES: [408, 429, 500, 502, 503, 504, 401],
33
+ // Response codes
34
+ GLOBAL_SUCCESS_CODE: 200,
35
+ PARTIAL_SUCCESS_CODE: 201,
36
+ };
37
+ // ===== STORAGE CONFIGURATION =====
38
+ // Base storage keys - use getStorageKey() for brand-aware keys
39
+ const BASE_STORAGE_KEYS = {
40
+ NONCE_DATA: 'websdk_nonce_data',
41
+ USER_CONTEXT: 'websdk_user_context',
42
+ DEVICE_ID: 'websdk_device_id',
43
+ SESSION_ID: 'websdk_session_id',
44
+ };
45
+ // Legacy export for backwards compatibility
46
+ const STORAGE_KEYS = BASE_STORAGE_KEYS;
47
+ /**
48
+ * Get isolation-aware storage key
49
+ * @param key - Base storage key
50
+ * @param brandId - Optional brand identifier
51
+ * @param applicationId - Optional application identifier
52
+ * @returns Isolated storage key with proper namespacing
53
+ */
54
+ function getStorageKey(key, brandId, applicationId) {
55
+ const baseKey = BASE_STORAGE_KEYS[key];
56
+ // Build namespace prefix
57
+ const namespaces = [];
58
+ if (brandId) {
59
+ namespaces.push(brandId);
60
+ }
61
+ if (applicationId) {
62
+ namespaces.push(applicationId);
63
+ }
64
+ return namespaces.length > 0 ? `${namespaces.join('_')}_${baseKey}` : baseKey;
65
+ }
66
+ const STORAGE_CONFIG = {
67
+ TEST_KEY: 'websdk_storage_test',
68
+ TEST_VALUE: 'test_value',
69
+ };
70
+ // ===== ERROR CODES =====
71
+ const ERROR_CODES = {
72
+ INITIALIZATION_ERROR: 'INIT_ERROR',
73
+ AUTHENTICATION_ERROR: 'AUTH_ERROR',
74
+ NETWORK_ERROR: 'NETWORK_ERROR',
75
+ EVENT_TRACKING_ERROR: 'EVENT_ERROR',
76
+ };
77
+ // ===== LOG MESSAGES =====
78
+ const LOG_MESSAGES = {
79
+ // Initialization
80
+ WEBSDK_INIT_SUCCESS: 'WebSDK initialized successfully',
81
+ WEBSDK_INIT_FAILED: 'Failed to initialize WebSDK',
82
+ WEBSDK_DESTROYED: 'WebSDK destroyed successfully',
83
+ // Authentication
84
+ AUTH_SUCCESS: 'Authentication successful',
85
+ AUTH_FAILED: 'Authentication failed',
86
+ AUTH_INIT_SUCCESS: 'AuthManager initialized successfully',
87
+ NONCE_REQUEST_SUCCESS: 'Nonce request successful',
88
+ NONCE_REQUEST_FAILED: 'Nonce request failed',
89
+ NONCE_EXPIRED: 'Nonce has expired',
90
+ SIGNATURE_GENERATION_SUCCESS: 'Request signature generated successfully',
91
+ SIGNATURE_GENERATION_FAILED: 'Failed to generate request signature',
92
+ NONCE_DATA_STORE_FAILED: 'Failed to store nonce data',
93
+ NONCE_DATA_RESTORE_FAILED: 'Failed to restore nonce data from storage',
94
+ NONCE_DATA_CLEAR_FAILED: 'Failed to clear stored nonce data',
95
+ // Events
96
+ EVENTS_INIT_SUCCESS: 'EventQueue initialized successfully',
97
+ EVENTS_TRACKER_INIT_SUCCESS: 'EventTracker initialized successfully',
98
+ EVENTS_TRACKER_DESTROYED: 'EventTracker destroyed successfully',
99
+ EVENT_ADDED: 'Event added to queue',
100
+ EVENT_TRACK_FAILED: 'Failed to track event',
101
+ EVENT_ENQUEUE_FAILED: 'Failed to enqueue event',
102
+ EVENTS_SENT_SUCCESS: 'Events sent successfully',
103
+ EVENTS_SEND_FAILED: 'Failed to send events',
104
+ BATCH_PROCESSED_SUCCESS: 'Batch processed successfully',
105
+ BATCH_SEND_SUCCESS: 'Batch sent successfully',
106
+ BATCH_SEND_FAILED: 'Failed to send batch',
107
+ BATCH_API_ERROR: 'Batch failed with API error',
108
+ QUEUE_PROCESSING_START: 'Starting queue processing',
109
+ QUEUE_PROCESSING_COMPLETE: 'Queue processing completed',
110
+ QUEUE_PROCESSING_FAILED: 'Queue processing failed',
111
+ QUEUE_PROCESSING_SKIP: 'Queue processing already in progress, skipping',
112
+ NO_PENDING_EVENTS: 'No pending events to process',
113
+ NO_MORE_PENDING_EVENTS: 'No more pending events',
114
+ EVENT_PERMANENTLY_FAILED: 'Event permanently failed after max retries',
115
+ EVENT_MARK_PROCESSING_FAILED: 'Failed to mark event as processing',
116
+ EVENT_STATUS_UPDATE_FAILED: 'Failed to update event status',
117
+ EVENT_REMOVE_FAILED: 'Failed to remove events from storage',
118
+ RETRYABLE_EVENTS_FAILED: 'Failed to process retryable events',
119
+ FLUSH_EVENTS_FAILED: 'Failed to flush events',
120
+ // Storage
121
+ STORAGE_INIT_FAILED: 'Failed to initialize storage:',
122
+ STORAGE_TEST_FAILED: 'Storage test failed:',
123
+ STORAGE_READ_WRITE_TEST_FAILED: 'Storage read/write test failed',
124
+ STORAGE_DESTROYED: 'StorageManager destroyed successfully',
125
+ STORAGE_CLEANUP_ERROR: 'Error during storage cleanup:',
126
+ // User events
127
+ USER_SIGNIN_FAILED: 'Failed to track user signin event',
128
+ USER_SIGNUP_FAILED: 'Failed to track user signup event',
129
+ USER_UPDATE_FAILED: 'Failed to track user update event',
130
+ USER_SIGNOUT_FAILED: 'Failed to track user signout event',
131
+ BEHAVIORAL_EVENT_FAILED: 'Failed to track behavioral event',
132
+ };
133
+ // ===== SYSTEM CONFIGURATION =====
134
+ const SYSTEM_CONFIG = {
135
+ OS_NAME: 'web',
136
+ PLATFORM: 'web',
137
+ DEFAULT_COUNTRY: '',
138
+ DEFAULT_CITY: '',
139
+ DEFAULT_COUNTRY_CODE: '',
140
+ };
141
+ // ===== USER EVENTS =====
142
+ const USER_EVENTS = {
143
+ USER_SIGNIN: 'user_signin',
144
+ USER_SIGNUP: 'user_signup',
145
+ USER_UPDATE: 'user_update',
146
+ USER_SIGNOUT: 'user_signout',
147
+ };
148
+ const SDK_VERSION = "1.0.0";
149
+
150
+ /**
151
+ * HTTP Client
152
+ * Core HTTP client with fetch API and error handling
153
+ */
154
+ class HttpClient {
155
+ constructor(config) {
156
+ this.baseUrl = config.baseUrl.replace(/\/$/, ''); // Remove trailing slash
157
+ }
158
+ /**
159
+ * Make HTTP request - single attempt only (retry handled at application level)
160
+ */
161
+ async request(endpoint, options = {}) {
162
+ const { method = 'GET', headers = {}, body } = options;
163
+ const normalizedEndpoint = !endpoint || endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
164
+ const url = `${this.baseUrl}${normalizedEndpoint}`;
165
+ try {
166
+ // Prepare request options
167
+ const requestOptions = {
168
+ method,
169
+ headers: {
170
+ 'Content-Type': 'application/json',
171
+ ...headers,
172
+ },
173
+ body: body ? JSON.stringify(body) : null,
174
+ };
175
+ // Execute single request
176
+ const response = await fetch(url, requestOptions);
177
+ // Handle HTTP errors
178
+ if (!response.ok) {
179
+ const errorText = await response.text();
180
+ throw new Error(`HTTP ${response.status}: ${response.statusText} - ${errorText}`);
181
+ }
182
+ const data = await response.json();
183
+ return data;
184
+ }
185
+ catch (error) {
186
+ throw this.handleError(error);
187
+ }
188
+ }
189
+ /**
190
+ * Handle and transform errors
191
+ */
192
+ handleError(error) {
193
+ if (error instanceof Error) {
194
+ if (error.name === 'AbortError') {
195
+ return {
196
+ code: ERROR_CODES.NETWORK_ERROR,
197
+ message: 'Request timeout',
198
+ details: error,
199
+ };
200
+ }
201
+ if (error.message.includes('HTTP 401') || error.message.includes('HTTP 403')) {
202
+ return {
203
+ code: ERROR_CODES.AUTHENTICATION_ERROR,
204
+ message: 'Authentication failed',
205
+ details: error,
206
+ };
207
+ }
208
+ if (error.message.includes('HTTP')) {
209
+ return {
210
+ code: ERROR_CODES.NETWORK_ERROR,
211
+ message: error.message,
212
+ details: error,
213
+ };
214
+ }
215
+ return {
216
+ code: ERROR_CODES.NETWORK_ERROR,
217
+ message: error.message,
218
+ details: error,
219
+ };
220
+ }
221
+ return {
222
+ code: ERROR_CODES.NETWORK_ERROR,
223
+ message: `Unknown error: ${String(error)}`,
224
+ details: error,
225
+ };
226
+ }
227
+ /**
228
+ * GET request helper
229
+ */
230
+ async get(endpoint, options = {}) {
231
+ return this.request(endpoint, { ...options, method: 'GET' });
232
+ }
233
+ /**
234
+ * POST request helper
235
+ */
236
+ async post(endpoint, body, options = {}) {
237
+ return this.request(endpoint, { ...options, method: 'POST', body });
238
+ }
239
+ /**
240
+ * PUT request helper
241
+ */
242
+ async put(endpoint, body, options = {}) {
243
+ return this.request(endpoint, { ...options, method: 'PUT', body });
244
+ }
245
+ /**
246
+ * DELETE request helper
247
+ */
248
+ async delete(endpoint, options = {}) {
249
+ return this.request(endpoint, { ...options, method: 'DELETE' });
250
+ }
251
+ }
252
+
253
+ /**
254
+ * UUID Generation Utility
255
+ */
256
+ /* global crypto */
257
+ function generateUUID() {
258
+ // Use crypto.randomUUID if available (modern browsers)
259
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) {
260
+ return crypto.randomUUID();
261
+ }
262
+ // Fallback to custom implementation
263
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
264
+ const r = (Math.random() * 16) | 0;
265
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
266
+ return v.toString(16);
267
+ });
268
+ }
269
+ function generateSessionId() {
270
+ return `session_${generateUUID()}`;
271
+ }
272
+
273
+ /**
274
+ * Signature generation utilities for nonce-based authentication
275
+ */
276
+ /**
277
+ * Generate HMAC-SHA256 signature for request authentication
278
+ * @param payload - The request payload to sign
279
+ * @param nonce - Server-provided nonce
280
+ * @param accountId - Account identifier
281
+ * @param deviceId - Device identifier
282
+ * @returns Promise<string> - Base64 encoded signature
283
+ */
284
+ async function generateRequestSignature(payload, nonce, accountId, deviceId) {
285
+ try {
286
+ // Use provided deviceId or generate one
287
+ const effectiveDeviceId = deviceId || generateDeviceId();
288
+ // Create signing data
289
+ const signingData = {
290
+ nonce,
291
+ account_id: accountId,
292
+ device_id: effectiveDeviceId,
293
+ timestamp: Date.now(),
294
+ payload: JSON.stringify(payload, Object.keys(payload).sort()),
295
+ };
296
+ // Convert to canonical string
297
+ const canonicalString = createCanonicalString(signingData);
298
+ // Generate signature key based on account and device
299
+ const signingKey = await generateSigningKey(accountId, effectiveDeviceId);
300
+ // Create HMAC-SHA256 signature
301
+ const signature = await createHMACSignature(canonicalString, signingKey);
302
+ return signature;
303
+ }
304
+ catch (error) {
305
+ throw new Error(`Signature generation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
306
+ }
307
+ }
308
+ /**
309
+ * Create canonical string from signing data
310
+ */
311
+ function createCanonicalString(data) {
312
+ // Sort keys and create deterministic string
313
+ const sortedKeys = Object.keys(data).sort();
314
+ const canonicalPairs = sortedKeys.map(key => `${key}=${data[key]}`);
315
+ return canonicalPairs.join('&');
316
+ }
317
+ /**
318
+ * Generate signing key based on account and device
319
+ */
320
+ async function generateSigningKey(accountId, deviceId) {
321
+ // Create deterministic key material from account and device
322
+ const keyMaterial = `${accountId}:${deviceId}:cap-hydra-web-sdk`;
323
+ // Hash the key material
324
+ const encoder = new TextEncoder();
325
+ const keyData = encoder.encode(keyMaterial);
326
+ const hashedKey = await crypto.subtle.digest('SHA-256', keyData);
327
+ // Import as HMAC key
328
+ return await crypto.subtle.importKey('raw', hashedKey, { name: 'HMAC', hash: 'SHA-256' }, false, [
329
+ 'sign',
330
+ ]);
331
+ }
332
+ /**
333
+ * Create HMAC-SHA256 signature
334
+ */
335
+ async function createHMACSignature(data, key) {
336
+ const encoder = new TextEncoder();
337
+ const dataBuffer = encoder.encode(data);
338
+ const signature = await crypto.subtle.sign('HMAC', key, dataBuffer);
339
+ // Convert to base64
340
+ return btoa(String.fromCharCode(...new Uint8Array(signature)));
341
+ }
342
+
343
+ /**
344
+ * System Data Utilities
345
+ * Utilities for collecting browser and system information
346
+ */
347
+ /**
348
+ * Generate a unique device ID for this browser/device
349
+ */
350
+ function generateDeviceId() {
351
+ // Import storage key constant
352
+ const DEVICE_ID_KEY = STORAGE_KEYS.DEVICE_ID;
353
+ // Try to get existing device ID from localStorage
354
+ const existingDeviceId = localStorage.getItem(DEVICE_ID_KEY);
355
+ if (existingDeviceId) {
356
+ return existingDeviceId;
357
+ }
358
+ // Generate new device ID and store it
359
+ const deviceId = generateUUID();
360
+ localStorage.setItem(DEVICE_ID_KEY, deviceId);
361
+ return deviceId;
362
+ }
363
+ /**
364
+ * Parse user agent to extract browser information
365
+ */
366
+ function parseBrowserInfo() {
367
+ const userAgent = navigator.userAgent;
368
+ // Extract browser name and version
369
+ let browserName = 'Unknown';
370
+ let browserVersion = 'Unknown';
371
+ if (userAgent.includes('Chrome')) {
372
+ browserName = 'Chrome';
373
+ const match = userAgent.match(/Chrome\/([0-9.]+)/);
374
+ browserVersion = match?.[1] ?? 'Unknown';
375
+ }
376
+ else if (userAgent.includes('Firefox')) {
377
+ browserName = 'Firefox';
378
+ const match = userAgent.match(/Firefox\/([0-9.]+)/);
379
+ browserVersion = match?.[1] ?? 'Unknown';
380
+ }
381
+ else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
382
+ browserName = 'Safari';
383
+ const match = userAgent.match(/Version\/([0-9.]+)/);
384
+ browserVersion = match?.[1] ?? 'Unknown';
385
+ }
386
+ else if (userAgent.includes('Edge')) {
387
+ browserName = 'Edge';
388
+ const match = userAgent.match(/Edge\/([0-9.]+)/);
389
+ browserVersion = match?.[1] ?? 'Unknown';
390
+ }
391
+ // Extract OS information
392
+ let osName = 'Unknown';
393
+ let osVersion = 'Unknown';
394
+ if (userAgent.includes('Windows')) {
395
+ osName = 'Windows';
396
+ if (userAgent.includes('Windows NT 10.0')) {
397
+ osVersion = '10';
398
+ }
399
+ else if (userAgent.includes('Windows NT 6.3')) {
400
+ osVersion = '8.1';
401
+ }
402
+ else if (userAgent.includes('Windows NT 6.2')) {
403
+ osVersion = '8';
404
+ }
405
+ else if (userAgent.includes('Windows NT 6.1')) {
406
+ osVersion = '7';
407
+ }
408
+ }
409
+ else if (userAgent.includes('Mac OS X')) {
410
+ osName = 'macOS';
411
+ const match = userAgent.match(/Mac OS X ([0-9_]+)/);
412
+ osVersion = match?.[1]?.replace(/_/g, '.') ?? 'Unknown';
413
+ }
414
+ else if (userAgent.includes('Linux')) {
415
+ osName = 'Linux';
416
+ osVersion = 'Unknown';
417
+ }
418
+ else if (userAgent.includes('Android')) {
419
+ osName = 'Android';
420
+ const match = userAgent.match(/Android ([0-9.]+)/);
421
+ osVersion = match?.[1] ?? 'Unknown';
422
+ }
423
+ else if (userAgent.includes('iPhone') || userAgent.includes('iPad')) {
424
+ osName = 'iOS';
425
+ const match = userAgent.match(/OS ([0-9_]+)/);
426
+ osVersion = match?.[1]?.replace(/_/g, '.') ?? 'Unknown';
427
+ }
428
+ return {
429
+ browserName,
430
+ browserVersion,
431
+ osName,
432
+ osVersion,
433
+ };
434
+ }
435
+ /**
436
+ * Get viewport dimensions
437
+ */
438
+ function getViewportDimensions() {
439
+ return {
440
+ width: window.innerWidth || document.documentElement.clientWidth || 0,
441
+ height: window.innerHeight || document.documentElement.clientHeight || 0,
442
+ };
443
+ }
444
+ /**
445
+ * Get timezone information
446
+ */
447
+ function getTimezone() {
448
+ try {
449
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
450
+ }
451
+ catch {
452
+ return 'UTC';
453
+ }
454
+ }
455
+ /**
456
+ * Get browser language
457
+ */
458
+ function getBrowserLanguage() {
459
+ return navigator.language || (navigator.languages && navigator.languages[0]) || 'en-US';
460
+ }
461
+ /**
462
+ * Get bundle identifier (hostname)
463
+ */
464
+ function getBundleIdentifier() {
465
+ return window.location.hostname || 'localhost';
466
+ }
467
+ /**
468
+ * Collect all system data
469
+ */
470
+ function collectSystemData(args) {
471
+ const browserInfo = parseBrowserInfo();
472
+ const viewport = getViewportDimensions();
473
+ const deviceId = generateDeviceId();
474
+ return {
475
+ os_version: browserInfo.osVersion,
476
+ country_code: args.country_code,
477
+ os_name: browserInfo.osName,
478
+ viewport_width: viewport.width,
479
+ country: args.country,
480
+ viewport_height: viewport.height,
481
+ device_id: deviceId,
482
+ bundle_identifier: getBundleIdentifier(),
483
+ last_seen: new Date().toISOString(),
484
+ city: args.city,
485
+ sdk_version: SDK_VERSION,
486
+ platform: 'web',
487
+ browser_name: browserInfo.browserName,
488
+ browser_version: browserInfo.browserVersion,
489
+ browser_language: getBrowserLanguage(),
490
+ timezone: getTimezone(),
491
+ };
492
+ }
493
+
494
+ /**
495
+ * API Client
496
+ * Main API client with OAuth and Events endpoints
497
+ */
498
+ class ApiClient {
499
+ constructor(config, logger, accountId) {
500
+ this.httpClient = new HttpClient(config);
501
+ this.logger = logger;
502
+ this.accountId = accountId;
503
+ }
504
+ /**
505
+ * Request a nonce for authentication
506
+ */
507
+ async getNonce(bundleIdentifier, deviceId) {
508
+ const effectiveDeviceId = deviceId || generateDeviceId();
509
+ this.logger.info('Requesting nonce', {
510
+ accountId: this.accountId,
511
+ bundleIdentifier,
512
+ deviceId: effectiveDeviceId,
513
+ });
514
+ const request = {
515
+ account_id: this.accountId,
516
+ bundle_identifier: bundleIdentifier,
517
+ device_id: effectiveDeviceId,
518
+ timestamp: Date.now(),
519
+ os_name: SYSTEM_CONFIG.OS_NAME,
520
+ };
521
+ try {
522
+ const response = await this.httpClient.post(API_ENDPOINTS.NONCE_REQUEST, request);
523
+ this.logger.info(LOG_MESSAGES.NONCE_REQUEST_SUCCESS, {
524
+ challengeId: response.challenge_id,
525
+ expiresAt: response.expires_at,
526
+ });
527
+ return response;
528
+ }
529
+ catch (error) {
530
+ this.logger.error(LOG_MESSAGES.NONCE_REQUEST_FAILED, error);
531
+ throw error;
532
+ }
533
+ }
534
+ /**
535
+ * Send events to the server with nonce-based authentication via headers
536
+ */
537
+ async sendEvents(events, cuid, systemDataArgs, nonce, challengeId, deviceId) {
538
+ this.logger.info('Sending events', { eventCount: events.length, cuid, challengeId });
539
+ const effectiveDeviceId = deviceId || generateDeviceId();
540
+ // Collect system data
541
+ const systemData = collectSystemData(systemDataArgs);
542
+ // Create request payload (clean business data only)
543
+ const requestPayload = {
544
+ system_data: systemData,
545
+ request_id: generateUUID(),
546
+ events,
547
+ cuid,
548
+ };
549
+ try {
550
+ // Generate signature for the request (includes nonce data for signing)
551
+ const signature = await generateRequestSignature({ ...requestPayload, nonce, challenge_id: challengeId }, nonce, this.accountId, effectiveDeviceId);
552
+ this.logger.info(LOG_MESSAGES.SIGNATURE_GENERATION_SUCCESS, {
553
+ requestId: requestPayload.request_id,
554
+ challengeId,
555
+ });
556
+ // Create authentication headers
557
+ const authHeaders = {
558
+ 'X-Cap-Nonce': nonce,
559
+ 'X-Cap-Challenge-ID': challengeId,
560
+ 'X-Cap-Signature': signature,
561
+ 'X-Cap-Device-ID': effectiveDeviceId,
562
+ };
563
+ const response = await this.httpClient.post(API_ENDPOINTS.MAPP_EVENTS, requestPayload, { headers: authHeaders });
564
+ this.logger.info(LOG_MESSAGES.EVENTS_SENT_SUCCESS, {
565
+ requestId: requestPayload.request_id,
566
+ eventCount: events.length,
567
+ success: response.status.success,
568
+ });
569
+ return response;
570
+ }
571
+ catch (error) {
572
+ this.logger.error(LOG_MESSAGES.EVENTS_SEND_FAILED, {
573
+ requestId: requestPayload.request_id,
574
+ eventCount: events.length,
575
+ error,
576
+ });
577
+ throw error;
578
+ }
579
+ }
580
+ }
581
+ /**
582
+ * Helper function to create event payload
583
+ */
584
+ function createEventPayload(category, name, attributes, cuid) {
585
+ const deviceId = generateDeviceId();
586
+ return {
587
+ category,
588
+ attributes: {
589
+ ...attributes,
590
+ device_id: deviceId,
591
+ cuid,
592
+ },
593
+ name,
594
+ created_at: new Date().toISOString(),
595
+ event_id: generateUUID(),
596
+ };
597
+ }
598
+
599
+ /**
600
+ * IndexedDB Storage Adapter
601
+ * Provides IndexedDB-based storage for larger data sets and event queuing
602
+ */
603
+ /**
604
+ * IndexedDBStorage serves dual purposes:
605
+ * 1. General Storage: Key-value pairs for auth tokens, config, etc. (uses 'data' object store)
606
+ * 2. Event Queue: Complex event management with retry logic (uses 'events' object store)
607
+ */
608
+ class IndexedDBStorage {
609
+ constructor(dbName = 'WebSDK', version = 2, storeName = 'data') {
610
+ this.db = null;
611
+ this.dbName = dbName;
612
+ this.version = version;
613
+ this.storeName = storeName; // General key-value storage
614
+ this.eventsStoreName = 'events'; // Event queue storage
615
+ }
616
+ async openDB() {
617
+ if (this.db) {
618
+ return this.db;
619
+ }
620
+ return new Promise((resolve, reject) => {
621
+ const request = indexedDB.open(this.dbName, this.version);
622
+ request.onerror = () => reject(request.error);
623
+ request.onsuccess = () => {
624
+ this.db = request.result;
625
+ resolve(this.db);
626
+ };
627
+ request.onupgradeneeded = event => {
628
+ const db = event.target.result;
629
+ // Create data store for general key-value storage (auth tokens, config, etc.)
630
+ if (!db.objectStoreNames.contains(this.storeName)) {
631
+ db.createObjectStore(this.storeName);
632
+ }
633
+ // Create events store for event queuing and batch processing
634
+ if (!db.objectStoreNames.contains(this.eventsStoreName)) {
635
+ const eventsStore = db.createObjectStore(this.eventsStoreName, { keyPath: 'id' });
636
+ eventsStore.createIndex('timestamp', 'timestamp', { unique: false });
637
+ eventsStore.createIndex('status', 'status', { unique: false });
638
+ }
639
+ };
640
+ });
641
+ }
642
+ // ===== GENERAL STORAGE METHODS (StorageAdapter Interface) =====
643
+ // Used by StorageManager for auth tokens, config, and other key-value data
644
+ async getItem(key) {
645
+ const db = await this.openDB();
646
+ return new Promise((resolve, reject) => {
647
+ const transaction = db.transaction([this.storeName], 'readonly');
648
+ const store = transaction.objectStore(this.storeName);
649
+ const request = store.get(key);
650
+ request.onerror = () => reject(request.error);
651
+ request.onsuccess = () => {
652
+ const result = request.result;
653
+ if (result === undefined || result === null) {
654
+ resolve(null);
655
+ }
656
+ else if (typeof result === 'string') {
657
+ resolve(result);
658
+ }
659
+ else {
660
+ // Convert any non-string data to string (e.g., objects stored directly)
661
+ resolve(typeof result === 'object' ? JSON.stringify(result) : String(result));
662
+ }
663
+ };
664
+ });
665
+ }
666
+ async setItem(key, value) {
667
+ const db = await this.openDB();
668
+ return new Promise((resolve, reject) => {
669
+ const transaction = db.transaction([this.storeName], 'readwrite');
670
+ const store = transaction.objectStore(this.storeName);
671
+ const request = store.put(value, key);
672
+ request.onerror = () => reject(request.error);
673
+ request.onsuccess = () => resolve();
674
+ });
675
+ }
676
+ async removeItem(key) {
677
+ const db = await this.openDB();
678
+ return new Promise((resolve, reject) => {
679
+ const transaction = db.transaction([this.storeName], 'readwrite');
680
+ const store = transaction.objectStore(this.storeName);
681
+ const request = store.delete(key);
682
+ request.onerror = () => reject(request.error);
683
+ request.onsuccess = () => resolve();
684
+ });
685
+ }
686
+ async clear() {
687
+ const db = await this.openDB();
688
+ return new Promise((resolve, reject) => {
689
+ const transaction = db.transaction([this.storeName], 'readwrite');
690
+ const store = transaction.objectStore(this.storeName);
691
+ const request = store.clear();
692
+ request.onerror = () => reject(request.error);
693
+ request.onsuccess = () => resolve();
694
+ });
695
+ }
696
+ async close() {
697
+ if (this.db) {
698
+ this.db.close();
699
+ this.db = null;
700
+ }
701
+ }
702
+ // ===== EVENT QUEUE METHODS =====
703
+ // The following methods are specifically for event queuing and batch processing
704
+ /**
705
+ * Add event to the queue
706
+ */
707
+ async addEvent(queuedEvent) {
708
+ const db = await this.openDB();
709
+ return new Promise((resolve, reject) => {
710
+ const transaction = db.transaction([this.eventsStoreName], 'readwrite');
711
+ const store = transaction.objectStore(this.eventsStoreName);
712
+ const request = store.add(queuedEvent);
713
+ request.onerror = () => reject(request.error);
714
+ request.onsuccess = () => resolve();
715
+ });
716
+ }
717
+ /**
718
+ * Get oldest pending events (up to limit)
719
+ */
720
+ async getOldestPendingEvents(limit = 50, accountId) {
721
+ const db = await this.openDB();
722
+ return new Promise((resolve, reject) => {
723
+ const transaction = db.transaction([this.eventsStoreName], 'readonly');
724
+ const store = transaction.objectStore(this.eventsStoreName);
725
+ const index = store.index('timestamp');
726
+ const request = index.openCursor();
727
+ const events = [];
728
+ let count = 0;
729
+ request.onerror = () => reject(request.error);
730
+ request.onsuccess = event => {
731
+ const cursor = event.target.result;
732
+ if (cursor && count < limit) {
733
+ const queuedEvent = cursor.value;
734
+ if (queuedEvent.status === 'pending' && queuedEvent.accountId === accountId) {
735
+ events.push(queuedEvent);
736
+ count++;
737
+ }
738
+ cursor.continue();
739
+ }
740
+ else {
741
+ resolve(events);
742
+ }
743
+ };
744
+ });
745
+ }
746
+ /**
747
+ * Update event status
748
+ */
749
+ async updateEventStatus(eventId, status, error, attempts) {
750
+ const db = await this.openDB();
751
+ return new Promise((resolve, reject) => {
752
+ const transaction = db.transaction([this.eventsStoreName], 'readwrite');
753
+ const store = transaction.objectStore(this.eventsStoreName);
754
+ const getRequest = store.get(eventId);
755
+ getRequest.onerror = () => reject(getRequest.error);
756
+ getRequest.onsuccess = () => {
757
+ const event = getRequest.result;
758
+ if (event) {
759
+ event.status = status;
760
+ event.lastAttempt = Date.now();
761
+ if (error) {
762
+ event.error = error;
763
+ }
764
+ if (attempts !== undefined) {
765
+ event.attempts = attempts;
766
+ }
767
+ const putRequest = store.put(event);
768
+ putRequest.onerror = () => reject(putRequest.error);
769
+ putRequest.onsuccess = () => resolve();
770
+ }
771
+ else {
772
+ reject(new Error(`Event with id ${eventId} not found`));
773
+ }
774
+ };
775
+ });
776
+ }
777
+ /**
778
+ * Remove events by IDs
779
+ */
780
+ async removeEvents(eventIds) {
781
+ const db = await this.openDB();
782
+ return new Promise((resolve, reject) => {
783
+ const transaction = db.transaction([this.eventsStoreName], 'readwrite');
784
+ const store = transaction.objectStore(this.eventsStoreName);
785
+ let completed = 0;
786
+ const total = eventIds.length;
787
+ if (total === 0) {
788
+ resolve();
789
+ return;
790
+ }
791
+ eventIds.forEach(id => {
792
+ const request = store.delete(id);
793
+ request.onerror = () => reject(request.error);
794
+ request.onsuccess = () => {
795
+ completed++;
796
+ if (completed === total) {
797
+ resolve();
798
+ }
799
+ };
800
+ });
801
+ });
802
+ }
803
+ /**
804
+ * Get total count of pending events for a specific user
805
+ */
806
+ /**
807
+ * Recover orphaned processing events (e.g., after tab close during API call)
808
+ */
809
+ async recoverOrphanedEvents(accountId) {
810
+ const db = await this.openDB();
811
+ return new Promise((resolve, reject) => {
812
+ const transaction = db.transaction([this.eventsStoreName], 'readwrite');
813
+ const store = transaction.objectStore(this.eventsStoreName);
814
+ const request = store.openCursor();
815
+ let recoveredCount = 0;
816
+ request.onerror = () => reject(request.error);
817
+ request.onsuccess = event => {
818
+ const cursor = event.target.result;
819
+ if (cursor) {
820
+ const queuedEvent = cursor.value;
821
+ if (queuedEvent.status === 'processing' && queuedEvent.accountId === accountId) {
822
+ // Reset processing events back to failed for retry
823
+ queuedEvent.status = 'failed';
824
+ queuedEvent.lastAttempt = Date.now();
825
+ queuedEvent.error = 'Recovered from orphaned processing state';
826
+ const updateRequest = cursor.update(queuedEvent);
827
+ updateRequest.onsuccess = () => {
828
+ recoveredCount++;
829
+ };
830
+ }
831
+ cursor.continue();
832
+ }
833
+ else {
834
+ resolve(recoveredCount);
835
+ }
836
+ };
837
+ });
838
+ }
839
+ async getPendingEventCount(accountId) {
840
+ const db = await this.openDB();
841
+ return new Promise((resolve, reject) => {
842
+ const transaction = db.transaction([this.eventsStoreName], 'readonly');
843
+ const store = transaction.objectStore(this.eventsStoreName);
844
+ const request = store.openCursor();
845
+ let count = 0;
846
+ request.onerror = () => reject(request.error);
847
+ request.onsuccess = event => {
848
+ const cursor = event.target.result;
849
+ if (cursor) {
850
+ const queuedEvent = cursor.value;
851
+ if (queuedEvent.status === 'pending' && queuedEvent.accountId === accountId) {
852
+ count++;
853
+ }
854
+ cursor.continue();
855
+ }
856
+ else {
857
+ resolve(count);
858
+ }
859
+ };
860
+ });
861
+ }
862
+ /**
863
+ * Get failed events that can be retried
864
+ */
865
+ async getRetryableEvents(maxAttempts = 5, accountId) {
866
+ const db = await this.openDB();
867
+ return new Promise((resolve, reject) => {
868
+ const transaction = db.transaction([this.eventsStoreName], 'readonly');
869
+ const store = transaction.objectStore(this.eventsStoreName);
870
+ const request = store.openCursor();
871
+ const events = [];
872
+ request.onerror = () => reject(request.error);
873
+ request.onsuccess = event => {
874
+ const cursor = event.target.result;
875
+ if (cursor) {
876
+ const queuedEvent = cursor.value;
877
+ if (queuedEvent.status === 'failed' &&
878
+ queuedEvent.attempts <= maxAttempts &&
879
+ queuedEvent.accountId === accountId) {
880
+ events.push(queuedEvent);
881
+ }
882
+ cursor.continue();
883
+ }
884
+ else {
885
+ resolve(events);
886
+ }
887
+ };
888
+ });
889
+ }
890
+ }
891
+
892
+ /**
893
+ * Event Queue with Concurrency Control
894
+ * Handles event queuing, batch processing, and network concurrency control with IndexedDB persistence
895
+ */
896
+ class EventQueue {
897
+ constructor(authManager, logger, storageManagerOrStorage, retryDelays) {
898
+ this.systemDataArgs = null;
899
+ this.currentAccountId = null; // Used for filtering events in IndexedDB
900
+ this.currentCuid = null; // Used for event data
901
+ // Concurrency control
902
+ this.isProcessing = false;
903
+ this.processingPromise = null;
904
+ // Configuration
905
+ this.BATCH_SIZE = EVENT_CONFIG.BATCH_SIZE;
906
+ this.authManager = authManager;
907
+ this.logger = logger;
908
+ // Set retry delays (configurable or use default)
909
+ this.RETRY_DELAYS = retryDelays || EVENT_CONFIG.DEFAULT_RETRY_DELAYS;
910
+ // If StorageManager is passed, get its IndexedDB adapter
911
+ if (storageManagerOrStorage && 'getIndexedDBAdapter' in storageManagerOrStorage) {
912
+ // It's a StorageManager, get the IndexedDB adapter
913
+ const storageManager = storageManagerOrStorage;
914
+ const indexedDBAdapter = storageManager.getIndexedDBAdapter();
915
+ if (indexedDBAdapter) {
916
+ logger.info('EventQueue: Reusing existing IndexedDB adapter from StorageManager');
917
+ this.storage = indexedDBAdapter;
918
+ }
919
+ else {
920
+ logger.warn('EventQueue: StorageManager has no IndexedDB adapter, creating new one');
921
+ this.storage = new IndexedDBStorage();
922
+ }
923
+ }
924
+ else if (storageManagerOrStorage) {
925
+ // It's already an IndexedDBStorage
926
+ logger.info('EventQueue: Using provided IndexedDBStorage');
927
+ this.storage = storageManagerOrStorage;
928
+ }
929
+ else {
930
+ // Fallback to creating new instance (for backward compatibility)
931
+ logger.warn('EventQueue: No storage provided, creating new IndexedDBStorage');
932
+ this.storage = new IndexedDBStorage();
933
+ }
934
+ }
935
+ /**
936
+ * Initialize the event queue
937
+ */
938
+ async init() {
939
+ this.logger.info('Initializing EventQueue');
940
+ // Process any existing events on startup
941
+ await this.processQueueIfIdle();
942
+ this.logger.info('EventQueue initialized successfully');
943
+ }
944
+ /**
945
+ * Set user context for events
946
+ */
947
+ async setUserContext(accountId, systemDataArgs, cuid) {
948
+ this.currentAccountId = accountId; // Used for filtering events in IndexedDB
949
+ this.currentCuid = cuid || null; // Used for event data
950
+ this.systemDataArgs = systemDataArgs;
951
+ this.logger.debug('EventQueue user context set', { accountId, cuid, systemDataArgs });
952
+ // Recover any orphaned processing events for this account
953
+ const recoveredCount = await this.storage.recoverOrphanedEvents(accountId);
954
+ if (recoveredCount > 0) {
955
+ this.logger.info(`Recovered ${recoveredCount} orphaned processing events for account ${accountId}`);
956
+ }
957
+ }
958
+ /**
959
+ * Get current account ID (used for filtering)
960
+ */
961
+ getCurrentAccountId() {
962
+ return this.currentAccountId;
963
+ }
964
+ /**
965
+ * Get current CUID (used for event data)
966
+ */
967
+ getCurrentCuid() {
968
+ return this.currentCuid;
969
+ }
970
+ /**
971
+ * Add event to queue and process if possible
972
+ */
973
+ async enqueue(event) {
974
+ try {
975
+ // Create queued event with account context
976
+ if (!this.currentAccountId) {
977
+ throw new Error('Cannot enqueue event: No account context set');
978
+ }
979
+ const queuedEvent = {
980
+ id: generateUUID(),
981
+ event,
982
+ accountId: this.currentAccountId,
983
+ timestamp: new Date().toISOString(),
984
+ attempts: 0,
985
+ status: EVENT_CONFIG.STATUSES.PENDING,
986
+ };
987
+ // Store in IndexedDB
988
+ await this.storage.addEvent(queuedEvent);
989
+ this.logger.debug('Event added to queue', {
990
+ eventId: queuedEvent.id,
991
+ eventType: event.category,
992
+ eventName: event.name,
993
+ });
994
+ // Process queue if no active network call
995
+ await this.processQueueIfIdle();
996
+ }
997
+ catch (error) {
998
+ this.logger.error('Failed to enqueue event', { event, error });
999
+ throw error;
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Process queue only if not already processing
1004
+ */
1005
+ async processQueueIfIdle() {
1006
+ if (this.isProcessing) {
1007
+ this.logger.debug('Queue processing already in progress, skipping');
1008
+ return;
1009
+ }
1010
+ if (!this.processingPromise) {
1011
+ this.processingPromise = this.processQueue();
1012
+ }
1013
+ return this.processingPromise;
1014
+ }
1015
+ /**
1016
+ * Main queue processing logic with concurrency control
1017
+ */
1018
+ async processQueue() {
1019
+ if (this.isProcessing) {
1020
+ return;
1021
+ }
1022
+ this.isProcessing = true;
1023
+ this.logger.debug('Starting queue processing');
1024
+ try {
1025
+ while (true) {
1026
+ // Check for ready retry events before each batch
1027
+ // This naturally handles user context isolation since only the current user's
1028
+ // events get processed when they're active in the app
1029
+ await this.checkAndPromoteRetryEvents();
1030
+ // Get oldest pending events for current account (up to batch size)
1031
+ if (!this.currentAccountId) {
1032
+ this.logger.debug('No account context, skipping event processing');
1033
+ break;
1034
+ }
1035
+ const pendingEvents = await this.storage.getOldestPendingEvents(this.BATCH_SIZE, this.currentAccountId);
1036
+ if (pendingEvents.length === 0) {
1037
+ this.logger.debug('No pending events to process');
1038
+ break;
1039
+ }
1040
+ this.logger.info('Processing batch of events', {
1041
+ batchSize: pendingEvents.length,
1042
+ eventIds: pendingEvents.map(e => e.id),
1043
+ });
1044
+ // Mark events as processing
1045
+ await this.markEventsAsProcessing(pendingEvents);
1046
+ // Send batch to API
1047
+ await this.sendBatch(pendingEvents);
1048
+ // Continue processing if there might be more events
1049
+ const remainingCount = await this.storage.getPendingEventCount(this.currentAccountId);
1050
+ if (remainingCount === 0) {
1051
+ this.logger.debug('No more pending events');
1052
+ break;
1053
+ }
1054
+ }
1055
+ }
1056
+ catch (error) {
1057
+ this.logger.error('Queue processing failed', error);
1058
+ }
1059
+ finally {
1060
+ this.isProcessing = false;
1061
+ this.processingPromise = null;
1062
+ this.logger.debug('Queue processing completed');
1063
+ }
1064
+ }
1065
+ /**
1066
+ * Mark events as processing
1067
+ */
1068
+ async markEventsAsProcessing(events) {
1069
+ for (const event of events) {
1070
+ try {
1071
+ await this.storage.updateEventStatus(event.id, 'processing');
1072
+ }
1073
+ catch (error) {
1074
+ this.logger.warn('Failed to mark event as processing', { eventId: event.id, error });
1075
+ }
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Send batch of events to API
1080
+ */
1081
+ async sendBatch(events) {
1082
+ try {
1083
+ if (!this.currentAccountId) {
1084
+ throw new Error('Missing account context for batch sending');
1085
+ }
1086
+ // Get fresh nonce data (automatically refreshes if needed)
1087
+ const nonceData = await this.authManager.getNonceData();
1088
+ const apiClient = this.authManager.getApiClient();
1089
+ const eventPayloads = events.map(e => e.event);
1090
+ const response = await apiClient.sendEvents(eventPayloads, this.currentCuid || '', this.systemDataArgs || {
1091
+ country: SYSTEM_CONFIG.DEFAULT_COUNTRY,
1092
+ city: SYSTEM_CONFIG.DEFAULT_CITY,
1093
+ country_code: SYSTEM_CONFIG.DEFAULT_COUNTRY_CODE,
1094
+ }, nonceData.nonce, nonceData.challengeId, nonceData.deviceId);
1095
+ // Handle response based on new logic
1096
+ await this.handleBatchResponse(events, response);
1097
+ return true; // Always return true as we handle individual events
1098
+ }
1099
+ catch (error) {
1100
+ // TODO: Check error structure matches expected API response
1101
+ // Check if this is a retryable HTTP error
1102
+ const isRetryable = this.isRetryableHttpError(error);
1103
+ this.logger.error('Failed to send batch', {
1104
+ batchSize: events.length,
1105
+ error,
1106
+ isRetryable,
1107
+ });
1108
+ if (isRetryable) {
1109
+ // Mark all events for retry
1110
+ await this.handleFailedBatch(events);
1111
+ }
1112
+ else {
1113
+ // Remove non-retryable events permanently
1114
+ await this.removeNonRetryableEvents(events);
1115
+ }
1116
+ return false;
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Remove successfully sent events from storage
1121
+ */
1122
+ async removeSuccessfulEvents(events) {
1123
+ const eventIds = events.map(e => e.id);
1124
+ try {
1125
+ await this.storage.removeEvents(eventIds);
1126
+ this.logger.debug('Successfully removed events from storage', { count: eventIds.length });
1127
+ }
1128
+ catch (error) {
1129
+ this.logger.error('Failed to remove events from storage', { eventIds, error });
1130
+ }
1131
+ }
1132
+ /**
1133
+ * Handle batch response with individual event processing
1134
+ */
1135
+ async handleBatchResponse(events, response) {
1136
+ const globalCode = response.status.code;
1137
+ if (globalCode === EVENT_CONFIG.GLOBAL_SUCCESS_CODE) {
1138
+ // All events succeeded - remove all from storage
1139
+ await this.removeSuccessfulEvents(events);
1140
+ this.logger.info('All events processed successfully', { count: events.length });
1141
+ }
1142
+ else if (globalCode === EVENT_CONFIG.PARTIAL_SUCCESS_CODE) {
1143
+ // Some events failed - handle individually
1144
+ await this.handlePartialSuccess(events, response.events);
1145
+ }
1146
+ else {
1147
+ // Check if global error is retryable
1148
+ const isRetryable = EVENT_CONFIG.RETRYABLE_HTTP_CODES.includes(parseInt(globalCode));
1149
+ if (isRetryable) {
1150
+ await this.handleFailedBatch(events);
1151
+ this.logger.warn('Batch failed with retryable error', {
1152
+ code: globalCode,
1153
+ message: response.status.message,
1154
+ });
1155
+ }
1156
+ else {
1157
+ await this.removeNonRetryableEvents(events);
1158
+ this.logger.error('Batch failed with non-retryable error', {
1159
+ code: globalCode,
1160
+ message: response.status.message,
1161
+ });
1162
+ }
1163
+ }
1164
+ }
1165
+ /**
1166
+ * Handle partial success response (code 201)
1167
+ */
1168
+ async handlePartialSuccess(events, eventResults) {
1169
+ const eventResultMap = new Map();
1170
+ eventResults.forEach(result => {
1171
+ eventResultMap.set(result.event_id, result);
1172
+ });
1173
+ for (const event of events) {
1174
+ const result = eventResultMap.get(event.event.event_id);
1175
+ if (!result) {
1176
+ // No result for this event - treat as failed and retry
1177
+ await this.markEventForRetry(event, 'No response received');
1178
+ continue;
1179
+ }
1180
+ if (result.status.success) {
1181
+ // Event succeeded - remove from storage
1182
+ await this.storage.removeEvents([event.id]);
1183
+ this.logger.debug('Event processed successfully', { eventId: event.id });
1184
+ }
1185
+ else {
1186
+ // Event failed - check if retryable
1187
+ const eventCode = parseInt(result.status.code);
1188
+ const isRetryable = EVENT_CONFIG.RETRYABLE_HTTP_CODES.includes(eventCode);
1189
+ if (isRetryable) {
1190
+ await this.markEventForRetry(event, result.status.message);
1191
+ this.logger.debug('Event marked for retry', {
1192
+ eventId: event.id,
1193
+ code: eventCode,
1194
+ message: result.status.message,
1195
+ });
1196
+ }
1197
+ else {
1198
+ await this.storage.removeEvents([event.id]);
1199
+ this.logger.warn('Event permanently failed - removed', {
1200
+ eventId: event.id,
1201
+ code: eventCode,
1202
+ message: result.status.message,
1203
+ });
1204
+ }
1205
+ }
1206
+ }
1207
+ }
1208
+ /**
1209
+ * Mark individual event for retry with infinite retry logic
1210
+ */
1211
+ async markEventForRetry(event, errorMessage) {
1212
+ const newAttempts = (event.attempts || 0) + 1;
1213
+ // Always mark as failed initially, no max attempts limit
1214
+ await this.storage.updateEventStatus(event.id, 'failed', `Attempt ${newAttempts} failed: ${errorMessage}`, newAttempts);
1215
+ // Get delay based on attempt number or use last delay for infinite retry
1216
+ const attemptIndex = Math.min(Math.max(newAttempts - 1, 0), this.RETRY_DELAYS.length - 1);
1217
+ const delay = this.RETRY_DELAYS[attemptIndex];
1218
+ this.logger.debug('Event marked for retry', {
1219
+ eventId: event.id,
1220
+ attempts: newAttempts,
1221
+ delay,
1222
+ isInfiniteRetry: newAttempts > this.RETRY_DELAYS.length,
1223
+ });
1224
+ // No immediate retry - all events wait for their designated delay period
1225
+ }
1226
+ /**
1227
+ * Check all failed events and promote ready ones to pending
1228
+ * Called before each batch in processQueue - natural event-driven retry
1229
+ */
1230
+ async checkAndPromoteRetryEvents() {
1231
+ try {
1232
+ if (!this.currentAccountId) {
1233
+ this.logger.debug('No account context, skipping retry check');
1234
+ return;
1235
+ }
1236
+ // Get all failed events for this account (no max attempts limit for infinite retry)
1237
+ const retryableEvents = await this.storage.getRetryableEvents(Number.MAX_SAFE_INTEGER, this.currentAccountId);
1238
+ if (retryableEvents.length === 0) {
1239
+ return;
1240
+ }
1241
+ let promotedCount = 0;
1242
+ for (const event of retryableEvents) {
1243
+ const attemptIndex = Math.min(Math.max(event.attempts - 1, 0), this.RETRY_DELAYS.length - 1);
1244
+ const delay = this.RETRY_DELAYS[attemptIndex];
1245
+ const timeSinceLastAttempt = Date.now() - (event.lastAttempt || 0);
1246
+ if (timeSinceLastAttempt >= (delay || 0)) {
1247
+ // Event is ready to retry - mark as pending
1248
+ await this.storage.updateEventStatus(event.id, 'pending');
1249
+ promotedCount++;
1250
+ this.logger.debug('Failed event promoted to pending', {
1251
+ eventId: event.id,
1252
+ attempt: event.attempts + 1,
1253
+ delay,
1254
+ timeSinceLastAttempt,
1255
+ });
1256
+ }
1257
+ }
1258
+ if (promotedCount > 0) {
1259
+ this.logger.debug(`Promoted ${promotedCount} failed events for retry`);
1260
+ }
1261
+ }
1262
+ catch (error) {
1263
+ this.logger.error('Failed to check retry events', error);
1264
+ }
1265
+ }
1266
+ /**
1267
+ * Check if HTTP error is retryable
1268
+ */
1269
+ isRetryableHttpError(error) {
1270
+ // Check for network errors, timeouts, etc.
1271
+ if (error.code) {
1272
+ const httpCode = parseInt(error.code);
1273
+ return EVENT_CONFIG.RETRYABLE_HTTP_CODES.includes(httpCode);
1274
+ }
1275
+ // Default to retryable for network issues
1276
+ return (error.message?.includes('network') ||
1277
+ error.message?.includes('timeout') ||
1278
+ error.message?.includes('fetch'));
1279
+ }
1280
+ /**
1281
+ * Remove events that have non-retryable errors
1282
+ */
1283
+ async removeNonRetryableEvents(events) {
1284
+ const eventIds = events.map(e => e.id);
1285
+ try {
1286
+ await this.storage.removeEvents(eventIds);
1287
+ this.logger.warn('Non-retryable events removed permanently', { eventIds });
1288
+ }
1289
+ catch (error) {
1290
+ this.logger.error('Failed to remove non-retryable events', { eventIds, error });
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Handle failed batch by updating status and attempts
1295
+ */
1296
+ async handleFailedBatch(events) {
1297
+ for (const event of events) {
1298
+ try {
1299
+ await this.markEventForRetry(event, 'Batch failed');
1300
+ }
1301
+ catch (error) {
1302
+ this.logger.error('Failed to mark event for retry', { eventId: event.id, error });
1303
+ }
1304
+ }
1305
+ }
1306
+ /**
1307
+ * Manually flush all pending events
1308
+ */
1309
+ async flush() {
1310
+ this.logger.info('Manual flush requested');
1311
+ await this.processQueueIfIdle();
1312
+ }
1313
+ /**
1314
+ * Destroy the queue and cleanup
1315
+ */
1316
+ async destroy() {
1317
+ this.logger.info('Destroying EventQueue');
1318
+ // Wait for current processing to complete
1319
+ if (this.processingPromise) {
1320
+ await this.processingPromise;
1321
+ }
1322
+ // Close storage
1323
+ await this.storage.close();
1324
+ this.logger.info('EventQueue destroyed');
1325
+ }
1326
+ async clear() {
1327
+ // This would require implementing a clear method in IndexedDBStorage
1328
+ this.logger.warn('Clear method not implemented for IndexedDB queue');
1329
+ }
1330
+ }
1331
+
1332
+ /**
1333
+ * Event Tracker
1334
+ * Main event tracking logic with IndexedDB queue and concurrency control
1335
+ */
1336
+ class EventTracker {
1337
+ constructor(config, authManager, storageManager, logger) {
1338
+ this.eventQueue = null;
1339
+ this.initialized = false;
1340
+ this.config = config;
1341
+ this.logger = logger;
1342
+ this.authManager = authManager;
1343
+ this.storageManager = storageManager;
1344
+ // EventQueue will be created in init() after StorageManager is initialized
1345
+ }
1346
+ async init() {
1347
+ if (this.initialized) {
1348
+ this.logger.warn('EventTracker already initialized');
1349
+ return;
1350
+ }
1351
+ this.logger.info('Initializing EventTracker with IndexedDB queue');
1352
+ // Create EventQueue now that StorageManager is initialized
1353
+ this.eventQueue = new EventQueue(this.authManager, this.logger, this.storageManager, this.config.retryDelays);
1354
+ // Initialize event queue
1355
+ await this.eventQueue.init();
1356
+ this.initialized = true;
1357
+ this.logger.info(LOG_MESSAGES.EVENTS_TRACKER_INIT_SUCCESS);
1358
+ }
1359
+ /**
1360
+ * Set user context for event tracking
1361
+ */
1362
+ async setUserContext(accountId, systemDataArgs, cuid) {
1363
+ if (!this.eventQueue) {
1364
+ throw new Error('EventTracker not initialized');
1365
+ }
1366
+ await this.eventQueue.setUserContext(accountId, systemDataArgs, cuid);
1367
+ this.logger.info('User context set', { accountId, systemDataArgs, cuid });
1368
+ }
1369
+ /**
1370
+ * Track an event
1371
+ */
1372
+ async track(event) {
1373
+ if (!this.initialized || !this.eventQueue) {
1374
+ throw new Error('EventTracker not initialized');
1375
+ }
1376
+ this.logger.debug('Tracking event', { event });
1377
+ try {
1378
+ // Convert SDK event to API event payload
1379
+ const eventPayload = this.convertToApiEvent(event);
1380
+ // Add to IndexedDB queue (will automatically process if no active network call)
1381
+ await this.eventQueue.enqueue(eventPayload);
1382
+ }
1383
+ catch (error) {
1384
+ this.logger.error(LOG_MESSAGES.EVENT_TRACK_FAILED, { event, error });
1385
+ throw new Error(`${ERROR_CODES.EVENT_TRACKING_ERROR}: ${error}`);
1386
+ }
1387
+ }
1388
+ /**
1389
+ * Convert SDK event to API event payload
1390
+ */
1391
+ convertToApiEvent(event) {
1392
+ const category = event.type === 'user' ? EVENT_CONFIG.CATEGORIES.USER : EVENT_CONFIG.CATEGORIES.BEHAVIORAL;
1393
+ // Create attributes with device ID
1394
+ const attributes = {
1395
+ ...event.data,
1396
+ device_id: generateDeviceId(),
1397
+ };
1398
+ // Get cuid from event queue's user context
1399
+ if (!this.eventQueue) {
1400
+ throw new Error('EventTracker not initialized');
1401
+ }
1402
+ const cuid = this.eventQueue.getCurrentCuid();
1403
+ if (!cuid) {
1404
+ throw new Error('User context not set. Call setUserContext() first.');
1405
+ }
1406
+ return createEventPayload(category, event.name || 'custom', attributes, cuid);
1407
+ }
1408
+ /**
1409
+ * Flush pending events to server
1410
+ */
1411
+ async flush() {
1412
+ if (!this.initialized || !this.eventQueue) {
1413
+ this.logger.warn('Cannot flush events - EventTracker not initialized');
1414
+ return;
1415
+ }
1416
+ this.logger.info('Manual flush requested');
1417
+ await this.eventQueue.flush();
1418
+ }
1419
+ /**
1420
+ * Destroy EventTracker and cleanup resources
1421
+ */
1422
+ async destroy() {
1423
+ this.logger.info('Destroying EventTracker');
1424
+ // Destroy event queue
1425
+ if (this.eventQueue) {
1426
+ await this.eventQueue.destroy();
1427
+ }
1428
+ this.initialized = false;
1429
+ this.logger.info(LOG_MESSAGES.EVENTS_TRACKER_DESTROYED);
1430
+ }
1431
+ }
1432
+
1433
+ /**
1434
+ * Authentication Manager
1435
+ * Handles user authentication and session management with API integration
1436
+ */
1437
+ class AuthManager {
1438
+ constructor(config, logger, storageManager) {
1439
+ this.initialized = false;
1440
+ this.nonceData = null;
1441
+ this.config = config;
1442
+ this.logger = logger;
1443
+ this.storageManager = storageManager;
1444
+ // Initialize API client
1445
+ this.apiClient = new ApiClient({
1446
+ baseUrl: config.baseURL,
1447
+ }, logger, config.accountId);
1448
+ }
1449
+ async init() {
1450
+ if (this.initialized) {
1451
+ this.logger.warn('AuthManager already initialized');
1452
+ return;
1453
+ }
1454
+ this.logger.info('Initializing AuthManager', { accountId: this.config.accountId });
1455
+ this.initialized = true;
1456
+ this.logger.info(LOG_MESSAGES.AUTH_INIT_SUCCESS);
1457
+ }
1458
+ /**
1459
+ * Request and cache a fresh nonce for authentication
1460
+ */
1461
+ async requestNonce() {
1462
+ if (!this.initialized) {
1463
+ throw new Error('AuthManager not initialized');
1464
+ }
1465
+ this.logger.info('Requesting nonce for authentication');
1466
+ try {
1467
+ const bundleIdentifier = getBundleIdentifier();
1468
+ const deviceId = generateDeviceId();
1469
+ // Request nonce from server
1470
+ const response = await this.apiClient.getNonce(bundleIdentifier, deviceId);
1471
+ // Create nonce data object
1472
+ this.nonceData = {
1473
+ nonce: response.nonce,
1474
+ challengeId: response.challenge_id,
1475
+ expiresAt: response.expires_at,
1476
+ deviceId,
1477
+ };
1478
+ // Persist nonce data to storage
1479
+ await this.storeNonceData();
1480
+ this.logger.info(LOG_MESSAGES.AUTH_SUCCESS, {
1481
+ challengeId: response.challenge_id,
1482
+ expiresAt: response.expires_at,
1483
+ });
1484
+ return this.nonceData;
1485
+ }
1486
+ catch (error) {
1487
+ this.logger.error(LOG_MESSAGES.AUTH_FAILED, error);
1488
+ throw error;
1489
+ }
1490
+ }
1491
+ /**
1492
+ * Ensure we have a valid nonce (restore existing or request new)
1493
+ */
1494
+ async ensureValidNonce() {
1495
+ if (!this.initialized) {
1496
+ throw new Error('AuthManager not initialized');
1497
+ }
1498
+ this.logger.info('Ensuring valid nonce');
1499
+ try {
1500
+ // First, try to restore existing valid nonce data
1501
+ await this.restoreNonceData();
1502
+ // If we have valid nonce data, we're done
1503
+ if (this.nonceData && !this.isNonceExpired(this.nonceData.expiresAt)) {
1504
+ this.logger.info('Using existing valid nonce');
1505
+ return this.nonceData;
1506
+ }
1507
+ // If nonce is expired or doesn't exist, request fresh
1508
+ this.logger.info('No valid nonce found, requesting fresh');
1509
+ return await this.requestNonce();
1510
+ }
1511
+ catch (error) {
1512
+ this.logger.error('Failed to ensure valid nonce', error);
1513
+ throw error;
1514
+ }
1515
+ }
1516
+ /**
1517
+ * Get current nonce data, refreshing automatically if needed
1518
+ */
1519
+ async getNonceData() {
1520
+ return await this.ensureValidNonce();
1521
+ }
1522
+ /**
1523
+ * Check if nonce is expired
1524
+ */
1525
+ isNonceExpired(expiresAt) {
1526
+ const now = Date.now();
1527
+ const bufferTime = AUTH_CONFIG.NONCE_EXPIRY_BUFFER_MS;
1528
+ return now >= expiresAt - bufferTime;
1529
+ }
1530
+ /**
1531
+ * Check if we have valid nonce
1532
+ */
1533
+ hasValidNonce() {
1534
+ return !!this.nonceData && !this.isNonceExpired(this.nonceData.expiresAt);
1535
+ }
1536
+ /**
1537
+ * Get API client instance
1538
+ */
1539
+ getApiClient() {
1540
+ return this.apiClient;
1541
+ }
1542
+ /**
1543
+ * Store nonce data to persistent storage
1544
+ */
1545
+ async storeNonceData() {
1546
+ if (!this.nonceData) {
1547
+ return;
1548
+ }
1549
+ try {
1550
+ await this.storageManager.set(STORAGE_KEYS.NONCE_DATA, JSON.stringify(this.nonceData));
1551
+ }
1552
+ catch (error) {
1553
+ this.logger.warn(LOG_MESSAGES.NONCE_DATA_STORE_FAILED, error);
1554
+ }
1555
+ }
1556
+ /**
1557
+ * Restore nonce data from storage
1558
+ */
1559
+ async restoreNonceData() {
1560
+ try {
1561
+ const storedNonceData = await this.storageManager.get(STORAGE_KEYS.NONCE_DATA);
1562
+ if (storedNonceData) {
1563
+ this.nonceData = JSON.parse(storedNonceData);
1564
+ this.logger.info('Nonce data restored from storage');
1565
+ }
1566
+ }
1567
+ catch (error) {
1568
+ this.logger.warn(LOG_MESSAGES.NONCE_DATA_RESTORE_FAILED, error);
1569
+ this.nonceData = null;
1570
+ }
1571
+ }
1572
+ /**
1573
+ * Clear stored nonce data
1574
+ */
1575
+ async clearNonceData() {
1576
+ this.nonceData = null;
1577
+ try {
1578
+ await this.storageManager.remove(STORAGE_KEYS.NONCE_DATA);
1579
+ }
1580
+ catch (error) {
1581
+ this.logger.warn(LOG_MESSAGES.NONCE_DATA_CLEAR_FAILED, error);
1582
+ }
1583
+ }
1584
+ /**
1585
+ * Destroy AuthManager and cleanup resources
1586
+ */
1587
+ async destroy() {
1588
+ this.logger.info('Destroying AuthManager');
1589
+ await this.clearNonceData();
1590
+ this.initialized = false;
1591
+ this.logger.info('AuthManager destroyed successfully');
1592
+ }
1593
+ }
1594
+
1595
+ /* eslint-disable no-undef */
1596
+ /**
1597
+ * Storage Manager
1598
+ * Provides abstraction layer for different storage mechanisms
1599
+ */
1600
+ class StorageManager {
1601
+ constructor(logger, brandId, applicationId) {
1602
+ this.initialized = false;
1603
+ this.logger = logger;
1604
+ this.brandId = brandId;
1605
+ this.applicationId = applicationId;
1606
+ // Default to localStorage adapter
1607
+ this.adapter = new LocalStorageAdapter();
1608
+ }
1609
+ async init() {
1610
+ if (this.initialized) {
1611
+ this.logger.warn('StorageManager already initialized');
1612
+ return;
1613
+ }
1614
+ this.logger.info('Initializing StorageManager');
1615
+ try {
1616
+ // Prefer IndexedDB for better performance and capacity
1617
+ if (this.isIndexedDBSupported()) {
1618
+ // Create isolation-aware database name
1619
+ const namespaces = ['WebSDK'];
1620
+ if (this.brandId) {
1621
+ namespaces.push(this.brandId);
1622
+ }
1623
+ if (this.applicationId) {
1624
+ namespaces.push(this.applicationId);
1625
+ }
1626
+ const dbName = namespaces.join('_');
1627
+ const indexedDBAdapter = new IndexedDBStorage(dbName);
1628
+ await this.testStorageAdapter(indexedDBAdapter);
1629
+ this.adapter = indexedDBAdapter;
1630
+ this.logger.info('StorageManager initialized with IndexedDB', {
1631
+ dbName,
1632
+ brandId: this.brandId,
1633
+ applicationId: this.applicationId,
1634
+ });
1635
+ }
1636
+ else {
1637
+ // Fallback to localStorage
1638
+ await this.testStorageAdapter(this.adapter);
1639
+ this.logger.info('StorageManager initialized with localStorage');
1640
+ }
1641
+ this.initialized = true;
1642
+ }
1643
+ catch (error) {
1644
+ this.logger.error(LOG_MESSAGES.STORAGE_INIT_FAILED, error);
1645
+ throw new Error(`Storage initialization failed: ${error}`);
1646
+ }
1647
+ }
1648
+ isIndexedDBSupported() {
1649
+ return typeof window !== 'undefined' && 'indexedDB' in window && indexedDB !== null;
1650
+ }
1651
+ async testStorageAdapter(adapter) {
1652
+ const testKey = STORAGE_CONFIG.TEST_KEY;
1653
+ const testValue = STORAGE_CONFIG.TEST_VALUE;
1654
+ try {
1655
+ await adapter.setItem(testKey, testValue);
1656
+ const retrieved = await adapter.getItem(testKey);
1657
+ if (retrieved !== testValue) {
1658
+ throw new Error(LOG_MESSAGES.STORAGE_READ_WRITE_TEST_FAILED);
1659
+ }
1660
+ await adapter.removeItem(testKey);
1661
+ }
1662
+ catch (error) {
1663
+ throw new Error(`${LOG_MESSAGES.STORAGE_TEST_FAILED} ${error}`);
1664
+ }
1665
+ }
1666
+ async get(key) {
1667
+ if (!this.initialized) {
1668
+ throw new Error('StorageManager not initialized');
1669
+ }
1670
+ return this.adapter.getItem(key);
1671
+ }
1672
+ async set(key, value) {
1673
+ if (!this.initialized) {
1674
+ throw new Error('StorageManager not initialized');
1675
+ }
1676
+ return this.adapter.setItem(key, value);
1677
+ }
1678
+ async remove(key) {
1679
+ if (!this.initialized) {
1680
+ throw new Error('StorageManager not initialized');
1681
+ }
1682
+ return this.adapter.removeItem(key);
1683
+ }
1684
+ async clear() {
1685
+ if (!this.initialized) {
1686
+ throw new Error('StorageManager not initialized');
1687
+ }
1688
+ return this.adapter.clear();
1689
+ }
1690
+ getIndexedDBAdapter() {
1691
+ if (this.adapter instanceof IndexedDBStorage) {
1692
+ return this.adapter;
1693
+ }
1694
+ return null;
1695
+ }
1696
+ async destroy() {
1697
+ this.logger.info('Destroying StorageManager');
1698
+ try {
1699
+ // Close IndexedDB connection if using IndexedDB
1700
+ if (this.adapter instanceof IndexedDBStorage) {
1701
+ await this.adapter.close();
1702
+ }
1703
+ this.initialized = false;
1704
+ this.logger.info(LOG_MESSAGES.STORAGE_DESTROYED);
1705
+ }
1706
+ catch (error) {
1707
+ this.logger.error(LOG_MESSAGES.STORAGE_CLEANUP_ERROR, error);
1708
+ this.initialized = false; // Force to false even on error
1709
+ }
1710
+ }
1711
+ }
1712
+ // Default localStorage adapter
1713
+ class LocalStorageAdapter {
1714
+ async getItem(key) {
1715
+ try {
1716
+ return localStorage.getItem(key);
1717
+ }
1718
+ catch (error) {
1719
+ throw new Error(`LocalStorage getItem failed: ${error}`);
1720
+ }
1721
+ }
1722
+ async setItem(key, value) {
1723
+ try {
1724
+ localStorage.setItem(key, value);
1725
+ }
1726
+ catch (error) {
1727
+ // Check for quota exceeded error
1728
+ if (error instanceof DOMException &&
1729
+ (error.code === 22 || // QuotaExceededError in legacy browsers
1730
+ error.code === 1014 || // QuotaExceededError in FireFox
1731
+ error.name === 'QuotaExceededError' ||
1732
+ error.name === 'NS_ERROR_DOM_QUOTA_REACHED')) {
1733
+ throw new Error('LocalStorage quota exceeded');
1734
+ }
1735
+ throw new Error(`LocalStorage setItem failed: ${error}`);
1736
+ }
1737
+ }
1738
+ async removeItem(key) {
1739
+ try {
1740
+ localStorage.removeItem(key);
1741
+ }
1742
+ catch (error) {
1743
+ throw new Error(`LocalStorage removeItem failed: ${error}`);
1744
+ }
1745
+ }
1746
+ async clear() {
1747
+ try {
1748
+ localStorage.clear();
1749
+ }
1750
+ catch (error) {
1751
+ throw new Error(`LocalStorage clear failed: ${error}`);
1752
+ }
1753
+ }
1754
+ }
1755
+
1756
+ /* eslint-disable no-unused-vars */
1757
+ /**
1758
+ * WebSDK Logger Module
1759
+ * Provides centralized logging with different levels and formatting
1760
+ */
1761
+ var LogLevel;
1762
+ (function (LogLevel) {
1763
+ LogLevel[LogLevel["VERBOSE"] = 0] = "VERBOSE";
1764
+ LogLevel[LogLevel["DEBUG"] = 1] = "DEBUG";
1765
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
1766
+ LogLevel[LogLevel["WARN"] = 3] = "WARN";
1767
+ LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
1768
+ LogLevel[LogLevel["NONE"] = 5] = "NONE";
1769
+ })(LogLevel || (LogLevel = {}));
1770
+ class Logger {
1771
+ constructor(enabled = false, level = LogLevel.INFO) {
1772
+ this.logs = [];
1773
+ this.maxLogs = 1000;
1774
+ this.enabled = enabled;
1775
+ this.level = level;
1776
+ }
1777
+ formatMessage(level, message) {
1778
+ const timestamp = new Date().toISOString();
1779
+ const levelName = LogLevel[level];
1780
+ return `[${timestamp}] [WebSDK:${levelName}] ${message}`;
1781
+ }
1782
+ log(level, message, data) {
1783
+ if (!this.enabled || level < this.level) {
1784
+ return;
1785
+ }
1786
+ const logEntry = {
1787
+ level,
1788
+ message,
1789
+ timestamp: Date.now(),
1790
+ data,
1791
+ };
1792
+ // Store log entry
1793
+ this.logs.push(logEntry);
1794
+ if (this.logs.length > this.maxLogs) {
1795
+ this.logs.shift();
1796
+ }
1797
+ // Output to console
1798
+ const formattedMessage = this.formatMessage(level, message);
1799
+ const consoleArgs = data ? [formattedMessage, data] : [formattedMessage];
1800
+ switch (level) {
1801
+ case LogLevel.VERBOSE:
1802
+ console.debug(...consoleArgs);
1803
+ break;
1804
+ case LogLevel.DEBUG:
1805
+ console.debug(...consoleArgs);
1806
+ break;
1807
+ case LogLevel.INFO:
1808
+ console.info(...consoleArgs);
1809
+ break;
1810
+ case LogLevel.WARN:
1811
+ console.warn(...consoleArgs);
1812
+ break;
1813
+ case LogLevel.ERROR:
1814
+ console.error(...consoleArgs);
1815
+ break;
1816
+ }
1817
+ }
1818
+ verbose(message, data) {
1819
+ this.log(LogLevel.VERBOSE, message, data);
1820
+ }
1821
+ debug(message, data) {
1822
+ this.log(LogLevel.DEBUG, message, data);
1823
+ }
1824
+ info(message, data) {
1825
+ this.log(LogLevel.INFO, message, data);
1826
+ }
1827
+ warn(message, data) {
1828
+ this.log(LogLevel.WARN, message, data);
1829
+ }
1830
+ error(message, data) {
1831
+ this.log(LogLevel.ERROR, message, data);
1832
+ }
1833
+ setLevel(level) {
1834
+ this.level = level;
1835
+ }
1836
+ setEnabled(enabled) {
1837
+ this.enabled = enabled;
1838
+ }
1839
+ getLogs() {
1840
+ return [...this.logs];
1841
+ }
1842
+ clearLogs() {
1843
+ this.logs = [];
1844
+ }
1845
+ }
1846
+
1847
+ /**
1848
+ * WebSDK Core Initialization
1849
+ * Handles SDK bootstrap, lifecycle management, and main API
1850
+ */
1851
+ class WebSDK {
1852
+ constructor(config) {
1853
+ this.userContextSet = false;
1854
+ this.initialized = false;
1855
+ this.initializationPromise = null;
1856
+ this.config = config;
1857
+ this.logger = new Logger(this.shouldEnableLogging(config.debugLevel));
1858
+ this.sessionId = ''; // Will be set during init
1859
+ this.storageManager = new StorageManager(this.logger, config.brandId, config.applicationId);
1860
+ this.authManager = new AuthManager(config, this.logger, this.storageManager);
1861
+ this.eventTracker = new EventTracker(config, this.authManager, this.storageManager, this.logger);
1862
+ }
1863
+ /**
1864
+ * Static factory method for Android SDK-style initialization
1865
+ */
1866
+ static instanceWithConfig(config) {
1867
+ return new WebSDK(config);
1868
+ }
1869
+ /**
1870
+ * Check if debug level should enable logging
1871
+ */
1872
+ shouldEnableLogging(debugLevel) {
1873
+ if (!debugLevel || debugLevel === 'NONE') {
1874
+ return false;
1875
+ }
1876
+ return ['ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE'].includes(debugLevel);
1877
+ }
1878
+ /**
1879
+ * Get or create session ID - shared across tabs for same session
1880
+ */
1881
+ async getOrCreateSessionId() {
1882
+ try {
1883
+ // Try to get existing session ID from storage (shared across tabs)
1884
+ const sessionKey = getStorageKey('SESSION_ID', this.config.brandId, this.config.applicationId);
1885
+ const existingSessionId = await this.storageManager.get(sessionKey);
1886
+ if (existingSessionId) {
1887
+ return existingSessionId;
1888
+ }
1889
+ // Generate new session ID and store it
1890
+ const sessionId = generateSessionId();
1891
+ await this.storageManager.set(sessionKey, sessionId);
1892
+ return sessionId;
1893
+ }
1894
+ catch (error) {
1895
+ this.logger.warn('Failed to get or create session ID', error);
1896
+ // Fallback to in-memory session if storage fails
1897
+ return generateSessionId();
1898
+ }
1899
+ }
1900
+ /**
1901
+ * Restore user context from storage
1902
+ */
1903
+ async restoreUserContext() {
1904
+ try {
1905
+ const userContextKey = getStorageKey('USER_CONTEXT', this.config.brandId, this.config.applicationId);
1906
+ const storedUserContext = await this.storageManager.get(userContextKey);
1907
+ if (storedUserContext) {
1908
+ const userContext = JSON.parse(storedUserContext);
1909
+ // Extract cuid from stored context, use accountId from config for filtering
1910
+ const cuid = userContext.cuid;
1911
+ await this.eventTracker.setUserContext(this.config.accountId, userContext.systemDataArgs, cuid);
1912
+ this.userContextSet = true;
1913
+ this.logger.info('User context restored from storage', {
1914
+ cuid,
1915
+ accountId: this.config.accountId,
1916
+ });
1917
+ }
1918
+ }
1919
+ catch (error) {
1920
+ this.logger.warn('Failed to restore user context from storage', error);
1921
+ }
1922
+ }
1923
+ /**
1924
+ * Validate and clear different user context if needed
1925
+ */
1926
+ async validateAndClearDifferentUserContext(newCuid) {
1927
+ try {
1928
+ const userContextKey = getStorageKey('USER_CONTEXT', this.config.brandId, this.config.applicationId);
1929
+ const storedUserContext = await this.storageManager.get(userContextKey);
1930
+ if (storedUserContext) {
1931
+ const userContext = JSON.parse(storedUserContext);
1932
+ // Check if stored context is for a different user
1933
+ if (userContext.cuid && userContext.cuid !== newCuid) {
1934
+ this.logger.info('Different user detected, clearing previous user context', {
1935
+ previousCuid: userContext.cuid,
1936
+ newCuid: newCuid,
1937
+ });
1938
+ // Clear the previous user's context
1939
+ await this.clearUserContext();
1940
+ // Reset internal state
1941
+ this.userContextSet = false;
1942
+ }
1943
+ }
1944
+ }
1945
+ catch (error) {
1946
+ this.logger.warn('Error validating different user context', error);
1947
+ // If there's an error, clear context to be safe
1948
+ await this.clearUserContext();
1949
+ this.userContextSet = false;
1950
+ }
1951
+ }
1952
+ /**
1953
+ * Store user context to storage for cross-tab persistence
1954
+ */
1955
+ async storeUserContext(cuid, systemDataArgs) {
1956
+ try {
1957
+ const userContext = { cuid, systemDataArgs, timestamp: Date.now() };
1958
+ const userContextKey = getStorageKey('USER_CONTEXT', this.config.brandId, this.config.applicationId);
1959
+ await this.storageManager.set(userContextKey, JSON.stringify(userContext));
1960
+ }
1961
+ catch (error) {
1962
+ this.logger.warn('Failed to store user context', error);
1963
+ }
1964
+ }
1965
+ /**
1966
+ * Initialize the WebSDK (fire-and-forget)
1967
+ */
1968
+ init() {
1969
+ if (this.initialized) {
1970
+ this.logger.warn('WebSDK already initialized');
1971
+ return;
1972
+ }
1973
+ if (this.initializationPromise) {
1974
+ this.logger.warn('WebSDK initialization already in progress');
1975
+ return;
1976
+ }
1977
+ // Store the initialization promise so other methods can wait for it
1978
+ this.initializationPromise = this.initializeAsync().catch(error => {
1979
+ this.logger.error(LOG_MESSAGES.WEBSDK_INIT_FAILED, error);
1980
+ this.initializationPromise = null; // Reset on failure
1981
+ });
1982
+ }
1983
+ /**
1984
+ * Internal async initialization logic
1985
+ */
1986
+ async initializeAsync() {
1987
+ try {
1988
+ this.logger.info('Initializing WebSDK', { version: SDK_VERSION, config: this.config });
1989
+ // Initialize storage
1990
+ await this.storageManager.init();
1991
+ // Initialize session ID
1992
+ this.sessionId = await this.getOrCreateSessionId();
1993
+ // Initialize authentication
1994
+ await this.authManager.init();
1995
+ // Initialize event tracker
1996
+ await this.eventTracker.init();
1997
+ // Ensure we have a valid nonce (restore existing or request new)
1998
+ await this.authManager.ensureValidNonce();
1999
+ // Restore user context from storage
2000
+ await this.restoreUserContext();
2001
+ this.initialized = true;
2002
+ this.logger.info(LOG_MESSAGES.WEBSDK_INIT_SUCCESS);
2003
+ }
2004
+ catch (error) {
2005
+ throw new Error(`${ERROR_CODES.INITIALIZATION_ERROR}: ${error}`);
2006
+ }
2007
+ }
2008
+ /**
2009
+ * Set user context for event tracking
2010
+ */
2011
+ async setUserContext(cuid, systemDataArgs) {
2012
+ if (!this.initialized) {
2013
+ throw new Error('WebSDK must be initialized before setting user context');
2014
+ }
2015
+ // Check if there's an existing different user context and clear it
2016
+ await this.validateAndClearDifferentUserContext(cuid);
2017
+ // Use accountId from config for event filtering, but store cuid for event data
2018
+ await this.eventTracker.setUserContext(this.config.accountId, systemDataArgs, cuid);
2019
+ this.userContextSet = true;
2020
+ // Store user context for cross-tab persistence
2021
+ await this.storeUserContext(cuid, systemDataArgs);
2022
+ this.logger.info('User context set and persisted', { cuid, accountId: this.config.accountId });
2023
+ }
2024
+ /**
2025
+ * Clear user context (sign out equivalent)
2026
+ */
2027
+ async clearUserContext() {
2028
+ try {
2029
+ const userContextKey = getStorageKey('USER_CONTEXT', this.config.brandId, this.config.applicationId);
2030
+ await this.storageManager.remove(userContextKey);
2031
+ this.userContextSet = false;
2032
+ this.logger.info('User context cleared');
2033
+ }
2034
+ catch (error) {
2035
+ this.logger.warn('Failed to clear user context', error);
2036
+ // Still mark as cleared to prevent further attempts
2037
+ this.userContextSet = false;
2038
+ }
2039
+ }
2040
+ /**
2041
+ * Track an event
2042
+ */
2043
+ async track(event) {
2044
+ if (!this.initialized) {
2045
+ throw new Error('WebSDK must be initialized before tracking events');
2046
+ }
2047
+ try {
2048
+ await this.eventTracker.track(event);
2049
+ }
2050
+ catch (error) {
2051
+ this.logger.error(LOG_MESSAGES.EVENT_TRACK_FAILED, { event, error });
2052
+ throw error;
2053
+ }
2054
+ }
2055
+ /**
2056
+ * Destroy SDK instance and cleanup resources
2057
+ */
2058
+ async destroy() {
2059
+ this.logger.info('Destroying WebSDK instance');
2060
+ try {
2061
+ await this.eventTracker.flush();
2062
+ await this.eventTracker.destroy();
2063
+ await this.authManager.destroy();
2064
+ // Clear user context before destroying storage (but after flushing events)
2065
+ await this.clearUserContext();
2066
+ await this.storageManager.destroy();
2067
+ this.initialized = false;
2068
+ this.logger.info(LOG_MESSAGES.WEBSDK_DESTROYED);
2069
+ }
2070
+ catch (error) {
2071
+ this.logger.error(LOG_MESSAGES.WEBSDK_DESTROYED, error);
2072
+ throw error;
2073
+ }
2074
+ }
2075
+ /**
2076
+ * Push user signin event (fire-and-forget)
2077
+ */
2078
+ pushUserSignin(cuid, firstName, lastName, email, phone, customData) {
2079
+ // Fire-and-forget user signin tracking
2080
+ this.pushUserSigninAsync(cuid, firstName, lastName, email, phone, customData).catch(error => {
2081
+ this.logger.error(LOG_MESSAGES.USER_SIGNIN_FAILED, { cuid, error });
2082
+ });
2083
+ }
2084
+ /**
2085
+ * Internal async user signin logic
2086
+ */
2087
+ async pushUserSigninAsync(cuid, firstName, lastName, email, phone, customData) {
2088
+ await this.ensureInitialized();
2089
+ await this.setUserContextIfNeeded(cuid);
2090
+ const eventData = {
2091
+ cuid,
2092
+ ...(firstName && { first_name: firstName }),
2093
+ ...(lastName && { last_name: lastName }),
2094
+ ...(email && { email }),
2095
+ ...(phone && { phone }),
2096
+ ...(customData && { custom_data: customData }),
2097
+ };
2098
+ const event = {
2099
+ type: 'user',
2100
+ name: USER_EVENTS.USER_SIGNIN,
2101
+ timestamp: Date.now(),
2102
+ sessionId: this.sessionId,
2103
+ userId: cuid,
2104
+ data: eventData,
2105
+ };
2106
+ try {
2107
+ await this.track(event);
2108
+ this.logger.info('User signin event tracked', { cuid, firstName, lastName, email });
2109
+ }
2110
+ catch (error) {
2111
+ this.logger.error(LOG_MESSAGES.USER_SIGNIN_FAILED, { cuid, error });
2112
+ throw error;
2113
+ }
2114
+ }
2115
+ /**
2116
+ * Push user signup event (fire-and-forget)
2117
+ */
2118
+ pushUserSignup(cuid, firstName, lastName, email, phone, customData) {
2119
+ // Fire-and-forget user signup tracking
2120
+ this.pushUserSignupAsync(cuid, firstName, lastName, email, phone, customData).catch(error => {
2121
+ this.logger.error(LOG_MESSAGES.USER_SIGNUP_FAILED, { cuid, error });
2122
+ });
2123
+ }
2124
+ /**
2125
+ * Internal async user signup logic
2126
+ */
2127
+ async pushUserSignupAsync(cuid, firstName, lastName, email, phone, customData) {
2128
+ await this.ensureInitialized();
2129
+ await this.setUserContextIfNeeded(cuid);
2130
+ const eventData = {
2131
+ cuid,
2132
+ first_name: firstName,
2133
+ last_name: lastName,
2134
+ email,
2135
+ phone,
2136
+ ...(customData && { custom_data: customData }),
2137
+ };
2138
+ const event = {
2139
+ type: 'user',
2140
+ name: USER_EVENTS.USER_SIGNUP,
2141
+ timestamp: Date.now(),
2142
+ sessionId: this.sessionId,
2143
+ userId: cuid,
2144
+ data: eventData,
2145
+ };
2146
+ try {
2147
+ await this.track(event);
2148
+ this.logger.info('User signup event tracked', { cuid, firstName, lastName, email });
2149
+ }
2150
+ catch (error) {
2151
+ this.logger.error(LOG_MESSAGES.USER_SIGNUP_FAILED, { cuid, error });
2152
+ throw error;
2153
+ }
2154
+ }
2155
+ /**
2156
+ * Push user update event (fire-and-forget)
2157
+ */
2158
+ pushUserUpdate(cuid, firstName, lastName, email, phone, customData) {
2159
+ // Fire-and-forget user update tracking
2160
+ this.pushUserUpdateAsync(cuid, firstName, lastName, email, phone, customData).catch(error => {
2161
+ this.logger.error(LOG_MESSAGES.USER_UPDATE_FAILED, { cuid, error });
2162
+ });
2163
+ }
2164
+ /**
2165
+ * Internal async user update logic
2166
+ */
2167
+ async pushUserUpdateAsync(cuid, firstName, lastName, email, phone, customData) {
2168
+ await this.ensureInitialized();
2169
+ await this.setUserContextIfNeeded(cuid);
2170
+ const eventData = {
2171
+ cuid,
2172
+ ...(firstName && { first_name: firstName }),
2173
+ ...(lastName && { last_name: lastName }),
2174
+ ...(email && { email }),
2175
+ ...(phone && { phone }),
2176
+ ...(customData && { custom_data: customData }),
2177
+ };
2178
+ const event = {
2179
+ type: 'user',
2180
+ name: USER_EVENTS.USER_UPDATE,
2181
+ timestamp: Date.now(),
2182
+ sessionId: this.sessionId,
2183
+ userId: cuid,
2184
+ data: eventData,
2185
+ };
2186
+ try {
2187
+ await this.track(event);
2188
+ this.logger.info('User update event tracked', { cuid, firstName, lastName, email });
2189
+ }
2190
+ catch (error) {
2191
+ this.logger.error(LOG_MESSAGES.USER_UPDATE_FAILED, { cuid, error });
2192
+ throw error;
2193
+ }
2194
+ }
2195
+ /**
2196
+ * Push user signout event and destroy SDK (fire-and-forget)
2197
+ */
2198
+ pushUserSignOut(cuid) {
2199
+ // Fire-and-forget user signout tracking
2200
+ this.pushUserSignOutAsync(cuid).catch(error => {
2201
+ this.logger.error(LOG_MESSAGES.USER_SIGNOUT_FAILED, { cuid, error });
2202
+ // Still destroy even if signout event fails
2203
+ this.destroy().catch(destroyError => {
2204
+ this.logger.error('Failed to destroy SDK after failed signout', destroyError);
2205
+ });
2206
+ });
2207
+ }
2208
+ /**
2209
+ * Internal async user signout logic
2210
+ */
2211
+ async pushUserSignOutAsync(cuid) {
2212
+ await this.ensureInitialized();
2213
+ await this.setUserContextIfNeeded(cuid);
2214
+ const event = {
2215
+ type: 'user',
2216
+ name: USER_EVENTS.USER_SIGNOUT,
2217
+ timestamp: Date.now(),
2218
+ sessionId: this.sessionId,
2219
+ userId: cuid,
2220
+ data: { cuid },
2221
+ };
2222
+ try {
2223
+ await this.track(event);
2224
+ this.logger.info('User signout event tracked', { cuid });
2225
+ // Destroy SDK instance after signout event is sent
2226
+ await this.destroy();
2227
+ }
2228
+ catch (error) {
2229
+ this.logger.error(LOG_MESSAGES.USER_SIGNOUT_FAILED, { cuid, error });
2230
+ // Still destroy even if signout event fails
2231
+ try {
2232
+ await this.destroy();
2233
+ }
2234
+ catch (destroyError) {
2235
+ this.logger.error('Failed to destroy SDK after failed signout', destroyError);
2236
+ }
2237
+ throw error;
2238
+ }
2239
+ }
2240
+ /**
2241
+ * Push behavioral event (fire-and-forget)
2242
+ */
2243
+ pushEvent(eventName, attributes) {
2244
+ // Fire-and-forget behavioral event tracking
2245
+ this.pushEventAsync(eventName, attributes).catch(error => {
2246
+ this.logger.error(LOG_MESSAGES.BEHAVIORAL_EVENT_FAILED, { eventName, error });
2247
+ });
2248
+ }
2249
+ /**
2250
+ * Internal async behavioral event logic
2251
+ */
2252
+ async pushEventAsync(eventName, attributes) {
2253
+ await this.ensureInitialized();
2254
+ // Check if user context is set for behavioral events
2255
+ if (!this.userContextSet) {
2256
+ throw new Error('User context must be set before tracking behavioral events. Call setUserContext() first.');
2257
+ }
2258
+ const eventData = {
2259
+ event_name: eventName,
2260
+ ...(attributes && attributes),
2261
+ };
2262
+ const event = {
2263
+ type: 'behavioral',
2264
+ name: eventName,
2265
+ timestamp: Date.now(),
2266
+ sessionId: this.sessionId,
2267
+ data: eventData,
2268
+ };
2269
+ try {
2270
+ await this.track(event);
2271
+ this.logger.info('Behavioral event tracked', { eventName, attributes });
2272
+ }
2273
+ catch (error) {
2274
+ this.logger.error(LOG_MESSAGES.BEHAVIORAL_EVENT_FAILED, { eventName, error });
2275
+ throw error;
2276
+ }
2277
+ }
2278
+ // ===== Private Helper Methods =====
2279
+ /**
2280
+ * Ensure SDK is initialized before operations
2281
+ * Waits for initialization to complete if in progress
2282
+ */
2283
+ async ensureInitialized() {
2284
+ // If initialization is in progress, wait for it to complete
2285
+ if (this.initializationPromise) {
2286
+ try {
2287
+ await this.initializationPromise;
2288
+ }
2289
+ catch (error) {
2290
+ throw new Error(`SDK initialization failed: ${error}`);
2291
+ }
2292
+ }
2293
+ // Check if SDK is properly initialized
2294
+ if (!this.initialized) {
2295
+ throw new Error('WebSDK must be initialized before tracking events. Call init() first.');
2296
+ }
2297
+ }
2298
+ /**
2299
+ * Set user context if needed (for HydraSDK methods)
2300
+ */
2301
+ async setUserContextIfNeeded(cuid) {
2302
+ if (!this.userContextSet) {
2303
+ const systemDataArgs = {
2304
+ country: this.config.country,
2305
+ city: this.config.city,
2306
+ country_code: this.config.countryCode,
2307
+ };
2308
+ await this.setUserContext(cuid, systemDataArgs);
2309
+ this.logger.debug('User context set automatically', { cuid, systemDataArgs });
2310
+ }
2311
+ }
2312
+ }
2313
+
2314
+ export { WebSDK as default };