UNPKG

uni-analytics-sdk

Version:

A universal SDK for analytics and logging.

372 lines (366 loc) 10.8 kB
declare global { interface Window { dataLayer: any[]; gtag: (...args: any[]) => void; } } /** * Represents a user's traits for an `identify` call. */ interface UserTraits { name?: string; email?: string; [key: string]: any; } /** * Defines the structure for a generic event that the SDK can process. * This is the universal format that providers will translate. */ interface SDKEvent { type: 'track' | 'identify' | 'captureException' | 'captureMessage'; timestamp: number; eventName?: string; properties?: Record<string, any>; userId?: string; traits?: UserTraits; error?: Error; message?: string; level?: 'info' | 'warning' | 'error' | 'critical'; context?: Record<string, any>; } /** * Configuration options for the UniversalSDK. */ interface SDKConfig { /** * An array of provider instances to be used by the SDK. */ providers: Provider[]; /** * Configuration for each provider, keyed by the provider's name. */ providerConfigs?: { [providerName: string]: ProviderConfig; }; /** * The maximum number of events to hold in the queue before flushing. * @default 20 */ maxQueueSize?: number; /** * The maximum time in milliseconds to wait before flushing the queue. * @default 15000 (15 seconds) */ flushInterval?: number; /** * Enable or disable debug logging for the SDK itself. * @default false */ debug?: boolean; } /** * A generic configuration object for any provider. * Using `[key: string]: any` allows for flexible provider-specific options * with different value types (string, boolean, etc.), fixing the type errors. */ interface ProviderConfig { [key: string]: any; } /** * Defines the contract for any provider. * Providers are responsible for sending data to a specific third-party service. */ interface Provider { /** * A unique identifier for the provider (e.g., 'GoogleAnalytics', 'Sentry'). */ name: string; /** * Called when the SDK is initialized. Use this to set up the provider, * for example, by loading an external script or initializing a client. * @param {Record<string, any>} config - The configuration object for this provider. */ setup(config: Record<string, any>): Promise<void>; /** * Called by the SDK to process a batch of events. * @param {SDKEvent[]} events - An array of events to be processed. */ processEvents(events: SDKEvent[]): Promise<void>; /** * A method to gracefully shut down the provider, ensuring any pending data is sent. */ shutdown?(): Promise<void>; } /** * Defines the contract that all providers must adhere to. */ interface Provider { name: string; setup(config: ProviderConfig): Promise<void>; processEvents(events: SDKEvent[]): Promise<void>; } interface GoogleAnalyticsProviderConfig { /** * Your GA4 Measurement ID (e.g., "G-XXXXXXXXXX"). Required for both browser and server. */ measurementId: string; /** * Your Measurement Protocol API Secret. Required for server-side (Node.js) tracking. */ apiSecret?: string; /** * If true, sends a 'page_view' event automatically when the script loads in the browser. * @default true */ automaticPageViews?: boolean; /** * If true, puts the provider in debug mode. * @default false */ debug?: boolean; region?: 'eu' | string; } /** * Defines the main configuration object for the SDK. */ interface UniversalSDKConfig { providers: Provider[]; providerConfigs?: { [providerName: string]: Record<string, any>; }; queueSize?: number; flushInterval?: number; debug?: boolean; } /** * @fileoverview This file contains the core implementation of the Universal Analytics and Logging SDK. * It defines the main SDK class, provider interfaces, and the logic for event queueing, * batching, and dispatching. */ /** * The main class for the Universal SDK. It orchestrates providers and manages the event lifecycle. */ /** * The core of the Universal SDK. It manages the event queue, provider lifecycle, * and orchestrates the sending of data. */ declare class UniversalSDK { private queue; private providers; private config; private flushInterval; private isInitialized; constructor(config: UniversalSDKConfig); /** * Initializes the SDK and sets up all configured providers. * This must be called before any tracking or identification can occur. */ init(): Promise<void>; /** * Tracks a custom event. * @param eventName The name of the event. * @param properties An object of key-value pairs for additional data. */ track(eventName: string, properties?: Record<string, any>): void; /** * Identifies a user and associates traits with them. * @param userId A unique identifier for the user. * @param traits An object of user properties. */ identify(userId: string, traits?: Record<string, any>): void; /** * Captures a manually thrown error or exception. * @param error The error object. * @param context Additional context for the error. */ captureException(error: Error, context?: Record<string, any>): void; /** * Captures a log message. * @param message The message to log. * @param level The severity level of the message. */ captureMessage(message: string, level?: 'info' | 'warning' | 'error'): void; /** * Adds an event to the processing queue. * @param event The SDKEvent to enqueue. */ private enqueue; /** * Sends all events in the queue to the configured providers. */ private flush; /** * Cleans up resources, like the flush interval. */ shutdown(): void; } /** * @fileoverview This file contains the implementation of the GoogleAnalyticsProvider. * It handles sending analytics and error data to Google Analytics 4 (GA4) from both * client-side (browser) and server-side (Node.js) environments. */ declare class GoogleAnalyticsProvider implements Provider { name: string; private config; private isBrowser; private lastUserId; /** * Sets up the GA4 provider. In the browser, it loads the gtag.js script. * In Node.js, it verifies the necessary configuration. * @param {GoogleAnalyticsProviderConfig} config - The configuration for this provider. */ setup(config: GoogleAnalyticsProviderConfig): Promise<void>; /** * Processes a batch of events and sends them to GA4. * @param {SDKEvent[]} events - An array of events from the SDK core. */ processEvents(events: SDKEvent[]): Promise<void>; private setupBrowser; private processEventsBrowser; private setupNode; private processEventsNode; private sendPayloadForUser; private extractUserProperties; private mapEventToMeasurementProtocol; private generateStableSessionId; private sanitizeAndFormatUserProperties; } /** * @fileoverview This file contains strongly-typed event creators for standard * Google Analytics 4 events, particularly for e-commerce. Using these templates * ensures that the data sent to GA4 via the SDK's `track` method is valid and * conforms to Google's official schema. */ /** * Represents a single item in an e-commerce transaction. */ interface GA4Item { item_id?: string; item_name?: string; affiliation?: string; coupon?: string; discount?: number; index?: number; item_brand?: string; item_category?: string; item_category2?: string; item_category3?: string; item_category4?: string; item_category5?: string; item_list_id?: string; item_list_name?: string; item_variant?: string; location_id?: string; price?: number; quantity?: number; } interface PurchaseParams { transaction_id: string; value: number; currency: string; items: GA4Item[]; affiliation?: string; coupon?: string; shipping?: number; tax?: number; } interface RefundParams { transaction_id: string; value: number; currency: string; items?: GA4Item[]; affiliation?: string; coupon?: string; shipping?: number; tax?: number; } interface AddToCartParams { value: number; currency: string; items: GA4Item[]; } interface BeginCheckoutParams { value: number; currency: string; items: GA4Item[]; coupon?: string; } interface ViewItemParams { value: number; currency: string; items: GA4Item[]; } interface GenerateLeadParams { value: number; currency: string; } interface SignUpParams { method: 'Google' | 'Email' | 'Facebook' | string; } interface LoginParams { method: 'Google' | 'Email' | 'Facebook' | string; } /** * A collection of functions to create standardized GA4 event objects. * These can be passed directly to the `sdk.track()` method. */ declare const ga4: { /** * Creates a valid 'purchase' event payload. */ purchase: (params: PurchaseParams) => { eventName: string; properties: PurchaseParams; }; /** * Creates a valid 'refund' event payload. */ refund: (params: RefundParams) => { eventName: string; properties: RefundParams; }; /** * Creates a valid 'add_to_cart' event payload. */ addToCart: (params: AddToCartParams) => { eventName: string; properties: AddToCartParams; }; /** * Creates a valid 'begin_checkout' event payload. */ beginCheckout: (params: BeginCheckoutParams) => { eventName: string; properties: BeginCheckoutParams; }; /** * Creates a valid 'view_item' event payload. */ viewItem: (params: ViewItemParams) => { eventName: string; properties: ViewItemParams; }; /** * Creates a valid 'generate_lead' event payload. */ generateLead: (params: GenerateLeadParams) => { eventName: string; properties: GenerateLeadParams; }; /** * Creates a valid 'sign_up' event payload. */ signUp: (params: SignUpParams) => { eventName: string; properties: SignUpParams; }; /** * Creates a valid 'login' event payload. */ login: (params: LoginParams) => { eventName: string; properties: LoginParams; }; }; export { GoogleAnalyticsProvider, UniversalSDK, ga4 }; export type { AddToCartParams, BeginCheckoutParams, GA4Item, GenerateLeadParams, GoogleAnalyticsProviderConfig, LoginParams, Provider, ProviderConfig, PurchaseParams, RefundParams, SDKConfig, SDKEvent, SignUpParams, UniversalSDKConfig, UserTraits, ViewItemParams };