cap-hydra-web-sdk 1.1.0 → 1.7.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.d.ts CHANGED
@@ -1,2 +1,584 @@
1
- export { WebSDK as default } from '@/core/init';
2
- export { DebugLevel, FirebaseConfig, Identifier, IdentifierType, IdentifyActionType, IdentifyParams, IdentifyTraits, NotificationConfig, NotificationPayload, NotificationState, PageViewOptions, UserAttributes, UserInfo, WebSDKConfig } from '@/shared/types';
1
+ import { Messaging } from 'firebase/messaging';
2
+
3
+ /**
4
+ * Firebase Configuration for FCM
5
+ */
6
+ interface FirebaseConfig {
7
+ apiKey: string;
8
+ authDomain: string;
9
+ databaseURL: string;
10
+ projectId: string;
11
+ storageBucket: string;
12
+ messagingSenderId: string;
13
+ appId: string;
14
+ measurementId?: string;
15
+ }
16
+ /**
17
+ * Notification configuration options.
18
+ *
19
+ * The host application owns Firebase: create the Firebase app and the `Messaging` instance
20
+ * yourself (`initializeApp()` + `getMessaging()` from the modular `firebase/app` and
21
+ * `firebase/messaging` packages) and pass the resulting instance as `messaging`. The SDK never
22
+ * initializes Firebase itself — it only calls `getToken()`/`onMessage()` against the instance
23
+ * you provide, registers the service worker, persists the token, and syncs it to the backend.
24
+ * Omit `messaging` to disable push notifications entirely — the SDK no-ops safely.
25
+ */
26
+ interface NotificationConfig {
27
+ messaging?: Messaging;
28
+ vapidKey?: string;
29
+ serviceWorkerPath?: string;
30
+ onTokenReceived?: (token: string) => void;
31
+ onTokenRefresh?: (token: string) => void;
32
+ onMessageReceived?: (payload: NotificationPayload) => void;
33
+ showBrowserNotification?: boolean;
34
+ }
35
+ /**
36
+ * Notification payload structure
37
+ */
38
+ interface NotificationPayload {
39
+ notification?: {
40
+ title?: string;
41
+ body?: string;
42
+ icon?: string;
43
+ image?: string;
44
+ badge?: string;
45
+ tag?: string;
46
+ data?: Record<string, unknown>;
47
+ };
48
+ data?: Record<string, unknown>;
49
+ from?: string;
50
+ collapseKey?: string;
51
+ messageId?: string;
52
+ }
53
+ /**
54
+ * Internal notification state stored in SDK
55
+ */
56
+ interface NotificationState {
57
+ isNotificationEnabled: boolean;
58
+ fcmToken?: string;
59
+ firebaseInitialized: boolean;
60
+ permissionStatus: NotificationPermission;
61
+ }
62
+ /**
63
+ * WebSDK Configuration
64
+ *
65
+ * The SDK supports two, mutually exclusive bootstrap modes, selected by whether
66
+ * `remoteConfigKey` is present:
67
+ *
68
+ * - Remote Config bootstrap: supply `firebaseConfig` + `remoteConfigKey`. All fields below marked
69
+ * "auto-populated from Remote Config" are fetched from a Firebase Remote Config parameter at
70
+ * startup and must not be set directly.
71
+ * - Direct-config bootstrap: omit `firebaseConfig` and `remoteConfigKey` entirely. In this mode,
72
+ * `accountId`, `baseURL`, and `orgId` are required arguments on this object, and every other
73
+ * field below is an optional argument with the same default as the Remote Config path. No
74
+ * Firebase project is required in this mode.
75
+ *
76
+ * `firebaseConfig` here is used only for Remote Config bootstrap. Push notifications (via
77
+ * `notifications`) are entirely independent of both bootstrap modes — the host application
78
+ * always owns Firebase for push, by creating its own Messaging instance and passing it via
79
+ * `notifications.messaging`, regardless of which bootstrap mode is used for SDK configuration.
80
+ */
81
+ interface WebSDKConfig {
82
+ firebaseConfig?: FirebaseConfig;
83
+ remoteConfigKey?: string;
84
+ retryDelays?: readonly number[];
85
+ notifications?: NotificationConfig;
86
+ /**
87
+ * Host application version (optional)
88
+ * Used to populate app_version field in extended fields
89
+ * @example "1.0.0"
90
+ */
91
+ appVersion?: string;
92
+ gamificationWriteKey?: string;
93
+ gamificationRegion?: string;
94
+ gamificationBaseUrl?: string;
95
+ accountId?: string;
96
+ baseURL?: string;
97
+ orgId?: string;
98
+ source?: string;
99
+ channelType?: string;
100
+ brandId?: string;
101
+ applicationId?: string;
102
+ sessionTimeoutMinutes?: number;
103
+ batchSize?: number;
104
+ debugLevel?: DebugLevel;
105
+ }
106
+ type DebugLevel = 'NONE' | 'ERROR' | 'WARN' | 'INFO' | 'DEBUG' | 'VERBOSE';
107
+ /**
108
+ * User attributes for pushUserSignin, pushUserSignup, pushUserUpdate
109
+ * - firstName, lastName are always required
110
+ * - At least one of email or mobile is required (validated at runtime)
111
+ * - customData is optional
112
+ */
113
+ interface UserAttributes {
114
+ firstName: string;
115
+ lastName: string;
116
+ email?: string;
117
+ mobile?: string;
118
+ externalId?: string;
119
+ customData?: Record<string, unknown>;
120
+ }
121
+ /**
122
+ * Identify action type — determines which internal user event is tracked.
123
+ * USER_REGISTER: signin
124
+ * USER_UPDATE: updates existing user attributes
125
+ */
126
+ type IdentifyActionType = 'USER_REGISTER' | 'USER_UPDATE';
127
+ /**
128
+ * Identifier type for the identify method
129
+ */
130
+ type IdentifierType = 'email' | 'mobile' | 'externalId';
131
+ /**
132
+ * User identifier — specifies how the user is identified
133
+ */
134
+ interface Identifier {
135
+ type: IdentifierType;
136
+ cuid: string;
137
+ }
138
+ /**
139
+ * User traits for the identify method
140
+ */
141
+ interface IdentifyTraits {
142
+ firstName?: string;
143
+ lastName?: string;
144
+ gender?: string;
145
+ birthday?: string;
146
+ city?: string;
147
+ country?: string;
148
+ timezone?: string;
149
+ custom?: Record<string, unknown>;
150
+ }
151
+ /**
152
+ * Parameters for the identify method.
153
+ * identifier and actionType are required.
154
+ */
155
+ interface IdentifyParams {
156
+ identifier: Identifier;
157
+ actionType: IdentifyActionType;
158
+ traits?: IdentifyTraits;
159
+ }
160
+ /**
161
+ * Options for manual page view tracking
162
+ */
163
+ interface PageViewOptions {
164
+ url?: string;
165
+ title?: string;
166
+ referrer?: string;
167
+ category?: string;
168
+ properties?: Record<string, unknown>;
169
+ }
170
+ /**
171
+ * Snapshot of the current user's identity, session, and engagement status.
172
+ * Returned by `WebSDK.getUser()`.
173
+ */
174
+ interface UserInfo {
175
+ visitorId: string;
176
+ userId: string | null;
177
+ sessionId: string;
178
+ isIdentified: boolean;
179
+ isAnonymous: boolean;
180
+ profileTier: 'anonymous' | 'known';
181
+ attributes: Record<string, unknown> | null;
182
+ sessionNumber: number;
183
+ isFirstSession: boolean;
184
+ isReturningVisitor: boolean;
185
+ }
186
+
187
+ /**
188
+ * User object for Events API v2
189
+ * Identifier-based format for flexible user identification
190
+ */
191
+ type UserIdentifierName = 'id' | 'mobile' | 'email' | 'externalId';
192
+
193
+ /**
194
+ * WebSDK Core Initialization
195
+ * Handles SDK bootstrap, lifecycle management, and main API
196
+ */
197
+
198
+ declare class WebSDK {
199
+ private static _instance;
200
+ private config;
201
+ private userContextSet;
202
+ private initialized;
203
+ private initializationPromise;
204
+ private logger;
205
+ private storageManager;
206
+ private sessionManager;
207
+ private eventTracker;
208
+ private visitorConfigManager;
209
+ private anonymousVisitorManager;
210
+ private visitorTrackingEnabled;
211
+ private visitorId;
212
+ private currentUserIdentifierType;
213
+ private notificationManager;
214
+ private permissionChangeCleanup;
215
+ private dlrMessageCleanup;
216
+ private lastAuthenticatedUser;
217
+ private lastUserAttributes;
218
+ private scrollDepthTracker;
219
+ private sdkDisabled;
220
+ private userIdentified;
221
+ private userOperationChain;
222
+ private apiClient;
223
+ private gamificationManager;
224
+ private gamificationBaseUrl;
225
+ constructor(config: WebSDKConfig);
226
+ /**
227
+ * Initialize the WebSDK singleton instance.
228
+ * This is the recommended way to set up the SDK — the host application
229
+ * only needs to call this once with the configuration.
230
+ *
231
+ * Supports two bootstrap modes, selected by whether `remoteConfigKey` is present:
232
+ * Remote Config bootstrap (fetches config from Firebase Remote Config), or direct-config
233
+ * bootstrap (config passed directly, no Firebase dependency unless `notifications` is used).
234
+ *
235
+ * @param config - SDK configuration
236
+ * @returns The WebSDK singleton instance
237
+ *
238
+ * @example Remote Config bootstrap
239
+ * ```typescript
240
+ * WebSDK.initialize({
241
+ * debugLevel: 'INFO',
242
+ * firebaseConfig: { ... },
243
+ * remoteConfigKey: 'my_app_config',
244
+ * notifications: { vapidKey: '...' },
245
+ * });
246
+ * ```
247
+ *
248
+ * @example Direct-config bootstrap (no Firebase)
249
+ * ```typescript
250
+ * WebSDK.initialize({
251
+ * accountId: 'my-account-id',
252
+ * baseURL: 'https://api.example.com',
253
+ * orgId: 'my-org-id',
254
+ * });
255
+ * ```
256
+ */
257
+ static initialize(config: WebSDKConfig): WebSDK;
258
+ /**
259
+ * Get the current WebSDK singleton instance.
260
+ * Returns null if the SDK has not been initialized.
261
+ *
262
+ * @returns The WebSDK instance or null
263
+ */
264
+ static getInstance(): WebSDK | null;
265
+ /**
266
+ * Check if the SDK singleton has been initialized.
267
+ */
268
+ static isInitialized(): boolean;
269
+ /**
270
+ * Internal helper — returns the singleton or throws if not initialized.
271
+ */
272
+ private static requireInstance;
273
+ /** @see WebSDK.prototype.track */
274
+ static track(eventName: string, properties?: Record<string, unknown>): void;
275
+ /** @see WebSDK.prototype.pageView */
276
+ static pageView(options?: PageViewOptions): void;
277
+ /** @see WebSDK.prototype.identify */
278
+ static identify(params: IdentifyParams): void;
279
+ /** @see WebSDK.prototype.getUser */
280
+ static getUser(): UserInfo;
281
+ /** @see WebSDK.prototype.getAnonymousId */
282
+ static getAnonymousId(): string | null;
283
+ /** @see WebSDK.prototype.reset */
284
+ static reset(): void;
285
+ /** @see WebSDK.prototype.setCapToken */
286
+ static setCapToken(token: string): void;
287
+ /** @see WebSDK.prototype.getCapToken */
288
+ static getCapToken(): string | null;
289
+ /** @see WebSDK.prototype.enablePagePathTracking */
290
+ static enablePagePathTracking(enabled: boolean): void;
291
+ /** @see WebSDK.prototype.onScreenChanged */
292
+ static onScreenChanged(screenName: string): void;
293
+ /** @see WebSDK.prototype.disableSDK */
294
+ static disableSDK(): void;
295
+ /** @see WebSDK.prototype.enableSDK */
296
+ static enableSDK(): void;
297
+ /** @see WebSDK.prototype.destroy */
298
+ static destroy(): Promise<void>;
299
+ /**
300
+ * Check if debug level should enable logging
301
+ */
302
+ private shouldEnableLogging;
303
+ /**
304
+ * Maps the Remote Config debugLevel string to the Logger's numeric threshold, so
305
+ * e.g. debugLevel: 'DEBUG' actually unlocks logger.debug() calls instead of only
306
+ * enabling/disabling logging while leaving the threshold at its INFO default.
307
+ */
308
+ private resolveLogLevel;
309
+ /**
310
+ * Restore user context from storage
311
+ */
312
+ private restoreUserContext;
313
+ /**
314
+ * Validate and clear different user context if needed
315
+ * Checks if the new user is different from the last authenticated user
316
+ * If so, ends the session to prevent mixing events
317
+ */
318
+ private validateAndClearDifferentUserContext;
319
+ /**
320
+ * Persist lastAuthenticatedUser to storage
321
+ */
322
+ private persistLastAuthenticatedUser;
323
+ /**
324
+ * Store user context to storage for cross-tab persistence
325
+ */
326
+ private storeUserContext;
327
+ /**
328
+ * Initialize the WebSDK (fire-and-forget)
329
+ */
330
+ init(): void;
331
+ /**
332
+ * Runs an initialization step and swallows any error, logging it instead.
333
+ * Used for non-fatal steps in initializeAsync so gamification always proceeds.
334
+ */
335
+ private tryStep;
336
+ /**
337
+ * Internal async initialization logic.
338
+ * Remote Config bootstrap is required — it provides gamificationWriteKey and all other config.
339
+ * Every step after that is isolated: failures in Hydra tracking infrastructure (storage,
340
+ * sessions, visitor API, event tracker) do not block gamification, which is an independent module.
341
+ */
342
+ private initializeAsync;
343
+ /**
344
+ * Setup automatic detection for notification permission changes
345
+ * This handles cases where user changes permission in browser settings
346
+ */
347
+ private handleVisibilityChange;
348
+ private setupPermissionChangeDetection;
349
+ /**
350
+ * Setup listener for DLR events from service worker.
351
+ * Service worker stores DLR events in IndexedDB and notifies the main app.
352
+ */
353
+ private setupDLRServiceWorkerListener;
354
+ /**
355
+ * Initialize visitor configuration and create visitor ID if enabled
356
+ */
357
+ private initializeVisitorConfig;
358
+ /**
359
+ * Sync event tracker context with visitor tracking state and user context
360
+ * Must be called AFTER eventTracker.init() to ensure EventQueue is initialized
361
+ */
362
+ private syncEventTrackerContext;
363
+ /**
364
+ * Get or create visitor ID
365
+ */
366
+ private getOrCreateVisitorId;
367
+ /**
368
+ * Setup callback to handle FCM token updates
369
+ * Automatically syncs token changes with backend via updateVisitor API
370
+ */
371
+ private setupTokenUpdateCallback;
372
+ /**
373
+ * Handle FCM token updates by syncing with backend
374
+ * Called automatically when token is created or refreshed
375
+ */
376
+ private handleTokenUpdate;
377
+ private logTokenSyncStart;
378
+ private syncTokenForIdentifiedUser;
379
+ private syncTokenForAnonymousUser;
380
+ /**
381
+ * Get a snapshot of the current user's identity, session, and engagement status.
382
+ * Only available for anonymous users. Once the user is identified, this method
383
+ * throws to prevent exposure of identified-user data.
384
+ */
385
+ getAnonymousId(): string | null;
386
+ getUser(): UserInfo;
387
+ /**
388
+ * Set user context for event tracking
389
+ * When user logs in/signs up, both visitor ID (if exists) and user ID will be sent for identity linking
390
+ */
391
+ setUserContext(cuid: string, userIdentifierType?: UserIdentifierName): Promise<void>;
392
+ /**
393
+ * Clear user context (sign out equivalent)
394
+ */
395
+ clearUserContext(): Promise<void>;
396
+ /**
397
+ * Track a behavioral event (fire-and-forget).
398
+ * This is the recommended public API for tracking events.
399
+ *
400
+ * @param eventName - Name of the event (e.g., 'page_view', 'button_click')
401
+ * @param properties - Optional event properties/attributes
402
+ */
403
+ track(eventName: string, properties?: Record<string, unknown>): void;
404
+ /**
405
+ * Manually track a page view event.
406
+ *
407
+ * @param options - Optional page view options (url, title, category, properties)
408
+ */
409
+ pageView(options?: PageViewOptions): void;
410
+ /**
411
+ * @param params - Identify parameters
412
+ * @example
413
+ * WebSDK.identify({
414
+ * identifier: { type: 'email', cuid: 'john@example.com' },
415
+ * actionType: 'USER_REGISTER',
416
+ * traits: { firstName: 'John', lastName: 'Doe', gender: 'male' }
417
+ * });
418
+ */
419
+ private pickTraitFields;
420
+ identify(params: IdentifyParams): void;
421
+ /**
422
+ * Internal method to track a structured Event object.
423
+ */
424
+ private trackEvent;
425
+ /**
426
+ * Destroy SDK instance and cleanup resources
427
+ */
428
+ destroy(): Promise<void>;
429
+ /**
430
+ * Validate user attributes (at least one identifier required)
431
+ */
432
+ private validateUserAttributes;
433
+ /**
434
+ * Build event data from cuid and user attributes
435
+ */
436
+ /**
437
+ * Attempt to merge anonymous visitor with authenticated user.
438
+ * Awaits the first merge attempt and returns its result. Retries run in background on failure.
439
+ */
440
+ private attemptVisitorMerge;
441
+ private buildPushData;
442
+ private buildUserAttributePayload;
443
+ /**
444
+ * Send a user lifecycle event to the User Events API.
445
+ * Pass explicit pushState to override permission/token detection (e.g. signout always forces push_opted:false).
446
+ */
447
+ private sendUserEventToApi;
448
+ /**
449
+ * Push user signin event (fire-and-forget)
450
+ * @param cuid - Customer user ID
451
+ * @param attributes - User attributes
452
+ */
453
+ pushUserSignin(cuid: string, attributes: UserAttributes, identifierType?: UserIdentifierName): void;
454
+ /**
455
+ * Internal async user signin logic
456
+ */
457
+ private pushUserSigninAsync;
458
+ /**
459
+ * Push user signup event (fire-and-forget)
460
+ * @param cuid - Customer user ID
461
+ * @param attributes - User attributes
462
+ */
463
+ pushUserSignup(cuid: string, attributes: UserAttributes, identifierType?: UserIdentifierName): void;
464
+ /**
465
+ * Internal async user signup logic
466
+ * user_signup is deprecated — routed as user_signin via User Events API
467
+ */
468
+ private pushUserSignupAsync;
469
+ /**
470
+ * Push user update event (fire-and-forget)
471
+ * @param cuid - Customer user ID
472
+ * @param attributes - User attributes
473
+ */
474
+ pushUserUpdate(cuid: string, attributes: UserAttributes, identifierType?: UserIdentifierName): void;
475
+ /**
476
+ * Internal async user update logic
477
+ */
478
+ private pushUserUpdateAsync;
479
+ /**
480
+ * Reset the SDK user state. Signs out the current authenticated user
481
+ * and returns to anonymous tracking mode.
482
+ * No-op if no user is currently authenticated.
483
+ */
484
+ reset(): void;
485
+ setCapToken(token: string): void;
486
+ getCapToken(): string | null;
487
+ /**
488
+ * Toggle automatic (default) vs manual path/screen tracking for gamification display
489
+ * rules. See DEVELOPER_GUIDE.md's Gamification section for details.
490
+ */
491
+ enablePagePathTracking(enabled: boolean): void;
492
+ /** Report the current screen when path tracking is disabled — call on every navigation. */
493
+ onScreenChanged(screenName: string): void;
494
+ /**
495
+ * Push user signout event and return to anonymous mode (fire-and-forget)
496
+ * Note: SDK continues to run for anonymous tracking after signout
497
+ */
498
+ pushUserSignOut(cuid: string): void;
499
+ private resetToAnonymousMode;
500
+ /**
501
+ * Internal async user signout logic
502
+ */
503
+ private pushUserSignOutAsync;
504
+ private buildInternalEventAttributes;
505
+ /**
506
+ * Push behavioral event (fire-and-forget)
507
+ */
508
+ pushEvent(eventName: string, attributes?: Record<string, unknown>): void;
509
+ /**
510
+ * Internal async behavioral event logic
511
+ */
512
+ private pushEventAsync;
513
+ /**
514
+ * Disable the SDK. Stops all event tracking immediately.
515
+ * New events are silently dropped. Queued events are paused (not deleted).
516
+ * The SDK remains initialized but inactive.
517
+ * Note: Consent storage is handled by the UI layer, not by the SDK.
518
+ */
519
+ disableSDK(): void;
520
+ /**
521
+ * Re-enable the SDK. Resumes event tracking and queue processing.
522
+ * Does not require re-initialization.
523
+ * Note: Consent storage is handled by the UI layer, not by the SDK.
524
+ */
525
+ enableSDK(): void;
526
+ /**
527
+ * Get the channel type for communication channels (e.g., 'web')
528
+ * This value is fetched from Remote Config and can be used when creating CommChannel objects
529
+ * @returns The channel type string from Remote Config (defaults to 'web')
530
+ */
531
+ getChannelType(): string;
532
+ private resolveGamificationBaseUrl;
533
+ /**
534
+ * Fills defaults for anything not already set on this.config, derives the gamification base/
535
+ * stream URLs, and wires the logger's enabled state. Shared by both bootstrap paths — by the
536
+ * time this runs, this.config already has accountId/baseURL/orgId (either freshly parsed from
537
+ * Remote Config or supplied directly by the host in direct-config bootstrap).
538
+ */
539
+ private applyConfigDefaults;
540
+ private applyRemoteConfigValues;
541
+ /**
542
+ * Applies config supplied directly by the host application (direct-config bootstrap —
543
+ * no remoteConfigKey). accountId/baseURL/orgId are already present on this.config
544
+ * (validateRequiredConfig() guarantees this); just apply the same defaults Remote Config
545
+ * bootstrap uses for everything else.
546
+ */
547
+ private applyDirectConfigValues;
548
+ /**
549
+ * Selects and runs the appropriate config bootstrap path. Presence of remoteConfigKey
550
+ * selects Remote Config bootstrap (fetches from Firebase); its absence selects
551
+ * direct-config bootstrap (uses whatever the host already passed into initialize()) —
552
+ * no Firebase module is loaded or executed in that case.
553
+ */
554
+ private bootstrapConfig;
555
+ private getExtendedFieldsForMerge;
556
+ private initializeManagersFromConfig;
557
+ /**
558
+ * Fetch configuration from Firebase Remote Config and apply to SDK
559
+ * This is ALWAYS called during SDK initialization
560
+ */
561
+ private fetchAndApplyRemoteConfig;
562
+ /**
563
+ * Validate required configuration fields for whichever bootstrap mode applies.
564
+ * Throws error if any required field is missing.
565
+ */
566
+ private validateRequiredConfig;
567
+ /**
568
+ * Ensure SDK is initialized before operations
569
+ * Waits for initialization to complete if in progress
570
+ */
571
+ private ensureInitialized;
572
+ /**
573
+ * Set user context if needed (for HydraSDK methods)
574
+ */
575
+ private setUserContextIfNeeded;
576
+ /**
577
+ * Serialize user identity operations (signin, signout, signup, update)
578
+ * so they execute in order and never overlap.
579
+ */
580
+ private queueUserOperation;
581
+ }
582
+
583
+ export { WebSDK as HydraSDK, WebSDK as default };
584
+ export type { DebugLevel, FirebaseConfig, Identifier, IdentifierType, IdentifyActionType, IdentifyParams, IdentifyTraits, NotificationConfig, NotificationPayload, NotificationState, PageViewOptions, UserAttributes, UserInfo, WebSDKConfig };