UNPKG

@snowplow/tracker-core

Version:

Core functionality for Snowplow JavaScript trackers

1,336 lines 54.3 kB
declare const version: string; declare enum LOG_LEVEL { none = 0, error = 1, warn = 2, debug = 3, info = 4 } interface Logger { setLogLevel: (level: LOG_LEVEL) => void; info: (message: string, ...extraParams: unknown[]) => void; debug: (message: string, ...extraParams: unknown[]) => void; warn: (message: string, error?: unknown, ...extraParams: unknown[]) => void; error: (message: string, error?: unknown, ...extraParams: unknown[]) => void; } declare const LOG: Logger; /** * Interface which defines Core Plugins */ interface CorePlugin { /** * Called when the plugin is initialised during the trackerCore construction * * @remarks * Use to capture the specific core instance for each instance of a core plugin */ activateCorePlugin?: (core: TrackerCore) => void; /** * Called when the tracker is being destroyed. * Should be used to clean up any resources or listeners that the plugin has created. */ deactivatePlugin?: (core: TrackerCore) => void; /** * Called before the `filter` method is called and before the trackerCore callback fires (if the filter passes) * @param payloadBuilder - The payloadBuilder which will be sent to the callback, can be modified */ beforeTrack?: (payloadBuilder: PayloadBuilder) => void; /** * Called just after the trackerCore callback fires * @param payload - The final built payload */ afterTrack?: (payload: Payload) => void; /** * Called before the payload is sent to the callback to decide whether to send the payload or skip it * @param payload - The final event payload, can't be modified. * @returns True if the payload should be sent, false if it should be skipped */ filter?: (payload: Payload) => boolean; /** * Called when constructing the context for each event * Useful for adding additional context to events */ contexts?: () => SelfDescribingJson[]; /** * Passed a logger instance which can be used to send log information * to the active logger */ logger?: (logger: Logger) => void; } /** * Export interface for any Self-Describing JSON such as context or Self Describing events * @typeParam T - The type of the data object within a SelfDescribingJson */ type SelfDescribingJson<T = Record<string, unknown>> = { /** * The schema string * @example 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0' */ schema: string; /** * The data object which should conform to the supplied schema */ data: T extends any[] ? never : T extends {} ? T : never; }; /** * Export interface for any Self-Describing JSON which has the data attribute as an array * @typeParam T - The type of the data object within the SelfDescribingJson data array */ type SelfDescribingJsonArray<T = Record<string, unknown>> = { /** * The schema string * @example 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-1' */ schema: string; /** * The data array which should conform to the supplied schema */ data: (T extends SelfDescribingJson ? T : SelfDescribingJson<T>)[]; }; /** * Algebraic datatype representing possible timestamp type choice */ type Timestamp = TrueTimestamp | DeviceTimestamp | number; /** * A representation of a True Timestamp (ttm) */ interface TrueTimestamp { readonly type: "ttm"; readonly value: number; } /** * A representation of a Device Timestamp (dtm) */ interface DeviceTimestamp { readonly type: "dtm"; readonly value: number; } /** Additional data points to set when tracking an event */ interface CommonEventProperties<T = Record<string, unknown>> { /** Add context to an event by setting an Array of Self Describing JSON */ context?: Array<SelfDescribingJson<T>> | null; /** Set the true timestamp or overwrite the device sent timestamp on an event */ timestamp?: Timestamp | null; } /** * Export interface containing all Core functions */ interface TrackerCore { /** * Call with a payload from a buildX function * Adds context and payloadPairs name-value pairs to the payload * Applies the callback to the built payload * * @param pb - Payload * @param context - Custom contexts relating to the event * @param timestamp - Timestamp of the event * @returns Payload after the callback is applied or undefined if the event is skipped */ track: (/** A PayloadBuilder created by one of the `buildX` functions */ pb: PayloadBuilder, /** The additional contextual information related to the event */ context?: Array<SelfDescribingJson> | null, /** Timestamp override */ timestamp?: Timestamp | null) => Payload | undefined; /** * Set a persistent key-value pair to be added to every payload * * @param key - Field name * @param value - Field value */ addPayloadPair: (key: string, value: unknown) => void; /** * Deactivate tracker core including all plugins. * This is useful for cleaning up resources or listeners that have been created. * Once deactivated, the tracker won't be able to track any events. */ deactivate(): void; /** * Get current base64 encoding state */ getBase64Encoding(): boolean; /** * Turn base 64 encoding on or off * * @param encode - Whether to encode payload */ setBase64Encoding(encode: boolean): void; /** * Merges a dictionary into payloadPairs * * @param dict - Adds a new payload dictionary to the existing one */ addPayloadDict(dict: Payload): void; /** * Replace payloadPairs with a new dictionary * * @param dict - Resets all current payload pairs with a new dictionary of pairs */ resetPayloadPairs(dict: Payload): void; /** * Set the tracker version * * @param version - The version of the current tracker */ setTrackerVersion(version: string): void; /** * Set the tracker namespace * * @param name - The trackers namespace */ setTrackerNamespace(name: string): void; /** * Set the application ID * * @param appId - An application ID which identifies the current application */ setAppId(appId: string): void; /** * Set the platform * * @param value - A valid Snowplow platform value */ setPlatform(value: string): void; /** * Set the user ID * * @param userId - The custom user id */ setUserId(userId: string): void; /** * Set the screen resolution * * @param width - screen resolution width * @param height - screen resolution height */ setScreenResolution(width: string, height: string): void; /** * Set the viewport dimensions * * @param width - viewport width * @param height - viewport height */ setViewport(width: string, height: string): void; /** * Set the color depth * * @param depth - A color depth value as string */ setColorDepth(depth: string): void; /** * Set the timezone * * @param timezone - A timezone string */ setTimezone(timezone: string): void; /** * Set the language * * @param lang - A language string e.g. 'en-UK' */ setLang(lang: string): void; /** * Set the IP address * * @param ip - An IP Address string */ setIpAddress(ip: string): void; /** * Set the Useragent * * @param useragent - A useragent string */ setUseragent(useragent: string): void; /** * Adds contexts globally, contexts added here will be attached to all applicable events * @param contexts - An array containing either contexts or a conditional contexts */ addGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive> | Record<string, ConditionalContextProvider | ContextPrimitive>): void; /** * Removes all global contexts */ clearGlobalContexts(): void; /** * Removes previously added global context, performs a deep comparison of the contexts or conditional contexts * @param contexts - An array containing either contexts or a conditional contexts */ removeGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive | string>): void; /** * Add a plugin into the plugin collection after Core has already been initialised * @param configuration - The plugin to add */ addPlugin(configuration: CorePluginConfiguration): void; } /** * The configuration object for the tracker core library */ interface CoreConfiguration { /* Should payloads be base64 encoded when built */ base64?: boolean; /* A list of all the plugins to include at load */ corePlugins?: Array<CorePlugin>; /* The callback which will fire each time `track()` is called */ callback?: (PayloadData: PayloadBuilder) => void; } /** * The configuration of the plugin to add */ interface CorePluginConfiguration { /* The plugin to add */ plugin: CorePlugin; } /** * Create a tracker core object * * @param base64 - Whether to base 64 encode contexts and self describing event JSONs * @param corePlugins - The core plugins to be processed with each event * @param callback - Function applied to every payload dictionary object * @returns Tracker core */ declare function trackerCore(configuration?: CoreConfiguration): TrackerCore; /** * A Self Describing Event * A custom event type, allowing for an event to be tracked using your own custom schema * and a data object which conforms to the supplied schema */ interface SelfDescribingEvent<T = Record<string, unknown>> { /** The Self Describing JSON which describes the event */ event: SelfDescribingJson<T>; } /** * Build a self-describing event * A custom event type, allowing for an event to be tracked using your own custom schema * and a data object which conforms to the supplied schema * * @param event - Contains the properties and schema location for the event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildSelfDescribingEvent<T = Record<string, unknown>>(event: SelfDescribingEvent<T>): PayloadBuilder; /** * A Page View Event * Represents a Page View, which is typically fired as soon as possible when a web page * is loaded within the users browser. Often also fired on "virtual page views" within * Single Page Applications (SPA). */ interface PageViewEvent { /** The current URL visible in the users browser */ pageUrl?: string | null; /** The current page title in the users browser */ pageTitle?: string | null; /** The URL of the referring page */ referrer?: string | null; } /** * Build a Page View Event * Represents a Page View, which is typically fired as soon as possible when a web page * is loaded within the users browser. Often also fired on "virtual page views" within * Single Page Applications (SPA). * * @param event - Contains the properties for the Page View event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildPageView(event: PageViewEvent): PayloadBuilder; /** * A Page Ping Event * Fires when activity tracking is enabled in the browser. * Tracks same information as the last tracked Page View and includes scroll * information from the current page view */ interface PagePingEvent extends PageViewEvent { /** The minimum X scroll position for the current page view */ minXOffset?: number; /** The maximum X scroll position for the current page view */ maxXOffset?: number; /** The minimum Y scroll position for the current page view */ minYOffset?: number; /** The maximum Y scroll position for the current page view */ maxYOffset?: number; } /** * Build a Page Ping Event * Fires when activity tracking is enabled in the browser. * Tracks same information as the last tracked Page View and includes scroll * information from the current page view * * @param event - Contains the properties for the Page Ping event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildPagePing(event: PagePingEvent): PayloadBuilder; /** * A Structured Event * A classic style of event tracking, allows for easier movement between analytics * systems. A loosely typed event, creating a Self Describing event is preferred, but * useful for interoperability. */ interface StructuredEvent { category: string; action: string; label?: string; property?: string; value?: number; } /** * Build a Structured Event * A classic style of event tracking, allows for easier movement between analytics * systems. A loosely typed event, creating a Self Describing event is preferred, but * useful for interoperability. * * @param event - Contains the properties for the Structured event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildStructEvent(event: StructuredEvent): PayloadBuilder; /** * An Ecommerce Transaction Event * Allows for tracking common ecommerce events, this event is usually used when * a customer completes a transaction. */ interface EcommerceTransactionEvent { /** An identifier for the order */ orderId: string; /** The total value of the order */ total: number; /** Transaction affiliation (e.g. store where sale took place) */ affiliation?: string; /** The amount of tax on the transaction */ tax?: number; /** The amount of shipping costs for this transaction */ shipping?: number; /** Delivery address, city */ city?: string; /** Delivery address, state */ state?: string; /** Delivery address, country */ country?: string; /** Currency of the transaction */ currency?: string; } /** * Build an Ecommerce Transaction Event * Allows for tracking common ecommerce events, this event is usually used when * a consumer completes a transaction. * * @param event - Contains the properties for the Ecommerce Transactoion event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildEcommerceTransaction(event: EcommerceTransactionEvent): PayloadBuilder; /** * An Ecommerce Transaction Item * Related to the {@link EcommerceTransactionEvent} * Each Ecommerce Transaction may contain one or more EcommerceTransactionItem events */ interface EcommerceTransactionItemEvent { /** An identifier for the order */ orderId: string; /** A Product Stock Keeping Unit (SKU) */ sku: string; /** The price of the product */ price: number; /** The name of the product */ name?: string; /** The category the product belongs to */ category?: string; /** The quanity of this product within the transaction */ quantity?: number; /** The currency of the product for the transaction */ currency?: string; } /** * Build an Ecommerce Transaction Item Event * Related to the {@link buildEcommerceTransaction} * Each Ecommerce Transaction may contain one or more EcommerceTransactionItem events * * @param event - Contains the properties for the Ecommerce Transaction Item event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildEcommerceTransactionItem(event: EcommerceTransactionItemEvent): PayloadBuilder; /** * A Screen View Event * Similar to a Page View but less focused on typical web properties * Often used for mobile applications as the user is presented with * new views as they performance navigation events */ interface ScreenViewEvent { /** The name of the screen */ name?: string; /** The identifier of the screen */ id?: string; } /** * Build a Scren View Event * Similar to a Page View but less focused on typical web properties * Often used for mobile applications as the user is presented with * new views as they performance navigation events * * @param event - Contains the properties for the Screen View event. One or more properties must be included. * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildScreenView(event: ScreenViewEvent): PayloadBuilder; /** * A Link Click Event * Used when a user clicks on a link on a webpage, typically an anchor tag `<a>` */ interface LinkClickEvent { /** The target URL of the link */ targetUrl: string; /** The ID of the element clicked if present */ elementId?: string; /** An array of class names from the element clicked */ elementClasses?: Array<string>; /** The target value of the element if present */ elementTarget?: string; /** The content of the element if present and enabled */ elementContent?: string; } /** * Build a Link Click Event * Used when a user clicks on a link on a webpage, typically an anchor tag `<a>` * * @param event - Contains the properties for the Link Click event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildLinkClick(event: LinkClickEvent): PayloadBuilder; /** * An Ad Impression Event * Used to track an advertisement impression * * @remarks * If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field. */ interface AdImpressionEvent { /** Identifier for the particular impression instance */ impressionId?: string; /** The cost model for the campaign */ costModel?: "cpa" | "cpc" | "cpm"; /** Advertisement cost */ cost?: number; /** The destination URL of the advertisement */ targetUrl?: string; /** Identifier for the ad banner being displayed */ bannerId?: string; /** Identifier for the zone where the ad banner is located */ zoneId?: string; /** Identifier for the advertiser which the campaign belongs to */ advertiserId?: string; /** Identifier for the advertiser which the campaign belongs to */ campaignId?: string; } /** * Build a Ad Impression Event * Used to track an advertisement impression * * @remarks * If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field. * * @param event - Contains the properties for the Ad Impression event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildAdImpression(event: AdImpressionEvent): PayloadBuilder; /** * An Ad Click Event * Used to track an advertisement click * * @remarks * If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field. */ interface AdClickEvent { /** The destination URL of the advertisement */ targetUrl: string; /** Identifier for the particular click instance */ clickId?: string; /** The cost model for the campaign */ costModel?: "cpa" | "cpc" | "cpm"; /** Advertisement cost */ cost?: number; /** Identifier for the ad banner being displayed */ bannerId?: string; /** Identifier for the zone where the ad banner is located */ zoneId?: string; /** Identifier for the particular impression instance */ impressionId?: string; /** Identifier for the advertiser which the campaign belongs to */ advertiserId?: string; /** Identifier for the advertiser which the campaign belongs to */ campaignId?: string; } /** * Build a Ad Click Event * Used to track an advertisement click * * @remarks * If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field. * * @param event - Contains the properties for the Ad Click event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildAdClick(event: AdClickEvent): PayloadBuilder; /** * An Ad Conversion Event * Used to track an advertisement click * * @remarks * If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field. */ interface AdConversionEvent { /** Identifier for the particular conversion instance */ conversionId?: string; /** The cost model for the campaign */ costModel?: "cpa" | "cpc" | "cpm"; /** Advertisement cost */ cost?: number; /** Conversion category */ category?: string; /** The type of user interaction e.g. 'purchase' */ action?: string; /** Describes the object of the conversion */ property?: string; /** How much the conversion is initially worth */ initialValue?: number; /** Identifier for the advertiser which the campaign belongs to */ advertiserId?: string; /** Identifier for the advertiser which the campaign belongs to */ campaignId?: string; } /** * Build a Ad Conversion Event * Used to track an advertisement click * * @remarks * If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field. * * @param event - Contains the properties for the Ad Conversion event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildAdConversion(event: AdConversionEvent): PayloadBuilder; /** * A Social Interaction Event * Social tracking will be used to track the way users interact * with Facebook, Twitter and Google + widgets * e.g. to capture “like this” or “tweet this” events. */ interface SocialInteractionEvent { /** Social action performed */ action: string; /** Social network */ network: string; /** Object social action is performed on */ target?: string; } /** * Build a Social Interaction Event * Social tracking will be used to track the way users interact * with Facebook, Twitter and Google + widgets * e.g. to capture “like this” or “tweet this” events. * * @param event - Contains the properties for the Social Interaction event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildSocialInteraction(event: SocialInteractionEvent): PayloadBuilder; /** * An Add To Cart Event * For tracking users adding items from a cart * on an ecommerce site. */ interface AddToCartEvent { /** A Product Stock Keeping Unit (SKU) */ sku: string; /** The number added to the cart */ quantity: number; /** The name of the product */ name?: string; /** The category of the product */ category?: string; /** The price of the product */ unitPrice?: number; /** The currency of the product */ currency?: string; } /** * Build a Add To Cart Event * For tracking users adding items from a cart * on an ecommerce site. * * @param event - Contains the properties for the Add To Cart event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildAddToCart(event: AddToCartEvent): PayloadBuilder; /** * An Remove To Cart Event * For tracking users removing items from a cart * on an ecommerce site. */ interface RemoveFromCartEvent { /** A Product Stock Keeping Unit (SKU) */ sku: string; /** The number removed from the cart */ quantity: number; /** The name of the product */ name?: string; /** The category of the product */ category?: string; /** The price of the product */ unitPrice?: number; /** The currency of the product */ currency?: string; } /** * Build a Remove From Cart Event * For tracking users removing items from a cart * on an ecommerce site. * * @param event - Contains the properties for the Remove From Cart event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildRemoveFromCart(event: RemoveFromCartEvent): PayloadBuilder; /** * Represents either a Form Focus or Form Change event * When a user focuses on a form element or when a user makes a * change to a form element. */ interface FormFocusOrChangeEvent { /** The schema which will be used for the event */ schema: "change_form" | "focus_form"; /** The ID of the form which the element belongs to */ formId: string; /** The element ID which the user is interacting with */ elementId: string; /** The name of the node ("INPUT", "TEXTAREA", "SELECT") */ nodeName: string; /** The value of the element at the time of the event firing */ value: string | null; /** The type of element (e.g. "datetime", "text", "radio", etc.) */ type?: string | null; /** The class names on the element */ elementClasses?: Array<string> | null; } /** * Build a Form Focus or Change Form Event based on schema property * When a user focuses on a form element or when a user makes a * change to a form element. * * @param event - Contains the properties for the Form Focus or Change Form event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildFormFocusOrChange(event: FormFocusOrChangeEvent): PayloadBuilder; /** * A representation of an element within a form */ type FormElement = { /** The name of the element */ name: string; /** The current value of the element */ value: string | null; /** The name of the node ("INPUT", "TEXTAREA", "SELECT") */ nodeName: string; /** The type of element (e.g. "datetime", "text", "radio", etc.) */ type?: string | null; }; /** * A Form Submission Event * Used to track when a user submits a form */ interface FormSubmissionEvent { /** The ID of the form */ formId: string; /** The class names on the form */ formClasses?: Array<string>; /** The elements contained within the form */ elements?: Array<FormElement>; } /** * Build a Form Submission Event * Used to track when a user submits a form * * @param event - Contains the properties for the Form Submission event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildFormSubmission(event: FormSubmissionEvent): PayloadBuilder; /** * A Site Search Event * Used when a user performs a search action on a page */ interface SiteSearchEvent { /** The terms of the search */ terms: Array<string>; /** Any filters which have been applied to the search */ filters?: Record<string, string | boolean>; /** The total number of results for this search */ totalResults?: number; /** The number of visible results on the page */ pageResults?: number; } /** * Build a Site Search Event * Used when a user performs a search action on a page * * @param event - Contains the properties for the Site Search event * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} */ declare function buildSiteSearch(event: SiteSearchEvent): PayloadBuilder; /** * A Consent Withdrawn Event * Used for tracking when a user withdraws their consent */ interface ConsentWithdrawnEvent { /** Specifies whether all consent should be withdrawn */ all: boolean; /** Identifier for the document withdrawing consent */ id?: string; /** Version of the document withdrawing consent */ version?: string; /** Name of the document withdrawing consent */ name?: string; /** Description of the document withdrawing consent */ description?: string; } /** * Interface for returning a built event (PayloadBuilder) and context (Array of SelfDescribingJson). */ interface EventPayloadAndContext { /** Tracker payload for the event data */ event: PayloadBuilder; /** List of context entities to track along with the event */ context: Array<SelfDescribingJson>; } /** * Build a Consent Withdrawn Event * Used for tracking when a user withdraws their consent * * @param event - Contains the properties for the Consent Withdrawn event * @returns An object containing the PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} and a 'consent_document' context */ declare function buildConsentWithdrawn(event: ConsentWithdrawnEvent): EventPayloadAndContext; /** * A Consent Granted Event * Used for tracking when a user grants their consent */ interface ConsentGrantedEvent { /** Identifier for the document granting consent */ id: string; /** Version of the document granting consent */ version: string; /** Name of the document granting consent */ name?: string; /** Description of the document granting consent */ description?: string; /** When the consent expires */ expiry?: string; } /** * Build a Consent Granted Event * Used for tracking when a user grants their consent * * @param event - Contains the properties for the Consent Granted event * @returns An object containing the PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track} and a 'consent_document' context */ declare function buildConsentGranted(event: ConsentGrantedEvent): EventPayloadAndContext; /** * Returns a copy of a JSON with undefined and null properties removed * * @param event - JSON object to clean * @param exemptFields - Set of fields which should not be removed even if empty * @returns A cleaned copy of eventJson */ declare function removeEmptyProperties(event: Record<string, unknown>, exemptFields?: Record<string, boolean>): Record<string, unknown>; /** * Type for a Payload dictionary */ type Payload = Record<string, unknown>; /** * A tuple which represents the unprocessed JSON to be added to the Payload */ type EventJsonWithKeys = { keyIfEncoded: string; keyIfNotEncoded: string; json: Record<string, unknown>; }; /** * An array of tuples which represents the unprocessed JSON to be added to the Payload */ type EventJson = Array<EventJsonWithKeys>; /** * A function which will processor the Json onto the injected PayloadBuilder */ type JsonProcessor = (payloadBuilder: PayloadBuilder, jsonForProcessing: EventJson, contextEntitiesForProcessing: SelfDescribingJson[]) => void; /** * Interface for mutable object encapsulating tracker payload */ interface PayloadBuilder { /** * Adds an entry to the Payload * @param key - Key for Payload dictionary entry * @param value - Value for Payload dictionaty entry */ add: (key: string, value: unknown) => void; /** * Merges a payload into the existing payload * @param dict - The payload to merge */ addDict: (dict: Payload) => void; /** * Caches a JSON object to be added to payload on build * @param keyIfEncoded - key if base64 encoding is enabled * @param keyIfNotEncoded - key if base64 encoding is disabled * @param json - The json to be stringified and added to the payload */ addJson: (keyIfEncoded: string, keyIfNotEncoded: string, json: Record<string, unknown>) => void; /** * Caches a context entity to be added to payload on build * @param entity - Context entity to add to the event */ addContextEntity: (entity: SelfDescribingJson) => void; /** * Gets the current payload, before cached JSON is processed */ getPayload: () => Payload; /** * Gets all JSON objects added to payload */ getJson: () => EventJson; /** * Adds a function which will be executed when building * the payload to process the JSON which has been added to this payload * @param jsonProcessor - The JsonProcessor function for this builder */ withJsonProcessor: (jsonProcessor: JsonProcessor) => void; /** * Builds and returns the Payload * @param base64Encode - configures if unprocessed, cached json should be encoded */ build: () => Payload; } declare function payloadBuilder(): PayloadBuilder; /** * A helper to build a Snowplow request from a set of name-value pairs, provided using the add methods. * Will base64 encode JSON, if desired, on build * * @returns The request builder, with add and build methods */ declare function payloadJsonProcessor(encodeBase64: boolean): JsonProcessor; /** * Is property a non-empty JSON? * @param property - Checks if object is non-empty json */ declare function isNonEmptyJson(property?: Record<string, unknown>): boolean; /** * Is property a JSON? * @param property - Checks if object is json */ declare function isJson(property?: Record<string, unknown>): boolean; /** * Argument for {@link ContextGenerator} and {@link ContextFilter} callback */ interface ContextEvent { /** The event payload */ event: Payload; /** The event type * @example 'page_view' */ eventType: string; /** The event schema where one is available, or empty string * @example 'iglu:com.snowplowanalytics.snowplow/ad_impression/jsonschema/1-0-0' */ eventSchema: string; } /** * A context generator is a user-supplied callback that is evaluated for each event * to allow an additional context to be dynamically attached to the event * @param args - - Object which contains the event information to help decide what should be included in the returned Context */ type ContextGenerator = (args?: ContextEvent) => SelfDescribingJson | SelfDescribingJson[] | undefined; /** * A context filter is a user-supplied callback that is evaluated for each event * to determine if the context associated with the filter should be attached to the event * @param args - - Object that contains: event, eventType, eventSchema */ type ContextFilter = (args?: ContextEvent) => boolean; /** * A context primitive is either a self-describing JSON or a context generator */ type ContextPrimitive = SelfDescribingJson | ContextGenerator; /** * A filter provider is a tuple that has two parts: a context filter and the context primitive(s) * If the context filter evaluates to true, the tracker will attach the context primitive(s) */ type FilterProvider = [ ContextFilter, Array<ContextPrimitive> | ContextPrimitive ]; /** * A ruleset has accept or reject properties that contain rules for matching Iglu schema URIs */ interface RuleSet { accept?: Array<string> | string; reject?: Array<string> | string; } /** * A ruleset provider is aa tuple that has two parts: a ruleset and the context primitive(s) * If the ruleset allows the current event schema URI, the tracker will attach the context primitive(s) */ type RuleSetProvider = [ RuleSet, Array<ContextPrimitive> | ContextPrimitive ]; /** * Conditional context providers are two element arrays used to decide when to attach contexts, where: * - the first element is some conditional criterion * - the second element is any number of context primitives */ type ConditionalContextProvider = FilterProvider | RuleSetProvider; /** * A Dynamic context is an array of Self Describing JSON contexts, or an array of callbacks which return Self Describing JSON contexts * The array can be a mix of both contexts and callbacks which generate contexts */ type DynamicContext = Array<SelfDescribingJson | ((...params: any[]) => SelfDescribingJson | null)>; interface GlobalContexts { /** * Returns all Context Primitives */ getGlobalPrimitives(): Array<ContextPrimitive>; /** * Returns all Conditional Contexts */ getConditionalProviders(): Array<ConditionalContextProvider>; /** * Adds conditional or primitive global contexts * @param contexts - An Array of either Conditional Contexts or Primitive Contexts */ addGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive> | Record<string, ConditionalContextProvider | ContextPrimitive>): void; /** * Removes all global contexts */ clearGlobalContexts(): void; /** * Removes previously added global context, performs a deep comparison of the contexts or conditional contexts * @param contexts - An Array of either Condition Contexts or Primitive Contexts */ removeGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive | string>): void; /** * Returns all applicable global contexts for a specified event * @param event - The event to check for applicable global contexts for */ getApplicableContexts(event: PayloadBuilder): Array<SelfDescribingJson>; } /** * Contains helper functions to aid in the addition and removal of Global Contexts */ declare function globalContexts(): GlobalContexts; interface PluginContexts { /** * Returns list of contexts from all active plugins */ addPluginContexts: <T = Record<string, unknown>>(additionalContexts?: SelfDescribingJson<T>[] | null) => SelfDescribingJson[]; } declare function pluginContexts(plugins: Array<CorePlugin>): PluginContexts; /** * Find dynamic context generating functions and return their results to be merged into the static contexts * Combine an array of unchanging contexts with the result of a context-creating function * * @param dynamicOrStaticContexts - Array of custom context Objects or custom context generating functions * @param Parameters - to pass to dynamic context callbacks * @returns An array of Self Describing JSON context */ declare function resolveDynamicContext(dynamicOrStaticContexts?: DynamicContext | null, ...extraParams: any[]): Array<SelfDescribingJson>; /** * Slices a schema into its composite parts. Useful for ruleset filtering. * @param input - A schema string * @returns The vendor, schema name, major, minor and patch information of a schema string */ declare function getSchemaParts(input: string): Array<string> | undefined; /** * Validates the vendor section of a schema string contains allowed wildcard values * @param parts - Array of parts from a schema string * @returns Whether the vendor validation parts are a valid combination */ declare function validateVendorParts(parts: Array<string>): boolean; /** * Validates the vendor part of a schema string is valid for a rule set * @param input - Vendor part of a schema string * @returns Whether the vendor validation string is valid */ declare function validateVendor(input: string): boolean; /** * Checks for validity of input and returns all the sections of a schema string that are used to match rules in a ruleset * @param input - A Schema string * @returns The sections of a schema string that are used to match rules in a ruleset */ declare function getRuleParts(input: string): Array<string> | undefined; /** * Ensures the rules specified in a schema string of a ruleset are valid * @param input - A Schema string * @returns if there rule is valid */ declare function isValidRule(input: string): boolean; /** * Check if a variable is an Array containing only strings * @param input - The variable to validate * @returns True if the input is an array containing only strings */ declare function isStringArray(input: unknown): input is Array<string>; /** * Validates whether a rule set is an array of valid ruleset strings * @param input - The Array of rule set arguments * @returns True is the input is an array of valid rules */ declare function isValidRuleSetArg(input: unknown): boolean; /** * Check if a variable is a valid, non-empty Self Describing JSON * @param input - The variable to validate * @returns True if a valid Self Describing JSON */ declare function isSelfDescribingJson(input: unknown): input is SelfDescribingJson; /** * Validates if the input object contains the expected properties of a ruleset * @param input - The object containing a rule set * @returns True if a valid rule set */ declare function isRuleSet(input: unknown): input is Record<string, unknown>; /** * Validates if the function can be a valid context generator function * @param input - The function to be validated */ declare function isContextCallbackFunction(input: unknown): boolean; /** * Validates if the function can be a valid context primitive function or self describing json * @param input - The function or orbject to be validated * @returns True if either a Context Generator or Self Describing JSON */ declare function isContextPrimitive(input: unknown): input is ContextPrimitive; /** * Validates if an array is a valid shape to be a Filter Provider * @param input - The Array of Context filter callbacks */ declare function isFilterProvider(input: unknown): boolean; /** * Validates if an array is a valid shape to be an array of rule sets * @param input - The Array of Rule Sets */ declare function isRuleSetProvider(input: unknown): boolean; /** * Checks if an input array is either a filter provider or a rule set provider * @param input - An array of filter providers or rule set providers * @returns Whether the array is a valid {@link ConditionalContextProvider} */ declare function isConditionalContextProvider(input: unknown): input is ConditionalContextProvider; /** * Checks if a given schema matches any rules within the provided rule set * @param ruleSet - The rule set containing rules to match schema against * @param schema - The schema to be matched against the rule set */ declare function matchSchemaAgainstRuleSet(ruleSet: RuleSet, schema: string): boolean; /** * Checks if a given schema matches a specific rule from a rule set * @param rule - The rule to match schema against * @param schema - The schema to be matched against the rule */ declare function matchSchemaAgainstRule(rule: string, schema: string): boolean; interface EventStorePayload { /** * The event payload to be stored */ payload: Payload; /** * If the request should undergo server anonymization. * @defaultValue false */ svrAnon?: boolean; } /** * Create a new EventStorePayload */ declare function newEventStorePayload({ payload, svrAnon }: EventStorePayload): EventStorePayload; /** * Result of the next operation on an EventStoreIterator. */ interface EventStoreIteratorNextResult { /** * The next event in the store, or undefined if there are no more events. */ value: EventStorePayload | undefined; /** * True if there are no more events in the store. */ done: boolean; } /** * EventStoreIterator allows iterating over all events in the store. */ interface EventStoreIterator { /** * Retrieve the next event in the store */ next: () => Promise<EventStoreIteratorNextResult>; } /** * EventStore allows storing and retrieving events before they are sent to the collector */ interface EventStore { /** * Count all events in the store */ count: () => Promise<number>; /** * Add an event to the store * @returns the number of events in the store after adding */ add: (payload: EventStorePayload) => Promise<number>; /** * Remove the first `count` events from the store */ removeHead: (count: number) => Promise<void>; /** * Get an iterator over all events in the store */ iterator: () => EventStoreIterator; /** * Retrieve all payloads including their meta configuration in the store */ getAll: () => Promise<readonly EventStorePayload[]>; /** * Retrieve all pure payloads in the store */ getAllPayloads: () => Promise<readonly Payload[]>; } interface EventStoreConfiguration { /** * The maximum amount of events that will be buffered in the event store * * This is useful to ensure the Tracker doesn't fill the 5MB or 10MB available to * each website should the collector be unavailable due to lost connectivity. * Will drop old events once the limit is hit */ maxSize?: number; } interface InMemoryEventStoreConfiguration { /** * Initial events to add to the store */ events?: EventStorePayload[]; } declare function newInMemoryEventStore({ maxSize, events }: EventStoreConfiguration & InMemoryEventStoreConfiguration): EventStore; /** * A collection of event payloads which are sent to the collector. */ type EventBatch = Payload[]; /** * The data that will be available to the `onRequestFailure` callback */ type RequestFailure = { /** The batch of events that failed to send */ events: EventBatch; /** The status code of the failed request */ status?: number; /** The error message of the failed request */ message?: string; /** Whether the tracker will retry the request */ willRetry: boolean; }; /* The supported methods which events can be sent with */ type EventMethod = "post" | "get"; interface EmitterConfigurationBase { /** * The preferred technique to use to send events * @defaultValue post */ eventMethod?: EventMethod; /** * The post path which events will be sent to. * Ensure your collector is configured to accept events on this post path * @defaultValue '/com.snowplowanalytics.snowplow/tp2' */ postPath?: string; /** * The amount of events that should be buffered before sending * Recommended to leave as 1 to reduce change of losing events * @defaultValue 1 on Web, 10 on Node */ bufferSize?: number; /** * The max size a POST request can be before the tracker will force send it * Also dictates the max size of a POST request before a batch of events is split into multiple requests * @defaultValue 40000 */ maxPostBytes?: number; /** * The max size a GET request (its complete URL) can be. Requests over this size will be tried as a POST request. * @defaultValue unlimited */ maxGetBytes?: number; /** * Should the Sent Timestamp be attached to events. * Only applies for GET events. * @defaultValue true */ useStm?: boolean; /** * How long to wait before aborting requests to the collector * @defaultValue 5000 (milliseconds) */ connectionTimeout?: number; /** * An object of key value pairs which represent headers to * attach when sending a POST request, only works for POST * @defaultValue `{}` */ customHeaders?: Record<string, string>; /** * Controls whether or not the browser sends credentials (defaults to 'include') * @defaultValue 'include' */ credentials?: "omit" | "same-origin" | "include"; /** * Whether to retry failed requests to the collector. * * Failed requests are requests that failed due to * [timeouts](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout_event), * [network errors](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/error_event), * and [abort events](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort_event). * * Takes precedent over `retryStatusCodes` and `dontRetryStatusCodes`. * * @defaultValue true */ retryFailedRequests?: boolean; /** * List of HTTP response status codes for which events sent to Collector should be retried in future requests. * Only non-success status codes are considered (greater or equal to 300). * The retry codes are only considered for GET and POST requests. * They take priority over the `dontRetryStatusCodes` option. * By default, the tracker retries on all non-success status codes except for 400, 401, 403, 410, and 422. */ retryStatusCodes?: number[]; /** * List of HTTP response status codes for which events sent to Collector should not be retried in future request. * Only non-success status codes are considered (greater or equal to 300). * The don't retry codes are only considered for GET and POST requests. * By default, the tracker retries on all non-success status codes except for 400, 401, 403, 410, and 422 (these don't retry codes will remain even if you set your own `dontRetryStatusCodes` but can be changed using the `retryStatusCodes`). */ dontRetryStatusCodes?: number[]; /** * Id service full URL. This URL will be added to the queue and will be called using a GET method. * This option is there to allow the service URL to be called in order to set any required identifiers e.g. extra cookies. * * The request respects the `anonymousTracking` option, including the SP-Anonymous header if needed, and any additional custom headers from the customHeaders option. */ idService?: string; /** * Indicates that the request should be allowed to outlive the webpage that initiated it. * Enables collector requests to complete even if the page is closed or navigated away from. * Note: Browsers put a limit on keepalive requests of 64KB. In case of multiple keepalive requests in parallel (may happen in case of multiple trackers), the limit is shared. * @defaultValue false */ keepalive?: boolean; /** * Enables overriding the default fetch function with a custom implementation. * @param input - Instance of Request * @param options - Additional options for the request * @returns A Promise that resolves to the Response. */ customFetch?: (input: Request, options?: RequestInit) => Promise<Response>; /** * A callback function to be executed whenever a request is successfully sent to the collector. * In practice this means any request which returns a 2xx status code will trigger this callback. * * @param data - The event batch that was successfully sent */ onRequestSuccess?: (data: EventBatch, response: Response) => void; /** * A callback function to be executed whenever a request fails to be sent to the collector. * This is the inverse of the onRequestSuccess callback, so any non 2xx st