@temps-sdk/react-analytics 0.0.1-beta.9 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +534 -0
- package/dist/EngagementTracker.d.ts +55 -0
- package/dist/EngagementTracker.d.ts.map +1 -0
- package/dist/EngagementTracker.js +223 -0
- package/dist/Provider.d.ts +1 -1
- package/dist/Provider.d.ts.map +1 -1
- package/dist/Provider.js +65 -37
- package/dist/SessionRecorder.d.ts +57 -0
- package/dist/SessionRecorder.d.ts.map +1 -0
- package/dist/SessionRecorder.js +536 -0
- package/dist/constants.d.ts +2 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/types.d.ts +52 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/useEngagementTracking.d.ts +34 -0
- package/dist/useEngagementTracking.d.ts.map +1 -0
- package/dist/useEngagementTracking.js +65 -0
- package/dist/usePageLeave.d.ts.map +1 -1
- package/dist/usePageLeave.js +2 -1
- package/dist/useScrollVisibility.d.ts +58 -0
- package/dist/useScrollVisibility.d.ts.map +1 -0
- package/dist/useScrollVisibility.js +65 -0
- package/dist/useSessionRecording.d.ts +23 -0
- package/dist/useSessionRecording.d.ts.map +1 -0
- package/dist/useSessionRecording.js +99 -0
- package/dist/useSpeedAnalytics.d.ts +8 -0
- package/dist/useSpeedAnalytics.d.ts.map +1 -0
- package/dist/useSpeedAnalytics.js +60 -0
- package/dist/utils.d.ts +2 -2
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +2 -2
- package/package.json +27 -5
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef, useCallback, useState, useMemo } from "react";
|
|
3
|
+
import { record } from "rrweb";
|
|
4
|
+
import { pack } from "@rrweb/packer";
|
|
5
|
+
export const SESSION_RECORDER_ENDPOINT = "session-replay";
|
|
6
|
+
function generateSessionId() {
|
|
7
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
8
|
+
return crypto.randomUUID();
|
|
9
|
+
}
|
|
10
|
+
return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
11
|
+
}
|
|
12
|
+
function generateVisitorId() {
|
|
13
|
+
// Try to get a persistent visitor ID from localStorage
|
|
14
|
+
if (typeof localStorage !== "undefined") {
|
|
15
|
+
let visitorId = localStorage.getItem("temps_visitor_id");
|
|
16
|
+
if (!visitorId) {
|
|
17
|
+
visitorId = `visitor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
18
|
+
localStorage.setItem("temps_visitor_id", visitorId);
|
|
19
|
+
}
|
|
20
|
+
return visitorId;
|
|
21
|
+
}
|
|
22
|
+
return `visitor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
23
|
+
}
|
|
24
|
+
function getSessionMetadata(_domain) {
|
|
25
|
+
if (typeof window === "undefined")
|
|
26
|
+
return {};
|
|
27
|
+
const screen = window.screen || {};
|
|
28
|
+
const navigator = window.navigator || {};
|
|
29
|
+
return {
|
|
30
|
+
visitorId: generateVisitorId(),
|
|
31
|
+
userAgent: navigator.userAgent,
|
|
32
|
+
language: navigator.language,
|
|
33
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
34
|
+
screenWidth: screen.width,
|
|
35
|
+
screenHeight: screen.height,
|
|
36
|
+
colorDepth: screen.colorDepth || 24,
|
|
37
|
+
viewportWidth: window.innerWidth,
|
|
38
|
+
viewportHeight: window.innerHeight,
|
|
39
|
+
url: window.location.href,
|
|
40
|
+
timestamp: new Date().toISOString(),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function SessionRecorder({ basePath, // Required, no default
|
|
44
|
+
domain, enabled = false, excludedPaths = [], sessionSampleRate = 1.0, maskAllInputs = true, maskTextSelector = "[data-mask]", blockClass = "rr-block", ignoreClass = "rr-ignore", maskTextClass = "rr-mask", ignoreSelector = "[data-ignore]", blockSelector = "[data-private]", recordCanvas = false, collectFonts = true, slimDOMOptions = {
|
|
45
|
+
script: false,
|
|
46
|
+
comment: true,
|
|
47
|
+
headFavicon: true,
|
|
48
|
+
headWhitespace: true,
|
|
49
|
+
headMetaDescKeywords: true,
|
|
50
|
+
headMetaSocial: true,
|
|
51
|
+
headMetaRobots: true,
|
|
52
|
+
headMetaHttpEquiv: true,
|
|
53
|
+
headMetaAuthorship: true,
|
|
54
|
+
headMetaVerification: true,
|
|
55
|
+
}, maskInputOptions = {
|
|
56
|
+
password: true,
|
|
57
|
+
email: true,
|
|
58
|
+
}, batchSize = 100, flushInterval = 10000, sampling = {}, }) {
|
|
59
|
+
const stopFnRef = useRef(null);
|
|
60
|
+
const eventsRef = useRef([]);
|
|
61
|
+
const sessionIdRef = useRef("");
|
|
62
|
+
const sessionInitializedRef = useRef(false);
|
|
63
|
+
const flushTimeoutRef = useRef(null);
|
|
64
|
+
const initRetryCountRef = useRef(0);
|
|
65
|
+
const initFailedRef = useRef(false); // Track if init has permanently failed
|
|
66
|
+
const takeSnapshotRef = useRef(null); // Function to force a full snapshot
|
|
67
|
+
const maxInitRetries = 3;
|
|
68
|
+
const [isInitializing, setIsInitializing] = useState(false);
|
|
69
|
+
// Exponential backoff state for event sending
|
|
70
|
+
const sendRetryCountRef = useRef(0);
|
|
71
|
+
const maxSendRetries = 5;
|
|
72
|
+
const lastSendAttemptRef = useRef(0);
|
|
73
|
+
const isSendingRef = useRef(false); // Prevent concurrent sends
|
|
74
|
+
// Deep merge sampling defaults with proper handling of mouseInteraction
|
|
75
|
+
// Use useMemo to avoid recreating this object on every render
|
|
76
|
+
const samplingConfig = useMemo(() => {
|
|
77
|
+
const defaultSampling = {
|
|
78
|
+
scroll: 500,
|
|
79
|
+
media: 800,
|
|
80
|
+
mouseInteraction: {
|
|
81
|
+
MouseUp: false,
|
|
82
|
+
MouseDown: false,
|
|
83
|
+
Click: true,
|
|
84
|
+
ContextMenu: false,
|
|
85
|
+
DblClick: true,
|
|
86
|
+
Focus: true,
|
|
87
|
+
Blur: true,
|
|
88
|
+
TouchStart: false,
|
|
89
|
+
TouchEnd: false,
|
|
90
|
+
},
|
|
91
|
+
mousemove: false,
|
|
92
|
+
input: "last",
|
|
93
|
+
};
|
|
94
|
+
// Merge sampling configs, handling mouseInteraction specially
|
|
95
|
+
return {
|
|
96
|
+
...defaultSampling,
|
|
97
|
+
...sampling,
|
|
98
|
+
};
|
|
99
|
+
}, [sampling]);
|
|
100
|
+
const shouldRecord = useCallback(() => {
|
|
101
|
+
if (!enabled)
|
|
102
|
+
return false;
|
|
103
|
+
if (typeof window === "undefined")
|
|
104
|
+
return false;
|
|
105
|
+
// Check if current path should be excluded
|
|
106
|
+
const currentPath = window.location.pathname;
|
|
107
|
+
const isExcluded = excludedPaths.some(path => {
|
|
108
|
+
// Support wildcards in path patterns
|
|
109
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
110
|
+
return regex.test(currentPath);
|
|
111
|
+
});
|
|
112
|
+
if (isExcluded)
|
|
113
|
+
return false;
|
|
114
|
+
// Apply sampling rate
|
|
115
|
+
if (sessionSampleRate < 1.0) {
|
|
116
|
+
const random = Math.random();
|
|
117
|
+
if (random > sessionSampleRate)
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
return true;
|
|
121
|
+
}, [enabled, excludedPaths, sessionSampleRate]);
|
|
122
|
+
const initializeSession = useCallback(async () => {
|
|
123
|
+
// If already initialized or currently initializing, return current state
|
|
124
|
+
if (sessionInitializedRef.current || isInitializing)
|
|
125
|
+
return sessionInitializedRef.current;
|
|
126
|
+
// If we've permanently failed, don't try again
|
|
127
|
+
if (initFailedRef.current) {
|
|
128
|
+
console.warn("[SessionRecorder] Initialization has permanently failed, not retrying");
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
// Check if we've exceeded retry limit
|
|
132
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
133
|
+
console.error(`[SessionRecorder] Exceeded maximum initialization retries (${maxInitRetries})`);
|
|
134
|
+
initFailedRef.current = true; // Mark as permanently failed
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
setIsInitializing(true);
|
|
138
|
+
initRetryCountRef.current++;
|
|
139
|
+
console.log(`[SessionRecorder] Attempting to initialize session (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
140
|
+
const sessionId = generateSessionId();
|
|
141
|
+
sessionIdRef.current = sessionId;
|
|
142
|
+
try {
|
|
143
|
+
const metadata = {
|
|
144
|
+
sessionId: sessionId,
|
|
145
|
+
...getSessionMetadata(domain),
|
|
146
|
+
};
|
|
147
|
+
const response = await fetch(`${basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
|
|
148
|
+
method: "POST",
|
|
149
|
+
headers: {
|
|
150
|
+
"Content-Type": "application/json",
|
|
151
|
+
},
|
|
152
|
+
body: JSON.stringify(metadata),
|
|
153
|
+
});
|
|
154
|
+
if (response.status === 201) {
|
|
155
|
+
sessionInitializedRef.current = true;
|
|
156
|
+
initRetryCountRef.current = 0; // Reset retry count on success
|
|
157
|
+
initFailedRef.current = false; // Reset failed flag on success
|
|
158
|
+
// Store session ID in localStorage for reference
|
|
159
|
+
if (typeof localStorage !== "undefined") {
|
|
160
|
+
localStorage.setItem("currentRecordingSessionId", sessionId);
|
|
161
|
+
}
|
|
162
|
+
console.log("[SessionRecorder] Session initialized successfully:", sessionId);
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
console.error(`[SessionRecorder] Failed to initialize session: ${response.status} (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
167
|
+
sessionIdRef.current = ""; // Clear invalid session ID
|
|
168
|
+
// Mark as permanently failed if we've hit the retry limit
|
|
169
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
170
|
+
initFailedRef.current = true;
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
console.error(`[SessionRecorder] Failed to initialize session: ${error} (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
177
|
+
sessionIdRef.current = ""; // Clear invalid session ID
|
|
178
|
+
// Mark as permanently failed if we've hit the retry limit
|
|
179
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
180
|
+
initFailedRef.current = true;
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
setIsInitializing(false);
|
|
186
|
+
}
|
|
187
|
+
}, [basePath, domain, isInitializing]);
|
|
188
|
+
const sendEvents = useCallback(async (isReliable = false) => {
|
|
189
|
+
if (!sessionInitializedRef.current) {
|
|
190
|
+
console.warn("[SessionRecorder] Cannot send events - session not initialized");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const events = eventsRef.current;
|
|
194
|
+
if (events.length === 0)
|
|
195
|
+
return;
|
|
196
|
+
// Prevent concurrent sends
|
|
197
|
+
if (isSendingRef.current && !isReliable) {
|
|
198
|
+
console.log("[SessionRecorder] Already sending events, skipping this attempt");
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
// Check if we should apply backoff
|
|
202
|
+
const now = Date.now();
|
|
203
|
+
if (sendRetryCountRef.current > 0 && !isReliable) {
|
|
204
|
+
const backoffMs = Math.min(1000 * Math.pow(2, sendRetryCountRef.current), 30000);
|
|
205
|
+
const timeSinceLastAttempt = now - lastSendAttemptRef.current;
|
|
206
|
+
if (timeSinceLastAttempt < backoffMs) {
|
|
207
|
+
console.log(`[SessionRecorder] Backing off, waiting ${backoffMs - timeSinceLastAttempt}ms before retry`);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
isSendingRef.current = true;
|
|
212
|
+
lastSendAttemptRef.current = now;
|
|
213
|
+
const eventsToSend = [...events];
|
|
214
|
+
// Don't clear the array immediately - clear only after successful send
|
|
215
|
+
try {
|
|
216
|
+
// Pack the events for more efficient transmission
|
|
217
|
+
// Type assertion needed because rrweb's pack function expects eventWithTime but we have eventWithTime[]
|
|
218
|
+
const packedEvents = pack(eventsToSend);
|
|
219
|
+
// Base64 encode the packed string for safe JSON transmission
|
|
220
|
+
const encodedEvents = btoa(packedEvents);
|
|
221
|
+
const payload = {
|
|
222
|
+
sessionId: sessionIdRef.current,
|
|
223
|
+
events: encodedEvents,
|
|
224
|
+
};
|
|
225
|
+
const url = `${basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
|
|
226
|
+
if (isReliable) {
|
|
227
|
+
// Use sendBeacon for reliable sending on page unload
|
|
228
|
+
if (navigator.sendBeacon) {
|
|
229
|
+
const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
|
|
230
|
+
const sent = navigator.sendBeacon(url, blob);
|
|
231
|
+
if (!sent) {
|
|
232
|
+
// Fallback to fetch with keepalive
|
|
233
|
+
await fetch(url, {
|
|
234
|
+
method: "POST",
|
|
235
|
+
headers: { "Content-Type": "application/json" },
|
|
236
|
+
body: JSON.stringify(payload),
|
|
237
|
+
keepalive: true,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
// For reliable sends, we don't clear events as they're sent via beacon
|
|
241
|
+
// which doesn't provide response feedback
|
|
242
|
+
eventsRef.current = [];
|
|
243
|
+
sendRetryCountRef.current = 0; // Reset retry count on success
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
// Fallback to fetch with keepalive
|
|
247
|
+
await fetch(url, {
|
|
248
|
+
method: "POST",
|
|
249
|
+
headers: { "Content-Type": "application/json" },
|
|
250
|
+
body: JSON.stringify(payload),
|
|
251
|
+
keepalive: true,
|
|
252
|
+
});
|
|
253
|
+
// Clear events after successful send
|
|
254
|
+
eventsRef.current = [];
|
|
255
|
+
sendRetryCountRef.current = 0; // Reset retry count on success
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
const response = await fetch(url, {
|
|
260
|
+
method: "POST",
|
|
261
|
+
headers: { "Content-Type": "application/json" },
|
|
262
|
+
body: JSON.stringify(payload),
|
|
263
|
+
});
|
|
264
|
+
if (response.status === 404) {
|
|
265
|
+
// Session not found, mark as not initialized but don't auto-reinitialize
|
|
266
|
+
console.error("[SessionRecorder] Session not found on server, stopping recording");
|
|
267
|
+
sessionInitializedRef.current = false;
|
|
268
|
+
sessionIdRef.current = "";
|
|
269
|
+
// Clear the session from localStorage
|
|
270
|
+
if (typeof localStorage !== "undefined") {
|
|
271
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
272
|
+
}
|
|
273
|
+
// Stop recording to prevent further errors
|
|
274
|
+
if (stopFnRef.current) {
|
|
275
|
+
stopFnRef.current();
|
|
276
|
+
stopFnRef.current = null;
|
|
277
|
+
}
|
|
278
|
+
// Don't restore events - they're lost
|
|
279
|
+
eventsRef.current = [];
|
|
280
|
+
sendRetryCountRef.current = 0; // Reset retry count
|
|
281
|
+
}
|
|
282
|
+
else if (!response.ok) {
|
|
283
|
+
console.error("[SessionRecorder] Failed to send events:", response.status);
|
|
284
|
+
// Increment retry count with exponential backoff
|
|
285
|
+
sendRetryCountRef.current++;
|
|
286
|
+
if (sendRetryCountRef.current >= maxSendRetries) {
|
|
287
|
+
console.error(`[SessionRecorder] Exceeded max send retries (${maxSendRetries}), dropping ${events.length} events`);
|
|
288
|
+
eventsRef.current = []; // Drop events after too many failures
|
|
289
|
+
sendRetryCountRef.current = 0; // Reset for next batch
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
console.log(`[SessionRecorder] Will retry (${sendRetryCountRef.current}/${maxSendRetries}) with exponential backoff`);
|
|
293
|
+
// Keep events in the buffer for retry
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
// Clear events after successful send
|
|
298
|
+
eventsRef.current = [];
|
|
299
|
+
sendRetryCountRef.current = 0; // Reset retry count on success
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
console.error("[SessionRecorder] Failed to send session events:", error);
|
|
305
|
+
// Increment retry count with exponential backoff
|
|
306
|
+
sendRetryCountRef.current++;
|
|
307
|
+
if (sendRetryCountRef.current >= maxSendRetries) {
|
|
308
|
+
console.error(`[SessionRecorder] Exceeded max send retries (${maxSendRetries}) after error, dropping ${events.length} events`);
|
|
309
|
+
eventsRef.current = []; // Drop events after too many failures
|
|
310
|
+
sendRetryCountRef.current = 0; // Reset for next batch
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
console.log(`[SessionRecorder] Will retry (${sendRetryCountRef.current}/${maxSendRetries}) with exponential backoff`);
|
|
314
|
+
// Keep events in the buffer for retry
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
finally {
|
|
318
|
+
isSendingRef.current = false;
|
|
319
|
+
}
|
|
320
|
+
}, [basePath]);
|
|
321
|
+
const scheduleFlush = useCallback(() => {
|
|
322
|
+
// Clear any existing timeout
|
|
323
|
+
if (flushTimeoutRef.current) {
|
|
324
|
+
clearTimeout(flushTimeoutRef.current);
|
|
325
|
+
}
|
|
326
|
+
// Schedule the next flush after the interval
|
|
327
|
+
flushTimeoutRef.current = setTimeout(() => {
|
|
328
|
+
// Only send if we have events
|
|
329
|
+
if (eventsRef.current.length > 0) {
|
|
330
|
+
sendEvents(false);
|
|
331
|
+
}
|
|
332
|
+
// Reschedule for the next interval
|
|
333
|
+
scheduleFlush();
|
|
334
|
+
}, flushInterval);
|
|
335
|
+
}, [sendEvents, flushInterval]);
|
|
336
|
+
const startRecording = useCallback(async () => {
|
|
337
|
+
if (stopFnRef.current)
|
|
338
|
+
return; // Already recording
|
|
339
|
+
if (!shouldRecord())
|
|
340
|
+
return;
|
|
341
|
+
// If initialization has permanently failed, don't try to start
|
|
342
|
+
if (initFailedRef.current) {
|
|
343
|
+
console.warn("[SessionRecorder] Not starting recording - initialization has permanently failed");
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
// Initialize session first
|
|
347
|
+
const initialized = await initializeSession();
|
|
348
|
+
if (!initialized) {
|
|
349
|
+
console.error("[SessionRecorder] Failed to initialize session, not starting recording");
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
// Don't clear events buffer on restart - preserve any pending events
|
|
353
|
+
if (!eventsRef.current) {
|
|
354
|
+
eventsRef.current = [];
|
|
355
|
+
}
|
|
356
|
+
const stopFn = record({
|
|
357
|
+
emit(event) {
|
|
358
|
+
eventsRef.current.push(event);
|
|
359
|
+
// Send when we have accumulated a full batch (whichever comes first: time or size)
|
|
360
|
+
if (eventsRef.current.length >= batchSize) {
|
|
361
|
+
sendEvents(false);
|
|
362
|
+
// Reset the flush timer since we just sent
|
|
363
|
+
scheduleFlush();
|
|
364
|
+
}
|
|
365
|
+
},
|
|
366
|
+
sampling: samplingConfig,
|
|
367
|
+
blockSelector,
|
|
368
|
+
ignoreSelector,
|
|
369
|
+
recordCanvas,
|
|
370
|
+
collectFonts,
|
|
371
|
+
maskAllInputs,
|
|
372
|
+
maskInputOptions,
|
|
373
|
+
maskTextSelector,
|
|
374
|
+
blockClass,
|
|
375
|
+
ignoreClass,
|
|
376
|
+
maskTextClass,
|
|
377
|
+
slimDOMOptions,
|
|
378
|
+
checkoutEveryNms: 30000,
|
|
379
|
+
checkoutEveryNth: 200,
|
|
380
|
+
});
|
|
381
|
+
if (stopFn) {
|
|
382
|
+
stopFnRef.current = stopFn;
|
|
383
|
+
// Store the takeFullSnapshot function from rrweb
|
|
384
|
+
// The record function returns an object with both stop and takeFullSnapshot methods
|
|
385
|
+
takeSnapshotRef.current = stopFn.takeFullSnapshot || null;
|
|
386
|
+
}
|
|
387
|
+
// Start the flush interval
|
|
388
|
+
scheduleFlush();
|
|
389
|
+
}, [shouldRecord, initializeSession, sendEvents, scheduleFlush, batchSize, blockSelector, ignoreSelector, recordCanvas, collectFonts, maskAllInputs, maskInputOptions, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions, samplingConfig]);
|
|
390
|
+
const stopRecording = useCallback(() => {
|
|
391
|
+
if (stopFnRef.current) {
|
|
392
|
+
stopFnRef.current();
|
|
393
|
+
stopFnRef.current = null;
|
|
394
|
+
// Clear flush timeout
|
|
395
|
+
if (flushTimeoutRef.current) {
|
|
396
|
+
clearTimeout(flushTimeoutRef.current);
|
|
397
|
+
flushTimeoutRef.current = null;
|
|
398
|
+
}
|
|
399
|
+
// Send any remaining events reliably
|
|
400
|
+
sendEvents(true);
|
|
401
|
+
// Clear session state
|
|
402
|
+
sessionInitializedRef.current = false;
|
|
403
|
+
sessionIdRef.current = "";
|
|
404
|
+
// Clear session ID from localStorage
|
|
405
|
+
if (typeof localStorage !== "undefined") {
|
|
406
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
// Reset retry counters when explicitly stopping
|
|
410
|
+
initRetryCountRef.current = 0;
|
|
411
|
+
initFailedRef.current = false;
|
|
412
|
+
}, [sendEvents]);
|
|
413
|
+
// Effect to handle recording lifecycle
|
|
414
|
+
useEffect(() => {
|
|
415
|
+
// Early return if we shouldn't record or have permanently failed
|
|
416
|
+
if (!enabled || initFailedRef.current || stopFnRef.current || sessionInitializedRef.current) {
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
// Check if current path should be excluded
|
|
420
|
+
const currentPath = window.location.pathname;
|
|
421
|
+
const isExcluded = excludedPaths.some(path => {
|
|
422
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
423
|
+
return regex.test(currentPath);
|
|
424
|
+
});
|
|
425
|
+
if (isExcluded) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
// Apply sampling rate
|
|
429
|
+
if (sessionSampleRate < 1.0) {
|
|
430
|
+
const random = Math.random();
|
|
431
|
+
if (random > sessionSampleRate) {
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
// Now we can start recording
|
|
436
|
+
startRecording();
|
|
437
|
+
// Handle page unload
|
|
438
|
+
const handleUnload = () => {
|
|
439
|
+
if (sessionInitializedRef.current && eventsRef.current.length > 0) {
|
|
440
|
+
sendEvents(true);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
window.addEventListener("beforeunload", handleUnload);
|
|
444
|
+
window.addEventListener("pagehide", handleUnload);
|
|
445
|
+
return () => {
|
|
446
|
+
window.removeEventListener("beforeunload", handleUnload);
|
|
447
|
+
window.removeEventListener("pagehide", handleUnload);
|
|
448
|
+
};
|
|
449
|
+
// Dependencies that should trigger re-evaluation
|
|
450
|
+
}, [enabled, excludedPaths, sessionSampleRate, startRecording, sendEvents]);
|
|
451
|
+
// Monitor location changes to stop/start recording based on excluded paths
|
|
452
|
+
useEffect(() => {
|
|
453
|
+
const checkPathAndToggleRecording = () => {
|
|
454
|
+
if (!enabled || initFailedRef.current) {
|
|
455
|
+
if (!enabled) {
|
|
456
|
+
stopRecording();
|
|
457
|
+
}
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
const currentPath = window.location.pathname;
|
|
461
|
+
const isExcluded = excludedPaths.some(path => {
|
|
462
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
463
|
+
return regex.test(currentPath);
|
|
464
|
+
});
|
|
465
|
+
// Only stop/start recording if we're actually changing exclusion status
|
|
466
|
+
// This prevents unnecessary restarts during normal navigation
|
|
467
|
+
const isCurrentlyRecording = stopFnRef.current !== null;
|
|
468
|
+
if (isExcluded && isCurrentlyRecording) {
|
|
469
|
+
// Path is excluded and we're recording - stop
|
|
470
|
+
stopRecording();
|
|
471
|
+
}
|
|
472
|
+
else if (!isExcluded && !isCurrentlyRecording && !initFailedRef.current) {
|
|
473
|
+
// Path is not excluded and we're not recording - start
|
|
474
|
+
startRecording();
|
|
475
|
+
}
|
|
476
|
+
// If the path exclusion status hasn't changed, keep recording continuously
|
|
477
|
+
};
|
|
478
|
+
// Listen for route changes
|
|
479
|
+
const originalPushState = window.history.pushState;
|
|
480
|
+
const originalReplaceState = window.history.replaceState;
|
|
481
|
+
window.history.pushState = function (...args) {
|
|
482
|
+
// Flush current events before route change to ensure they're captured
|
|
483
|
+
if (stopFnRef.current && eventsRef.current.length > 0) {
|
|
484
|
+
sendEvents(false);
|
|
485
|
+
}
|
|
486
|
+
originalPushState.apply(window.history, args);
|
|
487
|
+
// Use setTimeout to allow DOM updates to complete, then take snapshot
|
|
488
|
+
setTimeout(() => {
|
|
489
|
+
checkPathAndToggleRecording();
|
|
490
|
+
// Force a full snapshot after route change to capture new page state
|
|
491
|
+
// This ensures the replay shows the correct content after navigation
|
|
492
|
+
if (takeSnapshotRef.current) {
|
|
493
|
+
takeSnapshotRef.current();
|
|
494
|
+
}
|
|
495
|
+
}, 100); // Small delay to ensure DOM is updated
|
|
496
|
+
};
|
|
497
|
+
window.history.replaceState = function (...args) {
|
|
498
|
+
// Flush current events before route change to ensure they're captured
|
|
499
|
+
if (stopFnRef.current && eventsRef.current.length > 0) {
|
|
500
|
+
sendEvents(false);
|
|
501
|
+
}
|
|
502
|
+
originalReplaceState.apply(window.history, args);
|
|
503
|
+
// Use setTimeout to allow DOM updates to complete, then take snapshot
|
|
504
|
+
setTimeout(() => {
|
|
505
|
+
checkPathAndToggleRecording();
|
|
506
|
+
// Force a full snapshot after route change to capture new page state
|
|
507
|
+
// This ensures the replay shows the correct content after navigation
|
|
508
|
+
if (takeSnapshotRef.current) {
|
|
509
|
+
takeSnapshotRef.current();
|
|
510
|
+
}
|
|
511
|
+
}, 100); // Small delay to ensure DOM is updated
|
|
512
|
+
};
|
|
513
|
+
const handlePopState = () => {
|
|
514
|
+
// Flush current events before route change to ensure they're captured
|
|
515
|
+
if (stopFnRef.current && eventsRef.current.length > 0) {
|
|
516
|
+
sendEvents(false);
|
|
517
|
+
}
|
|
518
|
+
// Use setTimeout to allow DOM updates to complete, then take snapshot
|
|
519
|
+
setTimeout(() => {
|
|
520
|
+
checkPathAndToggleRecording();
|
|
521
|
+
// Force a full snapshot after route change to capture new page state
|
|
522
|
+
// This ensures the replay shows the correct content after navigation
|
|
523
|
+
if (takeSnapshotRef.current) {
|
|
524
|
+
takeSnapshotRef.current();
|
|
525
|
+
}
|
|
526
|
+
}, 100); // Small delay to ensure DOM is updated
|
|
527
|
+
};
|
|
528
|
+
window.addEventListener("popstate", handlePopState);
|
|
529
|
+
return () => {
|
|
530
|
+
window.history.pushState = originalPushState;
|
|
531
|
+
window.history.replaceState = originalReplaceState;
|
|
532
|
+
window.removeEventListener("popstate", handlePopState);
|
|
533
|
+
};
|
|
534
|
+
}, [enabled, excludedPaths, startRecording, stopRecording, sendEvents]);
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,gBAAgB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DEFAULT_BASE_PATH = "/api/_temps";
|
package/dist/index.d.ts
CHANGED
|
@@ -4,4 +4,10 @@ export * from "./useAnalytics";
|
|
|
4
4
|
export * from "./useTrackEvent";
|
|
5
5
|
export * from "./useTrackPageview";
|
|
6
6
|
export * from "./usePageLeave";
|
|
7
|
+
export * from "./useSpeedAnalytics";
|
|
8
|
+
export * from "./useEngagementTracking";
|
|
9
|
+
export * from "./useScrollVisibility";
|
|
10
|
+
export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
|
|
11
|
+
export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
|
|
12
|
+
export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
|
|
7
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,eAAe,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -5,3 +5,9 @@ export * from "./useAnalytics";
|
|
|
5
5
|
export * from "./useTrackEvent";
|
|
6
6
|
export * from "./useTrackPageview";
|
|
7
7
|
export * from "./usePageLeave";
|
|
8
|
+
export * from "./useSpeedAnalytics";
|
|
9
|
+
export * from "./useEngagementTracking";
|
|
10
|
+
export * from "./useScrollVisibility";
|
|
11
|
+
export { EngagementTracker } from "./EngagementTracker";
|
|
12
|
+
export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
|
|
13
|
+
export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
|
package/dist/types.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ export interface AnalyticsEventBase {
|
|
|
10
10
|
event_data?: Record<string, JsonValue>;
|
|
11
11
|
}
|
|
12
12
|
export interface AnalyticsClientOptions {
|
|
13
|
-
/** Base endpoint path. Defaults to `/
|
|
13
|
+
/** Base endpoint path. Defaults to `/_temps`. */
|
|
14
14
|
basePath?: string;
|
|
15
15
|
/** Set to true to disable analytics (e.g., for tests). */
|
|
16
16
|
disabled?: boolean;
|
|
@@ -36,7 +36,58 @@ export interface TempsAnalyticsProviderProps extends AnalyticsClientOptions {
|
|
|
36
36
|
autoTrackPageLeave?: boolean;
|
|
37
37
|
/** Custom event name for page leave events. Defaults to "page_leave". */
|
|
38
38
|
pageLeaveEventName?: string;
|
|
39
|
+
/** Auto track speed analytics (Web Vitals). Defaults to true. */
|
|
40
|
+
autoTrackSpeedAnalytics?: boolean;
|
|
41
|
+
/** Auto track engagement with heartbeats. Defaults to true. */
|
|
42
|
+
autoTrackEngagement?: boolean;
|
|
43
|
+
/** Heartbeat interval in milliseconds. Defaults to 30000 (30 seconds). */
|
|
44
|
+
heartbeatInterval?: number;
|
|
45
|
+
/** Inactivity timeout in milliseconds. Defaults to 30000 (30 seconds). */
|
|
46
|
+
inactivityTimeout?: number;
|
|
47
|
+
/** Engagement threshold in milliseconds to consider session engaged. Defaults to 10000 (10 seconds). */
|
|
48
|
+
engagementThreshold?: number;
|
|
49
|
+
/** Enable session recording. Defaults to false. */
|
|
50
|
+
enableSessionRecording?: boolean;
|
|
51
|
+
/** Session recording configuration. */
|
|
52
|
+
sessionRecordingConfig?: {
|
|
53
|
+
/** Paths to exclude from recording. */
|
|
54
|
+
excludedPaths?: string[];
|
|
55
|
+
/** Sample rate for recording sessions (0.0 to 1.0). Defaults to 1.0. */
|
|
56
|
+
sessionSampleRate?: number;
|
|
57
|
+
/** Mask all inputs. Defaults to true. */
|
|
58
|
+
maskAllInputs?: boolean;
|
|
59
|
+
/** CSS selector for masking text. Defaults to "[data-mask]". */
|
|
60
|
+
maskTextSelector?: string;
|
|
61
|
+
/** CSS class to block from recording. Defaults to "rr-block". */
|
|
62
|
+
blockClass?: string;
|
|
63
|
+
/** CSS class to ignore from recording. Defaults to "rr-ignore". */
|
|
64
|
+
ignoreClass?: string;
|
|
65
|
+
/** CSS class to mask text. Defaults to "rr-mask". */
|
|
66
|
+
maskTextClass?: string;
|
|
67
|
+
/** Record canvas elements. Defaults to false. */
|
|
68
|
+
recordCanvas?: boolean;
|
|
69
|
+
/** Collect fonts. Defaults to false. */
|
|
70
|
+
collectFonts?: boolean;
|
|
71
|
+
/** Number of events to batch before sending. Defaults to 100. */
|
|
72
|
+
batchSize?: number;
|
|
73
|
+
/** Interval in ms to flush events. Defaults to 5000. */
|
|
74
|
+
flushInterval?: number;
|
|
75
|
+
};
|
|
39
76
|
/** Children to render inside the provider. */
|
|
40
77
|
children: React.ReactNode;
|
|
41
78
|
}
|
|
79
|
+
export interface WebVitalMetric {
|
|
80
|
+
value: number;
|
|
81
|
+
rating: "good" | "needs-improvement" | "poor";
|
|
82
|
+
}
|
|
83
|
+
export interface SpeedMetric {
|
|
84
|
+
ttfb?: number | null;
|
|
85
|
+
lcp?: number | null;
|
|
86
|
+
fid?: number | null;
|
|
87
|
+
fcp?: number | null;
|
|
88
|
+
cls?: number | null;
|
|
89
|
+
inp?: number | null;
|
|
90
|
+
path?: string | null;
|
|
91
|
+
query?: string | null;
|
|
92
|
+
}
|
|
42
93
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnF,MAAM,WAA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