UNPKG

humanbehavior-js

Version:

SDK for HumanBehavior session and event recording

256 lines (251 loc) 7.84 kB
import React, { ReactNode } from 'react'; interface RedactionOptions { redactedText?: string; excludeSelectors?: string[]; userFields?: string[]; } declare global { interface Window { HumanBehaviorTracker: typeof HumanBehaviorTracker; __humanBehaviorGlobalTracker?: HumanBehaviorTracker; } } declare class HumanBehaviorTracker { private eventIngestionQueue; private sessionId; private userProperties; private isProcessing; private flushInterval; private readonly FLUSH_INTERVAL_MS; private api; private endUserId; private apiKey; private initialized; initializationPromise: Promise<void> | null; private redactionManager; private originalConsole; private consoleTrackingEnabled; navigationTrackingEnabled: boolean; private currentUrl; private previousUrl; private originalPushState; private originalReplaceState; private navigationListeners; private _connectionBlocked; private recordInstance; private sessionStartTime; private rrwebRecord; private fullSnapshotTimeout; private recordCanvas; /** * Initialize the HumanBehavior tracker * This is the main entry point - call this once per page */ static init(apiKey: string, options?: { ingestionUrl?: string; logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug'; redactFields?: string[]; enableAutomaticTracking?: boolean; suppressConsoleErrors?: boolean; recordCanvas?: boolean; automaticTrackingOptions?: { trackButtons?: boolean; trackLinks?: boolean; trackForms?: boolean; includeText?: boolean; includeClasses?: boolean; }; }): HumanBehaviorTracker; constructor(apiKey: string | undefined, ingestionUrl?: string); private init; private ensureInitialized; /** * Setup navigation event tracking for SPA navigation */ private setupNavigationTracking; /** * Track navigation events and send custom events */ trackNavigationEvent(type: string, fromUrl: string, toUrl: string): Promise<void>; trackPageView(url?: string): Promise<void>; customEvent(eventName: string, properties?: Record<string, any>): Promise<void>; /** * Setup automatic tracking for buttons, links, and forms */ private setupAutomaticTracking; /** * Setup automatic button tracking */ private setupAutomaticButtonTracking; /** * Setup automatic link tracking */ private setupAutomaticLinkTracking; /** * Setup automatic form tracking */ private setupAutomaticFormTracking; /** * Cleanup navigation tracking */ private cleanupNavigationTracking; static logToStorage(message: string): void; /** * Configure logging behavior for the SDK * @param config Logger configuration options */ static configureLogging(config: { level?: 'none' | 'error' | 'warn' | 'info' | 'debug'; enableConsole?: boolean; enableStorage?: boolean; }): void; /** * Enable console event tracking */ enableConsoleTracking(): void; /** * Disable console event tracking */ disableConsoleTracking(): void; private trackConsoleEvent; private setupPageUnloadHandler; viewLogs(): void; /** * Add user identification information to the tracker * If userId is not provided, will use userProperties.email as the userId (if present) */ identifyUser({ userProperties }: { userProperties: Record<string, any>; }): Promise<string>; /** * Get current user attributes */ getUserAttributes(): Record<string, any>; start(): Promise<void>; /** * Manually trigger a FullSnapshot (for navigation events) * Delays snapshot to avoid capturing mid-animation states */ private takeFullSnapshot; stop(): Promise<void>; /** * Add an event to the ingestion queue * Events are sent directly without processing to avoid corruption */ addEvent(event: any): Promise<void>; /** * Flush events to the ingestion server * Events are sent in chunks to handle large payloads efficiently */ private flush; private setCookie; getCookie(name: string): string | null; /** * Delete a cookie by setting its expiration date to the past * @param name The name of the cookie to delete */ private deleteCookie; /** * Clear user data and reset session when user signs out of the site * This should be called when a user logs out of your application to prevent * data contamination between different users */ logout(): void; /** * Start redaction functionality for sensitive input fields * @param options Optional configuration for redaction behavior */ redact(options?: RedactionOptions): Promise<void>; /** * Set specific fields to be redacted during session recording * Uses rrweb's built-in masking instead of custom redaction processing * @param fields Array of CSS selectors for fields to redact (e.g., ['input[type="password"]', '#email-field']) */ setRedactedFields(fields: string[]): void; private restartWithNewRedaction; /** * Check if redaction is currently active */ isRedactionActive(): boolean; /** * Get the currently selected fields for redaction */ getRedactedFields(): string[]; /** * Get the current session ID */ getSessionId(): string; /** * Get the current URL being tracked */ getCurrentUrl(): string; /** * Get current snapshot frequency info * Uses configured values (5 minutes, 1000 events) */ getSnapshotFrequencyInfo(): { sessionDuration: number; currentInterval: number; currentThreshold: number; phase: string; }; /** * Test if the tracker can reach the ingestion server */ testConnection(): Promise<{ success: boolean; error?: string; }>; /** * Get connection status and recommendations */ getConnectionStatus(): { blocked: boolean; recommendations: string[]; }; /** * Check if the current user is a preexisting user * Returns true if the user has an existing endUserId cookie from a previous session */ isPreexistingUser(): boolean; /** * Get user information including whether they are preexisting */ getUserInfo(): { endUserId: string | null; sessionId: string; isPreexistingUser: boolean; initialized: boolean; }; } interface HumanBehaviorProviderProps { apiKey?: string; client?: HumanBehaviorTracker; children: ReactNode; options?: { ingestionUrl?: string; logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug'; redactFields?: string[]; suppressConsoleErrors?: boolean; recordCanvas?: boolean; }; } declare const HumanBehaviorProvider: ({ apiKey, client, children, options }: HumanBehaviorProviderProps) => React.JSX.Element; declare const useHumanBehavior: () => HumanBehaviorTracker; declare const useRedaction: () => { setRedactedFields: (fields: string[]) => void; isRedactionActive: () => boolean; getRedactedFields: () => string[]; }; declare const useUserTracking: () => { identifyUser: ({ userProperties }: { userProperties: Record<string, any>; }) => Promise<{ success: boolean; error?: undefined; } | { success: boolean; error: unknown; }>; }; export { HumanBehaviorProvider, HumanBehaviorTracker, useHumanBehavior, useRedaction, useUserTracking };