@temps-sdk/react-analytics 0.0.1-beta.2 → 0.0.1-beta.21

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,65 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ import { useTempsAnalytics } from "./Provider";
4
+ import { sendAnalyticsReliable } from "./utils";
5
+ export function usePageLeave(options = {}) {
6
+ const { eventName = "page_leave", eventData = {}, enabled = true } = options;
7
+ const { enabled: analyticsEnabled, trackEvent } = useTempsAnalytics();
8
+ const hasTrackedRef = useRef(false);
9
+ const startTimeRef = useRef();
10
+ useEffect(() => {
11
+ startTimeRef.current = Date.now();
12
+ hasTrackedRef.current = false;
13
+ }, []);
14
+ useEffect(() => {
15
+ if (!enabled || !analyticsEnabled)
16
+ return;
17
+ const trackPageLeave = () => {
18
+ if (hasTrackedRef.current)
19
+ return;
20
+ hasTrackedRef.current = true;
21
+ const timeOnPage = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
22
+ const finalEventData = {
23
+ ...eventData,
24
+ time_on_page_ms: timeOnPage,
25
+ timestamp: new Date().toISOString(),
26
+ url: window.location.href,
27
+ referrer: document.referrer,
28
+ };
29
+ // Use reliable sending method that tries sendBeacon first
30
+ sendAnalyticsReliable("event", {
31
+ event_name: eventName,
32
+ request_query: window.location.search,
33
+ request_path: window.location.pathname,
34
+ domain: window.location.hostname,
35
+ event_data: finalEventData,
36
+ });
37
+ };
38
+ // Use pagehide as primary (most reliable), with beforeunload as fallback
39
+ const handlePageLeave = () => trackPageLeave();
40
+ // pagehide is the most reliable for modern browsers
41
+ window.addEventListener("pagehide", handlePageLeave);
42
+ // beforeunload as fallback for older browsers
43
+ window.addEventListener("beforeunload", handlePageLeave);
44
+ return () => {
45
+ window.removeEventListener("pagehide", handlePageLeave);
46
+ window.removeEventListener("beforeunload", handlePageLeave);
47
+ };
48
+ }, [enabled, analyticsEnabled, eventName, eventData]);
49
+ // Manual trigger function
50
+ const triggerPageLeave = () => {
51
+ if (!enabled || !analyticsEnabled || hasTrackedRef.current)
52
+ return;
53
+ hasTrackedRef.current = true;
54
+ const timeOnPage = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
55
+ return trackEvent(eventName, {
56
+ ...eventData,
57
+ time_on_page_ms: timeOnPage,
58
+ timestamp: new Date().toISOString(),
59
+ url: window.location.href,
60
+ referrer: document.referrer,
61
+ manual_trigger: true,
62
+ });
63
+ };
64
+ return { triggerPageLeave };
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
@@ -3,4 +3,5 @@ export declare function getRequestId(): string | undefined;
3
3
  export declare function isLocalhostLike(): boolean;
4
4
  export declare function isTestEnvironment(): boolean;
5
5
  export declare function sendAnalytics(endpoint: string, data: Record<string, JsonValue>, method?: "POST" | "PUT" | "PATCH", 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":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,wBAAgB,YAAY,IAAI,MAAM,GAAG,SAAS,CAajD;AAED,wBAAgB,eAAe,IAAI,OAAO,CASzC;AAED,wBAAgB,iBAAiB,IAAI,OAAO,CAW3C;AAED,wBAAsB,aAAa,CAClC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAC/B,MAAM,GAAE,MAAM,GAAG,KAAK,GAAG,OAAgB,EACzC,QAAQ,SAAgB,GACtB,OAAO,CAAC,IAAI,CAAC,CAiBf"}
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,SAAY,GACnB,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAC/B,QAAQ,SAAY,GACnB,OAAO,CAqCT"}
package/dist/utils.js CHANGED
@@ -1,4 +1,7 @@
1
+ "use client";
1
2
  export function getRequestId() {
3
+ if (typeof document === "undefined")
4
+ return undefined;
2
5
  const metaElement = document.querySelector('meta[name="temps-metadata"]');
3
6
  if (metaElement) {
4
7
  try {
@@ -25,6 +28,8 @@ export function isLocalhostLike() {
25
28
  }
26
29
  }
27
30
  export function isTestEnvironment() {
31
+ if (typeof window === "undefined")
32
+ return false;
28
33
  // @ts-expect-error - non-standard globals from test frameworks
29
34
  const isPhantom = Boolean(window._phantom);
30
35
  // @ts-expect-error - non-standard globals from test frameworks
@@ -36,12 +41,14 @@ export function isTestEnvironment() {
36
41
  const allowTemps = Boolean(window.__temps);
37
42
  return (isPhantom || isNightmare || isWebdriver || isCypress) && !allowTemps;
38
43
  }
39
- export async function sendAnalytics(endpoint, data, method = "POST", basePath = "/api/_temps") {
44
+ export async function sendAnalytics(endpoint, data, method = "POST", basePath = "/_temps") {
40
45
  try {
41
46
  const enrichedData = {
42
47
  ...data,
43
48
  request_id: getRequestId(),
44
- session_id: (typeof localStorage !== "undefined" && localStorage.getItem("session_id")) || undefined,
49
+ session_id: typeof localStorage !== "undefined"
50
+ ? localStorage.getItem("session_id") || undefined
51
+ : undefined,
45
52
  };
46
53
  await fetch(`${basePath}/${endpoint}`, {
47
54
  method,
@@ -54,3 +61,37 @@ export async function sendAnalytics(endpoint, data, method = "POST", basePath =
54
61
  console.error("Failed to send analytics:", error);
55
62
  }
56
63
  }
64
+ export function sendAnalyticsReliable(endpoint, data, basePath = "/_temps") {
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,8 +1,7 @@
1
1
  {
2
2
  "name": "@temps-sdk/react-analytics",
3
- "version": "0.0.1-beta.2",
3
+ "version": "0.0.1-beta.21",
4
4
  "private": false,
5
- "type": "module",
6
5
  "main": "./dist/index.js",
7
6
  "types": "./dist/index.d.ts",
8
7
  "exports": {
@@ -19,24 +18,38 @@
19
18
  "build:types": "tsc -p tsconfig.types.json",
20
19
  "build": "bun run build:js && bun run build:types",
21
20
  "clean": "rm -rf dist",
22
- "prepublishOnly": "bun run clean && bun run build"
21
+ "prepublishOnly": "bun run clean && bun run build",
22
+ "test": "vitest",
23
+ "test:coverage": "vitest run --coverage"
23
24
  },
24
25
  "publishConfig": {
25
26
  "access": "public"
26
27
  },
27
28
  "peerDependencies": {
28
- "react": "^18.0.0 || ^19.0.0",
29
- "react-dom": "^18.0.0 || ^19.0.0"
29
+ "react": "^18.0.0 || ^19.0.0-rc || ^19.0.0",
30
+ "react-dom": "^18.0.0 || ^19.0.0-rc || ^19.0.0"
30
31
  },
31
32
  "peerDependenciesMeta": {
32
33
  "react-dom": {
33
34
  "optional": true
34
35
  }
35
36
  },
37
+ "dependencies": {
38
+ "@rrweb/packer": "^2.0.0-alpha.17",
39
+ "rrweb": "^2.0.0-alpha.17",
40
+ "web-vitals": "^4.2.4"
41
+ },
36
42
  "devDependencies": {
43
+ "@testing-library/react": "^14.2.1",
44
+ "@testing-library/react-hooks": "^8.0.1",
37
45
  "@types/react": "^18.2.56",
38
46
  "@types/react-dom": "^18.2.19",
39
- "typescript": "^5.5.4"
47
+ "@vitest/coverage-v8": "^1.3.1",
48
+ "jsdom": "^24.0.0",
49
+ "react": "^18.2.0",
50
+ "react-dom": "^18.2.0",
51
+ "typescript": "^5.5.4",
52
+ "vitest": "^1.3.1"
40
53
  },
41
54
  "sideEffects": false
42
55
  }