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