@temps-sdk/react-analytics 0.0.3 → 0.0.7

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 (44) hide show
  1. package/README.md +38 -7
  2. package/dist/EngagementTracker.d.ts +1 -54
  3. package/dist/EngagementTracker.d.ts.map +1 -1
  4. package/dist/EngagementTracker.js +3 -222
  5. package/dist/Provider.d.ts +2 -1
  6. package/dist/Provider.d.ts.map +1 -1
  7. package/dist/Provider.js +25 -10
  8. package/dist/SessionRecorder.d.ts +51 -52
  9. package/dist/SessionRecorder.d.ts.map +1 -1
  10. package/dist/SessionRecorder.js +32 -527
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/constants.d.ts.map +1 -1
  13. package/dist/constants.js +3 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -1
  17. package/dist/types.d.ts +9 -59
  18. package/dist/types.d.ts.map +1 -1
  19. package/dist/types.js +2 -0
  20. package/dist/useAnalytics.d.ts +3 -2
  21. package/dist/useAnalytics.d.ts.map +1 -1
  22. package/dist/useAnalytics.js +2 -0
  23. package/dist/useEngagementTracking.d.ts +3 -2
  24. package/dist/useEngagementTracking.d.ts.map +1 -1
  25. package/dist/useEngagementTracking.js +12 -23
  26. package/dist/usePageLeave.d.ts +4 -2
  27. package/dist/usePageLeave.d.ts.map +1 -1
  28. package/dist/usePageLeave.js +2 -0
  29. package/dist/useScrollVisibility.d.ts.map +1 -1
  30. package/dist/useScrollVisibility.js +2 -0
  31. package/dist/useSessionRecording.d.ts +5 -3
  32. package/dist/useSessionRecording.d.ts.map +1 -1
  33. package/dist/useSessionRecording.js +42 -42
  34. package/dist/useSpeedAnalytics.d.ts +11 -0
  35. package/dist/useSpeedAnalytics.d.ts.map +1 -1
  36. package/dist/useSpeedAnalytics.js +13 -53
  37. package/dist/useTrackEvent.d.ts.map +1 -1
  38. package/dist/useTrackEvent.js +2 -0
  39. package/dist/useTrackPageview.d.ts.map +1 -1
  40. package/dist/useTrackPageview.js +2 -0
  41. package/dist/utils.d.ts +1 -6
  42. package/dist/utils.d.ts.map +1 -1
  43. package/dist/utils.js +3 -96
  44. package/package.json +4 -3
@@ -1,536 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  "use client";
2
- import { useEffect, useRef, useCallback, useState, useMemo } from "react";
3
- import { record } from "rrweb";
4
- import { pack } from "@rrweb/packer";
4
+ import { useEffect, useMemo, useRef } from "react";
5
+ import { SessionRecorder as CoreSessionRecorder, } from "@temps-sdk/analytics-core";
5
6
  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
7
+ /**
8
+ * React binding for the framework-agnostic recorder in `@temps-sdk/analytics-core`.
9
+ *
10
+ * This used to be a second, independent rrweb implementation. Keeping two
11
+ * copies meant every ingest fix had to be made twice and they drifted instead
12
+ * — batch handling, the start-up race, and idle gating were all fixed in one
13
+ * and not the other. The component now owns only React lifecycle; all
14
+ * recording behaviour lives in the core class.
15
+ */
16
+ export function SessionRecorder(props) {
17
+ const recorderRef = useRef(null);
18
+ // Object and array props are rebuilt on every render by the caller (and by
19
+ // this component's own defaults), so depending on them directly would tear
20
+ // down and re-create the recorder on each render — losing the session and
21
+ // re-snapshotting the DOM every time. Key the effect on the serialized
22
+ // options instead.
23
+ const optionsKey = useMemo(() => JSON.stringify(props), [props]);
414
24
  useEffect(() => {
415
- // Early return if we shouldn't record or have permanently failed
416
- if (!enabled || initFailedRef.current || stopFnRef.current || sessionInitializedRef.current) {
25
+ if (!props.enabled)
417
26
  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);
27
+ const { enabled: _enabled, sampling, ...options } = props;
28
+ const recorder = new CoreSessionRecorder({
29
+ ...options,
30
+ sampling: sampling,
31
+ enabled: true,
424
32
  });
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);
33
+ recorderRef.current = recorder;
529
34
  return () => {
530
- window.history.pushState = originalPushState;
531
- window.history.replaceState = originalReplaceState;
532
- window.removeEventListener("popstate", handlePopState);
35
+ recorder.destroy();
36
+ recorderRef.current = null;
533
37
  };
534
- }, [enabled, excludedPaths, startRecording, stopRecording, sendEvents]);
38
+ // eslint-disable-next-line react-hooks/exhaustive-deps
39
+ }, [optionsKey]);
535
40
  return null;
536
41
  }
@@ -1,2 +1,2 @@
1
- export declare const DEFAULT_BASE_PATH = "/api/_temps";
1
+ export { DEFAULT_BASE_PATH } from "@temps-sdk/analytics-core";
2
2
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,gBAAgB,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC"}
package/dist/constants.js CHANGED
@@ -1 +1,3 @@
1
- export const DEFAULT_BASE_PATH = "/api/_temps";
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ export { DEFAULT_BASE_PATH } from "@temps-sdk/analytics-core";
package/dist/index.d.ts CHANGED
@@ -8,6 +8,6 @@ export * from "./useSpeedAnalytics";
8
8
  export * from "./useEngagementTracking";
9
9
  export * from "./useScrollVisibility";
10
10
  export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
11
- export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
11
+ export { SessionRecorder, SESSION_RECORDER_ENDPOINT, type SessionRecorderConfig, type SessionRecorderProps, type SessionRecordingSampling, } from "./SessionRecorder";
12
12
  export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
13
13
  //# sourceMappingURL=index.d.ts.map
@@ -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;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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,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,EACL,eAAe,EACf,yBAAyB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,GAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC"}
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  "use client";
2
4
  export * from "./types";
3
5
  export * from "./Provider";
@@ -9,5 +11,5 @@ export * from "./useSpeedAnalytics";
9
11
  export * from "./useEngagementTracking";
10
12
  export * from "./useScrollVisibility";
11
13
  export { EngagementTracker } from "./EngagementTracker";
12
- export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
14
+ export { SessionRecorder, SESSION_RECORDER_ENDPOINT, } from "./SessionRecorder";
13
15
  export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";