@grainql/analytics-web 2.2.0 → 2.2.1

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.
Files changed (83) hide show
  1. package/dist/index.global.dev.js +1 -1
  2. package/dist/index.global.js +1 -1
  3. package/dist/react/index.d.ts +44 -519
  4. package/dist/react/index.d.ts.map +1 -1
  5. package/dist/react/index.js +54 -1517
  6. package/dist/react/index.mjs +42 -1514
  7. package/package.json +1 -1
  8. package/dist/react/activity.d.ts +0 -59
  9. package/dist/react/activity.d.ts.map +0 -1
  10. package/dist/react/activity.js +0 -130
  11. package/dist/react/activity.mjs +0 -126
  12. package/dist/react/consent.d.ts +0 -72
  13. package/dist/react/consent.d.ts.map +0 -1
  14. package/dist/react/consent.js +0 -195
  15. package/dist/react/consent.mjs +0 -191
  16. package/dist/react/cookies.d.ts +0 -28
  17. package/dist/react/cookies.d.ts.map +0 -1
  18. package/dist/react/cookies.js +0 -94
  19. package/dist/react/cookies.mjs +0 -88
  20. package/dist/react/heartbeat.d.ts +0 -47
  21. package/dist/react/heartbeat.d.ts.map +0 -1
  22. package/dist/react/heartbeat.js +0 -119
  23. package/dist/react/heartbeat.mjs +0 -115
  24. package/dist/react/page-tracking.d.ts +0 -60
  25. package/dist/react/page-tracking.d.ts.map +0 -1
  26. package/dist/react/page-tracking.js +0 -179
  27. package/dist/react/page-tracking.mjs +0 -175
  28. package/dist/react/react/index.d.ts +0 -47
  29. package/dist/react/react/index.d.ts.map +0 -1
  30. package/dist/react/react/index.js +0 -58
  31. package/dist/react/react/index.mjs +0 -44
  32. /package/dist/react/{react/GrainProvider.d.ts → GrainProvider.d.ts} +0 -0
  33. /package/dist/react/{react/GrainProvider.d.ts.map → GrainProvider.d.ts.map} +0 -0
  34. /package/dist/react/{react/GrainProvider.js → GrainProvider.js} +0 -0
  35. /package/dist/react/{react/GrainProvider.mjs → GrainProvider.mjs} +0 -0
  36. /package/dist/react/{react/components → components}/ConsentBanner.d.ts +0 -0
  37. /package/dist/react/{react/components → components}/ConsentBanner.d.ts.map +0 -0
  38. /package/dist/react/{react/components → components}/ConsentBanner.js +0 -0
  39. /package/dist/react/{react/components → components}/ConsentBanner.mjs +0 -0
  40. /package/dist/react/{react/components → components}/CookieNotice.d.ts +0 -0
  41. /package/dist/react/{react/components → components}/CookieNotice.d.ts.map +0 -0
  42. /package/dist/react/{react/components → components}/CookieNotice.js +0 -0
  43. /package/dist/react/{react/components → components}/CookieNotice.mjs +0 -0
  44. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.d.ts +0 -0
  45. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.d.ts.map +0 -0
  46. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.js +0 -0
  47. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.mjs +0 -0
  48. /package/dist/react/{react/context.d.ts → context.d.ts} +0 -0
  49. /package/dist/react/{react/context.d.ts.map → context.d.ts.map} +0 -0
  50. /package/dist/react/{react/context.js → context.js} +0 -0
  51. /package/dist/react/{react/context.mjs → context.mjs} +0 -0
  52. /package/dist/react/{react/hooks → hooks}/useAllConfigs.d.ts +0 -0
  53. /package/dist/react/{react/hooks → hooks}/useAllConfigs.d.ts.map +0 -0
  54. /package/dist/react/{react/hooks → hooks}/useAllConfigs.js +0 -0
  55. /package/dist/react/{react/hooks → hooks}/useAllConfigs.mjs +0 -0
  56. /package/dist/react/{react/hooks → hooks}/useConfig.d.ts +0 -0
  57. /package/dist/react/{react/hooks → hooks}/useConfig.d.ts.map +0 -0
  58. /package/dist/react/{react/hooks → hooks}/useConfig.js +0 -0
  59. /package/dist/react/{react/hooks → hooks}/useConfig.mjs +0 -0
  60. /package/dist/react/{react/hooks → hooks}/useConsent.d.ts +0 -0
  61. /package/dist/react/{react/hooks → hooks}/useConsent.d.ts.map +0 -0
  62. /package/dist/react/{react/hooks → hooks}/useConsent.js +0 -0
  63. /package/dist/react/{react/hooks → hooks}/useConsent.mjs +0 -0
  64. /package/dist/react/{react/hooks → hooks}/useDataDeletion.d.ts +0 -0
  65. /package/dist/react/{react/hooks → hooks}/useDataDeletion.d.ts.map +0 -0
  66. /package/dist/react/{react/hooks → hooks}/useDataDeletion.js +0 -0
  67. /package/dist/react/{react/hooks → hooks}/useDataDeletion.mjs +0 -0
  68. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.d.ts +0 -0
  69. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.d.ts.map +0 -0
  70. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.js +0 -0
  71. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.mjs +0 -0
  72. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.d.ts +0 -0
  73. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.d.ts.map +0 -0
  74. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.js +0 -0
  75. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.mjs +0 -0
  76. /package/dist/react/{react/hooks → hooks}/useTrack.d.ts +0 -0
  77. /package/dist/react/{react/hooks → hooks}/useTrack.d.ts.map +0 -0
  78. /package/dist/react/{react/hooks → hooks}/useTrack.js +0 -0
  79. /package/dist/react/{react/hooks → hooks}/useTrack.mjs +0 -0
  80. /package/dist/react/{react/types.d.ts → types.d.ts} +0 -0
  81. /package/dist/react/{react/types.d.ts.map → types.d.ts.map} +0 -0
  82. /package/dist/react/{react/types.js → types.js} +0 -0
  83. /package/dist/react/{react/types.mjs → types.mjs} +0 -0
@@ -1,1521 +1,58 @@
1
1
  "use strict";
2
2
  /**
3
- * Grain Analytics Web SDK
4
- * A lightweight, dependency-free TypeScript SDK for sending analytics events to Grain's REST API
3
+ * Grain Analytics React Hooks
4
+ *
5
+ * React integration for @grainql/analytics-web
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * import { GrainProvider, useConfig, useTrack } from '@grainql/analytics-web/react';
10
+ *
11
+ * // Pattern 1: Provider-managed client
12
+ * <GrainProvider config={{ tenantId: 'xxx' }}>
13
+ * <App />
14
+ * </GrainProvider>
15
+ *
16
+ * // Pattern 2: External client
17
+ * const grain = new GrainAnalytics({ tenantId: 'xxx' });
18
+ * <GrainProvider client={grain}>
19
+ * <App />
20
+ * </GrainProvider>
21
+ *
22
+ * // Use hooks in components
23
+ * function MyComponent() {
24
+ * const { value } = useConfig('hero_variant');
25
+ * const track = useTrack();
26
+ *
27
+ * return <button onClick={() => track('clicked')}>Click</button>;
28
+ * }
29
+ * ```
5
30
  */
6
31
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.GrainAnalytics = void 0;
8
- exports.createGrainAnalytics = createGrainAnalytics;
9
- const consent_1 = require("./consent");
10
- const cookies_1 = require("./cookies");
11
- const activity_1 = require("./activity");
12
- const heartbeat_1 = require("./heartbeat");
13
- const page_tracking_1 = require("./page-tracking");
14
- class GrainAnalytics {
15
- constructor(config) {
16
- this.eventQueue = [];
17
- this.waitingForConsentQueue = [];
18
- this.flushTimer = null;
19
- this.isDestroyed = false;
20
- this.globalUserId = null;
21
- this.persistentAnonymousUserId = null;
22
- // Remote Config properties
23
- this.configCache = null;
24
- this.configRefreshTimer = null;
25
- this.configChangeListeners = [];
26
- this.configFetchPromise = null;
27
- this.cookiesEnabled = false;
28
- // Automatic Tracking properties
29
- this.activityDetector = null;
30
- this.heartbeatManager = null;
31
- this.pageTrackingManager = null;
32
- this.ephemeralSessionId = null;
33
- this.eventCountSinceLastHeartbeat = 0;
34
- this.config = {
35
- apiUrl: 'https://api.grainql.com',
36
- authStrategy: 'NONE',
37
- batchSize: 50,
38
- flushInterval: 5000, // 5 seconds
39
- retryAttempts: 3,
40
- retryDelay: 1000, // 1 second
41
- maxEventsPerRequest: 160, // Maximum events per API request
42
- debug: false,
43
- // Remote Config defaults
44
- defaultConfigurations: {},
45
- configCacheKey: 'grain_config',
46
- configRefreshInterval: 300000, // 5 minutes
47
- enableConfigCache: true,
48
- // Privacy defaults
49
- consentMode: 'opt-out',
50
- waitForConsent: false,
51
- enableCookies: false,
52
- anonymizeIP: false,
53
- disableAutoProperties: false,
54
- // Automatic Tracking defaults
55
- enableHeartbeat: true,
56
- heartbeatActiveInterval: 120000, // 2 minutes
57
- heartbeatInactiveInterval: 300000, // 5 minutes
58
- enableAutoPageView: true,
59
- stripQueryParams: true,
60
- ...config,
61
- tenantId: config.tenantId,
62
- };
63
- // Initialize consent manager
64
- this.consentManager = new consent_1.ConsentManager(this.config.tenantId, this.config.consentMode);
65
- // Check if cookies are enabled
66
- if (this.config.enableCookies) {
67
- this.cookiesEnabled = (0, cookies_1.areCookiesEnabled)();
68
- if (!this.cookiesEnabled && this.config.debug) {
69
- console.warn('[Grain Analytics] Cookies are not available, falling back to localStorage');
70
- }
71
- }
72
- // Set global userId if provided in config
73
- if (config.userId) {
74
- this.globalUserId = config.userId;
75
- }
76
- this.validateConfig();
77
- this.initializePersistentAnonymousUserId();
78
- this.setupBeforeUnload();
79
- this.startFlushTimer();
80
- this.initializeConfigCache();
81
- // Initialize ephemeral session ID (memory-only, not persisted)
82
- this.ephemeralSessionId = this.generateUUID();
83
- // Initialize automatic tracking (browser only)
84
- if (typeof window !== 'undefined') {
85
- this.initializeAutomaticTracking();
86
- }
87
- // Set up consent change listener to flush waiting events and handle consent upgrade
88
- this.consentManager.addListener((state) => {
89
- if (state.granted) {
90
- this.handleConsentGranted();
91
- }
92
- });
93
- }
94
- validateConfig() {
95
- if (!this.config.tenantId) {
96
- throw new Error('Grain Analytics: tenantId is required');
97
- }
98
- if (this.config.authStrategy === 'SERVER_SIDE' && !this.config.secretKey) {
99
- throw new Error('Grain Analytics: secretKey is required for SERVER_SIDE auth strategy');
100
- }
101
- if (this.config.authStrategy === 'JWT' && !this.config.authProvider) {
102
- throw new Error('Grain Analytics: authProvider is required for JWT auth strategy');
103
- }
104
- }
105
- /**
106
- * Generate a UUID v4 string
107
- */
108
- generateUUID() {
109
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
110
- return crypto.randomUUID();
111
- }
112
- // Fallback for environments without crypto.randomUUID
113
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
114
- const r = Math.random() * 16 | 0;
115
- const v = c === 'x' ? r : (r & 0x3 | 0x8);
116
- return v.toString(16);
117
- });
118
- }
119
- /**
120
- * Check if we should allow persistent storage (GDPR compliance)
121
- *
122
- * Returns true if:
123
- * - Consent has been granted, OR
124
- * - Not in opt-in mode, OR
125
- * - User has been explicitly identified by the site (login/identify), OR
126
- * - Using JWT auth strategy (functional/essential purpose)
127
- */
128
- shouldAllowPersistentStorage() {
129
- const hasConsent = this.consentManager.hasConsent('analytics');
130
- const isOptInMode = this.config.consentMode === 'opt-in';
131
- const userExplicitlyIdentified = !!this.globalUserId;
132
- const isJWTAuth = this.config.authStrategy === 'JWT';
133
- // Allow persistent storage if any of these conditions are met
134
- return hasConsent || !isOptInMode || userExplicitlyIdentified || isJWTAuth;
135
- }
136
- /**
137
- * Generate a proper UUIDv4 identifier for anonymous user ID
138
- */
139
- generateAnonymousUserId() {
140
- return this.generateUUID();
141
- }
142
- /**
143
- * Initialize persistent anonymous user ID from cookies or localStorage
144
- * Priority: Cookie → localStorage → generate new
145
- *
146
- * GDPR Compliance: In opt-in mode without consent, we skip loading/saving
147
- * persistent IDs unless the user has been explicitly identified by the site
148
- * or when using JWT auth (functional/essential purpose)
149
- */
150
- initializePersistentAnonymousUserId() {
151
- if (typeof window === 'undefined')
152
- return;
153
- // Check if we should avoid persistent storage (GDPR compliance)
154
- if (!this.shouldAllowPersistentStorage()) {
155
- this.log('Opt-in mode without consent: skipping persistent ID initialization (GDPR compliance)');
156
- return; // Don't load or create persistent ID
157
- }
158
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
159
- const cookieName = '_grain_uid';
160
- try {
161
- // Try to load from cookie first if enabled
162
- if (this.cookiesEnabled) {
163
- const cookieValue = (0, cookies_1.getCookie)(cookieName);
164
- if (cookieValue) {
165
- this.persistentAnonymousUserId = cookieValue;
166
- this.log('Loaded persistent anonymous user ID from cookie:', this.persistentAnonymousUserId);
167
- return;
168
- }
169
- }
170
- // Fallback to localStorage
171
- const stored = localStorage.getItem(storageKey);
172
- if (stored) {
173
- this.persistentAnonymousUserId = stored;
174
- this.log('Loaded persistent anonymous user ID from localStorage:', this.persistentAnonymousUserId);
175
- // Migrate to cookie if enabled
176
- if (this.cookiesEnabled) {
177
- this.savePersistentAnonymousUserId(stored);
178
- }
179
- }
180
- else {
181
- // Generate new UUIDv4 anonymous user ID
182
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
183
- this.savePersistentAnonymousUserId(this.persistentAnonymousUserId);
184
- this.log('Generated new persistent anonymous user ID:', this.persistentAnonymousUserId);
185
- }
186
- }
187
- catch (error) {
188
- this.log('Failed to initialize persistent anonymous user ID:', error);
189
- // Fallback: generate temporary ID without persistence
190
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
191
- }
192
- }
193
- /**
194
- * Save persistent anonymous user ID to cookie and/or localStorage
195
- *
196
- * GDPR Compliance: In opt-in mode without consent, we don't persist IDs
197
- * unless the user has been explicitly identified or using JWT auth
198
- */
199
- savePersistentAnonymousUserId(userId) {
200
- if (typeof window === 'undefined')
201
- return;
202
- // Check if we should avoid persistent storage (GDPR compliance)
203
- if (!this.shouldAllowPersistentStorage()) {
204
- this.log('Opt-in mode without consent: skipping persistent ID save (GDPR compliance)');
205
- return; // Don't save persistent ID
206
- }
207
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
208
- const cookieName = '_grain_uid';
209
- try {
210
- // Save to cookie if enabled
211
- if (this.cookiesEnabled) {
212
- const cookieOptions = {
213
- maxAge: 365 * 24 * 60 * 60, // 365 days
214
- sameSite: 'lax',
215
- secure: typeof window !== 'undefined' && window.location.protocol === 'https:',
216
- ...this.config.cookieOptions,
217
- };
218
- (0, cookies_1.setCookie)(cookieName, userId, cookieOptions);
219
- }
220
- // Always save to localStorage as fallback
221
- localStorage.setItem(storageKey, userId);
222
- }
223
- catch (error) {
224
- this.log('Failed to save persistent anonymous user ID:', error);
225
- }
226
- }
227
- /**
228
- * Get the effective user ID (global userId or persistent anonymous ID)
229
- *
230
- * GDPR Compliance: In opt-in mode without consent and no explicit user identification,
231
- * this should not be called. Use getEphemeralSessionId() instead.
232
- */
233
- getEffectiveUserIdInternal() {
234
- if (this.globalUserId) {
235
- return this.globalUserId;
236
- }
237
- if (this.persistentAnonymousUserId) {
238
- return this.persistentAnonymousUserId;
239
- }
240
- // Generate a new UUIDv4 identifier as fallback
241
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
242
- // Try to persist it (will be skipped in opt-in mode without consent)
243
- this.savePersistentAnonymousUserId(this.persistentAnonymousUserId);
244
- return this.persistentAnonymousUserId;
245
- }
246
- log(...args) {
247
- if (this.config.debug) {
248
- console.log('[Grain Analytics]', ...args);
249
- }
250
- }
251
- /**
252
- * Create error digest from events
253
- */
254
- createErrorDigest(events) {
255
- const eventNames = [...new Set(events.map(e => e.eventName))];
256
- const userIds = [...new Set(events.map(e => e.userId))];
257
- let totalProperties = 0;
258
- let totalSize = 0;
259
- events.forEach(event => {
260
- const properties = event.properties || {};
261
- totalProperties += Object.keys(properties).length;
262
- totalSize += JSON.stringify(event).length;
263
- });
264
- return {
265
- eventCount: events.length,
266
- totalProperties,
267
- totalSize,
268
- eventNames,
269
- userIds,
270
- };
271
- }
272
- /**
273
- * Format error with beautiful structure
274
- */
275
- formatError(error, context, events) {
276
- const digest = events ? this.createErrorDigest(events) : {
277
- eventCount: 0,
278
- totalProperties: 0,
279
- totalSize: 0,
280
- eventNames: [],
281
- userIds: [],
282
- };
283
- let code = 'UNKNOWN_ERROR';
284
- let message = 'An unknown error occurred';
285
- if (error instanceof Error) {
286
- message = error.message;
287
- // Determine error code based on error type and message
288
- if (message.includes('fetch failed') || message.includes('network error')) {
289
- code = 'NETWORK_ERROR';
290
- }
291
- else if (message.includes('timeout')) {
292
- code = 'TIMEOUT_ERROR';
293
- }
294
- else if (message.includes('HTTP 4')) {
295
- code = 'CLIENT_ERROR';
296
- }
297
- else if (message.includes('HTTP 5')) {
298
- code = 'SERVER_ERROR';
299
- }
300
- else if (message.includes('JSON')) {
301
- code = 'PARSE_ERROR';
302
- }
303
- else if (message.includes('auth') || message.includes('unauthorized')) {
304
- code = 'AUTH_ERROR';
305
- }
306
- else if (message.includes('rate limit') || message.includes('429')) {
307
- code = 'RATE_LIMIT_ERROR';
308
- }
309
- else {
310
- code = 'GENERAL_ERROR';
311
- }
312
- }
313
- else if (typeof error === 'string') {
314
- message = error;
315
- code = 'STRING_ERROR';
316
- }
317
- else if (error && typeof error === 'object' && 'status' in error) {
318
- const status = error.status;
319
- code = `HTTP_${status}`;
320
- message = `HTTP ${status} error`;
321
- }
322
- return {
323
- code,
324
- message,
325
- digest,
326
- timestamp: new Date().toISOString(),
327
- context,
328
- originalError: error,
329
- };
330
- }
331
- /**
332
- * Log formatted error gracefully
333
- */
334
- logError(formattedError) {
335
- const { code, message, digest, timestamp, context } = formattedError;
336
- const errorOutput = {
337
- '🚨 Grain Analytics Error': {
338
- 'Error Code': code,
339
- 'Message': message,
340
- 'Context': context,
341
- 'Timestamp': timestamp,
342
- 'Event Digest': {
343
- 'Events': digest.eventCount,
344
- 'Properties': digest.totalProperties,
345
- 'Size (bytes)': digest.totalSize,
346
- 'Event Names': digest.eventNames.length > 0 ? digest.eventNames.join(', ') : 'None',
347
- 'User IDs': digest.userIds.length > 0 ? digest.userIds.slice(0, 3).join(', ') + (digest.userIds.length > 3 ? '...' : '') : 'None',
348
- }
349
- }
350
- };
351
- console.error('🚨 Grain Analytics Error:', errorOutput);
352
- // Also log in a more compact format for debugging
353
- if (this.config.debug) {
354
- console.error(`[Grain Analytics] ${code}: ${message} (${context}) - Events: ${digest.eventCount}, Props: ${digest.totalProperties}, Size: ${digest.totalSize}B`);
355
- }
356
- }
357
- /**
358
- * Safely execute a function with error handling
359
- */
360
- async safeExecute(fn, context, events) {
361
- try {
362
- return await fn();
363
- }
364
- catch (error) {
365
- const formattedError = this.formatError(error, context, events);
366
- this.logError(formattedError);
367
- return null;
368
- }
369
- }
370
- formatEvent(event) {
371
- return {
372
- eventName: event.eventName,
373
- userId: event.userId || this.getEffectiveUserIdInternal(),
374
- properties: event.properties || {},
375
- };
376
- }
377
- async getAuthHeaders() {
378
- const headers = {
379
- 'Content-Type': 'application/json',
380
- };
381
- switch (this.config.authStrategy) {
382
- case 'NONE':
383
- break;
384
- case 'SERVER_SIDE':
385
- headers['Authorization'] = `Chase ${this.config.secretKey}`;
386
- break;
387
- case 'JWT':
388
- if (this.config.authProvider) {
389
- const token = await this.config.authProvider.getToken();
390
- headers['Authorization'] = `Bearer ${token}`;
391
- }
392
- break;
393
- }
394
- return headers;
395
- }
396
- async delay(ms) {
397
- return new Promise(resolve => setTimeout(resolve, ms));
398
- }
399
- isRetriableError(error) {
400
- if (error instanceof Error) {
401
- // Check for specific network or fetch errors
402
- const message = error.message.toLowerCase();
403
- if (message.includes('fetch failed'))
404
- return true;
405
- if (message === 'network error')
406
- return true; // Exact match to avoid "Non-network error"
407
- if (message.includes('timeout'))
408
- return true;
409
- if (message.includes('connection'))
410
- return true;
411
- }
412
- // Check for HTTP status codes that are retriable
413
- if (typeof error === 'object' && error !== null && 'status' in error) {
414
- const status = error.status;
415
- return status >= 500 || status === 429; // Server errors or rate limiting
416
- }
417
- return false;
418
- }
419
- async sendEvents(events) {
420
- if (events.length === 0)
421
- return;
422
- let lastError;
423
- for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
424
- try {
425
- const headers = await this.getAuthHeaders();
426
- const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;
427
- this.log(`Sending ${events.length} events to ${url} (attempt ${attempt + 1})`);
428
- const response = await fetch(url, {
429
- method: 'POST',
430
- headers,
431
- body: JSON.stringify(events),
432
- });
433
- if (!response.ok) {
434
- let errorMessage = `HTTP ${response.status}`;
435
- try {
436
- const errorBody = await response.json();
437
- if (errorBody?.message) {
438
- errorMessage = errorBody.message;
439
- }
440
- }
441
- catch {
442
- const errorText = await response.text();
443
- if (errorText) {
444
- errorMessage = errorText;
445
- }
446
- }
447
- const error = new Error(`Failed to send events: ${errorMessage}`);
448
- error.status = response.status;
449
- throw error;
450
- }
451
- this.log(`Successfully sent ${events.length} events`);
452
- return; // Success, exit retry loop
453
- }
454
- catch (error) {
455
- lastError = error;
456
- if (attempt === this.config.retryAttempts) {
457
- // Last attempt, don't retry - log error gracefully
458
- const formattedError = this.formatError(error, `sendEvents (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`, events);
459
- this.logError(formattedError);
460
- return; // Don't throw, just return gracefully
461
- }
462
- if (!this.isRetriableError(error)) {
463
- // Non-retriable error, don't retry - log error gracefully
464
- const formattedError = this.formatError(error, `sendEvents (non-retriable error)`, events);
465
- this.logError(formattedError);
466
- return; // Don't throw, just return gracefully
467
- }
468
- const delayMs = this.config.retryDelay * Math.pow(2, attempt); // Exponential backoff
469
- this.log(`Retrying in ${delayMs}ms after error:`, error);
470
- await this.delay(delayMs);
471
- }
472
- }
473
- }
474
- async sendEventsWithBeacon(events) {
475
- if (events.length === 0)
476
- return;
477
- try {
478
- const headers = await this.getAuthHeaders();
479
- const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;
480
- const body = JSON.stringify({ events });
481
- // Try beacon API first (more reliable for page unload)
482
- if (typeof navigator !== 'undefined' && 'sendBeacon' in navigator) {
483
- const blob = new Blob([body], { type: 'application/json' });
484
- const success = navigator.sendBeacon(url, blob);
485
- if (success) {
486
- this.log(`Successfully sent ${events.length} events via beacon`);
487
- return;
488
- }
489
- }
490
- // Fallback to fetch with keepalive
491
- await fetch(url, {
492
- method: 'POST',
493
- headers,
494
- body,
495
- keepalive: true,
496
- });
497
- this.log(`Successfully sent ${events.length} events via fetch (keepalive)`);
498
- }
499
- catch (error) {
500
- // Log error gracefully for beacon failures (page unload scenarios)
501
- const formattedError = this.formatError(error, 'sendEventsWithBeacon', events);
502
- this.logError(formattedError);
503
- }
504
- }
505
- startFlushTimer() {
506
- if (typeof window === 'undefined')
507
- return;
508
- if (this.flushTimer) {
509
- clearInterval(this.flushTimer);
510
- }
511
- this.flushTimer = window.setInterval(() => {
512
- if (this.eventQueue.length > 0) {
513
- this.flush().catch((error) => {
514
- const formattedError = this.formatError(error, 'auto-flush');
515
- this.logError(formattedError);
516
- });
517
- }
518
- }, this.config.flushInterval);
519
- }
520
- setupBeforeUnload() {
521
- if (typeof window === 'undefined')
522
- return;
523
- const handleBeforeUnload = () => {
524
- if (this.eventQueue.length > 0) {
525
- // Use beacon API for reliable delivery during page unload
526
- const eventsToSend = [...this.eventQueue];
527
- this.eventQueue = [];
528
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
529
- // Send first chunk with beacon (most important for page unload)
530
- if (chunks.length > 0) {
531
- this.sendEventsWithBeacon(chunks[0]).catch(() => {
532
- // Silently fail - page is unloading
533
- });
534
- }
535
- }
536
- };
537
- // Handle page unload
538
- window.addEventListener('beforeunload', handleBeforeUnload);
539
- window.addEventListener('pagehide', handleBeforeUnload);
540
- // Handle visibility change (page hidden)
541
- document.addEventListener('visibilitychange', () => {
542
- if (document.visibilityState === 'hidden' && this.eventQueue.length > 0) {
543
- const eventsToSend = [...this.eventQueue];
544
- this.eventQueue = [];
545
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
546
- // Send first chunk with beacon (most important for page hidden)
547
- if (chunks.length > 0) {
548
- this.sendEventsWithBeacon(chunks[0]).catch(() => {
549
- // Silently fail
550
- });
551
- }
552
- }
553
- });
554
- }
555
- /**
556
- * Initialize automatic tracking (heartbeat and page views)
557
- */
558
- initializeAutomaticTracking() {
559
- if (this.config.enableHeartbeat) {
560
- try {
561
- this.activityDetector = new activity_1.ActivityDetector();
562
- this.heartbeatManager = new heartbeat_1.HeartbeatManager(this, this.activityDetector, {
563
- activeInterval: this.config.heartbeatActiveInterval,
564
- inactiveInterval: this.config.heartbeatInactiveInterval,
565
- debug: this.config.debug,
566
- });
567
- this.log('Heartbeat tracking initialized');
568
- }
569
- catch (error) {
570
- this.log('Failed to initialize heartbeat tracking:', error);
571
- }
572
- }
573
- if (this.config.enableAutoPageView) {
574
- try {
575
- this.pageTrackingManager = new page_tracking_1.PageTrackingManager(this, {
576
- stripQueryParams: this.config.stripQueryParams,
577
- debug: this.config.debug,
578
- });
579
- this.log('Auto page view tracking initialized');
580
- }
581
- catch (error) {
582
- this.log('Failed to initialize page view tracking:', error);
583
- }
584
- }
585
- }
586
- /**
587
- * Handle consent granted - upgrade ephemeral session to persistent user
588
- */
589
- handleConsentGranted() {
590
- this.flushWaitingForConsentQueue();
591
- // Initialize persistent ID now that consent is granted (if not already initialized)
592
- if (!this.persistentAnonymousUserId) {
593
- this.initializePersistentAnonymousUserId();
594
- this.log('Initialized persistent ID after consent grant');
595
- }
596
- // Track consent granted event with mapping from ephemeral to persistent ID
597
- if (this.ephemeralSessionId) {
598
- this.trackSystemEvent('_grain_consent_granted', {
599
- previous_session_id: this.ephemeralSessionId,
600
- new_user_id: this.getEffectiveUserId(),
601
- timestamp: Date.now(),
602
- });
603
- }
604
- }
605
- /**
606
- * Track system events that bypass consent checks (for necessary/functional tracking)
607
- */
608
- trackSystemEvent(eventName, properties) {
609
- if (this.isDestroyed)
610
- return;
611
- const hasConsent = this.consentManager.hasConsent('analytics');
612
- // Create event with appropriate user ID
613
- const event = {
614
- eventName,
615
- userId: hasConsent ? this.getEffectiveUserId() : this.getEphemeralSessionId(),
616
- properties: {
617
- ...properties,
618
- _minimal: !hasConsent, // Flag to indicate minimal tracking
619
- _consent_status: hasConsent ? 'granted' : 'pending',
620
- },
621
- };
622
- // Bypass consent check for necessary system events
623
- this.eventQueue.push(event);
624
- this.eventCountSinceLastHeartbeat++;
625
- this.log(`Queued system event: ${eventName}`, properties);
626
- // Consider flushing
627
- if (this.eventQueue.length >= this.config.batchSize) {
628
- this.flush().catch((error) => {
629
- const formattedError = this.formatError(error, 'flush system event');
630
- this.logError(formattedError);
631
- });
632
- }
633
- }
634
- /**
635
- * Get ephemeral session ID (memory-only, not persisted)
636
- */
637
- getEphemeralSessionId() {
638
- if (!this.ephemeralSessionId) {
639
- this.ephemeralSessionId = this.generateUUID();
640
- }
641
- return this.ephemeralSessionId;
642
- }
643
- /**
644
- * Get the current page path from page tracker
645
- */
646
- getCurrentPage() {
647
- return this.pageTrackingManager?.getCurrentPage() || null;
648
- }
649
- /**
650
- * Get event count since last heartbeat
651
- */
652
- getEventCountSinceLastHeartbeat() {
653
- return this.eventCountSinceLastHeartbeat;
654
- }
655
- /**
656
- * Reset event count since last heartbeat
657
- */
658
- resetEventCountSinceLastHeartbeat() {
659
- this.eventCountSinceLastHeartbeat = 0;
660
- }
661
- /**
662
- * Get the effective user ID (public method)
663
- */
664
- getEffectiveUserId() {
665
- return this.getEffectiveUserIdInternal();
666
- }
667
- /**
668
- * Get the session ID (ephemeral or persistent based on consent)
669
- */
670
- getSessionId() {
671
- const hasConsent = this.consentManager.hasConsent('analytics');
672
- return hasConsent ? this.getEffectiveUserId() : this.getEphemeralSessionId();
673
- }
674
- async track(eventOrName, propertiesOrOptions, options) {
675
- try {
676
- if (this.isDestroyed) {
677
- const error = new Error('Grain Analytics: Client has been destroyed');
678
- const formattedError = this.formatError(error, 'track (client destroyed)');
679
- this.logError(formattedError);
680
- return;
681
- }
682
- let event;
683
- let opts = {};
684
- if (typeof eventOrName === 'string') {
685
- event = {
686
- eventName: eventOrName,
687
- properties: propertiesOrOptions,
688
- };
689
- opts = options || {};
690
- }
691
- else {
692
- event = eventOrName;
693
- opts = propertiesOrOptions || {};
694
- }
695
- // Filter properties if whitelist is enabled
696
- if (this.config.allowedProperties && event.properties) {
697
- const filtered = {};
698
- for (const key of this.config.allowedProperties) {
699
- if (key in event.properties) {
700
- filtered[key] = event.properties[key];
701
- }
702
- }
703
- event.properties = filtered;
704
- }
705
- const formattedEvent = this.formatEvent(event);
706
- // Check consent before tracking
707
- if (this.consentManager.shouldWaitForConsent() && this.config.waitForConsent) {
708
- // Queue event until consent is granted
709
- this.waitingForConsentQueue.push(formattedEvent);
710
- this.log(`Event waiting for consent: ${event.eventName}`, event.properties);
711
- return;
712
- }
713
- if (!this.consentManager.hasConsent('analytics')) {
714
- this.log(`Event blocked by consent: ${event.eventName}`);
715
- return;
716
- }
717
- this.eventQueue.push(formattedEvent);
718
- this.eventCountSinceLastHeartbeat++;
719
- this.log(`Queued event: ${event.eventName}`, event.properties);
720
- // Check if we should flush immediately
721
- if (opts.flush || this.eventQueue.length >= this.config.batchSize) {
722
- await this.flush();
723
- }
724
- }
725
- catch (error) {
726
- const formattedError = this.formatError(error, 'track');
727
- this.logError(formattedError);
728
- }
729
- }
730
- /**
731
- * Flush events that were waiting for consent
732
- */
733
- flushWaitingForConsentQueue() {
734
- if (this.waitingForConsentQueue.length === 0)
735
- return;
736
- this.log(`Flushing ${this.waitingForConsentQueue.length} events waiting for consent`);
737
- // Move waiting events to main queue
738
- this.eventQueue.push(...this.waitingForConsentQueue);
739
- this.waitingForConsentQueue = [];
740
- // Flush immediately
741
- this.flush().catch((error) => {
742
- const formattedError = this.formatError(error, 'flush waiting for consent queue');
743
- this.logError(formattedError);
744
- });
745
- }
746
- /**
747
- * Identify a user (sets userId for subsequent events)
748
- */
749
- identify(userId) {
750
- this.log(`Identified user: ${userId}`);
751
- this.globalUserId = userId;
752
- // Clear persistent anonymous user ID since we now have a real user ID
753
- this.persistentAnonymousUserId = null;
754
- }
755
- /**
756
- * Set global user ID for all subsequent events
757
- */
758
- setUserId(userId) {
759
- this.log(`Set global user ID: ${userId}`);
760
- this.globalUserId = userId;
761
- if (userId) {
762
- // Clear persistent anonymous user ID if setting a real user ID
763
- this.persistentAnonymousUserId = null;
764
- }
765
- else {
766
- // If clearing user ID, ensure we have an identifier
767
- if (!this.persistentAnonymousUserId) {
768
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
769
- // Try to persist the new anonymous ID (respects GDPR opt-in mode)
770
- this.savePersistentAnonymousUserId(this.persistentAnonymousUserId);
771
- }
772
- }
773
- }
774
- /**
775
- * Get current global user ID
776
- */
777
- getUserId() {
778
- return this.globalUserId;
779
- }
780
- /**
781
- * Get current effective user ID (global userId or persistent anonymous ID)
782
- */
783
- getEffectiveUserIdPublic() {
784
- return this.getEffectiveUserIdInternal();
785
- }
786
- /**
787
- * Login with auth token or userId on the fly
788
- *
789
- * @example
790
- * // Login with userId only
791
- * client.login({ userId: 'user123' });
792
- *
793
- * // Login with auth token (automatically sets authStrategy to JWT)
794
- * client.login({ authToken: 'jwt-token-here' });
795
- *
796
- * // Login with both userId and auth token
797
- * client.login({ userId: 'user123', authToken: 'jwt-token-here' });
798
- *
799
- * // Override auth strategy
800
- * client.login({ userId: 'user123', authStrategy: 'SERVER_SIDE' });
801
- */
802
- login(options) {
803
- try {
804
- if (this.isDestroyed) {
805
- const error = new Error('Grain Analytics: Client has been destroyed');
806
- const formattedError = this.formatError(error, 'login (client destroyed)');
807
- this.logError(formattedError);
808
- return;
809
- }
810
- // Set userId if provided
811
- if (options.userId) {
812
- this.log(`Login: Setting user ID to ${options.userId}`);
813
- this.globalUserId = options.userId;
814
- // Clear persistent anonymous user ID since we now have a real user ID
815
- this.persistentAnonymousUserId = null;
816
- }
817
- // Handle auth token if provided
818
- if (options.authToken) {
819
- this.log('Login: Setting auth token');
820
- // Update auth strategy to JWT if not already set
821
- if (this.config.authStrategy === 'NONE') {
822
- this.config.authStrategy = 'JWT';
823
- }
824
- // Create a simple auth provider that returns the provided token
825
- this.config.authProvider = {
826
- getToken: () => options.authToken
827
- };
828
- }
829
- // Override auth strategy if provided
830
- if (options.authStrategy) {
831
- this.log(`Login: Setting auth strategy to ${options.authStrategy}`);
832
- this.config.authStrategy = options.authStrategy;
833
- }
834
- this.log(`Login successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`);
835
- }
836
- catch (error) {
837
- const formattedError = this.formatError(error, 'login');
838
- this.logError(formattedError);
839
- }
840
- }
841
- /**
842
- * Logout and clear user session, fall back to UUIDv4 identifier
843
- *
844
- * @example
845
- * // Logout user and return to anonymous mode
846
- * client.logout();
847
- *
848
- * // After logout, events will use the persistent UUIDv4 identifier
849
- * client.track('page_view', { page: 'home' });
850
- */
851
- logout() {
852
- try {
853
- if (this.isDestroyed) {
854
- const error = new Error('Grain Analytics: Client has been destroyed');
855
- const formattedError = this.formatError(error, 'logout (client destroyed)');
856
- this.logError(formattedError);
857
- return;
858
- }
859
- this.log('Logout: Clearing user session');
860
- // Clear global user ID
861
- this.globalUserId = null;
862
- // Reset auth strategy to NONE
863
- this.config.authStrategy = 'NONE';
864
- this.config.authProvider = undefined;
865
- // Generate new UUIDv4 identifier if we don't have one
866
- if (!this.persistentAnonymousUserId) {
867
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
868
- // Try to persist the new anonymous ID
869
- if (typeof window !== 'undefined') {
870
- try {
871
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
872
- localStorage.setItem(storageKey, this.persistentAnonymousUserId);
873
- }
874
- catch (error) {
875
- this.log('Failed to persist new anonymous user ID after logout:', error);
876
- }
877
- }
878
- }
879
- this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`);
880
- }
881
- catch (error) {
882
- const formattedError = this.formatError(error, 'logout');
883
- this.logError(formattedError);
884
- }
885
- }
886
- /**
887
- * Set user properties
888
- */
889
- async setProperty(properties, options) {
890
- try {
891
- if (this.isDestroyed) {
892
- const error = new Error('Grain Analytics: Client has been destroyed');
893
- const formattedError = this.formatError(error, 'setProperty (client destroyed)');
894
- this.logError(formattedError);
895
- return;
896
- }
897
- const userId = options?.userId || this.getEffectiveUserIdInternal();
898
- // Validate property count (max 4 properties)
899
- const propertyKeys = Object.keys(properties);
900
- if (propertyKeys.length > 4) {
901
- const error = new Error('Grain Analytics: Maximum 4 properties allowed per request');
902
- const formattedError = this.formatError(error, 'setProperty (validation)');
903
- this.logError(formattedError);
904
- return;
905
- }
906
- if (propertyKeys.length === 0) {
907
- const error = new Error('Grain Analytics: At least one property is required');
908
- const formattedError = this.formatError(error, 'setProperty (validation)');
909
- this.logError(formattedError);
910
- return;
911
- }
912
- // Serialize all values to strings
913
- const serializedProperties = {};
914
- for (const [key, value] of Object.entries(properties)) {
915
- if (value === null || value === undefined) {
916
- serializedProperties[key] = '';
917
- }
918
- else if (typeof value === 'string') {
919
- serializedProperties[key] = value;
920
- }
921
- else {
922
- serializedProperties[key] = JSON.stringify(value);
923
- }
924
- }
925
- const payload = {
926
- userId,
927
- ...serializedProperties,
928
- };
929
- await this.sendProperties(payload);
930
- }
931
- catch (error) {
932
- const formattedError = this.formatError(error, 'setProperty');
933
- this.logError(formattedError);
934
- }
935
- }
936
- /**
937
- * Send properties to the API
938
- */
939
- async sendProperties(payload) {
940
- let lastError;
941
- for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
942
- try {
943
- const headers = await this.getAuthHeaders();
944
- const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`;
945
- this.log(`Setting properties for user ${payload.userId} (attempt ${attempt + 1})`);
946
- const response = await fetch(url, {
947
- method: 'POST',
948
- headers,
949
- body: JSON.stringify(payload),
950
- });
951
- if (!response.ok) {
952
- let errorMessage = `HTTP ${response.status}`;
953
- try {
954
- const errorBody = await response.json();
955
- if (errorBody?.message) {
956
- errorMessage = errorBody.message;
957
- }
958
- }
959
- catch {
960
- const errorText = await response.text();
961
- if (errorText) {
962
- errorMessage = errorText;
963
- }
964
- }
965
- const error = new Error(`Failed to set properties: ${errorMessage}`);
966
- error.status = response.status;
967
- throw error;
968
- }
969
- this.log(`Successfully set properties for user ${payload.userId}`);
970
- return; // Success, exit retry loop
971
- }
972
- catch (error) {
973
- lastError = error;
974
- if (attempt === this.config.retryAttempts) {
975
- // Last attempt, don't retry - log error gracefully
976
- const formattedError = this.formatError(error, `sendProperties (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`);
977
- this.logError(formattedError);
978
- return; // Don't throw, just return gracefully
979
- }
980
- if (!this.isRetriableError(error)) {
981
- // Non-retriable error, don't retry - log error gracefully
982
- const formattedError = this.formatError(error, 'sendProperties (non-retriable error)');
983
- this.logError(formattedError);
984
- return; // Don't throw, just return gracefully
985
- }
986
- const delayMs = this.config.retryDelay * Math.pow(2, attempt); // Exponential backoff
987
- this.log(`Retrying in ${delayMs}ms after error:`, error);
988
- await this.delay(delayMs);
989
- }
990
- }
991
- }
992
- // Template event methods
993
- /**
994
- * Track user login event
995
- */
996
- async trackLogin(properties, options) {
997
- try {
998
- return await this.track('login', properties, options);
999
- }
1000
- catch (error) {
1001
- const formattedError = this.formatError(error, 'trackLogin');
1002
- this.logError(formattedError);
1003
- }
1004
- }
1005
- /**
1006
- * Track user signup event
1007
- */
1008
- async trackSignup(properties, options) {
1009
- try {
1010
- return await this.track('signup', properties, options);
1011
- }
1012
- catch (error) {
1013
- const formattedError = this.formatError(error, 'trackSignup');
1014
- this.logError(formattedError);
1015
- }
1016
- }
1017
- /**
1018
- * Track checkout event
1019
- */
1020
- async trackCheckout(properties, options) {
1021
- try {
1022
- return await this.track('checkout', properties, options);
1023
- }
1024
- catch (error) {
1025
- const formattedError = this.formatError(error, 'trackCheckout');
1026
- this.logError(formattedError);
1027
- }
1028
- }
1029
- /**
1030
- * Track page view event
1031
- */
1032
- async trackPageView(properties, options) {
1033
- try {
1034
- return await this.track('page_view', properties, options);
1035
- }
1036
- catch (error) {
1037
- const formattedError = this.formatError(error, 'trackPageView');
1038
- this.logError(formattedError);
1039
- }
1040
- }
1041
- /**
1042
- * Track purchase event
1043
- */
1044
- async trackPurchase(properties, options) {
1045
- try {
1046
- return await this.track('purchase', properties, options);
1047
- }
1048
- catch (error) {
1049
- const formattedError = this.formatError(error, 'trackPurchase');
1050
- this.logError(formattedError);
1051
- }
1052
- }
1053
- /**
1054
- * Track search event
1055
- */
1056
- async trackSearch(properties, options) {
1057
- try {
1058
- return await this.track('search', properties, options);
1059
- }
1060
- catch (error) {
1061
- const formattedError = this.formatError(error, 'trackSearch');
1062
- this.logError(formattedError);
1063
- }
1064
- }
1065
- /**
1066
- * Track add to cart event
1067
- */
1068
- async trackAddToCart(properties, options) {
1069
- try {
1070
- return await this.track('add_to_cart', properties, options);
1071
- }
1072
- catch (error) {
1073
- const formattedError = this.formatError(error, 'trackAddToCart');
1074
- this.logError(formattedError);
1075
- }
1076
- }
1077
- /**
1078
- * Track remove from cart event
1079
- */
1080
- async trackRemoveFromCart(properties, options) {
1081
- try {
1082
- return await this.track('remove_from_cart', properties, options);
1083
- }
1084
- catch (error) {
1085
- const formattedError = this.formatError(error, 'trackRemoveFromCart');
1086
- this.logError(formattedError);
1087
- }
1088
- }
1089
- /**
1090
- * Manually flush all queued events
1091
- */
1092
- async flush() {
1093
- try {
1094
- if (this.eventQueue.length === 0)
1095
- return;
1096
- const eventsToSend = [...this.eventQueue];
1097
- this.eventQueue = [];
1098
- // Split events into chunks to respect maxEventsPerRequest limit
1099
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
1100
- // Send all chunks sequentially to maintain order
1101
- for (const chunk of chunks) {
1102
- await this.sendEvents(chunk);
1103
- }
1104
- }
1105
- catch (error) {
1106
- const formattedError = this.formatError(error, 'flush');
1107
- this.logError(formattedError);
1108
- }
1109
- }
1110
- // Remote Config Methods
1111
- /**
1112
- * Initialize configuration cache from localStorage
1113
- */
1114
- initializeConfigCache() {
1115
- if (!this.config.enableConfigCache || typeof window === 'undefined')
1116
- return;
1117
- try {
1118
- const cached = localStorage.getItem(this.config.configCacheKey);
1119
- if (cached) {
1120
- this.configCache = JSON.parse(cached);
1121
- this.log('Loaded configuration from cache:', this.configCache);
1122
- }
1123
- }
1124
- catch (error) {
1125
- this.log('Failed to load configuration cache:', error);
1126
- }
1127
- }
1128
- /**
1129
- * Save configuration cache to localStorage
1130
- */
1131
- saveConfigCache(cache) {
1132
- if (!this.config.enableConfigCache || typeof window === 'undefined')
1133
- return;
1134
- try {
1135
- localStorage.setItem(this.config.configCacheKey, JSON.stringify(cache));
1136
- this.log('Saved configuration to cache:', cache);
1137
- }
1138
- catch (error) {
1139
- this.log('Failed to save configuration cache:', error);
1140
- }
1141
- }
1142
- /**
1143
- * Get configuration value with fallback to defaults
1144
- */
1145
- getConfig(key) {
1146
- // First check cache
1147
- if (this.configCache?.configurations?.[key]) {
1148
- return this.configCache.configurations[key];
1149
- }
1150
- // Then check defaults
1151
- if (this.config.defaultConfigurations?.[key]) {
1152
- return this.config.defaultConfigurations[key];
1153
- }
1154
- return undefined;
1155
- }
1156
- /**
1157
- * Get all configurations with fallback to defaults
1158
- */
1159
- getAllConfigs() {
1160
- const configs = { ...this.config.defaultConfigurations };
1161
- if (this.configCache?.configurations) {
1162
- Object.assign(configs, this.configCache.configurations);
1163
- }
1164
- return configs;
1165
- }
1166
- /**
1167
- * Fetch configurations from API
1168
- */
1169
- async fetchConfig(options = {}) {
1170
- try {
1171
- if (this.isDestroyed) {
1172
- const error = new Error('Grain Analytics: Client has been destroyed');
1173
- const formattedError = this.formatError(error, 'fetchConfig (client destroyed)');
1174
- this.logError(formattedError);
1175
- return null;
1176
- }
1177
- const userId = options.userId || this.getEffectiveUserIdInternal();
1178
- const immediateKeys = options.immediateKeys || [];
1179
- const properties = options.properties || {};
1180
- const request = {
1181
- userId,
1182
- immediateKeys,
1183
- properties,
1184
- };
1185
- let lastError;
1186
- for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
1187
- try {
1188
- const headers = await this.getAuthHeaders();
1189
- const url = `${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`;
1190
- this.log(`Fetching configurations for user ${userId} (attempt ${attempt + 1})`);
1191
- const response = await fetch(url, {
1192
- method: 'POST',
1193
- headers,
1194
- body: JSON.stringify(request),
1195
- });
1196
- if (!response.ok) {
1197
- let errorMessage = `HTTP ${response.status}`;
1198
- try {
1199
- const errorBody = await response.json();
1200
- if (errorBody?.message) {
1201
- errorMessage = errorBody.message;
1202
- }
1203
- }
1204
- catch {
1205
- const errorText = await response.text();
1206
- if (errorText) {
1207
- errorMessage = errorText;
1208
- }
1209
- }
1210
- const error = new Error(`Failed to fetch configurations: ${errorMessage}`);
1211
- error.status = response.status;
1212
- throw error;
1213
- }
1214
- const configResponse = await response.json();
1215
- // Update cache if successful
1216
- if (configResponse.configurations) {
1217
- this.updateConfigCache(configResponse, userId);
1218
- }
1219
- this.log(`Successfully fetched configurations for user ${userId}:`, configResponse);
1220
- return configResponse;
1221
- }
1222
- catch (error) {
1223
- lastError = error;
1224
- if (attempt === this.config.retryAttempts) {
1225
- // Last attempt, don't retry - log error gracefully
1226
- const formattedError = this.formatError(error, `fetchConfig (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`);
1227
- this.logError(formattedError);
1228
- return null;
1229
- }
1230
- if (!this.isRetriableError(error)) {
1231
- // Non-retriable error, don't retry - log error gracefully
1232
- const formattedError = this.formatError(error, 'fetchConfig (non-retriable error)');
1233
- this.logError(formattedError);
1234
- return null;
1235
- }
1236
- const delayMs = this.config.retryDelay * Math.pow(2, attempt);
1237
- this.log(`Retrying config fetch in ${delayMs}ms after error:`, error);
1238
- await this.delay(delayMs);
1239
- }
1240
- }
1241
- return null;
1242
- }
1243
- catch (error) {
1244
- const formattedError = this.formatError(error, 'fetchConfig');
1245
- this.logError(formattedError);
1246
- return null;
1247
- }
1248
- }
1249
- /**
1250
- * Get configuration asynchronously (cache-first with fallback to API)
1251
- */
1252
- async getConfigAsync(key, options = {}) {
1253
- try {
1254
- // Return immediately if we have it in cache and not forcing refresh
1255
- if (!options.forceRefresh && this.configCache?.configurations?.[key]) {
1256
- return this.configCache.configurations[key];
1257
- }
1258
- // Return default if available and not forcing refresh
1259
- if (!options.forceRefresh && this.config.defaultConfigurations?.[key]) {
1260
- return this.config.defaultConfigurations[key];
1261
- }
1262
- // Fetch from API
1263
- const response = await this.fetchConfig(options);
1264
- if (response) {
1265
- return response.configurations[key];
1266
- }
1267
- // Return default as fallback
1268
- return this.config.defaultConfigurations?.[key];
1269
- }
1270
- catch (error) {
1271
- const formattedError = this.formatError(error, 'getConfigAsync');
1272
- this.logError(formattedError);
1273
- // Return default as fallback
1274
- return this.config.defaultConfigurations?.[key];
1275
- }
1276
- }
1277
- /**
1278
- * Get all configurations asynchronously (cache-first with fallback to API)
1279
- */
1280
- async getAllConfigsAsync(options = {}) {
1281
- try {
1282
- // Return cache if available and not forcing refresh
1283
- if (!options.forceRefresh && this.configCache?.configurations) {
1284
- return { ...this.config.defaultConfigurations, ...this.configCache.configurations };
1285
- }
1286
- // Fetch from API
1287
- const response = await this.fetchConfig(options);
1288
- if (response) {
1289
- return { ...this.config.defaultConfigurations, ...response.configurations };
1290
- }
1291
- // Return defaults as fallback
1292
- return { ...this.config.defaultConfigurations };
1293
- }
1294
- catch (error) {
1295
- const formattedError = this.formatError(error, 'getAllConfigsAsync');
1296
- this.logError(formattedError);
1297
- // Return defaults as fallback
1298
- return { ...this.config.defaultConfigurations };
1299
- }
1300
- }
1301
- /**
1302
- * Update configuration cache and notify listeners
1303
- */
1304
- updateConfigCache(response, userId) {
1305
- const newCache = {
1306
- configurations: response.configurations,
1307
- snapshotId: response.snapshotId,
1308
- timestamp: response.timestamp,
1309
- userId,
1310
- };
1311
- const oldConfigs = this.configCache?.configurations || {};
1312
- this.configCache = newCache;
1313
- this.saveConfigCache(newCache);
1314
- // Notify listeners if configurations changed
1315
- if (JSON.stringify(oldConfigs) !== JSON.stringify(response.configurations)) {
1316
- this.notifyConfigChangeListeners(response.configurations);
1317
- }
1318
- }
1319
- /**
1320
- * Add configuration change listener
1321
- */
1322
- addConfigChangeListener(listener) {
1323
- this.configChangeListeners.push(listener);
1324
- }
1325
- /**
1326
- * Remove configuration change listener
1327
- */
1328
- removeConfigChangeListener(listener) {
1329
- const index = this.configChangeListeners.indexOf(listener);
1330
- if (index > -1) {
1331
- this.configChangeListeners.splice(index, 1);
1332
- }
1333
- }
1334
- /**
1335
- * Notify all configuration change listeners
1336
- */
1337
- notifyConfigChangeListeners(configurations) {
1338
- this.configChangeListeners.forEach(listener => {
1339
- try {
1340
- listener(configurations);
1341
- }
1342
- catch (error) {
1343
- console.error('[Grain Analytics] Config change listener error:', error);
1344
- }
1345
- });
1346
- }
1347
- /**
1348
- * Start automatic configuration refresh timer
1349
- */
1350
- startConfigRefreshTimer() {
1351
- if (typeof window === 'undefined')
1352
- return;
1353
- if (this.configRefreshTimer) {
1354
- clearInterval(this.configRefreshTimer);
1355
- }
1356
- this.configRefreshTimer = window.setInterval(() => {
1357
- if (!this.isDestroyed) {
1358
- // Use effective userId (will be generated if not set)
1359
- this.fetchConfig().catch((error) => {
1360
- const formattedError = this.formatError(error, 'auto-config refresh');
1361
- this.logError(formattedError);
1362
- });
1363
- }
1364
- }, this.config.configRefreshInterval);
1365
- }
1366
- /**
1367
- * Stop automatic configuration refresh timer
1368
- */
1369
- stopConfigRefreshTimer() {
1370
- if (this.configRefreshTimer) {
1371
- clearInterval(this.configRefreshTimer);
1372
- this.configRefreshTimer = null;
1373
- }
1374
- }
1375
- /**
1376
- * Preload configurations for immediate access
1377
- */
1378
- async preloadConfig(immediateKeys = [], properties) {
1379
- try {
1380
- // Use effective userId (will be generated if not set)
1381
- const effectiveUserId = this.getEffectiveUserIdInternal();
1382
- this.log(`Preloading config for user: ${effectiveUserId}`);
1383
- const response = await this.fetchConfig({ immediateKeys, properties });
1384
- if (response) {
1385
- this.startConfigRefreshTimer();
1386
- }
1387
- }
1388
- catch (error) {
1389
- const formattedError = this.formatError(error, 'preloadConfig');
1390
- this.logError(formattedError);
1391
- }
1392
- }
1393
- /**
1394
- * Split events array into chunks of specified size
1395
- */
1396
- chunkEvents(events, chunkSize) {
1397
- const chunks = [];
1398
- for (let i = 0; i < events.length; i += chunkSize) {
1399
- chunks.push(events.slice(i, i + chunkSize));
1400
- }
1401
- return chunks;
1402
- }
1403
- // Privacy & Consent Methods
1404
- /**
1405
- * Grant consent for tracking
1406
- * @param categories - Optional array of consent categories (e.g., ['analytics', 'functional'])
1407
- */
1408
- grantConsent(categories) {
1409
- try {
1410
- this.consentManager.grantConsent(categories);
1411
- this.log('Consent granted', categories);
1412
- }
1413
- catch (error) {
1414
- const formattedError = this.formatError(error, 'grantConsent');
1415
- this.logError(formattedError);
1416
- }
1417
- }
1418
- /**
1419
- * Revoke consent for tracking (opt-out)
1420
- * @param categories - Optional array of categories to revoke (if not provided, revokes all)
1421
- */
1422
- revokeConsent(categories) {
1423
- try {
1424
- this.consentManager.revokeConsent(categories);
1425
- this.log('Consent revoked', categories);
1426
- // Clear queued events when consent is revoked
1427
- this.eventQueue = [];
1428
- this.waitingForConsentQueue = [];
1429
- }
1430
- catch (error) {
1431
- const formattedError = this.formatError(error, 'revokeConsent');
1432
- this.logError(formattedError);
1433
- }
1434
- }
1435
- /**
1436
- * Get current consent state
1437
- */
1438
- getConsentState() {
1439
- return this.consentManager.getConsentState();
1440
- }
1441
- /**
1442
- * Check if user has granted consent
1443
- * @param category - Optional category to check (if not provided, checks general consent)
1444
- */
1445
- hasConsent(category) {
1446
- return this.consentManager.hasConsent(category);
1447
- }
1448
- /**
1449
- * Add listener for consent state changes
1450
- */
1451
- onConsentChange(listener) {
1452
- this.consentManager.addListener(listener);
1453
- }
1454
- /**
1455
- * Remove consent change listener
1456
- */
1457
- offConsentChange(listener) {
1458
- this.consentManager.removeListener(listener);
1459
- }
1460
- /**
1461
- * Destroy the client and clean up resources
1462
- */
1463
- destroy() {
1464
- this.isDestroyed = true;
1465
- if (this.flushTimer) {
1466
- clearInterval(this.flushTimer);
1467
- this.flushTimer = null;
1468
- }
1469
- // Stop config refresh timer
1470
- this.stopConfigRefreshTimer();
1471
- // Clear config change listeners
1472
- this.configChangeListeners = [];
1473
- // Destroy automatic tracking managers
1474
- if (this.heartbeatManager) {
1475
- this.heartbeatManager.destroy();
1476
- this.heartbeatManager = null;
1477
- }
1478
- if (this.pageTrackingManager) {
1479
- this.pageTrackingManager.destroy();
1480
- this.pageTrackingManager = null;
1481
- }
1482
- if (this.activityDetector) {
1483
- this.activityDetector.destroy();
1484
- this.activityDetector = null;
1485
- }
1486
- // Send any remaining events (in chunks if necessary)
1487
- if (this.eventQueue.length > 0) {
1488
- const eventsToSend = [...this.eventQueue];
1489
- this.eventQueue = [];
1490
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
1491
- // Send first chunk with beacon (most important for page unload)
1492
- if (chunks.length > 0) {
1493
- this.sendEventsWithBeacon(chunks[0]).catch(() => {
1494
- // Silently fail during cleanup
1495
- });
1496
- // If there are more chunks, try to send them with regular fetch
1497
- for (let i = 1; i < chunks.length; i++) {
1498
- this.sendEventsWithBeacon(chunks[i]).catch(() => {
1499
- // Silently fail during cleanup
1500
- });
1501
- }
1502
- }
1503
- }
1504
- }
1505
- }
1506
- exports.GrainAnalytics = GrainAnalytics;
1507
- /**
1508
- * Create a new Grain Analytics client
1509
- */
1510
- function createGrainAnalytics(config) {
1511
- return new GrainAnalytics(config);
1512
- }
1513
- // Default export for convenience
1514
- exports.default = GrainAnalytics;
1515
- // Auto-setup for IIFE build
1516
- if (typeof window !== 'undefined') {
1517
- window.Grain = {
1518
- GrainAnalytics,
1519
- createGrainAnalytics,
1520
- };
1521
- }
32
+ exports.CookieNotice = exports.PrivacyPreferenceCenter = exports.ConsentBanner = exports.useDataDeletion = exports.usePrivacyPreferences = exports.useConsent = exports.useTrack = exports.useAllConfigs = exports.useConfig = exports.useGrainAnalytics = exports.GrainProvider = void 0;
33
+ // Provider
34
+ var GrainProvider_1 = require("./GrainProvider");
35
+ Object.defineProperty(exports, "GrainProvider", { enumerable: true, get: function () { return GrainProvider_1.GrainProvider; } });
36
+ // Hooks
37
+ var useGrainAnalytics_1 = require("./hooks/useGrainAnalytics");
38
+ Object.defineProperty(exports, "useGrainAnalytics", { enumerable: true, get: function () { return useGrainAnalytics_1.useGrainAnalytics; } });
39
+ var useConfig_1 = require("./hooks/useConfig");
40
+ Object.defineProperty(exports, "useConfig", { enumerable: true, get: function () { return useConfig_1.useConfig; } });
41
+ var useAllConfigs_1 = require("./hooks/useAllConfigs");
42
+ Object.defineProperty(exports, "useAllConfigs", { enumerable: true, get: function () { return useAllConfigs_1.useAllConfigs; } });
43
+ var useTrack_1 = require("./hooks/useTrack");
44
+ Object.defineProperty(exports, "useTrack", { enumerable: true, get: function () { return useTrack_1.useTrack; } });
45
+ // Privacy hooks
46
+ var useConsent_1 = require("./hooks/useConsent");
47
+ Object.defineProperty(exports, "useConsent", { enumerable: true, get: function () { return useConsent_1.useConsent; } });
48
+ var usePrivacyPreferences_1 = require("./hooks/usePrivacyPreferences");
49
+ Object.defineProperty(exports, "usePrivacyPreferences", { enumerable: true, get: function () { return usePrivacyPreferences_1.usePrivacyPreferences; } });
50
+ var useDataDeletion_1 = require("./hooks/useDataDeletion");
51
+ Object.defineProperty(exports, "useDataDeletion", { enumerable: true, get: function () { return useDataDeletion_1.useDataDeletion; } });
52
+ // Privacy components
53
+ var ConsentBanner_1 = require("./components/ConsentBanner");
54
+ Object.defineProperty(exports, "ConsentBanner", { enumerable: true, get: function () { return ConsentBanner_1.ConsentBanner; } });
55
+ var PrivacyPreferenceCenter_1 = require("./components/PrivacyPreferenceCenter");
56
+ Object.defineProperty(exports, "PrivacyPreferenceCenter", { enumerable: true, get: function () { return PrivacyPreferenceCenter_1.PrivacyPreferenceCenter; } });
57
+ var CookieNotice_1 = require("./components/CookieNotice");
58
+ Object.defineProperty(exports, "CookieNotice", { enumerable: true, get: function () { return CookieNotice_1.CookieNotice; } });