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/README.md ADDED
@@ -0,0 +1,502 @@
1
+ # WebSDK Integration Guide
2
+
3
+ A comprehensive guide for integrating the Hydra WebSDK into your web application for event tracking and analytics.
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [Quick Start](#quick-start)
8
+ 2. [Installation](#installation)
9
+ 3. [Basic Configuration](#basic-configuration)
10
+ 4. [Initialization](#initialization)
11
+ 5. [User Management](#user-management)
12
+ 6. [Event Tracking](#event-tracking)
13
+ 7. [Advanced Features](#advanced-features)
14
+ 8. [Best Practices](#best-practices)
15
+ 9. [Troubleshooting](#troubleshooting)
16
+ 10. [Support](#support)
17
+
18
+ ## Quick Start
19
+
20
+ Here's a minimal example to get you started:
21
+
22
+ ```javascript
23
+ import { WebSDK } from 'cap-hydra-web-sdk';
24
+
25
+ // Initialize the SDK
26
+ const sdk = new WebSDK({
27
+ accountId: 'your-account-id',
28
+ baseURL: 'https://api.your-domain.com',
29
+ brandId: 'your-brand-id',
30
+ applicationId: 'your-app-id',
31
+ debugLevel: 'INFO',
32
+ });
33
+
34
+ // Initialize (fire-and-forget - returns immediately)
35
+ sdk.init();
36
+
37
+ // Track events (fire-and-forget - returns immediately)
38
+ sdk.pushEvent('button_click', {
39
+ button_id: 'submit',
40
+ page: 'checkout',
41
+ });
42
+ ```
43
+
44
+ ## Installation
45
+
46
+ ### NPM Installation
47
+
48
+ ```bash
49
+ npm install cap-hydra-web-sdk
50
+ ```
51
+
52
+ ### CDN Installation
53
+
54
+ ```html
55
+ <script src="https://cdn.jsdelivr.net/npm/cap-hydra-web-sdk@latest/dist/websdk.min.js"></script>
56
+ ```
57
+
58
+ ### ES6 Modules
59
+
60
+ ```javascript
61
+ import { WebSDK } from 'cap-hydra-web-sdk';
62
+ ```
63
+
64
+ ### CommonJS
65
+
66
+ ```javascript
67
+ const { WebSDK } = require('cap-hydra-web-sdk');
68
+ ```
69
+
70
+ ## Basic Configuration
71
+
72
+ ### Required Configuration
73
+
74
+ ```javascript
75
+ const config = {
76
+ accountId: 'your-account-id', // Your Hydra account ID
77
+ baseURL: 'https://api.hydra.com', // API endpoint
78
+ };
79
+ ```
80
+
81
+ ### Optional Configuration
82
+
83
+ ```javascript
84
+ const config = {
85
+ // Required
86
+ accountId: 'your-account-id',
87
+ baseURL: 'https://api.hydra.com',
88
+
89
+ // Optional
90
+ brandId: 'your-brand-id',
91
+ applicationId: 'your-app-id',
92
+ debugLevel: 'INFO', // 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'NONE'
93
+ country: 'US', // Default country
94
+ city: 'New York', // Default city
95
+ countryCode: 'US', // Default country code
96
+ retryDelays: [60000, 120000, 240000, 480000, 900000], // Custom retry delays in milliseconds
97
+ };
98
+ ```
99
+
100
+ ### Debug Levels
101
+
102
+ - **VERBOSE**: Most detailed logging including trace information
103
+ - **DEBUG**: All logs including detailed debugging information
104
+ - **INFO**: General information and important events
105
+ - **WARN**: Warning messages and potential issues
106
+ - **ERROR**: Only error messages
107
+ - **NONE**: No logging (production recommended)
108
+
109
+ ## Initialization
110
+
111
+ ### Fire-and-Forget Initialization
112
+
113
+ ```javascript
114
+ const sdk = new WebSDK(config);
115
+
116
+ // Fire-and-forget initialization - returns immediately
117
+ sdk.init();
118
+
119
+ // You can immediately start tracking events
120
+ // The SDK will queue events until initialization completes
121
+ sdk.pushEvent('app_started', { timestamp: Date.now() });
122
+
123
+ console.log('SDK initialization started in background');
124
+ ```
125
+
126
+ ### Error Handling
127
+
128
+ Since initialization is fire-and-forget, errors are handled internally and logged.
129
+
130
+ ```javascript
131
+ const sdk = new WebSDK(config);
132
+
133
+ // Start initialization
134
+ sdk.init();
135
+
136
+ // Events will be queued and processed once initialization completes
137
+ sdk.pushEvent('page_view', { page: 'home' });
138
+ ```
139
+
140
+ ### React Integration
141
+
142
+ ```jsx
143
+ import React, { useEffect } from 'react';
144
+ import { WebSDK } from 'cap-hydra-web-sdk';
145
+
146
+ function App() {
147
+ useEffect(() => {
148
+ // Initialize SDK (fire-and-forget)
149
+ const webSDK = new WebSDK(config);
150
+ webSDK.init();
151
+
152
+ // Store SDK instance for use throughout the app
153
+ window.hydraSDK = webSDK;
154
+
155
+ // Start tracking immediately
156
+ webSDK.pushEvent('app_mounted', { timestamp: Date.now() });
157
+ }, []);
158
+
159
+ return (
160
+ <div>
161
+ <Dashboard />
162
+ </div>
163
+ );
164
+ }
165
+
166
+ // In other components, use the global SDK instance
167
+ function Dashboard() {
168
+ const handleButtonClick = () => {
169
+ // Fire-and-forget event tracking
170
+ window.hydraSDK.pushEvent('button_click', {
171
+ button_id: 'dashboard_action',
172
+ timestamp: Date.now(),
173
+ });
174
+ };
175
+
176
+ return <button onClick={handleButtonClick}>Click Me</button>;
177
+ }
178
+ ```
179
+
180
+ ## User Management
181
+
182
+ ### User Lifecycle Events
183
+
184
+ All user lifecycle methods now use the **fire-and-forget** approach for optimal performance:
185
+
186
+ #### User Sign In
187
+
188
+ ```javascript
189
+ // Fire-and-forget - returns immediately
190
+ sdk.pushUserSignin(
191
+ 'user-12345', // cuid (required)
192
+ 'John', // firstName (optional)
193
+ 'Doe', // lastName (optional)
194
+ 'user@example.com', // email (optional)
195
+ '+1234567890', // phone (optional)
196
+ {
197
+ // customData (optional)
198
+ method: 'email',
199
+ provider: 'google',
200
+ preferences: ['tech', 'sports'],
201
+ }
202
+ );
203
+ ```
204
+
205
+ #### User Sign Up
206
+
207
+ ```javascript
208
+ // Fire-and-forget - returns immediately
209
+ sdk.pushUserSignup(
210
+ 'user-12345', // cuid (required)
211
+ 'John', // firstName (required)
212
+ 'Doe', // lastName (required)
213
+ 'user@example.com', // email (required)
214
+ '+1234567890', // phone (required)
215
+ {
216
+ // customData (optional)
217
+ method: 'email',
218
+ age: 30,
219
+ interests: ['technology', 'travel'],
220
+ }
221
+ );
222
+ ```
223
+
224
+ #### User Profile Update
225
+
226
+ ```javascript
227
+ // Fire-and-forget - returns immediately
228
+ sdk.pushUserUpdate(
229
+ 'user-12345', // cuid (required)
230
+ 'John', // firstName (optional)
231
+ 'Smith', // lastName (optional)
232
+ 'john.smith@example.com', // email (optional)
233
+ '+1234567890', // phone (optional)
234
+ {
235
+ // customData (optional)
236
+ age: 31,
237
+ preferences: ['tech', 'music', 'travel'],
238
+ }
239
+ );
240
+ ```
241
+
242
+ #### User Sign Out
243
+
244
+ ```javascript
245
+ // Fire-and-forget - returns immediately
246
+ sdk.pushUserSignOut('user-12345'); // cuid (required)
247
+ ```
248
+
249
+ ## Event Tracking
250
+
251
+ ### Behavioral Events
252
+
253
+ Track user interactions and behaviors using the **fire-and-forget** approach for optimal performance:
254
+
255
+ **Function Signature:**
256
+
257
+ ```javascript
258
+ sdk.pushEvent(eventName, attributes);
259
+ // eventName: string (required) - The name of the event
260
+ // attributes: Record<string, unknown> (optional) - Event attributes/properties
261
+ // Returns: void (fire-and-forget - executes in background)
262
+ ```
263
+
264
+ **Common Behavioral Events:**
265
+
266
+ ```javascript
267
+ // Button clicks (fire-and-forget)
268
+ sdk.pushEvent('button_click', {
269
+ button_id: 'checkout',
270
+ button_text: 'Complete Purchase',
271
+ page: 'cart',
272
+ section: 'payment',
273
+ });
274
+
275
+ // E-commerce events (fire-and-forget)
276
+ sdk.pushEvent('add_to_cart', {
277
+ product_id: 'shoe-123',
278
+ product_name: 'Nike Air Max',
279
+ quantity: 1,
280
+ price: 129.99,
281
+ currency: 'USD',
282
+ cart_total: 259.98,
283
+ });
284
+
285
+ // Page navigation (fire-and-forget)
286
+ sdk.pushEvent('page_view', {
287
+ page: '/dashboard',
288
+ referrer: '/home',
289
+ timestamp: Date.now(),
290
+ });
291
+ ```
292
+
293
+ ## Advanced Features
294
+
295
+ ### Event Batching
296
+
297
+ The SDK automatically batches events for efficient network usage with the **fire-and-forget** approach:
298
+
299
+ - **Batch Size**: 50 events maximum per request
300
+ - **Auto Flush**: Events are automatically sent when batch is full
301
+ - **Background Processing**: All batching happens in background threads
302
+ - **Retry Logic**: Failed events are retried with exponential backoff
303
+ - **Persistence**: Events are stored locally until successfully sent
304
+ - **Race Condition Protection**: Events are queued if initialization is still in progress
305
+
306
+ ### Retry Configuration
307
+
308
+ The SDK includes robust retry logic that works seamlessly with fire-and-forget:
309
+
310
+ - **Infinite Retries**: Events retry indefinitely until successful
311
+ - **Default Retry Delays**: [60s, 120s, 240s, 480s, 900s] (customizable via config)
312
+ - **Constant Delay**: After exhausting array, continues with last delay value
313
+ - **Retryable Codes**: 408, 429, 500, 502, 503, 504, 401
314
+ - **Background Retries**: All retry logic executes in background without blocking UI
315
+
316
+ ### Configurable Retry Delays
317
+
318
+ ```javascript
319
+ const config = {
320
+ // ... other config
321
+ retryDelays: [30000, 60000, 120000], // Custom: 30s, 1min, 2min, then 2min indefinitely
322
+ };
323
+ ```
324
+
325
+ ## Best Practices
326
+
327
+ ### 1. Initialize Early with Fire-and-Forget
328
+
329
+ ```javascript
330
+ // Initialize SDK as early as possible in your app lifecycle
331
+ document.addEventListener('DOMContentLoaded', () => {
332
+ const sdk = new WebSDK(config);
333
+ // Fire-and-forget initialization
334
+ sdk.init();
335
+
336
+ // Store globally for immediate use
337
+ window.hydraSDK = sdk;
338
+ });
339
+ ```
340
+
341
+ ### 2. Use Fire-and-Forget for All Tracking
342
+
343
+ ```javascript
344
+ // Good: Fire-and-forget approach
345
+ const handleUserAction = () => {
346
+ // Immediate return, processing happens in background
347
+ sdk.pushEvent('user_action', { action: 'click' });
348
+
349
+ // Continue with your app logic immediately
350
+ navigateToNextPage();
351
+ };
352
+
353
+ // Avoid: Waiting for tracking to complete (old approach)
354
+ const handleUserActionOld = async () => {
355
+ await sdk.pushEvent('user_action', { action: 'click' }); // Blocks UI
356
+ navigateToNextPage();
357
+ };
358
+ ```
359
+
360
+ ### 3. Use Meaningful Event Names
361
+
362
+ ```javascript
363
+ // Good: Descriptive and consistent (fire-and-forget)
364
+ sdk.pushEvent('checkout_step_completed', {
365
+ step: 'payment_info',
366
+ step_number: 3,
367
+ });
368
+
369
+ // Avoid: Generic or unclear names
370
+ sdk.pushEvent('click', { type: 'button' });
371
+ ```
372
+
373
+ ### 4. Track Events Immediately
374
+
375
+ ```javascript
376
+ // With fire-and-forget, you can track events immediately after SDK creation
377
+ const sdk = new WebSDK(config);
378
+ sdk.init(); // Returns immediately
379
+
380
+ // Track events right away - they'll be queued until initialization completes
381
+ sdk.pushEvent('app_started', { timestamp: Date.now() });
382
+ sdk.pushEvent('page_view', { page: 'home' });
383
+ ```
384
+
385
+ ## Fire-and-Forget Benefits
386
+
387
+ The WebSDK's fire-and-forget approach provides several key advantages:
388
+
389
+ ### Performance Benefits
390
+
391
+ - **Non-blocking**: All SDK operations return immediately, never blocking your application's UI
392
+ - **Background Processing**: Event processing, network requests, and retries happen in background
393
+ - **Optimal User Experience**: No delays or freezing during event tracking
394
+ - **Race Condition Protection**: Events are safely queued if called before initialization completes
395
+
396
+ ### Reliability Benefits
397
+
398
+ - **Automatic Queuing**: Events are queued locally until they can be processed
399
+ - **Persistent Storage**: Events are stored in IndexedDB and survive page reloads
400
+ - **Infinite Retries**: Failed events retry indefinitely with exponential backoff
401
+ - **Error Resilience**: Network failures and API errors don't affect your application
402
+
403
+ ### Developer Experience Benefits
404
+
405
+ - **Simplified Integration**: No need for complex async/await handling
406
+ - **Immediate Usage**: Start tracking events immediately after SDK creation
407
+ - **No Error Handling Required**: All errors are handled internally with appropriate logging
408
+ - **Consistent API**: All methods follow the same fire-and-forget pattern
409
+
410
+ ## Troubleshooting
411
+
412
+ ### Common Issues
413
+
414
+ #### 1. Events Not Being Sent
415
+
416
+ Since the SDK uses fire-and-forget, check the browser console for error logs:
417
+
418
+ ```javascript
419
+ // Enable debug logging to see what's happening
420
+ const sdk = new WebSDK({
421
+ ...config,
422
+ debugLevel: 'DEBUG', // Enable verbose logging
423
+ });
424
+
425
+ sdk.init();
426
+ sdk.pushEvent('test_event', { test: true });
427
+
428
+ // Check browser console for logs like:
429
+ // "Event queued: test_event"
430
+ // "Batch sent successfully"
431
+ // "Retry scheduled for failed batch"
432
+ ```
433
+
434
+ #### 2. Checking Event Storage
435
+
436
+ Events are stored locally in IndexedDB. You can inspect them:
437
+
438
+ ```javascript
439
+ // Open browser DevTools → Application tab → IndexedDB → hydra-websdk
440
+ // Look for 'events' object store to see queued events
441
+ ```
442
+
443
+ #### 3. Network Issues
444
+
445
+ Monitor network requests in browser dev tools:
446
+
447
+ 1. Open Developer Tools (F12)
448
+ 2. Go to Network tab
449
+ 3. Filter by XHR/Fetch
450
+ 4. Look for requests to your API endpoint
451
+ 5. Check for 4xx/5xx errors that might indicate configuration issues
452
+
453
+ ### Debug Mode
454
+
455
+ Enable detailed logging for troubleshooting:
456
+
457
+ ```javascript
458
+ const sdk = new WebSDK({
459
+ ...config,
460
+ debugLevel: 'DEBUG', // Enable verbose logging
461
+ });
462
+
463
+ // Console will show detailed logs:
464
+ // - "SDK initialization started"
465
+ // - "Event queued: event_name"
466
+ // - "Batch processing started"
467
+ // - "Network request sent"
468
+ // - "Retry scheduled: attempt 1"
469
+ ```
470
+
471
+ ### Performance Monitoring
472
+
473
+ Since the SDK is fire-and-forget, you can monitor its performance impact:
474
+
475
+ ```javascript
476
+ // Monitor memory usage
477
+ console.log('Memory usage:', performance.memory?.usedJSHeapSize / 1024 / 1024, 'MB');
478
+
479
+ // Check IndexedDB storage
480
+ // DevTools → Application → Storage → IndexedDB → hydra-websdk
481
+ ```
482
+
483
+ ### Storage Inspection
484
+
485
+ Check stored events and configuration in browser:
486
+
487
+ 1. **IndexedDB**: DevTools → Application → IndexedDB → hydra-websdk
488
+ - `events` store: Queued events waiting to be sent
489
+ - `config` store: SDK configuration and state
490
+
491
+ 2. **Console Logs**: Check for SDK activity
492
+ - Event queuing messages
493
+ - Batch processing status
494
+ - Network request results
495
+ - Retry attempt logs
496
+
497
+ ## Support
498
+
499
+ ### Version Information
500
+
501
+ - Current Version: 1.0.0
502
+ - Minimum Browser Support: Chrome 61+, Firefox 60+, Safari 10+, Edge 16+
@@ -0,0 +1 @@
1
+ export { WebSDK as default } from '@/core/init';