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