//#region ../../internals/core/types.d.ts /** * Represents a generic payload for any event. */ type EventPayload = Record; /** * Information about a specific platform or environment. */ type PlatformInfo = { /** * The name of the platform/browser/os (e.g., "Chrome", "iOS"). */ name: string; /** * The semantic version or release number. */ version: string; }; /** * Web-specific platform details. */ type WebPlatform = { /** * Identifies the platform type. */ type: "web"; /** * Information about the user's browser. */ browser: PlatformInfo; /** * Information about the hardware device. */ device: PlatformInfo; /** * Information about the operating system. */ os: PlatformInfo; }; /** * Native app-specific platform details. */ type NativePlatform = { /** * Identifies the platform type. */ type: "native"; /** * Information about the hardware device. */ device: PlatformInfo; /** * Information about the operating system. */ os: PlatformInfo; }; /** * Server-side platform details. */ type ServerPlatform = { /** * Identifies the platform type. */ type: "server"; }; /** * The platform from which the event was issued. */ type Platform = WebPlatform | NativePlatform | ServerPlatform; /** * Information about the tracking SDK sending the event. */ type SdkInfo = { /** * The name of the SDK (e.g., "ripple-ts"). */ name: string; /** * The version of the SDK. */ version: string; }; /** * The root Event object shape. * * @template TMetadata Defines the shape of global/app-level metadata. */ type Event> = { /** * The unique name of the event (e.g., "product_viewed"). */ name: string; /** * The event-specific data. */ payload: EventPayload | null; /** * Environment/App-specific data attached to all events (e.g., app version, build number). */ metadata: Partial | null; /** * Platform context. */ platform: Platform | null; /** * SDK context. */ sdk: SdkInfo; /** * UNIX timestamp in milliseconds indicating when the event occurred. */ issuedAt: number; /** * A unique identifier for the anonymous user/device. */ anonymousId: string; /** * A unique UUID for this specific event to prevent deduplication. */ eventId: string; /** * The version of the tracking schema being used. */ schemaVersion: string | null; /** * The authenticated user's ID, if known. */ userId: string | null; }; /** * Represents a primitive value. */ type Primitive = number | boolean | string; /** * Represents monetary values. */ type Money = { /** * The decimal value of the money. */ amount: number; /** * The ISO 4217 currency code (e.g., "USD"). */ currency: string; }; /** * Represents a product category. */ type Category = { /** * Unique category identifier. */ id: string; /** * Human-readable category name. */ title?: string; }; /** * Represents a physical address. */ type Address = { /** * Complete formatted address. */ fullAddress: string; /** * City name. */ city: string; /** * Geographical coordinates. */ location?: { /** * Latitude coordinate. */ lat: number; /** * Longitude coordinate. */ long: number; }; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents shipping details for an order. */ type Shipping = { /** * Cost of shipping. */ price: Money; /** * Shipping method name (e.g., "Standard", "Next Day"). */ method: string; /** * Where the shipment originates. */ origin?: Address; /** * Where the shipment is going. */ destination: Address; /** * Estimated arrival information. */ arrival?: { /** * Exact UNIX timestamp in milliseconds for expected arrival. */ absoluteArriveAt?: number; /** * Time window for arrival [start, end] in UNIX timestamp milliseconds. */ rangeArriveAt?: [number, number]; }; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents a discount coupon. */ type Coupon = { /** * The string code applied by the user. */ code: string; /** * The monetary value discounted. */ amount: Money; /** * Internal ID of the coupon. */ id?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents an individual purchasable item. */ type Product = { /** * Unique product identifier. */ productId: string; /** * Name of the product. */ productTitle?: string; /** * Primary category of the product. */ category?: Category; /** * Stock Keeping Unit identifier. */ skuId?: string; /** * Manufacturer or seller. */ vendor?: string; /** * Current selling price of a single unit. */ price: Money; /** * Discount applied to this specific product. */ discount?: Money; /** * Number of items. */ quantity?: number; /** * The index position of the product in a list/grid. */ position?: number; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents a finalized or processing order. */ type Order = { /** * Unique order identifier. */ orderId: string; /** * Associated checkout session identifier. */ checkoutId?: string; /** * Payment gateway transaction ID. */ transactionId?: string; /** * Associated cart identifier. */ cartId?: string; /** * Final total value charged to the customer. */ totalValue: Money; /** * Total discount applied to the order. */ totalDiscount?: Money; /** * Value of the order before taxes and shipping. */ subtotalValue?: Money; /** * Tax amount applied. */ tax?: Money; /** * Shipping details and costs. */ shipping?: Shipping; /** * Method used for payment (e.g., "Credit Card", "PayPal"). */ paymentMethod?: string; /** * Incentives applied to this order. */ incentives?: Incentive[]; /** * Array of products purchased. */ products: Product[]; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents an active checkout session. */ type Checkout = { /** * Unique checkout session identifier. */ checkoutId?: string; /** * Order details populated so far (excludes finalized IDs). */ order: Omit; /** * Current step in the checkout funnel (e.g., "2" or "shipping"). */ step: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Pagination details for list views. */ type Pagination = { /** * The current page number. */ page: number; /** * The number of items per page. */ limit: number; }; /** * Key-value filter applied to a list. */ type Filter = { /** * The filter parameter key. */ key: string; /** * The filter parameter value. */ value: string; }; /** * Sorting parameter applied to a list. */ type Sort = { /** * The sorting parameter key. */ key: string; /** * The sorting direction. */ value: "asc" | "dsc"; }; /** * Represents a payment transaction. */ type Payment = { /** * Unique payment identifier. */ paymentId: string; /** * Payment gateway used. */ gateway?: string; /** * Method of payment (e.g., "credit_card"). */ method: string; /** * Amount processed in this payment. */ value: Money; /** * The order associated with this payment. */ order?: Order; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents marketing campaign parameters (usually parsed from UTMs). */ type Campaign = { /** * The referrer or entity sending the traffic (utm_source). */ source: string; /** * The marketing medium (utm_medium). */ medium: string; /** * The specific campaign name (utm_campaign). */ name?: string; /** * Identify the paid keywords (utm_term). */ term?: string; /** * Differentiate similar content or links within the same ad (utm_content). */ content?: string; }; /** * Represents an incentive reward value. */ type Reward = { /** * The numerical amount of the reward. */ amount: number; /** * The unit of the reward (e.g., "points", "dollars"). */ unit: string; }; /** * Represents a shopping cart. */ type Cart = { /** * The unique identifier for the cart. */ cartId?: string; /** * The current list of products in the cart. */ products: Product[]; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents an incentive (e.g., loyalty points, cashback). */ type Incentive = { /** * Unique identifier for the incentive. */ incentiveId: string; /** * Human-readable title of the incentive. */ incentiveTitle?: string; /** * Type of incentive (e.g., "cashback", "points"). */ type: string; /** * The reward value associated with the incentive. */ reward: Reward; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents a gamification challenge. */ type Challenge = { /** * Unique identifier for the challenge. */ challengeId: string; /** * Human-readable title of the challenge. */ challengeTitle?: string; /** * Category grouping for the challenge. */ category?: Category; /** * Custom additional properties. */ customProperties?: Record; }; /** * Represents a referral object. */ type Referral = { /** * The unique referral code used. */ referralCode: string; /** * The ID of the user who owns the referral code. */ referrerId?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Application state enum. */ type AppState = "opened" | "closed" | "foreground" | "background"; /** * User profile attributes. */ type UserTraits = { /** * User's first name. */ firstName?: string; /** * User's last name. */ lastName?: string; /** * User's full name. */ fullName?: string; /** * User's chosen username. */ username?: string; /** * User's age. */ age?: number; /** * User's email address. */ email?: string; /** * User's phone number. */ phone?: string; /** * User's gender. */ gender?: "male" | "female" | "other"; /** * UNIX timestamp in milliseconds of user's birthday. */ birthday?: number; /** * UNIX timestamp in milliseconds of user registration. */ registeredAt?: number; /** * User's physical address details. */ address?: Address; /** * Custom additional properties. */ customProperties?: Record; }; /** * HTTP response structure. */ type HttpResponse = { /** * HTTP status code */ status: number; /** * Response data if available */ data?: unknown; }; //#endregion //#region ../../internals/core/adapters/http-adapter.d.ts /** * Context and configuration passed to HttpAdapter implementations. * Adapters can use this information to construct the underlying request. */ type HttpAdapterContext = { /** The API endpoint URL. */endpoint: string; /** Events to send. */ events: Event[]; /** Headers to include in the request. */ headers: Record; /** Header name used for the API key. */ apiKeyHeader: string; }; /** * Abstract interface for HTTP communication. * Implement this interface to use custom HTTP clients (axios, fetch, gRPC, etc.). */ interface HttpAdapter { /** * Send events using the provided adapter context. * * @param context System context and configuration needed by the adapter * to construct and perform the HTTP request. * @returns Promise resolving to HTTP response */ send(context: HttpAdapterContext): Promise; } //#endregion //#region ../../internals/core/adapters/logger-adapter.d.ts /** * Log levels in order of severity */ declare const LogLevel: { readonly DEBUG: "debug"; readonly INFO: "info"; readonly WARN: "warn"; readonly ERROR: "error"; readonly NONE: "none"; }; type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]; /** * Logger interface for customizable logging */ interface LoggerAdapter { debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } //#endregion //#region ../../internals/core/adapters/storage-adapter.d.ts /** * Abstract interface for event persistence. * Implement this interface to use custom storage backends (file system, database, etc.). */ interface StorageAdapter { /** * Initialize the storage adapter and prepare resources. */ init(): Promise; /** * Persist events to storage. * * @param events Array of events to save * @throws {StorageQuotaExceededError} When quota exceeded and events are dropped */ save(events: Event[]): Promise; /** * Load persisted events from storage. * * @returns Promise resolving to array of events */ load(): Promise; /** * Clear all persisted events from storage. */ clear(): Promise; /** * Close the storage adapter and release resources. */ close(): Promise; } //#endregion //#region ../../internals/core/telemetry.d.ts /** * Information provided to the onFlush hook. */ type FlushInfo = { eventCount: number; batchCount: number; }; /** * Information provided to the onSendSuccess hook. */ type SendSuccessInfo = { batchSize: number; status: number; }; /** * Information provided to the onSendFailure hook. */ type SendFailureInfo = { batchSize: number; error: string; attempt: number; }; /** * Information provided to the onRetry hook. */ type RetryInfo = { attempt: number; delay: number; }; /** * Reason an event was dropped. */ type DropReason = "expired" | "sampled" | "client_error"; /** * Information provided to the onDrop hook. */ type DropInfo = { eventCount: number; reason: DropReason; }; /** * Information provided to the onEnqueue hook. */ type EnqueueInfo = { bufferSize: number; }; /** * Telemetry hooks for production monitoring. * All hooks are fire-and-forget (synchronous). */ type TelemetryHooks = { onFlush?: (info: FlushInfo) => void; onSendSuccess?: (info: SendSuccessInfo) => void; onSendFailure?: (info: SendFailureInfo) => void; onRetry?: (info: RetryInfo) => void; onDrop?: (info: DropInfo) => void; onEnqueue?: (info: EnqueueInfo) => void; }; /** * Configuration for automatic SDK telemetry reporting. */ type TelemetryOptions = { /** * Disable automatic telemetry reporting. */ disabled?: boolean; /** * Endpoint to send telemetry data to. */ endpoint: string; /** * Interval in milliseconds between automatic telemetry flushes. * Defaults to 10000 (10 seconds). */ flushInterval?: number; }; //#endregion //#region ../../internals/core/dispatcher.d.ts /** * Batching configuration. */ type BatchOptions = { /** * Interval in milliseconds between automatic flushes (default: `10000`). */ interval?: number; /** * Maximum number of events per batch before auto-flush (default: `10`). */ size?: number; /** * Maximum total serialized payload size in bytes per batch before auto-flush (default: `65536` — 64 KB). */ maxPayloadSize?: number; }; /** * Retry configuration. */ type RetryOptions = { /** * Maximum number of retry attempts per request (default: `3`). */ maxAttempts?: number; /** * Minimum delay in milliseconds before the first retry (default: `1000`). */ minDelay?: number; /** * Maximum delay in milliseconds between retries (default: `360000`). */ maxDelay?: number; /** * Multiplicative factor applied to the delay on each retry (default: `2`). */ backoffFactor?: number; }; /** * Configuration for the Dispatcher. */ type DispatcherConfig = { /** * API key for authentication */ apiKey: string; /** * Header name for API key */ apiKeyHeader: string; /** * API endpoint URL */ endpoint: string; /** * Batching options */ batchOptions: Required; /** * Retry options */ retryOptions: Required; /** * Logger for internal logging */ logger: LoggerAdapter; /** * Maximum size of the in-memory event buffer (optional). * When limit is exceeded, oldest events are evicted using FIFO policy. */ maxBufferSize: number; /** * Per-event time-to-live in milliseconds. * Events older than this are filtered out at flush time. * `null` means no expiry. */ eventTtl: number | null; /** * Telemetry hooks for monitoring. */ hooks: TelemetryHooks; }; /** * Manages event queuing, batching, flushing, and retry logic. * Automatically flushes events based on batch size or time interval. * Implements exponential backoff with jitter for retries. * * @template TMetadata The type of metadata attached to events */ declare class Dispatcher = Record> { #private; /** * Create a new Dispatcher instance. * * @param config Dispatcher configuration * @param httpClient HTTP adapter for sending events * @param storage Storage adapter for persisting events */ constructor(config: DispatcherConfig, httpClient: HttpAdapter, storage: StorageAdapter); /** * Add an event to the buffer. * Triggers auto-flush if batch size threshold is reached. * * @param event The event to enqueue */ enqueue(event: Event): Promise; /** * Immediately flush all queued events. * Cancels any scheduled flush. * Uses mutex to prevent concurrent flush operations. */ flush(): Promise; /** * Restore persisted events from storage. * Called during initialization to recover unsent events. */ restore(): Promise; /** * Clean up resources, cancel scheduled flushes, and clear all references for memory cleanup. * Should be called when disposing the client. */ dispose(): void; } //#endregion //#region ../../internals/core/event-specs.d.ts /** * Payload for identify event. */ type UserIdentifiedPayload = { /** * The known database ID of the user. */ userId: string; /** * User profile attributes. */ traits: UserTraits; }; /** * Payload for screen event. */ type ScreenPayload = { /** * The page title. */ title: string; /** * Full URL of the page. */ url: string; /** * URL pathname. */ pathname?: string; /** * Previous page URL. */ referrer?: string; /** * Query string parameters. */ search?: string; /** * Extracted SEO keywords. */ keywords?: string[]; /** * Parsed UTM campaign parameters. */ campaign?: Campaign; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for app state change events. */ type AppStateChangedPayload = { /** * The new application state. */ newState: AppState; /** * The previous application state. */ previousState?: AppState; }; /** * Payload for click event. */ type ClickedPayload = { /** * The unique identifier of the clicked element (e.g., "submit_checkout_button"). */ elementId: string; /** * The type of element clicked (e.g., "button", "link", "icon"). */ elementType?: string; /** * The visible text or title of the element, if applicable. */ elementTitle?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for view event. */ type ViewedPayload = { /** * The unique identifier of the viewed element (e.g., "services_section"). */ elementId: string; /** * The type of element viewed. */ elementType?: string; /** * The title of the element, if applicable. */ elementTitle?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product clicked event. */ type ProductClickedPayload = { /** * The product that was clicked. */ product: Product; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product viewed event. */ type ProductViewedPayload = { /** * The product that was viewed. */ product: Product; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product shared event. */ type ProductSharedPayload = { /** * Platform shared to (e.g., "Twitter", "Email", "WhatsApp"). */ sharingMethod?: string; /** * User-generated message attached to the share. */ message?: string; /** * Recipient identifier if shared directly. */ recipient?: string; /** * The product that was shared. */ product: Product; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product wishlist events (add/remove). */ type ProductWishlistPayload = { /** * The unique identifier for the user's wishlist. */ wishlistId?: string; /** * The UI location from where the product was added/removed. */ referrer?: string; /** * The product being modified in the wishlist. */ product: Product; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for cart modification events (add/remove product). */ type CartModificationPayload = { /** * The cart being modified. */ cart: Cart; /** * The UI location from where the modification occurred. */ referrer?: string; /** * The product being added or removed. */ product: Product; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product reviewed event. */ type ProductReviewedPayload = { /** * The product being reviewed. */ product: Product; /** * Unique identifier for the review. */ reviewId: string; /** * Numerical rating given. */ rating: number; /** * Summary/title of the review. */ title?: string; /** * Body text of the review. */ body?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for cart viewed event. */ type CartViewedPayload = { /** * The cart being viewed. */ cart: Cart; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for cart emptied event. */ type CartEmptiedPayload = { /** * The cart being emptied. */ cart: Cart; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for checkout started event. */ type CheckoutStartedPayload = { /** * The checkout session details. */ checkout: Checkout; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for checkout step events (viewed/completed). */ type CheckoutStepPayload = { /** * The checkout session details at this step. */ checkout: Checkout; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order completed event. */ type OrderCompletedPayload = { /** * The finalized order details. */ order: Order; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order failed event. */ type OrderFailedPayload = { /** * The order that failed to process. */ order: Order; /** * Detailed reason for the failure. */ reason: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order cancelled event. */ type OrderCancelledPayload = { /** * The order being cancelled. */ order: Order; /** * Who cancelled the order (e.g., "customer", "admin", "system"). */ issuer?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order shipped event. */ type OrderShippedPayload = { /** * The order that was shipped. */ order: Order; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order product fulfilled event. */ type OrderProductFulfilledPayload = { /** * The overall order. */ order: Order; /** * The specific product within the order that was fulfilled. */ product: Product; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order refunded event. */ type OrderRefundedPayload = { /** * The order that was refunded. */ order: Order; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order product returned event. */ type OrderProductReturnedPayload = { /** * The order containing the returned product. */ order: Order; /** * The specific product being returned. */ product: Product; /** * Reason for return (e.g., "Defective", "Wrong Size"). */ reason: string; /** * How the customer was refunded (e.g., "Store Credit"). */ refundMethod?: string; /** * The monetary value of the return. */ totalReturnedValue: Money; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order updated event. */ type OrderUpdatedPayload = { /** * The updated order details. */ order: Order; /** * The reason for the update. */ reason?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order fulfillment status updated event. */ type OrderFulfillmentStatusUpdatedPayload = { /** * The order undergoing a status change. */ order: Order; /** * The previous fulfillment status. */ previousStatus?: string; /** * The new fulfillment status. */ newStatus: string; /** * The reason for the status change, if applicable. */ reason?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for order reviewed event. */ type OrderReviewedPayload = { /** * The order being reviewed. */ order: Order; /** * Unique identifier for the submitted review. */ reviewId: string; /** * The numerical rating given by the user (e.g., 1 to 5). */ rating: number; /** * The title or summary of the review. */ title?: string; /** * The full text body of the review. */ body?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for products searched event. */ type ProductsSearchedPayload = { /** * The raw text query submitted by the user. */ query: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product list viewed event. */ type ProductListViewedPayload = { /** * Unique identifier for the product list/grid. */ listId?: string; /** * The category being viewed, if applicable. */ category?: Category; /** * Pagination state of the list. */ pagination?: Pagination; /** * The products currently visible in the list. */ products: Product[]; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for product list filtered event. */ type ProductListFilteredPayload = { /** * Unique identifier for the product list being filtered. */ listId?: string; /** * The active category context. */ category?: Category; /** * The active filters applied. */ filters: Filter[]; /** * The active sorting parameters applied. */ sorts: Sort[]; /** * The resulting products after filtering/sorting. */ products: Product[]; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for coupon entered/removed events. */ type CouponEnteredRemovedPayload = { /** * The coupon being entered or removed. */ coupon: Coupon; /** * The checkout session context. */ checkout: Checkout; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for coupon denied event. */ type CouponDeniedPayload = { /** * The coupon that was rejected. */ coupon: Coupon; /** * The checkout session context. */ checkout: Checkout; /** * Reason the coupon was denied. */ reason: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for promotion events (viewed/clicked). */ type PromotionPayload = { /** * Unique identifier for the promotion/banner. */ promotionId: string; /** * Human-readable title of the promotion. */ promotionTitle?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for payment authorized event. */ type PaymentAuthorizedPayload = { /** * The payment authorization details. */ payment: Payment; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for payment captured event. */ type PaymentCapturedPayload = { /** * The payment capture details. */ payment: Payment; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for payment failed event. */ type PaymentFailedPayload = { /** * The failed payment details. */ payment: Payment; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for payment refunded event. */ type PaymentRefundedPayload = { /** * The refunded payment details. */ payment: Payment; /** * Reason for the refund. */ reason?: string; /** * The amount returned in this specific transaction. */ returnedAmount: Money; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for referral shared event. */ type ReferralSharedPayload = { /** * The referral object that was shared. */ referral: Referral; /** * The medium through which it was shared (e.g., "whatsapp", "email"). */ medium?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for referral applied event. */ type ReferralAppliedPayload = { /** * The referral object that was applied. */ referral: Referral; /** * The UI flow or surface where the referral was applied (e.g., "checkout", "registration"). */ flow?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for incentive granted event. */ type IncentiveGrantedPayload = { /** * The incentive that was granted. */ incentive: Incentive; /** * Identifier for the source triggering the grant (e.g., Order ID). */ sourceId?: string; /** * Descriptive title of the source. */ sourceTitle?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for incentive redeemed event. */ type IncentiveRedeemedPayload = { /** * The incentive being redeemed. */ incentive: Incentive; /** * Identifier for what consumed the incentive (e.g., Order ID). */ redeemerId?: string; /** * Descriptive title of the redeemer. */ redeemerTitle?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for incentive claimed event. */ type IncentiveClaimedPayload = { /** * The incentive that was claimed. */ incentive: Incentive; /** * Identifier for the origin of the claimable reward. */ sourceId?: string; /** * Descriptive title of the source. */ sourceTitle?: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for incentive expired event. */ type IncentiveExpiredPayload = { /** * The incentive that expired. */ incentive: Incentive; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for gamification challenge started event. */ type ChallengeStartedPayload = { /** * The challenge that was started. */ challenge: Challenge; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for gamification challenge completed event. */ type ChallengeCompletedPayload = { /** * The challenge that was completed. */ challenge: Challenge; /** * Custom additional properties. */ customProperties?: Record; }; /** * Payload for gamification challenge step completed event. */ type ChallengeStepCompletedPayload = { /** * The challenge containing the step. */ challenge: Challenge; /** * The identifier or index of the step completed. */ step: string; /** * Custom additional properties. */ customProperties?: Record; }; /** * Map of all predefined event names to their payload types. * Provides type-safe event tracking with autocomplete support. */ type PredefinedEvents = { user_identified: UserIdentifiedPayload; screened: ScreenPayload; app_state_changed: AppStateChangedPayload; clicked: ClickedPayload; viewed: ViewedPayload; product_clicked: ProductClickedPayload; product_viewed: ProductViewedPayload; product_shared: ProductSharedPayload; products_searched: ProductsSearchedPayload; product_list_viewed: ProductListViewedPayload; product_list_filtered: ProductListFilteredPayload; product_reviewed: ProductReviewedPayload; product_added_to_wishlist: ProductWishlistPayload; product_removed_from_wishlist: ProductWishlistPayload; product_added_to_cart: CartModificationPayload; product_removed_from_cart: CartModificationPayload; cart_viewed: CartViewedPayload; cart_emptied: CartEmptiedPayload; checkout_started: CheckoutStartedPayload; checkout_step_viewed: CheckoutStepPayload; checkout_step_completed: CheckoutStepPayload; order_completed: OrderCompletedPayload; order_failed: OrderFailedPayload; order_cancelled: OrderCancelledPayload; order_shipped: OrderShippedPayload; order_refunded: OrderRefundedPayload; order_updated: OrderUpdatedPayload; order_product_fulfilled: OrderProductFulfilledPayload; order_product_returned: OrderProductReturnedPayload; order_fulfillment_status_updated: OrderFulfillmentStatusUpdatedPayload; order_reviewed: OrderReviewedPayload; coupon_entered: CouponEnteredRemovedPayload; coupon_removed: CouponEnteredRemovedPayload; coupon_denied: CouponDeniedPayload; promotion_viewed: PromotionPayload; promotion_clicked: PromotionPayload; payment_authorized: PaymentAuthorizedPayload; payment_captured: PaymentCapturedPayload; payment_failed: PaymentFailedPayload; payment_refunded: PaymentRefundedPayload; referral_shared: ReferralSharedPayload; referral_applied: ReferralAppliedPayload; incentive_granted: IncentiveGrantedPayload; incentive_redeemed: IncentiveRedeemedPayload; incentive_claimed: IncentiveClaimedPayload; incentive_expired: IncentiveExpiredPayload; challenge_started: ChallengeStartedPayload; challenge_completed: ChallengeCompletedPayload; challenge_step_completed: ChallengeStepCompletedPayload; }; //#endregion //#region ../../internals/core/events-namespace.d.ts /** * Typed namespace for predefined CDP events. * All methods auto-attach `PREDEFINED_SCHEMA_VERSION`. */ declare class EventsNamespace { #private; constructor(client: Client); appStateChanged(payload: AppStateChangedPayload): Promise; productClicked(payload: ProductClickedPayload): Promise; productViewed(payload: ProductViewedPayload): Promise; productShared(payload: ProductSharedPayload): Promise; productsSearched(payload: ProductsSearchedPayload): Promise; productListViewed(payload: ProductListViewedPayload): Promise; productListFiltered(payload: ProductListFilteredPayload): Promise; productReviewed(payload: ProductReviewedPayload): Promise; productAddedToWishlist(payload: ProductWishlistPayload): Promise; productRemovedFromWishlist(payload: ProductWishlistPayload): Promise; productAddedToCart(payload: CartModificationPayload): Promise; productRemovedFromCart(payload: CartModificationPayload): Promise; cartViewed(payload: CartViewedPayload): Promise; cartEmptied(payload: CartEmptiedPayload): Promise; checkoutStarted(payload: CheckoutStartedPayload): Promise; checkoutStepViewed(payload: CheckoutStepPayload): Promise; checkoutStepCompleted(payload: CheckoutStepPayload): Promise; orderCompleted(payload: OrderCompletedPayload): Promise; orderFailed(payload: OrderFailedPayload): Promise; orderCancelled(payload: OrderCancelledPayload): Promise; orderShipped(payload: OrderShippedPayload): Promise; orderRefunded(payload: OrderRefundedPayload): Promise; orderUpdated(payload: OrderUpdatedPayload): Promise; orderProductFulfilled(payload: OrderProductFulfilledPayload): Promise; orderProductReturned(payload: OrderProductReturnedPayload): Promise; orderFulfillmentStatusUpdated(payload: OrderFulfillmentStatusUpdatedPayload): Promise; couponEntered(payload: CouponEnteredRemovedPayload): Promise; couponRemoved(payload: CouponEnteredRemovedPayload): Promise; couponDenied(payload: CouponDeniedPayload): Promise; promotionViewed(payload: PromotionPayload): Promise; promotionClicked(payload: PromotionPayload): Promise; paymentAuthorized(payload: PaymentAuthorizedPayload): Promise; paymentCaptured(payload: PaymentCapturedPayload): Promise; paymentFailed(payload: PaymentFailedPayload): Promise; paymentRefunded(payload: PaymentRefundedPayload): Promise; referralShared(payload: ReferralSharedPayload): Promise; referralApplied(payload: ReferralAppliedPayload): Promise; incentiveGranted(payload: IncentiveGrantedPayload): Promise; incentiveRedeemed(payload: IncentiveRedeemedPayload): Promise; incentiveClaimed(payload: IncentiveClaimedPayload): Promise; incentiveExpired(payload: IncentiveExpiredPayload): Promise; challengeStarted(payload: ChallengeStartedPayload): Promise; challengeCompleted(payload: ChallengeCompletedPayload): Promise; challengeStepCompleted(payload: ChallengeStepCompletedPayload): Promise; } //#endregion //#region ../../internals/core/metadata-manager.d.ts /** * Manages shared metadata that gets attached to all events. * Provides type-safe metadata management with generic support. * * @template TMetadata The type definition for metadata */ declare class MetadataManager> { #private; /** * Set a metadata value. * * @template K The metadata key type * @param key The metadata key * @param value The value to set */ set(key: K, value: TMetadata[K]): void; /** * Get all metadata as a single object. * * @returns All metadata or empty object if none set */ getAll(): Partial | null; /** * Check if metadata is empty. * * @returns True if no metadata has been set */ isEmpty(): boolean; /** * Clear all metadata. */ clear(): void; } //#endregion //#region ../../internals/core/client.d.ts /** * Function to sample events before they are enqueued. */ type EventSampler = Record> = (event: Event) => boolean; /** * Configuration for the Ripple client. */ type ClientConfig = { /** * API key for authentication. */ apiKey: string; /** * API endpoint URL. */ endpoint: string; /** * Header name for API key (default: `"X-API-Key"`). */ apiKeyHeader?: string; /** * Batching options controlling flush interval, batch size, and payload size limits. */ batchOptions?: BatchOptions; /** * Retry options controlling retry attempts, delays, and backoff strategy. */ retryOptions?: RetryOptions; /** * Maximum number of events the in-memory buffer can hold (default: `50`). * When limit is exceeded, oldest events are evicted using FIFO policy. */ maxBufferSize?: number; /** * Per-event time-to-live in milliseconds. * Events older than this (based on `issuedAt`) are dropped at flush time. */ eventTtl?: number; /** * HTTP adapter for sending events (default: built-in `HttpClient`). */ httpAdapter?: HttpAdapter; /** * Storage adapter for persisting events. */ storageAdapter: StorageAdapter; /** * Logger adapter for SDK internal logging (default: `ConsoleLogger` with `WARN` level). */ loggerAdapter?: LoggerAdapter; /** * Optional function to sample events before they are enqueued. * Return `true` to keep the event, `false` to drop it. */ eventSampler?: EventSampler; /** * Telemetry hooks for production monitoring (fire-and-forget). */ hooks?: TelemetryHooks; /** * Automatic telemetry reporting configuration. * When enabled, the SDK sends internal metrics to the specified endpoint. */ telemetryOptions?: TelemetryOptions; }; /** * Abstract base class for Ripple SDK clients. * Provides core event tracking functionality with type-safe metadata management. * * @template TCustomEvents Custom event definitions merged with predefined CDP events * @template TMetadata The type definition for metadata */ declare abstract class Client = Record, TMetadata extends Record = Record> { #private; protected readonly _metadataManager: MetadataManager; protected readonly _dispatcher: Dispatcher; protected readonly _storage: StorageAdapter; protected readonly _logger: LoggerAdapter; protected readonly _sampler: EventSampler; /** * Typed namespace for predefined CDP events. */ readonly events: EventsNamespace; protected _anonymousId: string; protected _userId: string | null; /** * Create a new Client instance. * * @param config Client configuration including adapters */ constructor(config: ClientConfig); /** * Generate a unique anonymous ID for this client instance. * Can be overridden by subclasses to provide custom ID generation or persistence. * * @returns A unique anonymous identifier string */ protected _generateAnonymousId(): string; /** * Get SDK information for the current runtime. * Must be implemented by runtime-specific clients. * * @returns SDK information */ protected abstract _getSdkInfo(): SdkInfo; /** * Get platform information for the current runtime. * Must be implemented by runtime-specific clients. * * @returns Platform information or null */ protected abstract _getPlatform(): Platform | null; /** * Identify a user and associate traits with their profile. * * @param userId The authenticated user's unique identifier * @param traits User profile attributes (e.g., name, email) */ identify(userId: string, traits: UserTraits): Promise; /** * Track a click interaction on a UI element. * * @param payload Click event data including element identifier */ clicked(payload: ClickedPayload): Promise; /** * Track a view impression of a UI element. * * @param payload View event data including element identifier */ viewed(payload: ViewedPayload): Promise; /** * Internal method for tracking predefined/internal events without generic constraints. * Used by convenience methods. * * @param name Event name * @param payload Event payload * @param schemaVersion Schema version */ protected _trackInternal(name: string, payload: EventPayload, schemaVersion: string): Promise; /** * Track an event. * Automatically initializes the client if not already initialized. * * @param name Event name/identifier * @param payload Event data payload * @param schemaVersion Event schema version */ track(name: K, payload?: TCustomEvents[K], schemaVersion?: string): Promise; /** * Set a shared metadata value. * This metadata will be attached to all subsequent events. * * @template K The metadata key type * @param key The metadata key * @param value The value to set */ setMetadata(key: K, value: TMetadata[K]): void; /** * Get all current metadata. * * @returns All metadata or null if none set */ getMetadata(): Partial | null; /** * Get the anonymous ID. * * @returns Anonymous ID */ getAnonymousId(): string; /** * Get the user ID. * * @returns User ID or null if not set */ getUserId(): string | null; /** * Immediately flush all queued events. */ flush(): Promise; /** * Initialize the client and restore persisted events. */ init(): Promise; /** * Dispose the client and clean up resources. * Cancels scheduled flushes and clears all references for memory cleanup. */ dispose(): void; } //#endregion //#region ../../internals/core/http-client.d.ts /** * Built-in HTTP adapter using the Fetch API. * Works in both browser and Node.js 18+ environments. * Uses keepalive flag when available for reliable delivery during page unload. */ declare class HttpClient implements HttpAdapter { /** * Send events using the Fetch API. * * @param context Request context including endpoint, events, and headers * @returns Promise resolving to HTTP response */ send(context: HttpAdapterContext): Promise; } //#endregion //#region ../../internals/core/logger.d.ts /** * Default console logger implementation. */ declare class ConsoleLogger implements LoggerAdapter { #private; constructor(level?: LogLevel); debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } /** * No-op logger that discards all log messages. */ declare class NoOpLogger implements LoggerAdapter { debug(_message: string, ..._args: unknown[]): void; info(_message: string, ..._args: unknown[]): void; warn(_message: string, ..._args: unknown[]): void; error(_message: string, ..._args: unknown[]): void; } //#endregion //#region src/ripple-client.d.ts /** * Node.js-specific client configuration */ type NodeClientConfig = ClientConfig; /** * Ripple SDK client for Node.js environments. * * @template TCustomEvents Custom event definitions merged with predefined CDP events * @template TMetadata The type definition for metadata */ declare class RippleClient = Record, TMetadata extends Record = Record> extends Client { /** * Create a new RippleClient instance. * * @param config Client configuration including required adapters */ constructor(config: NodeClientConfig); /** * Get SDK information for node environment. * * @returns Node SDK information */ protected _getSdkInfo(): SdkInfo; /** * Get platform information for Node.js environment. * * @returns Server platform information */ protected _getPlatform(): Platform | null; /** * Track a screen/page view event. * * @param payload Screen event data (required in Node.js) * @param schemaVersion Event schema version */ screen(payload: ScreenPayload): Promise; } //#endregion //#region src/storages/noop-storage.d.ts /** * No-operation storage adapter that discards all events. * Use when event persistence is not needed. */ declare class NoOpStorage implements StorageAdapter { init(): Promise; save(_events: Event[]): Promise; clear(): Promise; close(): Promise; load(): Promise; } //#endregion export { type AppState, type BatchOptions, type Cart, type Category, type Challenge, type Checkout, ConsoleLogger, type Coupon, type Event, type EventPayload, type EventSampler, type HttpAdapter, type HttpAdapterContext, HttpClient, type HttpResponse, type Incentive, LogLevel, type LoggerAdapter, NoOpLogger, NoOpStorage, NodeClientConfig, type Order, type Payment, type Platform, type PlatformInfo, type PredefinedEvents, type Product, type Referral, type RetryOptions, RippleClient, type SdkInfo, type ServerPlatform, type Shipping, type StorageAdapter, type TelemetryHooks, type UserTraits }; //# sourceMappingURL=index.d.ts.map