@temps-sdk/react-analytics 0.0.1-beta.8 → 0.0.2

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.
@@ -0,0 +1,34 @@
1
+ import { type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
2
+ export interface UseEngagementTrackingOptions extends Omit<EngagementTrackerOptions, "basePath" | "domain"> {
3
+ /** Whether to enable engagement tracking. Defaults to true. */
4
+ enabled?: boolean;
5
+ /** Callback when engagement data is updated via heartbeat */
6
+ onEngagementUpdate?: (data: EngagementData) => void;
7
+ /** Callback when page leave is triggered */
8
+ onPageLeave?: (data: EngagementData) => void;
9
+ }
10
+ /**
11
+ * Hook to manually control engagement tracking for specific components or pages.
12
+ * This is useful when you want fine-grained control over engagement tracking
13
+ * or need to track engagement for specific sections of your app.
14
+ *
15
+ * @example
16
+ * ```tsx
17
+ * function ArticlePage() {
18
+ * const { engagementData } = useEngagementTracking({
19
+ * heartbeatInterval: 15000, // Send heartbeat every 15 seconds
20
+ * engagementThreshold: 5000, // Consider engaged after 5 seconds
21
+ * onEngagementUpdate: (data) => {
22
+ * console.log('Engagement updated:', data);
23
+ * }
24
+ * });
25
+ *
26
+ * return <article>...</article>;
27
+ * }
28
+ * ```
29
+ */
30
+ export declare function useEngagementTracking(options?: UseEngagementTrackingOptions): {
31
+ engagementData: EngagementData;
32
+ isTracking: boolean;
33
+ };
34
+ //# sourceMappingURL=useEngagementTracking.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEngagementTracking.d.ts","sourceRoot":"","sources":["../src/useEngagementTracking.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqB,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5G,MAAM,WAAW,4BAA6B,SAAQ,IAAI,CAAC,wBAAwB,EAAE,UAAU,GAAG,QAAQ,CAAC;IACzG,+DAA+D;IAC/D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,6DAA6D;IAC7D,kBAAkB,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACpD,4CAA4C;IAC5C,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,GAAE,4BAAiC;;;EAkD/E"}
@@ -0,0 +1,65 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ import { EngagementTracker } from "./EngagementTracker";
4
+ import { useTempsAnalytics } from "./Provider";
5
+ /**
6
+ * Hook to manually control engagement tracking for specific components or pages.
7
+ * This is useful when you want fine-grained control over engagement tracking
8
+ * or need to track engagement for specific sections of your app.
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * function ArticlePage() {
13
+ * const { engagementData } = useEngagementTracking({
14
+ * heartbeatInterval: 15000, // Send heartbeat every 15 seconds
15
+ * engagementThreshold: 5000, // Consider engaged after 5 seconds
16
+ * onEngagementUpdate: (data) => {
17
+ * console.log('Engagement updated:', data);
18
+ * }
19
+ * });
20
+ *
21
+ * return <article>...</article>;
22
+ * }
23
+ * ```
24
+ */
25
+ export function useEngagementTracking(options = {}) {
26
+ const analytics = useTempsAnalytics();
27
+ const trackerRef = useRef(null);
28
+ const engagementDataRef = useRef({
29
+ engagement_time_seconds: 0,
30
+ total_time_seconds: 0,
31
+ heartbeat_count: 0,
32
+ is_engaged: false,
33
+ is_visible: true,
34
+ time_since_last_activity: 0,
35
+ });
36
+ const { enabled = true, onEngagementUpdate, onPageLeave, ...trackerOptions } = options;
37
+ useEffect(() => {
38
+ if (!enabled || !analytics.enabled) {
39
+ return;
40
+ }
41
+ // Create tracker instance
42
+ trackerRef.current = new EngagementTracker({
43
+ ...trackerOptions,
44
+ onHeartbeat: (data) => {
45
+ engagementDataRef.current = data;
46
+ onEngagementUpdate?.(data);
47
+ },
48
+ onPageLeave: (data) => {
49
+ engagementDataRef.current = data;
50
+ onPageLeave?.(data);
51
+ },
52
+ });
53
+ // Cleanup on unmount
54
+ return () => {
55
+ if (trackerRef.current) {
56
+ trackerRef.current.destroy();
57
+ trackerRef.current = null;
58
+ }
59
+ };
60
+ }, [enabled, analytics.enabled]);
61
+ return {
62
+ engagementData: engagementDataRef.current,
63
+ isTracking: Boolean(trackerRef.current),
64
+ };
65
+ }
@@ -0,0 +1,13 @@
1
+ import type { JsonValue } from "./types";
2
+ export interface UsePageLeaveOptions {
3
+ /** Custom event name. Defaults to "page_leave" */
4
+ eventName?: string;
5
+ /** Additional data to send with the page leave event */
6
+ eventData?: Record<string, JsonValue>;
7
+ /** Whether to enable page leave tracking. Defaults to true */
8
+ enabled?: boolean;
9
+ }
10
+ export declare function usePageLeave(options?: UsePageLeaveOptions): {
11
+ triggerPageLeave: () => Promise<void> | undefined;
12
+ };
13
+ //# sourceMappingURL=usePageLeave.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePageLeave.d.ts","sourceRoot":"","sources":["../src/usePageLeave.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,MAAM,WAAW,mBAAmB;IAClC,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACtC,8DAA8D;IAC9D,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB;;EA2E7D"}
@@ -0,0 +1,66 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ import { useTempsAnalytics } from "./Provider";
4
+ import { sendAnalyticsReliable } from "./utils";
5
+ import { DEFAULT_BASE_PATH } from "./constants";
6
+ export function usePageLeave(options = {}) {
7
+ const { eventName = "page_leave", eventData = {}, enabled = true } = options;
8
+ const { enabled: analyticsEnabled, trackEvent } = useTempsAnalytics();
9
+ const hasTrackedRef = useRef(false);
10
+ const startTimeRef = useRef();
11
+ useEffect(() => {
12
+ startTimeRef.current = Date.now();
13
+ hasTrackedRef.current = false;
14
+ }, []);
15
+ useEffect(() => {
16
+ if (!enabled || !analyticsEnabled)
17
+ return;
18
+ const trackPageLeave = () => {
19
+ if (hasTrackedRef.current)
20
+ return;
21
+ hasTrackedRef.current = true;
22
+ const timeOnPage = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
23
+ const finalEventData = {
24
+ ...eventData,
25
+ time_on_page_ms: timeOnPage,
26
+ timestamp: new Date().toISOString(),
27
+ url: window.location.href,
28
+ referrer: document.referrer,
29
+ };
30
+ // Use reliable sending method that tries sendBeacon first
31
+ sendAnalyticsReliable("event", {
32
+ event_name: eventName,
33
+ request_query: window.location.search,
34
+ request_path: window.location.pathname,
35
+ domain: window.location.hostname,
36
+ event_data: finalEventData,
37
+ }, DEFAULT_BASE_PATH);
38
+ };
39
+ // Use pagehide as primary (most reliable), with beforeunload as fallback
40
+ const handlePageLeave = () => trackPageLeave();
41
+ // pagehide is the most reliable for modern browsers
42
+ window.addEventListener("pagehide", handlePageLeave);
43
+ // beforeunload as fallback for older browsers
44
+ window.addEventListener("beforeunload", handlePageLeave);
45
+ return () => {
46
+ window.removeEventListener("pagehide", handlePageLeave);
47
+ window.removeEventListener("beforeunload", handlePageLeave);
48
+ };
49
+ }, [enabled, analyticsEnabled, eventName, eventData]);
50
+ // Manual trigger function
51
+ const triggerPageLeave = () => {
52
+ if (!enabled || !analyticsEnabled || hasTrackedRef.current)
53
+ return;
54
+ hasTrackedRef.current = true;
55
+ const timeOnPage = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
56
+ return trackEvent(eventName, {
57
+ ...eventData,
58
+ time_on_page_ms: timeOnPage,
59
+ timestamp: new Date().toISOString(),
60
+ url: window.location.href,
61
+ referrer: document.referrer,
62
+ manual_trigger: true,
63
+ });
64
+ };
65
+ return { triggerPageLeave };
66
+ }
@@ -0,0 +1,58 @@
1
+ import type { JsonValue } from "./types";
2
+ export interface UseScrollVisibilityOptions {
3
+ /**
4
+ * Event name to track when component becomes visible.
5
+ * @default "component_visible"
6
+ */
7
+ eventName?: string;
8
+ /**
9
+ * Additional data to send with the event.
10
+ */
11
+ eventData?: Record<string, JsonValue>;
12
+ /**
13
+ * Percentage of the element that must be visible (0.0 to 1.0).
14
+ * @default 0.5
15
+ */
16
+ threshold?: number;
17
+ /**
18
+ * Root element for intersection observer (null = viewport).
19
+ * @default null
20
+ */
21
+ root?: Element | null;
22
+ /**
23
+ * Margin around root element.
24
+ * @default "0px"
25
+ */
26
+ rootMargin?: string;
27
+ /**
28
+ * Whether to track only once (true) or every time it becomes visible (false).
29
+ * @default true
30
+ */
31
+ once?: boolean;
32
+ /**
33
+ * Whether tracking is enabled.
34
+ * @default true
35
+ */
36
+ enabled?: boolean;
37
+ }
38
+ /**
39
+ * Hook that tracks when a component scrolls into view using Intersection Observer.
40
+ *
41
+ * @example
42
+ * ```tsx
43
+ * function MyComponent() {
44
+ * const ref = useScrollVisibility({
45
+ * eventName: "hero_section_viewed",
46
+ * eventData: { section: "hero" },
47
+ * threshold: 0.75
48
+ * });
49
+ *
50
+ * return <div ref={ref}>Hero Section</div>;
51
+ * }
52
+ * ```
53
+ *
54
+ * @param options - Configuration options
55
+ * @returns A ref callback to attach to the element you want to track
56
+ */
57
+ export declare function useScrollVisibility(options?: UseScrollVisibilityOptions): (node: HTMLElement | null) => void;
58
+ //# sourceMappingURL=useScrollVisibility.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useScrollVisibility.d.ts","sourceRoot":"","sources":["../src/useScrollVisibility.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,MAAM,WAAW,0BAA0B;IACzC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IAEtC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAEtB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IAEf;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,0BAA+B,UAyBjE,WAAW,GAAG,IAAI,UAwC5B"}
@@ -0,0 +1,65 @@
1
+ "use client";
2
+ import { useCallback, useEffect, useRef } from "react";
3
+ import { useTempsAnalytics } from "./Provider";
4
+ /**
5
+ * Hook that tracks when a component scrolls into view using Intersection Observer.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * function MyComponent() {
10
+ * const ref = useScrollVisibility({
11
+ * eventName: "hero_section_viewed",
12
+ * eventData: { section: "hero" },
13
+ * threshold: 0.75
14
+ * });
15
+ *
16
+ * return <div ref={ref}>Hero Section</div>;
17
+ * }
18
+ * ```
19
+ *
20
+ * @param options - Configuration options
21
+ * @returns A ref callback to attach to the element you want to track
22
+ */
23
+ export function useScrollVisibility(options = {}) {
24
+ const { eventName = "component_visible", eventData, threshold = 0.5, root = null, rootMargin = "0px", once = true, enabled = true, } = options;
25
+ const { trackEvent } = useTempsAnalytics();
26
+ const hasTrackedRef = useRef(false);
27
+ const observerRef = useRef(null);
28
+ // Cleanup function
29
+ const cleanup = useCallback(() => {
30
+ if (observerRef.current) {
31
+ observerRef.current.disconnect();
32
+ observerRef.current = null;
33
+ }
34
+ }, []);
35
+ // Callback ref that sets up the observer when element is attached
36
+ const ref = useCallback((node) => {
37
+ // Clean up previous observer
38
+ cleanup();
39
+ if (!enabled || !node) {
40
+ return;
41
+ }
42
+ // Reset tracking state if once is false
43
+ if (!once) {
44
+ hasTrackedRef.current = false;
45
+ }
46
+ observerRef.current = new IntersectionObserver((entries) => {
47
+ entries.forEach((entry) => {
48
+ if (entry.isIntersecting && (!once || !hasTrackedRef.current)) {
49
+ trackEvent(eventName, eventData);
50
+ hasTrackedRef.current = true;
51
+ }
52
+ });
53
+ }, {
54
+ root,
55
+ rootMargin,
56
+ threshold,
57
+ });
58
+ observerRef.current.observe(node);
59
+ }, [eventName, eventData, threshold, root, rootMargin, once, enabled, trackEvent, cleanup]);
60
+ // Cleanup on unmount
61
+ useEffect(() => {
62
+ return cleanup;
63
+ }, [cleanup]);
64
+ return ref;
65
+ }
@@ -0,0 +1,23 @@
1
+ import type React from "react";
2
+ interface SessionRecordingContextValue {
3
+ isRecordingEnabled: boolean;
4
+ enableRecording: () => void;
5
+ disableRecording: () => void;
6
+ toggleRecording: () => void;
7
+ sessionId: string | null;
8
+ }
9
+ interface SessionRecordingProviderProps {
10
+ children: React.ReactNode;
11
+ defaultEnabled?: boolean;
12
+ persistPreference?: boolean;
13
+ }
14
+ export declare function SessionRecordingProvider({ children, defaultEnabled, persistPreference }: SessionRecordingProviderProps): import("react/jsx-runtime").JSX.Element;
15
+ export declare function useSessionRecording(): SessionRecordingContextValue;
16
+ export declare function useSessionRecordingControl(defaultEnabled?: boolean): {
17
+ isEnabled: boolean;
18
+ enable: () => void;
19
+ disable: () => void;
20
+ toggle: () => void;
21
+ };
22
+ export {};
23
+ //# sourceMappingURL=useSessionRecording.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSessionRecording.d.ts","sourceRoot":"","sources":["../src/useSessionRecording.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,UAAU,4BAA4B;IACpC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,gBAAgB,EAAE,MAAM,IAAI,CAAC;IAC7B,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAID,UAAU,6BAA6B;IACrC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,wBAAgB,wBAAwB,CAAC,EACvC,QAAQ,EACR,cAAsB,EACtB,iBAAwB,EACzB,EAAE,6BAA6B,2CA8D/B;AAED,wBAAgB,mBAAmB,IAAI,4BAA4B,CAMlE;AAGD,wBAAgB,0BAA0B,CAAC,cAAc,UAAQ;;;;;EAyChE"}
@@ -0,0 +1,99 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useState, useEffect, useCallback, createContext, useContext, useMemo } from "react";
4
+ const SessionRecordingContext = createContext(undefined);
5
+ export function SessionRecordingProvider({ children, defaultEnabled = false, persistPreference = true }) {
6
+ const [isRecordingEnabled, setIsRecordingEnabled] = useState(() => {
7
+ if (!persistPreference)
8
+ return defaultEnabled;
9
+ if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
10
+ const stored = localStorage.getItem("temps_session_recording_enabled");
11
+ if (stored !== null) {
12
+ return stored === "true";
13
+ }
14
+ }
15
+ return defaultEnabled;
16
+ });
17
+ const [sessionId, setSessionId] = useState(null);
18
+ useEffect(() => {
19
+ if (typeof localStorage !== "undefined") {
20
+ const storedSessionId = localStorage.getItem("currentRecordingSessionId");
21
+ setSessionId(storedSessionId);
22
+ }
23
+ }, [isRecordingEnabled]);
24
+ const enableRecording = useCallback(() => {
25
+ setIsRecordingEnabled(true);
26
+ if (persistPreference && typeof localStorage !== "undefined") {
27
+ localStorage.setItem("temps_session_recording_enabled", "true");
28
+ }
29
+ }, [persistPreference]);
30
+ const disableRecording = useCallback(() => {
31
+ setIsRecordingEnabled(false);
32
+ if (persistPreference && typeof localStorage !== "undefined") {
33
+ localStorage.setItem("temps_session_recording_enabled", "false");
34
+ }
35
+ }, [persistPreference]);
36
+ const toggleRecording = useCallback(() => {
37
+ setIsRecordingEnabled(prev => {
38
+ const newValue = !prev;
39
+ if (persistPreference && typeof localStorage !== "undefined") {
40
+ localStorage.setItem("temps_session_recording_enabled", String(newValue));
41
+ }
42
+ return newValue;
43
+ });
44
+ }, [persistPreference]);
45
+ const value = useMemo(() => ({
46
+ isRecordingEnabled,
47
+ enableRecording,
48
+ disableRecording,
49
+ toggleRecording,
50
+ sessionId,
51
+ }), [isRecordingEnabled, enableRecording, disableRecording, toggleRecording, sessionId]);
52
+ return (_jsx(SessionRecordingContext.Provider, { value: value, children: children }));
53
+ }
54
+ export function useSessionRecording() {
55
+ const context = useContext(SessionRecordingContext);
56
+ if (!context) {
57
+ throw new Error("useSessionRecording must be used within a SessionRecordingProvider");
58
+ }
59
+ return context;
60
+ }
61
+ // Standalone hook for controlling session recording without provider
62
+ export function useSessionRecordingControl(defaultEnabled = false) {
63
+ const [isEnabled, setIsEnabled] = useState(() => {
64
+ if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
65
+ const stored = localStorage.getItem("temps_session_recording_enabled");
66
+ if (stored !== null) {
67
+ return stored === "true";
68
+ }
69
+ }
70
+ return defaultEnabled;
71
+ });
72
+ const enable = useCallback(() => {
73
+ setIsEnabled(true);
74
+ if (typeof localStorage !== "undefined") {
75
+ localStorage.setItem("temps_session_recording_enabled", "true");
76
+ }
77
+ }, []);
78
+ const disable = useCallback(() => {
79
+ setIsEnabled(false);
80
+ if (typeof localStorage !== "undefined") {
81
+ localStorage.setItem("temps_session_recording_enabled", "false");
82
+ }
83
+ }, []);
84
+ const toggle = useCallback(() => {
85
+ setIsEnabled(prev => {
86
+ const newValue = !prev;
87
+ if (typeof localStorage !== "undefined") {
88
+ localStorage.setItem("temps_session_recording_enabled", String(newValue));
89
+ }
90
+ return newValue;
91
+ });
92
+ }, []);
93
+ return {
94
+ isEnabled,
95
+ enable,
96
+ disable,
97
+ toggle,
98
+ };
99
+ }
@@ -0,0 +1,8 @@
1
+ export interface UseSpeedAnalyticsOptions {
2
+ /** Base endpoint path. Defaults to `/_temps`. */
3
+ basePath?: string;
4
+ /** Set to true to disable speed analytics. Defaults to false. */
5
+ disabled?: boolean;
6
+ }
7
+ export declare function useSpeedAnalytics(options?: UseSpeedAnalyticsOptions): void;
8
+ //# sourceMappingURL=useSpeedAnalytics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSpeedAnalytics.d.ts","sourceRoot":"","sources":["../src/useSpeedAnalytics.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,wBAAwB;IACvC,iDAAiD;IACjD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,QAgEvE"}
@@ -0,0 +1,60 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { onCLS, onFID, onLCP, onTTFB, onFCP, onINP } from "web-vitals";
4
+ import { sendAnalytics } from "./utils";
5
+ export function useSpeedAnalytics(options = {}) {
6
+ const { basePath = "/_temps", disabled = false } = options;
7
+ useEffect(() => {
8
+ if (disabled || typeof window === "undefined")
9
+ return;
10
+ const initialMetrics = {};
11
+ const lateMetrics = {};
12
+ const sendInitialMetrics = () => {
13
+ if (Object.keys(initialMetrics).length === 4) {
14
+ const metricsPayload = {
15
+ ttfb: initialMetrics.TTFB?.value ?? null,
16
+ lcp: initialMetrics.LCP?.value ?? null,
17
+ fid: initialMetrics.FID?.value ?? null,
18
+ fcp: initialMetrics.FCP?.value ?? null,
19
+ path: window.location.pathname,
20
+ query: window.location.search,
21
+ };
22
+ sendAnalytics("speed", metricsPayload, "POST", basePath);
23
+ }
24
+ };
25
+ const sendLateMetric = (metricName, value) => {
26
+ const payload = {
27
+ [metricName.toLowerCase()]: value,
28
+ path: window.location.pathname,
29
+ query: window.location.search,
30
+ };
31
+ sendAnalytics("speed", payload, "POST", basePath);
32
+ };
33
+ // Track metrics that can be gathered quickly
34
+ onTTFB((metric) => {
35
+ initialMetrics.TTFB = { value: metric.value, rating: metric.rating };
36
+ sendInitialMetrics();
37
+ });
38
+ onLCP((metric) => {
39
+ initialMetrics.LCP = { value: metric.value, rating: metric.rating };
40
+ sendInitialMetrics();
41
+ });
42
+ onFID((metric) => {
43
+ initialMetrics.FID = { value: metric.value, rating: metric.rating };
44
+ sendInitialMetrics();
45
+ });
46
+ onFCP((metric) => {
47
+ initialMetrics.FCP = { value: metric.value, rating: metric.rating };
48
+ sendInitialMetrics();
49
+ });
50
+ // Track metrics that take longer to stabilize
51
+ onCLS((metric) => {
52
+ lateMetrics.CLS = { value: metric.value, rating: metric.rating };
53
+ sendLateMetric("cls", metric.value);
54
+ });
55
+ onINP((metric) => {
56
+ lateMetrics.INP = { value: metric.value, rating: metric.rating };
57
+ sendLateMetric("inp", metric.value);
58
+ });
59
+ }, [basePath, disabled]);
60
+ }
package/dist/utils.d.ts CHANGED
@@ -2,5 +2,6 @@ import type { JsonValue } from "./types";
2
2
  export declare function getRequestId(): string | undefined;
3
3
  export declare function isLocalhostLike(): boolean;
4
4
  export declare function isTestEnvironment(): boolean;
5
- export declare function sendAnalytics(endpoint: string, data: Record<string, JsonValue>, method?: "POST" | "PUT" | "PATCH", basePath?: string): Promise<void>;
5
+ export declare function sendAnalytics(endpoint: string, data: Record<string, JsonValue>, method: "POST" | "PUT" | "PATCH" | undefined, basePath: string): Promise<void>;
6
+ export declare function sendAnalyticsReliable(endpoint: string, data: Record<string, JsonValue>, basePath: string): boolean;
6
7
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,wBAAgB,YAAY,IAAI,MAAM,GAAG,SAAS,CAcjD;AAED,wBAAgB,eAAe,IAAI,OAAO,CASzC;AAED,wBAAgB,iBAAiB,IAAI,OAAO,CAY3C;AAED,wBAAsB,aAAa,CACjC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAC/B,MAAM,GAAE,MAAM,GAAG,KAAK,GAAG,OAAgB,EACzC,QAAQ,SAAgB,GACvB,OAAO,CAAC,IAAI,CAAC,CAoBf"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,wBAAgB,YAAY,IAAI,MAAM,GAAG,SAAS,CAcjD;AAED,wBAAgB,eAAe,IAAI,OAAO,CASzC;AAED,wBAAgB,iBAAiB,IAAI,OAAO,CAY3C;AAED,wBAAsB,aAAa,CACjC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAC/B,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,OAAO,YAAS,EACzC,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAC/B,QAAQ,EAAE,MAAM,GACf,OAAO,CAqCT"}
package/dist/utils.js CHANGED
@@ -41,7 +41,7 @@ export function isTestEnvironment() {
41
41
  const allowTemps = Boolean(window.__temps);
42
42
  return (isPhantom || isNightmare || isWebdriver || isCypress) && !allowTemps;
43
43
  }
44
- export async function sendAnalytics(endpoint, data, method = "POST", basePath = "/api/_temps") {
44
+ export async function sendAnalytics(endpoint, data, method = "POST", basePath) {
45
45
  try {
46
46
  const enrichedData = {
47
47
  ...data,
@@ -61,3 +61,37 @@ export async function sendAnalytics(endpoint, data, method = "POST", basePath =
61
61
  console.error("Failed to send analytics:", error);
62
62
  }
63
63
  }
64
+ export function sendAnalyticsReliable(endpoint, data, basePath) {
65
+ try {
66
+ const enrichedData = {
67
+ ...data,
68
+ request_id: getRequestId(),
69
+ session_id: typeof localStorage !== "undefined"
70
+ ? localStorage.getItem("session_id") || undefined
71
+ : undefined,
72
+ };
73
+ const url = `${basePath}/${endpoint}`;
74
+ const payload = JSON.stringify(enrichedData);
75
+ // Try sendBeacon first (most reliable for page unload)
76
+ if (navigator.sendBeacon && typeof navigator.sendBeacon === "function") {
77
+ const blob = new Blob([payload], { type: "application/json" });
78
+ return navigator.sendBeacon(url, blob);
79
+ }
80
+ // Fallback to synchronous fetch with keepalive
81
+ fetch(url, {
82
+ method: "POST",
83
+ headers: { "Content-Type": "application/json" },
84
+ body: payload,
85
+ keepalive: true,
86
+ }).catch((error) => {
87
+ // eslint-disable-next-line no-console
88
+ console.error("Failed to send analytics (reliable):", error);
89
+ });
90
+ return true;
91
+ }
92
+ catch (error) {
93
+ // eslint-disable-next-line no-console
94
+ console.error("Failed to send analytics (reliable):", error);
95
+ return false;
96
+ }
97
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temps-sdk/react-analytics",
3
- "version": "0.0.1-beta.8",
3
+ "version": "0.0.2",
4
4
  "private": false,
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -18,24 +18,46 @@
18
18
  "build:types": "tsc -p tsconfig.types.json",
19
19
  "build": "bun run build:js && bun run build:types",
20
20
  "clean": "rm -rf dist",
21
- "prepublishOnly": "bun run clean && bun run build"
21
+ "prepublishOnly": "bun run clean && bun run build",
22
+ "test": "vitest",
23
+ "test:coverage": "vitest run --coverage",
24
+ "lint": "eslint src --ext .ts,.tsx",
25
+ "lint:fix": "eslint src --ext .ts,.tsx --fix"
22
26
  },
23
27
  "publishConfig": {
24
28
  "access": "public"
25
29
  },
26
30
  "peerDependencies": {
27
- "react": "^18.0.0 || ^19.0.0",
28
- "react-dom": "^18.0.0 || ^19.0.0"
31
+ "react": "^18.0.0 || ^19.0.0-rc || ^19.0.0",
32
+ "react-dom": "^18.0.0 || ^19.0.0-rc || ^19.0.0"
29
33
  },
30
34
  "peerDependenciesMeta": {
31
35
  "react-dom": {
32
36
  "optional": true
33
37
  }
34
38
  },
39
+ "dependencies": {
40
+ "@rrweb/packer": "^2.0.0-alpha.17",
41
+ "rrweb": "^2.0.0-alpha.17",
42
+ "web-vitals": "^4.2.4"
43
+ },
35
44
  "devDependencies": {
45
+ "@eslint/js": "^9.37.0",
46
+ "@testing-library/react": "^14.2.1",
47
+ "@testing-library/react-hooks": "^8.0.1",
36
48
  "@types/react": "^18.2.56",
37
49
  "@types/react-dom": "^18.2.19",
38
- "typescript": "^5.5.4"
50
+ "@typescript-eslint/eslint-plugin": "^8.46.1",
51
+ "@typescript-eslint/parser": "^8.46.1",
52
+ "@vitest/coverage-v8": "^1.3.1",
53
+ "eslint": "^9.37.0",
54
+ "eslint-plugin-react": "^7.37.5",
55
+ "eslint-plugin-react-hooks": "^7.0.0",
56
+ "jsdom": "^24.0.0",
57
+ "react": "^18.2.0",
58
+ "react-dom": "^18.2.0",
59
+ "typescript": "^5.5.4",
60
+ "vitest": "^1.3.1"
39
61
  },
40
62
  "sideEffects": false
41
63
  }