@xsolla/metrika
Version:
A lightweight integration library for Xsolla Metrics (XMTS) that simplifies user tracking and analytics setup.
310 lines (307 loc) • 11.8 kB
TypeScript
type Prettify<T> = T extends object ? {
[Key in keyof T]: Prettify<T[Key]>;
} : T;
type RetryOptions = {
retries?: number;
retryDelay?: number;
};
/**
* Represents UTM (Urchin Tracking Module) parameters commonly used for tracking marketing campaigns.
*
* @property utm_source - Identifies the source of the traffic (e.g., 'google', 'newsletter'). Can be null if not specified.
* @property utm_medium - Specifies the marketing medium (e.g., 'cpc', 'email'). Can be null if not specified.
* @property utm_campaign - Names the specific campaign (e.g., 'spring_sale'). Can be null if not specified.
* @property utm_content - Differentiates similar content or links within the same ad (e.g., 'banner1'). Can be null if not specified.
* @property utm_term - Identifies paid search keywords (e.g., 'running+shoes'). Can be null if not specified.
*/
interface UtmParams {
utm_source: string | null;
utm_medium: string | null;
utm_campaign: string | null;
utm_content: string | null;
utm_term: string | null;
}
/**
* Represents Openstat parameters commonly used for tracking marketing campaigns in the Russian internet segment.
*
* @property openstat_service - Identifies the advertising service or platform (e.g., 'yandex', 'mail'). Can be null if not specified.
* @property openstat_campaign - Names the specific campaign (e.g., 'summer_promo'). Can be null if not specified.
* @property openstat_ad - Identifies the specific ad or banner (e.g., 'banner_123'). Can be null if not specified.
* @property openstat_source - Specifies the source of the traffic (e.g., 'search', 'email'). Can be null if not specified.
*/
interface OpenstatParams {
openstat_service: string | null;
openstat_campaign: string | null;
openstat_ad: string | null;
openstat_source: string | null;
}
interface XsollaAnalyticsTrackerFlags {
/**
* Track page load (page view event)
*/
hit?: boolean;
/**
* Track external links (outside siteDomains)
*/
extLink?: boolean;
/**
* Track clicks on elements with data-analytics="true"
*/
click?: boolean;
/**
* Track scroll depth (10%, 50%, 90%), does not send events if page height is less than 125% of viewport height
*/
scroll?: boolean;
/**
* Track transitions to allowed domains (from siteDomains)
*/
crossDomainTracking?: boolean;
/**
* Send page load metrics (LCP)
*/
sendLoadMetrics?: boolean;
/**
* Track navigation events (page transitions)
*/
navigation?: boolean;
}
interface XsollaAnalyticsParams extends XsollaAnalyticsTrackerFlags {
/**
* Counter ID (required)
*/
id: string | number;
/**
* User IP (for override, optional)
*/
ip?: string;
/**
* List of site domains to track (internal domains).
* For example, ["example.com", "sub.example.com"].
* If not specified, the current domain will be used.
*/
siteDomains?: string[];
/**
* Base analytics server URL (e.g., "https://analytics.example.com/")
*/
server?: string;
/**
* External ID (optional)
*/
externalId?: string | number;
/**
* Merchant ID (optional)
*/
merchantId?: string | number;
/**
* Additional parameters (optional)
*/
extraValues?: Record<string, unknown>;
/**
* A/B test parameters (optional)
*/
abParams?: Record<string, unknown>;
/**
* Alternative endpoint for page load events (page hit)
*/
hitEndpoint?: string;
/**
* Use beacon API for sending data (default: true)
*/
useBeacon?: boolean;
/**
* Options for retrying failed requests
* @default { retries: 2, retryDelay: 500 }
*/
retryOptions?: RetryOptions;
}
interface AnalyticsEvent {
/** Event type, required */
type: number | string;
/** Optional "raw" data part */
data?: Record<string, unknown>;
/** Any other fields are also allowed as key–value pairs */
[key: string]: unknown;
}
/**
* XsollaAnalytics is a singleton class for collecting and sending analytics events
* to the Xsolla analytics backend. It supports a variety of event types, including
* page hits, external link clicks, element clicks, form submissions, custom events,
* and performance metrics such as Page Load Time (PLT) and Largest Contentful Paint (LCP).
*
* The class manages internal configuration, handles fingerprinting for device identification,
* and registers various trackers for automatic event collection. It provides a flexible API
* for sending both standard and custom analytics events, with support for the Beacon API
* for reliable event delivery.
*
* Usage:
* - Initialize the singleton instance with `XsollaAnalytics.init(params)`.
* - Use instance methods to track events, send custom data, or update session parameters.
* - Call `destroy()` to clean up registered trackers when analytics is no longer needed.
*
* @example
* ```typescript
* const analytics = await XsollaAnalytics.init({ id: 'your-counter-id', ...otherParams });
* analytics.hit(window.location.href);
* analytics.elementClick('button-name');
* analytics.setAbParams({ experiment: 'A' });
* ```
*
* @remarks
* - Requires a valid `id` parameter for initialization.
* - Automatically collects browser, device, and session information for each event.
* - Supports extension via custom trackers and event types.
*
*/
declare class XsollaAnalytics {
/** Singleton instance reference */
private static instance?;
/** Page Load Time (ms), set by PageLoadTracker */
private _plt;
/** Largest Contentful Paint (ms), set by PerformanceTracker */
private _lcp;
get plt(): number;
set plt(value: number);
get lcp(): number;
set lcp(value: number);
/** Internal configuration for analytics */
private readonly config;
/** Sender instance for dispatching payloads */
private readonly sender;
/** Registered tracker instances */
private readonly trackers;
private constructor();
/**
* Initializes the singleton instance and sets up trackers.
* @param params Required analytics parameters (must include id)
* @returns Promise resolving to the XsollaAnalytics instance
* @throws Error if required id parameter is missing
*/
static init(params: Prettify<XsollaAnalyticsParams>): Promise<XsollaAnalytics>;
/**
* Registers trackers based on flags.
*/
private registerTrackers;
/**
* Builds the payload object to send to the analytics endpoint.
*/
private buildPayload;
/**
* Tracks a custom analytics event.
* @internal
* @param params Object containing event parameters:
* - type: Type of the event (e.g., 'hit', 'click', etc.)
* - data: Additional data to send with the event
* - endpoint: Optional custom endpoint for the event
* - useBeacon: Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
sendEvent({ type, data, endpoint, useBeacon, }: {
type: AnalyticsEvent['type'];
data?: AnalyticsEvent['data'];
endpoint?: string;
useBeacon?: boolean;
}): Promise<boolean>;
/**
* Sends a page hit event.
* @param url URL of the page
* @param data Additional data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
hit(url: string, data?: Record<string, unknown>, useBeacon?: boolean): Promise<boolean>;
/**
* Records an external link click.
* @param url URL of the external link
* @param data Additional data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
externalLink(url: string, data?: Record<string, unknown>, useBeacon?: boolean): Promise<boolean>;
/**
* Tracks a named element click on the page.
* @param name Name of the element
* @param data Additional data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
elementClick(name: string, data?: Record<string, unknown>, useBeacon?: boolean): Promise<boolean>;
/**
* Sends form submission data.
* @param name Name of the form
* @param form Form data as an object or FormData instance
* @param data Additional data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
formData(name: string, form: Record<string, unknown> | FormData, data?: Record<string, unknown>, useBeacon?: boolean): Promise<boolean>;
/**
* Sends a custom named event.
* @param name Name of the event
* @param data Additional data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
customEvent(name: string, data?: Record<string, unknown>, useBeacon?: boolean): Promise<boolean>;
/**
* Sends arbitrary data to a custom analytics route.
* The data is automatically supplemented with dfp and xsollauid identifiers.
* @param route Custom route for the analytics server
* @param customData Data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
* @returns Promise that resolves to true if the hit was successfully sent
*/
sendCustomData(endpoint: string, data: Record<string, unknown>, useBeacon?: boolean | undefined): Promise<boolean>;
/**
* Records a Pay Station user session event.
* @param data Data to send
* @param useBeacon Whether to use sendBeacon API (defaults to config)
*/
payStationUserSession(data: Record<string, unknown>, useBeacon?: boolean): Promise<boolean>;
/**
* Sends an event for Largest Contentful Paint (LCP).
*/
eventForLCP(useBeacon?: boolean): Promise<boolean>;
/**
* Updates the A/B testing parameters (abParams) for the current session.
* @param abParams Object containing A/B testing parameters
*/
setAbParams(abParams: Record<string, unknown>): void;
/**
* Updates the extra values (exv) for the current session.
* @param extraValues Object containing additional values to send with events
*/
setExtraValues(extraValues: Record<string, unknown>): void;
/**
* Retrieves the current fingerprint hash.
*
* @returns The fingerprint hash if available, otherwise undefined.
*/
getFingerprintHash(): string | undefined;
/**
* Retrieves the current fingerprint data.
*
* @returns The fingerprint data object if available, otherwise undefined.
*/
getFingerprintData(): Record<string, unknown> | undefined;
/**
* Retrieves the current client ID.
*
* @returns The client ID string.
*/
getClientId(): string;
/**
* Retrieves the current visitor ID.
*
* @returns The visitor ID string.
*/
getVisitorId(): string;
/**
* Destroys the instance and cleans up registered trackers.
* This should be called when analytics is no longer needed to prevent memory leaks.
*/
destroy(): void;
}
declare namespace XsollaAnalytics {
export type { AnalyticsEvent, OpenstatParams, RetryOptions, UtmParams, XsollaAnalyticsParams, XsollaAnalyticsTrackerFlags };
}
export = XsollaAnalytics;