@deriv-com/analytics
Version:
Comprehensive analytics package for Deriv applications. Provides unified event tracking, A/B testing, and user analytics through RudderStack, PostHog and GrowthBook integrations with built-in caching and offline support.
177 lines (173 loc) • 6.79 kB
TypeScript
import { PostHogConfig, SessionRecordingOptions } from 'posthog-js';
/**
* Extended SessionRecordingOptions to allow additional custom properties
*/
type TExtendedSessionRecordingOptions = SessionRecordingOptions & {
minimumDurationMilliseconds?: number;
[key: string]: any;
};
/**
* Partial version of PostHog configuration to allow flexible initialization
* All properties from the official PostHogConfig are optional
* Extends session_recording to support additional properties
*/
type TPosthogConfig = Partial<Omit<PostHogConfig, 'session_recording'>> & {
session_recording?: Partial<TExtendedSessionRecordingOptions>;
/**
* Client-side rate limiting for PostHog event capture.
* Not yet reflected in posthog-js TypeScript types but supported at runtime.
* Raise events_burst_limit if legitimate user flows are hitting the limiter.
*/
rate_limiting?: {
events_per_second?: number;
events_burst_limit?: number;
};
};
type TPosthogIdentifyTraits = {
email?: string;
language?: string;
country_of_residence?: string;
[key: string]: any;
};
type TPosthogOptions = {
/**
* PostHog API key
*/
apiKey: string;
/**
* Optional PostHog API host URL
* If not provided, uses the default from utils/urls
*/
api_host?: string;
/**
* PostHog configuration options
* Allows customization of PostHog behavior, session recording, etc.
*/
config?: TPosthogConfig;
};
/**
* PostHog analytics wrapper with singleton pattern.
* Provides optional PostHog integration for event tracking and session recording.
*
* Features:
* - Dynamically loads PostHog SDK on demand
* - Domain allowlisting for security
* - Automatic user identification with client_id enforcement
* - client_id backfill for previously identified users via backfillPersonProperties
* - Custom event tracking with property sanitization
* - Built-in caching and retry mechanisms (handled by posthog-js library)
*
* Note: PostHog handles its own event queuing, caching, and retry logic internally.
* No additional caching is needed at the wrapper level.
*/
declare class Posthog {
has_initialized: boolean;
has_identified: boolean;
private static _instance;
private static _hasLoaded;
private static readonly ILLEGAL_IDS;
private options;
private debug;
private log;
constructor(options: TPosthogOptions, debug?: boolean);
/**
* Get or create the singleton instance of Posthog
* @param options - PostHog configuration options including API key
* @param debug - Enable debug logging
* @returns The Posthog singleton instance
*/
static getPosthogInstance: (options: TPosthogOptions, debug?: boolean) => Posthog;
/**
* Remove stale PostHog cookies that don't belong to the current project key.
* PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys
* have been used in the same browser, old cookies pile up and should be cleaned.
*/
private cleanupStalePosthogCookies;
/**
* Initialize PostHog with configuration
* Configures PostHog instance with provided options
*/
init: () => void;
private static isAnonymousId;
private resetIfStaleId;
/**
* Identify a user with PostHog.
* Skipped if the user is already identified — use backfillPersonProperties to backfill
* client_id for users identified in previous sessions.
*
* @param user_id - The user ID to identify
* @param traits - User properties (language, country_of_residence, etc.)
*/
identifyEvent: (user_id: string, traits?: TPosthogIdentifyTraits) => void;
/**
* Reset PostHog state
* Clears user identification and resets the instance
*/
reset: () => void;
/**
* Ensure client_id is set in PostHog stored person properties.
* Call this when the user ID is available and PostHog is loaded.
* No-op if client_id is already present.
*
* @param params.user_id - The user ID to use as client_id
* @param params.email - The user's email, used to determine is_internal
* @param params.language - The user's language (BCP 47 tag, e.g. "en-GB")
* @param params.country_of_residence - The user's country of residence
*/
backfillPersonProperties: ({ user_id, email, language, country_of_residence, }: {
user_id: string;
email?: string;
language?: string;
country_of_residence?: string;
}) => void;
/**
* Capture a custom event with properties
* Properties are pre-flattened and cleaned by analytics.ts before being passed here
*
* @param event_name - The name of the event to track
* @param properties - Event properties including core attributes (already flattened and cleaned)
*/
capture: (event_name: string, properties?: Record<string, any>) => void;
/**
* Check whether a feature flag is enabled for the current user.
*
* @param key - The feature flag key
* @returns true/false, or undefined if PostHog is not ready
*/
isFeatureEnabled: (key: string) => boolean | undefined;
/**
* Get the value of a feature flag.
* Returns a string variant for multivariate flags, true/false for boolean flags,
* or undefined if the flag does not exist or PostHog is not ready.
*
* @param key - The feature flag key
*/
getFeatureFlag: (key: string) => string | boolean | undefined;
/**
* Get the JSON payload associated with a feature flag.
* Payloads allow attaching structured metadata (e.g. config objects) to a flag.
*
* @param key - The feature flag key
*/
getFeatureFlagPayload: (key: string) => string | number | boolean | null | Record<string, unknown> | unknown[] | undefined;
/**
* Get all currently active feature flags and their values.
*
* @returns A map of flag key → value (boolean or string variant)
*/
getAllFlags: () => Record<string, string | boolean>;
/**
* Subscribe to feature flag changes.
* The callback fires immediately with the current flags and again whenever they are reloaded.
*
* @param callback - Receives the list of active flag keys and a map of key → variant
* @returns An unsubscribe function — call it to stop listening
*/
onFeatureFlags: (callback: (flags: string[], variants: Record<string, string | boolean>) => void) => (() => void);
/**
* Force PostHog to reload feature flags from the server.
* Useful after login, logout, or any attribute change that may affect targeting.
*/
reloadFeatureFlags: () => void;
}
export { Posthog as P, type TPosthogOptions as T };