From 6bb174011ec12bb196ca89a57234b99c6f09026b Mon Sep 17 00:00:00 2001 From: Alexander Sapountzis Date: Fri, 20 Mar 2026 16:23:07 -0400 Subject: [PATCH 1/5] feat: migrate reporting service contract from logging to reporting module - Define IErrorReportingService, ILoggingService, ISDKError, ISDKLogEntry contracts - Add ErrorReportingDispatcher and LoggingDispatcher for multi-service fan-out - Decouple Logger from reporting (console-only now) - Remove concrete ReportingLogger implementation (moves to kit) - Remove Rokt-specific URLs from constants - Rename src/logging/ to src/reporting/ - Expose registerErrorReportingService/registerLoggingService on mParticle API --- src/constants.ts | 4 - src/identityApiClient.ts | 13 +- src/logger.ts | 15 +- src/logging/reportingLogger.ts | 192 ---------- src/mp-instance.ts | 34 +- src/mparticle-instance-manager.ts | 6 + src/reporting/errorReportingDispatcher.ts | 13 + src/reporting/loggingDispatcher.ts | 13 + src/{logging => reporting}/types.ts | 31 +- src/sdkRuntimeModels.ts | 4 +- src/store.ts | 4 +- test/jest/logger.spec.ts | 66 +--- test/jest/logging-integration.spec.ts | 298 ++++----------- test/jest/reportingLogger.spec.ts | 418 +++++----------------- test/src/tests-store.ts | 10 +- 15 files changed, 257 insertions(+), 864 deletions(-) delete mode 100644 src/logging/reportingLogger.ts create mode 100644 src/reporting/errorReportingDispatcher.ts create mode 100644 src/reporting/loggingDispatcher.ts rename src/{logging => reporting}/types.ts (52%) diff --git a/src/constants.ts b/src/constants.ts index 3072e9bee..bf513a5d1 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -139,8 +139,6 @@ const Constants = { identityUrl: 'identity.mparticle.com/v1/', aliasUrl: 'jssdks.mparticle.com/v1/identity/', userAudienceUrl: 'nativesdks.mparticle.com/v1/', - loggingUrl: 'apps.rokt-api.com/v1/log', - errorUrl: 'apps.rokt-api.com/v1/errors', }, // These are the paths that are used to construct the CNAME urls CNAMEUrlPaths: { @@ -150,8 +148,6 @@ const Constants = { configUrl: '/tags/JS/v2/', identityUrl: '/identity/v1/', aliasUrl: '/webevents/v1/identity/', - loggingUrl: '/v1/log', - errorUrl: '/v1/errors', }, Base64CookieKeys: { csm: 1, diff --git a/src/identityApiClient.ts b/src/identityApiClient.ts index 70387259b..fc5c58522 100644 --- a/src/identityApiClient.ts +++ b/src/identityApiClient.ts @@ -25,7 +25,7 @@ import { IIdentityResponse, } from './identity-user-interfaces'; import { IMParticleWebSDKInstance } from './mp-instance'; -import { ErrorCodes } from './logging/types'; +import { ErrorCodes, WSDKErrorSeverity } from './reporting/types'; const { HTTPCodes, Messages, IdentityMethods } = Constants; @@ -329,10 +329,13 @@ export default function IdentityAPIClient( } const errorMessage = (err as Error).message || err.toString(); - Logger.error( - 'Error sending identity request to servers' + ' - ' + errorMessage, - ErrorCodes.IDENTITY_REQUEST - ); + const msg = 'Error sending identity request to servers' + ' - ' + errorMessage; + Logger.error(msg); + mpInstance._ErrorReportingDispatcher.report({ + message: msg, + code: ErrorCodes.IDENTITY_REQUEST, + severity: WSDKErrorSeverity.ERROR, + }); mpInstance.processQueueOnIdentityFailure?.(); invokeCallback(callback, HTTPCodes.noHttpCoverage, errorMessage); diff --git a/src/logger.ts b/src/logger.ts index 82af753dd..02800a83e 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,6 +1,4 @@ import { LogLevelType, SDKInitConfig, SDKLoggerApi } from './sdkRuntimeModels'; -import { ReportingLogger } from './logging/reportingLogger'; -import { ErrorCodes } from './logging/types'; export type ILoggerConfig = Pick; export type IConsoleLogger = Partial>; @@ -8,18 +6,14 @@ export type IConsoleLogger = Partial { - console.error('ReportingLogger: Failed to send log', error); - }); - } catch (error) { - console.error('ReportingLogger: Failed to send log', error); - } - } - - private sendLog(severity: WSDKErrorSeverity, msg: string, code?: ErrorCodes, stackTrace?: string): void { - this.sendToServer(this.loggingUrl, severity, msg, code, stackTrace); - } - - private sendError(severity: WSDKErrorSeverity, msg: string, code?: ErrorCodes, stackTrace?: string): void { - this.sendToServer(this.errorUrl, severity, msg, code, stackTrace); - } - - private buildLogRequest(severity: WSDKErrorSeverity, msg: string, code?: ErrorCodes, stackTrace?: string): LogRequestBody { - return { - additionalInformation: { - message: msg, - version: this.getVersion(), - }, - severity: severity, - code: code ?? ErrorCodes.UNKNOWN_ERROR, - url: this.getUrl(), - deviceInfo: this.getUserAgent(), - stackTrace: stackTrace, - reporter: this.reporter, - // Integration will be set to integrationName once the kit connects via RoktManager.attachKit() - integration: this.store?.getIntegrationName() ?? 'mp-wsdk' - }; - } - - private getVersion(): string { - return this.store?.getIntegrationName?.() ?? `mParticle_wsdkv_${this.sdkVersion}`; - } - - private isReportingEnabled(): boolean { - return this.isDebugModeEnabled() || - (this.isRoktDomainPresent() && this.isFeatureFlagEnabled()); - } - - private isRoktDomainPresent(): boolean { - return typeof window !== 'undefined' && Boolean(window['ROKT_DOMAIN']); - } - - private isFeatureFlagEnabled = (): boolean => this.isLoggingEnabled; - - private isDebugModeEnabled(): boolean { - return ( - typeof window !== 'undefined' && - (window. - location?. - search?. - toLowerCase()?. - includes('mp_enable_logging=true') ?? false) - ); - } - - private canSendLog(severity: WSDKErrorSeverity): boolean { - return this.isEnabled && !this.isRateLimited(severity); - } - - private isRateLimited(severity: WSDKErrorSeverity): boolean { - return this.rateLimiter.incrementAndCheck(severity); - } - - private getUrl(): string | undefined { - return typeof window !== 'undefined' ? window.location?.href : undefined; - } - - private getUserAgent(): string | undefined { - return typeof window !== 'undefined' ? window.navigator?.userAgent : undefined; - } - - private getHeaders(): IReportingLoggerPayload['headers'] { - const headers: IReportingLoggerPayload['headers'] = { - [HEADER_ACCEPT]: 'text/plain;charset=UTF-8', - [HEADER_CONTENT_TYPE]: 'application/json', - [HEADER_ROKT_LAUNCHER_VERSION]: this.getVersion(), - [HEADER_ROKT_WSDK_VERSION]: 'joint', - }; - - if (this.launcherInstanceGuid) { - headers[HEADER_ROKT_LAUNCHER_INSTANCE_GUID] = this.launcherInstanceGuid; - } - - const accountId = this.store?.getRoktAccountId?.(); - if (accountId) { - headers['rokt-account-id'] = accountId; - } - - return headers; - } -} - -export interface IRateLimiter { - incrementAndCheck(severity: WSDKErrorSeverity): boolean; -} - -export class RateLimiter implements IRateLimiter { - private readonly rateLimits: Map = new Map([ - [WSDKErrorSeverity.ERROR, 10], - [WSDKErrorSeverity.WARNING, 10], - [WSDKErrorSeverity.INFO, 10], - ]); - private logCount: Map = new Map(); - - public incrementAndCheck(severity: WSDKErrorSeverity): boolean { - const count = this.logCount.get(severity) || 0; - const limit = this.rateLimits.get(severity) || 10; - - const newCount = count + 1; - this.logCount.set(severity, newCount); - - return newCount > limit; - } -} diff --git a/src/mp-instance.ts b/src/mp-instance.ts index 24f31333f..48ea45bed 100644 --- a/src/mp-instance.ts +++ b/src/mp-instance.ts @@ -52,7 +52,9 @@ import ForegroundTimer from './foregroundTimeTracker'; import RoktManager, { IRoktOptions } from './roktManager'; import filteredMparticleUser from './filteredMparticleUser'; import CookieConsentManager, { ICookieConsentManager } from './cookieConsentManager'; -import { ReportingLogger } from './logging/reportingLogger'; +import { ErrorReportingDispatcher } from './reporting/errorReportingDispatcher'; +import { LoggingDispatcher } from './reporting/loggingDispatcher'; +import { IErrorReportingService, ILoggingService } from './reporting/types'; export interface IErrorLogMessage { message?: string; @@ -85,7 +87,8 @@ export interface IMParticleWebSDKInstance extends MParticleWebSDK { _NativeSdkHelpers: INativeSdkHelpers; _Persistence: IPersistence; _CookieConsentManager: ICookieConsentManager; - _ReportingLogger: ReportingLogger; + _ErrorReportingDispatcher: ErrorReportingDispatcher; + _LoggingDispatcher: LoggingDispatcher; _RoktManager: RoktManager; _SessionManager: ISessionManager; _ServerModel: IServerModel; @@ -266,14 +269,14 @@ export default function mParticleInstance(this: IMParticleWebSDKInstance, instan } }; - this._resetForTests = function(config, keepPersistence, instance, reportingLogger?: ReportingLogger) { + this._resetForTests = function(config, keepPersistence, instance) { if (instance._Store) { delete instance._Store; } - instance.Logger = new Logger(config, reportingLogger); + instance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); + instance._LoggingDispatcher = new LoggingDispatcher(); + instance.Logger = new Logger(config); instance._Store = new Store(config, instance); - // Update ReportingLogger with the new Store reference to avoid stale data - reportingLogger?.setStore(instance._Store); instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability( window.localStorage ); @@ -1406,6 +1409,14 @@ export default function mParticleInstance(this: IMParticleWebSDKInstance, instan } }; + this.registerErrorReportingService = function(service: IErrorReportingService) { + self._ErrorReportingDispatcher.register(service); + }; + + this.registerLoggingService = function(service: ILoggingService) { + self._LoggingDispatcher.register(service); + }; + const launcherInstanceGuidKey = Constants.Rokt.LauncherInstanceGuidKey; this.setLauncherInstanceGuid = function() { if (!window[launcherInstanceGuidKey] @@ -1630,16 +1641,11 @@ function createIdentityCache(mpInstance) { } function runPreConfigFetchInitialization(mpInstance, apiKey, config) { - mpInstance._ReportingLogger = new ReportingLogger( - config, - Constants.sdkVersion, - undefined, - mpInstance.getLauncherInstanceGuid(), - ); - mpInstance.Logger = new Logger(config, mpInstance._ReportingLogger); + mpInstance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); + mpInstance._LoggingDispatcher = new LoggingDispatcher(); + mpInstance.Logger = new Logger(config); mpInstance._Store = new Store(config, mpInstance, apiKey); window.mParticle.Store = mpInstance._Store; - mpInstance._ReportingLogger.setStore(mpInstance._Store); mpInstance.Logger.verbose(StartingInitialization); // Initialize CookieConsentManager with privacy flags from launcherOptions diff --git a/src/mparticle-instance-manager.ts b/src/mparticle-instance-manager.ts index ab7fceff7..4b5b1ff75 100644 --- a/src/mparticle-instance-manager.ts +++ b/src/mparticle-instance-manager.ts @@ -487,6 +487,12 @@ function mParticleInstanceManager(this: IMParticleInstanceManager) { this._setWrapperSDKInfo = function(name, version) { self.getInstance()._setWrapperSDKInfo(name, version); }; + this.registerErrorReportingService = function(service) { + self.getInstance().registerErrorReportingService(service); + }; + this.registerLoggingService = function(service) { + self.getInstance().registerLoggingService(service); + }; } const mParticleManager = new mParticleInstanceManager(); diff --git a/src/reporting/errorReportingDispatcher.ts b/src/reporting/errorReportingDispatcher.ts new file mode 100644 index 000000000..afe60f866 --- /dev/null +++ b/src/reporting/errorReportingDispatcher.ts @@ -0,0 +1,13 @@ +import { IErrorReportingService, ISDKError } from './types'; + +export class ErrorReportingDispatcher implements IErrorReportingService { + private services: IErrorReportingService[] = []; + + public register(service: IErrorReportingService): void { + this.services.push(service); + } + + public report(error: ISDKError): void { + this.services.forEach(s => s.report(error)); + } +} diff --git a/src/reporting/loggingDispatcher.ts b/src/reporting/loggingDispatcher.ts new file mode 100644 index 000000000..d9e1d28e1 --- /dev/null +++ b/src/reporting/loggingDispatcher.ts @@ -0,0 +1,13 @@ +import { ILoggingService, ISDKLogEntry } from './types'; + +export class LoggingDispatcher implements ILoggingService { + private services: ILoggingService[] = []; + + public register(service: ILoggingService): void { + this.services.push(service); + } + + public log(entry: ISDKLogEntry): void { + this.services.forEach(s => s.log(entry)); + } +} diff --git a/src/logging/types.ts b/src/reporting/types.ts similarity index 52% rename from src/logging/types.ts rename to src/reporting/types.ts index 46c431158..a012cc98c 100644 --- a/src/logging/types.ts +++ b/src/reporting/types.ts @@ -18,15 +18,28 @@ export const WSDKErrorSeverity = { export type WSDKErrorSeverity = (typeof WSDKErrorSeverity)[keyof typeof WSDKErrorSeverity]; -export type ErrorsRequestBody = { - additionalInformation?: Record; - code: ErrorCode; +/** Structured error object for reporting. */ +export interface ISDKError { + message: string; + code?: ErrorCodes; severity: WSDKErrorSeverity; stackTrace?: string; - deviceInfo?: string; - integration?: string; - reporter?: string; - url?: string; -}; + additionalInformation?: Record; +} + +/** Structured log entry for informational logging. */ +export interface ISDKLogEntry { + message: string; + code?: ErrorCodes; + additionalInformation?: Record; +} + +/** Contract for error/warning reporting services. */ +export interface IErrorReportingService { + report(error: ISDKError): void; +} -export type LogRequestBody = ErrorsRequestBody; +/** Contract for informational logging services. */ +export interface ILoggingService { + log(entry: ISDKLogEntry): void; +} diff --git a/src/sdkRuntimeModels.ts b/src/sdkRuntimeModels.ts index da9c8952d..492964395 100644 --- a/src/sdkRuntimeModels.ts +++ b/src/sdkRuntimeModels.ts @@ -51,7 +51,7 @@ import { import Constants from './constants'; import RoktManager, { IRoktLauncherOptions } from './roktManager'; import { IConsoleLogger } from './logger'; -import { ErrorCodes } from './logging/types'; +import { ErrorCodes, IErrorReportingService, ILoggingService } from './reporting/types'; // TODO: Resolve this with version in @mparticle/web-sdk export type SDKEventCustomFlags = Dictionary; @@ -260,6 +260,8 @@ export interface MParticleWebSDK { ): void; getIntegrationAttributes(integrationModuleId: number): IntegrationAttribute; captureTiming(metricName: string): void; + registerErrorReportingService(service: IErrorReportingService): void; + registerLoggingService(service: ILoggingService): void; } // https://go.mparticle.com/work/SQDSDKS-4805 diff --git a/src/store.ts b/src/store.ts index 9c4fcc18f..504920ab1 100644 --- a/src/store.ts +++ b/src/store.ts @@ -96,8 +96,6 @@ export interface SDKConfig { webviewBridgeName?: string; workspaceToken?: string; requiredWebviewBridgeName?: string; - loggingUrl?: string; - errorUrl?: string; isLoggingEnabled?: boolean; } @@ -862,7 +860,7 @@ function processDirectBaseUrls( for (let baseUrlKey in defaultBaseUrls) { // Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. - if (baseUrlKey === 'configUrl' || baseUrlKey === 'loggingUrl' || baseUrlKey === 'errorUrl') { + if (baseUrlKey === 'configUrl') { directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; continue; diff --git a/test/jest/logger.spec.ts b/test/jest/logger.spec.ts index 6dce7fe1b..15f91fbe1 100644 --- a/test/jest/logger.spec.ts +++ b/test/jest/logger.spec.ts @@ -1,7 +1,5 @@ import { Logger, ConsoleLogger } from '../../src/logger'; import { LogLevelType } from '../../src/sdkRuntimeModels'; -import { ReportingLogger } from '../../src/logging/reportingLogger'; -import { ErrorCodes } from '../../src/logging/types'; describe('Logger', () => { let mockConsole: any; @@ -56,16 +54,16 @@ describe('Logger', () => { expect(mockConsole.error).not.toHaveBeenCalled(); }); - it('should only call error at error log level', () => { - logger = new Logger({ logLevel: LogLevelType.Error }); - - logger.verbose('message1'); - logger.warning('message2'); - logger.error('message3'); - - expect(mockConsole.info).not.toHaveBeenCalled(); - expect(mockConsole.warn).not.toHaveBeenCalled(); - expect(mockConsole.error).toHaveBeenCalledWith('message3'); + it('should only call error at error log level', () => { + logger = new Logger({ logLevel: LogLevelType.Error }); + + logger.verbose('message1'); + logger.warning('message2'); + logger.error('message3'); + + expect(mockConsole.info).not.toHaveBeenCalled(); + expect(mockConsole.warn).not.toHaveBeenCalled(); + expect(mockConsole.error).toHaveBeenCalledWith('message3'); }); it('should allow providing a custom logger', () => { @@ -106,44 +104,18 @@ describe('Logger', () => { expect(mockConsole.error).toHaveBeenCalledWith('c'); }); - describe('ReportingLogger integration', () => { - let mockReportingLogger: jest.Mocked; - - beforeEach(() => { - mockReportingLogger = { - error: jest.fn(), - warning: jest.fn(), - info: jest.fn(), - setStore: jest.fn(), - } as any; - }); - - it('should call reportingLogger.error when error is called with error code', () => { - logger = new Logger({ logLevel: LogLevelType.Verbose }, mockReportingLogger); - - logger.error('test error', ErrorCodes.UNHANDLED_EXCEPTION); - - expect(mockConsole.error).toHaveBeenCalledWith('test error'); - expect(mockReportingLogger.error).toHaveBeenCalledWith('test error', ErrorCodes.UNHANDLED_EXCEPTION); - }); - - it('should NOT call reportingLogger.error when error is called without error code', () => { - logger = new Logger({ logLevel: LogLevelType.Verbose }, mockReportingLogger); - - logger.error('test error'); - - expect(mockConsole.error).toHaveBeenCalledWith('test error'); - expect(mockReportingLogger.error).not.toHaveBeenCalled(); - }); + it('should have no reporting side effects from error()', () => { + // Logger.error() should only output to console, no reporting + const customLogger = { + error: jest.fn(), + }; - it('should NOT call reportingLogger when warning is called', () => { - logger = new Logger({ logLevel: LogLevelType.Verbose }, mockReportingLogger); + logger = new Logger({ logLevel: LogLevelType.Verbose, logger: customLogger }); - logger.warning('test warning'); + logger.error('test error'); - expect(mockConsole.warn).toHaveBeenCalledWith('test warning'); - expect(mockReportingLogger.warning).not.toHaveBeenCalled(); - }); + expect(customLogger.error).toHaveBeenCalledWith('test error'); + // No other side effects - Logger is purely console output }); }); diff --git a/test/jest/logging-integration.spec.ts b/test/jest/logging-integration.spec.ts index 7ba4e44e8..4eecfed28 100644 --- a/test/jest/logging-integration.spec.ts +++ b/test/jest/logging-integration.spec.ts @@ -1,250 +1,88 @@ import { Logger } from '../../src/logger'; -import { ReportingLogger } from '../../src/logging/reportingLogger'; -import { ErrorCodes } from '../../src/logging/types'; -import { IStore, SDKConfig } from '../../src/store'; +import { ErrorReportingDispatcher } from '../../src/reporting/errorReportingDispatcher'; +import { LoggingDispatcher } from '../../src/reporting/loggingDispatcher'; +import { ErrorCodes, WSDKErrorSeverity, IErrorReportingService, ILoggingService } from '../../src/reporting/types'; import { LogLevelType } from '../../src/sdkRuntimeModels'; describe('Logging Integration', () => { - let mockFetch: jest.Mock; - const loggingUrl = 'test-url.com/v1/log'; - const errorUrl = 'test-url.com/v1/errors'; - const sdkVersion = '1.2.3'; - const accountId = '9876543210'; - const integrationName = 'test-integration'; + describe('Logger is decoupled from reporting', () => { + it('Logger.error() does not trigger any reporting', () => { + const logger = new Logger({ logLevel: LogLevelType.Warning }); - beforeEach(() => { - mockFetch = jest.fn().mockResolvedValue({ ok: true }); - global.fetch = mockFetch; - - Object.defineProperty(window, 'location', { - writable: true, - value: { - href: 'https://example.com', - search: '' - } - }); - - Object.defineProperty(window, 'navigator', { - writable: true, - value: { userAgent: 'test-user-agent' } + // Logger.error() should only output to console - no reporting side effects + // This verifies the decoupling is complete + expect(() => logger.error('test error')).not.toThrow(); }); - Object.defineProperty(window, 'mParticle', { - writable: true, - value: { config: { isLoggingEnabled: true } } + it('Logger and ErrorReportingDispatcher work independently', () => { + const logger = new Logger({ logLevel: LogLevelType.Warning }); + const dispatcher = new ErrorReportingDispatcher(); + const mockService: IErrorReportingService = { report: jest.fn() }; + dispatcher.register(mockService); + + // Simulate the pattern from identityApiClient: separate Logger.error + dispatcher.report + const msg = 'Error sending identity request to servers - timeout'; + logger.error(msg); + dispatcher.report({ + message: msg, + code: ErrorCodes.IDENTITY_REQUEST, + severity: WSDKErrorSeverity.ERROR, + }); + + expect(mockService.report).toHaveBeenCalledTimes(1); + expect(mockService.report).toHaveBeenCalledWith({ + message: msg, + code: ErrorCodes.IDENTITY_REQUEST, + severity: WSDKErrorSeverity.ERROR, + }); }); - Object.defineProperty(window, 'ROKT_DOMAIN', { - writable: true, - value: 'test-domain' - }); - }); - - afterEach(() => { - jest.clearAllMocks(); - }); - - it('integrates Logger, ReportingLogger, and Store to send error with account ID and integration name', () => { - // Setup Store with account ID and integration name - const mockStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue(accountId), - getIntegrationName: jest.fn().mockReturnValue(integrationName) - }; - - // Create ReportingLogger with Store - const reportingLogger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-guid' - ); - - // Create Logger with ReportingLogger - const logger = new Logger( - { logLevel: LogLevelType.Warning }, - reportingLogger - ); - - // Log an error through the Logger - logger.error('Integration test error', ErrorCodes.UNHANDLED_EXCEPTION); - - // Verify the full flow - expect(mockFetch).toHaveBeenCalledTimes(1); - - const fetchCall = mockFetch.mock.calls[0]; - const fetchUrl = fetchCall[0]; - const fetchOptions = fetchCall[1]; - - // Verify URL - expect(fetchUrl).toBe(`https://${errorUrl}`); - - // Verify headers include Store data - expect(fetchOptions.headers['rokt-account-id']).toBe(accountId); - expect(fetchOptions.headers['rokt-launcher-version']).toBe(integrationName); - expect(fetchOptions.headers['rokt-launcher-instance-guid']).toBe('test-guid'); - - // Verify body includes correct data - const body = JSON.parse(fetchOptions.body); - expect(body.additionalInformation.message).toBe('Integration test error'); - expect(body.additionalInformation.version).toBe(integrationName); - expect(body.code).toBe(ErrorCodes.UNHANDLED_EXCEPTION); - expect(body.integration).toBe(integrationName); - expect(body.reporter).toBe('mp-wsdk'); - - // Verify Store methods were called - expect(mockStore.getRoktAccountId).toHaveBeenCalled(); - expect(mockStore.getIntegrationName).toHaveBeenCalled(); - }); - - it('does not send to ReportingLogger when error code is not provided', () => { - const mockStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue(accountId), - getIntegrationName: jest.fn().mockReturnValue(integrationName) - }; - - const reportingLogger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore - ); - - const logger = new Logger( - { logLevel: LogLevelType.Warning }, - reportingLogger - ); - - // Log error without error code - should not report to backend - logger.error('Console only error'); - - expect(mockFetch).not.toHaveBeenCalled(); - }); - - it('updates Store reference and uses new data after setStore is called', () => { - const initialStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue('initial-id'), - getIntegrationName: jest.fn().mockReturnValue('initial-integration') - }; - - const reportingLogger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - initialStore as IStore - ); + it('Logger and LoggingDispatcher work independently', () => { + const logger = new Logger({ logLevel: LogLevelType.Verbose }); + const dispatcher = new LoggingDispatcher(); + const mockService: ILoggingService = { log: jest.fn() }; + dispatcher.register(mockService); - const logger = new Logger( - { logLevel: LogLevelType.Warning }, - reportingLogger - ); + logger.verbose('Some verbose message'); + dispatcher.log({ + message: 'Some verbose message', + code: ErrorCodes.UNKNOWN_ERROR, + }); - // Update Store reference (simulating what happens in _resetForTests) - const newStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue('new-id'), - getIntegrationName: jest.fn().mockReturnValue('new-integration') - }; - - reportingLogger.setStore(newStore as IStore); - - // Log error - should use new Store data - logger.error('Test error', ErrorCodes.IDENTITY_REQUEST); - - expect(mockFetch).toHaveBeenCalledTimes(1); - - const fetchCall = mockFetch.mock.calls[0]; - const fetchOptions = fetchCall[1]; - - // Verify new Store data is used - expect(fetchOptions.headers['rokt-account-id']).toBe('new-id'); - expect(fetchOptions.headers['rokt-launcher-version']).toBe('new-integration'); - - const body = JSON.parse(fetchOptions.body); - expect(body.additionalInformation.version).toBe('new-integration'); - expect(body.integration).toBe('new-integration'); - - // Verify new Store was called, not the old one - expect(newStore.getRoktAccountId).toHaveBeenCalled(); - expect(newStore.getIntegrationName).toHaveBeenCalled(); - expect(initialStore.getRoktAccountId).not.toHaveBeenCalled(); - }); - - it('sends info logs to loggingUrl instead of errorUrl', () => { - const mockStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue(accountId), - getIntegrationName: jest.fn().mockReturnValue(integrationName) - }; - - const reportingLogger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore - ); - - // Call info directly on ReportingLogger - reportingLogger.info('Info message', ErrorCodes.IDENTITY_REQUEST); - - expect(mockFetch).toHaveBeenCalledTimes(1); - - const fetchCall = mockFetch.mock.calls[0]; - const fetchUrl = fetchCall[0]; - - // Verify it goes to loggingUrl, not errorUrl - expect(fetchUrl).toBe(`https://${loggingUrl}`); - expect(fetchUrl).not.toContain('errors'); - }); - - it('respects LogLevel settings in Logger', () => { - const mockStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue(accountId), - getIntegrationName: jest.fn().mockReturnValue(integrationName) - }; - - const reportingLogger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore - ); - - // Set LogLevel to None - should not log anything - const logger = new Logger( - { logLevel: LogLevelType.None }, - reportingLogger - ); - - logger.error('Should not log', ErrorCodes.UNHANDLED_EXCEPTION); - - expect(mockFetch).not.toHaveBeenCalled(); - }); - - it('uses default values when Store methods return null', () => { - const mockStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue(null), - getIntegrationName: jest.fn().mockReturnValue(null) - }; - - const reportingLogger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore - ); + expect(mockService.log).toHaveBeenCalledTimes(1); + }); - const logger = new Logger( - { logLevel: LogLevelType.Warning }, - reportingLogger - ); + it('Dispatchers with no registered services are safe no-ops', () => { + const errorDispatcher = new ErrorReportingDispatcher(); + const loggingDispatcher = new LoggingDispatcher(); - logger.error('Test error', ErrorCodes.UNHANDLED_EXCEPTION); + expect(() => errorDispatcher.report({ + message: 'test', + severity: WSDKErrorSeverity.ERROR, + })).not.toThrow(); - expect(mockFetch).toHaveBeenCalledTimes(1); + expect(() => loggingDispatcher.log({ + message: 'test', + })).not.toThrow(); + }); - const fetchCall = mockFetch.mock.calls[0]; - const fetchOptions = fetchCall[1]; + it('Multiple services receive reports from ErrorReportingDispatcher', () => { + const dispatcher = new ErrorReportingDispatcher(); + const service1: IErrorReportingService = { report: jest.fn() }; + const service2: IErrorReportingService = { report: jest.fn() }; - // Verify rokt-account-id header is not present - expect(fetchOptions.headers['rokt-account-id']).toBeUndefined(); + dispatcher.register(service1); + dispatcher.register(service2); - // Verify default integration name is used - expect(fetchOptions.headers['rokt-launcher-version']).toBe(`mParticle_wsdkv_${sdkVersion}`); + const error = { + message: 'test', + severity: WSDKErrorSeverity.ERROR as WSDKErrorSeverity, + code: ErrorCodes.UNHANDLED_EXCEPTION as ErrorCodes, + }; + dispatcher.report(error); - const body = JSON.parse(fetchOptions.body); - expect(body.integration).toBe('mp-wsdk'); + expect(service1.report).toHaveBeenCalledWith(error); + expect(service2.report).toHaveBeenCalledWith(error); + }); }); }); diff --git a/test/jest/reportingLogger.spec.ts b/test/jest/reportingLogger.spec.ts index 3d02f8bd7..acc1a5551 100644 --- a/test/jest/reportingLogger.spec.ts +++ b/test/jest/reportingLogger.spec.ts @@ -1,384 +1,126 @@ -import { IRateLimiter, RateLimiter, ReportingLogger } from '../../src/logging/reportingLogger'; -import { WSDKErrorSeverity, ErrorCodes } from '../../src/logging/types'; -import { IStore, SDKConfig } from '../../src/store'; +import { ErrorReportingDispatcher } from '../../src/reporting/errorReportingDispatcher'; +import { LoggingDispatcher } from '../../src/reporting/loggingDispatcher'; +import { IErrorReportingService, ILoggingService, ISDKError, ISDKLogEntry, WSDKErrorSeverity, ErrorCodes } from '../../src/reporting/types'; -describe('ReportingLogger', () => { - let logger: ReportingLogger; - const loggingUrl = 'test-url.com/v1/log'; - const errorUrl = 'test-url.com/v1/errors'; - const sdkVersion = '1.2.3'; - let mockFetch: jest.Mock; - const accountId = '1234567890'; - let mockStore: Partial; +describe('ErrorReportingDispatcher', () => { + let dispatcher: ErrorReportingDispatcher; beforeEach(() => { - mockFetch = jest.fn().mockResolvedValue({ ok: true }); - global.fetch = mockFetch; - - mockStore = { - getRoktAccountId: jest.fn().mockReturnValue(null), - getIntegrationName: jest.fn().mockReturnValue(null) - }; - - Object.defineProperty(window, 'location', { - writable: true, - value: { - href: 'https://e.com', - search: '' - } - }); - - Object.defineProperty(window, 'navigator', { - writable: true, - value: { userAgent: 'ua' } - }); - - Object.defineProperty(window, 'mParticle', { - writable: true, - value: { config: { isLoggingEnabled: true } } - }); - - Object.defineProperty(window, 'ROKT_DOMAIN', { - writable: true, - value: 'set' - }); - - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid' - ); + dispatcher = new ErrorReportingDispatcher(); }); - afterEach(() => { - jest.clearAllMocks(); - }); - - it('sends error logs with correct params', () => { - logger.error('msg', ErrorCodes.UNHANDLED_EXCEPTION, 'stack'); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[0]).toContain('/v1/errors'); - const body = JSON.parse(fetchCall[1].body); - expect(body).toMatchObject({ + it('report() is a no-op when no services are registered', () => { + // Should not throw + dispatcher.report({ + message: 'test', severity: WSDKErrorSeverity.ERROR, - code: ErrorCodes.UNHANDLED_EXCEPTION, - stackTrace: 'stack' - }); - }); - - it('sends warning logs with correct params', () => { - mockStore.getRoktAccountId = jest.fn().mockReturnValue(accountId); - logger.warning('warn', ErrorCodes.UNHANDLED_EXCEPTION); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[0]).toContain('/v1/errors'); - const body = JSON.parse(fetchCall[1].body); - expect(body).toMatchObject({ - severity: WSDKErrorSeverity.WARNING - }); - expect(fetchCall[1].headers['rokt-account-id']).toBe(accountId); - }); - - it('sends info logs to correct endpoint with correct params', () => { - logger.info('info message', ErrorCodes.UNHANDLED_EXCEPTION); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[0]).toContain('/v1/log'); - const body = JSON.parse(fetchCall[1].body); - expect(body).toMatchObject({ - severity: WSDKErrorSeverity.INFO, - code: ErrorCodes.UNHANDLED_EXCEPTION - }); - }); - - it('does not log if ROKT_DOMAIN missing', () => { - Object.defineProperty(window, 'ROKT_DOMAIN', { - writable: true, - value: undefined - }); - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid' - ); - logger.error('x'); - expect(mockFetch).not.toHaveBeenCalled(); - }); - - it('does not log if feature flag and debug mode off', () => { - Object.defineProperty(window, 'mParticle', { - writable: true, - value: { config: { isLoggingEnabled: false } } - }); - Object.defineProperty(window, 'location', { - writable: true, - value: { href: 'https://e.com', search: '' } }); - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: false } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid' - ); - logger.error('x'); - expect(mockFetch).not.toHaveBeenCalled(); }); - it('logs if debug mode on even if feature flag off', () => { - Object.defineProperty(window, 'mParticle', { - writable: true, - value: { config: { isLoggingEnabled: false } } - }); - Object.defineProperty(window, 'location', { - writable: true, - value: { href: 'https://e.com', search: '?mp_enable_logging=true' } - }); - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: false } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid' - ); - logger.error('x'); - expect(mockFetch).toHaveBeenCalled(); - }); - - it('logs if debug mode on even without ROKT_DOMAIN', () => { - Object.defineProperty(window, 'ROKT_DOMAIN', { - writable: true, - value: undefined - }); - Object.defineProperty(window, 'location', { - writable: true, - value: { href: 'https://e.com', search: '?mp_enable_logging=true' } - }); - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: false } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid' - ); - logger.error('x'); - expect(mockFetch).toHaveBeenCalled(); - }); - - it('rate limits after 3 errors', () => { - let count = 0; - const mockRateLimiter: IRateLimiter = { - incrementAndCheck: jest.fn().mockImplementation((severity) => { - return ++count > 3; - }), + it('register() adds a service and report() fans out to it', () => { + const mockService: IErrorReportingService = { + report: jest.fn(), }; - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid', - mockRateLimiter - ); - for (let i = 0; i < 5; i++) logger.error('err'); - expect(mockFetch).toHaveBeenCalledTimes(3); - }); + dispatcher.register(mockService); - it('does not include account id header when account id is not set', () => { - logger.error('msg'); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[1].headers['rokt-account-id']).toBeUndefined(); - }); - - it('omits user agent and url fields when navigator/location are undefined', () => { - Object.defineProperty(window, 'navigator', { - writable: true, - value: undefined - }); - Object.defineProperty(window, 'location', { - writable: true, - value: undefined - }); - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore, - 'test-launcher-instance-guid' - ); - logger.error('msg'); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - const body = JSON.parse(fetchCall[1].body); - // undefined values are omitted from JSON.stringify, so these fields won't be present - expect(body).not.toHaveProperty('deviceInfo'); - expect(body).not.toHaveProperty('url'); - }); - - it('can set store after initialization', () => { - const loggerWithoutStore = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - undefined, - 'test-launcher-instance-guid' - ); - - const newMockStore: Partial = { - getRoktAccountId: jest.fn().mockReturnValue(accountId), - getIntegrationName: jest.fn().mockReturnValue('custom-integration-name') + const error: ISDKError = { + message: 'test error', + code: ErrorCodes.UNHANDLED_EXCEPTION, + severity: WSDKErrorSeverity.ERROR, + stackTrace: 'stack', }; - loggerWithoutStore.setStore(newMockStore as IStore); - loggerWithoutStore.error('test error'); + dispatcher.report(error); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[1].headers['rokt-account-id']).toBe(accountId); - expect(fetchCall[1].headers['rokt-launcher-version']).toBe('custom-integration-name'); + expect(mockService.report).toHaveBeenCalledTimes(1); + expect(mockService.report).toHaveBeenCalledWith(error); }); - it('catches and logs errors during upload', () => { - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - mockFetch.mockRejectedValueOnce(new Error('Network failure')); + it('report() fans out to all registered services', () => { + const service1: IErrorReportingService = { report: jest.fn() }; + const service2: IErrorReportingService = { report: jest.fn() }; + const service3: IErrorReportingService = { report: jest.fn() }; - logger.error('test error', ErrorCodes.UNHANDLED_EXCEPTION); + dispatcher.register(service1); + dispatcher.register(service2); + dispatcher.register(service3); - // Wait for the promise to resolve - return new Promise(resolve => setTimeout(resolve, 0)).then(() => { - expect(consoleErrorSpy).toHaveBeenCalledWith( - 'ReportingLogger: Failed to send log', - expect.any(Error) - ); - consoleErrorSpy.mockRestore(); - }); - }); - - it('omits rokt-launcher-instance-guid header when launcherInstanceGuid is undefined', () => { - logger = new ReportingLogger( - { loggingUrl, errorUrl, isLoggingEnabled: true } as SDKConfig, - sdkVersion, - mockStore as IStore, - undefined - ); + const error: ISDKError = { + message: 'broadcast error', + severity: WSDKErrorSeverity.WARNING, + }; - logger.error('test error'); + dispatcher.report(error); - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[1].headers['rokt-launcher-instance-guid']).toBeUndefined(); - expect(fetchCall[1].headers['rokt-launcher-version']).toBeDefined(); + expect(service1.report).toHaveBeenCalledWith(error); + expect(service2.report).toHaveBeenCalledWith(error); + expect(service3.report).toHaveBeenCalledWith(error); }); - it('includes all required headers', () => { - mockStore.getRoktAccountId = jest.fn().mockReturnValue(accountId); - mockStore.getIntegrationName = jest.fn().mockReturnValue('custom-integration'); + it('passes additionalInformation through to services', () => { + const mockService: IErrorReportingService = { report: jest.fn() }; + dispatcher.register(mockService); - logger.error('test error'); + const error: ISDKError = { + message: 'test', + severity: WSDKErrorSeverity.ERROR, + additionalInformation: { key: 'value' }, + }; - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - const headers = fetchCall[1].headers; + dispatcher.report(error); - expect(headers['Accept']).toBe('text/plain;charset=UTF-8'); - expect(headers['Content-Type']).toBe('application/json'); - expect(headers['rokt-launcher-instance-guid']).toBe('test-launcher-instance-guid'); - expect(headers['rokt-launcher-version']).toBe('custom-integration'); - expect(headers['rokt-wsdk-version']).toBe('joint'); - expect(headers['rokt-account-id']).toBe(accountId); + expect(mockService.report).toHaveBeenCalledWith(error); }); +}); - it('constructs full URL with https prefix', () => { - logger.error('test error'); +describe('LoggingDispatcher', () => { + let dispatcher: LoggingDispatcher; - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - expect(fetchCall[0]).toBe(`https://${errorUrl}`); + beforeEach(() => { + dispatcher = new LoggingDispatcher(); }); - it('includes all fields in log request body with custom integration name', () => { - mockStore.getIntegrationName = jest.fn().mockReturnValue('test-integration'); - - logger.error('error message', ErrorCodes.IDENTITY_REQUEST, 'stack trace here'); - - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - const body = JSON.parse(fetchCall[1].body); - - expect(body).toEqual({ - additionalInformation: { - message: 'error message', - version: 'test-integration' - }, - severity: WSDKErrorSeverity.ERROR, - code: ErrorCodes.IDENTITY_REQUEST, - url: 'https://e.com', - deviceInfo: 'ua', - stackTrace: 'stack trace here', - reporter: 'mp-wsdk', - integration: 'test-integration' + it('log() is a no-op when no services are registered', () => { + // Should not throw + dispatcher.log({ + message: 'test', }); }); - it('uses default mp-wsdk for integration when integration name is not set', () => { - mockStore.getIntegrationName = jest.fn().mockReturnValue(null); - - logger.error('error message', ErrorCodes.IDENTITY_REQUEST); - - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - const body = JSON.parse(fetchCall[1].body); + it('register() adds a service and log() fans out to it', () => { + const mockService: ILoggingService = { + log: jest.fn(), + }; - expect(body.reporter).toBe('mp-wsdk'); - expect(body.integration).toBe('mp-wsdk'); - expect(body.additionalInformation.version).toBe(`mParticle_wsdkv_${sdkVersion}`); - }); + dispatcher.register(mockService); - it('uses default error code when code is undefined', () => { - logger.error('test error'); + const entry: ISDKLogEntry = { + message: 'test log', + code: ErrorCodes.IDENTITY_REQUEST, + }; - expect(mockFetch).toHaveBeenCalled(); - const fetchCall = mockFetch.mock.calls[0]; - const body = JSON.parse(fetchCall[1].body); + dispatcher.log(entry); - expect(body.code).toBe(ErrorCodes.UNKNOWN_ERROR); + expect(mockService.log).toHaveBeenCalledTimes(1); + expect(mockService.log).toHaveBeenCalledWith(entry); }); -}); -describe('RateLimiter', () => { - let rateLimiter: RateLimiter; - beforeEach(() => { - rateLimiter = new RateLimiter(); - }); + it('log() fans out to all registered services', () => { + const service1: ILoggingService = { log: jest.fn() }; + const service2: ILoggingService = { log: jest.fn() }; - it('allows up to 10 error logs then rate limits', () => { - for (let i = 0; i < 10; i++) { - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.ERROR)).toBe(false); - } - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.ERROR)).toBe(true); - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.ERROR)).toBe(true); - }); + dispatcher.register(service1); + dispatcher.register(service2); - it('allows up to 10 warning logs then rate limits', () => { - for (let i = 0; i < 10; i++) { - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.WARNING)).toBe(false); - } - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.WARNING)).toBe(true); - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.WARNING)).toBe(true); - }); + const entry: ISDKLogEntry = { + message: 'broadcast log', + additionalInformation: { detail: 'info' }, + }; - it('allows up to 10 info logs then rate limits', () => { - for (let i = 0; i < 10; i++) { - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.INFO)).toBe(false); - } - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.INFO)).toBe(true); - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.INFO)).toBe(true); - }); + dispatcher.log(entry); - it('tracks rate limits independently per severity', () => { - for (let i = 0; i < 10; i++) { - rateLimiter.incrementAndCheck(WSDKErrorSeverity.ERROR); - } - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.ERROR)).toBe(true); - expect(rateLimiter.incrementAndCheck(WSDKErrorSeverity.WARNING)).toBe(false); + expect(service1.log).toHaveBeenCalledWith(entry); + expect(service2.log).toHaveBeenCalledWith(entry); }); }); diff --git a/test/src/tests-store.ts b/test/src/tests-store.ts index 3d2a2baa5..9528c75be 100644 --- a/test/src/tests-store.ts +++ b/test/src/tests-store.ts @@ -1678,15 +1678,13 @@ describe('Store', () => { v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/', v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/', v3SecureServiceUrl: 'foo.customer.mp.com/v3/JS/', - loggingUrl: 'apps.rokt-api.com/v1/log', - errorUrl: 'apps.rokt-api.com/v1/errors', }; expect(result).to.deep.equal(expectedResult); }); it('should append url paths to domain when config.domain is set', () => { - // This example assumes only the domain is set, and not any of the + // This example assumes only the domain is set, and not any of the // configurable URLs const config = { domain: 'custom.domain.com' @@ -1705,8 +1703,6 @@ describe('Store', () => { v1SecureServiceUrl: 'custom.domain.com/webevents/v1/JS/', v2SecureServiceUrl: 'custom.domain.com/webevents/v2/JS/', v3SecureServiceUrl: 'custom.domain.com/webevents/v3/JS/', - loggingUrl: 'custom.domain.com/v1/log', - errorUrl: 'custom.domain.com/v1/errors', }; expect(result).to.deep.equal(expectedResult); @@ -1739,8 +1735,6 @@ describe('Store', () => { v1SecureServiceUrl: 'custom.domain.com/webevents/v1/JS/', v2SecureServiceUrl: 'custom.domain.com/webevents/v2/JS/', v3SecureServiceUrl: 'custom.domain.com/webevents/v3/JS/', - loggingUrl: 'custom.domain.com/v1/log', - errorUrl: 'custom.domain.com/v1/errors', }; expect(result).to.deep.equal(expectedResult); @@ -1805,8 +1799,6 @@ describe('Store', () => { v1SecureServiceUrl: 'jssdks.us1.mparticle.com/v1/JS/', v2SecureServiceUrl: 'jssdks.us1.mparticle.com/v2/JS/', v3SecureServiceUrl: 'foo.customer.mp.com/v3/JS/', - loggingUrl: 'apps.rokt-api.com/v1/log', - errorUrl: 'apps.rokt-api.com/v1/errors', }; expect(result).to.deep.equal(expectedResult); From f8a0936bb2ab6ad6726db31a3dfd0c47221bdb95 Mon Sep 17 00:00:00 2001 From: Alexander Sapountzis Date: Fri, 20 Mar 2026 17:12:16 -0400 Subject: [PATCH 2/5] fix: resolve Karma test failures for reporting dispatcher migration - Add optional chaining for _ErrorReportingDispatcher in identityApiClient so tests without a mock dispatcher don't crash - Add registerErrorReportingService and registerLoggingService to the expected public API keys in instance manager test --- dist/mparticle.common.js | 24 +- dist/mparticle.esm.js | 24 +- dist/mparticle.js | 229 ++++++------------- src/identityApiClient.ts | 2 +- test/src/tests-mparticle-instance-manager.ts | 2 + 5 files changed, 95 insertions(+), 186 deletions(-) diff --git a/dist/mparticle.common.js b/dist/mparticle.common.js index f4769471f..a15e079ae 100644 --- a/dist/mparticle.common.js +++ b/dist/mparticle.common.js @@ -18,8 +18,8 @@ isArray:function isArray(a){return "[object Array]"===Object.prototype.toString. var version = "2.59.0"; var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally -},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/",loggingUrl:"apps.rokt-api.com/v1/log",errorUrl:"apps.rokt-api.com/v1/errors"},// These are the paths that are used to construct the CNAME urls -CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/",loggingUrl:"/v1/log",errorUrl:"/v1/errors"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 +},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls +CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI",// CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI // - 'True' → capture all integration-specific IDs // - 'False' → capture none @@ -626,9 +626,9 @@ if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);retu // us1, us2, eu1, au1, or st1, etc as new silos are added for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. -if("configUrl"==g||"loggingUrl"===g||"errorUrl"===g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} +if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} -var Logger=/** @class */function(){function a(a,b){var c,d;this.logLevel=null!==(c=a.logLevel)&&void 0!==c?c:LogLevelType.Warning,this.logger=null!==(d=a.logger)&&void 0!==d?d:new ConsoleLogger,this.reportingLogger=b;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a,b){var c;this.logLevel===LogLevelType.None||this.logger.error&&(this.logger.error(a),b&&(null===(c=this.reportingLogger)||void 0===c?void 0:c.error(a,b)));},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); +var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 // https://go.mparticle.com/work/SQDSDKS-6045 @@ -1421,7 +1421,7 @@ return [2/*return*/,b]}})})};} var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"}; -var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,z,m,A,m,z;return __generator(this,function(B){switch(B.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];p=g||null,q=this.getUploadUrl(c,g),r=window.fetch?new FetchUploader(q):new XHRUploader(q),s={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,B.label=1;case 1:return B.trys.push([1,9,,10]),[4/*yield*/,r.upload(s)];case 2:return t=B.sent(),u=void 0,v=void 0,w=t.status,w===HTTP_ACCEPTED?[3/*break*/,3]:w===HTTP_OK?[3/*break*/,3]:w===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return t.json?[4/*yield*/,t.json()]:[3/*break*/,5];case 4:return x=B.sent(),u=this.getIdentityResponseFromFetch(t,x),[3/*break*/,6];case 5:u=this.getIdentityResponseFromXHR(t),B.label=6;case 6:return u.status===HTTP_BAD_REQUEST?(y=u.responseText,v="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+u.status,(null===y||void 0===y?void 0:y.Errors)&&(z=y.Errors.map(function(a){return a.message}).join(", "),v+=" - "+z)):(v="Received Identity Response from server: ",v+=JSON.stringify(u.responseText)),[3/*break*/,8];case 7:{if(t.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+t.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,z="Received HTTP Code of "+t.status,o.error("Error sending identity request to servers - "+z),n(d,HTTPCodes$1.noHttpCoverage,z),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,o.verbose(v),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(u,p,d,e,c,h,!1),[3/*break*/,10];case 9:return A=B.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),z=A.message||A.toString(),o.error("Error sending identity request to servers - "+z,ErrorCodes.IDENTITY_REQUEST),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,z),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} +var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l,m;return __awaiter(this,void 0,void 0,function(){var n,o,p,q,r,s,t,u,v,w,x,y,z,A,A,n,B,n,A,C;return __generator(this,function(D){switch(D.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestStart"))),o=a._Helpers.invokeCallback,p=a.Logger,p.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return p.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(p.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return o(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];q=g||null,r=this.getUploadUrl(c,g),s=window.fetch?new FetchUploader(r):new XHRUploader(r),t={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,D.label=1;case 1:return D.trys.push([1,9,,10]),[4/*yield*/,s.upload(t)];case 2:return u=D.sent(),v=void 0,w=void 0,x=u.status,x===HTTP_ACCEPTED?[3/*break*/,3]:x===HTTP_OK?[3/*break*/,3]:x===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return u.json?[4/*yield*/,u.json()]:[3/*break*/,5];case 4:return y=D.sent(),v=this.getIdentityResponseFromFetch(u,y),[3/*break*/,6];case 5:v=this.getIdentityResponseFromXHR(u),D.label=6;case 6:return v.status===HTTP_BAD_REQUEST?(z=v.responseText,w="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+v.status,(null===z||void 0===z?void 0:z.Errors)&&(A=z.Errors.map(function(a){return a.message}).join(", "),w+=" - "+A)):(w="Received Identity Response from server: ",w+=JSON.stringify(v.responseText)),[3/*break*/,8];case 7:{if(u.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} // The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: // - version is always this prefix: fb @@ -1500,8 +1500,9 @@ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}} * Targeting is allowed when noTargeting is false (default). */return a.prototype.getNoTargeting=function(){return this.flags.noTargeting},a.prototype.getNoFunctional=function(){return this.flags.noFunctional},a}(); -var HEADER_ACCEPT="Accept",HEADER_CONTENT_TYPE="Content-Type",HEADER_ROKT_LAUNCHER_VERSION="rokt-launcher-version",HEADER_ROKT_LAUNCHER_INSTANCE_GUID="rokt-launcher-instance-guid",HEADER_ROKT_WSDK_VERSION="rokt-wsdk-version",ReportingLogger=/** @class */function(){function a(a,b,c,d,e){var f=this;this.sdkVersion=b,this.launcherInstanceGuid=d,this.reporter="mp-wsdk",this.isFeatureFlagEnabled=function(){return f.isLoggingEnabled},this.loggingUrl="https://".concat(a.loggingUrl||Constants.DefaultBaseUrls.loggingUrl),this.errorUrl="https://".concat(a.errorUrl||Constants.DefaultBaseUrls.errorUrl),this.isLoggingEnabled=a.isLoggingEnabled||!1,this.store=null!==c&&void 0!==c?c:null,this.isEnabled=this.isReportingEnabled(),this.rateLimiter=null!==e&&void 0!==e?e:new RateLimiter;}return a.prototype.setStore=function(a){this.store=a;},a.prototype.info=function(a,b){this.sendLog(WSDKErrorSeverity.INFO,a,b);},a.prototype.error=function(a,b,c){this.sendError(WSDKErrorSeverity.ERROR,a,b,c);},a.prototype.warning=function(a,b){this.sendError(WSDKErrorSeverity.WARNING,a,b);},a.prototype.sendToServer=function(a,b,c,d,e){if(this.canSendLog(b))try{var f=this.buildLogRequest(b,c,d,e),g=new FetchUploader(a),h={method:"POST",headers:this.getHeaders(),body:JSON.stringify(f)};g.upload(h)["catch"](function(a){console.error("ReportingLogger: Failed to send log",a);});}catch(a){console.error("ReportingLogger: Failed to send log",a);}},a.prototype.sendLog=function(a,b,c,d){this.sendToServer(this.loggingUrl,a,b,c,d);},a.prototype.sendError=function(a,b,c,d){this.sendToServer(this.errorUrl,a,b,c,d);},a.prototype.buildLogRequest=function(a,b,c,d){var e,f;return {additionalInformation:{message:b,version:this.getVersion()},severity:a,code:null!==c&&void 0!==c?c:ErrorCodes.UNKNOWN_ERROR,url:this.getUrl(),deviceInfo:this.getUserAgent(),stackTrace:d,reporter:this.reporter,// Integration will be set to integrationName once the kit connects via RoktManager.attachKit() -integration:null!==(f=null===(e=this.store)||void 0===e?void 0:e.getIntegrationName())&&void 0!==f?f:"mp-wsdk"}},a.prototype.getVersion=function(){var a,b,c;return null!==(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.getIntegrationName)||void 0===b?void 0:b.call(a))&&void 0!==c?c:"mParticle_wsdkv_".concat(this.sdkVersion)},a.prototype.isReportingEnabled=function(){return this.isDebugModeEnabled()||this.isRoktDomainPresent()&&this.isFeatureFlagEnabled()},a.prototype.isRoktDomainPresent=function(){return "undefined"!=typeof window&&!!window.ROKT_DOMAIN},a.prototype.isDebugModeEnabled=function(){var a,b,c,d;return "undefined"!=typeof window&&null!==(d=null===(c=null===(b=null===(a=window.location)||void 0===a?void 0:a.search)||void 0===b?void 0:b.toLowerCase())||void 0===c?void 0:c.includes("mp_enable_logging=true"))&&void 0!==d&&d},a.prototype.canSendLog=function(a){return this.isEnabled&&!this.isRateLimited(a)},a.prototype.isRateLimited=function(a){return this.rateLimiter.incrementAndCheck(a)},a.prototype.getUrl=function(){var a;return "undefined"==typeof window||null===(a=window.location)||void 0===a?void 0:a.href},a.prototype.getUserAgent=function(){var a;return "undefined"==typeof window||null===(a=window.navigator)||void 0===a?void 0:a.userAgent},a.prototype.getHeaders=function(){var a,b,c,d=(a={},a[HEADER_ACCEPT]="text/plain;charset=UTF-8",a[HEADER_CONTENT_TYPE]="application/json",a[HEADER_ROKT_LAUNCHER_VERSION]=this.getVersion(),a[HEADER_ROKT_WSDK_VERSION]="joint",a);this.launcherInstanceGuid&&(d[HEADER_ROKT_LAUNCHER_INSTANCE_GUID]=this.launcherInstanceGuid);var e=null===(c=null===(b=this.store)||void 0===b?void 0:b.getRoktAccountId)||void 0===c?void 0:c.call(b);return e&&(d["rokt-account-id"]=e),d},a}();var RateLimiter=/** @class */function(){function a(){this.rateLimits=new Map([[WSDKErrorSeverity.ERROR,10],[WSDKErrorSeverity.WARNING,10],[WSDKErrorSeverity.INFO,10]]),this.logCount=new Map;}return a.prototype.incrementAndCheck=function(a){var b=this.logCount.get(a)||0,c=this.rateLimits.get(a)||10,d=b+1;return this.logCount.set(a,d),d>c},a}(); +var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.report=function(a){this.services.forEach(function(b){return b.report(a)});},a}(); + +var LoggingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.log=function(a){this.services.forEach(function(b){return b.log(a)});},a}(); var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,CaptureIntegrationSpecificIdsV2Modes=Constants.CaptureIntegrationSpecificIdsV2Modes,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,CaptureIntegrationSpecificIdsV2=FeatureFlags.CaptureIntegrationSpecificIdsV2,StartingInitialization=Messages.InformationMessages.StartingInitialization;/** *

All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

@@ -1518,8 +1519,7 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Const this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization // Since fetching the configuration is asynchronous, we must pass completeSDKInitialization // to it for it to be run after fetched -if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c,d){// Update ReportingLogger with the new Store reference to avoid stale data -c._Store&&delete c._Store,c.Logger=new Logger(a,d),c._Store=new Store(a,c),null===d||void 0===d?void 0:d.setStore(c._Store),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval +if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** * Creates a CCPA Opt Out Consent State. * @@ -1671,7 +1671,7 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any // other integration delays set to true. It not, process the queued events/. -var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment +var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's // Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize @@ -1690,7 +1690,7 @@ function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan 3. Self hosting via /config endpoint (config.dataPlanResult) */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault // ensures no identity response data is written to localStorage when noFunctional is true -return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ReportingLogger=new ReportingLogger(c,Constants.sdkVersion,void 0,a.getLauncherInstanceGuid()),a.Logger=new Logger(c,a._ReportingLogger),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a._ReportingLogger.setStore(a._Store),a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions +return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs // since we will need this for the current implementation of user persistence // TODO: Refactor this when we refactor User Identity Persistence @@ -1716,6 +1716,6 @@ Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.protot * @param {String} apiKey your mParticle assigned API key * @param {Object} [config] an options object for additional configuration * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); + */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); module.exports = mParticleManager; diff --git a/dist/mparticle.esm.js b/dist/mparticle.esm.js index f6ad659d2..75a493c69 100644 --- a/dist/mparticle.esm.js +++ b/dist/mparticle.esm.js @@ -18,8 +18,8 @@ isArray:function isArray(a){return "[object Array]"===Object.prototype.toString. var version = "2.59.0"; var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally -},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/",loggingUrl:"apps.rokt-api.com/v1/log",errorUrl:"apps.rokt-api.com/v1/errors"},// These are the paths that are used to construct the CNAME urls -CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/",loggingUrl:"/v1/log",errorUrl:"/v1/errors"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 +},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls +CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI",// CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI // - 'True' → capture all integration-specific IDs // - 'False' → capture none @@ -626,9 +626,9 @@ if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);retu // us1, us2, eu1, au1, or st1, etc as new silos are added for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. -if("configUrl"==g||"loggingUrl"===g||"errorUrl"===g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} +if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} -var Logger=/** @class */function(){function a(a,b){var c,d;this.logLevel=null!==(c=a.logLevel)&&void 0!==c?c:LogLevelType.Warning,this.logger=null!==(d=a.logger)&&void 0!==d?d:new ConsoleLogger,this.reportingLogger=b;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a,b){var c;this.logLevel===LogLevelType.None||this.logger.error&&(this.logger.error(a),b&&(null===(c=this.reportingLogger)||void 0===c?void 0:c.error(a,b)));},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); +var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 // https://go.mparticle.com/work/SQDSDKS-6045 @@ -1421,7 +1421,7 @@ return [2/*return*/,b]}})})};} var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"}; -var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,z,m,A,m,z;return __generator(this,function(B){switch(B.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];p=g||null,q=this.getUploadUrl(c,g),r=window.fetch?new FetchUploader(q):new XHRUploader(q),s={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,B.label=1;case 1:return B.trys.push([1,9,,10]),[4/*yield*/,r.upload(s)];case 2:return t=B.sent(),u=void 0,v=void 0,w=t.status,w===HTTP_ACCEPTED?[3/*break*/,3]:w===HTTP_OK?[3/*break*/,3]:w===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return t.json?[4/*yield*/,t.json()]:[3/*break*/,5];case 4:return x=B.sent(),u=this.getIdentityResponseFromFetch(t,x),[3/*break*/,6];case 5:u=this.getIdentityResponseFromXHR(t),B.label=6;case 6:return u.status===HTTP_BAD_REQUEST?(y=u.responseText,v="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+u.status,(null===y||void 0===y?void 0:y.Errors)&&(z=y.Errors.map(function(a){return a.message}).join(", "),v+=" - "+z)):(v="Received Identity Response from server: ",v+=JSON.stringify(u.responseText)),[3/*break*/,8];case 7:{if(t.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+t.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,z="Received HTTP Code of "+t.status,o.error("Error sending identity request to servers - "+z),n(d,HTTPCodes$1.noHttpCoverage,z),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,o.verbose(v),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(u,p,d,e,c,h,!1),[3/*break*/,10];case 9:return A=B.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),z=A.message||A.toString(),o.error("Error sending identity request to servers - "+z,ErrorCodes.IDENTITY_REQUEST),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,z),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} +var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l,m;return __awaiter(this,void 0,void 0,function(){var n,o,p,q,r,s,t,u,v,w,x,y,z,A,A,n,B,n,A,C;return __generator(this,function(D){switch(D.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestStart"))),o=a._Helpers.invokeCallback,p=a.Logger,p.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return p.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(p.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return o(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];q=g||null,r=this.getUploadUrl(c,g),s=window.fetch?new FetchUploader(r):new XHRUploader(r),t={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,D.label=1;case 1:return D.trys.push([1,9,,10]),[4/*yield*/,s.upload(t)];case 2:return u=D.sent(),v=void 0,w=void 0,x=u.status,x===HTTP_ACCEPTED?[3/*break*/,3]:x===HTTP_OK?[3/*break*/,3]:x===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return u.json?[4/*yield*/,u.json()]:[3/*break*/,5];case 4:return y=D.sent(),v=this.getIdentityResponseFromFetch(u,y),[3/*break*/,6];case 5:v=this.getIdentityResponseFromXHR(u),D.label=6;case 6:return v.status===HTTP_BAD_REQUEST?(z=v.responseText,w="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+v.status,(null===z||void 0===z?void 0:z.Errors)&&(A=z.Errors.map(function(a){return a.message}).join(", "),w+=" - "+A)):(w="Received Identity Response from server: ",w+=JSON.stringify(v.responseText)),[3/*break*/,8];case 7:{if(u.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} // The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: // - version is always this prefix: fb @@ -1500,8 +1500,9 @@ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}} * Targeting is allowed when noTargeting is false (default). */return a.prototype.getNoTargeting=function(){return this.flags.noTargeting},a.prototype.getNoFunctional=function(){return this.flags.noFunctional},a}(); -var HEADER_ACCEPT="Accept",HEADER_CONTENT_TYPE="Content-Type",HEADER_ROKT_LAUNCHER_VERSION="rokt-launcher-version",HEADER_ROKT_LAUNCHER_INSTANCE_GUID="rokt-launcher-instance-guid",HEADER_ROKT_WSDK_VERSION="rokt-wsdk-version",ReportingLogger=/** @class */function(){function a(a,b,c,d,e){var f=this;this.sdkVersion=b,this.launcherInstanceGuid=d,this.reporter="mp-wsdk",this.isFeatureFlagEnabled=function(){return f.isLoggingEnabled},this.loggingUrl="https://".concat(a.loggingUrl||Constants.DefaultBaseUrls.loggingUrl),this.errorUrl="https://".concat(a.errorUrl||Constants.DefaultBaseUrls.errorUrl),this.isLoggingEnabled=a.isLoggingEnabled||!1,this.store=null!==c&&void 0!==c?c:null,this.isEnabled=this.isReportingEnabled(),this.rateLimiter=null!==e&&void 0!==e?e:new RateLimiter;}return a.prototype.setStore=function(a){this.store=a;},a.prototype.info=function(a,b){this.sendLog(WSDKErrorSeverity.INFO,a,b);},a.prototype.error=function(a,b,c){this.sendError(WSDKErrorSeverity.ERROR,a,b,c);},a.prototype.warning=function(a,b){this.sendError(WSDKErrorSeverity.WARNING,a,b);},a.prototype.sendToServer=function(a,b,c,d,e){if(this.canSendLog(b))try{var f=this.buildLogRequest(b,c,d,e),g=new FetchUploader(a),h={method:"POST",headers:this.getHeaders(),body:JSON.stringify(f)};g.upload(h)["catch"](function(a){console.error("ReportingLogger: Failed to send log",a);});}catch(a){console.error("ReportingLogger: Failed to send log",a);}},a.prototype.sendLog=function(a,b,c,d){this.sendToServer(this.loggingUrl,a,b,c,d);},a.prototype.sendError=function(a,b,c,d){this.sendToServer(this.errorUrl,a,b,c,d);},a.prototype.buildLogRequest=function(a,b,c,d){var e,f;return {additionalInformation:{message:b,version:this.getVersion()},severity:a,code:null!==c&&void 0!==c?c:ErrorCodes.UNKNOWN_ERROR,url:this.getUrl(),deviceInfo:this.getUserAgent(),stackTrace:d,reporter:this.reporter,// Integration will be set to integrationName once the kit connects via RoktManager.attachKit() -integration:null!==(f=null===(e=this.store)||void 0===e?void 0:e.getIntegrationName())&&void 0!==f?f:"mp-wsdk"}},a.prototype.getVersion=function(){var a,b,c;return null!==(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.getIntegrationName)||void 0===b?void 0:b.call(a))&&void 0!==c?c:"mParticle_wsdkv_".concat(this.sdkVersion)},a.prototype.isReportingEnabled=function(){return this.isDebugModeEnabled()||this.isRoktDomainPresent()&&this.isFeatureFlagEnabled()},a.prototype.isRoktDomainPresent=function(){return "undefined"!=typeof window&&!!window.ROKT_DOMAIN},a.prototype.isDebugModeEnabled=function(){var a,b,c,d;return "undefined"!=typeof window&&null!==(d=null===(c=null===(b=null===(a=window.location)||void 0===a?void 0:a.search)||void 0===b?void 0:b.toLowerCase())||void 0===c?void 0:c.includes("mp_enable_logging=true"))&&void 0!==d&&d},a.prototype.canSendLog=function(a){return this.isEnabled&&!this.isRateLimited(a)},a.prototype.isRateLimited=function(a){return this.rateLimiter.incrementAndCheck(a)},a.prototype.getUrl=function(){var a;return "undefined"==typeof window||null===(a=window.location)||void 0===a?void 0:a.href},a.prototype.getUserAgent=function(){var a;return "undefined"==typeof window||null===(a=window.navigator)||void 0===a?void 0:a.userAgent},a.prototype.getHeaders=function(){var a,b,c,d=(a={},a[HEADER_ACCEPT]="text/plain;charset=UTF-8",a[HEADER_CONTENT_TYPE]="application/json",a[HEADER_ROKT_LAUNCHER_VERSION]=this.getVersion(),a[HEADER_ROKT_WSDK_VERSION]="joint",a);this.launcherInstanceGuid&&(d[HEADER_ROKT_LAUNCHER_INSTANCE_GUID]=this.launcherInstanceGuid);var e=null===(c=null===(b=this.store)||void 0===b?void 0:b.getRoktAccountId)||void 0===c?void 0:c.call(b);return e&&(d["rokt-account-id"]=e),d},a}();var RateLimiter=/** @class */function(){function a(){this.rateLimits=new Map([[WSDKErrorSeverity.ERROR,10],[WSDKErrorSeverity.WARNING,10],[WSDKErrorSeverity.INFO,10]]),this.logCount=new Map;}return a.prototype.incrementAndCheck=function(a){var b=this.logCount.get(a)||0,c=this.rateLimits.get(a)||10,d=b+1;return this.logCount.set(a,d),d>c},a}(); +var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.report=function(a){this.services.forEach(function(b){return b.report(a)});},a}(); + +var LoggingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.log=function(a){this.services.forEach(function(b){return b.log(a)});},a}(); var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,CaptureIntegrationSpecificIdsV2Modes=Constants.CaptureIntegrationSpecificIdsV2Modes,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,CaptureIntegrationSpecificIdsV2=FeatureFlags.CaptureIntegrationSpecificIdsV2,StartingInitialization=Messages.InformationMessages.StartingInitialization;/** *

All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

@@ -1518,8 +1519,7 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Const this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization // Since fetching the configuration is asynchronous, we must pass completeSDKInitialization // to it for it to be run after fetched -if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c,d){// Update ReportingLogger with the new Store reference to avoid stale data -c._Store&&delete c._Store,c.Logger=new Logger(a,d),c._Store=new Store(a,c),null===d||void 0===d?void 0:d.setStore(c._Store),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval +if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** * Creates a CCPA Opt Out Consent State. * @@ -1671,7 +1671,7 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any // other integration delays set to true. It not, process the queued events/. -var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment +var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's // Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize @@ -1690,7 +1690,7 @@ function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan 3. Self hosting via /config endpoint (config.dataPlanResult) */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault // ensures no identity response data is written to localStorage when noFunctional is true -return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ReportingLogger=new ReportingLogger(c,Constants.sdkVersion,void 0,a.getLauncherInstanceGuid()),a.Logger=new Logger(c,a._ReportingLogger),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a._ReportingLogger.setStore(a._Store),a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions +return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs // since we will need this for the current implementation of user persistence // TODO: Refactor this when we refactor User Identity Persistence @@ -1716,6 +1716,6 @@ Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.protot * @param {String} apiKey your mParticle assigned API key * @param {Object} [config] an options object for additional configuration * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); + */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); export { mParticleManager as default }; diff --git a/dist/mparticle.js b/dist/mparticle.js index 41fcfa785..ff767ca7f 100644 --- a/dist/mparticle.js +++ b/dist/mparticle.js @@ -328,9 +328,7 @@ var mParticle = (function () { configUrl: 'jssdkcdns.mparticle.com/JS/v2/', identityUrl: 'identity.mparticle.com/v1/', aliasUrl: 'jssdks.mparticle.com/v1/identity/', - userAudienceUrl: 'nativesdks.mparticle.com/v1/', - loggingUrl: 'apps.rokt-api.com/v1/log', - errorUrl: 'apps.rokt-api.com/v1/errors' + userAudienceUrl: 'nativesdks.mparticle.com/v1/' }, // These are the paths that are used to construct the CNAME urls CNAMEUrlPaths: { @@ -339,9 +337,7 @@ var mParticle = (function () { v3SecureServiceUrl: '/webevents/v3/JS/', configUrl: '/tags/JS/v2/', identityUrl: '/identity/v1/', - aliasUrl: '/webevents/v1/identity/', - loggingUrl: '/v1/log', - errorUrl: '/v1/errors' + aliasUrl: '/webevents/v1/identity/' }, Base64CookieKeys: { csm: 1, @@ -4968,7 +4964,7 @@ var mParticle = (function () { for (var baseUrlKey in defaultBaseUrls) { // Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. - if (baseUrlKey === 'configUrl' || baseUrlKey === 'loggingUrl' || baseUrlKey === 'errorUrl') { + if (baseUrlKey === 'configUrl') { directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; continue; } @@ -4983,11 +4979,10 @@ var mParticle = (function () { } var Logger = /** @class */function () { - function Logger(config, reportingLogger) { + function Logger(config) { var _a, _b; this.logLevel = (_a = config.logLevel) !== null && _a !== void 0 ? _a : LogLevelType.Warning; this.logger = (_b = config.logger) !== null && _b !== void 0 ? _b : new ConsoleLogger(); - this.reportingLogger = reportingLogger; } Logger.prototype.verbose = function (msg) { if (this.logLevel === LogLevelType.None) return; @@ -5001,14 +4996,10 @@ var mParticle = (function () { this.logger.warning(msg); } }; - Logger.prototype.error = function (msg, codeForReporting) { - var _a; + Logger.prototype.error = function (msg) { if (this.logLevel === LogLevelType.None) return; if (this.logger.error) { this.logger.error(msg); - if (codeForReporting) { - (_a = this.reportingLogger) === null || _a === void 0 ? void 0 : _a.error(msg, codeForReporting); - } } }; Logger.prototype.setLogLevel = function (newLogLevel) { @@ -9395,11 +9386,11 @@ var mParticle = (function () { }; this.sendIdentityRequest = function (identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid, knownIdentities) { - var _a, _b, _c, _d; + var _a, _b, _c, _d, _e; return __awaiter(this, void 0, void 0, function () { - var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _e, responseBody, errorResponse, errorMessage, errorMessage, requestCount, err_1, requestCount, errorMessage; - return __generator(this, function (_f) { - switch (_f.label) { + var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _f, responseBody, errorResponse, errorMessage, errorMessage, requestCount, err_1, requestCount, errorMessage, msg; + return __generator(this, function (_g) { + switch (_g.label) { case 0: if ((_a = mpInstance._RoktManager) === null || _a === void 0 ? void 0 : _a.isInitialized) { mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1; @@ -9433,16 +9424,16 @@ var mParticle = (function () { body: JSON.stringify(identityApiRequest) }; mpInstance._Store.identityCallInFlight = true; - _f.label = 1; + _g.label = 1; case 1: - _f.trys.push([1, 9,, 10]); + _g.trys.push([1, 9,, 10]); return [4 /*yield*/, uploader.upload(fetchPayload)]; case 2: - response = _f.sent(); + response = _g.sent(); identityResponse = void 0; message = void 0; - _e = response.status; - switch (_e) { + _f = response.status; + switch (_f) { case HTTP_ACCEPTED: return [3 /*break*/, 3]; case HTTP_OK: @@ -9455,12 +9446,12 @@ var mParticle = (function () { if (!response.json) return [3 /*break*/, 5]; return [4 /*yield*/, response.json()]; case 4: - responseBody = _f.sent(); + responseBody = _g.sent(); identityResponse = this.getIdentityResponseFromFetch(response, responseBody); return [3 /*break*/, 6]; case 5: identityResponse = this.getIdentityResponseFromXHR(response); - _f.label = 6; + _g.label = 6; case 6: if (identityResponse.status === HTTP_BAD_REQUEST) { errorResponse = identityResponse.responseText; @@ -9499,7 +9490,7 @@ var mParticle = (function () { parseIdentityResponse(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false); return [3 /*break*/, 10]; case 9: - err_1 = _f.sent(); + err_1 = _g.sent(); mpInstance._Store.identityCallInFlight = false; mpInstance._Store.identityCallFailed = true; if ((_c = mpInstance._RoktManager) === null || _c === void 0 ? void 0 : _c.isInitialized) { @@ -9507,8 +9498,14 @@ var mParticle = (function () { mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); } errorMessage = err_1.message || err_1.toString(); - Logger.error('Error sending identity request to servers' + ' - ' + errorMessage, ErrorCodes.IDENTITY_REQUEST); - (_d = mpInstance.processQueueOnIdentityFailure) === null || _d === void 0 ? void 0 : _d.call(mpInstance); + msg = 'Error sending identity request to servers' + ' - ' + errorMessage; + Logger.error(msg); + (_d = mpInstance._ErrorReportingDispatcher) === null || _d === void 0 ? void 0 : _d.report({ + message: msg, + code: ErrorCodes.IDENTITY_REQUEST, + severity: WSDKErrorSeverity.ERROR + }); + (_e = mpInstance.processQueueOnIdentityFailure) === null || _e === void 0 ? void 0 : _e.call(mpInstance); invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); return [3 /*break*/, 10]; case 10: @@ -10379,136 +10376,34 @@ var mParticle = (function () { return CookieConsentManager; }(); - // Header key constants - var HEADER_ACCEPT = 'Accept'; - var HEADER_CONTENT_TYPE = 'Content-Type'; - var HEADER_ROKT_LAUNCHER_VERSION = 'rokt-launcher-version'; - var HEADER_ROKT_LAUNCHER_INSTANCE_GUID = 'rokt-launcher-instance-guid'; - var HEADER_ROKT_WSDK_VERSION = 'rokt-wsdk-version'; - var ReportingLogger = /** @class */function () { - function ReportingLogger(config, sdkVersion, store, launcherInstanceGuid, rateLimiter) { - var _this = this; - this.sdkVersion = sdkVersion; - this.launcherInstanceGuid = launcherInstanceGuid; - this.reporter = 'mp-wsdk'; - this.isFeatureFlagEnabled = function () { - return _this.isLoggingEnabled; - }; - this.loggingUrl = "https://".concat(config.loggingUrl || Constants.DefaultBaseUrls.loggingUrl); - this.errorUrl = "https://".concat(config.errorUrl || Constants.DefaultBaseUrls.errorUrl); - this.isLoggingEnabled = config.isLoggingEnabled || false; - this.store = store !== null && store !== void 0 ? store : null; - this.isEnabled = this.isReportingEnabled(); - this.rateLimiter = rateLimiter !== null && rateLimiter !== void 0 ? rateLimiter : new RateLimiter(); - } - ReportingLogger.prototype.setStore = function (store) { - this.store = store; - }; - ReportingLogger.prototype.info = function (msg, code) { - this.sendLog(WSDKErrorSeverity.INFO, msg, code); - }; - ReportingLogger.prototype.error = function (msg, code, stackTrace) { - this.sendError(WSDKErrorSeverity.ERROR, msg, code, stackTrace); - }; - ReportingLogger.prototype.warning = function (msg, code) { - this.sendError(WSDKErrorSeverity.WARNING, msg, code); - }; - ReportingLogger.prototype.sendToServer = function (url, severity, msg, code, stackTrace) { - if (!this.canSendLog(severity)) return; - try { - var logRequest = this.buildLogRequest(severity, msg, code, stackTrace); - var uploader = new FetchUploader(url); - var payload = { - method: 'POST', - headers: this.getHeaders(), - body: JSON.stringify(logRequest) - }; - uploader.upload(payload)["catch"](function (error) { - console.error('ReportingLogger: Failed to send log', error); - }); - } catch (error) { - console.error('ReportingLogger: Failed to send log', error); - } - }; - ReportingLogger.prototype.sendLog = function (severity, msg, code, stackTrace) { - this.sendToServer(this.loggingUrl, severity, msg, code, stackTrace); - }; - ReportingLogger.prototype.sendError = function (severity, msg, code, stackTrace) { - this.sendToServer(this.errorUrl, severity, msg, code, stackTrace); - }; - ReportingLogger.prototype.buildLogRequest = function (severity, msg, code, stackTrace) { - var _a, _b; - return { - additionalInformation: { - message: msg, - version: this.getVersion() - }, - severity: severity, - code: code !== null && code !== void 0 ? code : ErrorCodes.UNKNOWN_ERROR, - url: this.getUrl(), - deviceInfo: this.getUserAgent(), - stackTrace: stackTrace, - reporter: this.reporter, - // Integration will be set to integrationName once the kit connects via RoktManager.attachKit() - integration: (_b = (_a = this.store) === null || _a === void 0 ? void 0 : _a.getIntegrationName()) !== null && _b !== void 0 ? _b : 'mp-wsdk' - }; - }; - ReportingLogger.prototype.getVersion = function () { - var _a, _b, _c; - return (_c = (_b = (_a = this.store) === null || _a === void 0 ? void 0 : _a.getIntegrationName) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : "mParticle_wsdkv_".concat(this.sdkVersion); - }; - ReportingLogger.prototype.isReportingEnabled = function () { - return this.isDebugModeEnabled() || this.isRoktDomainPresent() && this.isFeatureFlagEnabled(); - }; - ReportingLogger.prototype.isRoktDomainPresent = function () { - return typeof window !== 'undefined' && Boolean(window['ROKT_DOMAIN']); - }; - ReportingLogger.prototype.isDebugModeEnabled = function () { - var _a, _b, _c, _d; - return typeof window !== 'undefined' && ((_d = (_c = (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.search) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === null || _c === void 0 ? void 0 : _c.includes('mp_enable_logging=true')) !== null && _d !== void 0 ? _d : false); - }; - ReportingLogger.prototype.canSendLog = function (severity) { - return this.isEnabled && !this.isRateLimited(severity); - }; - ReportingLogger.prototype.isRateLimited = function (severity) { - return this.rateLimiter.incrementAndCheck(severity); + var ErrorReportingDispatcher = /** @class */function () { + function ErrorReportingDispatcher() { + this.services = []; + } + ErrorReportingDispatcher.prototype.register = function (service) { + this.services.push(service); }; - ReportingLogger.prototype.getUrl = function () { - var _a; - return typeof window !== 'undefined' ? (_a = window.location) === null || _a === void 0 ? void 0 : _a.href : undefined; + ErrorReportingDispatcher.prototype.report = function (error) { + this.services.forEach(function (s) { + return s.report(error); + }); }; - ReportingLogger.prototype.getUserAgent = function () { - var _a; - return typeof window !== 'undefined' ? (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent : undefined; + return ErrorReportingDispatcher; + }(); + + var LoggingDispatcher = /** @class */function () { + function LoggingDispatcher() { + this.services = []; + } + LoggingDispatcher.prototype.register = function (service) { + this.services.push(service); }; - ReportingLogger.prototype.getHeaders = function () { - var _a; - var _b, _c; - var headers = (_a = {}, _a[HEADER_ACCEPT] = 'text/plain;charset=UTF-8', _a[HEADER_CONTENT_TYPE] = 'application/json', _a[HEADER_ROKT_LAUNCHER_VERSION] = this.getVersion(), _a[HEADER_ROKT_WSDK_VERSION] = 'joint', _a); - if (this.launcherInstanceGuid) { - headers[HEADER_ROKT_LAUNCHER_INSTANCE_GUID] = this.launcherInstanceGuid; - } - var accountId = (_c = (_b = this.store) === null || _b === void 0 ? void 0 : _b.getRoktAccountId) === null || _c === void 0 ? void 0 : _c.call(_b); - if (accountId) { - headers['rokt-account-id'] = accountId; - } - return headers; + LoggingDispatcher.prototype.log = function (entry) { + this.services.forEach(function (s) { + return s.log(entry); + }); }; - return ReportingLogger; - }(); - var RateLimiter = /** @class */function () { - function RateLimiter() { - this.rateLimits = new Map([[WSDKErrorSeverity.ERROR, 10], [WSDKErrorSeverity.WARNING, 10], [WSDKErrorSeverity.INFO, 10]]); - this.logCount = new Map(); - } - RateLimiter.prototype.incrementAndCheck = function (severity) { - var count = this.logCount.get(severity) || 0; - var limit = this.rateLimits.get(severity) || 10; - var newCount = count + 1; - this.logCount.set(severity, newCount); - return newCount > limit; - }; - return RateLimiter; + return LoggingDispatcher; }(); var Messages = Constants.Messages, @@ -10648,14 +10543,14 @@ var mParticle = (function () { console.error('Cannot reset mParticle', error); } }; - this._resetForTests = function (config, keepPersistence, instance, reportingLogger) { + this._resetForTests = function (config, keepPersistence, instance) { if (instance._Store) { delete instance._Store; } - instance.Logger = new Logger(config, reportingLogger); + instance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); + instance._LoggingDispatcher = new LoggingDispatcher(); + instance.Logger = new Logger(config); instance._Store = new Store(config, instance); - // Update ReportingLogger with the new Store reference to avoid stale data - reportingLogger === null || reportingLogger === void 0 ? void 0 : reportingLogger.setStore(instance._Store); instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability(window.localStorage); instance._Events.stopTracking(); if (!keepPersistence) { @@ -11471,6 +11366,12 @@ var mParticle = (function () { }; } }; + this.registerErrorReportingService = function (service) { + self._ErrorReportingDispatcher.register(service); + }; + this.registerLoggingService = function (service) { + self._LoggingDispatcher.register(service); + }; var launcherInstanceGuidKey = Constants.Rokt.LauncherInstanceGuidKey; this.setLauncherInstanceGuid = function () { if (!window[launcherInstanceGuidKey] || typeof window[launcherInstanceGuidKey] !== 'string') { @@ -11645,11 +11546,11 @@ var mParticle = (function () { } function runPreConfigFetchInitialization(mpInstance, apiKey, config) { var _a; - mpInstance._ReportingLogger = new ReportingLogger(config, Constants.sdkVersion, undefined, mpInstance.getLauncherInstanceGuid()); - mpInstance.Logger = new Logger(config, mpInstance._ReportingLogger); + mpInstance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); + mpInstance._LoggingDispatcher = new LoggingDispatcher(); + mpInstance.Logger = new Logger(config); mpInstance._Store = new Store(config, mpInstance, apiKey); window.mParticle.Store = mpInstance._Store; - mpInstance._ReportingLogger.setStore(mpInstance._Store); mpInstance.Logger.verbose(StartingInitialization); // Initialize CookieConsentManager with privacy flags from launcherOptions var _b = (_a = config === null || config === void 0 ? void 0 : config.launcherOptions) !== null && _a !== void 0 ? _a : {}, @@ -12186,6 +12087,12 @@ var mParticle = (function () { this._setWrapperSDKInfo = function (name, version) { self.getInstance()._setWrapperSDKInfo(name, version); }; + this.registerErrorReportingService = function (service) { + self.getInstance().registerErrorReportingService(service); + }; + this.registerLoggingService = function (service) { + self.getInstance().registerLoggingService(service); + }; } var mParticleManager = new mParticleInstanceManager(); if (typeof window !== 'undefined') { diff --git a/src/identityApiClient.ts b/src/identityApiClient.ts index fc5c58522..876dc37e7 100644 --- a/src/identityApiClient.ts +++ b/src/identityApiClient.ts @@ -331,7 +331,7 @@ export default function IdentityAPIClient( const errorMessage = (err as Error).message || err.toString(); const msg = 'Error sending identity request to servers' + ' - ' + errorMessage; Logger.error(msg); - mpInstance._ErrorReportingDispatcher.report({ + mpInstance._ErrorReportingDispatcher?.report({ message: msg, code: ErrorCodes.IDENTITY_REQUEST, severity: WSDKErrorSeverity.ERROR, diff --git a/test/src/tests-mparticle-instance-manager.ts b/test/src/tests-mparticle-instance-manager.ts index abddf2322..33ec4c72e 100644 --- a/test/src/tests-mparticle-instance-manager.ts +++ b/test/src/tests-mparticle-instance-manager.ts @@ -216,6 +216,8 @@ describe('mParticle instance manager', () => { 'upload', 'Rokt', 'captureTiming', + 'registerErrorReportingService', + 'registerLoggingService', ]); }); From e573c1ff57418944451360dbdfe5b253f60b78f5 Mon Sep 17 00:00:00 2001 From: Alexander Sapountzis Date: Fri, 20 Mar 2026 17:14:51 -0400 Subject: [PATCH 3/5] chore: remove dist/ from tracking (already in gitignore) --- dist/build/src/batchUploader.d.ts | 36 - dist/build/src/constants.d.ts | 151 - dist/build/src/kitBlocking.d.ts | 123 - dist/build/src/mockBatchCreator.d.ts | 6 - dist/build/src/sdkRuntimeModels.d.ts | 303 - dist/build/src/sdkToEventsApiConverter.d.ts | 33 - dist/build/src/utils.d.ts | 9 - dist/build/src/validators.d.ts | 17 - dist/build/test/src/tests-batchUploader.d.ts | 7 - dist/build/test/src/tests-kit-blocking.d.ts | 7 - .../test/src/tests-mockBatchCreator.d.ts | 1 - .../src/tests-runtimeToBatchEventsDTO.d.ts | 6 - dist/build/test/src/tests-utils.d.ts | 1 - dist/build/test/src/tests-validators.d.ts | 1 - dist/mparticle.common.js | 1721 --- dist/mparticle.esm.js | 1721 --- dist/mparticle.js | 12110 ---------------- dist/mparticle.stub.js | 186 - dist/src/batchUploader.d.ts | 36 - dist/src/constants.d.ts | 151 - dist/src/kitBlocking.d.ts | 123 - dist/src/mockBatchCreator.d.ts | 6 - dist/src/sdkRuntimeModels.d.ts | 303 - dist/src/sdkToEventsApiConverter.d.ts | 33 - dist/src/utils.d.ts | 9 - dist/src/validators.d.ts | 17 - dist/test/src/tests-batchUploader.d.ts | 7 - dist/test/src/tests-kit-blocking.d.ts | 7 - dist/test/src/tests-mockBatchCreator.d.ts | 1 - .../src/tests-runtimeToBatchEventsDTO.d.ts | 6 - dist/test/src/tests-utils.d.ts | 1 - dist/test/src/tests-validators.d.ts | 1 - 32 files changed, 17140 deletions(-) delete mode 100644 dist/build/src/batchUploader.d.ts delete mode 100644 dist/build/src/constants.d.ts delete mode 100644 dist/build/src/kitBlocking.d.ts delete mode 100644 dist/build/src/mockBatchCreator.d.ts delete mode 100644 dist/build/src/sdkRuntimeModels.d.ts delete mode 100644 dist/build/src/sdkToEventsApiConverter.d.ts delete mode 100644 dist/build/src/utils.d.ts delete mode 100644 dist/build/src/validators.d.ts delete mode 100644 dist/build/test/src/tests-batchUploader.d.ts delete mode 100644 dist/build/test/src/tests-kit-blocking.d.ts delete mode 100644 dist/build/test/src/tests-mockBatchCreator.d.ts delete mode 100644 dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts delete mode 100644 dist/build/test/src/tests-utils.d.ts delete mode 100644 dist/build/test/src/tests-validators.d.ts delete mode 100644 dist/mparticle.common.js delete mode 100644 dist/mparticle.esm.js delete mode 100644 dist/mparticle.js delete mode 100644 dist/mparticle.stub.js delete mode 100644 dist/src/batchUploader.d.ts delete mode 100644 dist/src/constants.d.ts delete mode 100644 dist/src/kitBlocking.d.ts delete mode 100644 dist/src/mockBatchCreator.d.ts delete mode 100644 dist/src/sdkRuntimeModels.d.ts delete mode 100644 dist/src/sdkToEventsApiConverter.d.ts delete mode 100644 dist/src/utils.d.ts delete mode 100644 dist/src/validators.d.ts delete mode 100644 dist/test/src/tests-batchUploader.d.ts delete mode 100644 dist/test/src/tests-kit-blocking.d.ts delete mode 100644 dist/test/src/tests-mockBatchCreator.d.ts delete mode 100644 dist/test/src/tests-runtimeToBatchEventsDTO.d.ts delete mode 100644 dist/test/src/tests-utils.d.ts delete mode 100644 dist/test/src/tests-validators.d.ts diff --git a/dist/build/src/batchUploader.d.ts b/dist/build/src/batchUploader.d.ts deleted file mode 100644 index eafd5e14b..000000000 --- a/dist/build/src/batchUploader.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Batch } from '@mparticle/event-models'; -import { SDKEvent, MParticleWebSDK } from './sdkRuntimeModels'; -export declare class BatchUploader { - static readonly CONTENT_TYPE: string; - static readonly MINIMUM_INTERVAL_MILLIS: number; - uploadIntervalMillis: number; - pendingEvents: SDKEvent[]; - pendingUploads: Batch[]; - mpInstance: MParticleWebSDK; - uploadUrl: string; - batchingEnabled: boolean; - constructor(mpInstance: MParticleWebSDK, uploadInterval: number); - private addEventListeners; - private isBeaconAvailable; - queueEvent(event: SDKEvent): void; - /** - * This implements crucial logic to: - * - bucket pending events by MPID, and then by Session, and upload individual batches for each bucket. - * - * In the future this should enforce other requirements such as maximum batch size. - * - * @param sdkEvents current pending events - * @param defaultUser the user to reference for events that are missing data - */ - private static createNewUploads; - /** - * This is the main loop function: - * - take all pending events and turn them into batches - * - attempt to upload each batch - * - * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false - * @param useBeacon whether to use the beacon API - used when the page is being unloaded - */ - private prepareAndUpload; - private upload; -} diff --git a/dist/build/src/constants.d.ts b/dist/build/src/constants.d.ts deleted file mode 100644 index 7271faa4e..000000000 --- a/dist/build/src/constants.d.ts +++ /dev/null @@ -1,151 +0,0 @@ -declare const Constants: { - readonly sdkVersion: string; - readonly sdkVendor: "mparticle"; - readonly platform: "web"; - readonly Messages: { - readonly ErrorMessages: { - readonly NoToken: "A token must be specified."; - readonly EventNameInvalidType: "Event name must be a valid string value."; - readonly EventDataInvalidType: "Event data must be a valid object hash."; - readonly LoggingDisabled: "Event logging is currently disabled."; - readonly CookieParseError: "Could not parse cookie"; - readonly EventEmpty: "Event object is null or undefined, cancelling send"; - readonly APIRequestEmpty: "APIRequest is null or undefined, cancelling send"; - readonly NoEventType: "Event type must be specified."; - readonly TransactionIdRequired: "Transaction ID is required"; - readonly TransactionRequired: "A transaction attributes object is required"; - readonly PromotionIdRequired: "Promotion ID is required"; - readonly BadAttribute: "Attribute value cannot be object or array"; - readonly BadKey: "Key value cannot be object or array"; - readonly BadLogPurchase: "Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"; - }; - readonly InformationMessages: { - readonly CookieSearch: "Searching for cookie"; - readonly CookieFound: "Cookie found, parsing values"; - readonly CookieNotFound: "Cookies not found"; - readonly CookieSet: "Setting cookie"; - readonly CookieSync: "Performing cookie sync"; - readonly SendBegin: "Starting to send event"; - readonly SendIdentityBegin: "Starting to send event to identity server"; - readonly SendWindowsPhone: "Sending event to Windows Phone container"; - readonly SendIOS: "Calling iOS path: "; - readonly SendAndroid: "Calling Android JS interface method: "; - readonly SendHttp: "Sending event to mParticle HTTP service"; - readonly SendAliasHttp: "Sending alias request to mParticle HTTP service"; - readonly SendIdentityHttp: "Sending event to mParticle HTTP service"; - readonly StartingNewSession: "Starting new Session"; - readonly StartingLogEvent: "Starting to log event"; - readonly StartingLogOptOut: "Starting to log user opt in/out"; - readonly StartingEndSession: "Starting to end session"; - readonly StartingInitialization: "Starting to initialize"; - readonly StartingLogCommerceEvent: "Starting to log commerce event"; - readonly StartingAliasRequest: "Starting to Alias MPIDs"; - readonly LoadingConfig: "Loading configuration options"; - readonly AbandonLogEvent: "Cannot log event, logging disabled or developer token not set"; - readonly AbandonAliasUsers: "Cannot Alias Users, logging disabled or developer token not set"; - readonly AbandonStartSession: "Cannot start session, logging disabled or developer token not set"; - readonly AbandonEndSession: "Cannot end session, logging disabled or developer token not set"; - readonly NoSessionToEnd: "Cannot end session, no active session found"; - }; - readonly ValidationMessages: { - readonly ModifyIdentityRequestUserIdentitiesPresent: "identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again"; - readonly IdentityRequesetInvalidKey: "There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again."; - readonly OnUserAliasType: "The onUserAlias value must be a function."; - readonly UserIdentities: "The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again."; - readonly UserIdentitiesInvalidKey: "There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again."; - readonly UserIdentitiesInvalidValues: "All user identity values must be strings or null. Request not sent to server. Please fix and try again."; - readonly AliasMissingMpid: "Alias Request must contain both a destinationMpid and a sourceMpid"; - readonly AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique"; - readonly AliasMissingTime: "Alias Request must have both a startTime and an endTime"; - readonly AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime"; - }; - }; - readonly NativeSdkPaths: { - readonly LogEvent: "logEvent"; - readonly SetUserTag: "setUserTag"; - readonly RemoveUserTag: "removeUserTag"; - readonly SetUserAttribute: "setUserAttribute"; - readonly RemoveUserAttribute: "removeUserAttribute"; - readonly SetSessionAttribute: "setSessionAttribute"; - readonly AddToCart: "addToCart"; - readonly RemoveFromCart: "removeFromCart"; - readonly ClearCart: "clearCart"; - readonly LogOut: "logOut"; - readonly SetUserAttributeList: "setUserAttributeList"; - readonly RemoveAllUserAttributes: "removeAllUserAttributes"; - readonly GetUserAttributesLists: "getUserAttributesLists"; - readonly GetAllUserAttributes: "getAllUserAttributes"; - readonly Identify: "identify"; - readonly Logout: "logout"; - readonly Login: "login"; - readonly Modify: "modify"; - readonly Alias: "aliasUsers"; - readonly Upload: "upload"; - }; - readonly StorageNames: { - readonly localStorageName: "mprtcl-api"; - readonly localStorageNameV3: "mprtcl-v3"; - readonly cookieName: "mprtcl-api"; - readonly cookieNameV2: "mprtcl-v2"; - readonly cookieNameV3: "mprtcl-v3"; - readonly localStorageNameV4: "mprtcl-v4"; - readonly localStorageProductsV4: "mprtcl-prodv4"; - readonly cookieNameV4: "mprtcl-v4"; - readonly currentStorageName: "mprtcl-v4"; - readonly currentStorageProductsName: "mprtcl-prodv4"; - }; - readonly DefaultConfig: { - readonly cookieDomain: any; - readonly cookieExpiration: 365; - readonly logLevel: any; - readonly timeout: 300; - readonly sessionTimeout: 30; - readonly maxProducts: 20; - readonly forwarderStatsTimeout: 5000; - readonly integrationDelayTimeout: 5000; - readonly maxCookieSize: 3000; - readonly aliasMaxWindow: 90; - readonly uploadInterval: 0; - }; - readonly DefaultUrls: { - readonly v1SecureServiceUrl: "jssdks.mparticle.com/v1/JS/"; - readonly v2SecureServiceUrl: "jssdks.mparticle.com/v2/JS/"; - readonly v3SecureServiceUrl: "jssdks.mparticle.com/v3/JS/"; - readonly configUrl: "jssdkcdns.mparticle.com/JS/v2/"; - readonly identityUrl: "identity.mparticle.com/v1/"; - readonly aliasUrl: "jssdks.mparticle.com/v1/identity/"; - }; - readonly Base64CookieKeys: { - readonly csm: 1; - readonly sa: 1; - readonly ss: 1; - readonly ua: 1; - readonly ui: 1; - readonly csd: 1; - readonly ia: 1; - readonly con: 1; - }; - readonly SDKv2NonMPIDCookieKeys: { - readonly gs: 1; - readonly cu: 1; - readonly l: 1; - readonly globalSettings: 1; - readonly currentUserMPID: 1; - }; - readonly HTTPCodes: { - readonly noHttpCoverage: -1; - readonly activeIdentityRequest: -2; - readonly activeSession: -3; - readonly validationIssue: -4; - readonly nativeIdentityRequest: -5; - readonly loggingDisabledOrMissingAPIKey: -6; - readonly tooManyRequests: 429; - }; - readonly FeatureFlags: { - readonly ReportBatching: "reportBatching"; - readonly EventsV3: "eventsV3"; - readonly EventBatchingIntervalMillis: "eventBatchingIntervalMillis"; - }; - readonly DefaultInstance: "default_instance"; -}; -export default Constants; diff --git a/dist/build/src/kitBlocking.d.ts b/dist/build/src/kitBlocking.d.ts deleted file mode 100644 index 40ae6250b..000000000 --- a/dist/build/src/kitBlocking.d.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { SDKEvent, MParticleWebSDK, KitBlockerDataPlan } from './sdkRuntimeModels'; -import { BaseEvent } from '@mparticle/event-models'; -import { DataPlanPoint } from '@mparticle/data-planning-models'; -export default class KitBlocker { - dataPlanMatchLookups: { - [key: string]: {}; - }; - blockEvents: boolean; - blockEventAttributes: boolean; - blockUserAttributes: boolean; - blockUserIdentities: boolean; - kitBlockingEnabled: boolean; - mpInstance: MParticleWebSDK; - constructor(dataPlan: KitBlockerDataPlan, mpInstance: MParticleWebSDK); - addToMatchLookups(point: DataPlanPoint): void; - generateMatchKey(match: any): string | null; - generateProductAttributeMatchKey(match: any): string | null; - getPlannedProperties(type: any, validator: any): boolean | { - [key: string]: true; - } | null; - getProductProperties(type: any, validator: any): boolean | { - [key: string]: true; - } | null; - getMatchKey(eventToMatch: BaseEvent): string | null; - getProductAttributeMatchKey(eventToMatch: BaseEvent): string | null; - createBlockedEvent(event: SDKEvent): SDKEvent; - transformEventAndEventAttributes(event: SDKEvent): SDKEvent; - transformProductAttributes(event: SDKEvent): SDKEvent; - transformUserAttributes(event: SDKEvent): { - DeviceId: string; - IsFirstRun: boolean; - EventName: string; - EventCategory: number; - UserAttributes?: { - [key: string]: string | string[]; - }; - UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; - SourceMessageId: string; - MPID: string; - EventAttributes?: { - [key: string]: string; - }; - SDKVersion: string; - SessionId: string; - SessionStartDate: number; - SessionLength?: number; - currentSessionMPIDs?: string[]; - Timestamp: number; - EventDataType: number; - Debug: boolean; - Location?: import("./sdkRuntimeModels").SDKGeoLocation; - OptOut?: boolean; - CustomFlags?: { - [key: string]: string; - }; - AppVersion?: string; - AppName?: string; - Package?: string; - ConsentState?: import("./sdkRuntimeModels").SDKConsentState; - IntegrationAttributes?: { - [key: string]: { - [key: string]: string; - }; - }; - ProductAction?: import("./sdkRuntimeModels").SDKProductAction; - PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; - ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; - ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; - UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; - UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; - CurrencyCode: string; - DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; - LaunchReferral?: string; - }; - isAttributeKeyBlocked(key: string): boolean; - isIdentityBlocked(key: string): boolean; - transformUserIdentities(event: SDKEvent): { - DeviceId: string; - IsFirstRun: boolean; - EventName: string; - EventCategory: number; - UserAttributes?: { - [key: string]: string | string[]; - }; - UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; - SourceMessageId: string; - MPID: string; - EventAttributes?: { - [key: string]: string; - }; - SDKVersion: string; - SessionId: string; - SessionStartDate: number; - SessionLength?: number; - currentSessionMPIDs?: string[]; - Timestamp: number; - EventDataType: number; - Debug: boolean; - Location?: import("./sdkRuntimeModels").SDKGeoLocation; - OptOut?: boolean; - CustomFlags?: { - [key: string]: string; - }; - AppVersion?: string; - AppName?: string; - Package?: string; - ConsentState?: import("./sdkRuntimeModels").SDKConsentState; - IntegrationAttributes?: { - [key: string]: { - [key: string]: string; - }; - }; - ProductAction?: import("./sdkRuntimeModels").SDKProductAction; - PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; - ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; - ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; - UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; - UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; - CurrencyCode: string; - DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; - LaunchReferral?: string; - }; -} diff --git a/dist/build/src/mockBatchCreator.d.ts b/dist/build/src/mockBatchCreator.d.ts deleted file mode 100644 index 2be2d9c2e..000000000 --- a/dist/build/src/mockBatchCreator.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { BaseEvent } from './sdkRuntimeModels'; -import * as EventsApi from '@mparticle/event-models'; -export default class _BatchValidator { - private getMPInstance; - returnBatch(event: BaseEvent): EventsApi.Batch; -} diff --git a/dist/build/src/sdkRuntimeModels.d.ts b/dist/build/src/sdkRuntimeModels.d.ts deleted file mode 100644 index 253e653a2..000000000 --- a/dist/build/src/sdkRuntimeModels.d.ts +++ /dev/null @@ -1,303 +0,0 @@ -import * as EventsApi from '@mparticle/event-models'; -import { DataPlanVersion } from '@mparticle/data-planning-models'; -export interface SDKEvent { - DeviceId: string; - IsFirstRun: boolean; - EventName: string; - EventCategory: number; - UserAttributes?: { - [key: string]: string | string[] | null; - }; - UserIdentities?: SDKUserIdentity[]; - SourceMessageId: string; - MPID: string; - EventAttributes?: { - [key: string]: string; - }; - SDKVersion: string; - SessionId: string; - SessionStartDate: number; - SessionLength?: number; - currentSessionMPIDs?: string[]; - Timestamp: number; - EventDataType: number; - Debug: boolean; - Location?: SDKGeoLocation; - OptOut?: boolean; - CustomFlags?: { - [key: string]: string; - }; - AppVersion?: string; - AppName?: string; - Package?: string; - ConsentState?: SDKConsentState; - IntegrationAttributes?: { - [key: string]: { - [key: string]: string; - }; - }; - ProductAction?: SDKProductAction; - PromotionAction?: SDKPromotionAction; - ProductImpressions?: SDKProductImpression[]; - ShoppingCart?: SDKShoppingCart; - UserIdentityChanges?: SDKUserIdentityChangeData; - UserAttributeChanges?: SDKUserAttributeChangeData; - CurrencyCode: string; - DataPlan?: SDKDataPlan; - LaunchReferral?: string; -} -export interface SDKGeoLocation { - lat: number | string; - lng: number | string; -} -export interface SDKDataPlan { - PlanVersion?: number | null; - PlanId?: string | null; -} -export interface SDKUserIdentity { - Identity?: string; - Type: number; -} -export interface SDKShoppingCart { - ProductList?: SDKProduct[]; -} -export interface SDKPromotionAction { - PromotionActionType: string; - PromotionList?: SDKPromotion[]; -} -export interface SDKPromotion { - Id?: string; - Name?: string; - Creative?: string; - Position?: string; -} -export interface SDKProductImpression { - ProductImpressionList?: string; - ProductList?: SDKProduct[]; -} -export declare enum SDKProductActionType { - Unknown = 0, - AddToCart = 1, - RemoveFromCart = 2, - Checkout = 3, - CheckoutOption = 4, - Click = 5, - ViewDetail = 6, - Purchase = 7, - Refund = 8, - AddToWishlist = 9, - RemoveFromWishlist = 10 -} -export interface SDKProductAction { - ProductActionType: SDKProductActionType; - CheckoutStep?: number; - CheckoutOptions?: string; - ProductList?: SDKProduct[]; - TransactionId?: string; - Affiliation?: string; - CouponCode?: string; - TotalAmount?: number; - ShippingAmount?: number; - TaxAmount?: number; -} -export interface SDKProduct { - Sku?: string; - Name?: string; - Price?: number; - Quantity?: number; - Brand?: string; - Variant?: string; - Category?: string; - Position?: number; - CouponCode?: string; - TotalAmount?: number; - Attributes?: { - [key: string]: string; - }; -} -export interface MParticleWebSDK { - addForwarder(mockForwarder: any): any; - Identity: SDKIdentityApi; - Logger: SDKLoggerApi; - _Store: SDKStoreApi; - _Helpers: SDKHelpersApi; - config: SDKConfig; - _resetForTests(MPConfig: SDKConfig): void; - init(apiKey: string, config: SDKConfig): void; - getInstance(): any; - ServerModel(): any; - upload(): any; - setPosition(lat: number | string, lng: number | string): void; - logEvent(eventName: string, eventType?: number, attrs?: { - [key: string]: string; - }): void; - logBaseEvent(event: any): void; - eCommerce: any; - logLevel: string; - ProductActionType: SDKProductActionType; - generateHash(value: string): any; -} -export interface SDKConfig { - isDevelopmentMode?: boolean; - logger: { - error?(msg: any): any; - warning?(msg: any): any; - verbose?(msg: any): any; - }; - onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; - dataPlan: DataPlanConfig; - appVersion?: string; - package?: string; - flags?: { - [key: string]: string | number; - }; - kitConfigs: any; - appName?: string; - logLevel?: string; - sessionTimeout?: number; - useCookieStorage?: boolean; - cookieDomain?: string; - workspaceToken: string; - requiredWebviewBridgeName: string; - minWebviewBridgeVersion: number; - isIOS?: boolean; - identifyRequest: { - [key: string]: { - [key: string]: string; - }; - }; - identityCallback: (result: any) => void; - requestConfig: boolean; - dataPlanOptions: KitBlockerOptions; - dataPlanResult?: DataPlanResult; -} -export interface DataPlanConfig { - planId?: string; - planVersion?: number; - document?: DataPlanResult; -} -export interface SDKIdentityApi { - getCurrentUser(): any; - IdentityAPI: any; - identify: any; - login: any; - logout: any; - modify: any; -} -export interface SDKHelpersApi { - createServiceUrl(arg0: string, arg1: string): void; - parseNumber(value: number): any; - generateUniqueId(): any; - isObject(item: any): any; -} -export interface SDKLoggerApi { - error(arg0: string): void; - verbose(arg0: string): void; - warning(arg0: string): void; -} -export interface SDKStoreApi { - isFirstRun: boolean; - devToken: string; - SDKConfig: SDKConfigApi; - sessionId?: string; - deviceId?: string; -} -export interface SDKConfigApi { - v3SecureServiceUrl?: string; - isDevelopmentMode: boolean; - appVersion?: string; - onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; -} -export interface MParticleUser { - getMPID(): string; -} -export interface SDKConsentState { - getGDPRConsentState(): SDKGDPRConsentState; - getCCPAConsentState(): SDKCCPAConsentState; -} -export interface SDKGDPRConsentState { - [key: string]: SDKConsentStateData; -} -export interface SDKConsentStateData { - Consented: boolean; - Timestamp?: number; - ConsentDocument?: string; - Location?: string; - HardwareId?: string; -} -export interface SDKCCPAConsentState extends SDKConsentStateData { -} -export interface SDKUserIdentityChangeData { - New: Identity; - Old: Identity; -} -export interface Identity { - IdentityType: SDKIdentityTypeEnum; - Identity: string; - Timestamp: number; - CreatedThisBatch: boolean; -} -export interface SDKUserAttributeChangeData { - UserAttributeName: string; - New: string; - Old: string; - Deleted: boolean; - IsNewAttribute: boolean; -} -export interface BaseEvent { - messageType: number; - name: string; - eventType?: number; - data?: { - [key: string]: string; - }; - customFlags?: { - [key: string]: string; - }; -} -export interface KitBlockerOptions { - dataPlanVersion: DataPlanVersion; - blockUserAttributes: boolean; - blockEventAttributes: boolean; - blockEvents: boolean; - blockUserIdentities: boolean; -} -export interface KitBlockerDataPlan { - document: DataPlanResult; -} -export interface DataPlanResult { - dtpn?: { - vers: DataPlanVersion; - blok: { - ev: boolean; - ea: boolean; - ua: boolean; - id: boolean; - }; - }; - error_message?: string; -} -export declare enum SDKIdentityTypeEnum { - other = "other", - customerId = "customerid", - facebook = "facebook", - twitter = "twitter", - google = "google", - microsoft = "microsoft", - yahoo = "yahoo", - email = "email", - alias = "alias", - facebookCustomAudienceId = "facebookcustomaudienceid", - otherId2 = "other2", - otherId3 = "other3", - otherId4 = "other4", - otherId5 = "other5", - otherId6 = "other6", - otherId7 = "other7", - otherId8 = "other8", - otherId9 = "other9", - otherId10 = "other10", - mobileNumber = "mobile_number", - phoneNumber2 = "phone_number_2", - phoneNumber3 = "phone_number_3" -} diff --git a/dist/build/src/sdkToEventsApiConverter.d.ts b/dist/build/src/sdkToEventsApiConverter.d.ts deleted file mode 100644 index 08bf810a1..000000000 --- a/dist/build/src/sdkToEventsApiConverter.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { SDKEvent, SDKConsentState, SDKGDPRConsentState, SDKGeoLocation, SDKCCPAConsentState, SDKProduct, SDKPromotion, SDKUserIdentity, SDKProductActionType, MParticleWebSDK, SDKIdentityTypeEnum } from './sdkRuntimeModels'; -import * as EventsApi from '@mparticle/event-models'; -export declare function convertEvents(mpid: string, sdkEvents: SDKEvent[], mpInstance: MParticleWebSDK): EventsApi.Batch | null; -export declare function convertConsentState(sdkConsentState?: SDKConsentState): EventsApi.ConsentState | null; -export declare function convertGdprConsentState(sdkGdprConsentState: SDKGDPRConsentState): { - [key: string]: EventsApi.GDPRConsentState | null; -}; -export declare function convertCcpaConsentState(sdkCcpaConsentState: SDKCCPAConsentState): { - data_sale_opt_out: EventsApi.CCPAConsentState; -}; -export declare function convertUserIdentities(sdkUserIdentities?: SDKUserIdentity[]): EventsApi.BatchUserIdentities | null; -export declare function convertEvent(sdkEvent: SDKEvent): EventsApi.BaseEvent | null; -export declare function convertProductActionType(actionType: SDKProductActionType): EventsApi.ProductActionActionEnum; -export declare function convertProductAction(sdkEvent: SDKEvent): EventsApi.ProductAction | null; -export declare function convertProducts(sdkProducts: SDKProduct[]): EventsApi.Product[] | null; -export declare function convertPromotionAction(sdkEvent: SDKEvent): EventsApi.PromotionAction | null; -export declare function convertPromotions(sdkPromotions: SDKPromotion[]): EventsApi.Promotion[] | null; -export declare function convertImpressions(sdkEvent: SDKEvent): EventsApi.ProductImpression[] | null; -export declare function convertShoppingCart(sdkEvent: SDKEvent): EventsApi.ShoppingCart | null; -export declare function convertCommerceEvent(sdkEvent: SDKEvent): EventsApi.CommerceEvent; -export declare function convertCrashReportEvent(sdkEvent: SDKEvent): EventsApi.CrashReportEvent; -export declare function convertAST(sdkEvent: SDKEvent): EventsApi.ApplicationStateTransitionEvent; -export declare function convertSessionEndEvent(sdkEvent: SDKEvent): EventsApi.SessionEndEvent; -export declare function convertSessionStartEvent(sdkEvent: SDKEvent): EventsApi.SessionStartEvent; -export declare function convertPageViewEvent(sdkEvent: SDKEvent): EventsApi.ScreenViewEvent; -export declare function convertOptOutEvent(sdkEvent: SDKEvent): EventsApi.OptOutEvent; -export declare function convertCustomEvent(sdkEvent: SDKEvent): EventsApi.CustomEvent; -export declare function convertSdkEventType(sdkEventType: number): EventsApi.CustomEventDataCustomEventTypeEnum | EventsApi.CommerceEventDataCustomEventTypeEnum; -export declare function convertBaseEventData(sdkEvent: SDKEvent): EventsApi.CommonEventData; -export declare function convertSDKLocation(sdkEventLocation: SDKGeoLocation): EventsApi.GeoLocation; -export declare function convertUserAttributeChangeEvent(sdkEvent: SDKEvent): EventsApi.UserAttributeChangeEvent | null; -export declare function convertUserIdentityChangeEvent(sdkEvent: SDKEvent): EventsApi.UserIdentityChangeEvent | null; -export declare function convertUserIdentityTypeToServerIdentityType(identityType: SDKIdentityTypeEnum): EventsApi.IdentityType; diff --git a/dist/build/src/utils.d.ts b/dist/build/src/utils.d.ts deleted file mode 100644 index 65e815275..000000000 --- a/dist/build/src/utils.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare type valueof = T[keyof T]; -declare const inArray: (items: any[], name: string) => boolean; -declare const findKeyInObject: (obj: any, key: string) => string; -declare const isObject: (value: any) => boolean; -declare const parseNumber: (value: string | number) => number; -declare const returnConvertedBoolean: (data: string | boolean | number) => boolean; -declare const decoded: (s: string) => string; -declare const converted: (s: string) => string; -export { valueof, converted, decoded, findKeyInObject, inArray, isObject, parseNumber, returnConvertedBoolean, }; diff --git a/dist/build/src/validators.d.ts b/dist/build/src/validators.d.ts deleted file mode 100644 index a597733a3..000000000 --- a/dist/build/src/validators.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import Constants from './constants'; -import { IdentityApiData } from '@mparticle/web-sdk'; -import { valueof } from './utils'; -declare type IdentityAPIMethod = 'login' | 'logout' | 'identify' | 'modify'; -declare type ValidationIdentitiesReturn = { - valid: boolean; - error?: valueof; -}; -declare const Validators: { - isValidAttributeValue: (value: any) => boolean; - isValidKeyValue: (key: any) => boolean; - isStringOrNumber: (value: any) => boolean; - isNumber: (value: any) => boolean; - isFunction: (fn: any) => boolean; - validateIdentities: (identityApiData: IdentityApiData, method?: IdentityAPIMethod) => ValidationIdentitiesReturn; -}; -export default Validators; diff --git a/dist/build/test/src/tests-batchUploader.d.ts b/dist/build/test/src/tests-batchUploader.d.ts deleted file mode 100644 index 91747f762..000000000 --- a/dist/build/test/src/tests-batchUploader.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; -declare global { - interface Window { - mParticle: MParticleWebSDK; - fetchMock: any; - } -} diff --git a/dist/build/test/src/tests-kit-blocking.d.ts b/dist/build/test/src/tests-kit-blocking.d.ts deleted file mode 100644 index 80f99eb44..000000000 --- a/dist/build/test/src/tests-kit-blocking.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; -declare global { - interface Window { - mParticle: MParticleWebSDK; - MockForwarder1: any; - } -} diff --git a/dist/build/test/src/tests-mockBatchCreator.d.ts b/dist/build/test/src/tests-mockBatchCreator.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/dist/build/test/src/tests-mockBatchCreator.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts b/dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts deleted file mode 100644 index 0bf9e0891..000000000 --- a/dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; -declare global { - interface Window { - mParticle: MParticleWebSDK; - } -} diff --git a/dist/build/test/src/tests-utils.d.ts b/dist/build/test/src/tests-utils.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/dist/build/test/src/tests-utils.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/dist/build/test/src/tests-validators.d.ts b/dist/build/test/src/tests-validators.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/dist/build/test/src/tests-validators.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/dist/mparticle.common.js b/dist/mparticle.common.js deleted file mode 100644 index a15e079ae..000000000 --- a/dist/mparticle.common.js +++ /dev/null @@ -1,1721 +0,0 @@ -if (typeof globalThis !== 'undefined') {globalThis.regeneratorRuntime = undefined} - -// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html -var Base64$1={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",// Input must be a string -encode:function(a){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(a)))}catch(a){console.error("Error encoding cookie values into Base64:"+a);}return this._encode(a)},_encode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=UTF8.encode(a);k>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),j=j+Base64$1._keyStr.charAt(e)+Base64$1._keyStr.charAt(f)+Base64$1._keyStr.charAt(g)+Base64$1._keyStr.charAt(h);return j},decode:function(a){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(a)))}catch(a){//log(e); -}return Base64$1._decode(a)},_decode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j+=String.fromCharCode(b),64!==g&&(j+=String.fromCharCode(c)),64!==h&&(j+=String.fromCharCode(d));return j=UTF8.decode(j),j}},UTF8={encode:function(a){for(var b,d="",e=0;eb?d+=String.fromCharCode(b):127b?(d+=String.fromCharCode(192|b>>6),d+=String.fromCharCode(128|63&b)):(d+=String.fromCharCode(224|b>>12),d+=String.fromCharCode(128|63&b>>6),d+=String.fromCharCode(128|63&b));return d},decode:function(a){for(var b="",d=0,e=0,f=0,g=0;de?(b+=String.fromCharCode(e),d++):191e?(f=a.charCodeAt(d+1),b+=String.fromCharCode((31&e)<<6|63&f),d+=2):(f=a.charCodeAt(d+1),g=a.charCodeAt(d+2),b+=String.fromCharCode((15&e)<<12|(63&f)<<6|63&g),d+=3);return b}};var Polyfill = {// forEach polyfill -// Production steps of ECMA-262, Edition 5, 15.4.4.18 -// Reference: http://es5.github.io/#x15.4.4.18 -forEach:function forEach(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - -var Messages$9=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return -?generateRandomValue()// if the placeholder was passed, return -:// [1e7] -> // 10000000 + -// -1e3 -> // -1000 + -// -4e3 -> // -4000 + -// -8e3 -> // -80000000 + -// -1e11 -> //-100000000000, -"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,// zeroes, ones, and eights with -generateUniqueId// random hex digits -)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d){var e=replaceAmpWithAmpersand(b),f=c?replaceAmpWithAmpersand(c):null,g=replaceMPID(e,a),h=f?replaceMPID(f,a):"",i=g+encodeURIComponent(h);if(d){var j=i.includes("?")?"&":"?";i+="".concat(j,"domain=").concat(d);}return i},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers -return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=e[a.toLowerCase()];b&&(d[a]=b);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie -var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys -// Parse cookies from document.cookie -// Filter cookies by keys if provided -return function filterCookies(a,b){for(var c={},d=0,e=a;db.length)return null;for(var d,e=c._IntegrationCapture,f=c._Helpers,g=f.getFeatureFlag,h=c.Identity.getCurrentUser(),i=[],j=null,k=0,l=b;k=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTimej.status)b.verbose("Upload success for request ID: ".concat(e[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later -return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads. -return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}(); - -var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$4=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache -if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back -var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$4||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so -// we sort the identities based on their enum. -// we create an array, set the user identity at the index of the user identity type -var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type -if(d){var f=[];// create an array where each index is equal to the user identity type -for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place -// before identify fires, so there may not be a cache. See what happens when -// the ? in idCache is removed to the following test -// "queued events contain login mpid instead of identify mpid when calling -// login immediately after mParticle initializes" -var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity -if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity -if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time. -// If the current time is greater than the expireTimestamp, it is not a valid -// cached identity. -var g=d[f].expireTimestamp;return !(ga._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$1.currentStorageName+"_"+a:StorageNames$1.currentStorageName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.parseStringOrNumber=parseStringOrNumber,this.generateHash=generateHash,this.generateUniqueId=generateUniqueId,this.Validators=Validators;} - -var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge -return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge -// TODO: what to do about people setting things on mParticle itself? -// android -},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName -},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var f,g,h=window[androidBridgeNameBase+"_"+e+"_v2"],i=iosBridgeNameBase+"_"+e+"_v2";return window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[i]&&(f=window.webkit.messageHandlers[i]),a.uiwebviewBridgeName===i&&(g=a[i]),h&&h.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void h[c](d)):void(f?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),f.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):g&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};} - -var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations -var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public -// Private -this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync -// dates. Skip cookie sync to avoid running it on every page load. -{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h=!1,j=e.filteringConsentRuleValues,k=e.pixelUrl,l=e.redirectUrl,m=e.moduleId,// Tells you how often we should do a cookie sync (in days) -n=e.frequencyCap,o=(j||{}).values;// set requiresConsent to false to start each additional pixel configuration -// set to true only if filteringConsenRuleValues.values.length exists -// Filtering rules as defined in UI -if(!isEmpty(k)&&(isEmpty(o)||(h=!0),!(h&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting()))// For Rokt, block cookie sync when noTargeting privacy flag is true -// If MPID is new to cookies, we should not try to perform the cookie sync -// because a cookie sync can only occur once a user either consents or doesn't. -// we should not check if it's enabled if the user has a blank consent -// The Trade Desk requires a URL parameter for GDPR enabled users. -// It is optional but to simplify the code, we add it for all Trade -// // Desk cookie syncs. -// Add domain parameter for Trade Desk -{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},r=q[m]||null;if(isLastSyncDateExpired(n,r)){var s=m===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,t=createCookieSyncUrl(c,k,l,s);b.performCookieSync(t,m.toString(),c,q);}}}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie -return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again -}; - -var Messages$6=Constants.Messages;function SessionManager(a){/** - * Checks if the session has expired based on the last event timestamp - * @param lastEventTimestamp - Unix timestamp in milliseconds of the last event - * @param sessionTimeout - Session timeout in minutes - * @returns true if the session has expired, false otherwise - */function b(a,b){if(!a||!b||0>=b)return !1;var c=Date.now()-a;return c>=6e4*b}/** - * Performs session end operations: - * - Logs a SessionEnd event - * - Nullifies the session ID and related data - * - Resets the time-on-site timer - */function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045 -// https://go.mparticle.com/work/SQDSDKS-6323 -var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab -if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};} - -var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// sanitizes any non number, non string value to 0 -this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801 -return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof$1(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0 -return a._Helpers.parseNumber(b)};} - -var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window -document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}(); - -function createSDKConfig(a){// TODO: Refactor to create a default config object -var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access -return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels -function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model -persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state -(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315 -var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g,h=a.workspaceToken,i=a.requiredWebviewBridgeName;a.flags&&(d.SDKConfig.flags=processFlags(a));var j=processBaseUrls(a,d.SDKConfig.flags,c);for(var k in j)d.SDKConfig[k]=j[k];if(h){d.SDKConfig.workspaceToken=h;var l=!0===(null===(g=null===a||void 0===a?void 0:a.launcherOptions)||void 0===g?void 0:g.noFunctional);b._timeOnSiteTimer=new ForegroundTimeTracker(h,l);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned -d.storageName=e(h),d.SDKConfig.requiredWebviewBridgeName=i||h,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317 -function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b):{};// https://go.mparticle.com/work/SQDSDKS-6317 -// Passed in config flags take priority over defaults -}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed -if(!c)return {};// Set default baseUrls -// When direct URL routing is false, update baseUrls based custom urls -// passed to the config -return b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a)}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c=Constants.CNAMEUrlPaths,d={};// newBaseUrls are default if the customer is not using a CNAME -// If a customer passes either config.domain or config.v3SecureServiceUrl, -// config.identityUrl, etc, the customer is using a CNAME. -// config.domain will take priority if a customer passes both. -// If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain. -// This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty -// if a customer is using a snippet prior to 2.6. -if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);return d}for(var f in b)d[f]=a[f]||b[f];return d}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that -// include the silo in the urls. mParticle API keys are prefixed with the -// silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo, -// and before other silos existed, there were no prefixes and all apiKeys -// were us1. As such, if we split on a '-' and the resulting array length -// is 1, then it is an older APIkey that should route to us1. -// When splitKey.length is greater than 1, then splitKey[0] will be -// us1, us2, eu1, au1, or st1, etc as new silos are added -for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct -// mapping to the silo. The most common use case is a customer provided CNAME. -if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} - -var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); - -var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 -// https://go.mparticle.com/work/SQDSDKS-6045 -// https://go.mparticle.com/work/SQDSDKS-5022 -// https://go.mparticle.com/work/SQDSDKS-6021 -// https://go.mparticle.com/work/SQDSDKS-5022 -// https://go.mparticle.com/work/SQDSDKS-6021 -/* This function determines if a cookie is greater than the configured maxCookieSize. - - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie. - - Once removed, check size, and repeat. - - Never remove the currentUser's MPID from the cookie. - - MPID removal priority: - 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie. - 2. If there are currentSessionMPIDs: - a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs - b. Then remove MPIDs based on order in currentSessionMPIDs array, which - stores MPIDs based on earliest login. -*/ // TODO: This should actually be decodePersistenceString or -// we should refactor this to take a string and return an object -// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible. -// For example subdomain.domain.co.uk would try the following combinations: -// "co.uk" -> fail -// "domain.co.uk" -> success, return -// "subdomain.domain.co.uk" -> skipped, because already found -// https://go.mparticle.com/work/SQDSDKS-6021 -/** - * set the "first seen" time for a user. the time will only be set once for a given - * mpid after which subsequent calls will be ignored - */ /** - * returns the "last seen" time for a user. If the mpid represents the current user, the - * return value will always be the current time, otherwise it will be to stored "last seen" - * time - */ // https://go.mparticle.com/work/SQDSDKS-6045 -// Forwarder Batching Code -this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var b,c,d=f.getLocalStorage(),e=f.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045 -// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle -// https://go.mparticle.com/work/SQDSDKS-6046 -// Stores all non-current user MPID information into the store -for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?a._Helpers.extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?a._Helpers.extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){var c;if(a._Store.isLocalStorageAvailable&&!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true -{var d=a._Store.storageName,e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(d),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;cf&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie -var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above -if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above -for(var n,o=0;of);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through -// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched -if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1= 0; --o) { - var i = this.tryEntries[o], - a = i.completion; - if ("root" === i.tryLoc) return handle("end"); - if (i.tryLoc <= this.prev) { - var c = n.call(i, "catchLoc"), - u = n.call(i, "finallyLoc"); - if (c && u) { - if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); - if (this.prev < i.finallyLoc) return handle(i.finallyLoc); - } else if (c) { - if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); - } else { - if (!u) throw new Error("try statement without catch or finally"); - if (this.prev < i.finallyLoc) return handle(i.finallyLoc); - } - } - } - }, - abrupt: function abrupt(t, e) { - for (var r = this.tryEntries.length - 1; r >= 0; --r) { - var o = this.tryEntries[r]; - if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { - var i = o; - break; - } - } - i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); - var a = i ? i.completion : {}; - return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); - }, - complete: function complete(t, e) { - if ("throw" === t.type) throw t.arg; - return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; - }, - finish: function finish(t) { - for (var e = this.tryEntries.length - 1; e >= 0; --e) { - var r = this.tryEntries[e]; - if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; - } - }, - "catch": function _catch(t) { - for (var e = this.tryEntries.length - 1; e >= 0; --e) { - var r = this.tryEntries[e]; - if (r.tryLoc === t) { - var n = r.completion; - if ("throw" === n.type) { - var o = n.arg; - resetTryEntry(r); - } - return o; - } - } - throw new Error("illegal catch attempt"); - }, - delegateYield: function delegateYield(e, r, n) { - return this.delegate = { - iterator: values(e), - resultName: r, - nextLoc: n - }, "next" === this.method && (this.arg = t), y; - } - }, e; - } - module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; -} (regeneratorRuntime$1)); - -var regeneratorRuntimeExports = regeneratorRuntime$1.exports; - -// TODO(Babel 8): Remove this file. - -var runtime = regeneratorRuntimeExports(); -var regenerator = runtime; - -// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= -try { - regeneratorRuntime = runtime; -} catch (accidentalStrictMode) { - if (typeof globalThis === "object") { - globalThis.regeneratorRuntime = runtime; - } else { - Function("r", "regeneratorRuntime = r")(runtime); - } -} - -var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator); - -function filteredMparticleUser(a,b,c,d){var e=this;return {getUserIdentities:function getUserIdentities(){var e={},f=c._Store.getUserIdentities(a);for(var g in f)if(f.hasOwnProperty(g)){var h=Types.IdentityType.getIdentityName(c._Helpers.parseNumber(g));d&&(!d||d.isIdentityBlocked(h))||(//if identity type is not blocked -e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Store.getUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}} - -var _Constants$IdentityMe=Constants.IdentityMethods,Modify$2=_Constants$IdentityMe.Modify,Identify$1=_Constants$IdentityMe.Identify,Login$1=_Constants$IdentityMe.Login,Logout$1=_Constants$IdentityMe.Logout;function Forwarders(a,b){var c=this,d=this;this.forwarderStatsUploader=new APIClient(a,b).initializeForwarderStatsUploader();var e={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// TODO: https://go.mparticle.com/work/SQDSDKS-6036 -// Processing forwarders is a 2 step process: -// 1. Configure the kit -// 2. Initialize the kit -// There are 2 types of kits: -// 1. UI-enabled kits -// 2. Sideloaded kits. -// These are kits that are enabled via the mParticle UI. -// A kit that is UI-enabled will have a kit configuration that returns from -// the server, or in rare cases, is passed in by the developer. -// The kit configuration will be compared with the kit constructors to determine -// if there is a match before being initialized. -// Only kits that are configured properly can be active and used for kit forwarding. -// Unlike UI enabled kits, sideloaded kits are always added to active forwarders. -// TODO: Sideloading kits currently require the use of a register method -// which requires an object on which to be registered. -// In the future, when all kits are moved to the mpConfig rather than -// there being a separate process for MP configured kits and -// sideloaded kits, this will need to be refactored. -// kits can be included via mParticle UI, or via sideloaded kit config API -this.initForwarders=function(b,c){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!d.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!d.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=a._Helpers.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,c,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;var d,e,f;if(!c)return !1;f=c.getAllUserAttributes();var g=!1;try{if(f&&a._Helpers.isObject(f)&&Object.keys(f).length)for(var h in f)if(f.hasOwnProperty(h)&&(d=KitFilterHelper.hashAttributeConditionalForwarding(h),e=KitFilterHelper.hashAttributeConditionalForwarding(f[h]),d===b.userAttributeName&&e===b.userAttributeValue)){g=!0;break}return !b||b.includeOnMatch===g}catch(a){// in any error scenario, err on side of returning true and forwarding event -return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){var c,d,e,f=function(b,c){b.UserIdentities&&b.UserIdentities.length&&b.UserIdentities.forEach(function(d,e){a._Helpers.inArray(c,KitFilterHelper.hashUserIdentity(d.Type))&&(b.UserIdentities.splice(e,1),0e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate. -throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}(); - -var processReadyQueue=function(a){return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]};var processPreloadedItem=function(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it -if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(window.mParticle,b);else {var d=c.split(".");try{// Track both the function and its context -for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;hd?-1:1}),c},/** - * Initiate an alias request to the mParticle server - * @method aliasUsers - * @param {Object} aliasRequest object representing an AliasRequest - * @param {Function} [callback] A callback function that is called when the aliasUsers request completes - */aliasUsers:function aliasUsers(b,c){var d;if(b.destinationMpid&&b.sourceMpid||(d=Messages$2.ValidationMessages.AliasMissingMpid),b.destinationMpid===b.sourceMpid&&(d=Messages$2.ValidationMessages.AliasNonUniqueMpid),b.startTime&&b.endTime||(d=Messages$2.ValidationMessages.AliasMissingTime),b.startTime>b.endTime&&(d=Messages$2.ValidationMessages.AliasStartBeforeEndTime),d)return a.Logger.warning(d),void a._Helpers.invokeAliasCallback(c,HTTPCodes$2.validationIssue,d);if(!a._Helpers.canLog())a._Helpers.invokeAliasCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),a.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(a._Identity.IdentityRequest.convertAliasToNative(b))),a._Helpers.invokeAliasCallback(c,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {a.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+b.sourceMpid+" -> "+b.destinationMpid);var e=a._Identity.IdentityRequest.createAliasNetworkRequest(b);a._IdentityAPIClient.sendAliasRequest(e,c);}},/** - Create a default AliasRequest for 2 MParticleUsers. This will construct the request - using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime. - - In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only - be the case if they have not been the current user since this functionality was added, the - startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly, - if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time - - There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days. - If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime. - In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit, - after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() - validation that the startTime must be less than the endTime - */createAliasRequest:function createAliasRequest(b,c,d){try{if(!c||!b)return a.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var e=b.getFirstSeenTime();e||a.Identity.getUsers().forEach(function(a){a.getFirstSeenTime()&&(!e||a.getFirstSeenTime() - * Usage: const consent = mParticle.Consent.createConsentState() - *
- * consent.setGDPRCoonsentState() - * - * @class Consent - */ /** - * Add a GDPR Consent State to the consent state object - * - * @method addGDPRConsentState - * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data - * @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...) - */function e(c,e){var f=d(c);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=b.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/** - * Remove a GDPR Consent State to the consent state object - * - * @method removeGDPRConsentState - * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data - */function g(a){var b=d(a);return b?(delete k[b],this):this}/** - * Gets the GDPR Consent State - * - * @method getGDPRConsentState - * @return {Object} A GDPR Consent State - */function h(){return Object.assign({},k)}/** - * Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out') - * - * @method setCCPAConsentState - * @param {Object} ccpaConsent CCPA Consent State - */function i(c){if(!isObject(c))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=b.createPrivacyConsent(c.Consented,c.Timestamp,c.ConsentDocument,c.Location,c.HardwareId);return d&&(l[CCPAPurpose]=d),this}/** - * Gets the CCPA Consent State - * - * @method getCCPAConsentStatensent - * @return {Object} A CCPA Consent State - */ /** - * Removes CCPA from the consent state object - * - * @method removeCCPAConsentState - */function j(){return delete l[CCPAPurpose],this}// TODO: Can we remove this? It is deprecated. -var k={},l={};if(c){var m=b.createConsentState();// TODO: Remove casting once `removeCCPAState` is removed; -return m.setGDPRConsentState(c.getGDPRConsentState()),m.setCCPAConsentState(c.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAState:function b(){// @ts-ignore -return a.Logger.warning("removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"),j()},removeCCPAConsentState:j}};} - -/* - TODO: Including this as a workaround because attempting to import it from - @mparticle/data-planning-models directly creates a build error. - */var DataPlanMatchType={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},KitBlocker=/** @class */function(){function a(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r=this;// if data plan is not requested, the data plan is {document: null} -if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,a&&!a.document)return void(this.kitBlockingEnabled=!1);this.kitBlockingEnabled=!0,this.mpInstance=b,this.blockEvents=null===(e=null===(d=null===(c=null===a||void 0===a?void 0:a.document)||void 0===c?void 0:c.dtpn)||void 0===d?void 0:d.blok)||void 0===e?void 0:e.ev,this.blockEventAttributes=null===(h=null===(g=null===(f=null===a||void 0===a?void 0:a.document)||void 0===f?void 0:f.dtpn)||void 0===g?void 0:g.blok)||void 0===h?void 0:h.ea,this.blockUserAttributes=null===(k=null===(j=null===(i=null===a||void 0===a?void 0:a.document)||void 0===i?void 0:i.dtpn)||void 0===j?void 0:j.blok)||void 0===k?void 0:k.ua,this.blockUserIdentities=null===(n=null===(m=null===(l=null===a||void 0===a?void 0:a.document)||void 0===l?void 0:l.dtpn)||void 0===m?void 0:m.blok)||void 0===n?void 0:n.id;var s=null===(q=null===(p=null===(o=null===a||void 0===a?void 0:a.document)||void 0===o?void 0:o.dtpn)||void 0===p?void 0:p.vers)||void 0===q?void 0:q.version_document,t=null===s||void 0===s?void 0:s.data_points;if(s)try{0<(null===t||void 0===t?void 0:t.length)&&t.forEach(function(a){return r.addToMatchLookups(a)});}catch(a){this.mpInstance.Logger.error("There was an issue with the data plan: "+a);}}return a.prototype.addToMatchLookups=function(a){var b,c,d;if(!a.match||!a.validator)return void this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(a));// match keys for non product custom attribute related data points -var e=this.generateMatchKey(a.match),f=this.getPlannedProperties(a.match.type,a.validator);this.dataPlanMatchLookups[e]=f,((null===(b=null===a||void 0===a?void 0:a.match)||void 0===b?void 0:b.type)===DataPlanMatchType.ProductImpression||(null===(c=null===a||void 0===a?void 0:a.match)||void 0===c?void 0:c.type)===DataPlanMatchType.ProductAction||(null===(d=null===a||void 0===a?void 0:a.match)||void 0===d?void 0:d.type)===DataPlanMatchType.PromotionAction)&&(e=this.generateProductAttributeMatchKey(a.match),f=this.getProductProperties(a.match.type,a.validator),this.dataPlanMatchLookups[e]=f);},a.prototype.generateMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.CustomEvent:var c=b;return [DataPlanMatchType.CustomEvent,c.custom_event_type,c.event_name].join(":");case DataPlanMatchType.ScreenView:return [DataPlanMatchType.ScreenView,"",b.screen_name].join(":");case DataPlanMatchType.ProductAction:return [a.type,b.action].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action].join(":");case DataPlanMatchType.ProductImpression:return [a.type,b.action].join(":");case DataPlanMatchType.UserIdentities:case DataPlanMatchType.UserAttributes:return [a.type].join(":");default:return null}},a.prototype.generateProductAttributeMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.ProductAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.ProductImpression:return [a.type,"ProductAttributes"].join(":");default:return null}},a.prototype.getPlannedProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l;switch(a){case DataPlanMatchType.CustomEvent:case DataPlanMatchType.ScreenView:case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction:case DataPlanMatchType.ProductImpression:if(k=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.custom_attributes,k){if(!0===k.additionalProperties||void 0===k.additionalProperties)return !0;for(var m,n={},o=0,p=Object.keys(k.properties);o=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} - -// The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: -// - version is always this prefix: fb -// - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2) -// - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value -// - is the value for the fbclid query parameter in the page URL. -// https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc -var facebookClickIdProcessor=function(a,b,c){if(!a||!b)return "";var d=null===b||void 0===b?void 0:b.split("//");if(!d)return "";var e=d[1].split("/"),f=e[0].split("."),g=1;// The rules for subdomainIndex are for parsing the domain portion -// of the URL for cookies, but in this case we are parsing the URL -// itself, so we can ignore the use of 0 for 'com' -3<=f.length&&(g=2);// If timestamp is not provided, use the current time -var h=c||Date.now();return "fb.".concat(g,".").concat(h,".").concat(a)};// Integration outputs are used to determine how click ids are used within the SDK -// CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject -// PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch -// INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created -var IntegrationOutputs={CUSTOM_FLAGS:"custom_flags",PARTNER_IDENTITIES:"partner_identities",INTEGRATION_ATTRIBUTES:"integration_attributes"},integrationMappingExternal={// Facebook / Meta -fbclid:{mappedKey:"Facebook.ClickId",processor:facebookClickIdProcessor,output:IntegrationOutputs.CUSTOM_FLAGS},_fbp:{mappedKey:"Facebook.BrowserId",output:IntegrationOutputs.CUSTOM_FLAGS},_fbc:{mappedKey:"Facebook.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Google -gclid:{mappedKey:"GoogleEnhancedConversions.Gclid",output:IntegrationOutputs.CUSTOM_FLAGS},gbraid:{mappedKey:"GoogleEnhancedConversions.Gbraid",output:IntegrationOutputs.CUSTOM_FLAGS},wbraid:{mappedKey:"GoogleEnhancedConversions.Wbraid",output:IntegrationOutputs.CUSTOM_FLAGS},// TIKTOK -ttclid:{mappedKey:"TikTok.Callback",output:IntegrationOutputs.CUSTOM_FLAGS},_ttp:{mappedKey:"tiktok_cookie_id",output:IntegrationOutputs.PARTNER_IDENTITIES},// Snapchat -// https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US -ScCid:{mappedKey:"SnapchatConversions.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Snapchat -// https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id -_scid:{mappedKey:"SnapchatConversions.Cookie1",output:IntegrationOutputs.CUSTOM_FLAGS}},integrationMappingRokt={// Rokt -// https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/ -// https://go.mparticle.com/work/SQDSDKS-7167 -rtid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},rclid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},RoktTransactionId:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277}},IntegrationCapture=/** @class */function(){function a(a){this.initialTimestamp=Date.now(),this.captureMode=a,this.filteredPartnerIdentityMappings=this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES),this.filteredCustomFlagMappings=this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS),this.filteredIntegrationAttributeMappings=this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);}/** - * Captures Integration Ids from cookies and query params and stores them in clickIds object - */return a.prototype.capture=function(){var a=this.captureQueryParams()||{},b=this.captureCookies()||{},c=this.captureLocalStorage()||{};a.fbclid&&b._fbc&&delete b._fbc;// ROKT Rules -// If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid -// If RoktTransactionId is present in both cookies and localStorage, -// prioritize localStorage -var d=a.rtid||a.rclid,e=c.RoktTransactionId,f=b.RoktTransactionId;d?(e&&delete c.RoktTransactionId,f&&delete b.RoktTransactionId):e&&f&&delete b.RoktTransactionId,this.clickIds=__assign(__assign(__assign(__assign({},this.clickIds),a),c),b);},a.prototype.captureCookies=function(){var a=this.getAllowedKeysForMode(),b=getCookies(a);return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.captureQueryParams=function(){var a=this.getQueryParams();return this.applyProcessors(a,getHref(),this.initialTimestamp)},a.prototype.captureLocalStorage=function(){for(var a=this.getAllowedKeysForMode(),b={},c=0,d=a;c": { -// "mappedKey": "clickIdValue" -// } -// } -// } -for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}(); - -// Rokt Web SDK via a Web Kit. -// The Rokt Manager should load before the Web Kit and stubs out many of the -// Rokt Web SDK functions with an internal message queue in case a Rokt function -// is requested before the Rokt Web Kit or SDK is finished loaded. -// Once the Rokt Kit is attached to the Rokt Manager, we can consider the -// Rokt Manager in a "ready" state and it can begin sending data to the kit. -// -// https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt -var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1;}/** - * Sets a callback to be invoked when RoktManager becomes ready - */return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g){var h,i,j=a||{},k=j.userAttributeFilters,l=j.settings,m=l||{},n=m.placementAttributesMapping,o=m.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(h=null===o||void 0===o?void 0:o.toLowerCase())&&void 0!==h?h:null,this.identityService=c,this.store=d,this.logger=e,this.captureTiming=g,null===(i=this.captureTiming)||void 0===i?void 0:i.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:k,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(n);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode -// It is set here and passed in to the createLauncher method in the Rokt Kit -// This is not to be confused for the `sandbox` flag in the selectPlacements attributes -// as that is independent of this setting, though they share the same name. -var p=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through -// to the Rokt Launcher. -this.launcherOptions=__assign({sandbox:p},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h;return __awaiter(this,void 0,void 0,function(){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A=this;return __generator(this,function(B){switch(B.label){case 0:// Queue if kit isn't ready OR if identity is in flight -if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];B.label=1;case 1:if(B.trys.push([1,6,,7]),i=a.attributes,j=(null===i||void 0===i?void 0:i.sandbox)||null,k=this.mapPlacementAttributes(i,this.placementAttributesMapping),null===(d=this.logger)||void 0===d?void 0:d.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(i,null,2))),this.currentUser=this.identityService.getCurrentUser(),l=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},m=l.email,n=k.email,o=void 0,p=void 0,q=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),q&&(o=l[this.mappedEmailShaIdentityType],p=k.emailsha256||k[this.mappedEmailShaIdentityType]||void 0),r=this.hasIdentityChanged(m,n),s=this.hasIdentityChanged(o,p),t={},r&&(t.email=n,n&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),s&&(t[this.mappedEmailShaIdentityType]=p,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(t))return [3/*break*/,5];B.label=2;case 2:return B.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){A.identityService.identify({userIdentities:__assign(__assign({},l),t)},function(){a();});})];case 3:return B.sent(),[3/*break*/,5];case 4:return u=B.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(u)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),v=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},this.setUserAttributes(k),w=__assign(__assign({},k),null===j?{}:{sandbox:j}),v.email&&!w.email&&(w.email=v.email),q&&(x=v[this.mappedEmailShaIdentityType],x&&!w.emailsha256&&!w[this.mappedEmailShaIdentityType]&&(w.emailsha256=x)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,y=__assign(__assign({},a),{attributes:w}),[2/*return*/,this.kit.selectPlacements(y)];case 6:return z=B.sent(),[2/*return*/,Promise.reject(z instanceof Error?z:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);fAll of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

- *

In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.

- *

This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().

- *

If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:

- * - * mParticle.init('apiKey', config, 'another_instance'); - * mParticle.getInstance('another_instance').logPageView(); - * - * - * @class mParticle & mParticleInstance - */function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption -this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization -// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization -// to it for it to be run after fetched -if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval -b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** - * Creates a CCPA Opt Out Consent State. - * - * @method createCCPAConsent - * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" - * @param {Number} timestamp Unix time (likely to be Date.now()) - * @param {String} consentDocument document version or experience that the user may have consented to - * @param {String} location location where the user gave consent - * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users - * @return {Object} CCPA Consent State - */createCCPAConsent:b._Consent.createPrivacyConsent,/** - * Creates a GDPR Consent State. - * - * @method createGDPRConsent - * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" - * @param {Number} timestamp Unix time (likely to be Date.now()) - * @param {String} consentDocument document version or experience that the user may have consented to - * @param {String} location location where the user gave consent - * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users - * @return {Object} GDPR Consent State - */createGDPRConsent:b._Consent.createPrivacyConsent,/** - * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states. - * - * @method createConsentState - * @return {Object} ConsentState object - */createConsentState:b._Consent.createConsentState},this.eCommerce={/** - * Invoke these methods on the mParticle.eCommerce.Cart object. - * Example: mParticle.eCommerce.Cart.add(...) - * @class mParticle.eCommerce.Cart - * @deprecated - */Cart:{/** - * Adds a product to the cart - * @method add - * @param {Object} product The product you want to add to the cart - * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. - * @deprecated - */add:function add(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** - * Removes a product from the cart - * @method remove - * @param {Object} product The product you want to add to the cart - * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. - * @deprecated - */remove:function remove(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** - * Clears the cart - * @method clear - * @deprecated - */clear:function clear(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));}},/** - * Sets the currency code - * @for mParticle.eCommerce - * @method setCurrencyCode - * @param {String} code The currency code - */setCurrencyCode:function setCurrencyCode(a){var c=queueIfNotInitialized(function(){b.eCommerce.setCurrencyCode(a);},b);return c?void 0:"string"==typeof a?void(b._SessionManager.resetSessionTimer(),b._Store.currencyCode=a):void b.Logger.error("Code must be a string")},/** - * Creates a product - * @for mParticle.eCommerce - * @method createProduct - * @param {String} name product name - * @param {String} sku product sku - * @param {Number} price product price - * @param {Number} [quantity] product quantity. If blank, defaults to 1. - * @param {String} [variant] product variant - * @param {String} [category] product category - * @param {String} [brand] product brand - * @param {Number} [position] product position - * @param {String} [coupon] product coupon - * @param {Object} [attributes] product attributes - */createProduct:function createProduct(a,c,d,e,f,g,h,i,j,k){return b._Ecommerce.createProduct(a,c,d,e,f,g,h,i,j,k)},/** - * Creates a promotion - * @for mParticle.eCommerce - * @method createPromotion - * @param {String} id a unique promotion id - * @param {String} [creative] promotion creative - * @param {String} [name] promotion name - * @param {Number} [position] promotion position - */createPromotion:function createPromotion(a,c,d,e){return b._Ecommerce.createPromotion(a,c,d,e)},/** - * Creates a product impression - * @for mParticle.eCommerce - * @method createImpression - * @param {String} name impression name - * @param {Object} product the product for which an impression is being created - */createImpression:function createImpression(a,c){return b._Ecommerce.createImpression(a,c)},/** - * Creates a transaction attributes object to be used with a checkout - * @for mParticle.eCommerce - * @method createTransactionAttributes - * @param {String or Number} id a unique transaction id - * @param {String} [affiliation] affilliation - * @param {String} [couponCode] the coupon code for which you are creating transaction attributes - * @param {Number} [revenue] total revenue for the product being purchased - * @param {String} [shipping] the shipping method - * @param {Number} [tax] the tax amount - */createTransactionAttributes:function createTransactionAttributes(a,c,d,e,f,g){return b._Ecommerce.createTransactionAttributes(a,c,d,e,f,g)},/** - * Logs a checkout action - * @for mParticle.eCommerce - * @method logCheckout - * @param {Number} step checkout step number - * @param {String} checkout option string - * @param {Object} attrs - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */logCheckout:function logCheckout(a,c,d,e){return b.Logger.warning("mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logCheckoutEvent(a,c,d,e)):void b.ready(function(){b.eCommerce.logCheckout(a,c,d,e);})},/** - * Logs a product action - * @for mParticle.eCommerce - * @method logProductAction - * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218) - * @param {Object} product the product for which you are creating the product action - * @param {Object} [attrs] attributes related to the product action - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [transactionAttributes] Transaction Attributes for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */logProductAction:function logProductAction(a,c,d,e,f,g){var h=queueIfNotInitialized(function(){b.eCommerce.logProductAction(a,c,d,e,f,g);},b);h||(b._SessionManager.resetSessionTimer(),b._Events.logProductActionEvent(a,c,d,e,f,g));},/** - * Logs a product purchase - * @for mParticle.eCommerce - * @method logPurchase - * @param {Object} transactionAttributes transactionAttributes object - * @param {Object} product the product being purchased - * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false - * @param {Object} [attrs] other attributes related to the product purchase - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */logPurchase:function logPurchase(a,c,d,e,f){return b.Logger.warning("mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?a&&c?void(b._SessionManager.resetSessionTimer(),b._Events.logPurchaseEvent(a,c,e,f)):void b.Logger.error(Messages.ErrorMessages.BadLogPurchase):void b.ready(function(){b.eCommerce.logPurchase(a,c,d,e,f);})},/** - * Logs a product promotion - * @for mParticle.eCommerce - * @method logPromotion - * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279) - * @param {Object} promotion promotion object - * @param {Object} [attrs] boolean to clear the cart after logging or not - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */logPromotion:function logPromotion(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.eCommerce.logPromotion(a,c,d,e,f);},b);g||(b._SessionManager.resetSessionTimer(),b._Events.logPromotionEvent(a,c,d,e,f));},/** - * Logs a product impression - * @for mParticle.eCommerce - * @method logImpression - * @param {Object} impression product impression object - * @param {Object} attrs attributes related to the impression log - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */logImpression:function logImpression(a,c,d,e){var f=queueIfNotInitialized(function(){b.eCommerce.logImpression(a,c,d,e);},b);f||(b._SessionManager.resetSessionTimer(),b._Events.logImpressionEvent(a,c,d,e));},/** - * Logs a refund - * @for mParticle.eCommerce - * @method logRefund - * @param {Object} transactionAttributes transaction attributes related to the refund - * @param {Object} product product being refunded - * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false. - * @param {Object} [attrs] attributes related to the refund - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie -// And logs to in-memory object -// Example: mParticle.setSessionAttribute('location', '33431'); -if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed -if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any -// other integration delays set to true. It not, process the queued events/. -var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment -function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's -// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not -// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize -// persistence or Identity directly. -if(c._APIClient=new APIClient(c,f),c._Forwarders=new Forwarders(c,f),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use -var h=c.Identity.getCurrentUser(),i=h?h.getMPID():null,j=h?h.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:j}:c._Store.SDKConfig.identifyRequest,g(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639 -var k=g(CaptureIntegrationSpecificIds),l=g(CaptureIntegrationSpecificIdsV2),m=l&&l!==CaptureIntegrationSpecificIdsV2Modes.None||!0===k;if(m){var n;k||l===CaptureIntegrationSpecificIdsV2Modes.All?n="all":l===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(n="roktonly"),c._IntegrationCapture=new IntegrationCapture(n),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user -var o=parseConfig(b,"Rokt",181);if(o){var p=null===(d=o.settings)||void 0===d?void 0:d.accountId;c._Store.setRoktAccountId(p);var q=o.userAttributeFilters,r=filteredMparticleUser(i,{userAttributeFilters:q},c),s={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339 -c._RoktManager.init(o,r,c.Identity,c._Store,c.Logger,s,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,h,i,j);}// We will continue to clear out the ready queue as part of the initial init flow -// if an identify request is unnecessary, such as if there is an existing session -(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),null===(e=c.processQueueOnNoFunctional)||void 0===e?void 0:e.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061 -function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK: - 1. Manually via config.dataPlanOptions (this takes priority) - If not passed in manually, we user the server provided via either - 2. Snippet via /mparticle.js endpoint (config.dataPlan.document) - 3. Self hosting via /config endpoint (config.dataPlanResult) - */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault -// ensures no identity response data is written to localStorage when noFunctional is true -return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions -var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs -// since we will need this for the current implementation of user persistence -// TODO: Refactor this when we refactor User Identity Persistence -try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never -// receive an MPID. Let these calls through so events can still reach forwarders immediately. -// sendEventToServer handles queuing for the MP server upload path separately. -return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)} - -// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise! -var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method -_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:mockFunction},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}(); - -var MPSideloadedKit=/** @class */function(){function a(a){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],// The below filtering members are optional, but we instantiate them -// to simplify public method assignment -filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=a;}return a.prototype.addEventTypeFilter=function(a){var b=KitFilterHelper.hashEventType(a);this.filterDictionary.eventTypeFilters.push(b);},a.prototype.addEventNameFilter=function(a,b){var c=KitFilterHelper.hashEventName(b,a);this.filterDictionary.eventNameFilters.push(c);},a.prototype.addEventAttributeFilter=function(a,b,c){var d=KitFilterHelper.hashEventAttributeKey(a,b,c);this.filterDictionary.attributeFilters.push(d);},a.prototype.addScreenNameFilter=function(a){var b=KitFilterHelper.hashEventName(a,EventType.Unknown);this.filterDictionary.screenNameFilters.push(b);},a.prototype.addScreenAttributeFilter=function(a,b){var c=KitFilterHelper.hashEventAttributeKey(EventType.Unknown,a,b);this.filterDictionary.screenAttributeFilters.push(c);},a.prototype.addUserIdentityFilter=function(a){var b=KitFilterHelper.hashUserIdentity(a);this.filterDictionary.userIdentityFilters.push(b);},a.prototype.addUserAttributeFilter=function(a){var b=KitFilterHelper.hashUserAttribute(a);this.filterDictionary.userAttributeFilters.push(b);},a}(); - -Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticleInstanceManager(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing -/** - * Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used. - *

- * If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below. - * @method init - * @param {String} apiKey your mParticle assigned API key - * @param {Object} [config] an options object for additional configuration - * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); - -module.exports = mParticleManager; diff --git a/dist/mparticle.esm.js b/dist/mparticle.esm.js deleted file mode 100644 index 75a493c69..000000000 --- a/dist/mparticle.esm.js +++ /dev/null @@ -1,1721 +0,0 @@ -if (typeof globalThis !== 'undefined') {globalThis.regeneratorRuntime = undefined} - -// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html -var Base64$1={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",// Input must be a string -encode:function(a){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(a)))}catch(a){console.error("Error encoding cookie values into Base64:"+a);}return this._encode(a)},_encode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=UTF8.encode(a);k>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),j=j+Base64$1._keyStr.charAt(e)+Base64$1._keyStr.charAt(f)+Base64$1._keyStr.charAt(g)+Base64$1._keyStr.charAt(h);return j},decode:function(a){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(a)))}catch(a){//log(e); -}return Base64$1._decode(a)},_decode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j+=String.fromCharCode(b),64!==g&&(j+=String.fromCharCode(c)),64!==h&&(j+=String.fromCharCode(d));return j=UTF8.decode(j),j}},UTF8={encode:function(a){for(var b,d="",e=0;eb?d+=String.fromCharCode(b):127b?(d+=String.fromCharCode(192|b>>6),d+=String.fromCharCode(128|63&b)):(d+=String.fromCharCode(224|b>>12),d+=String.fromCharCode(128|63&b>>6),d+=String.fromCharCode(128|63&b));return d},decode:function(a){for(var b="",d=0,e=0,f=0,g=0;de?(b+=String.fromCharCode(e),d++):191e?(f=a.charCodeAt(d+1),b+=String.fromCharCode((31&e)<<6|63&f),d+=2):(f=a.charCodeAt(d+1),g=a.charCodeAt(d+2),b+=String.fromCharCode((15&e)<<12|(63&f)<<6|63&g),d+=3);return b}};var Polyfill = {// forEach polyfill -// Production steps of ECMA-262, Edition 5, 15.4.4.18 -// Reference: http://es5.github.io/#x15.4.4.18 -forEach:function forEach(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - -var Messages$9=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return -?generateRandomValue()// if the placeholder was passed, return -:// [1e7] -> // 10000000 + -// -1e3 -> // -1000 + -// -4e3 -> // -4000 + -// -8e3 -> // -80000000 + -// -1e11 -> //-100000000000, -"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,// zeroes, ones, and eights with -generateUniqueId// random hex digits -)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d){var e=replaceAmpWithAmpersand(b),f=c?replaceAmpWithAmpersand(c):null,g=replaceMPID(e,a),h=f?replaceMPID(f,a):"",i=g+encodeURIComponent(h);if(d){var j=i.includes("?")?"&":"?";i+="".concat(j,"domain=").concat(d);}return i},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers -return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=e[a.toLowerCase()];b&&(d[a]=b);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie -var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys -// Parse cookies from document.cookie -// Filter cookies by keys if provided -return function filterCookies(a,b){for(var c={},d=0,e=a;db.length)return null;for(var d,e=c._IntegrationCapture,f=c._Helpers,g=f.getFeatureFlag,h=c.Identity.getCurrentUser(),i=[],j=null,k=0,l=b;k=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTimej.status)b.verbose("Upload success for request ID: ".concat(e[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later -return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads. -return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}(); - -var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$4=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache -if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back -var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$4||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so -// we sort the identities based on their enum. -// we create an array, set the user identity at the index of the user identity type -var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type -if(d){var f=[];// create an array where each index is equal to the user identity type -for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place -// before identify fires, so there may not be a cache. See what happens when -// the ? in idCache is removed to the following test -// "queued events contain login mpid instead of identify mpid when calling -// login immediately after mParticle initializes" -var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity -if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity -if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time. -// If the current time is greater than the expireTimestamp, it is not a valid -// cached identity. -var g=d[f].expireTimestamp;return !(ga._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$1.currentStorageName+"_"+a:StorageNames$1.currentStorageName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.parseStringOrNumber=parseStringOrNumber,this.generateHash=generateHash,this.generateUniqueId=generateUniqueId,this.Validators=Validators;} - -var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge -return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge -// TODO: what to do about people setting things on mParticle itself? -// android -},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName -},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var f,g,h=window[androidBridgeNameBase+"_"+e+"_v2"],i=iosBridgeNameBase+"_"+e+"_v2";return window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[i]&&(f=window.webkit.messageHandlers[i]),a.uiwebviewBridgeName===i&&(g=a[i]),h&&h.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void h[c](d)):void(f?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),f.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):g&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};} - -var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations -var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public -// Private -this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync -// dates. Skip cookie sync to avoid running it on every page load. -{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h=!1,j=e.filteringConsentRuleValues,k=e.pixelUrl,l=e.redirectUrl,m=e.moduleId,// Tells you how often we should do a cookie sync (in days) -n=e.frequencyCap,o=(j||{}).values;// set requiresConsent to false to start each additional pixel configuration -// set to true only if filteringConsenRuleValues.values.length exists -// Filtering rules as defined in UI -if(!isEmpty(k)&&(isEmpty(o)||(h=!0),!(h&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting()))// For Rokt, block cookie sync when noTargeting privacy flag is true -// If MPID is new to cookies, we should not try to perform the cookie sync -// because a cookie sync can only occur once a user either consents or doesn't. -// we should not check if it's enabled if the user has a blank consent -// The Trade Desk requires a URL parameter for GDPR enabled users. -// It is optional but to simplify the code, we add it for all Trade -// // Desk cookie syncs. -// Add domain parameter for Trade Desk -{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},r=q[m]||null;if(isLastSyncDateExpired(n,r)){var s=m===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,t=createCookieSyncUrl(c,k,l,s);b.performCookieSync(t,m.toString(),c,q);}}}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie -return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again -}; - -var Messages$6=Constants.Messages;function SessionManager(a){/** - * Checks if the session has expired based on the last event timestamp - * @param lastEventTimestamp - Unix timestamp in milliseconds of the last event - * @param sessionTimeout - Session timeout in minutes - * @returns true if the session has expired, false otherwise - */function b(a,b){if(!a||!b||0>=b)return !1;var c=Date.now()-a;return c>=6e4*b}/** - * Performs session end operations: - * - Logs a SessionEnd event - * - Nullifies the session ID and related data - * - Resets the time-on-site timer - */function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045 -// https://go.mparticle.com/work/SQDSDKS-6323 -var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab -if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};} - -var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// https://go.mparticle.com/work/SQDSDKS-4801 -// sanitizes any non number, non string value to 0 -this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801 -return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof$1(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0 -return a._Helpers.parseNumber(b)};} - -var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window -document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}(); - -function createSDKConfig(a){// TODO: Refactor to create a default config object -var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access -return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels -function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model -persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state -(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315 -var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g,h=a.workspaceToken,i=a.requiredWebviewBridgeName;a.flags&&(d.SDKConfig.flags=processFlags(a));var j=processBaseUrls(a,d.SDKConfig.flags,c);for(var k in j)d.SDKConfig[k]=j[k];if(h){d.SDKConfig.workspaceToken=h;var l=!0===(null===(g=null===a||void 0===a?void 0:a.launcherOptions)||void 0===g?void 0:g.noFunctional);b._timeOnSiteTimer=new ForegroundTimeTracker(h,l);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned -d.storageName=e(h),d.SDKConfig.requiredWebviewBridgeName=i||h,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317 -function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b):{};// https://go.mparticle.com/work/SQDSDKS-6317 -// Passed in config flags take priority over defaults -}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed -if(!c)return {};// Set default baseUrls -// When direct URL routing is false, update baseUrls based custom urls -// passed to the config -return b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a)}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c=Constants.CNAMEUrlPaths,d={};// newBaseUrls are default if the customer is not using a CNAME -// If a customer passes either config.domain or config.v3SecureServiceUrl, -// config.identityUrl, etc, the customer is using a CNAME. -// config.domain will take priority if a customer passes both. -// If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain. -// This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty -// if a customer is using a snippet prior to 2.6. -if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);return d}for(var f in b)d[f]=a[f]||b[f];return d}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that -// include the silo in the urls. mParticle API keys are prefixed with the -// silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo, -// and before other silos existed, there were no prefixes and all apiKeys -// were us1. As such, if we split on a '-' and the resulting array length -// is 1, then it is an older APIkey that should route to us1. -// When splitKey.length is greater than 1, then splitKey[0] will be -// us1, us2, eu1, au1, or st1, etc as new silos are added -for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct -// mapping to the silo. The most common use case is a customer provided CNAME. -if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} - -var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); - -var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 -// https://go.mparticle.com/work/SQDSDKS-6045 -// https://go.mparticle.com/work/SQDSDKS-5022 -// https://go.mparticle.com/work/SQDSDKS-6021 -// https://go.mparticle.com/work/SQDSDKS-5022 -// https://go.mparticle.com/work/SQDSDKS-6021 -/* This function determines if a cookie is greater than the configured maxCookieSize. - - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie. - - Once removed, check size, and repeat. - - Never remove the currentUser's MPID from the cookie. - - MPID removal priority: - 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie. - 2. If there are currentSessionMPIDs: - a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs - b. Then remove MPIDs based on order in currentSessionMPIDs array, which - stores MPIDs based on earliest login. -*/ // TODO: This should actually be decodePersistenceString or -// we should refactor this to take a string and return an object -// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible. -// For example subdomain.domain.co.uk would try the following combinations: -// "co.uk" -> fail -// "domain.co.uk" -> success, return -// "subdomain.domain.co.uk" -> skipped, because already found -// https://go.mparticle.com/work/SQDSDKS-6021 -/** - * set the "first seen" time for a user. the time will only be set once for a given - * mpid after which subsequent calls will be ignored - */ /** - * returns the "last seen" time for a user. If the mpid represents the current user, the - * return value will always be the current time, otherwise it will be to stored "last seen" - * time - */ // https://go.mparticle.com/work/SQDSDKS-6045 -// Forwarder Batching Code -this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var b,c,d=f.getLocalStorage(),e=f.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045 -// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle -// https://go.mparticle.com/work/SQDSDKS-6046 -// Stores all non-current user MPID information into the store -for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?a._Helpers.extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?a._Helpers.extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){var c;if(a._Store.isLocalStorageAvailable&&!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true -{var d=a._Store.storageName,e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(d),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;cf&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie -var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above -if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above -for(var n,o=0;of);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through -// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched -if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1= 0; --o) { - var i = this.tryEntries[o], - a = i.completion; - if ("root" === i.tryLoc) return handle("end"); - if (i.tryLoc <= this.prev) { - var c = n.call(i, "catchLoc"), - u = n.call(i, "finallyLoc"); - if (c && u) { - if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); - if (this.prev < i.finallyLoc) return handle(i.finallyLoc); - } else if (c) { - if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); - } else { - if (!u) throw new Error("try statement without catch or finally"); - if (this.prev < i.finallyLoc) return handle(i.finallyLoc); - } - } - } - }, - abrupt: function abrupt(t, e) { - for (var r = this.tryEntries.length - 1; r >= 0; --r) { - var o = this.tryEntries[r]; - if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { - var i = o; - break; - } - } - i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); - var a = i ? i.completion : {}; - return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); - }, - complete: function complete(t, e) { - if ("throw" === t.type) throw t.arg; - return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; - }, - finish: function finish(t) { - for (var e = this.tryEntries.length - 1; e >= 0; --e) { - var r = this.tryEntries[e]; - if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; - } - }, - "catch": function _catch(t) { - for (var e = this.tryEntries.length - 1; e >= 0; --e) { - var r = this.tryEntries[e]; - if (r.tryLoc === t) { - var n = r.completion; - if ("throw" === n.type) { - var o = n.arg; - resetTryEntry(r); - } - return o; - } - } - throw new Error("illegal catch attempt"); - }, - delegateYield: function delegateYield(e, r, n) { - return this.delegate = { - iterator: values(e), - resultName: r, - nextLoc: n - }, "next" === this.method && (this.arg = t), y; - } - }, e; - } - module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; -} (regeneratorRuntime$1)); - -var regeneratorRuntimeExports = regeneratorRuntime$1.exports; - -// TODO(Babel 8): Remove this file. - -var runtime = regeneratorRuntimeExports(); -var regenerator = runtime; - -// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= -try { - regeneratorRuntime = runtime; -} catch (accidentalStrictMode) { - if (typeof globalThis === "object") { - globalThis.regeneratorRuntime = runtime; - } else { - Function("r", "regeneratorRuntime = r")(runtime); - } -} - -var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator); - -function filteredMparticleUser(a,b,c,d){var e=this;return {getUserIdentities:function getUserIdentities(){var e={},f=c._Store.getUserIdentities(a);for(var g in f)if(f.hasOwnProperty(g)){var h=Types.IdentityType.getIdentityName(c._Helpers.parseNumber(g));d&&(!d||d.isIdentityBlocked(h))||(//if identity type is not blocked -e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Store.getUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}} - -var _Constants$IdentityMe=Constants.IdentityMethods,Modify$2=_Constants$IdentityMe.Modify,Identify$1=_Constants$IdentityMe.Identify,Login$1=_Constants$IdentityMe.Login,Logout$1=_Constants$IdentityMe.Logout;function Forwarders(a,b){var c=this,d=this;this.forwarderStatsUploader=new APIClient(a,b).initializeForwarderStatsUploader();var e={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// TODO: https://go.mparticle.com/work/SQDSDKS-6036 -// Processing forwarders is a 2 step process: -// 1. Configure the kit -// 2. Initialize the kit -// There are 2 types of kits: -// 1. UI-enabled kits -// 2. Sideloaded kits. -// These are kits that are enabled via the mParticle UI. -// A kit that is UI-enabled will have a kit configuration that returns from -// the server, or in rare cases, is passed in by the developer. -// The kit configuration will be compared with the kit constructors to determine -// if there is a match before being initialized. -// Only kits that are configured properly can be active and used for kit forwarding. -// Unlike UI enabled kits, sideloaded kits are always added to active forwarders. -// TODO: Sideloading kits currently require the use of a register method -// which requires an object on which to be registered. -// In the future, when all kits are moved to the mpConfig rather than -// there being a separate process for MP configured kits and -// sideloaded kits, this will need to be refactored. -// kits can be included via mParticle UI, or via sideloaded kit config API -this.initForwarders=function(b,c){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!d.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!d.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=a._Helpers.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,c,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;var d,e,f;if(!c)return !1;f=c.getAllUserAttributes();var g=!1;try{if(f&&a._Helpers.isObject(f)&&Object.keys(f).length)for(var h in f)if(f.hasOwnProperty(h)&&(d=KitFilterHelper.hashAttributeConditionalForwarding(h),e=KitFilterHelper.hashAttributeConditionalForwarding(f[h]),d===b.userAttributeName&&e===b.userAttributeValue)){g=!0;break}return !b||b.includeOnMatch===g}catch(a){// in any error scenario, err on side of returning true and forwarding event -return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){var c,d,e,f=function(b,c){b.UserIdentities&&b.UserIdentities.length&&b.UserIdentities.forEach(function(d,e){a._Helpers.inArray(c,KitFilterHelper.hashUserIdentity(d.Type))&&(b.UserIdentities.splice(e,1),0e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate. -throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}(); - -var processReadyQueue=function(a){return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]};var processPreloadedItem=function(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it -if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(window.mParticle,b);else {var d=c.split(".");try{// Track both the function and its context -for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;hd?-1:1}),c},/** - * Initiate an alias request to the mParticle server - * @method aliasUsers - * @param {Object} aliasRequest object representing an AliasRequest - * @param {Function} [callback] A callback function that is called when the aliasUsers request completes - */aliasUsers:function aliasUsers(b,c){var d;if(b.destinationMpid&&b.sourceMpid||(d=Messages$2.ValidationMessages.AliasMissingMpid),b.destinationMpid===b.sourceMpid&&(d=Messages$2.ValidationMessages.AliasNonUniqueMpid),b.startTime&&b.endTime||(d=Messages$2.ValidationMessages.AliasMissingTime),b.startTime>b.endTime&&(d=Messages$2.ValidationMessages.AliasStartBeforeEndTime),d)return a.Logger.warning(d),void a._Helpers.invokeAliasCallback(c,HTTPCodes$2.validationIssue,d);if(!a._Helpers.canLog())a._Helpers.invokeAliasCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),a.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(a._Identity.IdentityRequest.convertAliasToNative(b))),a._Helpers.invokeAliasCallback(c,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {a.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+b.sourceMpid+" -> "+b.destinationMpid);var e=a._Identity.IdentityRequest.createAliasNetworkRequest(b);a._IdentityAPIClient.sendAliasRequest(e,c);}},/** - Create a default AliasRequest for 2 MParticleUsers. This will construct the request - using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime. - - In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only - be the case if they have not been the current user since this functionality was added, the - startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly, - if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time - - There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days. - If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime. - In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit, - after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() - validation that the startTime must be less than the endTime - */createAliasRequest:function createAliasRequest(b,c,d){try{if(!c||!b)return a.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var e=b.getFirstSeenTime();e||a.Identity.getUsers().forEach(function(a){a.getFirstSeenTime()&&(!e||a.getFirstSeenTime() - * Usage: const consent = mParticle.Consent.createConsentState() - *
- * consent.setGDPRCoonsentState() - * - * @class Consent - */ /** - * Add a GDPR Consent State to the consent state object - * - * @method addGDPRConsentState - * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data - * @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...) - */function e(c,e){var f=d(c);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=b.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/** - * Remove a GDPR Consent State to the consent state object - * - * @method removeGDPRConsentState - * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data - */function g(a){var b=d(a);return b?(delete k[b],this):this}/** - * Gets the GDPR Consent State - * - * @method getGDPRConsentState - * @return {Object} A GDPR Consent State - */function h(){return Object.assign({},k)}/** - * Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out') - * - * @method setCCPAConsentState - * @param {Object} ccpaConsent CCPA Consent State - */function i(c){if(!isObject(c))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=b.createPrivacyConsent(c.Consented,c.Timestamp,c.ConsentDocument,c.Location,c.HardwareId);return d&&(l[CCPAPurpose]=d),this}/** - * Gets the CCPA Consent State - * - * @method getCCPAConsentStatensent - * @return {Object} A CCPA Consent State - */ /** - * Removes CCPA from the consent state object - * - * @method removeCCPAConsentState - */function j(){return delete l[CCPAPurpose],this}// TODO: Can we remove this? It is deprecated. -var k={},l={};if(c){var m=b.createConsentState();// TODO: Remove casting once `removeCCPAState` is removed; -return m.setGDPRConsentState(c.getGDPRConsentState()),m.setCCPAConsentState(c.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAState:function b(){// @ts-ignore -return a.Logger.warning("removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"),j()},removeCCPAConsentState:j}};} - -/* - TODO: Including this as a workaround because attempting to import it from - @mparticle/data-planning-models directly creates a build error. - */var DataPlanMatchType={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},KitBlocker=/** @class */function(){function a(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r=this;// if data plan is not requested, the data plan is {document: null} -if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,a&&!a.document)return void(this.kitBlockingEnabled=!1);this.kitBlockingEnabled=!0,this.mpInstance=b,this.blockEvents=null===(e=null===(d=null===(c=null===a||void 0===a?void 0:a.document)||void 0===c?void 0:c.dtpn)||void 0===d?void 0:d.blok)||void 0===e?void 0:e.ev,this.blockEventAttributes=null===(h=null===(g=null===(f=null===a||void 0===a?void 0:a.document)||void 0===f?void 0:f.dtpn)||void 0===g?void 0:g.blok)||void 0===h?void 0:h.ea,this.blockUserAttributes=null===(k=null===(j=null===(i=null===a||void 0===a?void 0:a.document)||void 0===i?void 0:i.dtpn)||void 0===j?void 0:j.blok)||void 0===k?void 0:k.ua,this.blockUserIdentities=null===(n=null===(m=null===(l=null===a||void 0===a?void 0:a.document)||void 0===l?void 0:l.dtpn)||void 0===m?void 0:m.blok)||void 0===n?void 0:n.id;var s=null===(q=null===(p=null===(o=null===a||void 0===a?void 0:a.document)||void 0===o?void 0:o.dtpn)||void 0===p?void 0:p.vers)||void 0===q?void 0:q.version_document,t=null===s||void 0===s?void 0:s.data_points;if(s)try{0<(null===t||void 0===t?void 0:t.length)&&t.forEach(function(a){return r.addToMatchLookups(a)});}catch(a){this.mpInstance.Logger.error("There was an issue with the data plan: "+a);}}return a.prototype.addToMatchLookups=function(a){var b,c,d;if(!a.match||!a.validator)return void this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(a));// match keys for non product custom attribute related data points -var e=this.generateMatchKey(a.match),f=this.getPlannedProperties(a.match.type,a.validator);this.dataPlanMatchLookups[e]=f,((null===(b=null===a||void 0===a?void 0:a.match)||void 0===b?void 0:b.type)===DataPlanMatchType.ProductImpression||(null===(c=null===a||void 0===a?void 0:a.match)||void 0===c?void 0:c.type)===DataPlanMatchType.ProductAction||(null===(d=null===a||void 0===a?void 0:a.match)||void 0===d?void 0:d.type)===DataPlanMatchType.PromotionAction)&&(e=this.generateProductAttributeMatchKey(a.match),f=this.getProductProperties(a.match.type,a.validator),this.dataPlanMatchLookups[e]=f);},a.prototype.generateMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.CustomEvent:var c=b;return [DataPlanMatchType.CustomEvent,c.custom_event_type,c.event_name].join(":");case DataPlanMatchType.ScreenView:return [DataPlanMatchType.ScreenView,"",b.screen_name].join(":");case DataPlanMatchType.ProductAction:return [a.type,b.action].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action].join(":");case DataPlanMatchType.ProductImpression:return [a.type,b.action].join(":");case DataPlanMatchType.UserIdentities:case DataPlanMatchType.UserAttributes:return [a.type].join(":");default:return null}},a.prototype.generateProductAttributeMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.ProductAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.ProductImpression:return [a.type,"ProductAttributes"].join(":");default:return null}},a.prototype.getPlannedProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l;switch(a){case DataPlanMatchType.CustomEvent:case DataPlanMatchType.ScreenView:case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction:case DataPlanMatchType.ProductImpression:if(k=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.custom_attributes,k){if(!0===k.additionalProperties||void 0===k.additionalProperties)return !0;for(var m,n={},o=0,p=Object.keys(k.properties);o=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} - -// The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: -// - version is always this prefix: fb -// - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2) -// - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value -// - is the value for the fbclid query parameter in the page URL. -// https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc -var facebookClickIdProcessor=function(a,b,c){if(!a||!b)return "";var d=null===b||void 0===b?void 0:b.split("//");if(!d)return "";var e=d[1].split("/"),f=e[0].split("."),g=1;// The rules for subdomainIndex are for parsing the domain portion -// of the URL for cookies, but in this case we are parsing the URL -// itself, so we can ignore the use of 0 for 'com' -3<=f.length&&(g=2);// If timestamp is not provided, use the current time -var h=c||Date.now();return "fb.".concat(g,".").concat(h,".").concat(a)};// Integration outputs are used to determine how click ids are used within the SDK -// CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject -// PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch -// INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created -var IntegrationOutputs={CUSTOM_FLAGS:"custom_flags",PARTNER_IDENTITIES:"partner_identities",INTEGRATION_ATTRIBUTES:"integration_attributes"},integrationMappingExternal={// Facebook / Meta -fbclid:{mappedKey:"Facebook.ClickId",processor:facebookClickIdProcessor,output:IntegrationOutputs.CUSTOM_FLAGS},_fbp:{mappedKey:"Facebook.BrowserId",output:IntegrationOutputs.CUSTOM_FLAGS},_fbc:{mappedKey:"Facebook.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Google -gclid:{mappedKey:"GoogleEnhancedConversions.Gclid",output:IntegrationOutputs.CUSTOM_FLAGS},gbraid:{mappedKey:"GoogleEnhancedConversions.Gbraid",output:IntegrationOutputs.CUSTOM_FLAGS},wbraid:{mappedKey:"GoogleEnhancedConversions.Wbraid",output:IntegrationOutputs.CUSTOM_FLAGS},// TIKTOK -ttclid:{mappedKey:"TikTok.Callback",output:IntegrationOutputs.CUSTOM_FLAGS},_ttp:{mappedKey:"tiktok_cookie_id",output:IntegrationOutputs.PARTNER_IDENTITIES},// Snapchat -// https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US -ScCid:{mappedKey:"SnapchatConversions.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Snapchat -// https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id -_scid:{mappedKey:"SnapchatConversions.Cookie1",output:IntegrationOutputs.CUSTOM_FLAGS}},integrationMappingRokt={// Rokt -// https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/ -// https://go.mparticle.com/work/SQDSDKS-7167 -rtid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},rclid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},RoktTransactionId:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277}},IntegrationCapture=/** @class */function(){function a(a){this.initialTimestamp=Date.now(),this.captureMode=a,this.filteredPartnerIdentityMappings=this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES),this.filteredCustomFlagMappings=this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS),this.filteredIntegrationAttributeMappings=this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);}/** - * Captures Integration Ids from cookies and query params and stores them in clickIds object - */return a.prototype.capture=function(){var a=this.captureQueryParams()||{},b=this.captureCookies()||{},c=this.captureLocalStorage()||{};a.fbclid&&b._fbc&&delete b._fbc;// ROKT Rules -// If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid -// If RoktTransactionId is present in both cookies and localStorage, -// prioritize localStorage -var d=a.rtid||a.rclid,e=c.RoktTransactionId,f=b.RoktTransactionId;d?(e&&delete c.RoktTransactionId,f&&delete b.RoktTransactionId):e&&f&&delete b.RoktTransactionId,this.clickIds=__assign(__assign(__assign(__assign({},this.clickIds),a),c),b);},a.prototype.captureCookies=function(){var a=this.getAllowedKeysForMode(),b=getCookies(a);return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.captureQueryParams=function(){var a=this.getQueryParams();return this.applyProcessors(a,getHref(),this.initialTimestamp)},a.prototype.captureLocalStorage=function(){for(var a=this.getAllowedKeysForMode(),b={},c=0,d=a;c": { -// "mappedKey": "clickIdValue" -// } -// } -// } -for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}(); - -// Rokt Web SDK via a Web Kit. -// The Rokt Manager should load before the Web Kit and stubs out many of the -// Rokt Web SDK functions with an internal message queue in case a Rokt function -// is requested before the Rokt Web Kit or SDK is finished loaded. -// Once the Rokt Kit is attached to the Rokt Manager, we can consider the -// Rokt Manager in a "ready" state and it can begin sending data to the kit. -// -// https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt -var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1;}/** - * Sets a callback to be invoked when RoktManager becomes ready - */return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g){var h,i,j=a||{},k=j.userAttributeFilters,l=j.settings,m=l||{},n=m.placementAttributesMapping,o=m.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(h=null===o||void 0===o?void 0:o.toLowerCase())&&void 0!==h?h:null,this.identityService=c,this.store=d,this.logger=e,this.captureTiming=g,null===(i=this.captureTiming)||void 0===i?void 0:i.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:k,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(n);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode -// It is set here and passed in to the createLauncher method in the Rokt Kit -// This is not to be confused for the `sandbox` flag in the selectPlacements attributes -// as that is independent of this setting, though they share the same name. -var p=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through -// to the Rokt Launcher. -this.launcherOptions=__assign({sandbox:p},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h;return __awaiter(this,void 0,void 0,function(){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A=this;return __generator(this,function(B){switch(B.label){case 0:// Queue if kit isn't ready OR if identity is in flight -if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];B.label=1;case 1:if(B.trys.push([1,6,,7]),i=a.attributes,j=(null===i||void 0===i?void 0:i.sandbox)||null,k=this.mapPlacementAttributes(i,this.placementAttributesMapping),null===(d=this.logger)||void 0===d?void 0:d.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(i,null,2))),this.currentUser=this.identityService.getCurrentUser(),l=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},m=l.email,n=k.email,o=void 0,p=void 0,q=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),q&&(o=l[this.mappedEmailShaIdentityType],p=k.emailsha256||k[this.mappedEmailShaIdentityType]||void 0),r=this.hasIdentityChanged(m,n),s=this.hasIdentityChanged(o,p),t={},r&&(t.email=n,n&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),s&&(t[this.mappedEmailShaIdentityType]=p,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(t))return [3/*break*/,5];B.label=2;case 2:return B.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){A.identityService.identify({userIdentities:__assign(__assign({},l),t)},function(){a();});})];case 3:return B.sent(),[3/*break*/,5];case 4:return u=B.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(u)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),v=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},this.setUserAttributes(k),w=__assign(__assign({},k),null===j?{}:{sandbox:j}),v.email&&!w.email&&(w.email=v.email),q&&(x=v[this.mappedEmailShaIdentityType],x&&!w.emailsha256&&!w[this.mappedEmailShaIdentityType]&&(w.emailsha256=x)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,y=__assign(__assign({},a),{attributes:w}),[2/*return*/,this.kit.selectPlacements(y)];case 6:return z=B.sent(),[2/*return*/,Promise.reject(z instanceof Error?z:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);fAll of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

- *

In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.

- *

This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().

- *

If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:

- * - * mParticle.init('apiKey', config, 'another_instance'); - * mParticle.getInstance('another_instance').logPageView(); - * - * - * @class mParticle & mParticleInstance - */function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption -this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization -// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization -// to it for it to be run after fetched -if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval -b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** - * Creates a CCPA Opt Out Consent State. - * - * @method createCCPAConsent - * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" - * @param {Number} timestamp Unix time (likely to be Date.now()) - * @param {String} consentDocument document version or experience that the user may have consented to - * @param {String} location location where the user gave consent - * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users - * @return {Object} CCPA Consent State - */createCCPAConsent:b._Consent.createPrivacyConsent,/** - * Creates a GDPR Consent State. - * - * @method createGDPRConsent - * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" - * @param {Number} timestamp Unix time (likely to be Date.now()) - * @param {String} consentDocument document version or experience that the user may have consented to - * @param {String} location location where the user gave consent - * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users - * @return {Object} GDPR Consent State - */createGDPRConsent:b._Consent.createPrivacyConsent,/** - * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states. - * - * @method createConsentState - * @return {Object} ConsentState object - */createConsentState:b._Consent.createConsentState},this.eCommerce={/** - * Invoke these methods on the mParticle.eCommerce.Cart object. - * Example: mParticle.eCommerce.Cart.add(...) - * @class mParticle.eCommerce.Cart - * @deprecated - */Cart:{/** - * Adds a product to the cart - * @method add - * @param {Object} product The product you want to add to the cart - * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. - * @deprecated - */add:function add(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** - * Removes a product from the cart - * @method remove - * @param {Object} product The product you want to add to the cart - * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. - * @deprecated - */remove:function remove(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** - * Clears the cart - * @method clear - * @deprecated - */clear:function clear(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));}},/** - * Sets the currency code - * @for mParticle.eCommerce - * @method setCurrencyCode - * @param {String} code The currency code - */setCurrencyCode:function setCurrencyCode(a){var c=queueIfNotInitialized(function(){b.eCommerce.setCurrencyCode(a);},b);return c?void 0:"string"==typeof a?void(b._SessionManager.resetSessionTimer(),b._Store.currencyCode=a):void b.Logger.error("Code must be a string")},/** - * Creates a product - * @for mParticle.eCommerce - * @method createProduct - * @param {String} name product name - * @param {String} sku product sku - * @param {Number} price product price - * @param {Number} [quantity] product quantity. If blank, defaults to 1. - * @param {String} [variant] product variant - * @param {String} [category] product category - * @param {String} [brand] product brand - * @param {Number} [position] product position - * @param {String} [coupon] product coupon - * @param {Object} [attributes] product attributes - */createProduct:function createProduct(a,c,d,e,f,g,h,i,j,k){return b._Ecommerce.createProduct(a,c,d,e,f,g,h,i,j,k)},/** - * Creates a promotion - * @for mParticle.eCommerce - * @method createPromotion - * @param {String} id a unique promotion id - * @param {String} [creative] promotion creative - * @param {String} [name] promotion name - * @param {Number} [position] promotion position - */createPromotion:function createPromotion(a,c,d,e){return b._Ecommerce.createPromotion(a,c,d,e)},/** - * Creates a product impression - * @for mParticle.eCommerce - * @method createImpression - * @param {String} name impression name - * @param {Object} product the product for which an impression is being created - */createImpression:function createImpression(a,c){return b._Ecommerce.createImpression(a,c)},/** - * Creates a transaction attributes object to be used with a checkout - * @for mParticle.eCommerce - * @method createTransactionAttributes - * @param {String or Number} id a unique transaction id - * @param {String} [affiliation] affilliation - * @param {String} [couponCode] the coupon code for which you are creating transaction attributes - * @param {Number} [revenue] total revenue for the product being purchased - * @param {String} [shipping] the shipping method - * @param {Number} [tax] the tax amount - */createTransactionAttributes:function createTransactionAttributes(a,c,d,e,f,g){return b._Ecommerce.createTransactionAttributes(a,c,d,e,f,g)},/** - * Logs a checkout action - * @for mParticle.eCommerce - * @method logCheckout - * @param {Number} step checkout step number - * @param {String} checkout option string - * @param {Object} attrs - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */logCheckout:function logCheckout(a,c,d,e){return b.Logger.warning("mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logCheckoutEvent(a,c,d,e)):void b.ready(function(){b.eCommerce.logCheckout(a,c,d,e);})},/** - * Logs a product action - * @for mParticle.eCommerce - * @method logProductAction - * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218) - * @param {Object} product the product for which you are creating the product action - * @param {Object} [attrs] attributes related to the product action - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [transactionAttributes] Transaction Attributes for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */logProductAction:function logProductAction(a,c,d,e,f,g){var h=queueIfNotInitialized(function(){b.eCommerce.logProductAction(a,c,d,e,f,g);},b);h||(b._SessionManager.resetSessionTimer(),b._Events.logProductActionEvent(a,c,d,e,f,g));},/** - * Logs a product purchase - * @for mParticle.eCommerce - * @method logPurchase - * @param {Object} transactionAttributes transactionAttributes object - * @param {Object} product the product being purchased - * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false - * @param {Object} [attrs] other attributes related to the product purchase - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */logPurchase:function logPurchase(a,c,d,e,f){return b.Logger.warning("mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?a&&c?void(b._SessionManager.resetSessionTimer(),b._Events.logPurchaseEvent(a,c,e,f)):void b.Logger.error(Messages.ErrorMessages.BadLogPurchase):void b.ready(function(){b.eCommerce.logPurchase(a,c,d,e,f);})},/** - * Logs a product promotion - * @for mParticle.eCommerce - * @method logPromotion - * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279) - * @param {Object} promotion promotion object - * @param {Object} [attrs] boolean to clear the cart after logging or not - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */logPromotion:function logPromotion(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.eCommerce.logPromotion(a,c,d,e,f);},b);g||(b._SessionManager.resetSessionTimer(),b._Events.logPromotionEvent(a,c,d,e,f));},/** - * Logs a product impression - * @for mParticle.eCommerce - * @method logImpression - * @param {Object} impression product impression object - * @param {Object} attrs attributes related to the impression log - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */logImpression:function logImpression(a,c,d,e){var f=queueIfNotInitialized(function(){b.eCommerce.logImpression(a,c,d,e);},b);f||(b._SessionManager.resetSessionTimer(),b._Events.logImpressionEvent(a,c,d,e));},/** - * Logs a refund - * @for mParticle.eCommerce - * @method logRefund - * @param {Object} transactionAttributes transaction attributes related to the refund - * @param {Object} product product being refunded - * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false. - * @param {Object} [attrs] attributes related to the refund - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie -// And logs to in-memory object -// Example: mParticle.setSessionAttribute('location', '33431'); -if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed -if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any -// other integration delays set to true. It not, process the queued events/. -var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment -function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's -// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not -// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize -// persistence or Identity directly. -if(c._APIClient=new APIClient(c,f),c._Forwarders=new Forwarders(c,f),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use -var h=c.Identity.getCurrentUser(),i=h?h.getMPID():null,j=h?h.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:j}:c._Store.SDKConfig.identifyRequest,g(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639 -var k=g(CaptureIntegrationSpecificIds),l=g(CaptureIntegrationSpecificIdsV2),m=l&&l!==CaptureIntegrationSpecificIdsV2Modes.None||!0===k;if(m){var n;k||l===CaptureIntegrationSpecificIdsV2Modes.All?n="all":l===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(n="roktonly"),c._IntegrationCapture=new IntegrationCapture(n),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user -var o=parseConfig(b,"Rokt",181);if(o){var p=null===(d=o.settings)||void 0===d?void 0:d.accountId;c._Store.setRoktAccountId(p);var q=o.userAttributeFilters,r=filteredMparticleUser(i,{userAttributeFilters:q},c),s={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339 -c._RoktManager.init(o,r,c.Identity,c._Store,c.Logger,s,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,h,i,j);}// We will continue to clear out the ready queue as part of the initial init flow -// if an identify request is unnecessary, such as if there is an existing session -(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),null===(e=c.processQueueOnNoFunctional)||void 0===e?void 0:e.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061 -function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK: - 1. Manually via config.dataPlanOptions (this takes priority) - If not passed in manually, we user the server provided via either - 2. Snippet via /mparticle.js endpoint (config.dataPlan.document) - 3. Self hosting via /config endpoint (config.dataPlanResult) - */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault -// ensures no identity response data is written to localStorage when noFunctional is true -return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions -var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs -// since we will need this for the current implementation of user persistence -// TODO: Refactor this when we refactor User Identity Persistence -try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never -// receive an MPID. Let these calls through so events can still reach forwarders immediately. -// sendEventToServer handles queuing for the MP server upload path separately. -return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)} - -// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise! -var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method -_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:mockFunction},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}(); - -var MPSideloadedKit=/** @class */function(){function a(a){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],// The below filtering members are optional, but we instantiate them -// to simplify public method assignment -filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=a;}return a.prototype.addEventTypeFilter=function(a){var b=KitFilterHelper.hashEventType(a);this.filterDictionary.eventTypeFilters.push(b);},a.prototype.addEventNameFilter=function(a,b){var c=KitFilterHelper.hashEventName(b,a);this.filterDictionary.eventNameFilters.push(c);},a.prototype.addEventAttributeFilter=function(a,b,c){var d=KitFilterHelper.hashEventAttributeKey(a,b,c);this.filterDictionary.attributeFilters.push(d);},a.prototype.addScreenNameFilter=function(a){var b=KitFilterHelper.hashEventName(a,EventType.Unknown);this.filterDictionary.screenNameFilters.push(b);},a.prototype.addScreenAttributeFilter=function(a,b){var c=KitFilterHelper.hashEventAttributeKey(EventType.Unknown,a,b);this.filterDictionary.screenAttributeFilters.push(c);},a.prototype.addUserIdentityFilter=function(a){var b=KitFilterHelper.hashUserIdentity(a);this.filterDictionary.userIdentityFilters.push(b);},a.prototype.addUserAttributeFilter=function(a){var b=KitFilterHelper.hashUserAttribute(a);this.filterDictionary.userAttributeFilters.push(b);},a}(); - -Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticleInstanceManager(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing -/** - * Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used. - *

- * If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below. - * @method init - * @param {String} apiKey your mParticle assigned API key - * @param {Object} [config] an options object for additional configuration - * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); - -export { mParticleManager as default }; diff --git a/dist/mparticle.js b/dist/mparticle.js deleted file mode 100644 index ff767ca7f..000000000 --- a/dist/mparticle.js +++ /dev/null @@ -1,12110 +0,0 @@ -var mParticle = (function () { - - // Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html - var Base64$1 = { - _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', - // Input must be a string - encode: function encode(input) { - try { - if (window.btoa && window.atob) { - return window.btoa(unescape(encodeURIComponent(input))); - } - } catch (e) { - console.error('Error encoding cookie values into Base64:' + e); - } - return this._encode(input); - }, - _encode: function _encode(input) { - var output = ''; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; - input = UTF8.encode(input); - while (i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - enc1 = chr1 >> 2; - enc2 = (chr1 & 3) << 4 | chr2 >> 4; - enc3 = (chr2 & 15) << 2 | chr3 >> 6; - enc4 = chr3 & 63; - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; - } - output = output + Base64$1._keyStr.charAt(enc1) + Base64$1._keyStr.charAt(enc2) + Base64$1._keyStr.charAt(enc3) + Base64$1._keyStr.charAt(enc4); - } - return output; - }, - decode: function decode(input) { - try { - if (window.btoa && window.atob) { - return decodeURIComponent(escape(window.atob(input))); - } - } catch (e) { - //log(e); - } - return Base64$1._decode(input); - }, - _decode: function _decode(input) { - var output = ''; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); - while (i < input.length) { - enc1 = Base64$1._keyStr.indexOf(input.charAt(i++)); - enc2 = Base64$1._keyStr.indexOf(input.charAt(i++)); - enc3 = Base64$1._keyStr.indexOf(input.charAt(i++)); - enc4 = Base64$1._keyStr.indexOf(input.charAt(i++)); - chr1 = enc1 << 2 | enc2 >> 4; - chr2 = (enc2 & 15) << 4 | enc3 >> 2; - chr3 = (enc3 & 3) << 6 | enc4; - output = output + String.fromCharCode(chr1); - if (enc3 !== 64) { - output = output + String.fromCharCode(chr2); - } - if (enc4 !== 64) { - output = output + String.fromCharCode(chr3); - } - } - output = UTF8.decode(output); - return output; - } - }; - var UTF8 = { - encode: function encode(s) { - var utftext = ''; - for (var n = 0; n < s.length; n++) { - var c = s.charCodeAt(n); - if (c < 128) { - utftext += String.fromCharCode(c); - } else if (c > 127 && c < 2048) { - utftext += String.fromCharCode(c >> 6 | 192); - utftext += String.fromCharCode(c & 63 | 128); - } else { - utftext += String.fromCharCode(c >> 12 | 224); - utftext += String.fromCharCode(c >> 6 & 63 | 128); - utftext += String.fromCharCode(c & 63 | 128); - } - } - return utftext; - }, - decode: function decode(utftext) { - var s = ''; - var i = 0; - var c = 0, - c1 = 0, - c2 = 0; - while (i < utftext.length) { - c = utftext.charCodeAt(i); - if (c < 128) { - s += String.fromCharCode(c); - i++; - } else if (c > 191 && c < 224) { - c1 = utftext.charCodeAt(i + 1); - s += String.fromCharCode((c & 31) << 6 | c1 & 63); - i += 2; - } else { - c1 = utftext.charCodeAt(i + 1); - c2 = utftext.charCodeAt(i + 2); - s += String.fromCharCode((c & 15) << 12 | (c1 & 63) << 6 | c2 & 63); - i += 3; - } - } - return s; - } - }; - var Polyfill = { - // forEach polyfill - // Production steps of ECMA-262, Edition 5, 15.4.4.18 - // Reference: http://es5.github.io/#x15.4.4.18 - forEach: function forEach(callback, thisArg) { - var T, k; - if (this == null) { - throw new TypeError(' this is null or not defined'); - } - var O = Object(this); - var len = O.length >>> 0; - if (typeof callback !== 'function') { - throw new TypeError(callback + ' is not a function'); - } - if (arguments.length > 1) { - T = thisArg; - } - k = 0; - while (k < len) { - var kValue; - if (k in O) { - kValue = O[k]; - callback.call(T, kValue, k, O); - } - k++; - } - }, - // map polyfill - // Production steps of ECMA-262, Edition 5, 15.4.4.19 - // Reference: http://es5.github.io/#x15.4.4.19 - map: function map(callback, thisArg) { - var T, A, k; - if (this === null) { - throw new TypeError(' this is null or not defined'); - } - var O = Object(this); - var len = O.length >>> 0; - if (typeof callback !== 'function') { - throw new TypeError(callback + ' is not a function'); - } - if (arguments.length > 1) { - T = thisArg; - } - A = new Array(len); - k = 0; - while (k < len) { - var kValue, mappedValue; - if (k in O) { - kValue = O[k]; - mappedValue = callback.call(T, kValue, k, O); - A[k] = mappedValue; - } - k++; - } - return A; - }, - // filter polyfill - // Prodcution steps of ECMA-262, Edition 5 - // Reference: http://es5.github.io/#x15.4.4.20 - filter: function filter(fun /*, thisArg*/) { - - if (this === void 0 || this === null) { - throw new TypeError(); - } - var t = Object(this); - var len = t.length >>> 0; - if (typeof fun !== 'function') { - throw new TypeError(); - } - var res = []; - var thisArg = arguments.length >= 2 ? arguments[1] : void 0; - for (var i = 0; i < len; i++) { - if (i in t) { - var val = t[i]; - if (fun.call(thisArg, val, i, t)) { - res.push(val); - } - } - } - return res; - }, - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray - isArray: function isArray(arg) { - return Object.prototype.toString.call(arg) === '[object Array]'; - }, - Base64: Base64$1 - }; - - var version = "2.59.0"; - - var Constants = { - sdkVersion: version, - sdkVendor: 'mparticle', - platform: 'web', - Messages: { - DeprecationMessages: { - MethodHasBeenDeprecated: 'has been deprecated.', - MethodMarkedForDeprecationPostfix: 'is a deprecated method and will be removed in future releases.', - AlternativeMethodPrefix: 'Please use the alternate method:' - }, - ErrorMessages: { - NoToken: 'A token must be specified.', - EventNameInvalidType: 'Event name must be a valid string value.', - EventDataInvalidType: 'Event data must be a valid object hash.', - LoggingDisabled: 'Event logging is currently disabled.', - CookieParseError: 'Could not parse cookie', - EventEmpty: 'Event object is null or undefined, cancelling send', - APIRequestEmpty: 'APIRequest is null or undefined, cancelling send', - NoEventType: 'Event type must be specified.', - TransactionIdRequired: 'Transaction ID is required', - TransactionRequired: 'A transaction attributes object is required', - PromotionIdRequired: 'Promotion ID is required', - BadAttribute: 'Attribute value cannot be object or array', - BadKey: 'Key value cannot be object or array', - BadLogPurchase: 'Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions', - AudienceAPINotEnabled: 'Your workspace is not enabled to retrieve user audiences.' - }, - InformationMessages: { - CookieSearch: 'Searching for cookie', - CookieFound: 'Cookie found, parsing values', - CookieNotFound: 'Cookies not found', - CookieSet: 'Setting cookie', - CookieSync: 'Performing cookie sync', - SendBegin: 'Starting to send event', - SendIdentityBegin: 'Starting to send event to identity server', - SendWindowsPhone: 'Sending event to Windows Phone container', - SendIOS: 'Calling iOS path: ', - SendAndroid: 'Calling Android JS interface method: ', - SendHttp: 'Sending event to mParticle HTTP service', - SendAliasHttp: 'Sending alias request to mParticle HTTP service', - SendIdentityHttp: 'Sending event to mParticle HTTP service', - StartingNewSession: 'Starting new Session', - StartingLogEvent: 'Starting to log event', - StartingLogOptOut: 'Starting to log user opt in/out', - StartingEndSession: 'Starting to end session', - StartingInitialization: 'Starting to initialize', - StartingLogCommerceEvent: 'Starting to log commerce event', - StartingAliasRequest: 'Starting to Alias MPIDs', - LoadingConfig: 'Loading configuration options', - AbandonLogEvent: 'Cannot log event, logging disabled or developer token not set', - AbandonAliasUsers: 'Cannot Alias Users, logging disabled or developer token not set', - AbandonStartSession: 'Cannot start session, logging disabled or developer token not set', - AbandonEndSession: 'Cannot end session, logging disabled or developer token not set', - NoSessionToEnd: 'Cannot end session, no active session found' - }, - ValidationMessages: { - ModifyIdentityRequestUserIdentitiesPresent: 'identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again', - IdentityRequesetInvalidKey: 'There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.', - OnUserAliasType: 'The onUserAlias value must be a function.', - UserIdentities: 'The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.', - UserIdentitiesInvalidKey: 'There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.', - UserIdentitiesInvalidValues: 'All user identity values must be strings or null. Request not sent to server. Please fix and try again.', - AliasMissingMpid: 'Alias Request must contain both a destinationMpid and a sourceMpid', - AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique", - AliasMissingTime: 'Alias Request must have both a startTime and an endTime', - AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime" - } - }, - NativeSdkPaths: { - LogEvent: 'logEvent', - SetUserTag: 'setUserTag', - RemoveUserTag: 'removeUserTag', - SetUserAttribute: 'setUserAttribute', - RemoveUserAttribute: 'removeUserAttribute', - SetSessionAttribute: 'setSessionAttribute', - AddToCart: 'addToCart', - RemoveFromCart: 'removeFromCart', - ClearCart: 'clearCart', - LogOut: 'logOut', - SetUserAttributeList: 'setUserAttributeList', - RemoveAllUserAttributes: 'removeAllUserAttributes', - GetUserAttributesLists: 'getUserAttributesLists', - GetAllUserAttributes: 'getAllUserAttributes', - Identify: 'identify', - Logout: 'logout', - Login: 'login', - Modify: 'modify', - Alias: 'aliasUsers', - Upload: 'upload' - }, - StorageNames: { - localStorageName: 'mprtcl-api', - localStorageNameV3: 'mprtcl-v3', - cookieName: 'mprtcl-api', - cookieNameV2: 'mprtcl-v2', - cookieNameV3: 'mprtcl-v3', - localStorageNameV4: 'mprtcl-v4', - localStorageProductsV4: 'mprtcl-prodv4', - cookieNameV4: 'mprtcl-v4', - currentStorageName: 'mprtcl-v4', - currentStorageProductsName: 'mprtcl-prodv4' - }, - DefaultConfig: { - cookieDomain: null, - cookieExpiration: 365, - logLevel: null, - timeout: 300, - sessionTimeout: 30, - maxProducts: 20, - forwarderStatsTimeout: 5000, - integrationDelayTimeout: 5000, - maxCookieSize: 3000, - aliasMaxWindow: 90, - uploadInterval: 0 // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally - }, - - DefaultBaseUrls: { - v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/', - v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/', - v3SecureServiceUrl: 'jssdks.mparticle.com/v3/JS/', - configUrl: 'jssdkcdns.mparticle.com/JS/v2/', - identityUrl: 'identity.mparticle.com/v1/', - aliasUrl: 'jssdks.mparticle.com/v1/identity/', - userAudienceUrl: 'nativesdks.mparticle.com/v1/' - }, - // These are the paths that are used to construct the CNAME urls - CNAMEUrlPaths: { - v1SecureServiceUrl: '/webevents/v1/JS/', - v2SecureServiceUrl: '/webevents/v2/JS/', - v3SecureServiceUrl: '/webevents/v3/JS/', - configUrl: '/tags/JS/v2/', - identityUrl: '/identity/v1/', - aliasUrl: '/webevents/v1/identity/' - }, - Base64CookieKeys: { - csm: 1, - sa: 1, - ss: 1, - lsa: 1, - ua: 1, - ui: 1, - csd: 1, - ia: 1, - con: 1 - }, - // https://go.mparticle.com/work/SQDSDKS-6039 - SDKv2NonMPIDCookieKeys: { - gs: 1, - cu: 1, - l: 1, - globalSettings: 1, - currentUserMPID: 1 - }, - HTTPCodes: { - noHttpCoverage: -1, - activeIdentityRequest: -2, - activeSession: -3, - validationIssue: -4, - nativeIdentityRequest: -5, - loggingDisabledOrMissingAPIKey: -6, - tooManyRequests: 429 - }, - FeatureFlags: { - ReportBatching: 'reportBatching', - EventBatchingIntervalMillis: 'eventBatchingIntervalMillis', - OfflineStorage: 'offlineStorage', - DirectUrlRouting: 'directURLRouting', - CacheIdentity: 'cacheIdentity', - AudienceAPI: 'audienceAPI', - // CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI - // - 'True' → capture all integration-specific IDs - // - 'False' → capture none - CaptureIntegrationSpecificIds: 'captureIntegrationSpecificIds', - // CaptureIntegrationSpecificIdsV2 (new): string mode from server - // - 'all' → capture all IDs - // - 'none' → capture none - // - 'roktonly' → capture only Rokt-related IDs - CaptureIntegrationSpecificIdsV2: 'captureIntegrationSpecificIdsV2', - AstBackgroundEvents: 'astBackgroundEvents' - }, - DefaultInstance: 'default_instance', - CCPAPurpose: 'data_sale_opt_out', - IdentityMethods: { - Modify: 'modify', - Logout: 'logout', - Login: 'login', - Identify: 'identify' - }, - Environment: { - Development: 'development', - Production: 'production' - }, - CaptureIntegrationSpecificIdsV2Modes: { - All: 'all', - None: 'none', - RoktOnly: 'roktonly' - }, - Rokt: { - LauncherInstanceGuidKey: '__rokt_li_guid__' - } - }; - // https://go.mparticle.com/work/SQDSDKS-6080 - var ONE_DAY_IN_SECONDS = 60 * 60 * 24; - var MILLIS_IN_ONE_SEC = 1000; - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status - var HTTP_OK = 200; - var HTTP_ACCEPTED = 202; - var HTTP_BAD_REQUEST = 400; - var HTTP_SERVER_ERROR = 500; - - /****************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise, SuppressedError, Symbol */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } - - function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - } - - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - } - - typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; - }; - - var Messages$9 = Constants.Messages; - var createCookieString = function createCookieString(value) { - return replaceCommasWithPipes(replaceQuotesWithApostrophes(value)); - }; - var revertCookieString = function revertCookieString(value) { - return replacePipesWithCommas(replaceApostrophesWithQuotes(value)); - }; - var inArray = function inArray(items, name) { - if (!items) { - return false; - } - var i = 0; - if (Array.prototype.indexOf) { - return items.indexOf(name, 0) >= 0; - } else { - for (var n = items.length; i < n; i++) { - if (i in items && items[i] === name) { - return true; - } - } - } - return false; - }; - var findKeyInObject = function findKeyInObject(obj, key) { - if (key && obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop) && prop.toLowerCase() === key.toLowerCase()) { - return prop; - } - } - } - return null; - }; - var generateDeprecationMessage = function generateDeprecationMessage(methodName, isDeprecated, alternateMethod, docsUrl) { - var messageArray = [methodName]; - if (isDeprecated) { - messageArray.push(Messages$9.DeprecationMessages.MethodHasBeenDeprecated); - } else { - messageArray.push(Messages$9.DeprecationMessages.MethodMarkedForDeprecationPostfix); - } - if (alternateMethod) { - messageArray.push(Messages$9.DeprecationMessages.AlternativeMethodPrefix); - messageArray.push(alternateMethod + "."); - } - if (docsUrl) { - messageArray.push("See - " + docsUrl); - } - return messageArray.join(' '); - }; - function generateHash(name) { - var hash = 0; - var character; - if (name === undefined || name === null) { - return 0; - } - name = name.toString().toLowerCase(); - if (Array.prototype.reduce) { - return name.split('').reduce(function (a, b) { - a = (a << 5) - a + b.charCodeAt(0); - return a & a; - }, 0); - } - if (name.length === 0) { - return hash; - } - for (var i = 0; i < name.length; i++) { - character = name.charCodeAt(i); - hash = (hash << 5) - hash + character; - hash = hash & hash; - } - return hash; - } - var generateRandomValue = function generateRandomValue(value) { - var randomValue; - var a; - if (window.crypto && window.crypto.getRandomValues) { - // @ts-ignore - randomValue = window.crypto.getRandomValues(new Uint8Array(1)); // eslint-disable-line no-undef - } - - if (randomValue) { - // @ts-ignore - return (a ^ randomValue[0] % 16 >> a / 4).toString(16); - } - return (a ^ Math.random() * 16 >> a / 4).toString(16); - }; - var generateUniqueId = function generateUniqueId(a) { - // https://gist.github.com/jed/982883 - // Added support for crypto for better random - if (a === void 0) { - a = ''; - } - return a // if the placeholder was passed, return - ? generateRandomValue() // if the placeholder was passed, return - : - // [1e7] -> // 10000000 + - // -1e3 -> // -1000 + - // -4e3 -> // -4000 + - // -8e3 -> // -80000000 + - // -1e11 -> //-100000000000, - "".concat(1e7, "-").concat(1e3, "-").concat(4e3, "-").concat(8e3, "-").concat(1e11).replace(/[018]/g, - // zeroes, ones, and eights with - generateUniqueId // random hex digits - ); - }; - /** - * Returns a value between 1-100 inclusive. - */ - var getRampNumber = function getRampNumber(value) { - if (!value) { - return 100; - } - var hash = generateHash(value); - return Math.abs(hash % 100) + 1; - }; - var isObject = function isObject(value) { - var objType = Object.prototype.toString.call(value); - return objType === '[object Object]' || objType === '[object Error]'; - }; - var parseNumber = function parseNumber(value) { - if (isNaN(value) || !isFinite(value)) { - return 0; - } - var floatValue = parseFloat(value); - return isNaN(floatValue) ? 0 : floatValue; - }; - var parseSettingsString = function parseSettingsString(settingsString) { - try { - return settingsString ? JSON.parse(settingsString.replace(/"/g, '"')) : []; - } catch (error) { - throw new Error('Settings string contains invalid JSON'); - } - }; - var parseStringOrNumber = function parseStringOrNumber(value) { - if (isStringOrNumber(value)) { - return value; - } else { - return null; - } - }; - var replaceCommasWithPipes = function replaceCommasWithPipes(value) { - return value.replace(/,/g, '|'); - }; - var replacePipesWithCommas = function replacePipesWithCommas(value) { - return value.replace(/\|/g, ','); - }; - var replaceApostrophesWithQuotes = function replaceApostrophesWithQuotes(value) { - return value.replace(/\'/g, '"'); - }; - var replaceQuotesWithApostrophes = function replaceQuotesWithApostrophes(value) { - return value.replace(/\"/g, "'"); - }; - var replaceMPID = function replaceMPID(value, mpid) { - return value.replace('%%mpid%%', mpid); - }; - var replaceAmpWithAmpersand = function replaceAmpWithAmpersand(value) { - return value.replace(/&/g, '&'); - }; - var createCookieSyncUrl = function createCookieSyncUrl(mpid, pixelUrl, redirectUrl, domain) { - var modifiedPixelUrl = replaceAmpWithAmpersand(pixelUrl); - var modifiedDirectUrl = redirectUrl ? replaceAmpWithAmpersand(redirectUrl) : null; - var url = replaceMPID(modifiedPixelUrl, mpid); - var redirect = modifiedDirectUrl ? replaceMPID(modifiedDirectUrl, mpid) : ''; - var fullUrl = url + encodeURIComponent(redirect); - if (domain) { - var separator = fullUrl.includes('?') ? '&' : '?'; - fullUrl += "".concat(separator, "domain=").concat(domain); - } - return fullUrl; - }; - // FIXME: REFACTOR for V3 - // only used in store.js to sanitize server-side formatting of - // booleans when checking for `isDevelopmentMode` - // Should be removed in v3 - var returnConvertedBoolean = function returnConvertedBoolean(data) { - if (data === 'false' || data === '0') { - return false; - } else { - return Boolean(data); - } - }; - var decoded = function decoded(s) { - return decodeURIComponent(s.replace(/\+/g, ' ')); - }; - var converted = function converted(s) { - if (s.indexOf('"') === 0) { - s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); - } - return s; - }; - var isString = function isString(value) { - return typeof value === 'string'; - }; - var isNumber = function isNumber(value) { - return typeof value === 'number'; - }; - var isBoolean = function isBoolean(value) { - return typeof value === 'boolean'; - }; - var isFunction = function isFunction(fn) { - return typeof fn === 'function'; - }; - var isValidAttributeValue = function isValidAttributeValue(value) { - return value !== undefined && !isObject(value) && !Array.isArray(value); - }; - var isValidCustomFlagProperty = function isValidCustomFlagProperty(value) { - return isNumber(value) || isString(value) || isBoolean(value); - }; - var toDataPlanSlug = function toDataPlanSlug(value) { - // Make sure we are only acting on strings or numbers - return isStringOrNumber(value) ? value.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g, '_') : ''; - }; - var isDataPlanSlug = function isDataPlanSlug(str) { - return str === toDataPlanSlug(str); - }; - var isStringOrNumber = function isStringOrNumber(value) { - return isString(value) || isNumber(value); - }; - var isEmpty = function isEmpty(value) { - return value == null || !(Object.keys(value) || value).length; - }; - var moveElementToEnd = function moveElementToEnd(array, index) { - return array.slice(0, index).concat(array.slice(index + 1), array[index]); - }; - var queryStringParser = function queryStringParser(url, keys) { - if (keys === void 0) { - keys = []; - } - var urlParams; - var results = {}; - var lowerCaseUrlParams = {}; - if (!url) return results; - if (typeof URL !== 'undefined' && typeof URLSearchParams !== 'undefined') { - var urlObject = new URL(url); - urlParams = new URLSearchParams(urlObject.search); - } else { - urlParams = queryStringParserFallback(url); - } - urlParams.forEach(function (value, key) { - lowerCaseUrlParams[key.toLowerCase()] = value; - }); - if (isEmpty(keys)) { - return lowerCaseUrlParams; - } else { - keys.forEach(function (key) { - var value = lowerCaseUrlParams[key.toLowerCase()]; - if (value) { - results[key] = value; - } - }); - } - return results; - }; - var queryStringParserFallback = function queryStringParserFallback(url) { - var params = {}; - var queryString = url.split('?')[1] || ''; - var pairs = queryString.split('&'); - pairs.forEach(function (pair) { - var _a = pair.split('='), - key = _a[0], - valueParts = _a.slice(1); - var value = valueParts.join('='); - if (key && value !== undefined) { - try { - params[key] = decodeURIComponent(value || ''); - } catch (e) { - console.error("Failed to decode value for key ".concat(key, ": ").concat(e)); - } - } - }); - return { - get: function get(key) { - return params[key]; - }, - forEach: function forEach(callback) { - for (var key in params) { - if (params.hasOwnProperty(key)) { - callback(params[key], key); - } - } - } - }; - }; - // Get cookies as a dictionary - var getCookies = function getCookies(keys) { - // Helper function to parse cookies from document.cookie - var parseCookies = function parseCookies() { - try { - if (typeof window === 'undefined') { - return []; - } - return window.document.cookie.split(';').map(function (cookie) { - return cookie.trim(); - }); - } catch (e) { - console.error('Unable to parse cookies', e); - return []; - } - }; - // Helper function to filter cookies by keys - var filterCookies = function filterCookies(cookies, keys) { - var results = {}; - for (var _i = 0, cookies_1 = cookies; _i < cookies_1.length; _i++) { - var cookie = cookies_1[_i]; - var _a = cookie.split('='), - key = _a[0], - value = _a[1]; - if (!keys || keys.includes(key)) { - results[key] = value; - } - } - return results; - }; - // Parse cookies from document.cookie - var parsedCookies = parseCookies(); - // Filter cookies by keys if provided - return filterCookies(parsedCookies, keys); - }; - var getHref = function getHref() { - return typeof window !== 'undefined' && window.location ? window.location.href : ''; - }; - var filterDictionaryWithHash = function filterDictionaryWithHash(dictionary, filterList, hashFn) { - var filtered = {}; - if (!isEmpty(dictionary)) { - for (var key in dictionary) { - if (dictionary.hasOwnProperty(key)) { - var hashedKey = hashFn(key); - if (!inArray(filterList, hashedKey)) { - filtered[key] = dictionary[key]; - } - } - } - } - return filtered; - }; - var parseConfig = function parseConfig(config, moduleName, moduleId) { - var _a; - return ((_a = config.kitConfigs) === null || _a === void 0 ? void 0 : _a.find(function (kitConfig) { - return kitConfig.name === moduleName && kitConfig.moduleId === moduleId; - })) || null; - }; - - var MessageType$1 = { - SessionStart: 1, - SessionEnd: 2, - PageView: 3, - PageEvent: 4, - CrashReport: 5, - OptOut: 6, - AppStateTransition: 10, - Profile: 14, - Commerce: 16, - Media: 20, - UserAttributeChange: 17, - UserIdentityChange: 18 - }; - var EventType = { - Unknown: 0, - Navigation: 1, - Location: 2, - Search: 3, - Transaction: 4, - UserContent: 5, - UserPreference: 6, - Social: 7, - Other: 8, - Media: 9, - getName: function getName(id) { - switch (id) { - case EventType.Unknown: - return 'Unknown'; - case EventType.Navigation: - return 'Navigation'; - case EventType.Location: - return 'Location'; - case EventType.Search: - return 'Search'; - case EventType.Transaction: - return 'Transaction'; - case EventType.UserContent: - return 'User Content'; - case EventType.UserPreference: - return 'User Preference'; - case EventType.Social: - return 'Social'; - case CommerceEventType.ProductAddToCart: - return 'Product Added to Cart'; - case CommerceEventType.ProductAddToWishlist: - return 'Product Added to Wishlist'; - case CommerceEventType.ProductCheckout: - return 'Product Checkout'; - case CommerceEventType.ProductCheckoutOption: - return 'Product Checkout Options'; - case CommerceEventType.ProductClick: - return 'Product Click'; - case CommerceEventType.ProductImpression: - return 'Product Impression'; - case CommerceEventType.ProductPurchase: - return 'Product Purchased'; - case CommerceEventType.ProductRefund: - return 'Product Refunded'; - case CommerceEventType.ProductRemoveFromCart: - return 'Product Removed From Cart'; - case CommerceEventType.ProductRemoveFromWishlist: - return 'Product Removed from Wishlist'; - case CommerceEventType.ProductViewDetail: - return 'Product View Details'; - case CommerceEventType.PromotionClick: - return 'Promotion Click'; - case CommerceEventType.PromotionView: - return 'Promotion View'; - default: - return 'Other'; - } - } - }; - // Continuation of EventType enum above, but in seperate object since we don't expose these to end user - var CommerceEventType = { - ProductAddToCart: 10, - ProductRemoveFromCart: 11, - ProductCheckout: 12, - ProductCheckoutOption: 13, - ProductClick: 14, - ProductViewDetail: 15, - ProductPurchase: 16, - ProductRefund: 17, - PromotionView: 18, - PromotionClick: 19, - ProductAddToWishlist: 20, - ProductRemoveFromWishlist: 21, - ProductImpression: 22 - }; - var IdentityType = { - Other: 0, - CustomerId: 1, - Facebook: 2, - Twitter: 3, - Google: 4, - Microsoft: 5, - Yahoo: 6, - Email: 7, - FacebookCustomAudienceId: 9, - Other2: 10, - Other3: 11, - Other4: 12, - Other5: 13, - Other6: 14, - Other7: 15, - Other8: 16, - Other9: 17, - Other10: 18, - MobileNumber: 19, - PhoneNumber2: 20, - PhoneNumber3: 21, - isValid: function isValid(identityType) { - if (typeof identityType === 'number') { - for (var prop in IdentityType) { - if (IdentityType.hasOwnProperty(prop)) { - if (IdentityType[prop] === identityType) { - return true; - } - } - } - } - return false; - }, - getName: function getName(identityType) { - switch (identityType) { - case window.mParticle.IdentityType.CustomerId: - return 'Customer ID'; - case window.mParticle.IdentityType.Facebook: - return 'Facebook ID'; - case window.mParticle.IdentityType.Twitter: - return 'Twitter ID'; - case window.mParticle.IdentityType.Google: - return 'Google ID'; - case window.mParticle.IdentityType.Microsoft: - return 'Microsoft ID'; - case window.mParticle.IdentityType.Yahoo: - return 'Yahoo ID'; - case window.mParticle.IdentityType.Email: - return 'Email'; - case window.mParticle.IdentityType.FacebookCustomAudienceId: - return 'Facebook App User ID'; - default: - return 'Other ID'; - } - }, - getIdentityType: function getIdentityType(identityName) { - switch (identityName) { - case 'other': - return IdentityType.Other; - case 'customerid': - return IdentityType.CustomerId; - case 'facebook': - return IdentityType.Facebook; - case 'twitter': - return IdentityType.Twitter; - case 'google': - return IdentityType.Google; - case 'microsoft': - return IdentityType.Microsoft; - case 'yahoo': - return IdentityType.Yahoo; - case 'email': - return IdentityType.Email; - case 'facebookcustomaudienceid': - return IdentityType.FacebookCustomAudienceId; - case 'other2': - return IdentityType.Other2; - case 'other3': - return IdentityType.Other3; - case 'other4': - return IdentityType.Other4; - case 'other5': - return IdentityType.Other5; - case 'other6': - return IdentityType.Other6; - case 'other7': - return IdentityType.Other7; - case 'other8': - return IdentityType.Other8; - case 'other9': - return IdentityType.Other9; - case 'other10': - return IdentityType.Other10; - case 'mobile_number': - return IdentityType.MobileNumber; - case 'phone_number_2': - return IdentityType.PhoneNumber2; - case 'phone_number_3': - return IdentityType.PhoneNumber3; - default: - return false; - } - }, - getIdentityName: function getIdentityName(identityType) { - switch (identityType) { - case IdentityType.Other: - return 'other'; - case IdentityType.CustomerId: - return 'customerid'; - case IdentityType.Facebook: - return 'facebook'; - case IdentityType.Twitter: - return 'twitter'; - case IdentityType.Google: - return 'google'; - case IdentityType.Microsoft: - return 'microsoft'; - case IdentityType.Yahoo: - return 'yahoo'; - case IdentityType.Email: - return 'email'; - case IdentityType.FacebookCustomAudienceId: - return 'facebookcustomaudienceid'; - case IdentityType.Other2: - return 'other2'; - case IdentityType.Other3: - return 'other3'; - case IdentityType.Other4: - return 'other4'; - case IdentityType.Other5: - return 'other5'; - case IdentityType.Other6: - return 'other6'; - case IdentityType.Other7: - return 'other7'; - case IdentityType.Other8: - return 'other8'; - case IdentityType.Other9: - return 'other9'; - case IdentityType.Other10: - return 'other10'; - case IdentityType.MobileNumber: - return 'mobile_number'; - case IdentityType.PhoneNumber2: - return 'phone_number_2'; - case IdentityType.PhoneNumber3: - return 'phone_number_3'; - default: - return null; - } - }, - // Strips out functions from Identity Types for easier lookups - getValuesAsStrings: function getValuesAsStrings() { - return Object.values(IdentityType).map(function (value) { - return isNumber(value) ? value.toString() : undefined; - }).filter(function (value) { - return value !== undefined; - }); - }, - getNewIdentitiesByName: function getNewIdentitiesByName(newIdentitiesByType) { - var newIdentitiesByName = {}; - var identityTypeValuesAsStrings = IdentityType.getValuesAsStrings(); - for (var key in newIdentitiesByType) { - // IdentityTypes are stored as numbers but are passed in as strings - if (identityTypeValuesAsStrings.includes(key)) { - var identityNameKey = IdentityType.getIdentityName(parseNumber(key)); - newIdentitiesByName[identityNameKey] = newIdentitiesByType[key]; - } - } - return newIdentitiesByName; - } - }; - var ProductActionType = { - Unknown: 0, - AddToCart: 1, - RemoveFromCart: 2, - Checkout: 3, - CheckoutOption: 4, - Click: 5, - ViewDetail: 6, - Purchase: 7, - Refund: 8, - AddToWishlist: 9, - RemoveFromWishlist: 10, - getName: function getName(id) { - switch (id) { - case ProductActionType.AddToCart: - return 'Add to Cart'; - case ProductActionType.RemoveFromCart: - return 'Remove from Cart'; - case ProductActionType.Checkout: - return 'Checkout'; - case ProductActionType.CheckoutOption: - return 'Checkout Option'; - case ProductActionType.Click: - return 'Click'; - case ProductActionType.ViewDetail: - return 'View Detail'; - case ProductActionType.Purchase: - return 'Purchase'; - case ProductActionType.Refund: - return 'Refund'; - case ProductActionType.AddToWishlist: - return 'Add to Wishlist'; - case ProductActionType.RemoveFromWishlist: - return 'Remove from Wishlist'; - default: - return 'Unknown'; - } - }, - // these are the action names used by server and mobile SDKs when expanding a CommerceEvent - getExpansionName: function getExpansionName(id) { - switch (id) { - case ProductActionType.AddToCart: - return 'add_to_cart'; - case ProductActionType.RemoveFromCart: - return 'remove_from_cart'; - case ProductActionType.Checkout: - return 'checkout'; - case ProductActionType.CheckoutOption: - return 'checkout_option'; - case ProductActionType.Click: - return 'click'; - case ProductActionType.ViewDetail: - return 'view_detail'; - case ProductActionType.Purchase: - return 'purchase'; - case ProductActionType.Refund: - return 'refund'; - case ProductActionType.AddToWishlist: - return 'add_to_wishlist'; - case ProductActionType.RemoveFromWishlist: - return 'remove_from_wishlist'; - default: - return 'unknown'; - } - } - }; - var PromotionActionType = { - Unknown: 0, - PromotionView: 1, - PromotionClick: 2, - getName: function getName(id) { - switch (id) { - case PromotionActionType.PromotionView: - return 'view'; - case PromotionActionType.PromotionClick: - return 'click'; - default: - return 'unknown'; - } - }, - // these are the names that the server and mobile SDKs use while expanding CommerceEvent - getExpansionName: function getExpansionName(id) { - switch (id) { - case PromotionActionType.PromotionView: - return 'view'; - case PromotionActionType.PromotionClick: - return 'click'; - default: - return 'unknown'; - } - } - }; - var ProfileMessageType = { - Logout: 3 - }; - var ApplicationTransitionType$1 = { - AppInit: 1 - }; - var PerformanceMarkType = { - SdkStart: 'mp:sdkStart', - JointSdkSelectPlacements: 'mp:jointSdkSelectPlacements', - JointSdkRoktKitInit: 'mp:jointSdkRoktKitInit' - }; - var Types = { - MessageType: MessageType$1, - EventType: EventType, - CommerceEventType: CommerceEventType, - IdentityType: IdentityType, - ProfileMessageType: ProfileMessageType, - ApplicationTransitionType: ApplicationTransitionType$1, - ProductActionType: ProductActionType, - PromotionActionType: PromotionActionType, - Environment: Constants.Environment - }; - - function _typeof$1(o) { - "@babel/helpers - typeof"; - - return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { - return typeof o; - } : function (o) { - return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; - }, _typeof$1(o); - } - - var SDKProductActionType; - (function (SDKProductActionType) { - SDKProductActionType[SDKProductActionType["Unknown"] = 0] = "Unknown"; - SDKProductActionType[SDKProductActionType["AddToCart"] = 1] = "AddToCart"; - SDKProductActionType[SDKProductActionType["RemoveFromCart"] = 2] = "RemoveFromCart"; - SDKProductActionType[SDKProductActionType["Checkout"] = 3] = "Checkout"; - SDKProductActionType[SDKProductActionType["CheckoutOption"] = 4] = "CheckoutOption"; - SDKProductActionType[SDKProductActionType["Click"] = 5] = "Click"; - SDKProductActionType[SDKProductActionType["ViewDetail"] = 6] = "ViewDetail"; - SDKProductActionType[SDKProductActionType["Purchase"] = 7] = "Purchase"; - SDKProductActionType[SDKProductActionType["Refund"] = 8] = "Refund"; - SDKProductActionType[SDKProductActionType["AddToWishlist"] = 9] = "AddToWishlist"; - SDKProductActionType[SDKProductActionType["RemoveFromWishlist"] = 10] = "RemoveFromWishlist"; - })(SDKProductActionType || (SDKProductActionType = {})); - var LogLevelType = { - None: 'none', - Verbose: 'verbose', - Warning: 'warning', - Error: 'error' - }; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var dist = {}; - - (function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - (function (ApplicationInformationOsEnum) { - ApplicationInformationOsEnum["unknown"] = "Unknown"; - ApplicationInformationOsEnum["iOS"] = "IOS"; - ApplicationInformationOsEnum["android"] = "Android"; - ApplicationInformationOsEnum["windowsPhone"] = "WindowsPhone"; - ApplicationInformationOsEnum["mobileWeb"] = "MobileWeb"; - ApplicationInformationOsEnum["unityIOS"] = "UnityIOS"; - ApplicationInformationOsEnum["unityAndroid"] = "UnityAndroid"; - ApplicationInformationOsEnum["desktop"] = "Desktop"; - ApplicationInformationOsEnum["tvOS"] = "TVOS"; - ApplicationInformationOsEnum["roku"] = "Roku"; - ApplicationInformationOsEnum["outOfBand"] = "OutOfBand"; - ApplicationInformationOsEnum["alexa"] = "Alexa"; - ApplicationInformationOsEnum["smartTV"] = "SmartTV"; - ApplicationInformationOsEnum["fireTV"] = "FireTV"; - ApplicationInformationOsEnum["xbox"] = "Xbox"; - })(exports.ApplicationInformationOsEnum || (exports.ApplicationInformationOsEnum = {})); - (function (ApplicationStateTransitionEventEventTypeEnum) { - ApplicationStateTransitionEventEventTypeEnum["applicationStateTransition"] = "application_state_transition"; - })(exports.ApplicationStateTransitionEventEventTypeEnum || (exports.ApplicationStateTransitionEventEventTypeEnum = {})); - (function (ApplicationStateTransitionEventDataApplicationTransitionTypeEnum) { - ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationInitialized"] = "application_initialized"; - ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationExit"] = "application_exit"; - ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationBackground"] = "application_background"; - ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationForeground"] = "application_foreground"; - })(exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum || (exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum = {})); - (function (BatchEnvironmentEnum) { - BatchEnvironmentEnum["unknown"] = "unknown"; - BatchEnvironmentEnum["development"] = "development"; - BatchEnvironmentEnum["production"] = "production"; - })(exports.BatchEnvironmentEnum || (exports.BatchEnvironmentEnum = {})); - (function (BreadcrumbEventEventTypeEnum) { - BreadcrumbEventEventTypeEnum["breadcrumb"] = "breadcrumb"; - })(exports.BreadcrumbEventEventTypeEnum || (exports.BreadcrumbEventEventTypeEnum = {})); - (function (CommerceEventEventTypeEnum) { - CommerceEventEventTypeEnum["commerceEvent"] = "commerce_event"; - })(exports.CommerceEventEventTypeEnum || (exports.CommerceEventEventTypeEnum = {})); - (function (CommerceEventDataCustomEventTypeEnum) { - CommerceEventDataCustomEventTypeEnum["addToCart"] = "add_to_cart"; - CommerceEventDataCustomEventTypeEnum["removeFromCart"] = "remove_from_cart"; - CommerceEventDataCustomEventTypeEnum["checkout"] = "checkout"; - CommerceEventDataCustomEventTypeEnum["checkoutOption"] = "checkout_option"; - CommerceEventDataCustomEventTypeEnum["click"] = "click"; - CommerceEventDataCustomEventTypeEnum["viewDetail"] = "view_detail"; - CommerceEventDataCustomEventTypeEnum["purchase"] = "purchase"; - CommerceEventDataCustomEventTypeEnum["refund"] = "refund"; - CommerceEventDataCustomEventTypeEnum["promotionView"] = "promotion_view"; - CommerceEventDataCustomEventTypeEnum["promotionClick"] = "promotion_click"; - CommerceEventDataCustomEventTypeEnum["addToWishlist"] = "add_to_wishlist"; - CommerceEventDataCustomEventTypeEnum["removeFromWishlist"] = "remove_from_wishlist"; - CommerceEventDataCustomEventTypeEnum["impression"] = "impression"; - })(exports.CommerceEventDataCustomEventTypeEnum || (exports.CommerceEventDataCustomEventTypeEnum = {})); - (function (CrashReportEventEventTypeEnum) { - CrashReportEventEventTypeEnum["crashReport"] = "crash_report"; - })(exports.CrashReportEventEventTypeEnum || (exports.CrashReportEventEventTypeEnum = {})); - (function (CustomEventEventTypeEnum) { - CustomEventEventTypeEnum["customEvent"] = "custom_event"; - })(exports.CustomEventEventTypeEnum || (exports.CustomEventEventTypeEnum = {})); - (function (CustomEventDataCustomEventTypeEnum) { - CustomEventDataCustomEventTypeEnum["navigation"] = "navigation"; - CustomEventDataCustomEventTypeEnum["location"] = "location"; - CustomEventDataCustomEventTypeEnum["search"] = "search"; - CustomEventDataCustomEventTypeEnum["transaction"] = "transaction"; - CustomEventDataCustomEventTypeEnum["userContent"] = "user_content"; - CustomEventDataCustomEventTypeEnum["userPreference"] = "user_preference"; - CustomEventDataCustomEventTypeEnum["social"] = "social"; - CustomEventDataCustomEventTypeEnum["media"] = "media"; - CustomEventDataCustomEventTypeEnum["other"] = "other"; - CustomEventDataCustomEventTypeEnum["unknown"] = "unknown"; - })(exports.CustomEventDataCustomEventTypeEnum || (exports.CustomEventDataCustomEventTypeEnum = {})); - (function (DeviceCurrentStateDeviceOrientationEnum) { - DeviceCurrentStateDeviceOrientationEnum["portrait"] = "portrait"; - DeviceCurrentStateDeviceOrientationEnum["portraitUpsideDown"] = "portrait_upside_down"; - DeviceCurrentStateDeviceOrientationEnum["landscape"] = "landscape"; - DeviceCurrentStateDeviceOrientationEnum["landscapeLeft"] = "LandscapeLeft"; - DeviceCurrentStateDeviceOrientationEnum["landscapeRight"] = "LandscapeRight"; - DeviceCurrentStateDeviceOrientationEnum["faceUp"] = "FaceUp"; - DeviceCurrentStateDeviceOrientationEnum["faceDown"] = "FaceDown"; - DeviceCurrentStateDeviceOrientationEnum["square"] = "Square"; - })(exports.DeviceCurrentStateDeviceOrientationEnum || (exports.DeviceCurrentStateDeviceOrientationEnum = {})); - (function (DeviceCurrentStateStatusBarOrientationEnum) { - DeviceCurrentStateStatusBarOrientationEnum["portrait"] = "portrait"; - DeviceCurrentStateStatusBarOrientationEnum["portraitUpsideDown"] = "portrait_upside_down"; - DeviceCurrentStateStatusBarOrientationEnum["landscape"] = "landscape"; - DeviceCurrentStateStatusBarOrientationEnum["landscapeLeft"] = "LandscapeLeft"; - DeviceCurrentStateStatusBarOrientationEnum["landscapeRight"] = "LandscapeRight"; - DeviceCurrentStateStatusBarOrientationEnum["faceUp"] = "FaceUp"; - DeviceCurrentStateStatusBarOrientationEnum["faceDown"] = "FaceDown"; - DeviceCurrentStateStatusBarOrientationEnum["square"] = "Square"; - })(exports.DeviceCurrentStateStatusBarOrientationEnum || (exports.DeviceCurrentStateStatusBarOrientationEnum = {})); - (function (DeviceInformationPlatformEnum) { - DeviceInformationPlatformEnum["iOS"] = "iOS"; - DeviceInformationPlatformEnum["android"] = "Android"; - DeviceInformationPlatformEnum["web"] = "web"; - DeviceInformationPlatformEnum["desktop"] = "desktop"; - DeviceInformationPlatformEnum["tvOS"] = "tvOS"; - DeviceInformationPlatformEnum["roku"] = "roku"; - DeviceInformationPlatformEnum["outOfBand"] = "out_of_band"; - DeviceInformationPlatformEnum["smartTV"] = "smart_tv"; - DeviceInformationPlatformEnum["xbox"] = "xbox"; - })(exports.DeviceInformationPlatformEnum || (exports.DeviceInformationPlatformEnum = {})); - (function (EventTypeEnum) { - EventTypeEnum["unknown"] = "unknown"; - EventTypeEnum["sessionStart"] = "session_start"; - EventTypeEnum["sessionEnd"] = "session_end"; - EventTypeEnum["screenView"] = "screen_view"; - EventTypeEnum["customEvent"] = "custom_event"; - EventTypeEnum["crashReport"] = "crash_report"; - EventTypeEnum["optOut"] = "opt_out"; - EventTypeEnum["firstRun"] = "first_run"; - EventTypeEnum["preAttribution"] = "pre_attribution"; - EventTypeEnum["pushRegistration"] = "push_registration"; - EventTypeEnum["applicationStateTransition"] = "application_state_transition"; - EventTypeEnum["pushMessage"] = "push_message"; - EventTypeEnum["networkPerformance"] = "network_performance"; - EventTypeEnum["breadcrumb"] = "breadcrumb"; - EventTypeEnum["profile"] = "profile"; - EventTypeEnum["pushReaction"] = "push_reaction"; - EventTypeEnum["commerceEvent"] = "commerce_event"; - EventTypeEnum["userAttributeChange"] = "user_attribute_change"; - EventTypeEnum["userIdentityChange"] = "user_identity_change"; - EventTypeEnum["uninstall"] = "uninstall"; - EventTypeEnum["validationResult"] = "validation_result"; - })(exports.EventTypeEnum || (exports.EventTypeEnum = {})); - (function (IdentityTypeEnum) { - IdentityTypeEnum["other"] = "other"; - IdentityTypeEnum["customerId"] = "customer_id"; - IdentityTypeEnum["facebook"] = "facebook"; - IdentityTypeEnum["twitter"] = "twitter"; - IdentityTypeEnum["google"] = "google"; - IdentityTypeEnum["microsoft"] = "microsoft"; - IdentityTypeEnum["yahoo"] = "yahoo"; - IdentityTypeEnum["email"] = "email"; - IdentityTypeEnum["alias"] = "alias"; - IdentityTypeEnum["facebookCustomAudienceId"] = "facebook_custom_audience_id"; - IdentityTypeEnum["otherId2"] = "other_id_2"; - IdentityTypeEnum["otherId3"] = "other_id_3"; - IdentityTypeEnum["otherId4"] = "other_id_4"; - IdentityTypeEnum["otherId5"] = "other_id_5"; - IdentityTypeEnum["otherId6"] = "other_id_6"; - IdentityTypeEnum["otherId7"] = "other_id_7"; - IdentityTypeEnum["otherId8"] = "other_id_8"; - IdentityTypeEnum["otherId9"] = "other_id_9"; - IdentityTypeEnum["otherId10"] = "other_id_10"; - IdentityTypeEnum["mobileNumber"] = "mobile_number"; - IdentityTypeEnum["phoneNumber2"] = "phone_number_2"; - IdentityTypeEnum["phoneNumber3"] = "phone_number_3"; - })(exports.IdentityTypeEnum || (exports.IdentityTypeEnum = {})); - (function (NetworkPerformanceEventEventTypeEnum) { - NetworkPerformanceEventEventTypeEnum["networkPerformance"] = "network_performance"; - })(exports.NetworkPerformanceEventEventTypeEnum || (exports.NetworkPerformanceEventEventTypeEnum = {})); - (function (OptOutEventEnum) { - OptOutEventEnum["optOut"] = "opt_out"; - })(exports.OptOutEventEnum || (exports.OptOutEventEnum = {})); - (function (ProductActionActionEnum) { - ProductActionActionEnum["unknown"] = "unknown"; - ProductActionActionEnum["addToCart"] = "add_to_cart"; - ProductActionActionEnum["removeFromCart"] = "remove_from_cart"; - ProductActionActionEnum["checkout"] = "checkout"; - ProductActionActionEnum["checkoutOption"] = "checkout_option"; - ProductActionActionEnum["click"] = "click"; - ProductActionActionEnum["viewDetail"] = "view_detail"; - ProductActionActionEnum["purchase"] = "purchase"; - ProductActionActionEnum["refund"] = "refund"; - ProductActionActionEnum["addToWishlist"] = "add_to_wishlist"; - ProductActionActionEnum["removeFromWishlist"] = "remove_from_wish_list"; - })(exports.ProductActionActionEnum || (exports.ProductActionActionEnum = {})); - (function (ProfileEventEventTypeEnum) { - ProfileEventEventTypeEnum["profile"] = "profile"; - })(exports.ProfileEventEventTypeEnum || (exports.ProfileEventEventTypeEnum = {})); - (function (ProfileEventDataProfileEventTypeEnum) { - ProfileEventDataProfileEventTypeEnum["signup"] = "signup"; - ProfileEventDataProfileEventTypeEnum["login"] = "login"; - ProfileEventDataProfileEventTypeEnum["logout"] = "logout"; - ProfileEventDataProfileEventTypeEnum["update"] = "update"; - ProfileEventDataProfileEventTypeEnum["delete"] = "delete"; - })(exports.ProfileEventDataProfileEventTypeEnum || (exports.ProfileEventDataProfileEventTypeEnum = {})); - (function (PromotionActionActionEnum) { - PromotionActionActionEnum["view"] = "view"; - PromotionActionActionEnum["click"] = "click"; - })(exports.PromotionActionActionEnum || (exports.PromotionActionActionEnum = {})); - (function (PushMessageEventEventTypeEnum) { - PushMessageEventEventTypeEnum["pushMessage"] = "push_message"; - })(exports.PushMessageEventEventTypeEnum || (exports.PushMessageEventEventTypeEnum = {})); - (function (PushMessageEventDataPushMessageTypeEnum) { - PushMessageEventDataPushMessageTypeEnum["sent"] = "sent"; - PushMessageEventDataPushMessageTypeEnum["received"] = "received"; - PushMessageEventDataPushMessageTypeEnum["action"] = "action"; - })(exports.PushMessageEventDataPushMessageTypeEnum || (exports.PushMessageEventDataPushMessageTypeEnum = {})); - (function (PushMessageEventDataApplicationStateEnum) { - PushMessageEventDataApplicationStateEnum["notRunning"] = "not_running"; - PushMessageEventDataApplicationStateEnum["background"] = "background"; - PushMessageEventDataApplicationStateEnum["foreground"] = "foreground"; - })(exports.PushMessageEventDataApplicationStateEnum || (exports.PushMessageEventDataApplicationStateEnum = {})); - (function (PushMessageEventDataPushMessageBehaviorEnum) { - PushMessageEventDataPushMessageBehaviorEnum["received"] = "Received"; - PushMessageEventDataPushMessageBehaviorEnum["directOpen"] = "DirectOpen"; - PushMessageEventDataPushMessageBehaviorEnum["read"] = "Read"; - PushMessageEventDataPushMessageBehaviorEnum["influencedOpen"] = "InfluencedOpen"; - PushMessageEventDataPushMessageBehaviorEnum["displayed"] = "Displayed"; - })(exports.PushMessageEventDataPushMessageBehaviorEnum || (exports.PushMessageEventDataPushMessageBehaviorEnum = {})); - (function (PushRegistrationEventEventTypeEnum) { - PushRegistrationEventEventTypeEnum["pushRegistration"] = "push_registration"; - })(exports.PushRegistrationEventEventTypeEnum || (exports.PushRegistrationEventEventTypeEnum = {})); - (function (SessionEndEventEventTypeEnum) { - SessionEndEventEventTypeEnum["sessionEnd"] = "session_end"; - })(exports.SessionEndEventEventTypeEnum || (exports.SessionEndEventEventTypeEnum = {})); - (function (SessionStartEventEventTypeEnum) { - SessionStartEventEventTypeEnum["sessionStart"] = "session_start"; - })(exports.SessionStartEventEventTypeEnum || (exports.SessionStartEventEventTypeEnum = {})); - (function (SourceInformationChannelEnum) { - SourceInformationChannelEnum["native"] = "native"; - SourceInformationChannelEnum["javascript"] = "javascript"; - SourceInformationChannelEnum["pixel"] = "pixel"; - SourceInformationChannelEnum["desktop"] = "desktop"; - SourceInformationChannelEnum["partner"] = "partner"; - SourceInformationChannelEnum["serverToServer"] = "server_to_server"; - })(exports.SourceInformationChannelEnum || (exports.SourceInformationChannelEnum = {})); - (function (UserAttributeChangeEventEventTypeEnum) { - UserAttributeChangeEventEventTypeEnum["userAttributeChange"] = "user_attribute_change"; - })(exports.UserAttributeChangeEventEventTypeEnum || (exports.UserAttributeChangeEventEventTypeEnum = {})); - (function (UserIdentityChangeEventEventTypeEnum) { - UserIdentityChangeEventEventTypeEnum["userIdentityChange"] = "user_identity_change"; - })(exports.UserIdentityChangeEventEventTypeEnum || (exports.UserIdentityChangeEventEventTypeEnum = {})); - } (dist)); - - var SDKIdentityTypeEnum; - (function (SDKIdentityTypeEnum) { - SDKIdentityTypeEnum["other"] = "other"; - SDKIdentityTypeEnum["customerId"] = "customerid"; - SDKIdentityTypeEnum["facebook"] = "facebook"; - SDKIdentityTypeEnum["twitter"] = "twitter"; - SDKIdentityTypeEnum["google"] = "google"; - SDKIdentityTypeEnum["microsoft"] = "microsoft"; - SDKIdentityTypeEnum["yahoo"] = "yahoo"; - SDKIdentityTypeEnum["email"] = "email"; - SDKIdentityTypeEnum["alias"] = "alias"; - SDKIdentityTypeEnum["facebookCustomAudienceId"] = "facebookcustomaudienceid"; - SDKIdentityTypeEnum["otherId2"] = "other2"; - SDKIdentityTypeEnum["otherId3"] = "other3"; - SDKIdentityTypeEnum["otherId4"] = "other4"; - SDKIdentityTypeEnum["otherId5"] = "other5"; - SDKIdentityTypeEnum["otherId6"] = "other6"; - SDKIdentityTypeEnum["otherId7"] = "other7"; - SDKIdentityTypeEnum["otherId8"] = "other8"; - SDKIdentityTypeEnum["otherId9"] = "other9"; - SDKIdentityTypeEnum["otherId10"] = "other10"; - SDKIdentityTypeEnum["mobileNumber"] = "mobile_number"; - SDKIdentityTypeEnum["phoneNumber2"] = "phone_number_2"; - SDKIdentityTypeEnum["phoneNumber3"] = "phone_number_3"; - })(SDKIdentityTypeEnum || (SDKIdentityTypeEnum = {})); - - var FeatureFlags$2 = Constants.FeatureFlags; - var CaptureIntegrationSpecificIds$1 = FeatureFlags$2.CaptureIntegrationSpecificIds, - CaptureIntegrationSpecificIdsV2$1 = FeatureFlags$2.CaptureIntegrationSpecificIdsV2; - function convertEvents(mpid, sdkEvents, mpInstance) { - if (!mpid) { - return null; - } - if (!sdkEvents || sdkEvents.length < 1) { - return null; - } - var _IntegrationCapture = mpInstance._IntegrationCapture, - _Helpers = mpInstance._Helpers; - var getFeatureFlag = _Helpers.getFeatureFlag; - var user = mpInstance.Identity.getCurrentUser(); - var uploadEvents = []; - var lastEvent = null; - for (var _i = 0, sdkEvents_1 = sdkEvents; _i < sdkEvents_1.length; _i++) { - var sdkEvent = sdkEvents_1[_i]; - if (sdkEvent) { - lastEvent = sdkEvent; - var baseEvent = convertEvent(sdkEvent); - if (baseEvent) { - uploadEvents.push(baseEvent); - } - } - } - if (!lastEvent) { - return null; - } - var currentConsentState = null; - // Add the consent state from either the Last Event or the user - if (!isEmpty(lastEvent.ConsentState)) { - currentConsentState = lastEvent.ConsentState; - } else if (!isEmpty(user)) { - currentConsentState = user.getConsentState(); - } - var upload = { - source_request_id: mpInstance._Helpers.generateUniqueId(), - mpid: mpid, - timestamp_unixtime_ms: new Date().getTime(), - environment: lastEvent.Debug ? dist.BatchEnvironmentEnum.development : dist.BatchEnvironmentEnum.production, - events: uploadEvents, - mp_deviceid: lastEvent.DeviceId, - sdk_version: lastEvent.SDKVersion, - // TODO: Refactor this to read from _Store or a global config - application_info: { - application_version: lastEvent.AppVersion, - application_name: lastEvent.AppName, - "package": lastEvent.Package, - sideloaded_kits_count: mpInstance._Store.sideloadedKitsCount - }, - device_info: { - platform: dist.DeviceInformationPlatformEnum.web, - screen_width: typeof window !== 'undefined' && typeof window.screen !== 'undefined' ? window.screen.width : 0, - screen_height: typeof window !== 'undefined' && typeof window.screen !== 'undefined' ? window.screen.height : 0 - }, - user_attributes: lastEvent.UserAttributes, - user_identities: convertUserIdentities(lastEvent.UserIdentities), - consent_state: convertConsentState(currentConsentState), - integration_attributes: lastEvent.IntegrationAttributes - }; - if (lastEvent.DataPlan && lastEvent.DataPlan.PlanId) { - upload.context = { - data_plan: { - plan_id: lastEvent.DataPlan.PlanId, - plan_version: lastEvent.DataPlan.PlanVersion || undefined - } - }; - } - // https://go.mparticle.com/work/SQDSDKS-7639 - var integrationSpecificIds = getFeatureFlag && Boolean(getFeatureFlag(CaptureIntegrationSpecificIds$1)); - var integrationSpecificIdsV2 = getFeatureFlag && getFeatureFlag(CaptureIntegrationSpecificIdsV2$1); - var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; - if (isIntegrationCaptureEnabled) { - var capturedPartnerIdentities = _IntegrationCapture === null || _IntegrationCapture === void 0 ? void 0 : _IntegrationCapture.getClickIdsAsPartnerIdentities(); - if (!isEmpty(capturedPartnerIdentities)) { - upload.partner_identities = capturedPartnerIdentities; - } - } - return upload; - } - function convertConsentState(sdkConsentState) { - if (isEmpty(sdkConsentState)) { - return null; - } - var consentState = { - gdpr: convertGdprConsentState(sdkConsentState.getGDPRConsentState()), - ccpa: convertCcpaConsentState(sdkConsentState.getCCPAConsentState()) - }; - return consentState; - } - function convertGdprConsentState(sdkGdprConsentState) { - if (!sdkGdprConsentState) { - return null; - } - var state = {}; - for (var purpose in sdkGdprConsentState) { - if (sdkGdprConsentState.hasOwnProperty(purpose)) { - state[purpose] = { - consented: sdkGdprConsentState[purpose].Consented, - hardware_id: sdkGdprConsentState[purpose].HardwareId, - document: sdkGdprConsentState[purpose].ConsentDocument, - timestamp_unixtime_ms: sdkGdprConsentState[purpose].Timestamp, - location: sdkGdprConsentState[purpose].Location - }; - } - } - return state; - } - function convertCcpaConsentState(sdkCcpaConsentState) { - if (!sdkCcpaConsentState) { - return null; - } - var state = { - data_sale_opt_out: { - consented: sdkCcpaConsentState.Consented, - hardware_id: sdkCcpaConsentState.HardwareId, - document: sdkCcpaConsentState.ConsentDocument, - timestamp_unixtime_ms: sdkCcpaConsentState.Timestamp, - location: sdkCcpaConsentState.Location - } - }; - return state; - } - function convertUserIdentities(sdkUserIdentities) { - if (!sdkUserIdentities || !sdkUserIdentities.length) { - return null; - } - var batchIdentities = {}; - for (var _i = 0, sdkUserIdentities_1 = sdkUserIdentities; _i < sdkUserIdentities_1.length; _i++) { - var identity = sdkUserIdentities_1[_i]; - switch (identity.Type) { - case Types.IdentityType.CustomerId: - batchIdentities.customer_id = identity.Identity; - break; - case Types.IdentityType.Email: - batchIdentities.email = identity.Identity; - break; - case Types.IdentityType.Facebook: - batchIdentities.facebook = identity.Identity; - break; - case Types.IdentityType.FacebookCustomAudienceId: - batchIdentities.facebook_custom_audience_id = identity.Identity; - break; - case Types.IdentityType.Google: - batchIdentities.google = identity.Identity; - break; - case Types.IdentityType.Microsoft: - batchIdentities.microsoft = identity.Identity; - break; - case Types.IdentityType.Other: - batchIdentities.other = identity.Identity; - break; - case Types.IdentityType.Other2: - batchIdentities.other_id_2 = identity.Identity; - break; - case Types.IdentityType.Other3: - batchIdentities.other_id_3 = identity.Identity; - break; - case Types.IdentityType.Other4: - batchIdentities.other_id_4 = identity.Identity; - break; - case Types.IdentityType.Other5: - batchIdentities.other_id_5 = identity.Identity; - break; - case Types.IdentityType.Other6: - batchIdentities.other_id_6 = identity.Identity; - break; - case Types.IdentityType.Other7: - batchIdentities.other_id_7 = identity.Identity; - break; - case Types.IdentityType.Other8: - batchIdentities.other_id_8 = identity.Identity; - break; - case Types.IdentityType.Other9: - batchIdentities.other_id_9 = identity.Identity; - break; - case Types.IdentityType.Other10: - batchIdentities.other_id_10 = identity.Identity; - break; - case Types.IdentityType.MobileNumber: - batchIdentities.mobile_number = identity.Identity; - break; - case Types.IdentityType.PhoneNumber2: - batchIdentities.phone_number_2 = identity.Identity; - break; - case Types.IdentityType.PhoneNumber3: - batchIdentities.phone_number_3 = identity.Identity; - break; - } - } - return batchIdentities; - } - function convertEvent(sdkEvent) { - if (!sdkEvent) { - return null; - } - switch (sdkEvent.EventDataType) { - case Types.MessageType.AppStateTransition: - return convertAST(sdkEvent); - case Types.MessageType.Commerce: - return convertCommerceEvent(sdkEvent); - case Types.MessageType.CrashReport: - return convertCrashReportEvent(sdkEvent); - case Types.MessageType.OptOut: - return convertOptOutEvent(sdkEvent); - case Types.MessageType.PageEvent: - // Note: Media Events are also sent as PageEvents/CustomEvents - return convertCustomEvent(sdkEvent); - case Types.MessageType.PageView: - return convertPageViewEvent(sdkEvent); - case Types.MessageType.Profile: - //deprecated and not supported by the web SDK - return null; - case Types.MessageType.SessionEnd: - return convertSessionEndEvent(sdkEvent); - case Types.MessageType.SessionStart: - return convertSessionStartEvent(sdkEvent); - case Types.MessageType.UserAttributeChange: - return convertUserAttributeChangeEvent(sdkEvent); - case Types.MessageType.UserIdentityChange: - return convertUserIdentityChangeEvent(sdkEvent); - } - return null; - } - function convertProductActionType(actionType) { - if (!actionType) { - return dist.ProductActionActionEnum.unknown; - } - switch (actionType) { - case SDKProductActionType.AddToCart: - return dist.ProductActionActionEnum.addToCart; - case SDKProductActionType.AddToWishlist: - return dist.ProductActionActionEnum.addToWishlist; - case SDKProductActionType.Checkout: - return dist.ProductActionActionEnum.checkout; - case SDKProductActionType.CheckoutOption: - return dist.ProductActionActionEnum.checkoutOption; - case SDKProductActionType.Click: - return dist.ProductActionActionEnum.click; - case SDKProductActionType.Purchase: - return dist.ProductActionActionEnum.purchase; - case SDKProductActionType.Refund: - return dist.ProductActionActionEnum.refund; - case SDKProductActionType.RemoveFromCart: - return dist.ProductActionActionEnum.removeFromCart; - case SDKProductActionType.RemoveFromWishlist: - return dist.ProductActionActionEnum.removeFromWishlist; - case SDKProductActionType.ViewDetail: - return dist.ProductActionActionEnum.viewDetail; - default: - return dist.ProductActionActionEnum.unknown; - } - } - function convertProductAction(sdkEvent) { - if (!sdkEvent.ProductAction) { - return null; - } - var productAction = { - action: convertProductActionType(sdkEvent.ProductAction.ProductActionType), - checkout_step: sdkEvent.ProductAction.CheckoutStep, - checkout_options: sdkEvent.ProductAction.CheckoutOptions, - transaction_id: sdkEvent.ProductAction.TransactionId, - affiliation: sdkEvent.ProductAction.Affiliation, - total_amount: sdkEvent.ProductAction.TotalAmount, - tax_amount: sdkEvent.ProductAction.TaxAmount, - shipping_amount: sdkEvent.ProductAction.ShippingAmount, - coupon_code: sdkEvent.ProductAction.CouponCode, - products: convertProducts(sdkEvent.ProductAction.ProductList) - }; - return productAction; - } - function convertProducts(sdkProducts) { - if (!sdkProducts || !sdkProducts.length) { - return null; - } - var products = []; - for (var _i = 0, sdkProducts_1 = sdkProducts; _i < sdkProducts_1.length; _i++) { - var sdkProduct = sdkProducts_1[_i]; - var product = { - id: sdkProduct.Sku, - name: sdkProduct.Name, - brand: sdkProduct.Brand, - category: sdkProduct.Category, - variant: sdkProduct.Variant, - total_product_amount: sdkProduct.TotalAmount, - position: sdkProduct.Position, - price: sdkProduct.Price, - quantity: sdkProduct.Quantity, - coupon_code: sdkProduct.CouponCode, - custom_attributes: sdkProduct.Attributes - }; - products.push(product); - } - return products; - } - function convertPromotionAction(sdkEvent) { - if (!sdkEvent.PromotionAction) { - return null; - } - var promotionAction = { - action: sdkEvent.PromotionAction.PromotionActionType, - promotions: convertPromotions(sdkEvent.PromotionAction.PromotionList) - }; - return promotionAction; - } - function convertPromotions(sdkPromotions) { - if (!sdkPromotions || !sdkPromotions.length) { - return null; - } - var promotions = []; - for (var _i = 0, sdkPromotions_1 = sdkPromotions; _i < sdkPromotions_1.length; _i++) { - var sdkPromotion = sdkPromotions_1[_i]; - var promotion = { - id: sdkPromotion.Id, - name: sdkPromotion.Name, - creative: sdkPromotion.Creative, - position: sdkPromotion.Position - }; - promotions.push(promotion); - } - return promotions; - } - function convertImpressions(sdkEvent) { - if (!sdkEvent.ProductImpressions) { - return null; - } - var impressions = []; - for (var _i = 0, _a = sdkEvent.ProductImpressions; _i < _a.length; _i++) { - var sdkImpression = _a[_i]; - var impression = { - product_impression_list: sdkImpression.ProductImpressionList, - products: convertProducts(sdkImpression.ProductList) - }; - impressions.push(impression); - } - return impressions; - } - function convertShoppingCart(sdkEvent) { - if (!sdkEvent.ShoppingCart || !sdkEvent.ShoppingCart.ProductList || !sdkEvent.ShoppingCart.ProductList.length) { - return null; - } - var shoppingCart = { - products: convertProducts(sdkEvent.ShoppingCart.ProductList) - }; - return shoppingCart; - } - function convertCommerceEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var commerceEventData = { - custom_flags: sdkEvent.CustomFlags, - product_action: convertProductAction(sdkEvent), - promotion_action: convertPromotionAction(sdkEvent), - product_impressions: convertImpressions(sdkEvent), - shopping_cart: convertShoppingCart(sdkEvent), - currency_code: sdkEvent.CurrencyCode - }; - commerceEventData = Object.assign(commerceEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.commerceEvent, - data: commerceEventData - }; - } - function convertCrashReportEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var crashReportEventData = { - message: sdkEvent.EventName - }; - crashReportEventData = Object.assign(crashReportEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.crashReport, - data: crashReportEventData - }; - } - function convertAST(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - // Determine the transition type based on IsBackgroundAST flag - var _a = dist.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum, - applicationBackground = _a.applicationBackground, - applicationInitialized = _a.applicationInitialized; - var transitionType = sdkEvent.IsBackgroundAST ? applicationBackground : applicationInitialized; - var astEventData = { - application_transition_type: transitionType, - is_first_run: sdkEvent.IsFirstRun, - is_upgrade: false, - launch_referral: sdkEvent.LaunchReferral - }; - astEventData = Object.assign(astEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.applicationStateTransition, - data: astEventData - }; - } - function convertSessionEndEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var sessionEndEventData = { - session_duration_ms: sdkEvent.SessionLength - //note: External Events DTO does not support the session mpids array as of this time. - //spanning_mpids: sdkEvent.SessionMpids - }; - - sessionEndEventData = Object.assign(sessionEndEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.sessionEnd, - data: sessionEndEventData - }; - } - function convertSessionStartEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var sessionStartEventData = {}; - sessionStartEventData = Object.assign(sessionStartEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.sessionStart, - data: sessionStartEventData - }; - } - function convertPageViewEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var screenViewEventData = { - custom_flags: sdkEvent.CustomFlags, - screen_name: sdkEvent.EventName - }; - screenViewEventData = Object.assign(screenViewEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.screenView, - data: screenViewEventData - }; - } - function convertOptOutEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var optOutEventData = { - is_opted_out: sdkEvent.OptOut - }; - optOutEventData = Object.assign(optOutEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.optOut, - data: optOutEventData - }; - } - function convertCustomEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var customEventData = { - custom_event_type: convertSdkEventType(sdkEvent.EventCategory), - custom_flags: sdkEvent.CustomFlags, - event_name: sdkEvent.EventName - }; - customEventData = Object.assign(customEventData, commonEventData); - return { - event_type: dist.EventTypeEnum.customEvent, - data: customEventData - }; - } - function convertSdkEventType(sdkEventType) { - switch (sdkEventType) { - case Types.EventType.Other: - return dist.CustomEventDataCustomEventTypeEnum.other; - case Types.EventType.Location: - return dist.CustomEventDataCustomEventTypeEnum.location; - case Types.EventType.Navigation: - return dist.CustomEventDataCustomEventTypeEnum.navigation; - case Types.EventType.Search: - return dist.CustomEventDataCustomEventTypeEnum.search; - case Types.EventType.Social: - return dist.CustomEventDataCustomEventTypeEnum.social; - case Types.EventType.Transaction: - return dist.CustomEventDataCustomEventTypeEnum.transaction; - case Types.EventType.UserContent: - return dist.CustomEventDataCustomEventTypeEnum.userContent; - case Types.EventType.UserPreference: - return dist.CustomEventDataCustomEventTypeEnum.userPreference; - case Types.EventType.Media: - return dist.CustomEventDataCustomEventTypeEnum.media; - case Types.CommerceEventType.ProductAddToCart: - return dist.CommerceEventDataCustomEventTypeEnum.addToCart; - case Types.CommerceEventType.ProductAddToWishlist: - return dist.CommerceEventDataCustomEventTypeEnum.addToWishlist; - case Types.CommerceEventType.ProductCheckout: - return dist.CommerceEventDataCustomEventTypeEnum.checkout; - case Types.CommerceEventType.ProductCheckoutOption: - return dist.CommerceEventDataCustomEventTypeEnum.checkoutOption; - case Types.CommerceEventType.ProductClick: - return dist.CommerceEventDataCustomEventTypeEnum.click; - case Types.CommerceEventType.ProductImpression: - return dist.CommerceEventDataCustomEventTypeEnum.impression; - case Types.CommerceEventType.ProductPurchase: - return dist.CommerceEventDataCustomEventTypeEnum.purchase; - case Types.CommerceEventType.ProductRefund: - return dist.CommerceEventDataCustomEventTypeEnum.refund; - case Types.CommerceEventType.ProductRemoveFromCart: - return dist.CommerceEventDataCustomEventTypeEnum.removeFromCart; - case Types.CommerceEventType.ProductRemoveFromWishlist: - return dist.CommerceEventDataCustomEventTypeEnum.removeFromWishlist; - case Types.CommerceEventType.ProductViewDetail: - return dist.CommerceEventDataCustomEventTypeEnum.viewDetail; - case Types.CommerceEventType.PromotionClick: - return dist.CommerceEventDataCustomEventTypeEnum.promotionClick; - case Types.CommerceEventType.PromotionView: - return dist.CommerceEventDataCustomEventTypeEnum.promotionView; - default: - return dist.CustomEventDataCustomEventTypeEnum.unknown; - } - } - function convertBaseEventData(sdkEvent) { - var commonEventData = { - timestamp_unixtime_ms: sdkEvent.Timestamp, - session_uuid: sdkEvent.SessionId, - session_start_unixtime_ms: sdkEvent.SessionStartDate, - custom_attributes: sdkEvent.EventAttributes, - location: convertSDKLocation(sdkEvent.Location), - source_message_id: sdkEvent.SourceMessageId, - active_time_on_site_ms: sdkEvent.ActiveTimeOnSite - }; - return commonEventData; - } - function convertSDKLocation(sdkEventLocation) { - if (sdkEventLocation && Object.keys(sdkEventLocation).length) { - return { - latitude: sdkEventLocation.lat, - longitude: sdkEventLocation.lng - }; - } - return null; - } - function convertUserAttributeChangeEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var userAttributeChangeEvent = { - user_attribute_name: sdkEvent.UserAttributeChanges.UserAttributeName, - "new": sdkEvent.UserAttributeChanges.New, - old: sdkEvent.UserAttributeChanges.Old, - deleted: sdkEvent.UserAttributeChanges.Deleted, - is_new_attribute: sdkEvent.UserAttributeChanges.IsNewAttribute - }; - userAttributeChangeEvent = __assign(__assign({}, userAttributeChangeEvent), commonEventData); - return { - event_type: dist.EventTypeEnum.userAttributeChange, - data: userAttributeChangeEvent - }; - } - function convertUserIdentityChangeEvent(sdkEvent) { - var commonEventData = convertBaseEventData(sdkEvent); - var userIdentityChangeEvent = { - "new": { - identity_type: convertUserIdentityTypeToServerIdentityType(sdkEvent.UserIdentityChanges.New.IdentityType), - identity: sdkEvent.UserIdentityChanges.New.Identity || null, - timestamp_unixtime_ms: sdkEvent.Timestamp, - created_this_batch: sdkEvent.UserIdentityChanges.New.CreatedThisBatch - }, - old: { - identity_type: convertUserIdentityTypeToServerIdentityType(sdkEvent.UserIdentityChanges.Old.IdentityType), - identity: sdkEvent.UserIdentityChanges.Old.Identity || null, - timestamp_unixtime_ms: sdkEvent.Timestamp, - created_this_batch: sdkEvent.UserIdentityChanges.Old.CreatedThisBatch - } - }; - userIdentityChangeEvent = Object.assign(userIdentityChangeEvent, commonEventData); - return { - event_type: dist.EventTypeEnum.userIdentityChange, - data: userIdentityChangeEvent - }; - } - function convertUserIdentityTypeToServerIdentityType(identityType) { - switch (identityType) { - case SDKIdentityTypeEnum.other: - return dist.IdentityTypeEnum.other; - case SDKIdentityTypeEnum.customerId: - return dist.IdentityTypeEnum.customerId; - case SDKIdentityTypeEnum.facebook: - return dist.IdentityTypeEnum.facebook; - case SDKIdentityTypeEnum.twitter: - return dist.IdentityTypeEnum.twitter; - case SDKIdentityTypeEnum.google: - return dist.IdentityTypeEnum.google; - case SDKIdentityTypeEnum.microsoft: - return dist.IdentityTypeEnum.microsoft; - case SDKIdentityTypeEnum.yahoo: - return dist.IdentityTypeEnum.yahoo; - case SDKIdentityTypeEnum.email: - return dist.IdentityTypeEnum.email; - case SDKIdentityTypeEnum.alias: - return dist.IdentityTypeEnum.alias; - case SDKIdentityTypeEnum.facebookCustomAudienceId: - return dist.IdentityTypeEnum.facebookCustomAudienceId; - case SDKIdentityTypeEnum.otherId2: - return dist.IdentityTypeEnum.otherId2; - case SDKIdentityTypeEnum.otherId3: - return dist.IdentityTypeEnum.otherId3; - case SDKIdentityTypeEnum.otherId4: - return dist.IdentityTypeEnum.otherId4; - case SDKIdentityTypeEnum.otherId5: - return dist.IdentityTypeEnum.otherId5; - case SDKIdentityTypeEnum.otherId6: - return dist.IdentityTypeEnum.otherId6; - case SDKIdentityTypeEnum.otherId7: - return dist.IdentityTypeEnum.otherId7; - case SDKIdentityTypeEnum.otherId8: - return dist.IdentityTypeEnum.otherId8; - case SDKIdentityTypeEnum.otherId9: - return dist.IdentityTypeEnum.otherId9; - case SDKIdentityTypeEnum.otherId10: - return dist.IdentityTypeEnum.otherId10; - case SDKIdentityTypeEnum.mobileNumber: - return dist.IdentityTypeEnum.mobileNumber; - case SDKIdentityTypeEnum.phoneNumber2: - return dist.IdentityTypeEnum.phoneNumber2; - case SDKIdentityTypeEnum.phoneNumber3: - return dist.IdentityTypeEnum.phoneNumber3; - } - } - - var BaseVault = /** @class */function () { - /** - * - * @param {string} storageKey the local storage key string - * @param {Storage} Web API Storage object that is being used - * @param {IVaultOptions} options A Dictionary of IVaultOptions - */ - function BaseVault(storageKey, storageObject, options) { - this._storageKey = storageKey; - this.storageObject = storageObject; - // Add a fake logger in case one is not provided or needed - this.logger = (options === null || options === void 0 ? void 0 : options.logger) || { - verbose: function verbose() {}, - warning: function warning() {}, - error: function error() {} - }; - this.contents = this.retrieve(); - } - /** - * Stores a StorableItem to Storage - * @method store - * @param item {StorableItem} - */ - BaseVault.prototype.store = function (item) { - var stringifiedItem; - this.contents = item; - if (isNumber(item) || !isEmpty(item)) { - stringifiedItem = JSON.stringify(item); - } else { - stringifiedItem = ''; - } - try { - this.storageObject.setItem(this._storageKey, stringifiedItem); - this.logger.verbose("Saving item to Storage: ".concat(stringifiedItem)); - } catch (error) { - this.logger.error("Cannot Save items to Storage: ".concat(stringifiedItem)); - this.logger.error(error); - } - }; - /** - * Retrieve StorableItem from Storage - * @method retrieve - * @returns {StorableItem} - */ - BaseVault.prototype.retrieve = function () { - // TODO: Handle cases where Local Storage is unavailable - // https://go.mparticle.com/work/SQDSDKS-5022 - var item = this.storageObject.getItem(this._storageKey); - this.contents = item ? JSON.parse(item) : null; - this.logger.verbose("Retrieving item from Storage: ".concat(item)); - return this.contents; - }; - /** - * Removes all persisted data from Storage based on this vault's `key` - * Will remove storage key from Storage as well - * @method purge - */ - BaseVault.prototype.purge = function () { - this.logger.verbose('Purging Storage'); - this.contents = null; - this.storageObject.removeItem(this._storageKey); - }; - return BaseVault; - }(); - var LocalStorageVault = /** @class */function (_super) { - __extends(LocalStorageVault, _super); - function LocalStorageVault(storageKey, options) { - return _super.call(this, storageKey, window.localStorage, options) || this; - } - return LocalStorageVault; - }(BaseVault); - var SessionStorageVault = /** @class */function (_super) { - __extends(SessionStorageVault, _super); - function SessionStorageVault(storageKey, options) { - return _super.call(this, storageKey, window.sessionStorage, options) || this; - } - return SessionStorageVault; - }(BaseVault); - // DisabledVault is used when persistence is disabled by privacy flags. - var DisabledVault = /** @class */function (_super) { - __extends(DisabledVault, _super); - function DisabledVault(storageKey, options) { - var _this = _super.call(this, storageKey, window.localStorage, options) || this; - _this.contents = null; - _this.storageObject.removeItem(_this._storageKey); - return _this; - } - DisabledVault.prototype.store = function (_item) { - this.contents = null; - }; - DisabledVault.prototype.retrieve = function () { - return this.contents; - }; - DisabledVault.prototype.purge = function () { - this.contents = null; - }; - return DisabledVault; - }(BaseVault); - - var AsyncUploader = /** @class */function () { - function AsyncUploader(url) { - this.url = url; - } - return AsyncUploader; - }(); - var FetchUploader = /** @class */function (_super) { - __extends(FetchUploader, _super); - function FetchUploader() { - return _super !== null && _super.apply(this, arguments) || this; - } - FetchUploader.prototype.upload = function (fetchPayload, _url) { - return __awaiter(this, void 0, void 0, function () { - var url; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - url = _url || this.url; - return [4 /*yield*/, fetch(url, fetchPayload)]; - case 1: - return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return FetchUploader; - }(AsyncUploader); - var XHRUploader = /** @class */function (_super) { - __extends(XHRUploader, _super); - function XHRUploader() { - return _super !== null && _super.apply(this, arguments) || this; - } - XHRUploader.prototype.upload = function (fetchPayload) { - return __awaiter(this, void 0, void 0, function () { - var response; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, this.makeRequest(this.url, fetchPayload.body, fetchPayload.method, fetchPayload.headers)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response]; - } - }); - }); - }; - // XHR Ready States - // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState - // 0 UNSENT open() has not been called yet. - // 1 OPENED send() has been called. - // 2 HEADERS_RECEIVED send() has been called, and headers and status are available. - // 3 LOADING Downloading; responseText holds partial data. - // 4 DONE The operation is complete. - // https://go.mparticle.com/work/SQDSDKS-6736 - XHRUploader.prototype.makeRequest = function (url, data, method, headers) { - if (method === void 0) { - method = 'post'; - } - if (headers === void 0) { - headers = {}; - } - return __awaiter(this, void 0, void 0, function () { - var xhr; - return __generator(this, function (_a) { - xhr = new XMLHttpRequest(); - return [2 /*return*/, new Promise(function (resolve, reject) { - xhr.onreadystatechange = function () { - if (xhr.readyState !== 4) return; - // Process the response - // We resolve all xhr responses whose ready state is 4 regardless of HTTP codes that may be errors (400+) - // because these are valid HTTP responses. - resolve(xhr); - }; - // Reject a promise only when there is an xhr error - xhr.onerror = function () { - reject(xhr); - }; - xhr.open(method, url); - for (var key in headers) { - if (headers.hasOwnProperty(key)) { - xhr.setRequestHeader(key, headers[key]); - } - } - xhr.send(data); - })]; - }); - }); - }; - return XHRUploader; - }(AsyncUploader); - - function hasMPIDAndUserLoginChanged(previousUser, newUser) { - return !previousUser || newUser.getMPID() !== previousUser.getMPID() || previousUser.isLoggedIn() !== newUser.isLoggedIn(); - } - // https://go.mparticle.com/work/SQDSDKS-6504 - function hasMPIDChanged(prevUser, identityApiResult) { - return !prevUser || prevUser.getMPID() && identityApiResult.mpid && identityApiResult.mpid !== prevUser.getMPID(); - } - // https://go.mparticle.com/work/SQDSDKS-7136 - function appendUserInfo(user, event) { - if (!event) { - return; - } - if (!user) { - event.MPID = null; - event.ConsentState = null; - event.UserAttributes = null; - event.UserIdentities = null; - return; - } - if (event.MPID && event.MPID === user.getMPID()) { - return; - } - event.MPID = user.getMPID(); - event.ConsentState = user.getConsentState(); - event.UserAttributes = user.getAllUserAttributes(); - var userIdentities = user.getUserIdentities().userIdentities; - var dtoUserIdentities = {}; - for (var identityKey in userIdentities) { - var identityType = Types.IdentityType.getIdentityType(identityKey); - if (identityType !== false) { - dtoUserIdentities[identityType] = userIdentities[identityKey]; - } - } - var validUserIdentities = []; - if (isObject(dtoUserIdentities)) { - if (Object.keys(dtoUserIdentities).length) { - for (var key in dtoUserIdentities) { - var userIdentity = {}; - userIdentity.Identity = dtoUserIdentities[key]; - userIdentity.Type = parseNumber(key); - validUserIdentities.push(userIdentity); - } - } - } - event.UserIdentities = validUserIdentities; - } - - /** - * BatchUploader contains all the logic to store/retrieve events and batches - * to/from persistence, and upload batches to mParticle. - * It queues events as they come in, storing them in persistence, then at set - * intervals turns them into batches and transfers between event and batch - * persistence. - * It then attempts to upload them to mParticle, purging batch persistence if - * the upload is successful - * - * These uploads happen on an interval basis using window.fetch or XHR - * requests, depending on what is available in the browser. - * - * Uploads can also be triggered on browser visibility/focus changes via an - * event listener, which then uploads to mPartice via the browser's Beacon API. - */ - var BatchUploader = /** @class */function () { - /** - * Creates an instance of a BatchUploader - * @param {IMParticleWebSDKInstance} mpInstance - the mParticle SDK instance - * @param {number} uploadInterval - the desired upload interval in milliseconds - */ - function BatchUploader(mpInstance, uploadInterval) { - var _a; - var _b; - this.offlineStorageEnabled = false; - this.lastASTEventTime = 0; - this.AST_DEBOUNCE_MS = 1000; // 1 second debounce - this.mpInstance = mpInstance; - this.uploadIntervalMillis = uploadInterval; - this.batchingEnabled = uploadInterval >= BatchUploader.MINIMUM_INTERVAL_MILLIS; - if (this.uploadIntervalMillis < BatchUploader.MINIMUM_INTERVAL_MILLIS) { - this.uploadIntervalMillis = BatchUploader.MINIMUM_INTERVAL_MILLIS; - } - // Events will be queued during `queueEvents` method - this.eventsQueuedForProcessing = []; - // Batch queue should start empty and will be populated during - // `prepareAndUpload` method, either via Local Storage or after - // new batches are created. - this.batchesQueuedForProcessing = []; - // Cache Offline Storage Availability boolean - // so that we don't have to check it every time - this.offlineStorageEnabled = this.isOfflineStorageAvailable(); - // When noFunctional is true, prevent events/batches storage - var noFunctional = (_b = mpInstance._CookieConsentManager) === null || _b === void 0 ? void 0 : _b.getNoFunctional(); - if (this.offlineStorageEnabled && !noFunctional) { - this.eventVault = new SessionStorageVault("".concat(mpInstance._Store.storageName, "-events"), { - logger: mpInstance.Logger - }); - this.batchVault = new LocalStorageVault("".concat(mpInstance._Store.storageName, "-batches"), { - logger: mpInstance.Logger - }); - // Load Events from Session Storage in case we have any in storage - (_a = this.eventsQueuedForProcessing).push.apply(_a, this.eventVault.retrieve()); - } - var _c = this.mpInstance._Store, - SDKConfig = _c.SDKConfig, - devToken = _c.devToken; - var baseUrl = this.mpInstance._Helpers.createServiceUrl(SDKConfig.v3SecureServiceUrl, devToken); - this.uploadUrl = "".concat(baseUrl, "/events"); - this.uploader = window.fetch ? new FetchUploader(this.uploadUrl) : new XHRUploader(this.uploadUrl); - this.triggerUploadInterval(true, false); - this.addEventListeners(); - } - BatchUploader.prototype.isOfflineStorageAvailable = function () { - var _a = this.mpInstance, - getFeatureFlag = _a._Helpers.getFeatureFlag, - deviceId = _a._Store.deviceId; - // https://go.mparticle.com/work/SQDSDKS-6317 - var offlineStorageFeatureFlagValue = getFeatureFlag(Constants.FeatureFlags.OfflineStorage); - var offlineStoragePercentage = parseInt(offlineStorageFeatureFlagValue, 10); - var rampNumber = getRampNumber(deviceId); - // TODO: Handle cases where Local Storage is unavailable - // Potentially shared between Vault and Persistence as well - // https://go.mparticle.com/work/SQDSDKS-5022 - return offlineStoragePercentage >= rampNumber; - }; - // debounce AST just in case multiple events are fired in a short period of time due to browser differences - BatchUploader.prototype.shouldDebounceAndUpdateLastASTTime = function () { - var now = Date.now(); - if (now - this.lastASTEventTime < this.AST_DEBOUNCE_MS) { - return true; - } - this.lastASTEventTime = now; - return false; - }; - // https://go.mparticle.com/work/SQDSDKS-7133 - BatchUploader.prototype.createBackgroundASTEvent = function () { - var now = Date.now(); - var _a = this.mpInstance, - _Store = _a._Store, - Identity = _a.Identity, - _timeOnSiteTimer = _a._timeOnSiteTimer, - _Helpers = _a._Helpers; - var sessionId = _Store.sessionId, - deviceId = _Store.deviceId, - sessionStartDate = _Store.sessionStartDate, - SDKConfig = _Store.SDKConfig; - var generateUniqueId = _Helpers.generateUniqueId, - getFeatureFlag = _Helpers.getFeatureFlag; - var getCurrentUser = Identity.getCurrentUser; - var event = { - AppName: SDKConfig.appName, - AppVersion: SDKConfig.appVersion, - Package: SDKConfig["package"], - EventDataType: MessageType$1.AppStateTransition, - Timestamp: now, - SessionId: sessionId, - DeviceId: deviceId, - IsFirstRun: false, - SourceMessageId: generateUniqueId(), - SDKVersion: Constants.sdkVersion, - CustomFlags: {}, - EventAttributes: {}, - SessionStartDate: (sessionStartDate === null || sessionStartDate === void 0 ? void 0 : sessionStartDate.getTime()) || now, - Debug: SDKConfig.isDevelopmentMode, - ActiveTimeOnSite: (_timeOnSiteTimer === null || _timeOnSiteTimer === void 0 ? void 0 : _timeOnSiteTimer.getTimeInForeground()) || 0, - IsBackgroundAST: true - }; - var customFlags = __assign({}, event.CustomFlags); - var integrationAttributes = _Store.integrationAttributes; - var integrationSpecificIds = getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds); - var integrationSpecificIdsV2 = getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || ''; - var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; - // https://go.mparticle.com/work/SQDSDKS-5053 - if (isIntegrationCaptureEnabled) { - // Attempt to recapture click IDs in case a third party integration - // has added or updated new click IDs since the last event was sent. - this.mpInstance._IntegrationCapture.capture(); - var transformedClickIDs = this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags(); - customFlags = __assign(__assign({}, transformedClickIDs), customFlags); - var transformedIntegrationAttributes = this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes(); - integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes); - } - event.CustomFlags = customFlags; - event.IntegrationAttributes = integrationAttributes; - appendUserInfo(getCurrentUser(), event); - return event; - }; - // Adds listeners to be used trigger Navigator.sendBeacon if the browser - // loses focus for any reason, such as closing browser tab or minimizing window - BatchUploader.prototype.addEventListeners = function () { - var _this_1 = this; - var _this = this; - var handleExit = function handleExit() { - // Check for debounce before creating and queueing event - var getFeatureFlag = _this_1.mpInstance._Helpers.getFeatureFlag; - var AstBackgroundEvents = Constants.FeatureFlags.AstBackgroundEvents; - if (getFeatureFlag(AstBackgroundEvents)) { - if (_this.shouldDebounceAndUpdateLastASTTime()) { - return; - } - // Add application state transition event to queue - var event_1 = _this.createBackgroundASTEvent(); - _this.queueEvent(event_1); - } - // Then trigger the upload with beacon - _this.prepareAndUpload(false, _this.isBeaconAvailable()); - }; - // visibility change is a document property, not window - document.addEventListener('visibilitychange', function () { - if (document.visibilityState === 'hidden') { - handleExit(); - } - }); - window.addEventListener('beforeunload', handleExit); - window.addEventListener('pagehide', handleExit); - }; - BatchUploader.prototype.isBeaconAvailable = function () { - if (navigator.sendBeacon) { - return true; - } - return false; - }; - // Triggers a setTimeout for prepareAndUpload - BatchUploader.prototype.triggerUploadInterval = function (triggerFuture, useBeacon) { - var _this_1 = this; - if (triggerFuture === void 0) { - triggerFuture = false; - } - if (useBeacon === void 0) { - useBeacon = false; - } - setTimeout(function () { - _this_1.prepareAndUpload(triggerFuture, useBeacon); - }, this.uploadIntervalMillis); - }; - /** - * This method will queue a single Event which will eventually be processed into a Batch - * @param event event that should be queued - */ - BatchUploader.prototype.queueEvent = function (event) { - if (isEmpty(event)) { - return; - } - var Logger = this.mpInstance.Logger; - this.eventsQueuedForProcessing.push(event); - if (this.offlineStorageEnabled && this.eventVault) { - this.eventVault.store(this.eventsQueuedForProcessing); - } - Logger.verbose("Queuing event: ".concat(JSON.stringify(event))); - Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length)); - if (this.shouldTriggerImmediateUpload(event.EventDataType)) { - this.prepareAndUpload(false, false); - } - }; - // https://go.mparticle.com/work/SQDSDKS-3720 - BatchUploader.prototype.shouldTriggerImmediateUpload = function (eventDataType) { - var priorityEvents = [MessageType$1.Commerce, MessageType$1.UserIdentityChange]; - return !this.batchingEnabled || priorityEvents.includes(eventDataType); - }; - /** - * This implements crucial logic to: - * - bucket pending events by MPID, and then by Session, and upload individual batches for each bucket. - * - * In the future this should enforce other requirements such as maximum batch size. - * - * @param sdkEvents current pending events - * @param defaultUser the user to reference for events that are missing data - */ - BatchUploader.createNewBatches = function (sdkEvents, defaultUser, mpInstance) { - if (!defaultUser || !sdkEvents || !sdkEvents.length) { - return null; - } - //bucket by MPID, and then by session, ordered by timestamp - var newUploads = []; - var eventsByUser = new Map(); - for (var _i = 0, sdkEvents_1 = sdkEvents; _i < sdkEvents_1.length; _i++) { - var sdkEvent = sdkEvents_1[_i]; - //on initial startup, there may be events logged without an mpid. - if (!sdkEvent.MPID) { - var mpid = defaultUser.getMPID(); - sdkEvent.MPID = mpid; - } - var events = eventsByUser.get(sdkEvent.MPID); - if (!events) { - events = []; - } - events.push(sdkEvent); - eventsByUser.set(sdkEvent.MPID, events); - } - for (var _a = 0, _b = Array.from(eventsByUser.entries()); _a < _b.length; _a++) { - var entry = _b[_a]; - var mpid = entry[0]; - var userEvents = entry[1]; - var eventsBySession = new Map(); - for (var _c = 0, userEvents_1 = userEvents; _c < userEvents_1.length; _c++) { - var sdkEvent = userEvents_1[_c]; - var events = eventsBySession.get(sdkEvent.SessionId); - if (!events) { - events = []; - } - events.push(sdkEvent); - eventsBySession.set(sdkEvent.SessionId, events); - } - for (var _d = 0, _e = Array.from(eventsBySession.entries()); _d < _e.length; _d++) { - var entry_1 = _e[_d]; - var uploadBatchObject = convertEvents(mpid, entry_1[1], mpInstance); - var onCreateBatchCallback = mpInstance._Store.SDKConfig.onCreateBatch; - if (onCreateBatchCallback) { - uploadBatchObject = onCreateBatchCallback(uploadBatchObject); - if (uploadBatchObject) { - uploadBatchObject.modified = true; - } else { - mpInstance.Logger.warning('Skiping batch upload because no batch was returned from onCreateBatch callback'); - } - } - if (uploadBatchObject) { - newUploads.push(uploadBatchObject); - } - } - } - return newUploads; - }; - /** - * This is the main loop function: - * - take all pending events and turn them into batches - * - attempt to upload each batch - * - * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false - * @param useBeacon whether to use the beacon API - used when the page is being unloaded - */ - BatchUploader.prototype.prepareAndUpload = function (triggerFuture, useBeacon) { - if (triggerFuture === void 0) { - triggerFuture = false; - } - if (useBeacon === void 0) { - useBeacon = false; - } - return __awaiter(this, void 0, void 0, function () { - var currentUser, currentEvents, newBatches, batchesToUpload, batchesThatDidNotUpload; - var _a, _b, _c; - return __generator(this, function (_d) { - switch (_d.label) { - case 0: - currentUser = this.mpInstance.Identity.getCurrentUser(); - currentEvents = this.eventsQueuedForProcessing; - this.eventsQueuedForProcessing = []; - if (this.offlineStorageEnabled && this.eventVault) { - this.eventVault.store([]); - } - newBatches = []; - if (!isEmpty(currentEvents)) { - newBatches = BatchUploader.createNewBatches(currentEvents, currentUser, this.mpInstance); - } - // Top Load any older Batches from Offline Storage so they go out first - if (this.offlineStorageEnabled && this.batchVault) { - (_a = this.batchesQueuedForProcessing).unshift.apply(_a, this.batchVault.retrieve()); - // Remove batches from local storage before transmit to - // prevent duplication - this.batchVault.purge(); - } - if (!isEmpty(newBatches)) { - (_b = this.batchesQueuedForProcessing).push.apply(_b, newBatches); - } - batchesToUpload = this.batchesQueuedForProcessing; - this.batchesQueuedForProcessing = []; - return [4 /*yield*/, this.uploadBatches(this.mpInstance.Logger, batchesToUpload, useBeacon)]; - case 1: - batchesThatDidNotUpload = _d.sent(); - // Batches that do not successfully upload are added back to the process queue - // in the order they were created so that we can attempt re-transmission in - // the same sequence. This is to prevent any potential data corruption. - if (!isEmpty(batchesThatDidNotUpload)) { - // TODO: https://go.mparticle.com/work/SQDSDKS-5165 - (_c = this.batchesQueuedForProcessing).unshift.apply(_c, batchesThatDidNotUpload); - } - // Update Offline Storage with current state of batch queue - if (!useBeacon && this.offlineStorageEnabled && this.batchVault) { - // Note: since beacon is "Fire and forget" it will empty `batchesThatDidNotUplod` - // regardless of whether the batches were successfully uploaded or not. We should - // therefore NOT overwrite Offline Storage when beacon returns, so that we can retry - // uploading saved batches at a later time. Batches should only be removed from - // Local Storage once we can confirm they are successfully uploaded. - this.batchVault.store(this.batchesQueuedForProcessing); - // Clear batch queue since everything should be in Offline Storage - this.batchesQueuedForProcessing = []; - } - if (triggerFuture) { - this.triggerUploadInterval(triggerFuture, false); - } - return [2 /*return*/]; - } - }); - }); - }; - // TODO: Refactor to use logger as a class method - // https://go.mparticle.com/work/SQDSDKS-5167 - BatchUploader.prototype.uploadBatches = function (logger, batches, useBeacon) { - return __awaiter(this, void 0, void 0, function () { - var uploads, i, fetchPayload, blob, response, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - uploads = batches.filter(function (batch) { - return !isEmpty(batch.events); - }); - if (isEmpty(uploads)) { - return [2 /*return*/, null]; - } - logger.verbose("Uploading batches: ".concat(JSON.stringify(uploads))); - logger.verbose("Batch count: ".concat(uploads.length)); - i = 0; - _a.label = 1; - case 1: - if (!(i < uploads.length)) return [3 /*break*/, 6]; - fetchPayload = { - method: 'POST', - headers: { - Accept: BatchUploader.CONTENT_TYPE, - 'Content-Type': 'text/plain;charset=UTF-8' - }, - body: JSON.stringify(uploads[i]) - }; - if (!(useBeacon && this.isBeaconAvailable())) return [3 /*break*/, 2]; - blob = new Blob([fetchPayload.body], { - type: 'text/plain;charset=UTF-8' - }); - navigator.sendBeacon(this.uploadUrl, blob); - return [3 /*break*/, 5]; - case 2: - _a.trys.push([2, 4,, 5]); - return [4 /*yield*/, this.uploader.upload(fetchPayload)]; - case 3: - response = _a.sent(); - if (response.status >= 200 && response.status < 300) { - logger.verbose("Upload success for request ID: ".concat(uploads[i].source_request_id)); - } else if (response.status >= 500 || response.status === 429) { - logger.error("HTTP error status ".concat(response.status, " received")); - // Server error, add back current batches and try again later - return [2 /*return*/, uploads.slice(i, uploads.length)]; - } else if (response.status >= 401) { - logger.error("HTTP error status ".concat(response.status, " while uploading - please verify your API key.")); - //if we're getting a 401, assume we'll keep getting a 401 and clear the uploads. - return [2 /*return*/, null]; - } else { - // In case there is an HTTP error we did not anticipate. - console.error("HTTP error status ".concat(response.status, " while uploading events."), response); - throw new Error("Uncaught HTTP Error ".concat(response.status, ". Batch upload will be re-attempted.")); - } - return [3 /*break*/, 5]; - case 4: - e_1 = _a.sent(); - logger.error("Error sending event to mParticle servers. ".concat(e_1)); - return [2 /*return*/, uploads.slice(i, uploads.length)]; - case 5: - i++; - return [3 /*break*/, 1]; - case 6: - return [2 /*return*/, null]; - } - }); - }); - }; - // We upload JSON, but this content type is required to avoid a CORS preflight request - BatchUploader.CONTENT_TYPE = 'text/plain;charset=UTF-8'; - BatchUploader.MINIMUM_INTERVAL_MILLIS = 500; - return BatchUploader; - }(); - - var _a = Constants.IdentityMethods, - Identify$2 = _a.Identify, - Modify$4 = _a.Modify, - Login$2 = _a.Login, - Logout$2 = _a.Logout; - var CACHE_HEADER = 'x-mp-max-age'; - var cacheOrClearIdCache = function cacheOrClearIdCache(method, knownIdentities, idCache, identityResponse, parsingCachedResponse) { - // when parsing a response that has already been cached, simply return instead of attempting another cache - if (parsingCachedResponse) { - return; - } - // default the expire timestamp to one day in milliseconds unless a header comes back - var expireTimestamp = getExpireTimestamp(identityResponse === null || identityResponse === void 0 ? void 0 : identityResponse.cacheMaxAge); - switch (method) { - case Login$2: - case Identify$2: - cacheIdentityRequest(method, knownIdentities, expireTimestamp, idCache, identityResponse); - break; - case Modify$4: - case Logout$2: - idCache.purge(); - break; - } - }; - var cacheIdentityRequest = function cacheIdentityRequest(method, identities, expireTimestamp, idCache, identityResponse) { - var responseText = identityResponse.responseText, - status = identityResponse.status; - var cache = idCache.retrieve() || {}; - var cacheKey = concatenateIdentities(method, identities); - var hashedKey = generateHash(cacheKey); - var mpid = responseText.mpid, - is_logged_in = responseText.is_logged_in; - var cachedResponseBody = { - mpid: mpid, - is_logged_in: is_logged_in - }; - cache[hashedKey] = { - responseText: JSON.stringify(cachedResponseBody), - status: status, - expireTimestamp: expireTimestamp - }; - idCache.store(cache); - }; - // We need to ensure that identities are concatenated in a deterministic way, so - // we sort the identities based on their enum. - // we create an array, set the user identity at the index of the user identity type - var concatenateIdentities = function concatenateIdentities(method, userIdentities) { - var DEVICE_APPLICATION_STAMP = 'device_application_stamp'; - // set DAS first since it is not an official identity type - var cacheKey = "".concat(method, ":").concat(DEVICE_APPLICATION_STAMP, "=").concat(userIdentities.device_application_stamp, ";"); - var idLength = Object.keys(userIdentities).length; - var concatenatedIdentities = ''; - if (idLength) { - var userIDArray = new Array(); - // create an array where each index is equal to the user identity type - for (var key in userIdentities) { - if (key === DEVICE_APPLICATION_STAMP) { - continue; - } else { - userIDArray[Types.IdentityType.getIdentityType(key)] = userIdentities[key]; - } - } - concatenatedIdentities = userIDArray.reduce(function (prevValue, currentValue, index) { - var idName = Types.IdentityType.getIdentityName(index); - return "".concat(prevValue).concat(idName, "=").concat(currentValue, ";"); - }, cacheKey); - } - return concatenatedIdentities; - }; - var hasValidCachedIdentity = function hasValidCachedIdentity(method, proposedUserIdentities, idCache) { - // There is an edge case where multiple identity calls are taking place - // before identify fires, so there may not be a cache. See what happens when - // the ? in idCache is removed to the following test - // "queued events contain login mpid instead of identify mpid when calling - // login immediately after mParticle initializes" - var cache = idCache === null || idCache === void 0 ? void 0 : idCache.retrieve(); - // if there is no cache, then there is no valid cached identity - if (!cache) { - return false; - } - var cacheKey = concatenateIdentities(method, proposedUserIdentities); - var hashedKey = generateHash(cacheKey); - // if cache doesn't have the cacheKey, there is no valid cached identity - if (!cache.hasOwnProperty(hashedKey)) { - return false; - } - // If there is a valid cache key, compare the expireTimestamp to the current time. - // If the current time is greater than the expireTimestamp, it is not a valid - // cached identity. - var expireTimestamp = cache[hashedKey].expireTimestamp; - if (expireTimestamp < new Date().getTime()) { - return false; - } else { - return true; - } - }; - var getCachedIdentity = function getCachedIdentity(method, proposedUserIdentities, idCache) { - var cacheKey = concatenateIdentities(method, proposedUserIdentities); - var hashedKey = generateHash(cacheKey); - var cache = idCache.retrieve(); - var cachedIdentity = cache ? cache[hashedKey] : null; - return { - responseText: parseIdentityResponse(cachedIdentity.responseText), - expireTimestamp: cachedIdentity.expireTimestamp, - status: cachedIdentity.status - }; - }; - // https://go.mparticle.com/work/SQDSDKS-6079 - var createKnownIdentities = function createKnownIdentities(identityApiData, deviceId) { - var identitiesResult = {}; - if (isObject(identityApiData === null || identityApiData === void 0 ? void 0 : identityApiData.userIdentities)) { - for (var identity in identityApiData.userIdentities) { - identitiesResult[identity] = identityApiData.userIdentities[identity]; - } - } - identitiesResult.device_application_stamp = deviceId; - return identitiesResult; - }; - var removeExpiredIdentityCacheDates = function removeExpiredIdentityCacheDates(idCache) { - var cache = idCache.retrieve() || {}; - var currentTime = new Date().getTime(); - // Iterate over the cache and remove any key/value pairs that are expired - for (var key in cache) { - if (cache[key].expireTimestamp < currentTime) { - delete cache[key]; - } - } - idCache.store(cache); - }; - var tryCacheIdentity = function tryCacheIdentity(knownIdentities, idCache, parseIdentityResponse, mpid, callback, identityApiData, identityMethod) { - // https://go.mparticle.com/work/SQDSDKS-6095 - var shouldReturnCachedIdentity = hasValidCachedIdentity(identityMethod, knownIdentities, idCache); - // If Identity is cached, then immediately parse the identity response - if (shouldReturnCachedIdentity) { - var cachedIdentity = getCachedIdentity(identityMethod, knownIdentities, idCache); - parseIdentityResponse(cachedIdentity, mpid, callback, identityApiData, identityMethod, knownIdentities, true); - return true; - } - return false; - }; - var getExpireTimestamp = function getExpireTimestamp(maxAge) { - if (maxAge === void 0) { - maxAge = ONE_DAY_IN_SECONDS; - } - return new Date().getTime() + maxAge * MILLIS_IN_ONE_SEC; - }; - var parseIdentityResponse = function parseIdentityResponse(responseText) { - return responseText ? JSON.parse(responseText) : {}; - }; - var hasIdentityRequestChanged = function hasIdentityRequestChanged(currentUser, newIdentityRequest) { - if (!currentUser || !(newIdentityRequest === null || newIdentityRequest === void 0 ? void 0 : newIdentityRequest.userIdentities)) { - return false; - } - var currentUserIdentities = currentUser.getUserIdentities().userIdentities; - var newIdentities = newIdentityRequest.userIdentities; - return JSON.stringify(currentUserIdentities) !== JSON.stringify(newIdentities); - }; - /** - * Checks if deviceId or other user identifiers (like email) were explicitly provided - * by the partner via config.deviceId or config.identifyRequest.userIdentities. - * When noFunctional is true, then cookies are blocked, so the partner must explicitly - * pass deviceId or other identifiers to prevent new users from being created on each page load. - * - * @param store - The SDK store (provides SDKConfig.deviceId and SDKConfig.identifyRequest.userIdentities) - * @returns true if deviceId or other identifiers were explicitly provided in config, false otherwise - */ - var hasExplicitIdentifier = function hasExplicitIdentifier(store) { - var _a, _b, _c; - var userIdentities = (_b = (_a = store === null || store === void 0 ? void 0 : store.SDKConfig) === null || _a === void 0 ? void 0 : _a.identifyRequest) === null || _b === void 0 ? void 0 : _b.userIdentities; - if (userIdentities && isObject(userIdentities) && !isEmpty(userIdentities) && Object.values(userIdentities).some(Boolean)) { - return true; - } - return !!((_c = store === null || store === void 0 ? void 0 : store.SDKConfig) === null || _c === void 0 ? void 0 : _c.deviceId); - }; - - function APIClient(mpInstance, kitBlocker) { - this.uploader = null; - var self = this; - this.queueEventForBatchUpload = function (event) { - if (!this.uploader) { - // https://go.mparticle.com/work/SQDSDKS-6317 - var millis = parseNumber(mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis)); - this.uploader = new BatchUploader(mpInstance, millis); - } - this.uploader.queueEvent(event); - // https://go.mparticle.com/work/SQDSDKS-6038 - mpInstance._Persistence.update(); - }; - this.processQueuedEvents = function () { - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(); - if (currentUser) { - mpid = currentUser.getMPID(); - } - if (mpInstance._Store.eventQueue.length && mpid) { - var localQueueCopy = mpInstance._Store.eventQueue; - mpInstance._Store.eventQueue = []; - this.appendUserInfoToEvents(currentUser, localQueueCopy); - localQueueCopy.forEach(function (event) { - self.sendEventToServer(event); - }); - } - }; - this.appendUserInfoToEvents = function (user, events) { - events.forEach(function (event) { - if (!event.MPID) { - appendUserInfo(user, event); - } - }); - }; - // When noFunctional is set and there are no identities passed, the SDK will not fully initialize. - // In this case, there will be no MPID, but we still want kits to initialize and forward the event to kits. - // The original event is queued for the MP server upload path so it can be sent once an MPID is returned. - // Returns true if the event was handled by this path (caller should return early). - var handleNoFunctionalPreMpidEvent = function handleNoFunctionalPreMpidEvent(event, mpid) { - var _a; - var noFunctionalWithoutId = ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store); - if (!noFunctionalWithoutId || mpid || !mpInstance._Store.configurationLoaded || mpInstance._Store.requireDelay) { - return false; - } - var forwarderEvent = event; - if (kitBlocker === null || kitBlocker === void 0 ? void 0 : kitBlocker.kitBlockingEnabled) { - forwarderEvent = kitBlocker.createBlockedEvent(event); - } - if (forwarderEvent) { - mpInstance._Forwarders.sendEventToForwarders(forwarderEvent); - event.AlreadySentToForwarders = true; - } - mpInstance.Logger.verbose('noFunctional event forwarded to kits and queued for MP server upload when MPID is available.'); - mpInstance._Store.eventQueue.push(event); - return true; - }; - this.sendEventToServer = function (event, _options) { - var defaultOptions = { - shouldUploadEvent: true - }; - var options = mpInstance._Helpers.extend(defaultOptions, _options); - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent, JSON.stringify(event)); - return; - } - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(); - if (currentUser) { - mpid = currentUser.getMPID(); - } - mpInstance._Store.requireDelay = mpInstance._Helpers.isDelayedByIntegration(mpInstance._preInit.integrationDelays, mpInstance._Store.integrationDelayTimeoutStart, Date.now()); - if (handleNoFunctionalPreMpidEvent(event, mpid)) { - return; - } - // We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that - // require this to stall because integration attributes need to be set, or if we are still - // fetching the config (self hosted only), and so require delaying events - if (!mpid || mpInstance._Store.requireDelay || !mpInstance._Store.configurationLoaded) { - mpInstance.Logger.verbose('Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.'); - mpInstance._Store.eventQueue.push(event); - return; - } - this.processQueuedEvents(); - if (isEmpty(event)) { - return; - } - // https://go.mparticle.com/work/SQDSDKS-6038 - if (options.shouldUploadEvent) { - this.queueEventForBatchUpload(event); - } - // https://go.mparticle.com/work/SQDSDKS-6935 - // While Event Name is 'usually' a string, there are some cases where it is a number - // in that it could be a type of MessageType Enum - if (event.EventName !== Types.MessageType.AppStateTransition) { - if (kitBlocker && kitBlocker.kitBlockingEnabled) { - event = kitBlocker.createBlockedEvent(event); - } - // We need to check event again, because kitblocking - // can nullify the event. - // Skip if forwarders were already called in the noFunctional pre-MPID path - // to prevent double-sending when the event queue is later flushed. - if (event && !event.AlreadySentToForwarders) { - mpInstance._Forwarders.sendEventToForwarders(event); - } - } - }; - this.sendBatchForwardingStatsToServer = function (forwardingStatsData, xhr) { - var url; - var data; - try { - url = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.v2SecureServiceUrl, mpInstance._Store.devToken); - data = { - uuid: mpInstance._Helpers.generateUniqueId(), - data: forwardingStatsData - }; - if (xhr) { - xhr.open('post', url + '/Forwarding'); - xhr.send(JSON.stringify(data)); - } - } catch (e) { - mpInstance.Logger.error('Error sending forwarding stats to mParticle servers.'); - } - }; - this.initializeForwarderStatsUploader = function () { - var forwardingDomain = mpInstance._Store.SDKConfig.v1SecureServiceUrl; - var devToken = mpInstance._Store.devToken; - var uploadUrl = "https://".concat(forwardingDomain).concat(devToken, "/Forwarding"); - var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); - return uploader; - }; - this.prepareForwardingStats = function (forwarder, event) { - var forwardingStatsData; - var queue = mpInstance._Forwarders.getForwarderStatsQueue(); - if (forwarder && forwarder.isVisible) { - forwardingStatsData = { - mid: forwarder.id, - esid: forwarder.eventSubscriptionId, - n: event.EventName, - attrs: event.EventAttributes, - sdk: event.SDKVersion, - dt: event.EventDataType, - et: event.EventCategory, - dbg: event.Debug, - ct: event.Timestamp, - eec: event.ExpandedEventCount, - dp: event.DataPlan - }; - var _a = mpInstance._Forwarders, - sendSingleForwardingStatsToServer = _a.sendSingleForwardingStatsToServer, - setForwarderStatsQueue = _a.setForwarderStatsQueue; - if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)) { - queue.push(forwardingStatsData); - setForwarderStatsQueue(queue); - } else { - sendSingleForwardingStatsToServer(forwardingStatsData); - } - } - }; - } - - var Modify$3 = Constants.IdentityMethods.Modify; - var Validators = { - // From ./utils - // Utility Functions for backwards compatability - isNumber: isNumber, - isFunction: isFunction, - isStringOrNumber: isStringOrNumber, - // Validator Functions - isValidAttributeValue: isValidAttributeValue, - // Validator Functions - // Neither null nor undefined can be a valid Key - isValidKeyValue: function isValidKeyValue(key) { - return Boolean(key && !isObject(key) && !Array.isArray(key) && !this.isFunction(key)); - }, - removeFalsyIdentityValues: function removeFalsyIdentityValues(identityApiData, logger) { - if (!identityApiData || !identityApiData.userIdentities) { - return identityApiData; - } - var cleanedData = {}; - var cleanedUserIdentities = __assign({}, identityApiData.userIdentities); - for (var identityType in identityApiData.userIdentities) { - if (identityApiData.userIdentities.hasOwnProperty(identityType)) { - var value = identityApiData.userIdentities[identityType]; - // Check if value is falsy (undefined, false, 0, '', etc.) but not null - if (value !== null && !value) { - logger.warning("Identity value for '".concat(identityType, "' is falsy (").concat(value, "). This value will be removed from the request.")); - delete cleanedUserIdentities[identityType]; - } - } - } - cleanedData.userIdentities = cleanedUserIdentities; - return cleanedData; - }, - validateIdentities: function validateIdentities(identityApiData, method) { - var validIdentityRequestKeys = { - userIdentities: 1, - onUserAlias: 1, - copyUserAttributes: 1 - }; - if (identityApiData) { - if (method === Modify$3) { - if (isObject(identityApiData.userIdentities) && !Object.keys(identityApiData.userIdentities).length || !isObject(identityApiData.userIdentities)) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent - }; - } - } - for (var key in identityApiData) { - if (identityApiData.hasOwnProperty(key)) { - if (!validIdentityRequestKeys[key]) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey - }; - } - if (key === 'onUserAlias' && !Validators.isFunction(identityApiData[key])) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.OnUserAliasType - }; - } - } - } - if (Object.keys(identityApiData).length === 0) { - return { - valid: true - }; - } else { - // identityApiData.userIdentities can't be undefined - if (identityApiData.userIdentities === undefined) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.UserIdentities - }; - // identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object - } else if (identityApiData.userIdentities !== null && !isObject(identityApiData.userIdentities)) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.UserIdentities - }; - } - if (isObject(identityApiData.userIdentities) && Object.keys(identityApiData.userIdentities).length) { - for (var identityType in identityApiData.userIdentities) { - if (identityApiData.userIdentities.hasOwnProperty(identityType)) { - if (Types.IdentityType.getIdentityType(identityType) === false) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey - }; - } - if (!(typeof identityApiData.userIdentities[identityType] === 'string' || identityApiData.userIdentities[identityType] === null)) { - return { - valid: false, - error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues - }; - } - } - } - } - } - } - return { - valid: true - }; - } - }; - - var KitFilterHelper = /** @class */function () { - function KitFilterHelper() {} - KitFilterHelper.hashEventType = function (eventType) { - return generateHash(eventType); - }; - KitFilterHelper.hashEventName = function (eventName, eventType) { - return generateHash(eventType + eventName); - }; - KitFilterHelper.hashEventAttributeKey = function (eventType, eventName, customAttributeName) { - return generateHash(eventType + eventName + customAttributeName); - }; - KitFilterHelper.hashUserAttribute = function (userAttributeKey) { - return generateHash(userAttributeKey); - }; - // User Identities are not actually hashed, this method is named this way to - // be consistent with the filter class. UserIdentityType is also a number - KitFilterHelper.hashUserIdentity = function (userIdentity) { - return userIdentity; - }; - KitFilterHelper.hashConsentPurpose = function (prefix, purpose) { - return generateHash(prefix + purpose); - }; - // The methods below are for conditional forwarding, a type of filter - // hashAttributeCondiitonalForwarding is used for both User and Event - // attribute keys and attribute values - // The backend returns the hashes as strings for conditional forwarding - // but returns "regular" filters as arrays of numbers - // See IFilteringEventAttributeValue in configApiClient.ts as an example - KitFilterHelper.hashAttributeConditionalForwarding = function (attribute) { - return generateHash(attribute).toString(); - }; - KitFilterHelper.hashConsentPurposeConditionalForwarding = function (prefix, purpose) { - return this.hashConsentPurpose(prefix, purpose).toString(); - }; - var _a; - _a = KitFilterHelper; - KitFilterHelper.filterUserAttributes = function (userAttributes, filterList) { - return filterDictionaryWithHash(userAttributes, filterList, function (key) { - return _a.hashUserAttribute(key); - }); - }; - KitFilterHelper.filterUserIdentities = function (userIdentities, filterList) { - return filterDictionaryWithHash(userIdentities, filterList, function (key) { - return _a.hashUserIdentity(IdentityType.getIdentityType(key)); - }); - }; - KitFilterHelper.isFilteredUserAttribute = function (userAttributeKey, filterList) { - var hashedUserAttribute = _a.hashUserAttribute(userAttributeKey); - return filterList && inArray(filterList, hashedUserAttribute); - }; - return KitFilterHelper; - }(); - - var StorageNames$1 = Constants.StorageNames; - function Helpers(mpInstance) { - var self = this; - this.canLog = function () { - if (mpInstance._Store.isEnabled && (mpInstance._Store.devToken || mpInstance._Store.webviewBridgeEnabled)) { - return true; - } - return false; - }; - this.getFeatureFlag = function (feature) { - if (mpInstance._Store.SDKConfig.flags.hasOwnProperty(feature)) { - return mpInstance._Store.SDKConfig.flags[feature]; - } - return null; - }; - this.invokeCallback = function (callback, code, body, mParticleUser, previousMpid) { - if (!callback) { - mpInstance.Logger.warning('There is no callback provided'); - } - try { - if (self.Validators.isFunction(callback)) { - callback({ - httpCode: code, - body: body, - getUser: function getUser() { - if (mParticleUser) { - return mParticleUser; - } else { - return mpInstance.Identity.getCurrentUser(); - } - }, - getPreviousUser: function getPreviousUser() { - if (!previousMpid) { - var users = mpInstance.Identity.getUsers(); - var mostRecentUser = users.shift(); - var currentUser = mParticleUser || mpInstance.Identity.getCurrentUser(); - if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) { - mostRecentUser = users.shift(); - } - return mostRecentUser || null; - } else { - return mpInstance.Identity.getUser(previousMpid); - } - } - }); - } - } catch (e) { - mpInstance.Logger.error('There was an error with your callback: ' + e); - } - }; - this.invokeAliasCallback = function (callback, code, message) { - if (!callback) { - mpInstance.Logger.warning('There is no callback provided'); - } - try { - if (self.Validators.isFunction(callback)) { - var callbackMessage = { - httpCode: code - }; - if (message) { - callbackMessage.message = message; - } - callback(callbackMessage); - } - } catch (e) { - mpInstance.Logger.error('There was an error with your callback: ' + e); - } - }; - - // https://go.mparticle.com/work/SQDSDKS-6047 - // Standalone version of jQuery.extend, from https://github.com/dansdom/extend - this.extend = function () { - var options, - name, - src, - copy, - copyIsArray, - clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false, - // helper which replicates the jquery internal functions - objectHelper = { - hasOwn: Object.prototype.hasOwnProperty, - class2type: {}, - type: function type(obj) { - return obj == null ? String(obj) : objectHelper.class2type[Object.prototype.toString.call(obj)] || 'object'; - }, - isPlainObject: function isPlainObject(obj) { - if (!obj || objectHelper.type(obj) !== 'object' || obj.nodeType || objectHelper.isWindow(obj)) { - return false; - } - try { - if (obj.constructor && !objectHelper.hasOwn.call(obj, 'constructor') && !objectHelper.hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) { - return false; - } - } catch (e) { - return false; - } - var key; - for (key in obj) {} // eslint-disable-line no-empty - - return key === undefined || objectHelper.hasOwn.call(obj, key); - }, - isArray: Array.isArray || function (obj) { - return objectHelper.type(obj) === 'array'; - }, - isFunction: function isFunction(obj) { - return objectHelper.type(obj) === 'function'; - }, - isWindow: function isWindow(obj) { - return obj != null && obj == obj.window; - } - }; // end of objectHelper - - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if (_typeof$1(target) !== 'object' && !objectHelper.isFunction(target)) { - target = {}; - } - - // If no second argument is used then this can extend an object that is using this method - if (length === i) { - target = this; - --i; - } - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) { - // Extend the base object - for (name in options) { - // Prevent prototype pollution - // https://github.com/advisories/GHSA-jf85-cpcp-j695 - if (name === '__proto__' || name === 'constructor' || name === 'prototype') { - continue; - } - - // Only copy own properties - if (!Object.prototype.hasOwnProperty.call(options, name)) { - continue; - } - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if (deep && copy && (objectHelper.isPlainObject(copy) || (copyIsArray = objectHelper.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && objectHelper.isArray(src) ? src : []; - } else { - clone = src && objectHelper.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[name] = self.extend(deep, clone, copy); - - // Don't bring in undefined values - } else if (copy !== undefined) { - target[name] = copy; - } - } - } - } - - // Return the modified object - return target; - }; - this.createServiceUrl = function (secureServiceUrl, devToken) { - var serviceScheme = window.mParticle && mpInstance._Store.SDKConfig.forceHttps ? 'https://' : window.location.protocol + '//'; - var baseUrl; - if (mpInstance._Store.SDKConfig.forceHttps) { - baseUrl = 'https://' + secureServiceUrl; - } else { - baseUrl = serviceScheme + secureServiceUrl; - } - if (devToken) { - baseUrl = baseUrl + devToken; - } - return baseUrl; - }; - this.createXHR = function (cb) { - var xhr; - try { - xhr = new window.XMLHttpRequest(); - } catch (e) { - mpInstance.Logger.error('Error creating XMLHttpRequest object.'); - } - if (xhr && cb && 'withCredentials' in xhr) { - xhr.onreadystatechange = cb; - } else if (typeof window.XDomainRequest !== 'undefined') { - mpInstance.Logger.verbose('Creating XDomainRequest object'); - try { - xhr = new window.XDomainRequest(); - xhr.onload = cb; - } catch (e) { - mpInstance.Logger.error('Error creating XDomainRequest object'); - } - } - return xhr; - }; - this.filterUserIdentities = function (userIdentitiesObject, filterList) { - var filteredUserIdentities = []; - if (userIdentitiesObject && Object.keys(userIdentitiesObject).length) { - for (var userIdentityName in userIdentitiesObject) { - if (userIdentitiesObject.hasOwnProperty(userIdentityName)) { - var userIdentityType = Types.IdentityType.getIdentityType(userIdentityName); - if (!self.inArray(filterList, userIdentityType)) { - var identity = { - Type: userIdentityType, - Identity: userIdentitiesObject[userIdentityName] - }; - if (userIdentityType === Types.IdentityType.CustomerId) { - filteredUserIdentities.unshift(identity); - } else { - filteredUserIdentities.push(identity); - } - } - } - } - } - return filteredUserIdentities; - }; - this.filterUserIdentitiesForForwarders = KitFilterHelper.filterUserIdentities; - this.filterUserAttributes = KitFilterHelper.filterUserAttributes; - this.isEventType = function (type) { - for (var prop in Types.EventType) { - if (Types.EventType.hasOwnProperty(prop)) { - if (Types.EventType[prop] === type) { - return true; - } - } - } - return false; - }; - this.sanitizeAttributes = function (attrs, name) { - if (!attrs || !self.isObject(attrs)) { - return null; - } - var sanitizedAttrs = {}; - for (var prop in attrs) { - // Make sure that attribute values are not objects or arrays, which are not valid - if (attrs.hasOwnProperty(prop) && self.Validators.isValidAttributeValue(attrs[prop])) { - sanitizedAttrs[prop] = attrs[prop]; - } else { - mpInstance.Logger.warning("For '" + name + "', the corresponding attribute value of '" + prop + "' must be a string, number, boolean, or null."); - } - } - return sanitizedAttrs; - }; - this.isDelayedByIntegration = function (delayedIntegrations, timeoutStart, now) { - if (now - timeoutStart > mpInstance._Store.SDKConfig.integrationDelayTimeout) { - return false; - } - for (var integration in delayedIntegrations) { - if (delayedIntegrations[integration] === true) { - return true; - } else { - continue; - } - } - return false; - }; - this.createMainStorageName = function (workspaceToken) { - if (workspaceToken) { - return StorageNames$1.currentStorageName + '_' + workspaceToken; - } else { - return StorageNames$1.currentStorageName; - } - }; - - // TODO: Refactor SDK to directly use these methods - // https://go.mparticle.com/work/SQDSDKS-5239 - // Utility Functions - this.converted = converted; - this.findKeyInObject = findKeyInObject; - this.parseNumber = parseNumber; - this.inArray = inArray; - this.isObject = isObject; - this.decoded = decoded; - this.parseStringOrNumber = parseStringOrNumber; - this.generateHash = generateHash; - this.generateUniqueId = generateUniqueId; - - // Imported Validators - this.Validators = Validators; - } - - var Messages$8 = Constants.Messages; - var androidBridgeNameBase = 'mParticleAndroid'; - var iosBridgeNameBase = 'mParticle'; - function NativeSdkHelpers(mpInstance) { - var self = this; - this.initializeSessionAttributes = function (apiKey) { - var SetSessionAttribute = Constants.NativeSdkPaths.SetSessionAttribute; - var env = JSON.stringify({ - key: '$src_env', - value: 'webview' - }); - var key = JSON.stringify({ - key: '$src_key', - value: apiKey - }); - self.sendToNative(SetSessionAttribute, env); - if (apiKey) { - self.sendToNative(SetSessionAttribute, key); - } - }; - this.isBridgeV2Available = function (bridgeName) { - if (!bridgeName) { - return false; - } - var androidBridgeName = androidBridgeNameBase + '_' + bridgeName + '_v2'; - var iosBridgeName = iosBridgeNameBase + '_' + bridgeName + '_v2'; - - // iOS v2 bridge - if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)) { - return true; - } - // other iOS v2 bridge - // TODO: what to do about people setting things on mParticle itself? - if (window.mParticle && window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName === iosBridgeName) { - return true; - } - // android - if (window.hasOwnProperty(androidBridgeName)) { - return true; - } - return false; - }; - this.isWebviewEnabled = function (requiredWebviewBridgeName, minWebviewBridgeVersion) { - mpInstance._Store.bridgeV2Available = self.isBridgeV2Available(requiredWebviewBridgeName); - mpInstance._Store.bridgeV1Available = self.isBridgeV1Available(); - if (minWebviewBridgeVersion === 2) { - return mpInstance._Store.bridgeV2Available; - } - - // iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName - if (window.mParticle) { - if (window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName !== iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2') { - return false; - } - } - if (minWebviewBridgeVersion < 2) { - // ios - return mpInstance._Store.bridgeV2Available || mpInstance._Store.bridgeV1Available; - } - return false; - }; - this.isBridgeV1Available = function () { - if (mpInstance._Store.SDKConfig.useNativeSdk || window.mParticleAndroid || mpInstance._Store.SDKConfig.isIOS) { - return true; - } - return false; - }; - this.sendToNative = function (path, value) { - if (mpInstance._Store.bridgeV2Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion === 2) { - self.sendViaBridgeV2(path, value, mpInstance._Store.SDKConfig.requiredWebviewBridgeName); - return; - } - if (mpInstance._Store.bridgeV2Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2) { - self.sendViaBridgeV2(path, value, mpInstance._Store.SDKConfig.requiredWebviewBridgeName); - return; - } - if (mpInstance._Store.bridgeV1Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2) { - self.sendViaBridgeV1(path, value); - return; - } - }; - this.sendViaBridgeV1 = function (path, value) { - if (window.mParticleAndroid && window.mParticleAndroid.hasOwnProperty(path)) { - mpInstance.Logger.verbose(Messages$8.InformationMessages.SendAndroid + path); - window.mParticleAndroid[path](value); - } else if (mpInstance._Store.SDKConfig.isIOS) { - mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path); - self.sendViaIframeToIOS(path, value); - } - }; - this.sendViaIframeToIOS = function (path, value) { - var iframe = document.createElement('IFRAME'); - iframe.setAttribute('src', 'mp-sdk://' + path + '/' + encodeURIComponent(value)); - document.documentElement.appendChild(iframe); - iframe.parentNode.removeChild(iframe); - }; - this.sendViaBridgeV2 = function (path, value, requiredWebviewBridgeName) { - if (!requiredWebviewBridgeName) { - return; - } - var androidBridgeName = androidBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2', - androidBridge = window[androidBridgeName], - iosBridgeName = iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2', - iOSBridgeMessageHandler, - iOSBridgeNonMessageHandler; - if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers[iosBridgeName]) { - iOSBridgeMessageHandler = window.webkit.messageHandlers[iosBridgeName]; - } - if (mpInstance.uiwebviewBridgeName === iosBridgeName) { - iOSBridgeNonMessageHandler = mpInstance[iosBridgeName]; - } - if (androidBridge && androidBridge.hasOwnProperty(path)) { - mpInstance.Logger.verbose(Messages$8.InformationMessages.SendAndroid + path); - androidBridge[path](value); - return; - } else if (iOSBridgeMessageHandler) { - mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path); - iOSBridgeMessageHandler.postMessage(JSON.stringify({ - path: path, - value: value ? JSON.parse(value) : null - })); - } else if (iOSBridgeNonMessageHandler) { - mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path); - self.sendViaIframeToIOS(path, value); - } - }; - } - - var Messages$7 = Constants.Messages; - var InformationMessages = Messages$7.InformationMessages; - var DAYS_IN_MILLISECONDS = 1000 * 60 * 60 * 24; - // Partner module IDs for cookie sync configurations - var PARTNER_MODULE_IDS = { - AdobeEventForwarder: 11, - DoubleclickDFP: 41, - AppNexus: 50, - Lotame: 58, - TradeDesk: 103, - VerizonMedia: 155, - Rokt: 1277 - }; - function CookieSyncManager(mpInstance) { - var self = this; - // Public - this.attemptCookieSync = function (mpid, mpidIsNotInCookies) { - var _a; - var _b = mpInstance._Store, - pixelConfigurations = _b.pixelConfigurations, - webviewBridgeEnabled = _b.webviewBridgeEnabled; - if (!mpid || webviewBridgeEnabled) { - return; - } - // When noFunctional is true, persistence is not saved, so we cannot track cookie sync - // dates. Skip cookie sync to avoid running it on every page load. - if ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) { - return; - } - var persistence = mpInstance._Persistence.getPersistence(); - if (isEmpty(persistence)) { - return; - } - pixelConfigurations.forEach(function (pixelSettings) { - var _a, _b; - // set requiresConsent to false to start each additional pixel configuration - // set to true only if filteringConsenRuleValues.values.length exists - var requiresConsent = false; - // Filtering rules as defined in UI - var filteringConsentRuleValues = pixelSettings.filteringConsentRuleValues, - pixelUrl = pixelSettings.pixelUrl, - redirectUrl = pixelSettings.redirectUrl, - moduleId = pixelSettings.moduleId, - // Tells you how often we should do a cookie sync (in days) - frequencyCap = pixelSettings.frequencyCap; - var values = (filteringConsentRuleValues || {}).values; - if (isEmpty(pixelUrl)) { - return; - } - if (!isEmpty(values)) { - requiresConsent = true; - } - // If MPID is new to cookies, we should not try to perform the cookie sync - // because a cookie sync can only occur once a user either consents or doesn't. - // we should not check if it's enabled if the user has a blank consent - if (requiresConsent && mpidIsNotInCookies) { - return; - } - // For Rokt, block cookie sync when noTargeting privacy flag is true - if (moduleId === PARTNER_MODULE_IDS.Rokt && mpInstance._CookieConsentManager.getNoTargeting()) { - return; - } - var isEnabledForUserConsent = mpInstance._Consent.isEnabledForUserConsent; - if (!isEnabledForUserConsent(filteringConsentRuleValues, mpInstance.Identity.getCurrentUser())) { - return; - } - var cookieSyncDates = (_b = (_a = persistence[mpid]) === null || _a === void 0 ? void 0 : _a.csd) !== null && _b !== void 0 ? _b : {}; - var lastSyncDateForModule = cookieSyncDates[moduleId] || null; - if (!isLastSyncDateExpired(frequencyCap, lastSyncDateForModule)) { - return; - } - // The Trade Desk requires a URL parameter for GDPR enabled users. - // It is optional but to simplify the code, we add it for all Trade - // // Desk cookie syncs. - var domain = moduleId === PARTNER_MODULE_IDS.TradeDesk ? window.location.hostname : undefined; - // Add domain parameter for Trade Desk - var fullUrl = createCookieSyncUrl(mpid, pixelUrl, redirectUrl, domain); - self.performCookieSync(fullUrl, moduleId.toString(), mpid, cookieSyncDates); - }); - }; - // Private - this.performCookieSync = function (url, moduleId, mpid, cookieSyncDates) { - var img = document.createElement('img'); - mpInstance.Logger.verbose(InformationMessages.CookieSync); - img.onload = function () { - cookieSyncDates[moduleId] = new Date().getTime(); - mpInstance._Persistence.saveUserCookieSyncDatesToPersistence(mpid, cookieSyncDates); - }; - img.src = url; - }; - } - var isLastSyncDateExpired = function isLastSyncDateExpired(frequencyCap, lastSyncDate) { - // If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie - if (!lastSyncDate) { - return true; - } - // Otherwise, compare the last sync date to determine if it should do a cookie sync again - return new Date().getTime() > new Date(lastSyncDate).getTime() + frequencyCap * DAYS_IN_MILLISECONDS; - }; - - var Messages$6 = Constants.Messages; - function SessionManager(mpInstance) { - var self = this; - this.initialize = function () { - var _a; - if (mpInstance._Store.sessionId) { - var _b = mpInstance._Store, - dateLastEventSent = _b.dateLastEventSent, - SDKConfig = _b.SDKConfig; - var sessionTimeout = SDKConfig.sessionTimeout; - if (hasSessionTimedOut(dateLastEventSent === null || dateLastEventSent === void 0 ? void 0 : dateLastEventSent.getTime(), sessionTimeout)) { - self.endSession(); - self.startNewSession(); - } else { - // https://go.mparticle.com/work/SQDSDKS-6045 - // https://go.mparticle.com/work/SQDSDKS-6323 - var currentUser = mpInstance.Identity.getCurrentUser(); - var sdkIdentityRequest = SDKConfig.identifyRequest; - var shouldSuppressIdentify = ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store); - if (!shouldSuppressIdentify && hasIdentityRequestChanged(currentUser, sdkIdentityRequest)) { - mpInstance.Identity.identify(sdkIdentityRequest, SDKConfig.identityCallback); - mpInstance._Store.identifyCalled = true; - mpInstance._Store.SDKConfig.identityCallback = null; - } - } - } else { - self.startNewSession(); - } - }; - this.getSession = function () { - mpInstance.Logger.warning(generateDeprecationMessage('SessionManager.getSession()', false, 'SessionManager.getSessionId()')); - return this.getSessionId(); - }; - this.getSessionId = function () { - return mpInstance._Store.sessionId; - }; - this.startNewSession = function () { - var _a; - mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingNewSession); - if (mpInstance._Helpers.canLog()) { - mpInstance._Store.sessionId = mpInstance._Helpers.generateUniqueId().toUpperCase(); - var currentUser = mpInstance.Identity.getCurrentUser(); - var mpid = currentUser ? currentUser.getMPID() : null; - if (mpid) { - mpInstance._Store.currentSessionMPIDs = [mpid]; - } - if (!mpInstance._Store.sessionStartDate) { - var date = new Date(); - mpInstance._Store.sessionStartDate = date; - mpInstance._Store.dateLastEventSent = date; - } - self.setSessionTimer(); - var shouldSuppressIdentify = ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store); - if (!mpInstance._Store.identifyCalled && !shouldSuppressIdentify) { - mpInstance.Identity.identify(mpInstance._Store.SDKConfig.identifyRequest, mpInstance._Store.SDKConfig.identityCallback); - mpInstance._Store.identifyCalled = true; - mpInstance._Store.SDKConfig.identityCallback = null; - } - mpInstance._Events.logEvent({ - messageType: Types.MessageType.SessionStart - }); - } else { - mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession); - } - }; - this.endSession = function (override) { - var _a, _b, _c, _d; - mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingEndSession); - if (override) { - performSessionEnd(); - return; - } - if (!mpInstance._Helpers.canLog()) { - // At this moment, an AbandonedEndSession is defined when one of three things occurs: - // - the SDK's store is not enabled because mParticle.setOptOut was called - // - the devToken is undefined - // - webviewBridgeEnabled is set to false - mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession); - (_a = mpInstance._timeOnSiteTimer) === null || _a === void 0 ? void 0 : _a.resetTimer(); - return; - } - var cookies = mpInstance._Persistence.getPersistence(); - if (!cookies || cookies.gs && !cookies.gs.sid) { - mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd); - (_b = mpInstance._timeOnSiteTimer) === null || _b === void 0 ? void 0 : _b.resetTimer(); - return; - } - // sessionId is not equal to cookies.sid if cookies.sid is changed in another tab - if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) { - mpInstance._Store.sessionId = cookies.gs.sid; - } - if ((_c = cookies === null || cookies === void 0 ? void 0 : cookies.gs) === null || _c === void 0 ? void 0 : _c.les) { - var sessionTimeout = mpInstance._Store.SDKConfig.sessionTimeout; - if (hasSessionTimedOut(cookies.gs.les, sessionTimeout)) { - performSessionEnd(); - } else { - self.setSessionTimer(); - (_d = mpInstance._timeOnSiteTimer) === null || _d === void 0 ? void 0 : _d.resetTimer(); - } - } - }; - this.setSessionTimer = function () { - var sessionTimeoutInMilliseconds = mpInstance._Store.SDKConfig.sessionTimeout * 60000; - mpInstance._Store.globalTimer = window.setTimeout(function () { - self.endSession(); - }, sessionTimeoutInMilliseconds); - }; - this.resetSessionTimer = function () { - if (!mpInstance._Store.webviewBridgeEnabled) { - if (!mpInstance._Store.sessionId) { - self.startNewSession(); - } - self.clearSessionTimeout(); - self.setSessionTimer(); - } - self.startNewSessionIfNeeded(); - }; - this.clearSessionTimeout = function () { - clearTimeout(mpInstance._Store.globalTimer); - }; - this.startNewSessionIfNeeded = function () { - if (!mpInstance._Store.webviewBridgeEnabled) { - var persistence = mpInstance._Persistence.getPersistence(); - if (!mpInstance._Store.sessionId && persistence) { - if (persistence.sid) { - mpInstance._Store.sessionId = persistence.sid; - } else { - self.startNewSession(); - } - } - } - }; - /** - * Checks if the session has expired based on the last event timestamp - * @param lastEventTimestamp - Unix timestamp in milliseconds of the last event - * @param sessionTimeout - Session timeout in minutes - * @returns true if the session has expired, false otherwise - */ - function hasSessionTimedOut(lastEventTimestamp, sessionTimeout) { - if (!lastEventTimestamp || !sessionTimeout || sessionTimeout <= 0) { - return false; - } - var sessionTimeoutInMilliseconds = sessionTimeout * 60000; - var timeSinceLastEvent = Date.now() - lastEventTimestamp; - return timeSinceLastEvent >= sessionTimeoutInMilliseconds; - } - /** - * Performs session end operations: - * - Logs a SessionEnd event - * - Nullifies the session ID and related data - * - Resets the time-on-site timer - */ - function performSessionEnd() { - var _a; - mpInstance._Events.logEvent({ - messageType: Types.MessageType.SessionEnd - }); - mpInstance._Store.nullifySession(); - (_a = mpInstance._timeOnSiteTimer) === null || _a === void 0 ? void 0 : _a.resetTimer(); - } - } - - var Messages$5 = Constants.Messages; - function Ecommerce(mpInstance) { - var self = this; - - // https://go.mparticle.com/work/SQDSDKS-4801 - this.convertTransactionAttributesToProductAction = function (transactionAttributes, productAction) { - if (transactionAttributes.hasOwnProperty('Id')) { - productAction.TransactionId = transactionAttributes.Id; - } - if (transactionAttributes.hasOwnProperty('Affiliation')) { - productAction.Affiliation = transactionAttributes.Affiliation; - } - if (transactionAttributes.hasOwnProperty('CouponCode')) { - productAction.CouponCode = transactionAttributes.CouponCode; - } - if (transactionAttributes.hasOwnProperty('Revenue')) { - productAction.TotalAmount = this.sanitizeAmount(transactionAttributes.Revenue, 'Revenue'); - } - if (transactionAttributes.hasOwnProperty('Shipping')) { - productAction.ShippingAmount = this.sanitizeAmount(transactionAttributes.Shipping, 'Shipping'); - } - if (transactionAttributes.hasOwnProperty('Tax')) { - productAction.TaxAmount = this.sanitizeAmount(transactionAttributes.Tax, 'Tax'); - } - if (transactionAttributes.hasOwnProperty('Step')) { - productAction.CheckoutStep = transactionAttributes.Step; - } - if (transactionAttributes.hasOwnProperty('Option')) { - productAction.CheckoutOptions = transactionAttributes.Option; - } - }; - this.getProductActionEventName = function (productActionType) { - switch (productActionType) { - case Types.ProductActionType.AddToCart: - return 'AddToCart'; - case Types.ProductActionType.AddToWishlist: - return 'AddToWishlist'; - case Types.ProductActionType.Checkout: - return 'Checkout'; - case Types.ProductActionType.CheckoutOption: - return 'CheckoutOption'; - case Types.ProductActionType.Click: - return 'Click'; - case Types.ProductActionType.Purchase: - return 'Purchase'; - case Types.ProductActionType.Refund: - return 'Refund'; - case Types.ProductActionType.RemoveFromCart: - return 'RemoveFromCart'; - case Types.ProductActionType.RemoveFromWishlist: - return 'RemoveFromWishlist'; - case Types.ProductActionType.ViewDetail: - return 'ViewDetail'; - case Types.ProductActionType.Unknown: - default: - return 'Unknown'; - } - }; - this.getPromotionActionEventName = function (promotionActionType) { - switch (promotionActionType) { - case Types.PromotionActionType.PromotionClick: - return 'PromotionClick'; - case Types.PromotionActionType.PromotionView: - return 'PromotionView'; - default: - return 'Unknown'; - } - }; - this.convertProductActionToEventType = function (productActionType) { - switch (productActionType) { - case Types.ProductActionType.AddToCart: - return Types.CommerceEventType.ProductAddToCart; - case Types.ProductActionType.AddToWishlist: - return Types.CommerceEventType.ProductAddToWishlist; - case Types.ProductActionType.Checkout: - return Types.CommerceEventType.ProductCheckout; - case Types.ProductActionType.CheckoutOption: - return Types.CommerceEventType.ProductCheckoutOption; - case Types.ProductActionType.Click: - return Types.CommerceEventType.ProductClick; - case Types.ProductActionType.Purchase: - return Types.CommerceEventType.ProductPurchase; - case Types.ProductActionType.Refund: - return Types.CommerceEventType.ProductRefund; - case Types.ProductActionType.RemoveFromCart: - return Types.CommerceEventType.ProductRemoveFromCart; - case Types.ProductActionType.RemoveFromWishlist: - return Types.CommerceEventType.ProductRemoveFromWishlist; - - // https://go.mparticle.com/work/SQDSDKS-4801 - case Types.ProductActionType.Unknown: - return Types.EventType.Unknown; - case Types.ProductActionType.ViewDetail: - return Types.CommerceEventType.ProductViewDetail; - default: - mpInstance.Logger.error('Could not convert product action type ' + productActionType + ' to event type'); - return null; - } - }; - this.convertPromotionActionToEventType = function (promotionActionType) { - switch (promotionActionType) { - case Types.PromotionActionType.PromotionClick: - return Types.CommerceEventType.PromotionClick; - case Types.PromotionActionType.PromotionView: - return Types.CommerceEventType.PromotionView; - default: - mpInstance.Logger.error('Could not convert promotion action type ' + promotionActionType + ' to event type'); - return null; - } - }; - this.generateExpandedEcommerceName = function (eventName, plusOne) { - return 'eCommerce - ' + eventName + ' - ' + (plusOne ? 'Total' : 'Item'); - }; - - // https://go.mparticle.com/work/SQDSDKS-4801 - this.extractProductAttributes = function (attributes, product) { - if (product.CouponCode) { - attributes['Coupon Code'] = product.CouponCode; - } - if (product.Brand) { - attributes['Brand'] = product.Brand; - } - if (product.Category) { - attributes['Category'] = product.Category; - } - if (product.Name) { - attributes['Name'] = product.Name; - } - if (product.Sku) { - attributes['Id'] = product.Sku; - } - if (product.Price) { - attributes['Item Price'] = product.Price; - } - if (product.Quantity) { - attributes['Quantity'] = product.Quantity; - } - if (product.Position) { - attributes['Position'] = product.Position; - } - if (product.Variant) { - attributes['Variant'] = product.Variant; - } - attributes['Total Product Amount'] = product.TotalAmount || 0; - }; - - // https://go.mparticle.com/work/SQDSDKS-4801 - this.extractTransactionId = function (attributes, productAction) { - if (productAction.TransactionId) { - attributes['Transaction Id'] = productAction.TransactionId; - } - }; - - // https://go.mparticle.com/work/SQDSDKS-4801 - this.extractActionAttributes = function (attributes, productAction) { - self.extractTransactionId(attributes, productAction); - if (productAction.Affiliation) { - attributes['Affiliation'] = productAction.Affiliation; - } - if (productAction.CouponCode) { - attributes['Coupon Code'] = productAction.CouponCode; - } - if (productAction.TotalAmount) { - attributes['Total Amount'] = productAction.TotalAmount; - } - if (productAction.ShippingAmount) { - attributes['Shipping Amount'] = productAction.ShippingAmount; - } - if (productAction.TaxAmount) { - attributes['Tax Amount'] = productAction.TaxAmount; - } - if (productAction.CheckoutOptions) { - attributes['Checkout Options'] = productAction.CheckoutOptions; - } - if (productAction.CheckoutStep) { - attributes['Checkout Step'] = productAction.CheckoutStep; - } - }; - - // https://go.mparticle.com/work/SQDSDKS-4801 - this.extractPromotionAttributes = function (attributes, promotion) { - if (promotion.Id) { - attributes['Id'] = promotion.Id; - } - if (promotion.Creative) { - attributes['Creative'] = promotion.Creative; - } - if (promotion.Name) { - attributes['Name'] = promotion.Name; - } - if (promotion.Position) { - attributes['Position'] = promotion.Position; - } - }; - this.buildProductList = function (event, product) { - if (product) { - if (Array.isArray(product)) { - return product; - } - return [product]; - } - return event.ShoppingCart.ProductList; - }; - this.createProduct = function (name, sku, price, quantity, variant, category, brand, position, couponCode, attributes) { - attributes = mpInstance._Helpers.sanitizeAttributes(attributes, name); - if (typeof name !== 'string') { - mpInstance.Logger.error('Name is required when creating a product'); - return null; - } - if (!mpInstance._Helpers.Validators.isStringOrNumber(sku)) { - mpInstance.Logger.error('SKU is required when creating a product, and must be a string or a number'); - return null; - } - if (!mpInstance._Helpers.Validators.isStringOrNumber(price)) { - mpInstance.Logger.error('Price is required when creating a product, and must be a string or a number'); - return null; - } else { - price = mpInstance._Helpers.parseNumber(price); - } - if (position && !mpInstance._Helpers.Validators.isNumber(position)) { - mpInstance.Logger.error('Position must be a number, it will be set to null.'); - position = null; - } - if (!mpInstance._Helpers.Validators.isStringOrNumber(quantity)) { - quantity = 1; - } else { - quantity = mpInstance._Helpers.parseNumber(quantity); - } - return { - Name: name, - Sku: sku, - Price: price, - Quantity: quantity, - Brand: brand, - Variant: variant, - Category: category, - Position: position, - CouponCode: couponCode, - TotalAmount: quantity * price, - Attributes: attributes - }; - }; - this.createPromotion = function (id, creative, name, position) { - if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) { - mpInstance.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired); - return null; - } - return { - Id: id, - Creative: creative, - Name: name, - Position: position - }; - }; - this.createImpression = function (name, product) { - if (typeof name !== 'string') { - mpInstance.Logger.error('Name is required when creating an impression.'); - return null; - } - if (!product) { - mpInstance.Logger.error('Product is required when creating an impression.'); - return null; - } - return { - Name: name, - Product: product - }; - }; - this.createTransactionAttributes = function (id, affiliation, couponCode, revenue, shipping, tax) { - if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) { - mpInstance.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired); - return null; - } - return { - Id: id, - Affiliation: affiliation, - CouponCode: couponCode, - Revenue: revenue, - Shipping: shipping, - Tax: tax - }; - }; - this.expandProductImpression = function (commerceEvent) { - var appEvents = []; - if (!commerceEvent.ProductImpressions) { - return appEvents; - } - commerceEvent.ProductImpressions.forEach(function (productImpression) { - if (productImpression.ProductList) { - productImpression.ProductList.forEach(function (product) { - var attributes = mpInstance._Helpers.extend(false, {}, commerceEvent.EventAttributes); - if (product.Attributes) { - for (var attribute in product.Attributes) { - attributes[attribute] = product.Attributes[attribute]; - } - } - self.extractProductAttributes(attributes, product); - if (productImpression.ProductImpressionList) { - attributes['Product Impression List'] = productImpression.ProductImpressionList; - } - var appEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.PageEvent, - name: self.generateExpandedEcommerceName('Impression'), - data: attributes, - eventType: Types.EventType.Transaction - }); - appEvents.push(appEvent); - }); - } - }); - return appEvents; - }; - this.expandCommerceEvent = function (event) { - if (!event) { - return null; - } - return self.expandProductAction(event).concat(self.expandPromotionAction(event)).concat(self.expandProductImpression(event)); - }; - this.expandPromotionAction = function (commerceEvent) { - var appEvents = []; - if (!commerceEvent.PromotionAction) { - return appEvents; - } - var promotions = commerceEvent.PromotionAction.PromotionList; - promotions.forEach(function (promotion) { - var attributes = mpInstance._Helpers.extend(false, {}, commerceEvent.EventAttributes); - self.extractPromotionAttributes(attributes, promotion); - var appEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.PageEvent, - name: self.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(commerceEvent.PromotionAction.PromotionActionType)), - data: attributes, - eventType: Types.EventType.Transaction - }); - appEvents.push(appEvent); - }); - return appEvents; - }; - this.expandProductAction = function (commerceEvent) { - var appEvents = []; - if (!commerceEvent.ProductAction) { - return appEvents; - } - var shouldExtractActionAttributes = false; - if (commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Purchase || commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Refund) { - var attributes = mpInstance._Helpers.extend(false, {}, commerceEvent.EventAttributes); - attributes['Product Count'] = commerceEvent.ProductAction.ProductList ? commerceEvent.ProductAction.ProductList.length : 0; - self.extractActionAttributes(attributes, commerceEvent.ProductAction); - if (commerceEvent.CurrencyCode) { - attributes['Currency Code'] = commerceEvent.CurrencyCode; - } - var plusOneEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.PageEvent, - name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType), true), - data: attributes, - eventType: Types.EventType.Transaction - }); - appEvents.push(plusOneEvent); - } else { - shouldExtractActionAttributes = true; - } - var products = commerceEvent.ProductAction.ProductList; - if (!products) { - return appEvents; - } - products.forEach(function (product) { - var attributes = mpInstance._Helpers.extend(false, commerceEvent.EventAttributes, product.Attributes); - if (shouldExtractActionAttributes) { - self.extractActionAttributes(attributes, commerceEvent.ProductAction); - } else { - self.extractTransactionId(attributes, commerceEvent.ProductAction); - } - self.extractProductAttributes(attributes, product); - var productEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.PageEvent, - name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType)), - data: attributes, - eventType: Types.EventType.Transaction - }); - appEvents.push(productEvent); - }); - return appEvents; - }; - this.createCommerceEventObject = function (customFlags, options) { - var baseEvent; - // https://go.mparticle.com/work/SQDSDKS-4801 - var extend = mpInstance._Helpers.extend; - mpInstance.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent); - if (mpInstance._Helpers.canLog()) { - baseEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.Commerce, - sourceMessageId: options === null || options === void 0 ? void 0 : options.sourceMessageId - }); - baseEvent.EventName = 'eCommerce - '; - baseEvent.CurrencyCode = mpInstance._Store.currencyCode; - baseEvent.ShoppingCart = []; - baseEvent.CustomFlags = extend(baseEvent.CustomFlags, customFlags); - return baseEvent; - } else { - mpInstance.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent); - } - return null; - }; - - // sanitizes any non number, non string value to 0 - this.sanitizeAmount = function (amount, category) { - if (!mpInstance._Helpers.Validators.isStringOrNumber(amount)) { - var message = [category, 'must be of type number. A', _typeof$1(amount), 'was passed. Converting to 0'].join(' '); - mpInstance.Logger.warning(message); - return 0; - } - - // if amount is a string, it will be parsed into a number if possible, or set to 0 - return mpInstance._Helpers.parseNumber(amount); - }; - } - - var ForegroundTimeTracker = /** @class */function () { - function ForegroundTimeTracker(timerKey, noFunctional) { - if (noFunctional === void 0) { - noFunctional = false; - } - this.noFunctional = noFunctional; - this.isTrackerActive = false; - this.localStorageName = ''; - this.startTime = 0; - this.totalTime = 0; - this.localStorageName = "mprtcl-tos-".concat(timerKey); - this.timerVault = new LocalStorageVault(this.localStorageName); - if (!this.noFunctional) { - this.loadTimeFromStorage(); - } - this.addHandlers(); - if (document.hidden === false) { - this.startTracking(); - } - } - ForegroundTimeTracker.prototype.addHandlers = function () { - var _this = this; - // when user switches tabs or minimizes the window - document.addEventListener('visibilitychange', function () { - return _this.handleVisibilityChange(); - }); - // when user switches to another application - window.addEventListener('blur', function () { - return _this.handleWindowBlur(); - }); - // when window gains focus - window.addEventListener('focus', function () { - return _this.handleWindowFocus(); - }); - // this ensures that timers between tabs are in sync - window.addEventListener('storage', function (event) { - return _this.syncAcrossTabs(event); - }); - // when user closes tab, refreshes, or navigates to another page via link - window.addEventListener('beforeunload', function () { - return _this.updateTimeInPersistence(); - }); - }; - ForegroundTimeTracker.prototype.handleVisibilityChange = function () { - if (document.hidden) { - this.stopTracking(); - } else { - this.startTracking(); - } - }; - ForegroundTimeTracker.prototype.handleWindowBlur = function () { - if (this.isTrackerActive) { - this.stopTracking(); - } - }; - ForegroundTimeTracker.prototype.handleWindowFocus = function () { - if (!this.isTrackerActive) { - this.startTracking(); - } - }; - ForegroundTimeTracker.prototype.syncAcrossTabs = function (event) { - if (event.key === this.localStorageName && event.newValue !== null) { - var newTime = parseFloat(event.newValue) || 0; - this.totalTime = newTime; - } - }; - ForegroundTimeTracker.prototype.updateTimeInPersistence = function () { - if (this.isTrackerActive && !this.noFunctional) { - this.timerVault.store(Math.round(this.totalTime)); - } - }; - ForegroundTimeTracker.prototype.loadTimeFromStorage = function () { - var storedTime = this.timerVault.retrieve(); - if (isNumber(storedTime) && storedTime !== null) { - this.totalTime = storedTime; - } - }; - ForegroundTimeTracker.prototype.startTracking = function () { - if (!document.hidden) { - this.startTime = Math.floor(performance.now()); - this.isTrackerActive = true; - } - }; - ForegroundTimeTracker.prototype.stopTracking = function () { - if (this.isTrackerActive) { - this.setTotalTime(); - this.updateTimeInPersistence(); - this.isTrackerActive = false; - } - }; - ForegroundTimeTracker.prototype.setTotalTime = function () { - if (this.isTrackerActive) { - var now = Math.floor(performance.now()); - this.totalTime += now - this.startTime; - this.startTime = now; - } - }; - ForegroundTimeTracker.prototype.getTimeInForeground = function () { - this.setTotalTime(); - this.updateTimeInPersistence(); - return this.totalTime; - }; - ForegroundTimeTracker.prototype.resetTimer = function () { - this.totalTime = 0; - this.updateTimeInPersistence(); - }; - return ForegroundTimeTracker; - }(); - - function createSDKConfig(config) { - // TODO: Refactor to create a default config object - var sdkConfig = {}; - for (var prop in Constants.DefaultConfig) { - if (Constants.DefaultConfig.hasOwnProperty(prop)) { - sdkConfig[prop] = Constants.DefaultConfig[prop]; - } - } - if (config) { - for (var prop in config) { - if (config.hasOwnProperty(prop)) { - sdkConfig[prop] = config[prop]; - } - } - } - for (var prop in Constants.DefaultBaseUrls) { - sdkConfig[prop] = Constants.DefaultBaseUrls[prop]; - } - // Always initialize flags to at least an empty object to prevent undefined access - sdkConfig.flags = sdkConfig.flags || {}; - return sdkConfig; - } - // TODO: Merge this with SDKStoreApi in sdkRuntimeModels - function Store(config, mpInstance, apiKey) { - var _this = this; - var createMainStorageName = mpInstance._Helpers.createMainStorageName; - var isWebviewEnabled = mpInstance._NativeSdkHelpers.isWebviewEnabled; - var defaultStore = { - isEnabled: true, - sessionAttributes: {}, - localSessionAttributes: {}, - currentSessionMPIDs: [], - consentState: null, - sessionId: null, - isFirstRun: null, - clientId: null, - deviceId: null, - devToken: null, - serverSettings: {}, - dateLastEventSent: null, - sessionStartDate: null, - currentPosition: null, - isTracking: false, - watchPositionId: null, - cartProducts: [], - eventQueue: [], - currencyCode: null, - globalTimer: null, - context: null, - configurationLoaded: false, - identityCallInFlight: false, - identityCallFailed: false, - identifyRequestCount: 0, - SDKConfig: {}, - nonCurrentUserMPIDs: {}, - identifyCalled: false, - isLoggedIn: false, - cookieSyncDates: {}, - integrationAttributes: {}, - requireDelay: true, - isLocalStorageAvailable: null, - storageName: null, - activeForwarders: [], - kits: {}, - sideloadedKits: [], - configuredForwarders: [], - pixelConfigurations: [], - wrapperSDKInfo: { - name: 'none', - version: null, - isInfoSet: false - }, - roktAccountId: null, - integrationName: null, - // Placeholder for in-memory persistence model - persistenceData: { - gs: {} - } - }; - for (var key in defaultStore) { - this[key] = defaultStore[key]; - } - this.devToken = apiKey || null; - this.integrationDelayTimeoutStart = Date.now(); - // Set configuration to default settings - this.SDKConfig = createSDKConfig(config); - if (config) { - if (!config.hasOwnProperty('flags')) { - this.SDKConfig.flags = {}; - } - this.SDKConfig.flags = processFlags(config); - if (config.deviceId) { - this.deviceId = config.deviceId; - } - if (config.hasOwnProperty('isDevelopmentMode')) { - this.SDKConfig.isDevelopmentMode = returnConvertedBoolean(config.isDevelopmentMode); - } else { - this.SDKConfig.isDevelopmentMode = false; - } - var baseUrls = processBaseUrls(config, this.SDKConfig.flags, apiKey); - for (var baseUrlKeys in baseUrls) { - this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys]; - } - this.SDKConfig.useNativeSdk = !!config.useNativeSdk; - this.SDKConfig.kits = config.kits || {}; - this.SDKConfig.sideloadedKits = config.sideloadedKits || []; - if (config.hasOwnProperty('isIOS')) { - this.SDKConfig.isIOS = config.isIOS; - } else { - this.SDKConfig.isIOS = window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false; - } - if (config.hasOwnProperty('useCookieStorage')) { - this.SDKConfig.useCookieStorage = config.useCookieStorage; - } else { - this.SDKConfig.useCookieStorage = false; - } - if (config.hasOwnProperty('maxProducts')) { - this.SDKConfig.maxProducts = config.maxProducts; - } else { - this.SDKConfig.maxProducts = Constants.DefaultConfig.maxProducts; - } - if (config.hasOwnProperty('maxCookieSize')) { - this.SDKConfig.maxCookieSize = config.maxCookieSize; - } else { - this.SDKConfig.maxCookieSize = Constants.DefaultConfig.maxCookieSize; - } - if (config.hasOwnProperty('appName')) { - this.SDKConfig.appName = config.appName; - } - if (config.hasOwnProperty('package')) { - this.SDKConfig["package"] = config["package"]; - } - if (config.hasOwnProperty('integrationDelayTimeout')) { - this.SDKConfig.integrationDelayTimeout = config.integrationDelayTimeout; - } else { - this.SDKConfig.integrationDelayTimeout = Constants.DefaultConfig.integrationDelayTimeout; - } - if (config.hasOwnProperty('identifyRequest')) { - this.SDKConfig.identifyRequest = config.identifyRequest; - } - if (config.hasOwnProperty('identityCallback')) { - var callback = config.identityCallback; - if (mpInstance._Helpers.Validators.isFunction(callback)) { - this.SDKConfig.identityCallback = config.identityCallback; - } else { - mpInstance.Logger.warning('The optional callback must be a function. You tried entering a(n) ' + _typeof$1(callback) + ' . Callback not set. Please set your callback again.'); - } - } - if (config.hasOwnProperty('appVersion')) { - this.SDKConfig.appVersion = config.appVersion; - } - if (config.hasOwnProperty('appName')) { - this.SDKConfig.appName = config.appName; - } - if (config.hasOwnProperty('sessionTimeout')) { - this.SDKConfig.sessionTimeout = config.sessionTimeout; - } - if (config.hasOwnProperty('dataPlan')) { - this.SDKConfig.dataPlan = { - PlanVersion: null, - PlanId: null - }; - var dataPlan = config.dataPlan; - if (dataPlan.planId) { - if (isDataPlanSlug(dataPlan.planId)) { - this.SDKConfig.dataPlan.PlanId = dataPlan.planId; - } else { - mpInstance.Logger.error('Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)'); - } - } - if (dataPlan.planVersion) { - if (isNumber(dataPlan.planVersion)) { - this.SDKConfig.dataPlan.PlanVersion = dataPlan.planVersion; - } else { - mpInstance.Logger.error('Your data plan version must be a number'); - } - } - } else { - this.SDKConfig.dataPlan = {}; - } - if (config.hasOwnProperty('forceHttps')) { - this.SDKConfig.forceHttps = config.forceHttps; - } else { - this.SDKConfig.forceHttps = true; - } - // Some forwarders require custom flags on initialization, so allow them to be set using config object - this.SDKConfig.customFlags = config.customFlags || {}; - if (config.hasOwnProperty('minWebviewBridgeVersion')) { - this.SDKConfig.minWebviewBridgeVersion = config.minWebviewBridgeVersion; - } else { - this.SDKConfig.minWebviewBridgeVersion = 1; - } - if (config.hasOwnProperty('aliasMaxWindow')) { - this.SDKConfig.aliasMaxWindow = config.aliasMaxWindow; - } else { - this.SDKConfig.aliasMaxWindow = Constants.DefaultConfig.aliasMaxWindow; - } - if (config.hasOwnProperty('dataPlanOptions')) { - var dataPlanOptions = config.dataPlanOptions; - if (!dataPlanOptions.hasOwnProperty('dataPlanVersion') || !dataPlanOptions.hasOwnProperty('blockUserAttributes') || !dataPlanOptions.hasOwnProperty('blockEventAttributes') || !dataPlanOptions.hasOwnProperty('blockEvents') || !dataPlanOptions.hasOwnProperty('blockUserIdentities')) { - mpInstance.Logger.error('Ensure your config.dataPlanOptions object has the following keys: a "dataPlanVersion" object, and "blockUserAttributes", "blockEventAttributes", "blockEvents", "blockUserIdentities" booleans'); - } - } - if (config.hasOwnProperty('onCreateBatch')) { - if (typeof config.onCreateBatch === 'function') { - this.SDKConfig.onCreateBatch = config.onCreateBatch; - } else { - mpInstance.Logger.error('config.onCreateBatch must be a function'); - // set to undefined because all items are set on createSDKConfig - this.SDKConfig.onCreateBatch = undefined; - } - } - } - this._getFromPersistence = function (mpid, key) { - if (!mpid) { - return null; - } - _this.syncPersistenceData(); - if (_this.persistenceData && _this.persistenceData[mpid] && _this.persistenceData[mpid][key]) { - return _this.persistenceData[mpid][key]; - } else { - return null; - } - }; - this._setPersistence = function (mpid, key, value) { - var _a; - if (!mpid) { - return; - } - _this.syncPersistenceData(); - if (_this.persistenceData) { - if (_this.persistenceData[mpid]) { - _this.persistenceData[mpid][key] = value; - } else { - _this.persistenceData[mpid] = (_a = {}, _a[key] = value, _a); - } - // Clear out persistence attributes that are empty - // so that we don't upload empty or undefined values - if (isObject(_this.persistenceData[mpid][key]) && isEmpty(_this.persistenceData[mpid][key])) { - delete _this.persistenceData[mpid][key]; - } - mpInstance._Persistence.savePersistence(_this.persistenceData); - } - }; - this.hasInvalidIdentifyRequest = function () { - var identifyRequest = _this.SDKConfig.identifyRequest; - return isObject(identifyRequest) && isObject(identifyRequest.userIdentities) && isEmpty(identifyRequest.userIdentities) || !identifyRequest; - }; - this.getConsentState = function (mpid) { - var fromMinifiedJsonObject = mpInstance._Consent.ConsentSerialization.fromMinifiedJsonObject; - var serializedConsentState = _this._getFromPersistence(mpid, 'con'); - if (!isEmpty(serializedConsentState)) { - return fromMinifiedJsonObject(serializedConsentState); - } - return null; - }; - this.setConsentState = function (mpid, consentState) { - var toMinifiedJsonObject = mpInstance._Consent.ConsentSerialization.toMinifiedJsonObject; - // If ConsentState is null, we assume the intent is to clear out the consent state - if (consentState || consentState === null) { - _this._setPersistence(mpid, 'con', toMinifiedJsonObject(consentState)); - } - }; - this.getDeviceId = function () { - return _this.deviceId; - }; - this.setDeviceId = function (deviceId) { - _this.deviceId = deviceId; - _this.persistenceData.gs.das = deviceId; - mpInstance._Persistence.update(); - }; - this.getFirstSeenTime = function (mpid) { - return _this._getFromPersistence(mpid, 'fst'); - }; - this.setFirstSeenTime = function (mpid, _time) { - if (!mpid) { - return; - } - var time = _time || new Date().getTime(); - _this._setPersistence(mpid, 'fst', time); - }; - this.getLastSeenTime = function (mpid) { - if (!mpid) { - return null; - } - // https://go.mparticle.com/work/SQDSDKS-6315 - var currentUser = mpInstance.Identity.getCurrentUser(); - if (mpid === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.getMPID())) { - // if the mpid is the current user, its last seen time is the current time - return new Date().getTime(); - } - return _this._getFromPersistence(mpid, 'lst'); - }; - this.setLastSeenTime = function (mpid, _time) { - if (!mpid) { - return; - } - var time = _time || new Date().getTime(); - _this._setPersistence(mpid, 'lst', time); - }; - this.getLocalSessionAttributes = function () { - return _this.localSessionAttributes || {}; - }; - this.setLocalSessionAttribute = function (key, value) { - var _a; - _this.localSessionAttributes[key] = value; - _this.persistenceData.gs.lsa = __assign(__assign({}, _this.persistenceData.gs.lsa || {}), (_a = {}, _a[key] = value, _a)); - mpInstance._Persistence.savePersistence(_this.persistenceData); - }; - this.syncPersistenceData = function () { - var persistenceData = mpInstance._Persistence.getPersistence(); - _this.persistenceData = mpInstance._Helpers.extend({}, _this.persistenceData, persistenceData); - }; - this.getUserAttributes = function (mpid) { - return _this._getFromPersistence(mpid, 'ua') || {}; - }; - this.setUserAttributes = function (mpid, userAttributes) { - return _this._setPersistence(mpid, 'ua', userAttributes); - }; - this.getUserIdentities = function (mpid) { - return _this._getFromPersistence(mpid, 'ui') || {}; - }; - this.setUserIdentities = function (mpid, userIdentities) { - _this._setPersistence(mpid, 'ui', userIdentities); - }; - this.getRoktAccountId = function () { - return _this.roktAccountId; - }; - this.setRoktAccountId = function (accountId) { - _this.roktAccountId = accountId; - }; - this.getIntegrationName = function () { - return _this.integrationName; - }; - this.setIntegrationName = function (integrationName) { - _this.integrationName = integrationName; - }; - this.addMpidToSessionHistory = function (mpid, previousMPID) { - var indexOfMPID = _this.currentSessionMPIDs.indexOf(mpid); - if (mpid && previousMPID !== mpid && indexOfMPID < 0) { - _this.currentSessionMPIDs.push(mpid); - return; - } - if (indexOfMPID >= 0) { - _this.currentSessionMPIDs = moveElementToEnd(_this.currentSessionMPIDs, indexOfMPID); - } - }; - this.nullifySession = function () { - _this.sessionId = null; - _this.dateLastEventSent = null; - _this.sessionStartDate = null; - _this.sessionAttributes = {}; - _this.localSessionAttributes = {}; - mpInstance._Persistence.update(); - }; - this.processConfig = function (config) { - var _a; - var workspaceToken = config.workspaceToken, - requiredWebviewBridgeName = config.requiredWebviewBridgeName; - // We should reprocess the flags and baseUrls in case they have changed when we request an updated config - // such as if the SDK is being self-hosted and the flags are different on the server config - // https://go.mparticle.com/work/SQDSDKS-6317 - // Only update flags if the config actually has flags (don't overwrite with empty object) - if (config.flags) { - _this.SDKConfig.flags = processFlags(config); - } - var baseUrls = processBaseUrls(config, _this.SDKConfig.flags, apiKey); - for (var baseUrlKeys in baseUrls) { - _this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys]; - } - if (workspaceToken) { - _this.SDKConfig.workspaceToken = workspaceToken; - var noFunctional = ((_a = config === null || config === void 0 ? void 0 : config.launcherOptions) === null || _a === void 0 ? void 0 : _a.noFunctional) === true; - mpInstance._timeOnSiteTimer = new ForegroundTimeTracker(workspaceToken, noFunctional); - } else { - mpInstance.Logger.warning('You should have a workspaceToken on your config object for security purposes.'); - } - // add a new function to apply items to the store that require config to be returned - _this.storageName = createMainStorageName(workspaceToken); - _this.SDKConfig.requiredWebviewBridgeName = requiredWebviewBridgeName || workspaceToken; - _this.webviewBridgeEnabled = isWebviewEnabled(_this.SDKConfig.requiredWebviewBridgeName, _this.SDKConfig.minWebviewBridgeVersion); - _this.configurationLoaded = true; - }; - } - // https://go.mparticle.com/work/SQDSDKS-6317 - function processFlags(config) { - var flags = {}; - var _a = Constants.FeatureFlags, - ReportBatching = _a.ReportBatching, - EventBatchingIntervalMillis = _a.EventBatchingIntervalMillis, - OfflineStorage = _a.OfflineStorage, - DirectUrlRouting = _a.DirectUrlRouting, - CacheIdentity = _a.CacheIdentity, - AudienceAPI = _a.AudienceAPI, - CaptureIntegrationSpecificIds = _a.CaptureIntegrationSpecificIds, - CaptureIntegrationSpecificIdsV2 = _a.CaptureIntegrationSpecificIdsV2, - AstBackgroundEvents = _a.AstBackgroundEvents; - if (!config.flags) { - return {}; - } - // https://go.mparticle.com/work/SQDSDKS-6317 - // Passed in config flags take priority over defaults - flags[ReportBatching] = config.flags[ReportBatching] || false; - // The server returns stringified numbers, sowe need to parse - flags[EventBatchingIntervalMillis] = parseNumber(config.flags[EventBatchingIntervalMillis]) || Constants.DefaultConfig.uploadInterval; - flags[OfflineStorage] = config.flags[OfflineStorage] || '0'; - flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === 'True'; - flags[CacheIdentity] = config.flags[CacheIdentity] === 'True'; - flags[AudienceAPI] = config.flags[AudienceAPI] === 'True'; - flags[CaptureIntegrationSpecificIds] = config.flags[CaptureIntegrationSpecificIds] === 'True'; - flags[CaptureIntegrationSpecificIdsV2] = config.flags[CaptureIntegrationSpecificIdsV2] || 'none'; - flags[AstBackgroundEvents] = config.flags[AstBackgroundEvents] === 'True'; - return flags; - } - function processBaseUrls(config, flags, apiKey) { - // an API key is not present in a webview only mode. In this case, no baseUrls are needed - if (!apiKey) { - return {}; - } - // When direct URL routing is false, update baseUrls based custom urls - // passed to the config - if (flags.directURLRouting) { - return processDirectBaseUrls(config, apiKey); - } else { - return processCustomBaseUrls(config); - } - } - function processCustomBaseUrls(config) { - var defaultBaseUrls = Constants.DefaultBaseUrls; - var CNAMEUrlPaths = Constants.CNAMEUrlPaths; - // newBaseUrls are default if the customer is not using a CNAME - // If a customer passes either config.domain or config.v3SecureServiceUrl, - // config.identityUrl, etc, the customer is using a CNAME. - // config.domain will take priority if a customer passes both. - var newBaseUrls = {}; - // If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain. - // This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty - // if a customer is using a snippet prior to 2.6. - if (!isEmpty(config.domain)) { - for (var pathKey in CNAMEUrlPaths) { - newBaseUrls[pathKey] = "".concat(config.domain).concat(CNAMEUrlPaths[pathKey]); - } - return newBaseUrls; - } - for (var baseUrlKey in defaultBaseUrls) { - newBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; - } - return newBaseUrls; - } - function processDirectBaseUrls(config, apiKey) { - var defaultBaseUrls = Constants.DefaultBaseUrls; - var directBaseUrls = {}; - // When Direct URL Routing is true, we create a new set of baseUrls that - // include the silo in the urls. mParticle API keys are prefixed with the - // silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo, - // and before other silos existed, there were no prefixes and all apiKeys - // were us1. As such, if we split on a '-' and the resulting array length - // is 1, then it is an older APIkey that should route to us1. - // When splitKey.length is greater than 1, then splitKey[0] will be - // us1, us2, eu1, au1, or st1, etc as new silos are added - var DEFAULT_SILO = 'us1'; - var splitKey = apiKey.split('-'); - var routingPrefix = splitKey.length <= 1 ? DEFAULT_SILO : splitKey[0]; - for (var baseUrlKey in defaultBaseUrls) { - // Any custom endpoints passed to mpConfig will take priority over direct - // mapping to the silo. The most common use case is a customer provided CNAME. - if (baseUrlKey === 'configUrl') { - directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; - continue; - } - if (config.hasOwnProperty(baseUrlKey)) { - directBaseUrls[baseUrlKey] = config[baseUrlKey]; - } else { - var urlparts = defaultBaseUrls[baseUrlKey].split('.'); - directBaseUrls[baseUrlKey] = __spreadArray([urlparts[0], routingPrefix], urlparts.slice(1), true).join('.'); - } - } - return directBaseUrls; - } - - var Logger = /** @class */function () { - function Logger(config) { - var _a, _b; - this.logLevel = (_a = config.logLevel) !== null && _a !== void 0 ? _a : LogLevelType.Warning; - this.logger = (_b = config.logger) !== null && _b !== void 0 ? _b : new ConsoleLogger(); - } - Logger.prototype.verbose = function (msg) { - if (this.logLevel === LogLevelType.None) return; - if (this.logger.verbose && this.logLevel === LogLevelType.Verbose) { - this.logger.verbose(msg); - } - }; - Logger.prototype.warning = function (msg) { - if (this.logLevel === LogLevelType.None) return; - if (this.logger.warning && (this.logLevel === LogLevelType.Verbose || this.logLevel === LogLevelType.Warning)) { - this.logger.warning(msg); - } - }; - Logger.prototype.error = function (msg) { - if (this.logLevel === LogLevelType.None) return; - if (this.logger.error) { - this.logger.error(msg); - } - }; - Logger.prototype.setLogLevel = function (newLogLevel) { - this.logLevel = newLogLevel; - }; - return Logger; - }(); - var ConsoleLogger = /** @class */function () { - function ConsoleLogger() {} - ConsoleLogger.prototype.verbose = function (msg) { - if (console && console.info) { - console.info(msg); - } - }; - ConsoleLogger.prototype.error = function (msg) { - if (console && console.error) { - console.error(msg); - } - }; - ConsoleLogger.prototype.warning = function (msg) { - if (console && console.warn) { - console.warn(msg); - } - }; - return ConsoleLogger; - }(); - - var Base64 = Polyfill.Base64, - Messages$4 = Constants.Messages, - Base64CookieKeys = Constants.Base64CookieKeys, - SDKv2NonMPIDCookieKeys = Constants.SDKv2NonMPIDCookieKeys, - StorageNames = Constants.StorageNames; - function _Persistence(mpInstance) { - var self = this; - - // https://go.mparticle.com/work/SQDSDKS-5022 - this.useLocalStorage = function () { - return !mpInstance._Store.SDKConfig.useCookieStorage && mpInstance._Store.isLocalStorageAvailable; - }; - this.initializeStorage = function () { - try { - var storage, - localStorageData = self.getLocalStorage(), - cookies = self.getCookie(), - allData; - - // https://go.mparticle.com/work/SQDSDKS-6045 - // Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle - if (!localStorageData && !cookies) { - mpInstance._Store.isFirstRun = true; - mpInstance._Store.mpid = 0; - } else { - mpInstance._Store.isFirstRun = false; - } - - // https://go.mparticle.com/work/SQDSDKS-6045 - if (!mpInstance._Store.isLocalStorageAvailable) { - mpInstance._Store.SDKConfig.useCookieStorage = true; - } - - // https://go.mparticle.com/work/SQDSDKS-6046 - if (mpInstance._Store.isLocalStorageAvailable) { - storage = window.localStorage; - if (mpInstance._Store.SDKConfig.useCookieStorage) { - // For migrating from localStorage to cookies -- If an instance switches from localStorage to cookies, then - // no mParticle cookie exists yet and there is localStorage. Get the localStorage, set them to cookies, then delete the localStorage item. - if (localStorageData) { - if (cookies) { - // https://go.mparticle.com/work/SQDSDKS-6047 - allData = mpInstance._Helpers.extend(false, localStorageData, cookies); - } else { - allData = localStorageData; - } - storage.removeItem(mpInstance._Store.storageName); - } else if (cookies) { - allData = cookies; - } - self.storeDataInMemory(allData); - } else { - // For migrating from cookie to localStorage -- If an instance is newly switching from cookies to localStorage, then - // no mParticle localStorage exists yet and there are cookies. Get the cookies, set them to localStorage, then delete the cookies. - if (cookies) { - if (localStorageData) { - // https://go.mparticle.com/work/SQDSDKS-6047 - allData = mpInstance._Helpers.extend(false, localStorageData, cookies); - } else { - allData = cookies; - } - self.storeDataInMemory(allData); - self.expireCookies(mpInstance._Store.storageName); - } else { - self.storeDataInMemory(localStorageData); - } - } - } else { - self.storeDataInMemory(cookies); - } - - // https://go.mparticle.com/work/SQDSDKS-6046 - // Stores all non-current user MPID information into the store - for (var key in allData) { - if (allData.hasOwnProperty(key)) { - if (!SDKv2NonMPIDCookieKeys[key]) { - mpInstance._Store.nonCurrentUserMPIDs[key] = allData[key]; - } - } - } - self.update(); - } catch (e) { - // If cookies or local storage is corrupt, we want to remove it - // so that in the future, initializeStorage will work - if (self.useLocalStorage() && mpInstance._Store.isLocalStorageAvailable) { - localStorage.removeItem(mpInstance._Store.storageName); - } else { - self.expireCookies(mpInstance._Store.storageName); - } - mpInstance.Logger.error('Error initializing storage: ' + e); - } - }; - this.update = function () { - if (!mpInstance._Store.webviewBridgeEnabled) { - if (mpInstance._Store.SDKConfig.useCookieStorage) { - self.setCookie(); - } - self.setLocalStorage(); - } - }; - - // https://go.mparticle.com/work/SQDSDKS-6045 - this.storeDataInMemory = function (obj, currentMPID) { - try { - if (!obj) { - mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieNotFound); - mpInstance._Store.clientId = mpInstance._Store.clientId || mpInstance._Helpers.generateUniqueId(); - mpInstance._Store.deviceId = mpInstance._Store.deviceId || mpInstance._Helpers.generateUniqueId(); - } else { - // Set MPID first, then change object to match MPID data - if (currentMPID) { - mpInstance._Store.mpid = currentMPID; - } else { - mpInstance._Store.mpid = obj.cu || 0; - } - obj.gs = obj.gs || {}; - mpInstance._Store.sessionId = obj.gs.sid || mpInstance._Store.sessionId; - mpInstance._Store.isEnabled = typeof obj.gs.ie !== 'undefined' ? obj.gs.ie : mpInstance._Store.isEnabled; - mpInstance._Store.sessionAttributes = obj.gs.sa || mpInstance._Store.sessionAttributes; - mpInstance._Store.localSessionAttributes = obj.gs.lsa || mpInstance._Store.localSessionAttributes; - mpInstance._Store.serverSettings = obj.gs.ss || mpInstance._Store.serverSettings; - mpInstance._Store.devToken = mpInstance._Store.devToken || obj.gs.dt; - mpInstance._Store.SDKConfig.appVersion = mpInstance._Store.SDKConfig.appVersion || obj.gs.av; - mpInstance._Store.clientId = obj.gs.cgid || mpInstance._Store.clientId || mpInstance._Helpers.generateUniqueId(); - - // For most persistence values, we prioritize localstorage/cookie values over - // Store. However, we allow device ID to be overriden via a config value and - // thus the priority of the deviceId value is - // 1. value passed via config.deviceId - // 2. previous value in persistence - // 3. generate new guid - mpInstance._Store.deviceId = mpInstance._Store.deviceId || obj.gs.das || mpInstance._Helpers.generateUniqueId(); - mpInstance._Store.integrationAttributes = obj.gs.ia || {}; - mpInstance._Store.context = obj.gs.c || mpInstance._Store.context; - mpInstance._Store.currentSessionMPIDs = obj.gs.csm || mpInstance._Store.currentSessionMPIDs; - mpInstance._Store.isLoggedIn = obj.l === true; - if (obj.gs.les) { - mpInstance._Store.dateLastEventSent = new Date(obj.gs.les); - } - if (obj.gs.ssd) { - mpInstance._Store.sessionStartDate = new Date(obj.gs.ssd); - } else { - mpInstance._Store.sessionStartDate = new Date(); - } - if (currentMPID) { - obj = obj[currentMPID]; - } else { - obj = obj[obj.cu]; - } - } - } catch (e) { - mpInstance.Logger.error(Messages$4.ErrorMessages.CookieParseError); - } - }; - - // https://go.mparticle.com/work/SQDSDKS-5022 - this.determineLocalStorageAvailability = function (storage) { - var result; - if (window.mParticle && window.mParticle._forceNoLocalStorage) { - storage = undefined; - } - try { - storage.setItem('mparticle', 'test'); - result = storage.getItem('mparticle') === 'test'; - storage.removeItem('mparticle'); - return result && storage; - } catch (e) { - return false; - } - }; - - // https://go.mparticle.com/work/SQDSDKS-6021 - this.setLocalStorage = function () { - var _mpInstance$_CookieCo; - if (!mpInstance._Store.isLocalStorageAvailable) { - return; - } - - // Block mprtcl-v4 localStorage when noFunctional is true - if ((_mpInstance$_CookieCo = mpInstance._CookieConsentManager) !== null && _mpInstance$_CookieCo !== void 0 && _mpInstance$_CookieCo.getNoFunctional()) { - return; - } - var key = mpInstance._Store.storageName, - localStorageData = self.getLocalStorage() || {}, - currentUser = mpInstance.Identity.getCurrentUser(), - mpid = currentUser ? currentUser.getMPID() : null; - if (!mpInstance._Store.SDKConfig.useCookieStorage) { - localStorageData.gs = localStorageData.gs || {}; - localStorageData.l = mpInstance._Store.isLoggedIn ? 1 : 0; - if (mpInstance._Store.sessionId) { - localStorageData.gs.csm = mpInstance._Store.currentSessionMPIDs; - } - localStorageData.gs.ie = mpInstance._Store.isEnabled; - if (mpid) { - localStorageData.cu = mpid; - } - if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) { - localStorageData = mpInstance._Helpers.extend({}, localStorageData, mpInstance._Store.nonCurrentUserMPIDs); - mpInstance._Store.nonCurrentUserMPIDs = {}; - } - localStorageData = setGlobalStorageAttributes(localStorageData); - try { - window.localStorage.setItem(encodeURIComponent(key), self.encodePersistence(JSON.stringify(localStorageData))); - } catch (e) { - mpInstance.Logger.error('Error with setting localStorage item.'); - } - } - }; - function setGlobalStorageAttributes(data) { - var store = mpInstance._Store; - data.gs.sid = store.sessionId; - data.gs.ie = store.isEnabled; - data.gs.sa = store.sessionAttributes; - data.gs.lsa = store.localSessionAttributes; - data.gs.ss = store.serverSettings; - data.gs.dt = store.devToken; - data.gs.les = store.dateLastEventSent ? store.dateLastEventSent.getTime() : null; - data.gs.av = store.SDKConfig.appVersion; - data.gs.cgid = store.clientId; - data.gs.das = store.deviceId; - data.gs.c = store.context; - data.gs.ssd = store.sessionStartDate ? store.sessionStartDate.getTime() : 0; - data.gs.ia = store.integrationAttributes; - return data; - } - this.getLocalStorage = function () { - if (!mpInstance._Store.isLocalStorageAvailable) { - return null; - } - var key = mpInstance._Store.storageName, - localStorageData = self.decodePersistence(window.localStorage.getItem(key)), - obj = {}, - j; - if (localStorageData) { - localStorageData = JSON.parse(localStorageData); - for (j in localStorageData) { - if (localStorageData.hasOwnProperty(j)) { - obj[j] = localStorageData[j]; - } - } - } - if (Object.keys(obj).length) { - return obj; - } - return null; - }; - function removeLocalStorage(localStorageName) { - localStorage.removeItem(localStorageName); - } - this.expireCookies = function (cookieName) { - var date = new Date(), - expires, - domain, - cookieDomain; - cookieDomain = self.getCookieDomain(); - if (cookieDomain === '') { - domain = ''; - } else { - domain = ';domain=' + cookieDomain; - } - date.setTime(date.getTime() - 24 * 60 * 60 * 1000); - expires = '; expires=' + date.toUTCString(); - document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain; - }; - this.getCookie = function () { - var cookies, - key = mpInstance._Store.storageName, - i, - l, - parts, - name, - cookie, - result = key ? undefined : {}; - mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSearch); - try { - cookies = window.document.cookie.split('; '); - } catch (e) { - mpInstance.Logger.verbose('Unable to parse undefined cookie'); - return null; - } - for (i = 0, l = cookies.length; i < l; i++) { - try { - parts = cookies[i].split('='); - name = parts.shift(); - cookie = parts.join('='); - } catch (e) { - mpInstance.Logger.verbose('Unable to parse cookie: ' + name + '. Skipping.'); - } - if (key && key === name) { - result = mpInstance._Helpers.converted(cookie); - break; - } - if (!key) { - result[name] = mpInstance._Helpers.converted(cookie); - } - } - if (result) { - mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieFound); - return JSON.parse(self.decodePersistence(result)); - } else { - return null; - } - }; - - // https://go.mparticle.com/work/SQDSDKS-5022 - // https://go.mparticle.com/work/SQDSDKS-6021 - this.setCookie = function () { - var _mpInstance$_CookieCo2; - // Block mprtcl-v4 cookies when noFunctional is true - if ((_mpInstance$_CookieCo2 = mpInstance._CookieConsentManager) !== null && _mpInstance$_CookieCo2 !== void 0 && _mpInstance$_CookieCo2.getNoFunctional()) { - return; - } - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(); - if (currentUser) { - mpid = currentUser.getMPID(); - } - var date = new Date(), - key = mpInstance._Store.storageName, - cookies = self.getCookie() || {}, - expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000).toGMTString(), - cookieDomain, - domain, - encodedCookiesWithExpirationAndPath; - cookieDomain = self.getCookieDomain(); - if (cookieDomain === '') { - domain = ''; - } else { - domain = ';domain=' + cookieDomain; - } - cookies.gs = cookies.gs || {}; - if (mpInstance._Store.sessionId) { - cookies.gs.csm = mpInstance._Store.currentSessionMPIDs; - } - if (mpid) { - cookies.cu = mpid; - } - cookies.l = mpInstance._Store.isLoggedIn ? 1 : 0; - cookies = setGlobalStorageAttributes(cookies); - if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) { - cookies = mpInstance._Helpers.extend({}, cookies, mpInstance._Store.nonCurrentUserMPIDs); - mpInstance._Store.nonCurrentUserMPIDs = {}; - } - encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(cookies, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize); - mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSet); - window.document.cookie = encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath; - }; - - /* This function determines if a cookie is greater than the configured maxCookieSize. - - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie. - - Once removed, check size, and repeat. - - Never remove the currentUser's MPID from the cookie. - MPID removal priority: - 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie. - 2. If there are currentSessionMPIDs: - a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs - b. Then remove MPIDs based on order in currentSessionMPIDs array, which - stores MPIDs based on earliest login. - */ - this.reduceAndEncodePersistence = function (persistence, expires, domain, maxCookieSize) { - var encodedCookiesWithExpirationAndPath, - currentSessionMPIDs = persistence.gs.csm ? persistence.gs.csm : []; - // Comment 1 above - if (!currentSessionMPIDs.length) { - for (var key in persistence) { - if (persistence.hasOwnProperty(key)) { - encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); - if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { - if (!SDKv2NonMPIDCookieKeys[key] && key !== persistence.cu) { - delete persistence[key]; - } - } - } - } - } else { - // Comment 2 above - First create an object of all MPIDs on the cookie - var MPIDsOnCookie = {}; - for (var potentialMPID in persistence) { - if (persistence.hasOwnProperty(potentialMPID)) { - if (!SDKv2NonMPIDCookieKeys[potentialMPID] && potentialMPID !== persistence.cu) { - MPIDsOnCookie[potentialMPID] = 1; - } - } - } - // Comment 2a above - if (Object.keys(MPIDsOnCookie).length) { - for (var mpid in MPIDsOnCookie) { - encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); - if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { - if (MPIDsOnCookie.hasOwnProperty(mpid)) { - if (currentSessionMPIDs.indexOf(mpid) === -1) { - delete persistence[mpid]; - } - } - } - } - } - // Comment 2b above - for (var i = 0; i < currentSessionMPIDs.length; i++) { - encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); - if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { - var MPIDtoRemove = currentSessionMPIDs[i]; - if (persistence[MPIDtoRemove]) { - mpInstance.Logger.verbose('Size of new encoded cookie is larger than maxCookieSize setting of ' + maxCookieSize + '. Removing from cookie the earliest logged in MPID containing: ' + JSON.stringify(persistence[MPIDtoRemove], 0, 2)); - delete persistence[MPIDtoRemove]; - } else { - mpInstance.Logger.error('Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' + maxCookieSize + '. We recommend using a maxCookieSize of 1500.'); - } - } else { - break; - } - } - } - return encodedCookiesWithExpirationAndPath; - }; - function createFullEncodedCookie(persistence, expires, domain) { - return self.encodePersistence(JSON.stringify(persistence)) + ';expires=' + expires + ';path=/' + domain; - } - this.findPrevCookiesBasedOnUI = function (identityApiData) { - var persistence = mpInstance._Persistence.getPersistence(); - var matchedUser; - if (identityApiData) { - for (var requestedIdentityType in identityApiData.userIdentities) { - if (persistence && Object.keys(persistence).length) { - for (var key in persistence) { - // any value in persistence that has an MPID key will be an MPID to search through - // other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched - if (persistence[key].mpid) { - var cookieUIs = persistence[key].ui; - for (var cookieUIType in cookieUIs) { - if (requestedIdentityType === cookieUIType && identityApiData.userIdentities[requestedIdentityType] === cookieUIs[cookieUIType]) { - matchedUser = key; - break; - } - } - } - } - } - } - } - if (matchedUser) { - self.storeDataInMemory(persistence, matchedUser); - } - }; - this.encodePersistence = function (persistence) { - persistence = JSON.parse(persistence); - for (var key in persistence.gs) { - if (persistence.gs.hasOwnProperty(key)) { - if (Base64CookieKeys[key]) { - if (persistence.gs[key]) { - // base64 encode any value that is an object or Array in globalSettings - if (Array.isArray(persistence.gs[key]) && persistence.gs[key].length || mpInstance._Helpers.isObject(persistence.gs[key]) && Object.keys(persistence.gs[key]).length) { - persistence.gs[key] = Base64.encode(JSON.stringify(persistence.gs[key])); - } else { - delete persistence.gs[key]; - } - } else { - delete persistence.gs[key]; - } - } else if (key === 'ie') { - persistence.gs[key] = persistence.gs[key] ? 1 : 0; - } else if (!persistence.gs[key]) { - delete persistence.gs[key]; - } - } - } - for (var mpid in persistence) { - if (persistence.hasOwnProperty(mpid)) { - if (!SDKv2NonMPIDCookieKeys[mpid]) { - for (key in persistence[mpid]) { - if (persistence[mpid].hasOwnProperty(key)) { - if (Base64CookieKeys[key]) { - if (mpInstance._Helpers.isObject(persistence[mpid][key]) && Object.keys(persistence[mpid][key]).length) { - persistence[mpid][key] = Base64.encode(JSON.stringify(persistence[mpid][key])); - } else { - delete persistence[mpid][key]; - } - } - } - } - } - } - } - return createCookieString(JSON.stringify(persistence)); - }; - - // TODO: This should actually be decodePersistenceString or - // we should refactor this to take a string and return an object - this.decodePersistence = function (persistence) { - try { - if (persistence) { - persistence = JSON.parse(revertCookieString(persistence)); - if (mpInstance._Helpers.isObject(persistence) && Object.keys(persistence).length) { - for (var key in persistence.gs) { - if (persistence.gs.hasOwnProperty(key)) { - if (Base64CookieKeys[key]) { - persistence.gs[key] = JSON.parse(Base64.decode(persistence.gs[key])); - } else if (key === 'ie') { - persistence.gs[key] = Boolean(persistence.gs[key]); - } - } - } - for (var mpid in persistence) { - if (persistence.hasOwnProperty(mpid)) { - if (!SDKv2NonMPIDCookieKeys[mpid]) { - for (key in persistence[mpid]) { - if (persistence[mpid].hasOwnProperty(key)) { - if (Base64CookieKeys[key]) { - if (persistence[mpid][key].length) { - persistence[mpid][key] = JSON.parse(Base64.decode(persistence[mpid][key])); - } - } - } - } - } else if (mpid === 'l') { - persistence[mpid] = Boolean(persistence[mpid]); - } - } - } - } - return JSON.stringify(persistence); - } - } catch (e) { - mpInstance.Logger.error('Problem with decoding cookie', e); - } - }; - this.getCookieDomain = function () { - if (mpInstance._Store.SDKConfig.cookieDomain) { - return mpInstance._Store.SDKConfig.cookieDomain; - } else { - var rootDomain = self.getDomain(document, location.hostname); - if (rootDomain === '') { - return ''; - } else { - return '.' + rootDomain; - } - } - }; - - // This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible. - // For example subdomain.domain.co.uk would try the following combinations: - // "co.uk" -> fail - // "domain.co.uk" -> success, return - // "subdomain.domain.co.uk" -> skipped, because already found - this.getDomain = function (doc, locationHostname) { - var i, - testParts, - mpTest = 'mptest=cookie', - hostname = locationHostname.split('.'); - for (i = hostname.length - 1; i >= 0; i--) { - testParts = hostname.slice(i).join('.'); - doc.cookie = mpTest + ';domain=.' + testParts + ';'; - if (doc.cookie.indexOf(mpTest) > -1) { - doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;'; - return testParts; - } - } - return ''; - }; - this.saveUserCookieSyncDatesToPersistence = function (mpid, csd) { - if (csd) { - var persistence = self.getPersistence(); - if (persistence) { - if (persistence[mpid]) { - persistence[mpid].csd = csd; - } else { - persistence[mpid] = { - csd: csd - }; - } - } - self.savePersistence(persistence); - } - }; - this.swapCurrentUser = function (previousMPID, currentMPID, currentSessionMPIDs) { - if (previousMPID && currentMPID && previousMPID !== currentMPID) { - var persistence = self.getPersistence(); - if (persistence) { - persistence.cu = currentMPID; - persistence.gs.csm = currentSessionMPIDs; - self.savePersistence(persistence); - } - } - }; - - // https://go.mparticle.com/work/SQDSDKS-6021 - this.savePersistence = function (persistence) { - var _mpInstance$_CookieCo3; - // Block mprtcl-v4 persistence when noFunctional is true - if ((_mpInstance$_CookieCo3 = mpInstance._CookieConsentManager) !== null && _mpInstance$_CookieCo3 !== void 0 && _mpInstance$_CookieCo3.getNoFunctional()) { - return; - } - var encodedPersistence = self.encodePersistence(JSON.stringify(persistence)), - date = new Date(), - key = mpInstance._Store.storageName, - expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000).toGMTString(), - cookieDomain = self.getCookieDomain(), - domain; - if (cookieDomain === '') { - domain = ''; - } else { - domain = ';domain=' + cookieDomain; - } - if (mpInstance._Store.SDKConfig.useCookieStorage) { - var encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(persistence, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize); - window.document.cookie = encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath; - } else { - if (mpInstance._Store.isLocalStorageAvailable) { - localStorage.setItem(mpInstance._Store.storageName, encodedPersistence); - } - } - }; - this.getPersistence = function () { - var persistence = this.useLocalStorage() ? this.getLocalStorage() : this.getCookie(); - return persistence; - }; - this.getFirstSeenTime = function (mpid) { - if (!mpid) { - return null; - } - var persistence = self.getPersistence(); - if (persistence && persistence[mpid] && persistence[mpid].fst) { - return persistence[mpid].fst; - } else { - return null; - } - }; - - /** - * set the "first seen" time for a user. the time will only be set once for a given - * mpid after which subsequent calls will be ignored - */ - this.setFirstSeenTime = function (mpid, time) { - if (!mpid) { - return; - } - // https://go.mparticle.com/work/SQDSDKS-6329 - if (!time) { - time = new Date().getTime(); - } - var persistence = self.getPersistence(); - if (persistence) { - if (!persistence[mpid]) { - persistence[mpid] = {}; - } - if (!persistence[mpid].fst) { - persistence[mpid].fst = time; - self.savePersistence(persistence); - } - } - }; - - /** - * returns the "last seen" time for a user. If the mpid represents the current user, the - * return value will always be the current time, otherwise it will be to stored "last seen" - * time - */ - this.getLastSeenTime = function (mpid) { - if (!mpid) { - return null; - } - if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) { - //if the mpid is the current user, its last seen time is the current time - return new Date().getTime(); - } else { - var persistence = self.getPersistence(); - if (persistence && persistence[mpid] && persistence[mpid].lst) { - return persistence[mpid].lst; - } - return null; - } - }; - this.setLastSeenTime = function (mpid, time) { - if (!mpid) { - return; - } - // https://go.mparticle.com/work/SQDSDKS-6329 - if (!time) { - time = new Date().getTime(); - } - var persistence = self.getPersistence(); - if (persistence && persistence[mpid]) { - persistence[mpid].lst = time; - self.savePersistence(persistence); - } - }; - this.getDeviceId = function () { - return mpInstance._Store.deviceId; - }; - this.setDeviceId = function (guid) { - mpInstance._Store.deviceId = guid; - self.update(); - }; - this.resetPersistence = function () { - localStorage.clear(); - self.expireCookies(StorageNames.cookieName); - self.expireCookies(StorageNames.cookieNameV2); - self.expireCookies(StorageNames.cookieNameV3); - self.expireCookies(StorageNames.cookieNameV4); - self.expireCookies(mpInstance._Store.storageName); - if (mParticle._isTestEnv) { - var testWorkspaceToken = 'abcdef'; - removeLocalStorage(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); - self.expireCookies(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); - } - }; - - // https://go.mparticle.com/work/SQDSDKS-6045 - // Forwarder Batching Code - this.forwardingStatsBatches = { - uploadsTable: {}, - forwardingStatsEventQueue: [] - }; - } - - var Messages$3 = Constants.Messages; - function Events(mpInstance) { - var self = this; - this.logEvent = function (event, options) { - mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogEvent + ': ' + event.name); - if (mpInstance._Helpers.canLog()) { - var uploadObject = mpInstance._ServerModel.createEventObject(event); - mpInstance._APIClient.sendEventToServer(uploadObject, options); - } else { - mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); - } - }; - this.startTracking = function (callback) { - if (!mpInstance._Store.isTracking) { - if ('geolocation' in navigator) { - mpInstance._Store.watchPositionId = navigator.geolocation.watchPosition(successTracking, errorTracking); - } - } else { - var position = { - coords: { - latitude: mpInstance._Store.currentPosition.lat, - longitude: mpInstance._Store.currentPosition.lng - } - }; - triggerCallback(callback, position); - } - function successTracking(position) { - mpInstance._Store.currentPosition = { - lat: position.coords.latitude, - lng: position.coords.longitude - }; - triggerCallback(callback, position); - // prevents callback from being fired multiple times - callback = null; - mpInstance._Store.isTracking = true; - } - function errorTracking() { - triggerCallback(callback); - // prevents callback from being fired multiple times - callback = null; - mpInstance._Store.isTracking = false; - } - function triggerCallback(callback, position) { - if (callback) { - try { - if (position) { - callback(position); - } else { - callback(); - } - } catch (e) { - mpInstance.Logger.error('Error invoking the callback passed to startTrackingLocation.'); - mpInstance.Logger.error(e); - } - } - } - }; - this.stopTracking = function () { - if (mpInstance._Store.isTracking) { - navigator.geolocation.clearWatch(mpInstance._Store.watchPositionId); - mpInstance._Store.currentPosition = null; - mpInstance._Store.isTracking = false; - } - }; - this.logOptOut = function () { - mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut); - var event = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.OptOut, - eventType: Types.EventType.Other - }); - mpInstance._APIClient.sendEventToServer(event); - }; - this.logAST = function () { - self.logEvent({ - messageType: Types.MessageType.AppStateTransition - }); - }; - this.logCheckoutEvent = function (step, option, attrs, customFlags) { - var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); - if (event) { - event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout); - event.EventCategory = Types.CommerceEventType.ProductCheckout; - event.ProductAction = { - ProductActionType: Types.ProductActionType.Checkout, - CheckoutStep: step, - CheckoutOptions: option, - ProductList: [] - }; - self.logCommerceEvent(event, attrs); - } - }; - this.logProductActionEvent = function (productActionType, product, customAttrs, customFlags, transactionAttributes, options) { - var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags, options); - var productList = Array.isArray(product) ? product : [product]; - productList.forEach(function (product) { - if (product.TotalAmount) { - product.TotalAmount = mpInstance._Ecommerce.sanitizeAmount(product.TotalAmount, 'TotalAmount'); - } - if (product.Position) { - product.Position = mpInstance._Ecommerce.sanitizeAmount(product.Position, 'Position'); - } - if (product.Price) { - product.Price = mpInstance._Ecommerce.sanitizeAmount(product.Price, 'Price'); - } - if (product.Quantity) { - product.Quantity = mpInstance._Ecommerce.sanitizeAmount(product.Quantity, 'Quantity'); - } - }); - if (event) { - event.EventCategory = mpInstance._Ecommerce.convertProductActionToEventType(productActionType); - event.EventName += mpInstance._Ecommerce.getProductActionEventName(productActionType); - event.ProductAction = { - ProductActionType: productActionType, - ProductList: productList - }; - if (mpInstance._Helpers.isObject(transactionAttributes)) { - mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); - } - self.logCommerceEvent(event, customAttrs, options); - } - }; - this.logPurchaseEvent = function (transactionAttributes, product, attrs, customFlags) { - var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); - if (event) { - event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase); - event.EventCategory = Types.CommerceEventType.ProductPurchase; - event.ProductAction = { - ProductActionType: Types.ProductActionType.Purchase - }; - event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product); - mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); - self.logCommerceEvent(event, attrs); - } - }; - this.logRefundEvent = function (transactionAttributes, product, attrs, customFlags) { - if (!transactionAttributes) { - mpInstance.Logger.error(Messages$3.ErrorMessages.TransactionRequired); - return; - } - var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); - if (event) { - event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund); - event.EventCategory = Types.CommerceEventType.ProductRefund; - event.ProductAction = { - ProductActionType: Types.ProductActionType.Refund - }; - event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product); - mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); - self.logCommerceEvent(event, attrs); - } - }; - this.logPromotionEvent = function (promotionType, promotion, attrs, customFlags, eventOptions) { - var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); - if (event) { - event.EventName += mpInstance._Ecommerce.getPromotionActionEventName(promotionType); - event.EventCategory = mpInstance._Ecommerce.convertPromotionActionToEventType(promotionType); - event.PromotionAction = { - PromotionActionType: promotionType, - PromotionList: Array.isArray(promotion) ? promotion : [promotion] - }; - self.logCommerceEvent(event, attrs, eventOptions); - } - }; - this.logImpressionEvent = function (impression, attrs, customFlags, options) { - var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); - if (event) { - event.EventName += 'Impression'; - event.EventCategory = Types.CommerceEventType.ProductImpression; - if (!Array.isArray(impression)) { - impression = [impression]; - } - event.ProductImpressions = []; - impression.forEach(function (impression) { - event.ProductImpressions.push({ - ProductImpressionList: impression.Name, - ProductList: Array.isArray(impression.Product) ? impression.Product : [impression.Product] - }); - }); - self.logCommerceEvent(event, attrs, options); - } - }; - this.logCommerceEvent = function (commerceEvent, attrs, options) { - mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent); - - // If a developer typos the ProductActionType, the event category will be - // null, resulting in kit forwarding errors on the server. - // The check for `ProductAction` is required to denote that these are - // ProductAction events, and not impression or promotions - if (commerceEvent.ProductAction && commerceEvent.EventCategory === null) { - mpInstance.Logger.error('Commerce event not sent. The mParticle.ProductActionType you passed was invalid. Re-check your code.'); - return; - } - attrs = mpInstance._Helpers.sanitizeAttributes(attrs, commerceEvent.EventName); - if (mpInstance._Helpers.canLog()) { - if (mpInstance._Store.webviewBridgeEnabled) { - // Don't send shopping cart to parent sdks - commerceEvent.ShoppingCart = {}; - } - if (attrs) { - commerceEvent.EventAttributes = attrs; - } - mpInstance._APIClient.sendEventToServer(commerceEvent, options); - - // https://go.mparticle.com/work/SQDSDKS-6038 - mpInstance._Persistence.update(); - } else { - mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); - } - }; - this.addEventHandler = function (domEvent, selector, eventName, data, eventType) { - var elements = [], - handler = function handler(e) { - var timeoutHandler = function timeoutHandler() { - if (element.href) { - window.location.href = element.href; - } else if (element.submit) { - element.submit(); - } - }; - mpInstance.Logger.verbose('DOM event triggered, handling event'); - self.logEvent({ - messageType: Types.MessageType.PageEvent, - name: typeof eventName === 'function' ? eventName(element) : eventName, - data: typeof data === 'function' ? data(element) : data, - eventType: eventType || Types.EventType.Other - }); - - // TODO: Handle middle-clicks and special keys (ctrl, alt, etc) - if (element.href && element.target !== '_blank' || element.submit) { - // Give xmlhttprequest enough time to execute before navigating a link or submitting form - - if (e.preventDefault) { - e.preventDefault(); - } else { - e.returnValue = false; - } - setTimeout(timeoutHandler, mpInstance._Store.SDKConfig.timeout); - } - }, - element, - i; - if (!selector) { - mpInstance.Logger.error("Can't bind event, selector is required"); - return; - } - - // Handle a css selector string or a dom element - if (typeof selector === 'string') { - elements = document.querySelectorAll(selector); - } else if (selector.nodeType) { - elements = [selector]; - } - if (elements.length) { - mpInstance.Logger.verbose('Found ' + elements.length + ' element' + (elements.length > 1 ? 's' : '') + ', attaching event handlers'); - for (i = 0; i < elements.length; i++) { - element = elements[i]; - if (element.addEventListener) { - // Modern browsers - element.addEventListener(domEvent, handler, false); - } else if (element.attachEvent) { - // IE < 9 - element.attachEvent('on' + domEvent, handler); - } else { - // All other browsers - element['on' + domEvent] = handler; - } - } - } else { - mpInstance.Logger.verbose('No elements found'); - } - }; - } - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - _next(undefined); - }); - }; - } - - var regeneratorRuntime$1 = {exports: {}}; - - var _typeof = {exports: {}}; - - _typeof.exports; - - (function (module) { - function _typeof(o) { - "@babel/helpers - typeof"; - - return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { - return typeof o; - } : function (o) { - return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; - }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o); - } - module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; - } (_typeof)); - - var _typeofExports = _typeof.exports; - - regeneratorRuntime$1.exports; - - (function (module) { - var _typeof = _typeofExports["default"]; - function _regeneratorRuntime() { - module.exports = _regeneratorRuntime = function _regeneratorRuntime() { - return e; - }, module.exports.__esModule = true, module.exports["default"] = module.exports; - var t, - e = {}, - r = Object.prototype, - n = r.hasOwnProperty, - o = Object.defineProperty || function (t, e, r) { - t[e] = r.value; - }, - i = "function" == typeof Symbol ? Symbol : {}, - a = i.iterator || "@@iterator", - c = i.asyncIterator || "@@asyncIterator", - u = i.toStringTag || "@@toStringTag"; - function define(t, e, r) { - return Object.defineProperty(t, e, { - value: r, - enumerable: !0, - configurable: !0, - writable: !0 - }), t[e]; - } - try { - define({}, ""); - } catch (t) { - define = function define(t, e, r) { - return t[e] = r; - }; - } - function wrap(t, e, r, n) { - var i = e && e.prototype instanceof Generator ? e : Generator, - a = Object.create(i.prototype), - c = new Context(n || []); - return o(a, "_invoke", { - value: makeInvokeMethod(t, r, c) - }), a; - } - function tryCatch(t, e, r) { - try { - return { - type: "normal", - arg: t.call(e, r) - }; - } catch (t) { - return { - type: "throw", - arg: t - }; - } - } - e.wrap = wrap; - var h = "suspendedStart", - l = "suspendedYield", - f = "executing", - s = "completed", - y = {}; - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - var p = {}; - define(p, a, function () { - return this; - }); - var d = Object.getPrototypeOf, - v = d && d(d(values([]))); - v && v !== r && n.call(v, a) && (p = v); - var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); - function defineIteratorMethods(t) { - ["next", "throw", "return"].forEach(function (e) { - define(t, e, function (t) { - return this._invoke(e, t); - }); - }); - } - function AsyncIterator(t, e) { - function invoke(r, o, i, a) { - var c = tryCatch(t[r], t, o); - if ("throw" !== c.type) { - var u = c.arg, - h = u.value; - return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { - invoke("next", t, i, a); - }, function (t) { - invoke("throw", t, i, a); - }) : e.resolve(h).then(function (t) { - u.value = t, i(u); - }, function (t) { - return invoke("throw", t, i, a); - }); - } - a(c.arg); - } - var r; - o(this, "_invoke", { - value: function value(t, n) { - function callInvokeWithMethodAndArg() { - return new e(function (e, r) { - invoke(t, n, e, r); - }); - } - return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - } - }); - } - function makeInvokeMethod(e, r, n) { - var o = h; - return function (i, a) { - if (o === f) throw new Error("Generator is already running"); - if (o === s) { - if ("throw" === i) throw a; - return { - value: t, - done: !0 - }; - } - for (n.method = i, n.arg = a;;) { - var c = n.delegate; - if (c) { - var u = maybeInvokeDelegate(c, n); - if (u) { - if (u === y) continue; - return u; - } - } - if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { - if (o === h) throw o = s, n.arg; - n.dispatchException(n.arg); - } else "return" === n.method && n.abrupt("return", n.arg); - o = f; - var p = tryCatch(e, r, n); - if ("normal" === p.type) { - if (o = n.done ? s : l, p.arg === y) continue; - return { - value: p.arg, - done: n.done - }; - } - "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); - } - }; - } - function maybeInvokeDelegate(e, r) { - var n = r.method, - o = e.iterator[n]; - if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; - var i = tryCatch(o, e.iterator, r.arg); - if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; - var a = i.arg; - return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); - } - function pushTryEntry(t) { - var e = { - tryLoc: t[0] - }; - 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); - } - function resetTryEntry(t) { - var e = t.completion || {}; - e.type = "normal", delete e.arg, t.completion = e; - } - function Context(t) { - this.tryEntries = [{ - tryLoc: "root" - }], t.forEach(pushTryEntry, this), this.reset(!0); - } - function values(e) { - if (e || "" === e) { - var r = e[a]; - if (r) return r.call(e); - if ("function" == typeof e.next) return e; - if (!isNaN(e.length)) { - var o = -1, - i = function next() { - for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; - return next.value = t, next.done = !0, next; - }; - return i.next = i; - } - } - throw new TypeError(_typeof(e) + " is not iterable"); - } - return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { - value: GeneratorFunctionPrototype, - configurable: !0 - }), o(GeneratorFunctionPrototype, "constructor", { - value: GeneratorFunction, - configurable: !0 - }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { - var e = "function" == typeof t && t.constructor; - return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); - }, e.mark = function (t) { - return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; - }, e.awrap = function (t) { - return { - __await: t - }; - }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { - return this; - }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { - void 0 === i && (i = Promise); - var a = new AsyncIterator(wrap(t, r, n, o), i); - return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { - return t.done ? t.value : a.next(); - }); - }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { - return this; - }), define(g, "toString", function () { - return "[object Generator]"; - }), e.keys = function (t) { - var e = Object(t), - r = []; - for (var n in e) r.push(n); - return r.reverse(), function next() { - for (; r.length;) { - var t = r.pop(); - if (t in e) return next.value = t, next.done = !1, next; - } - return next.done = !0, next; - }; - }, e.values = values, Context.prototype = { - constructor: Context, - reset: function reset(e) { - if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); - }, - stop: function stop() { - this.done = !0; - var t = this.tryEntries[0].completion; - if ("throw" === t.type) throw t.arg; - return this.rval; - }, - dispatchException: function dispatchException(e) { - if (this.done) throw e; - var r = this; - function handle(n, o) { - return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; - } - for (var o = this.tryEntries.length - 1; o >= 0; --o) { - var i = this.tryEntries[o], - a = i.completion; - if ("root" === i.tryLoc) return handle("end"); - if (i.tryLoc <= this.prev) { - var c = n.call(i, "catchLoc"), - u = n.call(i, "finallyLoc"); - if (c && u) { - if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); - if (this.prev < i.finallyLoc) return handle(i.finallyLoc); - } else if (c) { - if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); - } else { - if (!u) throw new Error("try statement without catch or finally"); - if (this.prev < i.finallyLoc) return handle(i.finallyLoc); - } - } - } - }, - abrupt: function abrupt(t, e) { - for (var r = this.tryEntries.length - 1; r >= 0; --r) { - var o = this.tryEntries[r]; - if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { - var i = o; - break; - } - } - i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); - var a = i ? i.completion : {}; - return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); - }, - complete: function complete(t, e) { - if ("throw" === t.type) throw t.arg; - return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; - }, - finish: function finish(t) { - for (var e = this.tryEntries.length - 1; e >= 0; --e) { - var r = this.tryEntries[e]; - if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; - } - }, - "catch": function _catch(t) { - for (var e = this.tryEntries.length - 1; e >= 0; --e) { - var r = this.tryEntries[e]; - if (r.tryLoc === t) { - var n = r.completion; - if ("throw" === n.type) { - var o = n.arg; - resetTryEntry(r); - } - return o; - } - } - throw new Error("illegal catch attempt"); - }, - delegateYield: function delegateYield(e, r, n) { - return this.delegate = { - iterator: values(e), - resultName: r, - nextLoc: n - }, "next" === this.method && (this.arg = t), y; - } - }, e; - } - module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; - } (regeneratorRuntime$1)); - - var regeneratorRuntimeExports = regeneratorRuntime$1.exports; - - // TODO(Babel 8): Remove this file. - - var runtime = regeneratorRuntimeExports(); - var regenerator = runtime; - - // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - if (typeof globalThis === "object") { - globalThis.regeneratorRuntime = runtime; - } else { - Function("r", "regeneratorRuntime = r")(runtime); - } - } - - var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator); - - function filteredMparticleUser(mpid, forwarder, mpInstance, kitBlocker) { - var self = this; - return { - getUserIdentities: function getUserIdentities() { - var currentUserIdentities = {}; - var identities = mpInstance._Store.getUserIdentities(mpid); - for (var identityType in identities) { - if (identities.hasOwnProperty(identityType)) { - var identityName = Types.IdentityType.getIdentityName(mpInstance._Helpers.parseNumber(identityType)); - if (!kitBlocker || kitBlocker && !kitBlocker.isIdentityBlocked(identityName)) - //if identity type is not blocked - currentUserIdentities[identityName] = identities[identityType]; - } - } - currentUserIdentities = mpInstance._Helpers.filterUserIdentitiesForForwarders(currentUserIdentities, forwarder.userIdentityFilters); - return { - userIdentities: currentUserIdentities - }; - }, - getMPID: function getMPID() { - return mpid; - }, - getUserAttributesLists: function getUserAttributesLists(forwarder) { - var userAttributes, - userAttributesLists = {}; - userAttributes = self.getAllUserAttributes(); - for (var key in userAttributes) { - if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) { - if (!kitBlocker || kitBlocker && !kitBlocker.isAttributeKeyBlocked(key)) { - userAttributesLists[key] = userAttributes[key].slice(); - } - } - } - userAttributesLists = mpInstance._Helpers.filterUserAttributes(userAttributesLists, forwarder.userAttributeFilters); - return userAttributesLists; - }, - getAllUserAttributes: function getAllUserAttributes() { - var userAttributesCopy = {}; - var userAttributes = mpInstance._Store.getUserAttributes(mpid); - if (userAttributes) { - for (var prop in userAttributes) { - if (userAttributes.hasOwnProperty(prop)) { - if (!kitBlocker || kitBlocker && !kitBlocker.isAttributeKeyBlocked(prop)) { - if (Array.isArray(userAttributes[prop])) { - userAttributesCopy[prop] = userAttributes[prop].slice(); - } else { - userAttributesCopy[prop] = userAttributes[prop]; - } - } - } - } - } - userAttributesCopy = mpInstance._Helpers.filterUserAttributes(userAttributesCopy, forwarder.userAttributeFilters); - return userAttributesCopy; - } - }; - } - - var _Constants$IdentityMe = Constants.IdentityMethods, - Modify$2 = _Constants$IdentityMe.Modify, - Identify$1 = _Constants$IdentityMe.Identify, - Login$1 = _Constants$IdentityMe.Login, - Logout$1 = _Constants$IdentityMe.Logout; - function Forwarders(mpInstance, kitBlocker) { - var _this = this; - var self = this; - this.forwarderStatsUploader = new APIClient(mpInstance, kitBlocker).initializeForwarderStatsUploader(); - var UserAttributeActionTypes = { - setUserAttribute: 'setUserAttribute', - removeUserAttribute: 'removeUserAttribute' - }; - this.initForwarders = function (userIdentities, forwardingStatsCallback) { - var user = mpInstance.Identity.getCurrentUser(); - if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.configuredForwarders) { - // Some js libraries require that they be loaded first, or last, etc - mpInstance._Store.configuredForwarders.sort(function (x, y) { - x.settings.PriorityValue = x.settings.PriorityValue || 0; - y.settings.PriorityValue = y.settings.PriorityValue || 0; - return -1 * (x.settings.PriorityValue - y.settings.PriorityValue); - }); - mpInstance._Store.activeForwarders = mpInstance._Store.configuredForwarders.filter(function (forwarder) { - if (!mpInstance._Consent.isEnabledForUserConsent(forwarder.filteringConsentRuleValues, user)) { - return false; - } - if (!self.isEnabledForUserAttributes(forwarder.filteringUserAttributeValue, user)) { - return false; - } - if (!self.isEnabledForUnknownUser(forwarder.excludeAnonymousUser, user)) { - return false; - } - var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters); - var filteredUserAttributes = mpInstance._Helpers.filterUserAttributes(user ? user.getAllUserAttributes() : {}, forwarder.userAttributeFilters); - if (!forwarder.initialized) { - forwarder.logger = mpInstance.Logger; - forwarder.init(forwarder.settings, forwardingStatsCallback, false, null, filteredUserAttributes, filteredUserIdentities, mpInstance._Store.SDKConfig.appVersion, mpInstance._Store.SDKConfig.appName, mpInstance._Store.SDKConfig.customFlags, mpInstance._Store.clientId); - forwarder.initialized = true; - } - return true; - }); - } - }; - this.isEnabledForUserAttributes = function (filterObject, user) { - if (!filterObject || !mpInstance._Helpers.isObject(filterObject) || !Object.keys(filterObject).length) { - return true; - } - var attrHash, valueHash, userAttributes; - if (!user) { - return false; - } else { - userAttributes = user.getAllUserAttributes(); - } - var isMatch = false; - try { - if (userAttributes && mpInstance._Helpers.isObject(userAttributes) && Object.keys(userAttributes).length) { - for (var attrName in userAttributes) { - if (userAttributes.hasOwnProperty(attrName)) { - attrHash = KitFilterHelper.hashAttributeConditionalForwarding(attrName); - valueHash = KitFilterHelper.hashAttributeConditionalForwarding(userAttributes[attrName]); - if (attrHash === filterObject.userAttributeName && valueHash === filterObject.userAttributeValue) { - isMatch = true; - break; - } - } - } - } - if (filterObject) { - return filterObject.includeOnMatch === isMatch; - } else { - return true; - } - } catch (e) { - // in any error scenario, err on side of returning true and forwarding event - return true; - } - }; - this.isEnabledForUnknownUser = function (excludeAnonymousUserBoolean, user) { - if (!user || !user.isLoggedIn()) { - if (excludeAnonymousUserBoolean) { - return false; - } - } - return true; - }; - this.applyToForwarders = function (functionName, functionArgs) { - if (mpInstance._Store.activeForwarders.length) { - mpInstance._Store.activeForwarders.forEach(function (forwarder) { - var forwarderFunction = forwarder[functionName]; - if (forwarderFunction) { - try { - var result = forwarder[functionName](functionArgs); - if (result) { - mpInstance.Logger.verbose(result); - } - } catch (e) { - mpInstance.Logger.verbose(e); - } - } - }); - } - }; - this.sendEventToForwarders = function (event) { - var clonedEvent, - hashedEventName, - hashedEventType, - filterUserIdentities = function filterUserIdentities(event, filterList) { - if (event.UserIdentities && event.UserIdentities.length) { - event.UserIdentities.forEach(function (userIdentity, i) { - if (mpInstance._Helpers.inArray(filterList, KitFilterHelper.hashUserIdentity(userIdentity.Type))) { - event.UserIdentities.splice(i, 1); - if (i > 0) { - i--; - } - } - }); - } - }, - filterAttributes = function filterAttributes(event, filterList) { - var hash; - if (!filterList) { - return; - } - for (var attrName in event.EventAttributes) { - if (event.EventAttributes.hasOwnProperty(attrName)) { - hash = KitFilterHelper.hashEventAttributeKey(event.EventCategory, event.EventName, attrName); - if (mpInstance._Helpers.inArray(filterList, hash)) { - delete event.EventAttributes[attrName]; - } - } - } - }, - inFilteredList = function inFilteredList(filterList, hash) { - if (filterList && filterList.length) { - if (mpInstance._Helpers.inArray(filterList, hash)) { - return true; - } - } - return false; - }, - forwardingRuleMessageTypes = [Types.MessageType.PageEvent, Types.MessageType.PageView, Types.MessageType.Commerce]; - if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.activeForwarders) { - hashedEventName = KitFilterHelper.hashEventName(event.EventName, event.EventCategory); - hashedEventType = KitFilterHelper.hashEventType(event.EventCategory); - for (var i = 0; i < mpInstance._Store.activeForwarders.length; i++) { - // Check attribute forwarding rule. This rule allows users to only forward an event if a - // specific attribute exists and has a specific value. Alternatively, they can specify - // that an event not be forwarded if the specified attribute name and value exists. - // The two cases are controlled by the "includeOnMatch" boolean value. - // Supported message types for attribute forwarding rules are defined in the forwardingRuleMessageTypes array - - if (forwardingRuleMessageTypes.indexOf(event.EventDataType) > -1 && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue) { - var foundProp = null; - - // Attempt to find the attribute in the collection of event attributes - if (event.EventAttributes) { - for (var prop in event.EventAttributes) { - var hashedEventAttributeName; - hashedEventAttributeName = KitFilterHelper.hashAttributeConditionalForwarding(prop); - if (hashedEventAttributeName === mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName) { - foundProp = { - name: hashedEventAttributeName, - value: KitFilterHelper.hashAttributeConditionalForwarding(event.EventAttributes[prop]) - }; - } - if (foundProp) { - break; - } - } - } - var isMatch = foundProp !== null && foundProp.value === mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue; - var shouldInclude = mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.includeOnMatch === true ? isMatch : !isMatch; - if (!shouldInclude) { - continue; - } - } - - // Clone the event object, as we could be sending different attributes to each forwarder - clonedEvent = {}; - clonedEvent = mpInstance._Helpers.extend(true, clonedEvent, event); - // Check event filtering rules - if (event.EventDataType === Types.MessageType.PageEvent && (inFilteredList(mpInstance._Store.activeForwarders[i].eventNameFilters, hashedEventName) || inFilteredList(mpInstance._Store.activeForwarders[i].eventTypeFilters, hashedEventType))) { - continue; - } else if (event.EventDataType === Types.MessageType.Commerce && inFilteredList(mpInstance._Store.activeForwarders[i].eventTypeFilters, hashedEventType)) { - continue; - } else if (event.EventDataType === Types.MessageType.PageView && inFilteredList(mpInstance._Store.activeForwarders[i].screenNameFilters, hashedEventName)) { - continue; - } - - // Check attribute filtering rules - if (clonedEvent.EventAttributes) { - if (event.EventDataType === Types.MessageType.PageEvent) { - filterAttributes(clonedEvent, mpInstance._Store.activeForwarders[i].attributeFilters); - } else if (event.EventDataType === Types.MessageType.PageView) { - filterAttributes(clonedEvent, mpInstance._Store.activeForwarders[i].screenAttributeFilters); - } - } - - // Check user identity filtering rules - filterUserIdentities(clonedEvent, mpInstance._Store.activeForwarders[i].userIdentityFilters); - - // Check user attribute filtering rules - clonedEvent.UserAttributes = mpInstance._Helpers.filterUserAttributes(clonedEvent.UserAttributes, mpInstance._Store.activeForwarders[i].userAttributeFilters); - if (mpInstance._Store.activeForwarders[i].process) { - mpInstance.Logger.verbose('Sending message to forwarder: ' + mpInstance._Store.activeForwarders[i].name); - var result = mpInstance._Store.activeForwarders[i].process(clonedEvent); - if (result) { - mpInstance.Logger.verbose(result); - } - } - } - } - }; - this.handleForwarderUserAttributes = function (functionNameKey, key, value) { - if (kitBlocker && kitBlocker.isAttributeKeyBlocked(key) || !mpInstance._Store.activeForwarders.length) { - return; - } - mpInstance._Store.activeForwarders.forEach(function (forwarder) { - var forwarderFunction = forwarder[functionNameKey]; - if (!forwarderFunction || KitFilterHelper.isFilteredUserAttribute(key, forwarder.userAttributeFilters)) { - return; - } - try { - var result; - if (functionNameKey === UserAttributeActionTypes.setUserAttribute) { - result = forwarder.setUserAttribute(key, value); - } else if (functionNameKey === UserAttributeActionTypes.removeUserAttribute) { - result = forwarder.removeUserAttribute(key); - } - if (result) { - mpInstance.Logger.verbose(result); - } - } catch (e) { - mpInstance.Logger.error(e); - } - }); - }; - - // TODO: https://go.mparticle.com/work/SQDSDKS-6036 - this.setForwarderUserIdentities = function (userIdentities) { - mpInstance._Store.activeForwarders.forEach(function (forwarder) { - var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters); - if (forwarder.setUserIdentity) { - filteredUserIdentities.forEach(function (identity) { - var result = forwarder.setUserIdentity(identity.Identity, identity.Type); - if (result) { - mpInstance.Logger.verbose(result); - } - }); - } - }); - }; - this.setForwarderOnUserIdentified = function (user) { - mpInstance._Store.activeForwarders.forEach(function (forwarder) { - var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); - if (forwarder.onUserIdentified) { - var result = forwarder.onUserIdentified(filteredUser); - if (result) { - mpInstance.Logger.verbose(result); - } - } - }); - }; - this.setForwarderOnIdentityComplete = function (user, identityMethod) { - var result; - mpInstance._Store.activeForwarders.forEach(function (forwarder) { - var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); - var filteredUserIdentities = filteredUser.getUserIdentities(); - if (identityMethod === Identify$1) { - if (forwarder.onIdentifyComplete) { - result = forwarder.onIdentifyComplete(filteredUser, filteredUserIdentities); - if (result) { - mpInstance.Logger.verbose(result); - } - } - } else if (identityMethod === Login$1) { - if (forwarder.onLoginComplete) { - result = forwarder.onLoginComplete(filteredUser, filteredUserIdentities); - if (result) { - mpInstance.Logger.verbose(result); - } - } - } else if (identityMethod === Logout$1) { - if (forwarder.onLogoutComplete) { - result = forwarder.onLogoutComplete(filteredUser, filteredUserIdentities); - if (result) { - mpInstance.Logger.verbose(result); - } - } - } else if (identityMethod === Modify$2) { - if (forwarder.onModifyComplete) { - result = forwarder.onModifyComplete(filteredUser, filteredUserIdentities); - if (result) { - mpInstance.Logger.verbose(result); - } - } - } - }); - }; - this.getForwarderStatsQueue = function () { - return mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue; - }; - this.setForwarderStatsQueue = function (queue) { - mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue; - }; - - // Processing forwarders is a 2 step process: - // 1. Configure the kit - // 2. Initialize the kit - // There are 2 types of kits: - // 1. UI-enabled kits - // 2. Sideloaded kits. - this.processForwarders = function (config, forwardingStatsCallback) { - if (!config) { - mpInstance.Logger.warning('No config was passed. Cannot process forwarders'); - } else { - this.processUIEnabledKits(config); - this.processSideloadedKits(config); - self.initForwarders(mpInstance._Store.SDKConfig.identifyRequest.userIdentities, forwardingStatsCallback); - } - }; - - // These are kits that are enabled via the mParticle UI. - // A kit that is UI-enabled will have a kit configuration that returns from - // the server, or in rare cases, is passed in by the developer. - // The kit configuration will be compared with the kit constructors to determine - // if there is a match before being initialized. - // Only kits that are configured properly can be active and used for kit forwarding. - this.processUIEnabledKits = function (config) { - var kits = this.returnKitConstructors(); - try { - if (Array.isArray(config.kitConfigs) && config.kitConfigs.length) { - config.kitConfigs.forEach(function (kitConfig) { - self.configureUIEnabledKit(kitConfig, kits); - }); - } - } catch (e) { - mpInstance.Logger.error('MP Kits not configured propertly. Kits may not be initialized. ' + e); - } - }; - this.returnKitConstructors = function () { - var kits = {}; - // If there are kits inside of mpInstance._Store.SDKConfig.kits, then mParticle is self hosted - if (!isEmpty(mpInstance._Store.SDKConfig.kits)) { - kits = mpInstance._Store.SDKConfig.kits; - // otherwise mParticle is loaded via script tag - } else if (!isEmpty(mpInstance._preInit.forwarderConstructors)) { - mpInstance._preInit.forwarderConstructors.forEach(function (kitConstructor) { - // A suffix is added to a kitConstructor and kit config if there are multiple different - // versions of a client kit. This matches the suffix in the DB. As an example - // the GA4 kit has a client kit and a server side kit which has a client side - // component. They share the same name/module ID in the DB, so we include a - // suffix to distinguish them in the kits object. - // If a customer wanted simultaneous GA4 client and server connections, - // a suffix allows the SDK to distinguish the two. - if (kitConstructor.suffix) { - var kitNameWithConstructorSuffix = "".concat(kitConstructor.name, "-").concat(kitConstructor.suffix); - kits[kitNameWithConstructorSuffix] = kitConstructor; - } else { - kits[kitConstructor.name] = kitConstructor; - } - }); - } - return kits; - }; - this.configureUIEnabledKit = function (configuration, kits) { - var newKit = null; - var config = configuration; - for (var name in kits) { - // Configs are returned with suffixes also. We need to consider the - // config suffix here to match the constructor suffix - var kitNameWithConfigSuffix = void 0; - if (config.suffix) { - kitNameWithConfigSuffix = "".concat(config.name, "-").concat(config.suffix); - } - if (name === kitNameWithConfigSuffix || name === config.name) { - if (config.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || config.isSandbox === mpInstance._Store.SDKConfig.isDevelopmentMode) { - newKit = this.returnConfiguredKit(kits[name], config); - mpInstance._Store.configuredForwarders.push(newKit); - break; - } - } - } - }; - - // Unlike UI enabled kits, sideloaded kits are always added to active forwarders. - - // TODO: Sideloading kits currently require the use of a register method - // which requires an object on which to be registered. - // In the future, when all kits are moved to the mpConfig rather than - // there being a separate process for MP configured kits and - // sideloaded kits, this will need to be refactored. - this.processSideloadedKits = function (mpConfig) { - try { - if (Array.isArray(mpConfig.sideloadedKits)) { - var registeredSideloadedKits = { - kits: {} - }; - var unregisteredSideloadedKits = mpConfig.sideloadedKits; - unregisteredSideloadedKits.forEach(function (unregisteredKit) { - try { - // Register each sideloaded kit, which adds a key of the sideloaded kit name - // and a value of the sideloaded kit constructor. - unregisteredKit.kitInstance.register(registeredSideloadedKits); - var kitName = unregisteredKit.kitInstance.name; - // Then add the kit filters to each registered kit. - registeredSideloadedKits.kits[kitName].filters = unregisteredKit.filterDictionary; - } catch (e) { - console.error('Error registering sideloaded kit ' + unregisteredKit.kitInstance.name); - } - }); - - // Then configure each registered kit - for (var registeredKitKey in registeredSideloadedKits.kits) { - var registeredKit = registeredSideloadedKits.kits[registeredKitKey]; - self.configureSideloadedKit(registeredKit); - } - - // If Sideloaded Kits are successfully registered, - // record this in the Store. - if (!isEmpty(registeredSideloadedKits.kits)) { - var kitKeys = Object.keys(registeredSideloadedKits.kits); - mpInstance._Store.sideloadedKitsCount = kitKeys.length; - } - } - } catch (e) { - mpInstance.Logger.error('Sideloaded Kits not configured propertly. Kits may not be initialized. ' + e); - } - }; - - // kits can be included via mParticle UI, or via sideloaded kit config API - this.configureSideloadedKit = function (kitConstructor) { - mpInstance._Store.configuredForwarders.push(this.returnConfiguredKit(kitConstructor, kitConstructor.filters)); - }; - this.returnConfiguredKit = function (forwarder) { - var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var newForwarder = new forwarder.constructor(); - newForwarder.id = config.moduleId; - - // TODO: isSandbox, hasSandbox is never used in any kit or in core SDK. - // isVisible. Investigate is only used in 1 place. It is always true if - // it is sent to JS. Investigate further to determine if these can be removed. - // https://go.mparticle.com/work/SQDSDKS-5156 - newForwarder.isSandbox = config.isDebug || config.isSandbox; - newForwarder.hasSandbox = config.hasDebugString === 'true'; - newForwarder.isVisible = config.isVisible || true; - newForwarder.settings = config.settings || {}; - newForwarder.eventNameFilters = config.eventNameFilters || []; - newForwarder.eventTypeFilters = config.eventTypeFilters || []; - newForwarder.attributeFilters = config.attributeFilters || []; - newForwarder.screenNameFilters = config.screenNameFilters || []; - newForwarder.screenAttributeFilters = config.screenAttributeFilters || []; - newForwarder.userIdentityFilters = config.userIdentityFilters || []; - newForwarder.userAttributeFilters = config.userAttributeFilters || []; - newForwarder.filteringEventAttributeValue = config.filteringEventAttributeValue || {}; - newForwarder.filteringUserAttributeValue = config.filteringUserAttributeValue || {}; - newForwarder.eventSubscriptionId = config.eventSubscriptionId || null; - newForwarder.filteringConsentRuleValues = config.filteringConsentRuleValues || {}; - newForwarder.excludeAnonymousUser = config.excludeAnonymousUser || false; - return newForwarder; - }; - this.configurePixel = function (settings) { - if (settings.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || settings.isProduction !== mpInstance._Store.SDKConfig.isDevelopmentMode) { - mpInstance._Store.pixelConfigurations.push(settings); - } - }; - this.processPixelConfigs = function (config) { - try { - if (!isEmpty(config.pixelConfigs)) { - config.pixelConfigs.forEach(function (pixelConfig) { - self.configurePixel(pixelConfig); - }); - } - } catch (e) { - mpInstance.Logger.error('Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. ' + e); - } - }; - this.sendSingleForwardingStatsToServer = /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(forwardingStatsData) { - var _mpInstance$Logger; - var fetchPayload, response, message; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - // https://go.mparticle.com/work/SQDSDKS-6568 - fetchPayload = { - method: 'post', - body: JSON.stringify(forwardingStatsData), - headers: { - Accept: 'text/plain;charset=UTF-8', - 'Content-Type': 'text/plain;charset=UTF-8' - } - }; - _context.next = 3; - return _this.forwarderStatsUploader.upload(fetchPayload); - case 3: - response = _context.sent; - // This is a fire and forget, so we only need to log the response based on the code, and not return any response body - if (response.status === 202) { - // https://go.mparticle.com/work/SQDSDKS-6670 - message = 'Successfully sent forwarding stats to mParticle Servers'; - } else { - message = 'Issue with forwarding stats to mParticle Servers, received HTTP Code of ' + response.statusText; - } - mpInstance === null || mpInstance === void 0 || (_mpInstance$Logger = mpInstance.Logger) === null || _mpInstance$Logger === void 0 || _mpInstance$Logger.verbose(message); - case 6: - case "end": - return _context.stop(); - } - }, _callee); - })); - return function (_x) { - return _ref.apply(this, arguments); - }; - }(); - } - - // TODO: This file is no longer the server model because the web SDK payload - var MessageType = Types.MessageType; - var ApplicationTransitionType = Types.ApplicationTransitionType; - // TODO: Make this a pure function that returns a new object - function convertCustomFlags(event, dto) { - var valueArray = []; - dto.flags = {}; - for (var prop in event.CustomFlags) { - valueArray = []; - if (event.CustomFlags.hasOwnProperty(prop)) { - if (Array.isArray(event.CustomFlags[prop])) { - event.CustomFlags[prop].forEach(function (customFlagProperty) { - if (isValidCustomFlagProperty(customFlagProperty)) { - valueArray.push(customFlagProperty.toString()); - } - }); - } else if (isValidCustomFlagProperty(event.CustomFlags[prop])) { - valueArray.push(event.CustomFlags[prop].toString()); - } - if (valueArray.length) { - dto.flags[prop] = valueArray; - } - } - } - } - function convertProductToV2DTO(product) { - return { - id: parseStringOrNumber(product.Sku), - nm: parseStringOrNumber(product.Name), - pr: parseNumber(product.Price), - qt: parseNumber(product.Quantity), - br: parseStringOrNumber(product.Brand), - va: parseStringOrNumber(product.Variant), - ca: parseStringOrNumber(product.Category), - ps: parseNumber(product.Position), - cc: parseStringOrNumber(product.CouponCode), - tpa: parseNumber(product.TotalAmount), - attrs: product.Attributes - }; - } - function convertProductListToV2DTO(productList) { - if (!productList) { - return []; - } - return productList.map(function (product) { - return convertProductToV2DTO(product); - }); - } - function ServerModel(mpInstance) { - var self = this; - this.convertToConsentStateV2DTO = function (state) { - if (!state) { - return null; - } - var jsonObject = {}; - var gdprConsentState = state.getGDPRConsentState(); - if (gdprConsentState) { - var gdpr = {}; - jsonObject.gdpr = gdpr; - for (var purpose in gdprConsentState) { - if (gdprConsentState.hasOwnProperty(purpose)) { - var gdprConsent = gdprConsentState[purpose]; - jsonObject.gdpr[purpose] = {}; - if (typeof gdprConsent.Consented === 'boolean') { - gdpr[purpose].c = gdprConsent.Consented; - } - if (typeof gdprConsent.Timestamp === 'number') { - gdpr[purpose].ts = gdprConsent.Timestamp; - } - if (typeof gdprConsent.ConsentDocument === 'string') { - gdpr[purpose].d = gdprConsent.ConsentDocument; - } - if (typeof gdprConsent.Location === 'string') { - gdpr[purpose].l = gdprConsent.Location; - } - if (typeof gdprConsent.HardwareId === 'string') { - gdpr[purpose].h = gdprConsent.HardwareId; - } - } - } - } - var ccpaConsentState = state.getCCPAConsentState(); - if (ccpaConsentState) { - jsonObject.ccpa = { - data_sale_opt_out: { - c: ccpaConsentState.Consented, - ts: ccpaConsentState.Timestamp, - d: ccpaConsentState.ConsentDocument, - l: ccpaConsentState.Location, - h: ccpaConsentState.HardwareId - } - }; - } - return jsonObject; - }; - this.createEventObject = function (event, user) { - var _a; - var uploadObject = {}; - var eventObject = {}; - // The `optOut` variable is passed later in this method to the `uploadObject` - // so that it can be used to denote whether or not a user has "opted out" of being - // tracked. If this is an `optOut` Event, we set `optOut` to the inverse of the SDK's - // `isEnabled` boolean which is controlled via `MPInstanceManager.setOptOut`. - var optOut = event.messageType === Types.MessageType.OptOut ? !mpInstance._Store.isEnabled : null; - // TODO: Why is Webview Bridge Enabled or Opt Out necessary here? - if (mpInstance._Store.sessionId || event.messageType === Types.MessageType.OptOut || mpInstance._Store.webviewBridgeEnabled) { - var customFlags = __assign({}, event.customFlags); - var integrationAttributes = mpInstance._Store.integrationAttributes; - var getFeatureFlag = mpInstance._Helpers.getFeatureFlag; - // https://go.mparticle.com/work/SQDSDKS-5053 - // https://go.mparticle.com/work/SQDSDKS-7639 - var integrationSpecificIds = getFeatureFlag && getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds); - var integrationSpecificIdsV2 = getFeatureFlag && (getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || ''); - var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; - if (isIntegrationCaptureEnabled) { - // Attempt to recapture click IDs in case a third party integration - // has added or updated new click IDs since the last event was sent. - mpInstance._IntegrationCapture.capture(); - var transformedClickIDs = mpInstance._IntegrationCapture.getClickIdsAsCustomFlags(); - customFlags = __assign(__assign({}, transformedClickIDs), customFlags); - var transformedIntegrationAttributes = mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes(); - integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes); - } - if (event.hasOwnProperty('toEventAPIObject')) { - eventObject = event.toEventAPIObject(); - } else { - eventObject = { - // This is an artifact from v2 events where SessionStart/End and AST event - // names are numbers (1, 2, or 10), but going forward with v3, these lifecycle - // events do not have names, but are denoted by their `event_type` - EventName: event.name || event.messageType, - EventCategory: event.eventType, - EventAttributes: mpInstance._Helpers.sanitizeAttributes(event.data, event.name), - ActiveTimeOnSite: (_a = mpInstance._timeOnSiteTimer) === null || _a === void 0 ? void 0 : _a.getTimeInForeground(), - SourceMessageId: event.sourceMessageId || mpInstance._Helpers.generateUniqueId(), - EventDataType: event.messageType, - CustomFlags: customFlags, - UserAttributeChanges: event.userAttributeChanges, - UserIdentityChanges: event.userIdentityChanges - }; - } - // TODO: Should we move this side effect outside of this method? - if (event.messageType !== Types.MessageType.SessionEnd) { - mpInstance._Store.dateLastEventSent = new Date(); - } - uploadObject = { - // FIXME: Deprecate when we get rid of V2 - Store: mpInstance._Store.serverSettings, - SDKVersion: Constants.sdkVersion, - SessionId: mpInstance._Store.sessionId, - SessionStartDate: mpInstance._Store.sessionStartDate ? mpInstance._Store.sessionStartDate.getTime() : 0, - Debug: mpInstance._Store.SDKConfig.isDevelopmentMode, - Location: mpInstance._Store.currentPosition, - OptOut: optOut, - ExpandedEventCount: 0, - AppVersion: mpInstance.getAppVersion(), - AppName: mpInstance.getAppName(), - Package: mpInstance._Store.SDKConfig["package"], - ClientGeneratedId: mpInstance._Store.clientId, - DeviceId: mpInstance._Store.deviceId, - IntegrationAttributes: integrationAttributes, - CurrencyCode: mpInstance._Store.currencyCode, - DataPlan: mpInstance._Store.SDKConfig.dataPlan ? mpInstance._Store.SDKConfig.dataPlan : {} - }; - if (eventObject.EventDataType === MessageType.AppStateTransition) { - eventObject.IsFirstRun = mpInstance._Store.isFirstRun; - eventObject.LaunchReferral = window.location.href || null; - } - // FIXME: Remove duplicate occurence - eventObject.CurrencyCode = mpInstance._Store.currencyCode; - var currentUser = user || mpInstance.Identity.getCurrentUser(); - appendUserInfo(currentUser, eventObject); - if (event.messageType === Types.MessageType.SessionEnd) { - eventObject.SessionLength = mpInstance._Store.dateLastEventSent.getTime() - mpInstance._Store.sessionStartDate.getTime(); - eventObject.currentSessionMPIDs = mpInstance._Store.currentSessionMPIDs; - // Session attributes are assigned on a session level, but only uploaded - // when a session ends. As there is no way to attach event attributes to - // a `SessionEnd` event, we are uploading the session level attributes - // as event level attributes in a `SessionEnd` event. - eventObject.EventAttributes = mpInstance._Store.sessionAttributes; - // TODO: We should move this out of here to avoid side effects - mpInstance._Store.currentSessionMPIDs = []; - mpInstance._Store.sessionStartDate = null; - } - uploadObject.Timestamp = mpInstance._Store.dateLastEventSent.getTime(); - return mpInstance._Helpers.extend({}, eventObject, uploadObject); - } - return null; - }; - this.convertEventToV2DTO = function (event) { - var dto = { - n: event.EventName, - et: event.EventCategory, - ua: event.UserAttributes, - ui: event.UserIdentities, - ia: event.IntegrationAttributes, - str: event.Store, - attrs: event.EventAttributes, - sdk: event.SDKVersion, - sid: event.SessionId, - sl: event.SessionLength, - ssd: event.SessionStartDate, - dt: event.EventDataType, - dbg: event.Debug, - ct: event.Timestamp, - lc: event.Location, - o: event.OptOut, - eec: event.ExpandedEventCount, - av: event.AppVersion, - cgid: event.ClientGeneratedId, - das: event.DeviceId, - mpid: event.MPID, - smpids: event.currentSessionMPIDs - }; - if (event.DataPlan && event.DataPlan.PlanId) { - dto.dp_id = event.DataPlan.PlanId; - if (event.DataPlan.PlanVersion) { - dto.dp_v = event.DataPlan.PlanVersion; - } - } - var consent = self.convertToConsentStateV2DTO(event.ConsentState); - if (consent) { - dto.con = consent; - } - if (event.EventDataType === MessageType.AppStateTransition) { - dto.fr = event.IsFirstRun; - dto.iu = false; - dto.at = ApplicationTransitionType.AppInit; - dto.lr = event.LaunchReferral; - // Nullify Attributes in case AST Was logged manually or - // via logBaseEvent. AST should not have any attributes - dto.attrs = null; - } - if (event.CustomFlags) { - convertCustomFlags(event, dto); - } - if (event.EventDataType === MessageType.Commerce) { - dto.cu = event.CurrencyCode; - // TODO: If Cart is deprecated, we should deprecate this too - if (event.ShoppingCart) { - dto.sc = { - pl: convertProductListToV2DTO(event.ShoppingCart.ProductList) - }; - } - if (event.ProductAction) { - dto.pd = { - an: event.ProductAction.ProductActionType, - cs: mpInstance._Helpers.parseNumber(event.ProductAction.CheckoutStep), - co: event.ProductAction.CheckoutOptions, - pl: convertProductListToV2DTO(event.ProductAction.ProductList), - ti: event.ProductAction.TransactionId, - ta: event.ProductAction.Affiliation, - tcc: event.ProductAction.CouponCode, - tr: mpInstance._Helpers.parseNumber(event.ProductAction.TotalAmount), - ts: mpInstance._Helpers.parseNumber(event.ProductAction.ShippingAmount), - tt: mpInstance._Helpers.parseNumber(event.ProductAction.TaxAmount) - }; - } else if (event.PromotionAction) { - dto.pm = { - an: event.PromotionAction.PromotionActionType, - pl: event.PromotionAction.PromotionList.map(function (promotion) { - return { - id: promotion.Id, - nm: promotion.Name, - cr: promotion.Creative, - ps: promotion.Position ? promotion.Position : 0 - }; - }) - }; - } else if (event.ProductImpressions) { - dto.pi = event.ProductImpressions.map(function (impression) { - return { - pil: impression.ProductImpressionList, - pl: convertProductListToV2DTO(impression.ProductList) - }; - }); - } - } else if (event.EventDataType === MessageType.Profile) { - dto.pet = event.ProfileMessageType; - } - return dto; - }; - } - - function forwardingStatsUploader(mpInstance) { - this.startForwardingStatsTimer = function () { - mParticle._forwardingStatsTimer = setInterval(function () { - prepareAndSendForwardingStatsBatch(); - }, mpInstance._Store.SDKConfig.forwarderStatsTimeout); - }; - function prepareAndSendForwardingStatsBatch() { - var forwarderQueue = mpInstance._Forwarders.getForwarderStatsQueue(), - uploadsTable = mpInstance._Persistence.forwardingStatsBatches.uploadsTable, - now = Date.now(); - if (forwarderQueue.length) { - uploadsTable[now] = { - uploading: false, - data: forwarderQueue - }; - mpInstance._Forwarders.setForwarderStatsQueue([]); - } - for (var date in uploadsTable) { - (function (date) { - if (uploadsTable.hasOwnProperty(date)) { - if (uploadsTable[date].uploading === false) { - var xhrCallback = function xhrCallback() { - if (xhr.readyState === 4) { - if (xhr.status === 200 || xhr.status === 202) { - mpInstance.Logger.verbose('Successfully sent ' + xhr.statusText + ' from server'); - delete uploadsTable[date]; - } else if (xhr.status.toString()[0] === '4') { - if (xhr.status !== 429) { - delete uploadsTable[date]; - } - } else { - uploadsTable[date].uploading = false; - } - } - }; - var xhr = mpInstance._Helpers.createXHR(xhrCallback); - var forwardingStatsData = uploadsTable[date].data; - uploadsTable[date].uploading = true; - mpInstance._APIClient.sendBatchForwardingStatsToServer(forwardingStatsData, xhr); - } - } - })(date); - } - } - } - - var AudienceManager = /** @class */function () { - function AudienceManager(userAudienceUrl, apiKey, logger) { - this.url = ''; - this.logger = logger; - this.url = "https://".concat(userAudienceUrl).concat(apiKey, "/audience"); - this.userAudienceAPI = window.fetch ? new FetchUploader(this.url) : new XHRUploader(this.url); - } - AudienceManager.prototype.sendGetUserAudienceRequest = function (mpid, callback) { - return __awaiter(this, void 0, void 0, function () { - var fetchPayload, audienceURLWithMPID, userAudiencePromise, userAudienceMembershipsServerResponse, parsedUserAudienceMemberships, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.logger.verbose('Fetching user audiences from server'); - fetchPayload = { - method: 'GET', - headers: { - Accept: '*/*' - } - }; - audienceURLWithMPID = "".concat(this.url, "?mpid=").concat(mpid); - _a.label = 1; - case 1: - _a.trys.push([1, 6,, 7]); - return [4 /*yield*/, this.userAudienceAPI.upload(fetchPayload, audienceURLWithMPID)]; - case 2: - userAudiencePromise = _a.sent(); - if (!(userAudiencePromise.status >= 200 && userAudiencePromise.status < 300)) return [3 /*break*/, 4]; - this.logger.verbose("User Audiences successfully received"); - return [4 /*yield*/, userAudiencePromise.json()]; - case 3: - userAudienceMembershipsServerResponse = _a.sent(); - parsedUserAudienceMemberships = { - currentAudienceMemberships: userAudienceMembershipsServerResponse === null || userAudienceMembershipsServerResponse === void 0 ? void 0 : userAudienceMembershipsServerResponse.audience_memberships - }; - try { - callback(parsedUserAudienceMemberships); - } catch (e) { - throw new Error('Error invoking callback on user audience response.'); - } - return [3 /*break*/, 5]; - case 4: - if (userAudiencePromise.status === 401) { - throw new Error('`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`'); - } else if (userAudiencePromise.status === 403) { - throw new Error('`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`'); - } else { - // In case there is an HTTP error we did not anticipate. - throw new Error("Uncaught HTTP Error ".concat(userAudiencePromise.status, ".")); - } - case 5: - return [3 /*break*/, 7]; - case 6: - e_1 = _a.sent(); - this.logger.error("Error retrieving audiences. ".concat(e_1)); - return [3 /*break*/, 7]; - case 7: - return [2 /*return*/]; - } - }); - }); - }; - - return AudienceManager; - }(); - - var processReadyQueue = function processReadyQueue(readyQueue) { - if (!isEmpty(readyQueue)) { - readyQueue.forEach(function (readyQueueItem) { - if (isFunction(readyQueueItem)) { - readyQueueItem(); - } else if (Array.isArray(readyQueueItem)) { - processPreloadedItem(readyQueueItem); - } - }); - } - return []; - }; - var processPreloadedItem = function processPreloadedItem(readyQueueItem) { - var args = readyQueueItem; - var method = args.splice(0, 1)[0]; - // if the first argument is a method on the base mParticle object, run it - if (typeof window !== 'undefined' && window.mParticle && window.mParticle[args[0]]) { - window.mParticle[method].apply(window.mParticle, args); - // otherwise, the method is on either eCommerce or Identity objects, ie. "eCommerce.setCurrencyCode", "Identity.login" - } else { - var methodArray = method.split('.'); - try { - var computedMPFunction = window.mParticle; - var context_1 = window.mParticle; - // Track both the function and its context - for (var _i = 0, methodArray_1 = methodArray; _i < methodArray_1.length; _i++) { - var currentMethod = methodArray_1[_i]; - context_1 = computedMPFunction; // Keep track of the parent object - computedMPFunction = computedMPFunction[currentMethod]; - } - // Apply the function with its proper context - computedMPFunction.apply(context_1, args); - } catch (e) { - throw new Error('Unable to compute proper mParticle function ' + e); - } - } - }; - - var Messages$2 = Constants.Messages, - HTTPCodes$2 = Constants.HTTPCodes, - FeatureFlags$1 = Constants.FeatureFlags, - IdentityMethods$1 = Constants.IdentityMethods; - var ErrorMessages = Messages$2.ErrorMessages; - var CacheIdentity = FeatureFlags$1.CacheIdentity; - var Identify = IdentityMethods$1.Identify, - Modify$1 = IdentityMethods$1.Modify, - Login = IdentityMethods$1.Login, - Logout = IdentityMethods$1.Logout; - function Identity(mpInstance) { - var _mpInstance$_Helpers = mpInstance._Helpers, - getFeatureFlag = _mpInstance$_Helpers.getFeatureFlag, - extend = _mpInstance$_Helpers.extend; - var self = this; - this.idCache = null; - this.audienceManager = null; - - // https://go.mparticle.com/work/SQDSDKS-6353 - this.IdentityRequest = { - preProcessIdentityRequest: function preProcessIdentityRequest(identityApiData, callback, method) { - mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent + ': ' + method); - - // First, remove any falsy identity values and warn about them - var cleanedIdentityApiData = mpInstance._Helpers.Validators.removeFalsyIdentityValues(identityApiData, mpInstance.Logger); - var identityValidationResult = mpInstance._Helpers.Validators.validateIdentities(cleanedIdentityApiData, method); - if (!identityValidationResult.valid) { - mpInstance.Logger.error('ERROR: ' + identityValidationResult.error); - return { - valid: false, - error: identityValidationResult.error - }; - } - if (callback && !mpInstance._Helpers.Validators.isFunction(callback)) { - var error = 'The optional callback must be a function. You tried entering a(n) ' + _typeof$1(callback); - mpInstance.Logger.error(error); - return { - valid: false, - error: error - }; - } - return { - valid: true, - cleanedIdentities: cleanedIdentityApiData - }; - }, - createIdentityRequest: function createIdentityRequest(identityApiData, platform, sdkVendor, sdkVersion, deviceId, context, mpid) { - var APIRequest = { - client_sdk: { - platform: platform, - sdk_vendor: sdkVendor, - sdk_version: sdkVersion - }, - context: context, - environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? 'development' : 'production', - request_id: mpInstance._Helpers.generateUniqueId(), - request_timestamp_ms: new Date().getTime(), - previous_mpid: mpid || null, - known_identities: createKnownIdentities(identityApiData, deviceId) - }; - return APIRequest; - }, - createModifyIdentityRequest: function createModifyIdentityRequest(currentUserIdentities, newUserIdentities, platform, sdkVendor, sdkVersion, context) { - return { - client_sdk: { - platform: platform, - sdk_vendor: sdkVendor, - sdk_version: sdkVersion - }, - context: context, - environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? 'development' : 'production', - request_id: mpInstance._Helpers.generateUniqueId(), - request_timestamp_ms: new Date().getTime(), - identity_changes: this.createIdentityChanges(currentUserIdentities, newUserIdentities) - }; - }, - createIdentityChanges: function createIdentityChanges(previousIdentities, newIdentities) { - var identityChanges = []; - var key; - if (newIdentities && isObject(newIdentities) && previousIdentities && isObject(previousIdentities)) { - for (key in newIdentities) { - identityChanges.push({ - old_value: previousIdentities[key] || null, - new_value: newIdentities[key], - identity_type: key - }); - } - } - return identityChanges; - }, - // takes 2 UI objects keyed by name, combines them, returns them keyed by type - combineUserIdentities: function combineUserIdentities(previousUIByName, newUIByName) { - var combinedUIByType = {}; - var combinedUIByName = extend({}, previousUIByName, newUIByName); - for (var key in combinedUIByName) { - var type = Types.IdentityType.getIdentityType(key); - // this check removes anything that is not whitelisted as an identity type - if (type !== false && type >= 0) { - combinedUIByType[Types.IdentityType.getIdentityType(key)] = combinedUIByName[key]; - } - } - return combinedUIByType; - }, - createAliasNetworkRequest: function createAliasNetworkRequest(aliasRequest) { - return { - request_id: mpInstance._Helpers.generateUniqueId(), - request_type: 'alias', - environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? 'development' : 'production', - api_key: mpInstance._Store.devToken, - data: { - destination_mpid: aliasRequest.destinationMpid, - source_mpid: aliasRequest.sourceMpid, - start_unixtime_ms: aliasRequest.startTime, - end_unixtime_ms: aliasRequest.endTime, - scope: aliasRequest.scope, - device_application_stamp: mpInstance._Store.deviceId - } - }; - }, - convertAliasToNative: function convertAliasToNative(aliasRequest) { - return { - DestinationMpid: aliasRequest.destinationMpid, - SourceMpid: aliasRequest.sourceMpid, - StartUnixtimeMs: aliasRequest.startTime, - EndUnixtimeMs: aliasRequest.endTime, - Scope: aliasRequest.scope - }; - }, - convertToNative: function convertToNative(identityApiData) { - var nativeIdentityRequest = []; - if (identityApiData && identityApiData.userIdentities) { - for (var key in identityApiData.userIdentities) { - if (identityApiData.userIdentities.hasOwnProperty(key)) { - nativeIdentityRequest.push({ - Type: Types.IdentityType.getIdentityType(key), - Identity: identityApiData.userIdentities[key] - }); - } - } - return { - UserIdentities: nativeIdentityRequest - }; - } - } - }; - /** - * Invoke these methods on the mParticle.Identity object. - * Example: mParticle.Identity.getCurrentUser(). - * @class mParticle.Identity - */ - this.IdentityAPI = { - HTTPCodes: HTTPCodes$2, - /** - * Initiate a logout request to the mParticle server - * @method identify - * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) - * @param {Function} [callback] A callback function that is called when the identify request completes - */ - identify: function identify(identityApiData, callback) { - // https://go.mparticle.com/work/SQDSDKS-6337 - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(), - preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Identify); - if (currentUser) { - mpid = currentUser.getMPID(); - } - if (preProcessResult.valid) { - var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); - if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) { - var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Identify); - if (successfullyCachedIdentity) { - return; - } - } - if (mpInstance._Helpers.canLog()) { - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Identify request sent to native sdk'); - } else { - mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Identify, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); - mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); - mpInstance.Logger.verbose(preProcessResult); - } - }, - /** - * Initiate a logout request to the mParticle server - * @method logout - * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) - * @param {Function} [callback] A callback function that is called when the logout request completes - */ - logout: function logout(identityApiData, callback) { - // https://go.mparticle.com/work/SQDSDKS-6337 - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(), - preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Logout); - if (currentUser) { - mpid = currentUser.getMPID(); - } - if (preProcessResult.valid) { - var evt, - identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); - if (mpInstance._Helpers.canLog()) { - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Logout request sent to native sdk'); - } else { - mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Logout, callback, identityApiData, self.parseIdentityResponse, mpid); - evt = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.Profile - }); - evt.ProfileMessageType = Types.ProfileMessageType.Logout; - if (mpInstance._Store.activeForwarders.length) { - mpInstance._Store.activeForwarders.forEach(function (forwarder) { - if (forwarder.logOut) { - forwarder.logOut(evt); - } - }); - } - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); - mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); - mpInstance.Logger.verbose(preProcessResult); - } - }, - /** - * Initiate a login request to the mParticle server - * @method login - * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) - * @param {Function} [callback] A callback function that is called when the login request completes - */ - login: function login(identityApiData, callback) { - // https://go.mparticle.com/work/SQDSDKS-6337 - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(), - preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Login); - if (currentUser) { - mpid = currentUser.getMPID(); - } - if (preProcessResult.valid) { - var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); - if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) { - var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Login); - if (successfullyCachedIdentity) { - return; - } - } - if (mpInstance._Helpers.canLog()) { - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Login request sent to native sdk'); - } else { - mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Login, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); - mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); - mpInstance.Logger.verbose(preProcessResult); - } - }, - /** - * Initiate a modify request to the mParticle server - * @method modify - * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) - * @param {Function} [callback] A callback function that is called when the modify request completes - */ - modify: function modify(identityApiData, callback) { - // https://go.mparticle.com/work/SQDSDKS-6337 - var mpid, - currentUser = mpInstance.Identity.getCurrentUser(), - preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Modify$1); - if (currentUser) { - mpid = currentUser.getMPID(); - } - if (preProcessResult.valid) { - var newUserIdentities = identityApiData && identityApiData.userIdentities ? preProcessResult.cleanedIdentities.userIdentities : {}; - var identityApiRequest = mpInstance._Identity.IdentityRequest.createModifyIdentityRequest(currentUser ? currentUser.getUserIdentities().userIdentities : {}, newUserIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.context); - if (mpInstance._Helpers.canLog()) { - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Modify request sent to native sdk'); - } else { - mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Modify$1, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); - mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); - } - } else { - mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); - mpInstance.Logger.verbose(preProcessResult); - } - }, - /** - * Returns a user object with methods to interact with the current user - * @method getCurrentUser - * @return {Object} the current user object - */ - getCurrentUser: function getCurrentUser() { - var mpid; - if (mpInstance._Store) { - mpid = mpInstance._Store.mpid; - if (mpid) { - mpid = mpInstance._Store.mpid.slice(); - return self.mParticleUser(mpid, mpInstance._Store.isLoggedIn); - } else if (mpInstance._Store.webviewBridgeEnabled) { - return self.mParticleUser(); - } else { - return null; - } - } else { - return null; - } - }, - /** - * Returns a the user object associated with the mpid parameter or 'null' if no such - * user exists - * @method getUser - * @param {String} mpid of the desired user - * @return {Object} the user for mpid - */ - getUser: function getUser(mpid) { - var persistence = mpInstance._Persistence.getPersistence(); - if (persistence) { - if (persistence[mpid] && !Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(mpid)) { - return self.mParticleUser(mpid); - } else { - return null; - } - } else { - return null; - } - }, - /** - * Returns all users, including the current user and all previous users that are stored on the device. - * @method getUsers - * @return {Array} array of users - */ - getUsers: function getUsers() { - var persistence = mpInstance._Persistence.getPersistence(); - var users = []; - if (persistence) { - for (var key in persistence) { - if (!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(key)) { - users.push(self.mParticleUser(key)); - } - } - } - users.sort(function (a, b) { - var aLastSeen = a.getLastSeenTime() || 0; - var bLastSeen = b.getLastSeenTime() || 0; - if (aLastSeen > bLastSeen) { - return -1; - } else { - return 1; - } - }); - return users; - }, - /** - * Initiate an alias request to the mParticle server - * @method aliasUsers - * @param {Object} aliasRequest object representing an AliasRequest - * @param {Function} [callback] A callback function that is called when the aliasUsers request completes - */ - aliasUsers: function aliasUsers(aliasRequest, callback) { - var message; - if (!aliasRequest.destinationMpid || !aliasRequest.sourceMpid) { - message = Messages$2.ValidationMessages.AliasMissingMpid; - } - if (aliasRequest.destinationMpid === aliasRequest.sourceMpid) { - message = Messages$2.ValidationMessages.AliasNonUniqueMpid; - } - if (!aliasRequest.startTime || !aliasRequest.endTime) { - message = Messages$2.ValidationMessages.AliasMissingTime; - } - if (aliasRequest.startTime > aliasRequest.endTime) { - message = Messages$2.ValidationMessages.AliasStartBeforeEndTime; - } - if (message) { - mpInstance.Logger.warning(message); - mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.validationIssue, message); - return; - } - if (mpInstance._Helpers.canLog()) { - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias, JSON.stringify(mpInstance._Identity.IdentityRequest.convertAliasToNative(aliasRequest))); - mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Alias request sent to native sdk'); - } else { - mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest + ': ' + aliasRequest.sourceMpid + ' -> ' + aliasRequest.destinationMpid); - var aliasRequestMessage = mpInstance._Identity.IdentityRequest.createAliasNetworkRequest(aliasRequest); - mpInstance._IdentityAPIClient.sendAliasRequest(aliasRequestMessage, callback); - } - } else { - mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonAliasUsers); - mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers); - } - }, - /** - Create a default AliasRequest for 2 MParticleUsers. This will construct the request - using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime. - - In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only - be the case if they have not been the current user since this functionality was added, the - startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly, - if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time - - There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days. - If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime. - In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit, - after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() - validation that the startTime must be less than the endTime - */ - createAliasRequest: function createAliasRequest(sourceUser, destinationUser, scope) { - try { - if (!destinationUser || !sourceUser) { - mpInstance.Logger.error("'destinationUser' and 'sourceUser' must both be present"); - return null; - } - var startTime = sourceUser.getFirstSeenTime(); - if (!startTime) { - mpInstance.Identity.getUsers().forEach(function (user) { - if (user.getFirstSeenTime() && (!startTime || user.getFirstSeenTime() < startTime)) { - startTime = user.getFirstSeenTime(); - } - }); - } - var minFirstSeenTimeMs = new Date().getTime() - mpInstance._Store.SDKConfig.aliasMaxWindow * 24 * 60 * 60 * 1000; - var endTime = sourceUser.getLastSeenTime() || new Date().getTime(); - //if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed - if (startTime < minFirstSeenTimeMs) { - startTime = minFirstSeenTimeMs; - if (endTime < startTime) { - mpInstance.Logger.warning('Source User has not been seen in the last ' + mpInstance._Store.SDKConfig.maxAliasWindow + ' days, Alias Request will likely fail'); - } - } - return { - destinationMpid: destinationUser.getMPID(), - sourceMpid: sourceUser.getMPID(), - startTime: startTime, - endTime: endTime, - scope: scope || 'device' - }; - } catch (e) { - mpInstance.Logger.error('There was a problem with creating an alias request: ' + e); - return null; - } - } - }; - - // https://go.mparticle.com/work/SQDSDKS-6354 - /** - * Invoke these methods on the mParticle.Identity.getCurrentUser() object. - * Example: mParticle.Identity.getCurrentUser().getAllUserAttributes() - * @class mParticle.Identity.getCurrentUser() - */ - this.mParticleUser = function (mpid, _isLoggedIn) { - var self = this; - return { - /** - * Get user identities for current user - * @method getUserIdentities - * @return {Object} an object with userIdentities as its key - */ - getUserIdentities: function getUserIdentities() { - var currentUserIdentities = {}; - var identities = mpInstance._Store.getUserIdentities(mpid); - for (var identityType in identities) { - if (identities.hasOwnProperty(identityType)) { - currentUserIdentities[Types.IdentityType.getIdentityName(mpInstance._Helpers.parseNumber(identityType))] = identities[identityType]; - } - } - return { - userIdentities: currentUserIdentities - }; - }, - /** - * Get the MPID of the current user - * @method getMPID - * @return {String} the current user MPID as a string - */ - getMPID: function getMPID() { - return mpid; - }, - /** - * Sets a user tag - * @method setUserTag - * @param {String} tagName - */ - setUserTag: function setUserTag(tagName) { - if (!mpInstance._Helpers.Validators.isValidKeyValue(tagName)) { - mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); - return; - } - this.setUserAttribute(tagName, null); - }, - /** - * Removes a user tag - * @method removeUserTag - * @param {String} tagName - */ - removeUserTag: function removeUserTag(tagName) { - if (!mpInstance._Helpers.Validators.isValidKeyValue(tagName)) { - mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); - return; - } - this.removeUserAttribute(tagName); - }, - /** - * Sets a user attribute - * @method setUserAttribute - * @param {String} key - * @param {String} value - */ - // https://go.mparticle.com/work/SQDSDKS-4576 - // https://go.mparticle.com/work/SQDSDKS-6373 - setUserAttribute: function setUserAttribute(key, newValue) { - mpInstance._SessionManager.resetSessionTimer(); - if (mpInstance._Helpers.canLog()) { - if (!mpInstance._Helpers.Validators.isValidAttributeValue(newValue)) { - mpInstance.Logger.error(Messages$2.ErrorMessages.BadAttribute); - return; - } - if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) { - mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); - return; - } - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute, JSON.stringify({ - key: key, - value: newValue - })); - } else { - var userAttributes = this.getAllUserAttributes(); - var previousUserAttributeValue; - var isNewAttribute; - var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key); - if (existingProp) { - isNewAttribute = false; - previousUserAttributeValue = userAttributes[existingProp]; - delete userAttributes[existingProp]; - } else { - isNewAttribute = true; - } - userAttributes[key] = newValue; - mpInstance._Store.setUserAttributes(mpid, userAttributes); - self.sendUserAttributeChangeEvent(key, newValue, previousUserAttributeValue, isNewAttribute, false, this); - mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); - mpInstance._Forwarders.handleForwarderUserAttributes('setUserAttribute', key, newValue); - } - } - }, - /** - * Set multiple user attributes - * @method setUserAttributes - * @param {Object} user attribute object with keys of the attribute type, and value of the attribute value - */ - // https://go.mparticle.com/work/SQDSDKS-6373 - setUserAttributes: function setUserAttributes(userAttributes) { - mpInstance._SessionManager.resetSessionTimer(); - if (isObject(userAttributes)) { - if (mpInstance._Helpers.canLog()) { - for (var key in userAttributes) { - if (userAttributes.hasOwnProperty(key)) { - this.setUserAttribute(key, userAttributes[key]); - } - } - } - } else { - mpInstance.Logger.error('Must pass an object into setUserAttributes. You passed a ' + _typeof$1(userAttributes)); - } - }, - /** - * Removes a specific user attribute - * @method removeUserAttribute - * @param {String} key - */ - removeUserAttribute: function removeUserAttribute(key) { - var cookies, userAttributes; - mpInstance._SessionManager.resetSessionTimer(); - if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) { - mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); - return; - } - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute, JSON.stringify({ - key: key, - value: null - })); - } else { - cookies = mpInstance._Persistence.getPersistence(); - userAttributes = this.getAllUserAttributes(); - var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key); - if (existingProp) { - key = existingProp; - } - var deletedUAKeyCopy = userAttributes[key] ? userAttributes[key].toString() : null; - delete userAttributes[key]; - if (cookies && cookies[mpid]) { - cookies[mpid].ua = userAttributes; - mpInstance._Persistence.savePersistence(cookies, mpid); - } - self.sendUserAttributeChangeEvent(key, null, deletedUAKeyCopy, false, true, this); - mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); - mpInstance._Forwarders.handleForwarderUserAttributes('removeUserAttribute', key, null); - } - }, - /** - * Sets a list of user attributes - * @method setUserAttributeList - * @param {String} key - * @param {Array} value an array of values - */ - // https://go.mparticle.com/work/SQDSDKS-6373 - setUserAttributeList: function setUserAttributeList(key, newValue) { - mpInstance._SessionManager.resetSessionTimer(); - if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) { - mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); - return; - } - if (!Array.isArray(newValue)) { - mpInstance.Logger.error('The value you passed in to setUserAttributeList must be an array. You passed in a ' + (typeof value === "undefined" ? "undefined" : _typeof$1(value))); - return; - } - var arrayCopy = newValue.slice(); - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList, JSON.stringify({ - key: key, - value: arrayCopy - })); - } else { - var userAttributes = this.getAllUserAttributes(); - var previousUserAttributeValue; - var isNewAttribute; - var userAttributeChange; - var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key); - if (existingProp) { - isNewAttribute = false; - previousUserAttributeValue = userAttributes[existingProp]; - delete userAttributes[existingProp]; - } else { - isNewAttribute = true; - } - userAttributes[key] = arrayCopy; - mpInstance._Store.setUserAttributes(mpid, userAttributes); - - // If the new attributeList length is different than the previous, then there is a change event. - // Loop through new attributes list, see if they are all in the same index as previous user attributes list - // If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value - if (!previousUserAttributeValue || !Array.isArray(previousUserAttributeValue)) { - userAttributeChange = true; - } else if (newValue.length !== previousUserAttributeValue.length) { - userAttributeChange = true; - } else { - for (var i = 0; i < newValue.length; i++) { - if (previousUserAttributeValue[i] !== newValue[i]) { - userAttributeChange = true; - break; - } - } - } - if (userAttributeChange) { - self.sendUserAttributeChangeEvent(key, newValue, previousUserAttributeValue, isNewAttribute, false, this); - } - mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); - mpInstance._Forwarders.handleForwarderUserAttributes('setUserAttribute', key, arrayCopy); - } - }, - /** - * Removes all user attributes - * @method removeAllUserAttributes - */ - removeAllUserAttributes: function removeAllUserAttributes() { - var userAttributes; - mpInstance._SessionManager.resetSessionTimer(); - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes); - } else { - userAttributes = this.getAllUserAttributes(); - mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); - if (userAttributes) { - for (var prop in userAttributes) { - if (userAttributes.hasOwnProperty(prop)) { - mpInstance._Forwarders.handleForwarderUserAttributes('removeUserAttribute', prop, null); - } - this.removeUserAttribute(prop); - } - } - } - }, - /** - * Returns all user attribute keys that have values that are arrays - * @method getUserAttributesLists - * @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] } - */ - getUserAttributesLists: function getUserAttributesLists() { - var userAttributes, - userAttributesLists = {}; - userAttributes = this.getAllUserAttributes(); - for (var key in userAttributes) { - if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) { - userAttributesLists[key] = userAttributes[key].slice(); - } - } - return userAttributesLists; - }, - /** - * Returns all user attributes - * @method getAllUserAttributes - * @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] } - */ - getAllUserAttributes: function getAllUserAttributes() { - var getUserAttributes = mpInstance._Store.getUserAttributes; - var userAttributesCopy = {}; - var userAttributes = getUserAttributes(mpid); - if (userAttributes) { - for (var prop in userAttributes) { - if (userAttributes.hasOwnProperty(prop)) { - if (Array.isArray(userAttributes[prop])) { - userAttributesCopy[prop] = userAttributes[prop].slice(); - } else { - userAttributesCopy[prop] = userAttributes[prop]; - } - } - } - } - return userAttributesCopy; - }, - /** - * Returns the cart object for the current user - * @method getCart - * @return a cart object - */ - getCart: function getCart() { - mpInstance.Logger.warning('Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases'); - return self.mParticleUserCart(); - }, - /** - * Returns the Consent State stored locally for this user. - * @method getConsentState - * @return a ConsentState object - */ - getConsentState: function getConsentState() { - return mpInstance._Store.getConsentState(mpid); - }, - /** - * Sets the Consent State stored locally for this user. - * @method setConsentState - * @param {Object} consent state - */ - setConsentState: function setConsentState(state) { - mpInstance._Store.setConsentState(mpid, state); - mpInstance._Forwarders.initForwarders(this.getUserIdentities().userIdentities, mpInstance._APIClient.prepareForwardingStats); - mpInstance._CookieSyncManager.attemptCookieSync(this.getMPID()); - }, - isLoggedIn: function isLoggedIn() { - return _isLoggedIn; - }, - getLastSeenTime: function getLastSeenTime() { - return mpInstance._Persistence.getLastSeenTime(mpid); - }, - getFirstSeenTime: function getFirstSeenTime() { - return mpInstance._Persistence.getFirstSeenTime(mpid); - }, - /** - * Get user audiences - * @method getuserAudiences - * @param {Function} [callback] A callback function that is invoked when the user audience request completes - */ - // https://go.mparticle.com/work/SQDSDKS-6436 - getUserAudiences: function getUserAudiences(callback) { - // user audience API is feature flagged - if (!mpInstance._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)) { - mpInstance.Logger.error(ErrorMessages.AudienceAPINotEnabled); - return; - } - if (self.audienceManager === null) { - self.audienceManager = new AudienceManager(mpInstance._Store.SDKConfig.userAudienceUrl, mpInstance._Store.devToken, mpInstance.Logger, mpid); - } - self.audienceManager.sendGetUserAudienceRequest(mpid, callback); - } - }; - }; - - /** - * Invoke these methods on the mParticle.Identity.getCurrentUser().getCart() object. - * Example: mParticle.Identity.getCurrentUser().getCart().add(...); - * @class mParticle.Identity.getCurrentUser().getCart() - * @deprecated - */ - this.mParticleUserCart = function () { - return { - /** - * Adds a cart product to the user cart - * @method add - * @deprecated - */ - add: function add() { - mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().add()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - }, - /** - * Removes a cart product from the current user cart - * @method remove - * @deprecated - */ - remove: function remove() { - mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().remove()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - }, - /** - * Clears the user's cart - * @method clear - * @deprecated - */ - clear: function clear() { - mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().clear()', true, '', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - }, - /** - * Returns all cart products - * @method getCartProducts - * @return {Array} array of cart products - * @deprecated - */ - getCartProducts: function getCartProducts() { - mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().getCartProducts()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - return []; - } - }; - }; - - // https://go.mparticle.com/work/SQDSDKS-6355 - this.parseIdentityResponse = function (identityResponse, previousMPID, callback, identityApiData, method, knownIdentities, parsingCachedResponse) { - var prevUser = mpInstance.Identity.getUser(previousMPID); - var prevUserMPID = prevUser ? prevUser.getMPID() : null; - var previousUIByName = prevUser ? prevUser.getUserIdentities().userIdentities : {}; - var mpidIsNotInCookies; - var identityApiResult; - var newUser; - var newIdentitiesByType = {}; - mpInstance._Store.identityCallInFlight = false; - try { - var _identityResponse$res, _identityApiResult, _mpInstance$_APIClien; - mpInstance.Logger.verbose('Parsing "' + method + '" identity response from server'); - identityApiResult = (_identityResponse$res = identityResponse.responseText) !== null && _identityResponse$res !== void 0 ? _identityResponse$res : null; - mpInstance._Store.isLoggedIn = ((_identityApiResult = identityApiResult) === null || _identityApiResult === void 0 ? void 0 : _identityApiResult.is_logged_in) || false; - - // https://go.mparticle.com/work/SQDSDKS-6504 - // set currentUser - if (hasMPIDChanged(prevUser, identityApiResult)) { - mpInstance._Store.mpid = identityApiResult.mpid; - if (prevUser) { - // https://go.mparticle.com/work/SQDSDKS-6329 - mpInstance._Persistence.setLastSeenTime(previousMPID); - } - mpidIsNotInCookies = !mpInstance._Persistence.getFirstSeenTime(identityApiResult.mpid); - - // https://go.mparticle.com/work/SQDSDKS-6329 - mpInstance._Persistence.setFirstSeenTime(identityApiResult.mpid); - } - if (identityResponse.status === HTTP_OK) { - if (getFeatureFlag(CacheIdentity)) { - cacheOrClearIdCache(method, knownIdentities, self.idCache, identityResponse, parsingCachedResponse); - } - var incomingUser = self.IdentityAPI.getUser(identityApiResult.mpid); - var incomingUIByName = incomingUser ? incomingUser.getUserIdentities().userIdentities : {}; - if (method === Modify$1) { - newIdentitiesByType = mpInstance._Identity.IdentityRequest.combineUserIdentities(previousUIByName, identityApiData.userIdentities); - mpInstance._Store.setUserIdentities(previousMPID, newIdentitiesByType); - } else { - // https://go.mparticle.com/work/SQDSDKS-6356 - //this covers an edge case where, users stored before "firstSeenTime" was introduced - //will not have a value for "fst" until the current MPID changes, and in some cases, - //the current MPID will never change - if (method === Identify && prevUser && identityApiResult.mpid === prevUserMPID) { - // https://go.mparticle.com/work/SQDSDKS-6329 - mpInstance._Persistence.setFirstSeenTime(identityApiResult.mpid); - } - mpInstance._Store.addMpidToSessionHistory(identityApiResult.mpid, previousMPID); - mpInstance._CookieSyncManager.attemptCookieSync(identityApiResult.mpid, mpidIsNotInCookies); - mpInstance._Persistence.swapCurrentUser(previousMPID, identityApiResult.mpid, mpInstance._Store.currentSessionMPIDs); - if (identityApiData && !isEmpty(identityApiData.userIdentities)) { - newIdentitiesByType = self.IdentityRequest.combineUserIdentities(incomingUIByName, identityApiData.userIdentities); - } - - // https://go.mparticle.com/work/SQDSDKS-6041 - mpInstance._Store.setUserIdentities(identityApiResult.mpid, newIdentitiesByType); - mpInstance._Persistence.update(); - mpInstance._Store.syncPersistenceData(); - mpInstance._Persistence.findPrevCookiesBasedOnUI(identityApiData); - - // https://go.mparticle.com/work/SQDSDKS-6357 - mpInstance._Store.context = identityApiResult.context || mpInstance._Store.context; - } - newUser = mpInstance.Identity.getCurrentUser(); - - // https://go.mparticle.com/work/SQDSDKS-6359 - tryOnUserAlias(prevUser, newUser, identityApiData, mpInstance.Logger); - var persistence = mpInstance._Persistence.getPersistence(); - if (newUser) { - mpInstance._Persistence.storeDataInMemory(persistence, newUser.getMPID()); - self.reinitForwardersOnUserChange(prevUser, newUser); - self.setForwarderCallbacks(newUser, method); - } - var newIdentitiesByName = IdentityType.getNewIdentitiesByName(newIdentitiesByType); - var uiByName = method === Modify$1 ? previousUIByName : incomingUIByName; - - // https://go.mparticle.com/work/SQDSDKS-6501 - self.sendUserIdentityChangeEvent(newIdentitiesByName, method, identityApiResult.mpid, uiByName); - } - if (callback) { - var callbackCode = identityResponse.status === 0 ? HTTPCodes$2.noHttpCoverage : identityResponse.status; - mpInstance._Helpers.invokeCallback(callback, callbackCode, identityApiResult || null, newUser); - } else if (identityApiResult && !isEmpty(identityApiResult.errors)) { - // https://go.mparticle.com/work/SQDSDKS-6500 - mpInstance.Logger.error('Received HTTP response code of ' + identityResponse.status + ' - ' + identityApiResult.errors[0].message); - } - mpInstance.Logger.verbose('Successfully parsed Identity Response'); - - // https://go.mparticle.com/work/SQDSDKS-6654 - (_mpInstance$_APIClien = mpInstance._APIClient) === null || _mpInstance$_APIClien === void 0 || _mpInstance$_APIClien.processQueuedEvents(); - } catch (e) { - if (callback) { - mpInstance._Helpers.invokeCallback(callback, identityResponse.status, identityApiResult || null); - } - mpInstance.Logger.error('Error parsing JSON response from Identity server: ' + e); - } - mpInstance._Store.isInitialized = true; - mpInstance._RoktManager.onIdentityComplete(); - mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue); - }; - - // send a user identity change request on identify, login, logout, modify when any values change. - // compare what identities exist vs what is previously was for the specific user if they were in memory before. - // if it's the first time the user is logging in, send a user identity change request with - this.sendUserIdentityChangeEvent = function (newUserIdentities, method, mpid, prevUserIdentities) { - if (!mpid) { - // https://go.mparticle.com/work/SQDSDKS-6501 - if (method !== Modify$1) { - return; - } - } - - // https://go.mparticle.com/work/SQDSDKS-6354 - var currentUserInMemory = this.IdentityAPI.getUser(mpid); - for (var identityType in newUserIdentities) { - // Verifies a change actually happened - if (prevUserIdentities[identityType] !== newUserIdentities[identityType]) { - var _mpInstance$_APIClien2; - // If a new identity type was introduced when the identity changes - // we need to notify the server so that the user profile is updated in - // the mParticle UI. - var isNewUserIdentityType = !prevUserIdentities[identityType]; - var userIdentityChangeEvent = self.createUserIdentityChange(identityType, newUserIdentities[identityType], prevUserIdentities[identityType], isNewUserIdentityType, currentUserInMemory); - (_mpInstance$_APIClien2 = mpInstance._APIClient) === null || _mpInstance$_APIClien2 === void 0 || _mpInstance$_APIClien2.sendEventToServer(userIdentityChangeEvent); - } - } - }; - this.createUserIdentityChange = function (identityType, newIdentity, oldIdentity, isIdentityTypeNewToBatch, userInMemory) { - var userIdentityChangeEvent; - - // https://go.mparticle.com/work/SQDSDKS-6439 - userIdentityChangeEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.UserIdentityChange, - userIdentityChanges: { - New: { - IdentityType: identityType, - Identity: newIdentity, - CreatedThisBatch: isIdentityTypeNewToBatch - }, - Old: { - IdentityType: identityType, - Identity: oldIdentity, - CreatedThisBatch: false - } - }, - userInMemory: userInMemory - }); - return userIdentityChangeEvent; - }; - this.sendUserAttributeChangeEvent = function (attributeKey, newUserAttributeValue, previousUserAttributeValue, isNewAttribute, deleted, user) { - var userAttributeChangeEvent = self.createUserAttributeChange(attributeKey, newUserAttributeValue, previousUserAttributeValue, isNewAttribute, deleted, user); - if (userAttributeChangeEvent) { - var _mpInstance$_APIClien3; - (_mpInstance$_APIClien3 = mpInstance._APIClient) === null || _mpInstance$_APIClien3 === void 0 || _mpInstance$_APIClien3.sendEventToServer(userAttributeChangeEvent); - } - }; - this.createUserAttributeChange = function (key, newValue, previousUserAttributeValue, isNewAttribute, deleted, user) { - if (typeof previousUserAttributeValue === 'undefined') { - previousUserAttributeValue = null; - } - var userAttributeChangeEvent; - if (newValue !== previousUserAttributeValue) { - // https://go.mparticle.com/work/SQDSDKS-6439 - userAttributeChangeEvent = mpInstance._ServerModel.createEventObject({ - messageType: Types.MessageType.UserAttributeChange, - userAttributeChanges: { - UserAttributeName: key, - New: newValue, - Old: previousUserAttributeValue, - Deleted: deleted, - IsNewAttribute: isNewAttribute - } - }, user); - } - return userAttributeChangeEvent; - }; - this.reinitForwardersOnUserChange = function (prevUser, newUser) { - if (hasMPIDAndUserLoginChanged(prevUser, newUser)) { - var _mpInstance$_Forwarde; - (_mpInstance$_Forwarde = mpInstance._Forwarders) === null || _mpInstance$_Forwarde === void 0 || _mpInstance$_Forwarde.initForwarders(newUser.getUserIdentities().userIdentities, mpInstance._APIClient.prepareForwardingStats); - } - }; - this.setForwarderCallbacks = function (user, method) { - var _mpInstance$_Forwarde2, _mpInstance$_Forwarde3, _mpInstance$_Forwarde4; - // https://go.mparticle.com/work/SQDSDKS-6036 - (_mpInstance$_Forwarde2 = mpInstance._Forwarders) === null || _mpInstance$_Forwarde2 === void 0 || _mpInstance$_Forwarde2.setForwarderUserIdentities(user.getUserIdentities().userIdentities); - (_mpInstance$_Forwarde3 = mpInstance._Forwarders) === null || _mpInstance$_Forwarde3 === void 0 || _mpInstance$_Forwarde3.setForwarderOnIdentityComplete(user, method); - (_mpInstance$_Forwarde4 = mpInstance._Forwarders) === null || _mpInstance$_Forwarde4 === void 0 || _mpInstance$_Forwarde4.setForwarderOnUserIdentified(user); - }; - } - - // https://go.mparticle.com/work/SQDSDKS-6359 - function tryOnUserAlias(previousUser, newUser, identityApiData, logger) { - if (identityApiData && identityApiData.onUserAlias && isFunction(identityApiData.onUserAlias)) { - try { - logger.warning(generateDeprecationMessage('onUserAlias')); - identityApiData.onUserAlias(previousUser, newUser); - } catch (e) { - logger.error('There was an error with your onUserAlias function - ' + e); - } - } - } - - var CCPAPurpose = Constants.CCPAPurpose; - function Consent(mpInstance) { - var self = this; - // this function is called when consent is required to - // determine if a cookie sync should happen, or a - // forwarder should be initialized - this.isEnabledForUserConsent = function (consentRules, user) { - if (!consentRules || !consentRules.values || !consentRules.values.length) { - return true; - } - if (!user) { - return false; - } - var purposeHashes = {}; - var consentState = user.getConsentState(); - var purposeHash; - if (consentState) { - // the server hashes consent purposes in the following way: - // GDPR - '1' + purpose name - // CCPA - '2data_sale_opt_out' (there is only 1 purpose of data_sale_opt_out for CCPA) - var GDPRConsentHashPrefix = '1'; - var CCPAHashPrefix = '2'; - var gdprConsentState = consentState.getGDPRConsentState(); - if (gdprConsentState) { - for (var purpose in gdprConsentState) { - if (gdprConsentState.hasOwnProperty(purpose)) { - purposeHash = KitFilterHelper.hashConsentPurposeConditionalForwarding(GDPRConsentHashPrefix, purpose); - purposeHashes[purposeHash] = gdprConsentState[purpose].Consented; - } - } - } - var CCPAConsentState = consentState.getCCPAConsentState(); - if (CCPAConsentState) { - purposeHash = KitFilterHelper.hashConsentPurposeConditionalForwarding(CCPAHashPrefix, CCPAPurpose); - purposeHashes[purposeHash] = CCPAConsentState.Consented; - } - } - var isMatch = consentRules.values.some(function (consentRule) { - var consentPurposeHash = consentRule.consentPurpose; - var hasConsented = consentRule.hasConsented; - if (purposeHashes.hasOwnProperty(consentPurposeHash)) { - return purposeHashes[consentPurposeHash] === hasConsented; - } - return false; - }); - return consentRules.includeOnMatch === isMatch; - }; - this.createPrivacyConsent = function (consented, timestamp, consentDocument, location, hardwareId) { - if (typeof consented !== 'boolean') { - mpInstance.Logger.error('Consented boolean is required when constructing a Consent object.'); - return null; - } - if (timestamp && isNaN(timestamp)) { - mpInstance.Logger.error('Timestamp must be a valid number when constructing a Consent object.'); - return null; - } - if (consentDocument && typeof consentDocument !== 'string') { - mpInstance.Logger.error('Document must be a valid string when constructing a Consent object.'); - return null; - } - if (location && typeof location !== 'string') { - mpInstance.Logger.error('Location must be a valid string when constructing a Consent object.'); - return null; - } - if (hardwareId && typeof hardwareId !== 'string') { - mpInstance.Logger.error('Hardware ID must be a valid string when constructing a Consent object.'); - return null; - } - return { - Consented: consented, - Timestamp: timestamp || Date.now(), - ConsentDocument: consentDocument, - Location: location, - HardwareId: hardwareId - }; - }; - this.ConsentSerialization = { - toMinifiedJsonObject: function toMinifiedJsonObject(state) { - var _a; - var jsonObject = {}; - if (state) { - var gdprConsentState = state.getGDPRConsentState(); - if (gdprConsentState) { - jsonObject.gdpr = {}; - for (var purpose in gdprConsentState) { - if (gdprConsentState.hasOwnProperty(purpose)) { - var gdprConsent = gdprConsentState[purpose]; - jsonObject.gdpr[purpose] = {}; - if (typeof gdprConsent.Consented === 'boolean') { - jsonObject.gdpr[purpose].c = gdprConsent.Consented; - } - if (typeof gdprConsent.Timestamp === 'number') { - jsonObject.gdpr[purpose].ts = gdprConsent.Timestamp; - } - if (typeof gdprConsent.ConsentDocument === 'string') { - jsonObject.gdpr[purpose].d = gdprConsent.ConsentDocument; - } - if (typeof gdprConsent.Location === 'string') { - jsonObject.gdpr[purpose].l = gdprConsent.Location; - } - if (typeof gdprConsent.HardwareId === 'string') { - jsonObject.gdpr[purpose].h = gdprConsent.HardwareId; - } - } - } - } - var ccpaConsentState = state.getCCPAConsentState(); - if (ccpaConsentState) { - jsonObject.ccpa = (_a = {}, _a[CCPAPurpose] = {}, _a); - if (typeof ccpaConsentState.Consented === 'boolean') { - jsonObject.ccpa[CCPAPurpose].c = ccpaConsentState.Consented; - } - if (typeof ccpaConsentState.Timestamp === 'number') { - jsonObject.ccpa[CCPAPurpose].ts = ccpaConsentState.Timestamp; - } - if (typeof ccpaConsentState.ConsentDocument === 'string') { - jsonObject.ccpa[CCPAPurpose].d = ccpaConsentState.ConsentDocument; - } - if (typeof ccpaConsentState.Location === 'string') { - jsonObject.ccpa[CCPAPurpose].l = ccpaConsentState.Location; - } - if (typeof ccpaConsentState.HardwareId === 'string') { - jsonObject.ccpa[CCPAPurpose].h = ccpaConsentState.HardwareId; - } - } - } - return jsonObject; - }, - fromMinifiedJsonObject: function fromMinifiedJsonObject(json) { - var state = self.createConsentState(); - if (json.gdpr) { - for (var purpose in json.gdpr) { - if (json.gdpr.hasOwnProperty(purpose)) { - var gdprConsent = self.createPrivacyConsent(json.gdpr[purpose].c, json.gdpr[purpose].ts, json.gdpr[purpose].d, json.gdpr[purpose].l, json.gdpr[purpose].h); - state.addGDPRConsentState(purpose, gdprConsent); - } - } - } - if (json.ccpa) { - if (json.ccpa.hasOwnProperty(CCPAPurpose)) { - var ccpaConsent = self.createPrivacyConsent(json.ccpa[CCPAPurpose].c, json.ccpa[CCPAPurpose].ts, json.ccpa[CCPAPurpose].d, json.ccpa[CCPAPurpose].l, json.ccpa[CCPAPurpose].h); - state.setCCPAConsentState(ccpaConsent); - } - } - return state; - } - }; - // TODO: Refactor this method into a constructor - this.createConsentState = function (consentState) { - var gdpr = {}; - var ccpa = {}; - if (consentState) { - var consentStateCopy = self.createConsentState(); - consentStateCopy.setGDPRConsentState(consentState.getGDPRConsentState()); - consentStateCopy.setCCPAConsentState(consentState.getCCPAConsentState()); - // TODO: Remove casting once `removeCCPAState` is removed; - return consentStateCopy; - } - function canonicalizeForDeduplication(purpose) { - if (typeof purpose !== 'string') { - return null; - } - var trimmedPurpose = purpose.trim(); - if (!trimmedPurpose.length) { - return null; - } - return trimmedPurpose.toLowerCase(); - } - /** - * Invoke these methods on a consent state object. - *

- * Usage: const consent = mParticle.Consent.createConsentState() - *
- * consent.setGDPRCoonsentState() - * - * @class Consent - */ - /** - * Add a GDPR Consent State to the consent state object - * - * @method addGDPRConsentState - * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data - * @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...) - */ - function addGDPRConsentState(purpose, gdprConsent) { - var normalizedPurpose = canonicalizeForDeduplication(purpose); - if (!normalizedPurpose) { - mpInstance.Logger.error('Purpose must be a string.'); - return this; - } - if (!isObject(gdprConsent)) { - mpInstance.Logger.error('Invoked with a bad or empty consent object.'); - return this; - } - var gdprConsentCopy = self.createPrivacyConsent(gdprConsent.Consented, gdprConsent.Timestamp, gdprConsent.ConsentDocument, gdprConsent.Location, gdprConsent.HardwareId); - if (gdprConsentCopy) { - gdpr[normalizedPurpose] = gdprConsentCopy; - } - return this; - } - function setGDPRConsentState(gdprConsentState) { - if (!gdprConsentState) { - gdpr = {}; - } else if (isObject(gdprConsentState)) { - gdpr = {}; - for (var purpose in gdprConsentState) { - if (gdprConsentState.hasOwnProperty(purpose)) { - this.addGDPRConsentState(purpose, gdprConsentState[purpose]); - } - } - } - return this; - } - /** - * Remove a GDPR Consent State to the consent state object - * - * @method removeGDPRConsentState - * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data - */ - function removeGDPRConsentState(purpose) { - var normalizedPurpose = canonicalizeForDeduplication(purpose); - if (!normalizedPurpose) { - return this; - } - delete gdpr[normalizedPurpose]; - return this; - } - /** - * Gets the GDPR Consent State - * - * @method getGDPRConsentState - * @return {Object} A GDPR Consent State - */ - function getGDPRConsentState() { - return Object.assign({}, gdpr); - } - /** - * Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out') - * - * @method setCCPAConsentState - * @param {Object} ccpaConsent CCPA Consent State - */ - function setCCPAConsentState(ccpaConsent) { - if (!isObject(ccpaConsent)) { - mpInstance.Logger.error('Invoked with a bad or empty CCPA consent object.'); - return this; - } - var ccpaConsentCopy = self.createPrivacyConsent(ccpaConsent.Consented, ccpaConsent.Timestamp, ccpaConsent.ConsentDocument, ccpaConsent.Location, ccpaConsent.HardwareId); - if (ccpaConsentCopy) { - ccpa[CCPAPurpose] = ccpaConsentCopy; - } - return this; - } - /** - * Gets the CCPA Consent State - * - * @method getCCPAConsentStatensent - * @return {Object} A CCPA Consent State - */ - function getCCPAConsentState() { - return ccpa[CCPAPurpose]; - } - /** - * Removes CCPA from the consent state object - * - * @method removeCCPAConsentState - */ - function removeCCPAConsentState() { - delete ccpa[CCPAPurpose]; - return this; - } - // TODO: Can we remove this? It is deprecated. - function removeCCPAState() { - mpInstance.Logger.warning('removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead'); - // @ts-ignore - return removeCCPAConsentState(); - } - return { - setGDPRConsentState: setGDPRConsentState, - addGDPRConsentState: addGDPRConsentState, - setCCPAConsentState: setCCPAConsentState, - getCCPAConsentState: getCCPAConsentState, - getGDPRConsentState: getGDPRConsentState, - removeGDPRConsentState: removeGDPRConsentState, - removeCCPAState: removeCCPAState, - removeCCPAConsentState: removeCCPAConsentState - }; - }; - } - - /* - TODO: Including this as a workaround because attempting to import it from - @mparticle/data-planning-models directly creates a build error. - */ - var DataPlanMatchType = { - ScreenView: "screen_view", - CustomEvent: "custom_event", - Commerce: "commerce", - UserAttributes: "user_attributes", - UserIdentities: "user_identities", - ProductAction: "product_action", - PromotionAction: "promotion_action", - ProductImpression: "product_impression" - }; - /* - inspiration from https://github.com/mParticle/data-planning-node/blob/master/src/data_planning/data_plan_event_validator.ts - but modified to only include commerce events, custom events, screen views, and removes validation - - The purpose of the KitBlocker class is to parse a data plan and determine what events, event/user/product attributes, and user identities should be blocked from downstream forwarders. - - KitBlocker is instantiated with a data plan on mParticle initialization. KitBlocker.kitBlockingEnabled is false if no data plan is passed. - It parses the data plan by creating a `dataPlanMatchLookups` object in the following manner: - 1. For all events and user attributes/identities, it generates a `matchKey` in the shape of `typeOfEvent:eventType:nameOfEvent` - a. The matchKeys' value will return `true` if additionalProperties for the custom attributes/identities is `true`, otherwise it will return an object of planned attribute/identities - 2. For commerce events, after step 1 and 1a, a second `matchKey` is included that appends `Products`. This is used to determine productAttributes blocked - - When an event is logged in mParticle, it is sent to our server and then calls `KitBlocker.createBlockedEvent` before passing the event to each forwarder. - If the event is blocked, it will not send to the forwarder. If the event is not blocked, event/user/product attributes and user identities will be removed from the returned event if blocked. - */ - var KitBlocker = /** @class */function () { - function KitBlocker(dataPlan, mpInstance) { - var _this = this; - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; - this.dataPlanMatchLookups = {}; - this.blockEvents = false; - this.blockEventAttributes = false; - this.blockUserAttributes = false; - this.blockUserIdentities = false; - this.kitBlockingEnabled = false; - // if data plan is not requested, the data plan is {document: null} - if (dataPlan && !dataPlan.document) { - this.kitBlockingEnabled = false; - return; - } - this.kitBlockingEnabled = true; - this.mpInstance = mpInstance; - this.blockEvents = (_c = (_b = (_a = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _a === void 0 ? void 0 : _a.dtpn) === null || _b === void 0 ? void 0 : _b.blok) === null || _c === void 0 ? void 0 : _c.ev; - this.blockEventAttributes = (_f = (_e = (_d = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _d === void 0 ? void 0 : _d.dtpn) === null || _e === void 0 ? void 0 : _e.blok) === null || _f === void 0 ? void 0 : _f.ea; - this.blockUserAttributes = (_j = (_h = (_g = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _g === void 0 ? void 0 : _g.dtpn) === null || _h === void 0 ? void 0 : _h.blok) === null || _j === void 0 ? void 0 : _j.ua; - this.blockUserIdentities = (_m = (_l = (_k = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _k === void 0 ? void 0 : _k.dtpn) === null || _l === void 0 ? void 0 : _l.blok) === null || _m === void 0 ? void 0 : _m.id; - var versionDocument = (_q = (_p = (_o = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _o === void 0 ? void 0 : _o.dtpn) === null || _p === void 0 ? void 0 : _p.vers) === null || _q === void 0 ? void 0 : _q.version_document; - var dataPoints = versionDocument === null || versionDocument === void 0 ? void 0 : versionDocument.data_points; - if (versionDocument) { - try { - if ((dataPoints === null || dataPoints === void 0 ? void 0 : dataPoints.length) > 0) { - dataPoints.forEach(function (point) { - return _this.addToMatchLookups(point); - }); - } - } catch (e) { - this.mpInstance.Logger.error('There was an issue with the data plan: ' + e); - } - } - } - KitBlocker.prototype.addToMatchLookups = function (point) { - var _a, _b, _c; - if (!point.match || !point.validator) { - this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(point)); - return; - } - // match keys for non product custom attribute related data points - var matchKey = this.generateMatchKey(point.match); - var properties = this.getPlannedProperties(point.match.type, point.validator); - this.dataPlanMatchLookups[matchKey] = properties; - // match keys for product custom attribute related data points - if (((_a = point === null || point === void 0 ? void 0 : point.match) === null || _a === void 0 ? void 0 : _a.type) === DataPlanMatchType.ProductImpression || ((_b = point === null || point === void 0 ? void 0 : point.match) === null || _b === void 0 ? void 0 : _b.type) === DataPlanMatchType.ProductAction || ((_c = point === null || point === void 0 ? void 0 : point.match) === null || _c === void 0 ? void 0 : _c.type) === DataPlanMatchType.PromotionAction) { - matchKey = this.generateProductAttributeMatchKey(point.match); - properties = this.getProductProperties(point.match.type, point.validator); - this.dataPlanMatchLookups[matchKey] = properties; - } - }; - KitBlocker.prototype.generateMatchKey = function (match) { - var criteria = match.criteria || ''; - switch (match.type) { - case DataPlanMatchType.CustomEvent: - var customEventCriteria = criteria; - return [DataPlanMatchType.CustomEvent, customEventCriteria.custom_event_type, customEventCriteria.event_name].join(':'); - case DataPlanMatchType.ScreenView: - var screenViewCriteria = criteria; - return [DataPlanMatchType.ScreenView, '', screenViewCriteria.screen_name].join(':'); - case DataPlanMatchType.ProductAction: - var productActionMatch = criteria; - return [match.type, productActionMatch.action].join(':'); - case DataPlanMatchType.PromotionAction: - var promoActionMatch = criteria; - return [match.type, promoActionMatch.action].join(':'); - case DataPlanMatchType.ProductImpression: - var productImpressionActionMatch = criteria; - return [match.type, productImpressionActionMatch.action].join(':'); - case DataPlanMatchType.UserIdentities: - case DataPlanMatchType.UserAttributes: - return [match.type].join(':'); - default: - return null; - } - }; - KitBlocker.prototype.generateProductAttributeMatchKey = function (match) { - var criteria = match.criteria || ''; - switch (match.type) { - case DataPlanMatchType.ProductAction: - var productActionMatch = criteria; - return [match.type, productActionMatch.action, 'ProductAttributes'].join(':'); - case DataPlanMatchType.PromotionAction: - var promoActionMatch = criteria; - return [match.type, promoActionMatch.action, 'ProductAttributes'].join(':'); - case DataPlanMatchType.ProductImpression: - return [match.type, 'ProductAttributes'].join(':'); - default: - return null; - } - }; - KitBlocker.prototype.getPlannedProperties = function (type, validator) { - var _a, _b, _c, _d, _e, _f, _g, _h; - var customAttributes; - var userAdditionalProperties; - switch (type) { - case DataPlanMatchType.CustomEvent: - case DataPlanMatchType.ScreenView: - case DataPlanMatchType.ProductAction: - case DataPlanMatchType.PromotionAction: - case DataPlanMatchType.ProductImpression: - customAttributes = (_d = (_c = (_b = (_a = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.custom_attributes; - if (customAttributes) { - if (customAttributes.additionalProperties === true || customAttributes.additionalProperties === undefined) { - return true; - } else { - var properties = {}; - for (var _i = 0, _j = Object.keys(customAttributes.properties); _i < _j.length; _i++) { - var property = _j[_i]; - properties[property] = true; - } - return properties; - } - } else { - if (((_g = (_f = (_e = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _e === void 0 ? void 0 : _e.properties) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.additionalProperties) === false) { - return {}; - } else { - return true; - } - } - case DataPlanMatchType.UserAttributes: - case DataPlanMatchType.UserIdentities: - userAdditionalProperties = (_h = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _h === void 0 ? void 0 : _h.additionalProperties; - if (userAdditionalProperties === true || userAdditionalProperties === undefined) { - return true; - } else { - var properties = {}; - var userProperties = validator.definition.properties; - for (var _k = 0, _l = Object.keys(userProperties); _k < _l.length; _k++) { - var property = _l[_k]; - properties[property] = true; - } - return properties; - } - default: - return null; - } - }; - KitBlocker.prototype.getProductProperties = function (type, validator) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u; - var productCustomAttributes; - switch (type) { - case DataPlanMatchType.ProductImpression: - productCustomAttributes = (_k = (_j = (_h = (_g = (_f = (_e = (_d = (_c = (_b = (_a = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.product_impressions) === null || _e === void 0 ? void 0 : _e.items) === null || _f === void 0 ? void 0 : _f.properties) === null || _g === void 0 ? void 0 : _g.products) === null || _h === void 0 ? void 0 : _h.items) === null || _j === void 0 ? void 0 : _j.properties) === null || _k === void 0 ? void 0 : _k.custom_attributes; - //product item attributes - if ((productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.additionalProperties) === false) { - var properties = {}; - for (var _i = 0, _v = Object.keys(productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.properties); _i < _v.length; _i++) { - var property = _v[_i]; - properties[property] = true; - } - return properties; - } - return true; - case DataPlanMatchType.ProductAction: - case DataPlanMatchType.PromotionAction: - productCustomAttributes = (_u = (_t = (_s = (_r = (_q = (_p = (_o = (_m = (_l = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _l === void 0 ? void 0 : _l.properties) === null || _m === void 0 ? void 0 : _m.data) === null || _o === void 0 ? void 0 : _o.properties) === null || _p === void 0 ? void 0 : _p.product_action) === null || _q === void 0 ? void 0 : _q.properties) === null || _r === void 0 ? void 0 : _r.products) === null || _s === void 0 ? void 0 : _s.items) === null || _t === void 0 ? void 0 : _t.properties) === null || _u === void 0 ? void 0 : _u.custom_attributes; - //product item attributes - if (productCustomAttributes) { - if (productCustomAttributes.additionalProperties === false) { - var properties = {}; - for (var _w = 0, _x = Object.keys(productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.properties); _w < _x.length; _w++) { - var property = _x[_w]; - properties[property] = true; - } - return properties; - } - } - return true; - default: - return null; - } - }; - KitBlocker.prototype.getMatchKey = function (eventToMatch) { - switch (eventToMatch.event_type) { - case dist.EventTypeEnum.screenView: - var screenViewEvent = eventToMatch; - if (screenViewEvent.data) { - return ['screen_view', '', screenViewEvent.data.screen_name].join(':'); - } - return null; - case dist.EventTypeEnum.commerceEvent: - var commerceEvent = eventToMatch; - var matchKey = []; - if (commerceEvent && commerceEvent.data) { - var _a = commerceEvent.data, - product_action = _a.product_action, - product_impressions = _a.product_impressions, - promotion_action = _a.promotion_action; - if (product_action) { - matchKey.push(DataPlanMatchType.ProductAction); - matchKey.push(product_action.action); - } else if (promotion_action) { - matchKey.push(DataPlanMatchType.PromotionAction); - matchKey.push(promotion_action.action); - } else if (product_impressions) { - matchKey.push(DataPlanMatchType.ProductImpression); - } - } - return matchKey.join(':'); - case dist.EventTypeEnum.customEvent: - var customEvent = eventToMatch; - if (customEvent.data) { - return ['custom_event', customEvent.data.custom_event_type, customEvent.data.event_name].join(':'); - } - return null; - default: - return null; - } - }; - KitBlocker.prototype.getProductAttributeMatchKey = function (eventToMatch) { - switch (eventToMatch.event_type) { - case dist.EventTypeEnum.commerceEvent: - var commerceEvent = eventToMatch; - var matchKey = []; - var _a = commerceEvent.data, - product_action = _a.product_action, - product_impressions = _a.product_impressions, - promotion_action = _a.promotion_action; - if (product_action) { - matchKey.push(DataPlanMatchType.ProductAction); - matchKey.push(product_action.action); - matchKey.push('ProductAttributes'); - } else if (promotion_action) { - matchKey.push(DataPlanMatchType.PromotionAction); - matchKey.push(promotion_action.action); - matchKey.push('ProductAttributes'); - } else if (product_impressions) { - matchKey.push(DataPlanMatchType.ProductImpression); - matchKey.push('ProductAttributes'); - } - return matchKey.join(':'); - default: - return null; - } - }; - KitBlocker.prototype.createBlockedEvent = function (event) { - /* - return a transformed event based on event/event attributes, - then product attributes if applicable, then user attributes, - then the user identities - */ - try { - if (event) { - event = this.transformEventAndEventAttributes(event); - } - if (event && event.EventDataType === Types.MessageType.Commerce) { - event = this.transformProductAttributes(event); - } - if (event) { - event = this.transformUserAttributes(event); - event = this.transformUserIdentities(event); - } - return event; - } catch (e) { - return event; - } - }; - KitBlocker.prototype.transformEventAndEventAttributes = function (event) { - var clonedEvent = __assign({}, event); - var baseEvent = convertEvent(clonedEvent); - var matchKey = this.getMatchKey(baseEvent); - var matchedEvent = this.dataPlanMatchLookups[matchKey]; - if (this.blockEvents) { - /* - If the event is not planned, it doesn't exist in dataPlanMatchLookups - and should be blocked (return null to not send anything to forwarders) - */ - if (!matchedEvent) { - return null; - } - } - if (this.blockEventAttributes) { - /* - matchedEvent is set to `true` if additionalProperties is `true` - otherwise, delete attributes that exist on event.EventAttributes - that aren't on - */ - if (matchedEvent === true) { - return clonedEvent; - } - if (matchedEvent) { - for (var _i = 0, _a = Object.keys(clonedEvent.EventAttributes); _i < _a.length; _i++) { - var key = _a[_i]; - if (!matchedEvent[key]) { - delete clonedEvent.EventAttributes[key]; - } - } - return clonedEvent; - } else { - return clonedEvent; - } - } - return clonedEvent; - }; - KitBlocker.prototype.transformProductAttributes = function (event) { - var _a; - var clonedEvent = __assign({}, event); - var baseEvent = convertEvent(clonedEvent); - var matchKey = this.getProductAttributeMatchKey(baseEvent); - var matchedEvent = this.dataPlanMatchLookups[matchKey]; - function removeAttribute(matchedEvent, productList) { - productList.forEach(function (product) { - for (var _i = 0, _a = Object.keys(product.Attributes); _i < _a.length; _i++) { - var productKey = _a[_i]; - if (!matchedEvent[productKey]) { - delete product.Attributes[productKey]; - } - } - }); - } - if (this.blockEvents) { - /* - If the event is not planned, it doesn't exist in dataPlanMatchLookups - and should be blocked (return null to not send anything to forwarders) - */ - if (!matchedEvent) { - return null; - } - } - if (this.blockEventAttributes) { - /* - matchedEvent is set to `true` if additionalProperties is `true` - otherwise, delete attributes that exist on event.EventAttributes - that aren't on - */ - if (matchedEvent === true) { - return clonedEvent; - } - if (matchedEvent) { - switch (event.EventCategory) { - case Types.CommerceEventType.ProductImpression: - clonedEvent.ProductImpressions.forEach(function (impression) { - removeAttribute(matchedEvent, impression === null || impression === void 0 ? void 0 : impression.ProductList); - }); - break; - case Types.CommerceEventType.ProductPurchase: - removeAttribute(matchedEvent, (_a = clonedEvent.ProductAction) === null || _a === void 0 ? void 0 : _a.ProductList); - break; - default: - this.mpInstance.Logger.warning('Product Not Supported '); - } - return clonedEvent; - } else { - return clonedEvent; - } - } - return clonedEvent; - }; - KitBlocker.prototype.transformUserAttributes = function (event) { - var clonedEvent = __assign({}, event); - if (this.blockUserAttributes) { - /* - If the user attribute is not found in the matchedAttributes - then remove it from event.UserAttributes as it is blocked - */ - var matchedAttributes = this.dataPlanMatchLookups['user_attributes']; - if (this.mpInstance._Helpers.isObject(matchedAttributes)) { - for (var _i = 0, _a = Object.keys(clonedEvent.UserAttributes); _i < _a.length; _i++) { - var ua = _a[_i]; - if (!matchedAttributes[ua]) { - delete clonedEvent.UserAttributes[ua]; - } - } - } - } - return clonedEvent; - }; - KitBlocker.prototype.isAttributeKeyBlocked = function (key) { - /* used when an attribute is added to the user */ - if (!this.blockUserAttributes) { - return false; - } - var matchedAttributes = this.dataPlanMatchLookups['user_attributes']; - // When additionalProperties is set to true, matchedAttributes - // will be a boolean, otherwise it will return an object - if (typeof matchedAttributes === 'boolean' && matchedAttributes) { - return false; - } - if (_typeof$1(matchedAttributes) === "object") { - if (matchedAttributes[key] === true) { - return false; - } else { - return true; - } - } - // When "Block unplanned user attributes" is enabled and "Allow unplanned user - // attributes" is also enabled in the UI, allowing unplanned user attributes will be prioritized - return false; - }; - KitBlocker.prototype.isIdentityBlocked = function (key) { - /* used when an attribute is added to the user */ - if (!this.blockUserIdentities) { - return false; - } - if (this.blockUserIdentities) { - var matchedIdentities = this.dataPlanMatchLookups['user_identities']; - if (matchedIdentities === true) { - return false; - } - if (!matchedIdentities[key]) { - return true; - } - } else { - return false; - } - return false; - }; - KitBlocker.prototype.transformUserIdentities = function (event) { - var _this = this; - var _a; - /* - If the user identity is not found in matchedIdentities - then remove it from event.UserIdentities as it is blocked. - event.UserIdentities is of type [{Identity: 'id1', Type: 7}, ...] - and so to compare properly in matchedIdentities, each Type needs - to be converted to an identityName - */ - var clonedEvent = __assign({}, event); - if (this.blockUserIdentities) { - var matchedIdentities_1 = this.dataPlanMatchLookups['user_identities']; - if (this.mpInstance._Helpers.isObject(matchedIdentities_1)) { - if ((_a = clonedEvent === null || clonedEvent === void 0 ? void 0 : clonedEvent.UserIdentities) === null || _a === void 0 ? void 0 : _a.length) { - clonedEvent.UserIdentities.forEach(function (uiByType, i) { - var identityName = Types.IdentityType.getIdentityName(_this.mpInstance._Helpers.parseNumber(uiByType.Type)); - if (!matchedIdentities_1[identityName]) { - clonedEvent.UserIdentities.splice(i, 1); - } - }); - } - } - } - return clonedEvent; - }; - return KitBlocker; - }(); - - var buildUrl = function buildUrl(configUrl, apiKey, dataPlanConfig, isDevelopmentMode) { - var url = configUrl + apiKey + '/config'; - var env = isDevelopmentMode ? '1' : '0'; - var queryParams = ["env=".concat(env)]; - var _a = dataPlanConfig || {}, - planId = _a.planId, - planVersion = _a.planVersion; - if (planId) { - queryParams.push("plan_id=".concat(planId)); - } - if (planVersion) { - queryParams.push("plan_version=".concat(planVersion)); - } - return "".concat(url, "?").concat(queryParams.join('&')); - }; - function ConfigAPIClient(apiKey, config, mpInstance) { - var _this = this; - var baseUrl = 'https://' + mpInstance._Store.SDKConfig.configUrl; - var isDevelopmentMode = config.isDevelopmentMode; - var dataPlan = config.dataPlan; - var uploadUrl = buildUrl(baseUrl, apiKey, dataPlan, isDevelopmentMode); - var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); - this.getSDKConfiguration = function () { - return __awaiter(_this, void 0, void 0, function () { - var configResponse, fetchPayload, response, xhrResponse; - var _a, _b, _c; - return __generator(this, function (_d) { - switch (_d.label) { - case 0: - fetchPayload = { - method: 'get', - headers: { - Accept: 'text/plain;charset=UTF-8', - 'Content-Type': 'text/plain;charset=UTF-8' - }, - body: null - }; - _d.label = 1; - case 1: - _d.trys.push([1, 6,, 7]); - return [4 /*yield*/, uploader.upload(fetchPayload)]; - case 2: - response = _d.sent(); - if (!(response.status === 200)) return [3 /*break*/, 5]; - (_a = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _a === void 0 ? void 0 : _a.verbose('Successfully received configuration from server'); - if (!response.json) return [3 /*break*/, 4]; - return [4 /*yield*/, response.json()]; - case 3: - configResponse = _d.sent(); - return [2 /*return*/, configResponse]; - case 4: - xhrResponse = response; - configResponse = JSON.parse(xhrResponse.responseText); - return [2 /*return*/, configResponse]; - case 5: - (_b = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _b === void 0 ? void 0 : _b.verbose('Issue with receiving configuration from server, received HTTP Code of ' + response.statusText); - return [3 /*break*/, 7]; - case 6: - _d.sent(); - (_c = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _c === void 0 ? void 0 : _c.error('Error getting forwarder configuration from mParticle servers.'); - return [3 /*break*/, 7]; - case 7: - // Returns the original config object if we cannot retrieve the remote config - return [2 /*return*/, config]; - } - }); - }); - }; - } - - var ErrorCodes = { - UNKNOWN_ERROR: 'UNKNOWN_ERROR', - UNHANDLED_EXCEPTION: 'UNHANDLED_EXCEPTION', - IDENTITY_REQUEST: 'IDENTITY_REQUEST' - }; - var WSDKErrorSeverity = { - ERROR: 'ERROR', - INFO: 'INFO', - WARNING: 'WARNING' - }; - - var HTTPCodes$1 = Constants.HTTPCodes, - Messages$1 = Constants.Messages, - IdentityMethods = Constants.IdentityMethods; - var Modify = IdentityMethods.Modify; - function IdentityAPIClient(mpInstance) { - this.sendAliasRequest = function (aliasRequest, aliasCallback) { - return __awaiter(this, void 0, void 0, function () { - var Logger, invokeAliasCallback, aliasUrl, apiKey, uploadUrl, uploader, uploadPayload, response, aliasResponseBody, message, errorMessage, _a, xhrResponse, errorResponse, e_2, errorMessage; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - Logger = mpInstance.Logger; - invokeAliasCallback = mpInstance._Helpers.invokeAliasCallback; - aliasUrl = mpInstance._Store.SDKConfig.aliasUrl; - apiKey = mpInstance._Store.devToken; - Logger.verbose(Messages$1.InformationMessages.SendAliasHttp); - uploadUrl = "https://".concat(aliasUrl).concat(apiKey, "/Alias"); - uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); - uploadPayload = { - method: 'post', - headers: { - Accept: 'text/plain;charset=UTF-8', - 'Content-Type': 'application/json' - }, - body: JSON.stringify(aliasRequest) - }; - _b.label = 1; - case 1: - _b.trys.push([1, 13,, 14]); - return [4 /*yield*/, uploader.upload(uploadPayload)]; - case 2: - response = _b.sent(); - aliasResponseBody = void 0; - message = void 0; - errorMessage = void 0; - _a = response.status; - switch (_a) { - case HTTP_ACCEPTED: - return [3 /*break*/, 3]; - case HTTP_OK: - return [3 /*break*/, 3]; - case HTTP_BAD_REQUEST: - return [3 /*break*/, 4]; - } - return [3 /*break*/, 11]; - case 3: - // https://go.mparticle.com/work/SQDSDKS-6670 - message = 'Received Alias Response from server: ' + JSON.stringify(response.status); - return [3 /*break*/, 12]; - case 4: - if (!response.json) return [3 /*break*/, 9]; - _b.label = 5; - case 5: - _b.trys.push([5, 7,, 8]); - return [4 /*yield*/, response.json()]; - case 6: - aliasResponseBody = _b.sent(); - return [3 /*break*/, 8]; - case 7: - _b.sent(); - Logger.verbose('The request has no response body'); - return [3 /*break*/, 8]; - case 8: - return [3 /*break*/, 10]; - case 9: - xhrResponse = response; - aliasResponseBody = xhrResponse.responseText ? JSON.parse(xhrResponse.responseText) : ''; - _b.label = 10; - case 10: - errorResponse = aliasResponseBody; - if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.message) { - errorMessage = errorResponse.message; - } - message = 'Issue with sending Alias Request to mParticle Servers, received HTTP Code of ' + response.status; - if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.code) { - message += ' - ' + errorResponse.code; - } - return [3 /*break*/, 12]; - case 11: - { - throw new Error('Received HTTP Code of ' + response.status); - } - case 12: - Logger.verbose(message); - invokeAliasCallback(aliasCallback, response.status, errorMessage); - return [3 /*break*/, 14]; - case 13: - e_2 = _b.sent(); - errorMessage = e_2.message || e_2.toString(); - Logger.error('Error sending alias request to mParticle servers. ' + errorMessage); - invokeAliasCallback(aliasCallback, HTTPCodes$1.noHttpCoverage, errorMessage); - return [3 /*break*/, 14]; - case 14: - return [2 /*return*/]; - } - }); - }); - }; - - this.sendIdentityRequest = function (identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid, knownIdentities) { - var _a, _b, _c, _d, _e; - return __awaiter(this, void 0, void 0, function () { - var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _f, responseBody, errorResponse, errorMessage, errorMessage, requestCount, err_1, requestCount, errorMessage, msg; - return __generator(this, function (_g) { - switch (_g.label) { - case 0: - if ((_a = mpInstance._RoktManager) === null || _a === void 0 ? void 0 : _a.isInitialized) { - mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1; - requestCount = mpInstance._Store.identifyRequestCount; - mpInstance.captureTiming("".concat(requestCount, "-identityRequestStart")); - } - invokeCallback = mpInstance._Helpers.invokeCallback; - Logger = mpInstance.Logger; - Logger.verbose(Messages$1.InformationMessages.SendIdentityBegin); - if (!identityApiRequest) { - Logger.error(Messages$1.ErrorMessages.APIRequestEmpty); - return [2 /*return*/]; - } - - Logger.verbose(Messages$1.InformationMessages.SendIdentityHttp); - if (mpInstance._Store.identityCallInFlight) { - invokeCallback(callback, HTTPCodes$1.activeIdentityRequest, 'There is currently an Identity request processing. Please wait for this to return before requesting again'); - return [2 /*return*/]; - } - - previousMPID = mpid || null; - uploadUrl = this.getUploadUrl(method, mpid); - uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); - fetchPayload = { - method: 'post', - headers: { - Accept: 'text/plain;charset=UTF-8', - 'Content-Type': 'application/json', - 'x-mp-key': mpInstance._Store.devToken - }, - body: JSON.stringify(identityApiRequest) - }; - mpInstance._Store.identityCallInFlight = true; - _g.label = 1; - case 1: - _g.trys.push([1, 9,, 10]); - return [4 /*yield*/, uploader.upload(fetchPayload)]; - case 2: - response = _g.sent(); - identityResponse = void 0; - message = void 0; - _f = response.status; - switch (_f) { - case HTTP_ACCEPTED: - return [3 /*break*/, 3]; - case HTTP_OK: - return [3 /*break*/, 3]; - case HTTP_BAD_REQUEST: - return [3 /*break*/, 3]; - } - return [3 /*break*/, 7]; - case 3: - if (!response.json) return [3 /*break*/, 5]; - return [4 /*yield*/, response.json()]; - case 4: - responseBody = _g.sent(); - identityResponse = this.getIdentityResponseFromFetch(response, responseBody); - return [3 /*break*/, 6]; - case 5: - identityResponse = this.getIdentityResponseFromXHR(response); - _g.label = 6; - case 6: - if (identityResponse.status === HTTP_BAD_REQUEST) { - errorResponse = identityResponse.responseText; - message = 'Issue with sending Identity Request to mParticle Servers, received HTTP Code of ' + identityResponse.status; - if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.Errors) { - errorMessage = errorResponse.Errors.map(function (error) { - return error.message; - }).join(', '); - message += ' - ' + errorMessage; - } - } else { - message = 'Received Identity Response from server: '; - message += JSON.stringify(identityResponse.responseText); - } - return [3 /*break*/, 8]; - case 7: - { - if (response.status >= HTTP_SERVER_ERROR) { - throw new Error('Received HTTP Code of ' + response.status); - } - mpInstance._Store.identityCallInFlight = false; - mpInstance._Store.identityCallFailed = false; - errorMessage = 'Received HTTP Code of ' + response.status; - Logger.error('Error sending identity request to servers - ' + errorMessage); - invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); - return [2 /*return*/]; - } - case 8: - mpInstance._Store.identityCallInFlight = false; - mpInstance._Store.identityCallFailed = false; - Logger.verbose(message); - if ((_b = mpInstance._RoktManager) === null || _b === void 0 ? void 0 : _b.isInitialized) { - requestCount = mpInstance._Store.identifyRequestCount; - mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); - } - parseIdentityResponse(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false); - return [3 /*break*/, 10]; - case 9: - err_1 = _g.sent(); - mpInstance._Store.identityCallInFlight = false; - mpInstance._Store.identityCallFailed = true; - if ((_c = mpInstance._RoktManager) === null || _c === void 0 ? void 0 : _c.isInitialized) { - requestCount = mpInstance._Store.identifyRequestCount; - mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); - } - errorMessage = err_1.message || err_1.toString(); - msg = 'Error sending identity request to servers' + ' - ' + errorMessage; - Logger.error(msg); - (_d = mpInstance._ErrorReportingDispatcher) === null || _d === void 0 ? void 0 : _d.report({ - message: msg, - code: ErrorCodes.IDENTITY_REQUEST, - severity: WSDKErrorSeverity.ERROR - }); - (_e = mpInstance.processQueueOnIdentityFailure) === null || _e === void 0 ? void 0 : _e.call(mpInstance); - invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); - return [3 /*break*/, 10]; - case 10: - return [2 /*return*/]; - } - }); - }); - }; - - this.getUploadUrl = function (method, mpid) { - var uploadServiceUrl = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.identityUrl); - var uploadUrl = method === Modify ? uploadServiceUrl + mpid + '/' + method : uploadServiceUrl + method; - return uploadUrl; - }; - this.getIdentityResponseFromFetch = function (response, responseBody) { - return { - status: response.status, - responseText: responseBody, - cacheMaxAge: parseInt(response.headers.get(CACHE_HEADER)) || 0, - expireTimestamp: 0 - }; - }; - this.getIdentityResponseFromXHR = function (response) { - return { - status: response.status, - responseText: response.responseText ? JSON.parse(response.responseText) : {}, - cacheMaxAge: parseNumber(response.getResponseHeader(CACHE_HEADER) || ''), - expireTimestamp: 0 - }; - }; - } - - // Facebook Click ID has specific formatting rules - // The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: - // - version is always this prefix: fb - // - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2) - // - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value - // - is the value for the fbclid query parameter in the page URL. - // https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc - var facebookClickIdProcessor = function facebookClickIdProcessor(clickId, url, timestamp) { - if (!clickId || !url) { - return ''; - } - var urlSegments = url === null || url === void 0 ? void 0 : url.split('//'); - if (!urlSegments) { - return ''; - } - var urlParts = urlSegments[1].split('/'); - var domainParts = urlParts[0].split('.'); - var subdomainIndex = 1; - // The rules for subdomainIndex are for parsing the domain portion - // of the URL for cookies, but in this case we are parsing the URL - // itself, so we can ignore the use of 0 for 'com' - if (domainParts.length >= 3) { - subdomainIndex = 2; - } - // If timestamp is not provided, use the current time - var _timestamp = timestamp || Date.now(); - return "fb.".concat(subdomainIndex, ".").concat(_timestamp, ".").concat(clickId); - }; - // Integration outputs are used to determine how click ids are used within the SDK - // CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject - // PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch - // INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created - var IntegrationOutputs = { - CUSTOM_FLAGS: 'custom_flags', - PARTNER_IDENTITIES: 'partner_identities', - INTEGRATION_ATTRIBUTES: 'integration_attributes' - }; - var integrationMappingExternal = { - // Facebook / Meta - fbclid: { - mappedKey: 'Facebook.ClickId', - processor: facebookClickIdProcessor, - output: IntegrationOutputs.CUSTOM_FLAGS - }, - _fbp: { - mappedKey: 'Facebook.BrowserId', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - _fbc: { - mappedKey: 'Facebook.ClickId', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - // Google - gclid: { - mappedKey: 'GoogleEnhancedConversions.Gclid', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - gbraid: { - mappedKey: 'GoogleEnhancedConversions.Gbraid', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - wbraid: { - mappedKey: 'GoogleEnhancedConversions.Wbraid', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - // TIKTOK - ttclid: { - mappedKey: 'TikTok.Callback', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - _ttp: { - mappedKey: 'tiktok_cookie_id', - output: IntegrationOutputs.PARTNER_IDENTITIES - }, - // Snapchat - // https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US - ScCid: { - mappedKey: 'SnapchatConversions.ClickId', - output: IntegrationOutputs.CUSTOM_FLAGS - }, - // Snapchat - // https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id - _scid: { - mappedKey: 'SnapchatConversions.Cookie1', - output: IntegrationOutputs.CUSTOM_FLAGS - } - }; - var integrationMappingRokt = { - // Rokt - // https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/ - // https://go.mparticle.com/work/SQDSDKS-7167 - rtid: { - mappedKey: 'passbackconversiontrackingid', - output: IntegrationOutputs.INTEGRATION_ATTRIBUTES, - moduleId: 1277 - }, - rclid: { - mappedKey: 'passbackconversiontrackingid', - output: IntegrationOutputs.INTEGRATION_ATTRIBUTES, - moduleId: 1277 - }, - RoktTransactionId: { - mappedKey: 'passbackconversiontrackingid', - output: IntegrationOutputs.INTEGRATION_ATTRIBUTES, - moduleId: 1277 - } - }; - var IntegrationCapture = /** @class */function () { - function IntegrationCapture(captureMode) { - this.initialTimestamp = Date.now(); - this.captureMode = captureMode; - // Cache filtered mappings for faster access - this.filteredPartnerIdentityMappings = this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES); - this.filteredCustomFlagMappings = this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS); - this.filteredIntegrationAttributeMappings = this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES); - } - /** - * Captures Integration Ids from cookies and query params and stores them in clickIds object - */ - IntegrationCapture.prototype.capture = function () { - var queryParams = this.captureQueryParams() || {}; - var cookies = this.captureCookies() || {}; - var localStorage = this.captureLocalStorage() || {}; - // Facebook Rules - // Exclude _fbc if fbclid is present - // https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc#retrieve-from-fbclid-url-query-parameter - if (queryParams['fbclid'] && cookies['_fbc']) { - delete cookies['_fbc']; - } - // ROKT Rules - // If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid - // If RoktTransactionId is present in both cookies and localStorage, - // prioritize localStorage - var hasQueryParamId = queryParams['rtid'] || queryParams['rclid']; - var hasLocalStorageId = localStorage['RoktTransactionId']; - var hasCookieId = cookies['RoktTransactionId']; - if (hasQueryParamId) { - // Query param takes precedence, remove both localStorage and cookie if present - if (hasLocalStorageId) { - delete localStorage['RoktTransactionId']; - } - if (hasCookieId) { - delete cookies['RoktTransactionId']; - } - } else if (hasLocalStorageId && hasCookieId) { - // No query param, but both localStorage and cookie exist - // localStorage takes precedence over cookie - delete cookies['RoktTransactionId']; - } - this.clickIds = __assign(__assign(__assign(__assign({}, this.clickIds), queryParams), localStorage), cookies); - }; - /** - * Captures cookies based on the integration ID mapping. - */ - IntegrationCapture.prototype.captureCookies = function () { - var integrationKeys = this.getAllowedKeysForMode(); - var cookies = getCookies(integrationKeys); - return this.applyProcessors(cookies, getHref(), this.initialTimestamp); - }; - /** - * Captures query parameters based on the integration ID mapping. - */ - IntegrationCapture.prototype.captureQueryParams = function () { - var queryParams = this.getQueryParams(); - return this.applyProcessors(queryParams, getHref(), this.initialTimestamp); - }; - /** - * Captures local storage based on the integration ID mapping. - */ - IntegrationCapture.prototype.captureLocalStorage = function () { - var integrationKeys = this.getAllowedKeysForMode(); - var localStorageItems = {}; - for (var _i = 0, integrationKeys_1 = integrationKeys; _i < integrationKeys_1.length; _i++) { - var key = integrationKeys_1[_i]; - var localStorageItem = localStorage.getItem(key); - if (localStorageItem) { - localStorageItems[key] = localStorageItem; - } - } - return this.applyProcessors(localStorageItems, getHref(), this.initialTimestamp); - }; - /** - * Gets the query parameters based on the integration ID mapping. - * @returns {Dictionary} The query parameters. - */ - IntegrationCapture.prototype.getQueryParams = function () { - var integrationKeys = this.getAllowedKeysForMode(); - return queryStringParser(getHref(), integrationKeys); - }; - /** - * Converts captured click IDs to custom flags for SDK events. - * @returns {SDKEventCustomFlags} The custom flags. - */ - IntegrationCapture.prototype.getClickIdsAsCustomFlags = function () { - return this.getClickIds(this.clickIds, this.filteredCustomFlagMappings); - }; - /** - * Returns only the `partner_identities` mapped integration output. - * @returns {Dictionary} The partner identities. - */ - IntegrationCapture.prototype.getClickIdsAsPartnerIdentities = function () { - return this.getClickIds(this.clickIds, this.filteredPartnerIdentityMappings); - }; - /** - * Returns only the `integration_attributes` mapped integration output. - * @returns {IntegrationAttributes} The integration attributes. - */ - IntegrationCapture.prototype.getClickIdsAsIntegrationAttributes = function () { - var _a; - var _b, _c; - // Integration IDs are stored in the following format: - // { - // "integration_attributes": { - // "": { - // "mappedKey": "clickIdValue" - // } - // } - // } - var mappedClickIds = {}; - for (var key in this.clickIds) { - if (this.clickIds.hasOwnProperty(key)) { - var value = this.clickIds[key]; - var mappingKey = (_b = this.filteredIntegrationAttributeMappings[key]) === null || _b === void 0 ? void 0 : _b.mappedKey; - if (!isEmpty(mappingKey)) { - var moduleId = (_c = this.filteredIntegrationAttributeMappings[key]) === null || _c === void 0 ? void 0 : _c.moduleId; - if (moduleId && !mappedClickIds[moduleId]) { - mappedClickIds[moduleId] = (_a = {}, _a[mappingKey] = value, _a); - } - } - } - } - return mappedClickIds; - }; - IntegrationCapture.prototype.getClickIds = function (clickIds, mappingList) { - var _a; - var mappedClickIds = {}; - if (!clickIds) { - return mappedClickIds; - } - for (var key in clickIds) { - if (clickIds.hasOwnProperty(key)) { - var value = clickIds[key]; - var mappedKey = (_a = mappingList[key]) === null || _a === void 0 ? void 0 : _a.mappedKey; - if (!isEmpty(mappedKey)) { - mappedClickIds[mappedKey] = value; - } - } - } - return mappedClickIds; - }; - IntegrationCapture.prototype.applyProcessors = function (clickIds, url, timestamp) { - var _a; - var processedClickIds = {}; - var integrationKeys = this.getActiveIntegrationMapping(); - for (var key in clickIds) { - if (clickIds.hasOwnProperty(key)) { - var value = clickIds[key]; - var processor = (_a = integrationKeys[key]) === null || _a === void 0 ? void 0 : _a.processor; - processedClickIds[key] = processor ? processor(value, url, timestamp) : value; - } - } - return processedClickIds; - }; - IntegrationCapture.prototype.filterMappings = function (outputType) { - var filteredMappings = {}; - var integrationKeys = this.getActiveIntegrationMapping(); - for (var key in integrationKeys) { - if (integrationKeys[key].output === outputType) { - filteredMappings[key] = integrationKeys[key]; - } - } - return filteredMappings; - }; - /** - * Returns the allowed keys to capture based on the current mode. - * For RoktOnly, limit capture to Rokt keys; for All, capture all mapped keys. - */ - IntegrationCapture.prototype.getAllowedKeysForMode = function () { - return Object.keys(this.getActiveIntegrationMapping()); - }; - /** - * Selects the active integration mapping for the current captureMode. - * - 'roktonly': only Rokt IDs are considered - * - 'all': both External and Rokt IDs are considered - * - else: returns an empty mapping and nothing will be captured - */ - IntegrationCapture.prototype.getActiveIntegrationMapping = function () { - if (this.captureMode === Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly) { - return integrationMappingRokt; - } - if (this.captureMode === Constants.CaptureIntegrationSpecificIdsV2Modes.All) { - return __assign(__assign({}, integrationMappingExternal), integrationMappingRokt); - } - return {}; - }; - return IntegrationCapture; - }(); - - // The purpose of this class is to create a link between the Core mParticle SDK and the - // Rokt Web SDK via a Web Kit. - // The Rokt Manager should load before the Web Kit and stubs out many of the - // Rokt Web SDK functions with an internal message queue in case a Rokt function - // is requested before the Rokt Web Kit or SDK is finished loaded. - // Once the Rokt Kit is attached to the Rokt Manager, we can consider the - // Rokt Manager in a "ready" state and it can begin sending data to the kit. - // - // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt - var RoktManager = /** @class */function () { - function RoktManager() { - this.kit = null; - this.filters = {}; - this.currentUser = null; - this.messageQueue = new Map(); - this.sandbox = null; - this.placementAttributesMapping = []; - this.onReadyCallback = null; - this.initialized = false; - } - /** - * Sets a callback to be invoked when RoktManager becomes ready - */ - RoktManager.prototype.setOnReadyCallback = function (callback) { - this.onReadyCallback = callback; - }; - /** - * Initializes the RoktManager with configuration settings and user data. - * - * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings - * @param {IMParticleUser} filteredUser - User object with filtered attributes - * @param {SDKIdentityApi} identityService - The mParticle Identity instance - * @param {SDKLoggerApi} logger - The mParticle Logger instance - * @param {IRoktOptions} options - Options for the RoktManager - * @param {Function} captureTiming - Function to capture performance timing marks - * - * @throws Logs error to console if placementAttributesMapping parsing fails - */ - RoktManager.prototype.init = function (roktConfig, filteredUser, identityService, store, logger, options, captureTiming) { - var _a, _b; - var _c = roktConfig || {}, - userAttributeFilters = _c.userAttributeFilters, - settings = _c.settings; - var _d = settings || {}, - placementAttributesMapping = _d.placementAttributesMapping, - hashedEmailUserIdentityType = _d.hashedEmailUserIdentityType; - this.mappedEmailShaIdentityType = (_a = hashedEmailUserIdentityType === null || hashedEmailUserIdentityType === void 0 ? void 0 : hashedEmailUserIdentityType.toLowerCase()) !== null && _a !== void 0 ? _a : null; - this.identityService = identityService; - this.store = store; - this.logger = logger; - this.captureTiming = captureTiming; - (_b = this.captureTiming) === null || _b === void 0 ? void 0 : _b.call(this, PerformanceMarkType.JointSdkRoktKitInit); - this.filters = { - userAttributeFilters: userAttributeFilters, - filterUserAttributes: KitFilterHelper.filterUserAttributes, - filteredUser: filteredUser - }; - try { - this.placementAttributesMapping = parseSettingsString(placementAttributesMapping); - } catch (error) { - this.logger.error('Error parsing placement attributes mapping from config: ' + error); - } - // This is the global setting for sandbox mode - // It is set here and passed in to the createLauncher method in the Rokt Kit - // This is not to be confused for the `sandbox` flag in the selectPlacements attributes - // as that is independent of this setting, though they share the same name. - var sandbox = (options === null || options === void 0 ? void 0 : options.sandbox) || false; - // Launcher options are set here for the kit to pick up and pass through - // to the Rokt Launcher. - this.launcherOptions = __assign({ - sandbox: sandbox - }, options === null || options === void 0 ? void 0 : options.launcherOptions); - if (options === null || options === void 0 ? void 0 : options.domain) { - this.domain = options.domain; - } - // initialized indicates that init() has been called and the RoktManager has been initialized. - // This is different from isReady(), which only returns true once the kit has been attached - // (which is asynchronous), and has a launcher. - this.initialized = true; - }; - Object.defineProperty(RoktManager.prototype, "isInitialized", { - get: function get() { - return this.initialized; - }, - enumerable: false, - configurable: true - }); - RoktManager.prototype.attachKit = function (kit) { - var _a, _b, _c, _d; - this.kit = kit; - if ((_a = kit.settings) === null || _a === void 0 ? void 0 : _a.accountId) { - this.store.setRoktAccountId(kit.settings.accountId); - } - if (kit.integrationName) { - (_b = this.store) === null || _b === void 0 ? void 0 : _b.setIntegrationName(kit.integrationName); - } - this.processMessageQueue(); - try { - (_c = this.onReadyCallback) === null || _c === void 0 ? void 0 : _c.call(this); - } catch (e) { - (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error('RoktManager: Error in onReadyCallback: ' + e); - } - }; - /** - * Renders ads based on the options provided - * - * @param {IRoktSelectPlacementsOptions} options - The options for selecting placements, including attributes and optional identifier - * @returns {Promise} A promise that resolves to the selection - * - * @example - * // Correct usage with await - * await window.mParticle.Rokt.selectPlacements({ - * attributes: { - * email: 'user@example.com', - * customAttr: 'value' - * } - * }); - */ - RoktManager.prototype.selectPlacements = function (options) { - var _a, _b, _c, _d, _e, _f, _g; - return __awaiter(this, void 0, void 0, function () { - var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail, currentHashedEmail, newHashedEmail, isValidHashedEmailIdentityType, emailChanged, hashedEmailChanged, newIdentities_1, error_1, finalUserIdentities, enrichedAttributes, hashedEmail, enrichedOptions, error_2; - var _this = this; - return __generator(this, function (_h) { - switch (_h.label) { - case 0: - (_a = this.captureTiming) === null || _a === void 0 ? void 0 : _a.call(this, PerformanceMarkType.JointSdkSelectPlacements); - // Queue if kit isn't ready OR if identity is in flight - if (!this.isReady() || ((_b = this.store) === null || _b === void 0 ? void 0 : _b.identityCallInFlight)) { - return [2 /*return*/, this.deferredCall('selectPlacements', options)]; - } - _h.label = 1; - case 1: - _h.trys.push([1, 6,, 7]); - attributes = options.attributes; - sandboxValue = (attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) || null; - mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping); - (_c = this.logger) === null || _c === void 0 ? void 0 : _c.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(attributes, null, 2))); - this.currentUser = this.identityService.getCurrentUser(); - currentUserIdentities_1 = ((_e = (_d = this.currentUser) === null || _d === void 0 ? void 0 : _d.getUserIdentities()) === null || _e === void 0 ? void 0 : _e.userIdentities) || {}; - currentEmail = currentUserIdentities_1.email; - newEmail = mappedAttributes.email; - currentHashedEmail = void 0; - newHashedEmail = void 0; - isValidHashedEmailIdentityType = this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false; - if (isValidHashedEmailIdentityType) { - currentHashedEmail = currentUserIdentities_1[this.mappedEmailShaIdentityType]; - newHashedEmail = mappedAttributes['emailsha256'] || mappedAttributes[this.mappedEmailShaIdentityType] || undefined; - } - emailChanged = this.hasIdentityChanged(currentEmail, newEmail); - hashedEmailChanged = this.hasIdentityChanged(currentHashedEmail, newHashedEmail); - newIdentities_1 = {}; - if (emailChanged) { - newIdentities_1.email = newEmail; - if (newEmail) { - this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation."); - } - } - if (hashedEmailChanged) { - newIdentities_1[this.mappedEmailShaIdentityType] = newHashedEmail; - this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation."); - } - if (!!isEmpty(newIdentities_1)) return [3 /*break*/, 5]; - _h.label = 2; - case 2: - _h.trys.push([2, 4,, 5]); - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.identityService.identify({ - userIdentities: __assign(__assign({}, currentUserIdentities_1), newIdentities_1) - }, function () { - resolve(); - }); - })]; - case 3: - _h.sent(); - return [3 /*break*/, 5]; - case 4: - error_1 = _h.sent(); - this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error_1)); - return [3 /*break*/, 5]; - case 5: - // Refresh current user identities to ensure we have the latest values before building enrichedAttributes - this.currentUser = this.identityService.getCurrentUser(); - finalUserIdentities = ((_g = (_f = this.currentUser) === null || _f === void 0 ? void 0 : _f.getUserIdentities()) === null || _g === void 0 ? void 0 : _g.userIdentities) || {}; - this.setUserAttributes(mappedAttributes); - enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? { - sandbox: sandboxValue - } : {}); - // Propagate email from current user identities if not already in attributes - if (finalUserIdentities.email && !enrichedAttributes.email) { - enrichedAttributes.email = finalUserIdentities.email; - } - // Propagate emailsha256 from current user identities if not already in attributes - if (isValidHashedEmailIdentityType) { - hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType]; - if (hashedEmail && !enrichedAttributes.emailsha256 && !enrichedAttributes[this.mappedEmailShaIdentityType]) { - enrichedAttributes.emailsha256 = hashedEmail; - } - } - this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null; - enrichedOptions = __assign(__assign({}, options), { - attributes: enrichedAttributes - }); - return [2 /*return*/, this.kit.selectPlacements(enrichedOptions)]; - case 6: - error_2 = _h.sent(); - return [2 /*return*/, Promise.reject(error_2 instanceof Error ? error_2 : new Error('Unknown error occurred'))]; - case 7: - return [2 /*return*/]; - } - }); - }); - }; - /** - * Hashes attributes and returns both original and hashed versions - * with Rokt-compatible key names (like emailsha256, mobilesha256) - * - * - * @param {RoktAttributes} attributes - Attributes to hash - * @returns {Promise} Object with both original and hashed attributes - * - */ - RoktManager.prototype.hashAttributes = function (attributes) { - return __awaiter(this, void 0, void 0, function () { - var keys, hashPromises, results, hashedAttributes, _i, results_1, _a, key, attributeValue, hashedValue, error_3, errorMessage; - var _this = this; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2,, 3]); - if (!attributes || _typeof$1(attributes) !== 'object') { - return [2 /*return*/, {}]; - } - keys = Object.keys(attributes); - if (keys.length === 0) { - return [2 /*return*/, {}]; - } - hashPromises = keys.map(function (key) { - return __awaiter(_this, void 0, void 0, function () { - var attributeValue, hashedValue; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - attributeValue = attributes[key]; - return [4 /*yield*/, this.hashSha256(attributeValue)]; - case 1: - hashedValue = _a.sent(); - return [2 /*return*/, { - key: key, - attributeValue: attributeValue, - hashedValue: hashedValue - }]; - } - }); - }); - }); - return [4 /*yield*/, Promise.all(hashPromises)]; - case 1: - results = _b.sent(); - hashedAttributes = {}; - for (_i = 0, results_1 = results; _i < results_1.length; _i++) { - _a = results_1[_i], key = _a.key, attributeValue = _a.attributeValue, hashedValue = _a.hashedValue; - hashedAttributes[key] = attributeValue; - if (hashedValue) { - hashedAttributes["".concat(key, "sha256")] = hashedValue; - } - } - return [2 /*return*/, hashedAttributes]; - case 2: - error_3 = _b.sent(); - errorMessage = error_3 instanceof Error ? error_3.message : String(error_3); - this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(errorMessage)); - return [2 /*return*/, {}]; - case 3: - return [2 /*return*/]; - } - }); - }); - }; - - RoktManager.prototype.setExtensionData = function (extensionData) { - if (!this.isReady()) { - this.deferredCall('setExtensionData', extensionData); - return; - } - try { - this.kit.setExtensionData(extensionData); - } catch (error) { - var errorMessage = error instanceof Error ? error.message : String(error); - throw new Error('Error setting extension data: ' + errorMessage); - } - }; - RoktManager.prototype.use = function (name) { - if (!this.isReady()) { - return this.deferredCall('use', name); - } - try { - return this.kit.use(name); - } catch (error) { - return Promise.reject(error instanceof Error ? error : new Error('Error using extension: ' + name)); - } - }; - /** - * Hashes an attribute using SHA-256 - * - * @param {string | number | boolean | undefined | null} attribute - The value to hash - * @returns {Promise} SHA-256 hashed value or undefined/null - * - */ - RoktManager.prototype.hashSha256 = function (attribute) { - return __awaiter(this, void 0, void 0, function () { - var normalizedValue, error_4, errorMessage; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (attribute === null || attribute === undefined) { - this.logger.warning("hashSha256 received null/undefined as input"); - return [2 /*return*/, attribute]; - } - _a.label = 1; - case 1: - _a.trys.push([1, 3,, 4]); - normalizedValue = String(attribute).trim().toLocaleLowerCase(); - return [4 /*yield*/, this.sha256Hex(normalizedValue)]; - case 2: - return [2 /*return*/, _a.sent()]; - case 3: - error_4 = _a.sent(); - errorMessage = error_4 instanceof Error ? error_4.message : String(error_4); - this.logger.error("Failed to hashSha256, returning undefined: ".concat(errorMessage)); - return [2 /*return*/, undefined]; - case 4: - return [2 /*return*/]; - } - }); - }); - }; - - RoktManager.prototype.getLocalSessionAttributes = function () { - return this.store.getLocalSessionAttributes(); - }; - RoktManager.prototype.setLocalSessionAttribute = function (key, value) { - this.store.setLocalSessionAttribute(key, value); - }; - RoktManager.prototype.isReady = function () { - // The Rokt Manager is ready when a kit is attached and has a launcher - return Boolean(this.kit && this.kit.launcher); - }; - RoktManager.prototype.setUserAttributes = function (attributes) { - var reservedAttributes = ['sandbox']; - var filteredAttributes = {}; - for (var key in attributes) { - if (attributes.hasOwnProperty(key) && reservedAttributes.indexOf(key) === -1) { - var value = attributes[key]; - filteredAttributes[key] = Array.isArray(value) ? JSON.stringify(value) : value; - } - } - try { - this.currentUser.setUserAttributes(filteredAttributes); - } catch (error) { - this.logger.error('Error setting user attributes: ' + error); - } - }; - RoktManager.prototype.mapPlacementAttributes = function (attributes, placementAttributesMapping) { - var mappingLookup = {}; - for (var _i = 0, placementAttributesMapping_1 = placementAttributesMapping; _i < placementAttributesMapping_1.length; _i++) { - var mapping = placementAttributesMapping_1[_i]; - mappingLookup[mapping.map] = mapping.value; - } - var mappedAttributes = {}; - for (var key in attributes) { - if (attributes.hasOwnProperty(key)) { - var newKey = mappingLookup[key] || key; - mappedAttributes[newKey] = attributes[key]; - } - } - return mappedAttributes; - }; - RoktManager.prototype.onIdentityComplete = function () { - if (this.isReady()) { - this.currentUser = this.identityService.getCurrentUser(); - // Process any queued selectPlacements calls that were waiting for identity - this.processMessageQueue(); - } - }; - RoktManager.prototype.processMessageQueue = function () { - var _this = this; - var _a; - if (!this.isReady() || this.messageQueue.size === 0) { - return; - } - (_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages")); - var messagesToProcess = Array.from(this.messageQueue.values()); - // Clear the queue immediately to prevent re-processing - this.messageQueue.clear(); - messagesToProcess.forEach(function (message) { - var _a, _b; - if (!(message.methodName in _this) || !isFunction(_this[message.methodName])) { - (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Method ".concat(message.methodName, " not found")); - return; - } - (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.verbose("RoktManager: Processing queued message: ".concat(message.methodName, " with payload: ").concat(JSON.stringify(message.payload))); - // Capture resolve/reject functions before async processing - var resolve = message.resolve; - var reject = message.reject; - var handleError = function handleError(error) { - var _a; - var errorMessage = error instanceof Error ? error.message : String(error); - (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage)); - if (reject) { - reject(error); - } - }; - try { - var result = _this[message.methodName](message.payload); - // Handle both sync and async methods - Promise.resolve(result).then(function (resolvedResult) { - if (resolve) { - resolve(resolvedResult); - } - })["catch"](handleError); - } catch (error) { - handleError(error); - } - }); - }; - RoktManager.prototype.queueMessage = function (message) { - this.messageQueue.set(message.messageId, message); - }; - RoktManager.prototype.deferredCall = function (methodName, payload) { - var _this = this; - return new Promise(function (resolve, reject) { - var messageId = "".concat(methodName, "_").concat(generateUniqueId()); - _this.queueMessage({ - messageId: messageId, - methodName: methodName, - payload: payload, - resolve: resolve, - reject: reject - }); - }); - }; - /** - * Hashes a string input using SHA-256 and returns the hex digest - * Uses the Web Crypto API for secure hashing - * - * @param {string} input - The string to hash - * @returns {Promise} The SHA-256 hash as a hexadecimal string - */ - RoktManager.prototype.sha256Hex = function (input) { - return __awaiter(this, void 0, void 0, function () { - var encoder, encodedInput, digest; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - encoder = new TextEncoder(); - encodedInput = encoder.encode(input); - return [4 /*yield*/, crypto.subtle.digest('SHA-256', encodedInput)]; - case 1: - digest = _a.sent(); - return [2 /*return*/, this.arrayBufferToHex(digest)]; - } - }); - }); - }; - /** - * Converts an ArrayBuffer to a hexadecimal string representation - * Each byte is converted to a 2-character hex string with leading zeros - * - * @param {ArrayBuffer} buffer - The buffer to convert - * @returns {string} The hexadecimal string representation - */ - RoktManager.prototype.arrayBufferToHex = function (buffer) { - var bytes = new Uint8Array(buffer); - var hexString = ''; - for (var i = 0; i < bytes.length; i++) { - var hexByte = bytes[i].toString(16).padStart(2, '0'); - hexString += hexByte; - } - return hexString; - }; - /** - * Checks if an identity value has changed by comparing current and new values - * - * @param {string | undefined} currentValue - The current identity value - * @param {string | undefined} newValue - The new identity value to compare against - * @returns {boolean} True if the identity has changed (new value exists and differs from current), false otherwise - */ - RoktManager.prototype.hasIdentityChanged = function (currentValue, newValue) { - if (!newValue) { - return false; - } - if (!currentValue) { - return true; // New value exists but no current value - } - - if (currentValue !== newValue) { - return true; // Values are different - } - - return false; // Values are the same - }; - - return RoktManager; - }(); - - /** - * CookieConsentManager handles storage and access of consent flags (noFunctional, noTargeting) - * that are passed via launcherOptions during SDK initialization. - * - * These flags allow Rokt integration to respect user privacy choices. - * - * Default behavior: Both flags default to false, meaning all features are allowed - * unless explicitly opted out by the user. - */ - var CookieConsentManager = /** @class */function () { - function CookieConsentManager(flags) { - this.flags = flags; - this.flags = { - noFunctional: flags.noFunctional === true, - noTargeting: flags.noTargeting === true - }; - } - /** - * Returns true if third-party targeting is disabled. - * Targeting is allowed when noTargeting is false (default). - */ - CookieConsentManager.prototype.getNoTargeting = function () { - return this.flags.noTargeting; - }; - /** - * Returns true if functional tracking is disabled. - * Functional tracking is allowed when noFunctional is false (default). - */ - CookieConsentManager.prototype.getNoFunctional = function () { - return this.flags.noFunctional; - }; - return CookieConsentManager; - }(); - - var ErrorReportingDispatcher = /** @class */function () { - function ErrorReportingDispatcher() { - this.services = []; - } - ErrorReportingDispatcher.prototype.register = function (service) { - this.services.push(service); - }; - ErrorReportingDispatcher.prototype.report = function (error) { - this.services.forEach(function (s) { - return s.report(error); - }); - }; - return ErrorReportingDispatcher; - }(); - - var LoggingDispatcher = /** @class */function () { - function LoggingDispatcher() { - this.services = []; - } - LoggingDispatcher.prototype.register = function (service) { - this.services.push(service); - }; - LoggingDispatcher.prototype.log = function (entry) { - this.services.forEach(function (s) { - return s.log(entry); - }); - }; - return LoggingDispatcher; - }(); - - var Messages = Constants.Messages, - HTTPCodes = Constants.HTTPCodes, - FeatureFlags = Constants.FeatureFlags, - CaptureIntegrationSpecificIdsV2Modes = Constants.CaptureIntegrationSpecificIdsV2Modes; - var ReportBatching = FeatureFlags.ReportBatching, - CaptureIntegrationSpecificIds = FeatureFlags.CaptureIntegrationSpecificIds, - CaptureIntegrationSpecificIdsV2 = FeatureFlags.CaptureIntegrationSpecificIdsV2; - var StartingInitialization = Messages.InformationMessages.StartingInitialization; - /** - *

All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

- *

In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.

- *

This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().

- *

If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:

- * - * mParticle.init('apiKey', config, 'another_instance'); - * mParticle.getInstance('another_instance').logPageView(); - * - * - * @class mParticle & mParticleInstance - */ - function mParticleInstance(instanceName) { - var self = this; - // These classes are for internal use only. Not documented for public consumption - this._instanceName = instanceName; - this._NativeSdkHelpers = new NativeSdkHelpers(this); - this._SessionManager = new SessionManager(this); - this._Persistence = new _Persistence(this); - this._Helpers = new Helpers(this); - this._Events = new Events(this); - this._CookieSyncManager = new CookieSyncManager(this); - this._ServerModel = new ServerModel(this); - this._Ecommerce = new Ecommerce(this); - this._ForwardingStatsUploader = new forwardingStatsUploader(this); - this._Consent = new Consent(this); - this._IdentityAPIClient = new IdentityAPIClient(this); - this._preInit = { - readyQueue: [], - integrationDelays: {}, - forwarderConstructors: [] - }; - this._RoktManager = new RoktManager(); - this._RoktManager.setOnReadyCallback(function () { - self.processQueueOnIdentityFailure(); - }); - /** - * Processes message and ready queue when identity requests fails but Rokt is ready. - */ - this.processQueueOnIdentityFailure = function () { - var _a, _b, _c; - if ((_a = self._Store) === null || _a === void 0 ? void 0 : _a.isInitialized) { - return; - } - if (((_b = self._Store) === null || _b === void 0 ? void 0 : _b.identityCallFailed) && ((_c = self._RoktManager) === null || _c === void 0 ? void 0 : _c.isReady())) { - self._RoktManager.processMessageQueue(); - self._preInit.readyQueue = processReadyQueue(self._preInit.readyQueue); - } - }; - /** - * Drains the ready queue for noFunctional sessions with no explicit identity. - */ - this.processQueueOnNoFunctional = function () { - var _a, _b; - if ((_a = self._Store) === null || _a === void 0 ? void 0 : _a.isInitialized) { - return; - } - var noFunctionalWithoutId = ((_b = self._CookieConsentManager) === null || _b === void 0 ? void 0 : _b.getNoFunctional()) && !hasExplicitIdentifier(self._Store); - if (noFunctionalWithoutId) { - self._preInit.readyQueue = processReadyQueue(self._preInit.readyQueue); - } - }; - // required for forwarders once they reference the mparticle instance - this.IdentityType = IdentityType; - this.EventType = EventType; - this.CommerceEventType = CommerceEventType; - this.PromotionType = PromotionActionType; - this.ProductActionType = ProductActionType; - this._Identity = new Identity(this); - this.Identity = this._Identity.IdentityAPI; - this.generateHash = this._Helpers.generateHash; - // https://go.mparticle.com/work/SQDSDKS-6289 - // TODO: Replace this with Store once Store is moved earlier in the init process - this.getDeviceId = this._Persistence.getDeviceId; - if (typeof window !== 'undefined') { - if (window.mParticle && window.mParticle.config) { - if (window.mParticle.config.hasOwnProperty('rq')) { - this._preInit.readyQueue = window.mParticle.config.rq; - } - } - } - this.init = function (apiKey, config) { - var _this = this; - if (!config) { - console.warn('You did not pass a config object to init(). mParticle will not initialize properly'); - } - runPreConfigFetchInitialization(this, apiKey, config); - // config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization - // Since fetching the configuration is asynchronous, we must pass completeSDKInitialization - // to it for it to be run after fetched - if (config) { - if (!config.hasOwnProperty('requestConfig') || config.requestConfig) { - var configApiClient = new ConfigAPIClient(apiKey, config, this); - configApiClient.getSDKConfiguration().then(function (result) { - var mergedConfig = _this._Helpers.extend({}, config, result); - completeSDKInitialization(apiKey, mergedConfig, _this); - }); - } else { - completeSDKInitialization(apiKey, config, this); - } - } else { - console.error('No config available on the window, please pass a config object to mParticle.init()'); - return; - } - }; - /** - * Resets the SDK to an uninitialized state and removes cookies/localStorage. You MUST call mParticle.init(apiKey, window.mParticle.config) - * before any other mParticle methods or the SDK will not function as intended. - * @method setLogLevel - * @param {String} logLevel verbose, warning, or none. By default, `warning` is chosen. - */ - this.setLogLevel = function (newLogLevel) { - self.Logger.setLogLevel(newLogLevel); - }; - /** - * Resets the SDK to an uninitialized state and removes cookies/localStorage. You MUST call mParticle.init(apiKey, window.mParticle.config) - * before any other mParticle methods or the SDK will not function as intended. - * @method reset - */ - this.reset = function (instance) { - try { - instance._Persistence.resetPersistence(); - if (instance._Store) { - delete instance._Store; - } - } catch (error) { - console.error('Cannot reset mParticle', error); - } - }; - this._resetForTests = function (config, keepPersistence, instance) { - if (instance._Store) { - delete instance._Store; - } - instance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); - instance._LoggingDispatcher = new LoggingDispatcher(); - instance.Logger = new Logger(config); - instance._Store = new Store(config, instance); - instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability(window.localStorage); - instance._Events.stopTracking(); - if (!keepPersistence) { - instance._Persistence.resetPersistence(); - } - instance._Persistence.forwardingStatsBatches.uploadsTable = {}; - instance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = []; - instance._preInit = { - readyQueue: [], - pixelConfigurations: [], - integrationDelays: {}, - forwarderConstructors: [], - isDevelopmentMode: false - }; - }; - /** - * Executes callback when the SDK is ready, or Rokt is ready but identify requests fail due to server errors. - * This ensures Rokt methods like selectPlacements continue to work during backend outages. - * @method ready - * @param {Function} f Callback to execute - */ - this.ready = function (f) { - var _a, _b, _c; - var noFunctionalWithoutId = ((_a = self._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(self._Store); - var shouldExecute = isFunction(f) && (((_b = self._Store) === null || _b === void 0 ? void 0 : _b.isInitialized) || ((_c = self._Store) === null || _c === void 0 ? void 0 : _c.identityCallFailed) && self._RoktManager.isReady() || noFunctionalWithoutId); - if (shouldExecute) { - f(); - } else { - self._preInit.readyQueue.push(f); - } - }; - /** - * Returns the current mParticle environment setting - * @method getEnvironment - * @returns {String} mParticle environment setting - */ - this.getEnvironment = function () { - return self._Store.SDKConfig.isDevelopmentMode ? Constants.Environment.Development : Constants.Environment.Production; - }; - /** - * Returns the mParticle SDK version number - * @method getVersion - * @return {String} mParticle SDK version number - */ - this.getVersion = function () { - return Constants.sdkVersion; - }; - /** - * Sets the app version - * @method setAppVersion - * @param {String} version version number - */ - this.setAppVersion = function (version) { - var queued = queueIfNotInitialized(function () { - self.setAppVersion(version); - }, self); - if (queued) return; - self._Store.SDKConfig.appVersion = version; - self._Persistence.update(); - }; - /** - * Sets the device id - * @method setDeviceId - * @param {String} name device ID (UUIDv4-formatted string) - */ - this.setDeviceId = function (guid) { - var queued = queueIfNotInitialized(function () { - self.setDeviceId(guid); - }, self); - if (queued) return; - this._Store.setDeviceId(guid); - }; - /** - * Returns a boolean for whether or not the SDKhas been fully initialized - * @method isInitialized - * @return {Boolean} a boolean for whether or not the SDK has been fully initialized - */ - this.isInitialized = function () { - return self._Store ? self._Store.isInitialized : false; - }; - /** - * Gets the app name - * @method getAppName - * @return {String} App name - */ - this.getAppName = function () { - return self._Store.SDKConfig.appName; - }; - /** - * Sets the app name - * @method setAppName - * @param {String} name App Name - */ - this.setAppName = function (name) { - var queued = queueIfNotInitialized(function () { - self.setAppName(name); - }, self); - if (queued) return; - self._Store.SDKConfig.appName = name; - }; - /** - * Gets the app version - * @method getAppVersion - * @return {String} App version - */ - this.getAppVersion = function () { - return self._Store.SDKConfig.appVersion; - }; - /** - * Stops tracking the location of the user - * @method stopTrackingLocation - */ - this.stopTrackingLocation = function () { - self._SessionManager.resetSessionTimer(); - self._Events.stopTracking(); - }; - /** - * Starts tracking the location of the user - * @method startTrackingLocation - * @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback - */ - this.startTrackingLocation = function (callback) { - if (!isFunction(callback)) { - self.Logger.warning('Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.'); - } - self._SessionManager.resetSessionTimer(); - self._Events.startTracking(callback); - }; - /** - * Sets the position of the user - * @method setPosition - * @param {Number} lattitude lattitude digit - * @param {Number} longitude longitude digit - */ - this.setPosition = function (lat, lng) { - var queued = queueIfNotInitialized(function () { - self.setPosition(lat, lng); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - if (typeof lat === 'number' && typeof lng === 'number') { - self._Store.currentPosition = { - lat: lat, - lng: lng - }; - } else { - self.Logger.error('Position latitude and/or longitude must both be of type number'); - } - }; - /** - * Starts a new session - * @method startNewSession - */ - this.startNewSession = function () { - self._SessionManager.startNewSession(); - }; - /** - * Ends the current session - * @method endSession - */ - this.endSession = function () { - // Sends true as an over ride vs when endSession is called from the setInterval - self._SessionManager.endSession(true); - }; - /** - * Logs a Base Event to mParticle's servers - * @param {Object} event Base Event Object - * @param {Object} [eventOptions] For Event-level Configuration Options - */ - this.logBaseEvent = function (event, eventOptions) { - var queued = queueIfNotInitialized(function () { - self.logBaseEvent(event, eventOptions); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - if (typeof event.name !== 'string') { - self.Logger.error(Messages.ErrorMessages.EventNameInvalidType); - return; - } - if (!event.eventType) { - event.eventType = EventType.Unknown; - } - if (!self._Helpers.canLog()) { - self.Logger.error(Messages.ErrorMessages.LoggingDisabled); - return; - } - self._Events.logEvent(event, eventOptions); - }; - /** - * Logs an event to mParticle's servers - * @method logEvent - * @param {String} eventName The name of the event - * @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type) - * @param {Object} [eventInfo] Attributes for the event - * @param {Object} [customFlags] Additional customFlags - * @param {Object} [eventOptions] For Event-level Configuration Options - */ - this.logEvent = function (eventName, eventType, eventInfo, customFlags, eventOptions) { - var queued = queueIfNotInitialized(function () { - self.logEvent(eventName, eventType, eventInfo, customFlags, eventOptions); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - if (typeof eventName !== 'string') { - self.Logger.error(Messages.ErrorMessages.EventNameInvalidType); - return; - } - if (!eventType) { - eventType = EventType.Unknown; - } - if (!self._Helpers.isEventType(eventType)) { - self.Logger.error('Invalid event type: ' + eventType + ', must be one of: \n' + JSON.stringify(EventType)); - return; - } - if (!self._Helpers.canLog()) { - self.Logger.error(Messages.ErrorMessages.LoggingDisabled); - return; - } - self._Events.logEvent({ - messageType: MessageType$1.PageEvent, - name: eventName, - data: eventInfo, - eventType: eventType, - customFlags: customFlags - }, eventOptions); - }; - /** - * Used to log custom errors - * - * @method logError - * @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'} - * @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean - */ - this.logError = function (error, attrs) { - var queued = queueIfNotInitialized(function () { - self.logError(error, attrs); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - if (!error) { - return; - } - if (typeof error === 'string') { - error = { - message: error - }; - } - var data = { - m: error.message ? error.message : error, - s: 'Error', - t: error.stack || null - }; - if (attrs) { - var sanitized = self._Helpers.sanitizeAttributes(attrs, data.m); - for (var prop in sanitized) { - data[prop] = sanitized[prop]; - } - } - self._Events.logEvent({ - messageType: MessageType$1.CrashReport, - name: error.name ? error.name : 'Error', - eventType: EventType.Other, - data: data - }); - }; - /** - * Logs `click` events - * @method logLink - * @param {String} selector The selector to add a 'click' event to (ex. #purchase-event) - * @param {String} [eventName] The name of the event - * @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type) - * @param {Object} [eventInfo] Attributes for the event - */ - this.logLink = function (selector, eventName, eventType, eventInfo) { - self._Events.addEventHandler('click', selector, eventName, eventInfo, eventType); - }; - /** - * Logs `submit` events - * @method logForm - * @param {String} selector The selector to add the event handler to (ex. #search-event) - * @param {String} [eventName] The name of the event - * @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type) - * @param {Object} [eventInfo] Attributes for the event - */ - this.logForm = function (selector, eventName, eventType, eventInfo) { - self._Events.addEventHandler('submit', selector, eventName, eventInfo, eventType); - }; - /** - * Logs a page view - * @method logPageView - * @param {String} eventName The name of the event. Defaults to 'PageView'. - * @param {Object} [attrs] Attributes for the event - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */ - this.logPageView = function (eventName, attrs, customFlags, eventOptions) { - var queued = queueIfNotInitialized(function () { - self.logPageView(eventName, attrs, customFlags, eventOptions); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - if (self._Helpers.canLog()) { - if (!self._Helpers.Validators.isStringOrNumber(eventName)) { - eventName = 'PageView'; - } - if (!attrs) { - attrs = { - hostname: window.location.hostname, - title: window.document.title - }; - } else if (!self._Helpers.isObject(attrs)) { - self.Logger.error('The attributes argument must be an object. A ' + _typeof$1(attrs) + ' was entered. Please correct and retry.'); - return; - } - if (customFlags && !self._Helpers.isObject(customFlags)) { - self.Logger.error('The customFlags argument must be an object. A ' + _typeof$1(customFlags) + ' was entered. Please correct and retry.'); - return; - } - } - self._Events.logEvent({ - messageType: MessageType$1.PageView, - name: eventName, - data: attrs, - eventType: EventType.Unknown, - customFlags: customFlags - }, eventOptions); - }; - /** - * Forces an upload of the batch - * @method upload - */ - this.upload = function () { - var _a, _b; - if (self._Helpers.canLog()) { - if (self._Store.webviewBridgeEnabled) { - self._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload); - } else { - (_b = (_a = self._APIClient) === null || _a === void 0 ? void 0 : _a.uploader) === null || _b === void 0 ? void 0 : _b.prepareAndUpload(false, false); - } - } - }; - /** - * Invoke these methods on the mParticle.Consent object. - * Example: mParticle.Consent.createConsentState() - * - * @class mParticle.Consent - */ - this.Consent = { - /** - * Creates a CCPA Opt Out Consent State. - * - * @method createCCPAConsent - * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" - * @param {Number} timestamp Unix time (likely to be Date.now()) - * @param {String} consentDocument document version or experience that the user may have consented to - * @param {String} location location where the user gave consent - * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users - * @return {Object} CCPA Consent State - */ - createCCPAConsent: self._Consent.createPrivacyConsent, - /** - * Creates a GDPR Consent State. - * - * @method createGDPRConsent - * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" - * @param {Number} timestamp Unix time (likely to be Date.now()) - * @param {String} consentDocument document version or experience that the user may have consented to - * @param {String} location location where the user gave consent - * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users - * @return {Object} GDPR Consent State - */ - createGDPRConsent: self._Consent.createPrivacyConsent, - /** - * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states. - * - * @method createConsentState - * @return {Object} ConsentState object - */ - createConsentState: self._Consent.createConsentState - }; - /** - * Invoke these methods on the mParticle.eCommerce object. - * Example: mParticle.eCommerce.createImpresion(...) - * @class mParticle.eCommerce - */ - this.eCommerce = { - /** - * Invoke these methods on the mParticle.eCommerce.Cart object. - * Example: mParticle.eCommerce.Cart.add(...) - * @class mParticle.eCommerce.Cart - * @deprecated - */ - Cart: { - /** - * Adds a product to the cart - * @method add - * @param {Object} product The product you want to add to the cart - * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. - * @deprecated - */ - add: function add(product, logEventBoolean) { - self.Logger.warning(generateDeprecationMessage('eCommerce.Cart.add()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - }, - /** - * Removes a product from the cart - * @method remove - * @param {Object} product The product you want to add to the cart - * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. - * @deprecated - */ - remove: function remove(product, logEventBoolean) { - self.Logger.warning(generateDeprecationMessage('eCommerce.Cart.remove()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - }, - /** - * Clears the cart - * @method clear - * @deprecated - */ - clear: function clear() { - self.Logger.warning(generateDeprecationMessage('eCommerce.Cart.clear()', true, '', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); - } - }, - /** - * Sets the currency code - * @for mParticle.eCommerce - * @method setCurrencyCode - * @param {String} code The currency code - */ - setCurrencyCode: function setCurrencyCode(code) { - var queued = queueIfNotInitialized(function () { - self.eCommerce.setCurrencyCode(code); - }, self); - if (queued) return; - if (typeof code !== 'string') { - self.Logger.error('Code must be a string'); - return; - } - self._SessionManager.resetSessionTimer(); - self._Store.currencyCode = code; - }, - /** - * Creates a product - * @for mParticle.eCommerce - * @method createProduct - * @param {String} name product name - * @param {String} sku product sku - * @param {Number} price product price - * @param {Number} [quantity] product quantity. If blank, defaults to 1. - * @param {String} [variant] product variant - * @param {String} [category] product category - * @param {String} [brand] product brand - * @param {Number} [position] product position - * @param {String} [coupon] product coupon - * @param {Object} [attributes] product attributes - */ - createProduct: function createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) { - return self._Ecommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes); - }, - /** - * Creates a promotion - * @for mParticle.eCommerce - * @method createPromotion - * @param {String} id a unique promotion id - * @param {String} [creative] promotion creative - * @param {String} [name] promotion name - * @param {Number} [position] promotion position - */ - createPromotion: function createPromotion(id, creative, name, position) { - return self._Ecommerce.createPromotion(id, creative, name, position); - }, - /** - * Creates a product impression - * @for mParticle.eCommerce - * @method createImpression - * @param {String} name impression name - * @param {Object} product the product for which an impression is being created - */ - createImpression: function createImpression(name, product) { - return self._Ecommerce.createImpression(name, product); - }, - /** - * Creates a transaction attributes object to be used with a checkout - * @for mParticle.eCommerce - * @method createTransactionAttributes - * @param {String or Number} id a unique transaction id - * @param {String} [affiliation] affilliation - * @param {String} [couponCode] the coupon code for which you are creating transaction attributes - * @param {Number} [revenue] total revenue for the product being purchased - * @param {String} [shipping] the shipping method - * @param {Number} [tax] the tax amount - */ - createTransactionAttributes: function createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax) { - return self._Ecommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax); - }, - /** - * Logs a checkout action - * @for mParticle.eCommerce - * @method logCheckout - * @param {Number} step checkout step number - * @param {String} checkout option string - * @param {Object} attrs - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */ - logCheckout: function logCheckout(step, option, attrs, customFlags) { - self.Logger.warning('mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead'); - if (!self._Store.isInitialized) { - self.ready(function () { - self.eCommerce.logCheckout(step, option, attrs, customFlags); - }); - return; - } - self._SessionManager.resetSessionTimer(); - self._Events.logCheckoutEvent(step, option, attrs, customFlags); - }, - /** - * Logs a product action - * @for mParticle.eCommerce - * @method logProductAction - * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218) - * @param {Object} product the product for which you are creating the product action - * @param {Object} [attrs] attributes related to the product action - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [transactionAttributes] Transaction Attributes for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */ - logProductAction: function logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions) { - var queued = queueIfNotInitialized(function () { - self.eCommerce.logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - self._Events.logProductActionEvent(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions); - }, - /** - * Logs a product purchase - * @for mParticle.eCommerce - * @method logPurchase - * @param {Object} transactionAttributes transactionAttributes object - * @param {Object} product the product being purchased - * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false - * @param {Object} [attrs] other attributes related to the product purchase - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */ - logPurchase: function logPurchase(transactionAttributes, product, clearCart, attrs, customFlags) { - self.Logger.warning('mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead'); - if (!self._Store.isInitialized) { - self.ready(function () { - self.eCommerce.logPurchase(transactionAttributes, product, clearCart, attrs, customFlags); - }); - return; - } - if (!transactionAttributes || !product) { - self.Logger.error(Messages.ErrorMessages.BadLogPurchase); - return; - } - self._SessionManager.resetSessionTimer(); - self._Events.logPurchaseEvent(transactionAttributes, product, attrs, customFlags); - }, - /** - * Logs a product promotion - * @for mParticle.eCommerce - * @method logPromotion - * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279) - * @param {Object} promotion promotion object - * @param {Object} [attrs] boolean to clear the cart after logging or not - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */ - logPromotion: function logPromotion(type, promotion, attrs, customFlags, eventOptions) { - var queued = queueIfNotInitialized(function () { - self.eCommerce.logPromotion(type, promotion, attrs, customFlags, eventOptions); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - self._Events.logPromotionEvent(type, promotion, attrs, customFlags, eventOptions); - }, - /** - * Logs a product impression - * @for mParticle.eCommerce - * @method logImpression - * @param {Object} impression product impression object - * @param {Object} attrs attributes related to the impression log - * @param {Object} [customFlags] Custom flags for the event - * @param {Object} [eventOptions] For Event-level Configuration Options - */ - logImpression: function logImpression(impression, attrs, customFlags, eventOptions) { - var queued = queueIfNotInitialized(function () { - self.eCommerce.logImpression(impression, attrs, customFlags, eventOptions); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - self._Events.logImpressionEvent(impression, attrs, customFlags, eventOptions); - }, - /** - * Logs a refund - * @for mParticle.eCommerce - * @method logRefund - * @param {Object} transactionAttributes transaction attributes related to the refund - * @param {Object} product product being refunded - * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false. - * @param {Object} [attrs] attributes related to the refund - * @param {Object} [customFlags] Custom flags for the event - * @deprecated - */ - logRefund: function logRefund(transactionAttributes, product, clearCart, attrs, customFlags) { - self.Logger.warning('mParticle.logRefund is deprecated, please use mParticle.logProductAction instead'); - if (!self._Store.isInitialized) { - self.ready(function () { - self.eCommerce.logRefund(transactionAttributes, product, clearCart, attrs, customFlags); - }); - return; - } - self._SessionManager.resetSessionTimer(); - self._Events.logRefundEvent(transactionAttributes, product, attrs, customFlags); - }, - expandCommerceEvent: function expandCommerceEvent(event) { - return self._Ecommerce.expandCommerceEvent(event); - } - }; - /** - * Sets a session attribute - * @method setSessionAttribute - * @param {String} key key for session attribute - * @param {String or Number} value value for session attribute - */ - this.setSessionAttribute = function (key, value) { - var _a; - var skipQueue = ((_a = self._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(self._Store); - if (!skipQueue) { - var queued = queueIfNotInitialized(function () { - self.setSessionAttribute(key, value); - }, self); - if (queued) return; - } - // Logs to cookie - // And logs to in-memory object - // Example: mParticle.setSessionAttribute('location', '33431'); - if (self._Helpers.canLog()) { - if (!self._Helpers.Validators.isValidAttributeValue(value)) { - self.Logger.error(Messages.ErrorMessages.BadAttribute); - return; - } - if (!self._Helpers.Validators.isValidKeyValue(key)) { - self.Logger.error(Messages.ErrorMessages.BadKey); - return; - } - if (self._Store.webviewBridgeEnabled) { - self._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ - key: key, - value: value - })); - } else { - var existingProp = self._Helpers.findKeyInObject(self._Store.sessionAttributes, key); - if (existingProp) { - key = existingProp; - } - self._Store.sessionAttributes[key] = value; - self._Persistence.update(); - self._Forwarders.applyToForwarders('setSessionAttribute', [key, value]); - } - } - }; - /** - * Set opt out of logging - * @method setOptOut - * @param {Boolean} isOptingOut boolean to opt out or not. When set to true, opt out of logging. - */ - this.setOptOut = function (isOptingOut) { - var queued = queueIfNotInitialized(function () { - self.setOptOut(isOptingOut); - }, self); - if (queued) return; - self._SessionManager.resetSessionTimer(); - self._Store.isEnabled = !isOptingOut; - self._Events.logOptOut(); - self._Persistence.update(); - if (self._Store.activeForwarders.length) { - self._Store.activeForwarders.forEach(function (forwarder) { - if (forwarder.setOptOut) { - var result = forwarder.setOptOut(isOptingOut); - if (result) { - self.Logger.verbose(result); - } - } - }); - } - }; - /** - * Set or remove the integration attributes for a given integration ID. - * Integration attributes are keys and values specific to a given integration. For example, - * many integrations have their own internal user/device ID. mParticle will store integration attributes - * for a given device, and will be able to use these values for server-to-server communication to services. - * This is often useful when used in combination with a server-to-server feed, allowing the feed to be enriched - * with the necessary integration attributes to be properly forwarded to the given integration. - * @method setIntegrationAttribute - * @param {Number} integrationId mParticle integration ID - * @param {Object} attrs a map of attributes that will replace any current attributes. The keys are predefined by mParticle. - * Please consult with the mParticle docs or your solutions consultant for the correct value. You may - * also pass a null or empty map here to remove all of the attributes. - */ - this.setIntegrationAttribute = function (integrationId, attrs) { - var queued = queueIfNotInitialized(function () { - self.setIntegrationAttribute(integrationId, attrs); - }, self); - if (queued) return; - if (typeof integrationId !== 'number') { - self.Logger.error('integrationId must be a number'); - return; - } - if (attrs === null) { - self._Store.integrationAttributes[integrationId] = {}; - } else if (self._Helpers.isObject(attrs)) { - if (Object.keys(attrs).length === 0) { - self._Store.integrationAttributes[integrationId] = {}; - } else { - for (var key in attrs) { - if (typeof key === 'string') { - if (typeof attrs[key] === 'string') { - if (self._Helpers.isObject(self._Store.integrationAttributes[integrationId])) { - self._Store.integrationAttributes[integrationId][key] = attrs[key]; - } else { - self._Store.integrationAttributes[integrationId] = {}; - self._Store.integrationAttributes[integrationId][key] = attrs[key]; - } - } else { - self.Logger.error('Values for integration attributes must be strings. You entered a ' + _typeof$1(attrs[key])); - continue; - } - } else { - self.Logger.error('Keys must be strings, you entered a ' + _typeof$1(key)); - continue; - } - } - } - } else { - self.Logger.error('Attrs must be an object with keys and values. You entered a ' + _typeof$1(attrs)); - return; - } - self._Persistence.update(); - }; - /** - * Get integration attributes for a given integration ID. - * @method getIntegrationAttributes - * @param {Number} integrationId mParticle integration ID - * @return {Object} an object map of the integrationId's attributes - */ - this.getIntegrationAttributes = function (integrationId) { - if (self._Store.integrationAttributes[integrationId]) { - return self._Store.integrationAttributes[integrationId]; - } else { - return {}; - } - }; - // Used by our forwarders - this.addForwarder = function (forwarder) { - self._preInit.forwarderConstructors.push(forwarder); - }; - this.configurePixel = function (settings) { - self._Forwarders.configurePixel(settings); - }; - this._getActiveForwarders = function () { - return self._Store.activeForwarders; - }; - this._getIntegrationDelays = function () { - return self._preInit.integrationDelays; - }; - /* - An integration delay is a workaround that prevents events from being sent when it is necessary to do so. - Some server side integrations require a client side value to be included in the payload to successfully - forward. This value can only be pulled from the client side partner SDK. - During the kit initialization, the kit: - * sets an integration delay to `true` - * grabs the required value from the partner SDK, - * sets it via `setIntegrationAttribute` - * sets the integration delay to `false` - The core SDK can then read via `isDelayedByIntegration` to no longer delay sending events. - This integration attribute is now on the batch payload for the server side to read. - If there is no delay, then the events sent before an integration attribute is included would not - be forwarded successfully server side. - */ - this._setIntegrationDelay = function (module, shouldDelayIntegration) { - self._preInit.integrationDelays[module] = shouldDelayIntegration; - // If the integration delay is set to true, no further action needed - if (shouldDelayIntegration === true) { - return; - } - // If the integration delay is set to false, check to see if there are any - // other integration delays set to true. It not, process the queued events/. - var integrationDelaysKeys = Object.keys(self._preInit.integrationDelays); - if (integrationDelaysKeys.length === 0) { - return; - } - var hasIntegrationDelays = integrationDelaysKeys.some(function (integration) { - return self._preInit.integrationDelays[integration] === true; - }); - if (!hasIntegrationDelays) { - self._APIClient.processQueuedEvents(); - } - }; - // Internal use only. Used by our wrapper SDKs to identify themselves during initialization. - this._setWrapperSDKInfo = function (name, version) { - var queued = queueIfNotInitialized(function () { - self._setWrapperSDKInfo(name, version); - }, self); - if (queued) return; - if (self._Store.wrapperSDKInfo === undefined || !self._Store.wrapperSDKInfo.isInfoSet) { - self._Store.wrapperSDKInfo = { - name: name, - version: version, - isInfoSet: true - }; - } - }; - this.registerErrorReportingService = function (service) { - self._ErrorReportingDispatcher.register(service); - }; - this.registerLoggingService = function (service) { - self._LoggingDispatcher.register(service); - }; - var launcherInstanceGuidKey = Constants.Rokt.LauncherInstanceGuidKey; - this.setLauncherInstanceGuid = function () { - if (!window[launcherInstanceGuidKey] || typeof window[launcherInstanceGuidKey] !== 'string') { - window[launcherInstanceGuidKey] = self._Helpers.generateUniqueId(); - } - }; - this.getLauncherInstanceGuid = function () { - return window[launcherInstanceGuidKey]; - }; - this.captureTiming = function (metricsName) { - var _a; - if (typeof window !== 'undefined' && ((_a = window.performance) === null || _a === void 0 ? void 0 : _a.mark)) { - window.performance.mark(metricsName); - } - }; - } - // Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment - function completeSDKInitialization(apiKey, config, mpInstance) { - var _a, _b; - var kitBlocker = createKitBlocker(config, mpInstance); - var getFeatureFlag = mpInstance._Helpers.getFeatureFlag; - mpInstance._APIClient = new APIClient(mpInstance, kitBlocker); - mpInstance._Forwarders = new Forwarders(mpInstance, kitBlocker); - mpInstance._Store.processConfig(config); - mpInstance._Identity.idCache = createIdentityCache(mpInstance); - removeExpiredIdentityCacheDates(mpInstance._Identity.idCache); - // Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's - // Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not - // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize - // persistence or Identity directly. - if (mpInstance._Store.webviewBridgeEnabled) { - mpInstance._NativeSdkHelpers.initializeSessionAttributes(apiKey); - } else { - // Main SDK initialization flow - // Load any settings/identities/attributes from cookie or localStorage - mpInstance._Persistence.initializeStorage(); - mpInstance._Store.syncPersistenceData(); - // Set up user identitiy variables for later use - var currentUser = mpInstance.Identity.getCurrentUser(); - var currentUserMPID = currentUser ? currentUser.getMPID() : null; - var currentUserIdentities = currentUser ? currentUser.getUserIdentities().userIdentities : {}; - mpInstance._Store.SDKConfig.identifyRequest = mpInstance._Store.hasInvalidIdentifyRequest() ? { - userIdentities: currentUserIdentities - } : mpInstance._Store.SDKConfig.identifyRequest; - if (getFeatureFlag(ReportBatching)) { - mpInstance._ForwardingStatsUploader.startForwardingStatsTimer(); - } - // https://go.mparticle.com/work/SQDSDKS-7639 - var integrationSpecificIds = getFeatureFlag(CaptureIntegrationSpecificIds); - var integrationSpecificIdsV2 = getFeatureFlag(CaptureIntegrationSpecificIdsV2); - var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; - if (isIntegrationCaptureEnabled) { - var captureMode = void 0; - if (integrationSpecificIds || integrationSpecificIdsV2 === CaptureIntegrationSpecificIdsV2Modes.All) { - captureMode = 'all'; - } else if (integrationSpecificIdsV2 === CaptureIntegrationSpecificIdsV2Modes.RoktOnly) { - captureMode = 'roktonly'; - } - mpInstance._IntegrationCapture = new IntegrationCapture(captureMode); - mpInstance._IntegrationCapture.capture(); - } - // Configure Rokt Manager with user and filtered user - var roktConfig = parseConfig(config, 'Rokt', 181); - if (roktConfig) { - var accountId = (_a = roktConfig.settings) === null || _a === void 0 ? void 0 : _a.accountId; - mpInstance._Store.setRoktAccountId(accountId); - var userAttributeFilters = roktConfig.userAttributeFilters; - var roktFilteredUser = filteredMparticleUser(currentUserMPID, { - userAttributeFilters: userAttributeFilters - }, mpInstance); - var roktOptions = { - sandbox: config === null || config === void 0 ? void 0 : config.isDevelopmentMode, - launcherOptions: config === null || config === void 0 ? void 0 : config.launcherOptions, - domain: config === null || config === void 0 ? void 0 : config.domain - }; - // https://go.mparticle.com/work/SQDSDKS-7339 - mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance._Store, mpInstance.Logger, roktOptions, mpInstance.captureTiming); - } - mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats); - mpInstance._Forwarders.processPixelConfigs(config); - // Checks if session is created, resumed, or needs to be ended - // Logs a session start or session end event accordingly - mpInstance._SessionManager.initialize(); - mpInstance._Events.logAST(); - processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities); - } - // We will continue to clear out the ready queue as part of the initial init flow - // if an identify request is unnecessary, such as if there is an existing session - if (mpInstance._Store.mpid && !mpInstance._Store.identifyCalled || mpInstance._Store.webviewBridgeEnabled) { - mpInstance._Store.isInitialized = true; - mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue); - } - // For noFunctional sessions with no identity, drain any pre-init ready callbacks - // that were queued before _CookieConsentManager was available to evaluate the condition. - (_b = mpInstance.processQueueOnNoFunctional) === null || _b === void 0 ? void 0 : _b.call(mpInstance); - // https://go.mparticle.com/work/SQDSDKS-6040 - if (mpInstance._Store.isFirstRun) { - mpInstance._Store.isFirstRun = false; - } - } - // https://go.mparticle.com/work/SQDSDKS-7061 - function createKitBlocker(config, mpInstance) { - var kitBlocker; - var dataPlanForKitBlocker; - var kitBlockError; - var kitBlockOptions; - /* There are three ways a data plan object for blocking can be passed to the SDK: - 1. Manually via config.dataPlanOptions (this takes priority) - If not passed in manually, we user the server provided via either - 2. Snippet via /mparticle.js endpoint (config.dataPlan.document) - 3. Self hosting via /config endpoint (config.dataPlanResult) - */ - if (config.dataPlanOptions) { - mpInstance.Logger.verbose('Customer provided data plan found'); - kitBlockOptions = config.dataPlanOptions; - dataPlanForKitBlocker = { - document: { - dtpn: { - vers: kitBlockOptions.dataPlanVersion, - blok: { - ev: kitBlockOptions.blockEvents, - ea: kitBlockOptions.blockEventAttributes, - ua: kitBlockOptions.blockUserAttributes, - id: kitBlockOptions.blockUserIdentities - } - } - } - }; - } - if (!dataPlanForKitBlocker) { - // config.dataPlan.document returns on /mparticle.js endpoint - if (config.dataPlan && config.dataPlan.document) { - if (config.dataPlan.document.error_message) { - kitBlockError = config.dataPlan.document.error_message; - } else { - mpInstance.Logger.verbose('Data plan found from mParticle.js'); - dataPlanForKitBlocker = config.dataPlan; - } - } - // config.dataPlanResult returns on /config endpoint - else if (config.dataPlanResult) { - if (config.dataPlanResult.error_message) { - kitBlockError = config.dataPlanResult.error_message; - } else { - mpInstance.Logger.verbose('Data plan found from /config'); - dataPlanForKitBlocker = { - document: config.dataPlanResult - }; - } - } - } - if (kitBlockError) { - mpInstance.Logger.error(kitBlockError); - } - if (dataPlanForKitBlocker) { - kitBlocker = new KitBlocker(dataPlanForKitBlocker, mpInstance); - } - return kitBlocker; - } - function createIdentityCache(mpInstance) { - var _a; - // Identity expects mpInstance._Identity.idCache to always exist. DisabledVault - // ensures no identity response data is written to localStorage when noFunctional is true - if ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) { - return new DisabledVault("".concat(mpInstance._Store.storageName, "-id-cache"), { - logger: mpInstance.Logger - }); - } - return new LocalStorageVault("".concat(mpInstance._Store.storageName, "-id-cache"), { - logger: mpInstance.Logger - }); - } - function runPreConfigFetchInitialization(mpInstance, apiKey, config) { - var _a; - mpInstance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); - mpInstance._LoggingDispatcher = new LoggingDispatcher(); - mpInstance.Logger = new Logger(config); - mpInstance._Store = new Store(config, mpInstance, apiKey); - window.mParticle.Store = mpInstance._Store; - mpInstance.Logger.verbose(StartingInitialization); - // Initialize CookieConsentManager with privacy flags from launcherOptions - var _b = (_a = config === null || config === void 0 ? void 0 : config.launcherOptions) !== null && _a !== void 0 ? _a : {}, - noFunctional = _b.noFunctional, - noTargeting = _b.noTargeting; - mpInstance._CookieConsentManager = new CookieConsentManager({ - noFunctional: noFunctional, - noTargeting: noTargeting - }); - // Check to see if localStorage is available before main configuration runs - // since we will need this for the current implementation of user persistence - // TODO: Refactor this when we refactor User Identity Persistence - try { - mpInstance._Store.isLocalStorageAvailable = mpInstance._Persistence.determineLocalStorageAvailability(window.localStorage); - } catch (e) { - mpInstance.Logger.warning('localStorage is not available, using cookies if available'); - mpInstance._Store.isLocalStorageAvailable = false; - } - } - function processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities) { - // https://go.mparticle.com/work/SQDSDKS-6323 - // Call mParticle._Store.SDKConfig.identityCallback when identify was not called - // due to a reload or a sessionId already existing - // Any identity callback should always be ran regardless if an identity call - // is made - if (!mpInstance._Store.identifyCalled && mpInstance._Store.SDKConfig.identityCallback && currentUser && currentUserMPID) { - mpInstance._Store.SDKConfig.identityCallback({ - httpCode: HTTPCodes.activeSession, - getUser: function getUser() { - return mpInstance._Identity.mParticleUser(currentUserMPID); - }, - getPreviousUser: function getPreviousUser() { - var users = mpInstance.Identity.getUsers(); - var mostRecentUser = users.shift(); - var mostRecentUserMPID = mostRecentUser.getMPID(); - if (mostRecentUser && mostRecentUserMPID === currentUserMPID) { - mostRecentUser = users.shift(); - } - return mostRecentUser || null; - }, - body: { - mpid: currentUserMPID, - is_logged_in: mpInstance._Store.isLoggedIn, - matched_identities: currentUserIdentities, - context: null, - is_ephemeral: false - } - }); - } - } - function queueIfNotInitialized(func, self) { - var _a, _b; - // When noFunctional is true with no explicit identifier, the SDK will never - // receive an MPID. Let these calls through so events can still reach forwarders immediately. - // sendEventToServer handles queuing for the MP server upload path separately. - var noFunctionalWithoutId = ((_a = self._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(self._Store); - if (((_b = self._Store) === null || _b === void 0 ? void 0 : _b.isInitialized) || noFunctionalWithoutId) { - return false; - } - self._preInit.readyQueue.push(function () { - var _a; - if ((_a = self._Store) === null || _a === void 0 ? void 0 : _a.isInitialized) { - func(); - } - }); - return true; - } - - // This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise! - var mockFunction = function mockFunction() { - return null; - }; - var _BatchValidator = /** @class */function () { - function _BatchValidator() {} - _BatchValidator.prototype.getMPInstance = function () { - return { - // Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method - _Helpers: { - sanitizeAttributes: window.mParticle.getInstance()._Helpers.sanitizeAttributes, - generateHash: function generateHash() { - return 'mockHash'; - }, - generateUniqueId: function generateUniqueId() { - return 'mockId'; - }, - extend: window.mParticle.getInstance()._Helpers.extend, - createServiceUrl: mockFunction, - parseNumber: mockFunction, - isObject: mockFunction, - Validators: null - }, - _resetForTests: mockFunction, - _APIClient: null, - _timeOnSiteTimer: { - getTimeInForeground: mockFunction - }, - MPSideloadedKit: null, - _Consent: null, - _Events: null, - _Forwarders: null, - _NativeSdkHelpers: null, - _Persistence: null, - _preInit: null, - Consent: null, - _ServerModel: null, - _SessionManager: null, - _Store: { - sessionId: 'mockSessionId', - sideloadedKits: [], - devToken: 'test_dev_token', - isFirstRun: true, - isEnabled: true, - sessionAttributes: {}, - currentSessionMPIDs: [], - consentState: null, - clientId: null, - deviceId: null, - serverSettings: {}, - dateLastEventSent: null, - sessionStartDate: null, - currentPosition: null, - isTracking: false, - watchPositionId: null, - cartProducts: [], - eventQueue: [], - currencyCode: null, - globalTimer: null, - context: null, - configurationLoaded: false, - identityCallInFlight: false, - nonCurrentUserMPIDs: {}, - identifyCalled: false, - isLoggedIn: false, - cookieSyncDates: {}, - integrationAttributes: {}, - requireDelay: true, - isLocalStorageAvailable: null, - integrationDelayTimeoutStart: null, - storageName: null, - prodStorageName: null, - activeForwarders: [], - kits: {}, - configuredForwarders: [], - pixelConfigurations: [], - wrapperSDKInfo: { - name: 'none', - version: null, - isInfoSet: false - }, - SDKConfig: { - isDevelopmentMode: false, - onCreateBatch: mockFunction - } - }, - config: null, - eCommerce: null, - Identity: { - getCurrentUser: mockFunction, - IdentityAPI: {}, - identify: mockFunction, - login: mockFunction, - logout: mockFunction, - modify: mockFunction - }, - Logger: { - verbose: mockFunction, - error: mockFunction, - warning: mockFunction - }, - ProductActionType: null, - ServerModel: null, - addForwarder: mockFunction, - generateHash: mockFunction, - getAppVersion: mockFunction, - getAppName: mockFunction, - getInstance: mockFunction, - getDeviceId: mockFunction, - init: mockFunction, - logBaseEvent: mockFunction, - logEvent: mockFunction, - logLevel: 'none', - setPosition: mockFunction, - upload: mockFunction - }; - }; - _BatchValidator.prototype.createSDKEventFunction = function (event) { - return new ServerModel(this.getMPInstance()).createEventObject(event); - }; - _BatchValidator.prototype.returnBatch = function (events) { - var _this = this; - var mpInstance = this.getMPInstance(); - var sdkEvents = Array.isArray(events) ? events.map(function (event) { - return _this.createSDKEventFunction(event); - }) : [this.createSDKEventFunction(events)]; - var batch = convertEvents('0', sdkEvents, mpInstance); - return batch; - }; - return _BatchValidator; - }(); - - var MPSideloadedKit = /** @class */function () { - function MPSideloadedKit(unregisteredKitInstance) { - this.filterDictionary = { - eventTypeFilters: [], - eventNameFilters: [], - screenNameFilters: [], - screenAttributeFilters: [], - userIdentityFilters: [], - userAttributeFilters: [], - attributeFilters: [], - consentRegulationFilters: [], - consentRegulationPurposeFilters: [], - messageTypeFilters: [], - messageTypeStateFilters: [], - // The below filtering members are optional, but we instantiate them - // to simplify public method assignment - filteringEventAttributeValue: {}, - filteringUserAttributeValue: {}, - filteringConsentRuleValues: {} - }; - this.kitInstance = unregisteredKitInstance; - } - MPSideloadedKit.prototype.addEventTypeFilter = function (eventType) { - var hashedEventType = KitFilterHelper.hashEventType(eventType); - this.filterDictionary.eventTypeFilters.push(hashedEventType); - }; - MPSideloadedKit.prototype.addEventNameFilter = function (eventType, eventName) { - var hashedEventName = KitFilterHelper.hashEventName(eventName, eventType); - this.filterDictionary.eventNameFilters.push(hashedEventName); - }; - MPSideloadedKit.prototype.addEventAttributeFilter = function (eventType, eventName, customAttributeKey) { - var hashedEventAttribute = KitFilterHelper.hashEventAttributeKey(eventType, eventName, customAttributeKey); - this.filterDictionary.attributeFilters.push(hashedEventAttribute); - }; - MPSideloadedKit.prototype.addScreenNameFilter = function (screenName) { - var hashedScreenName = KitFilterHelper.hashEventName(screenName, EventType.Unknown); - this.filterDictionary.screenNameFilters.push(hashedScreenName); - }; - MPSideloadedKit.prototype.addScreenAttributeFilter = function (screenName, screenAttribute) { - var hashedScreenAttribute = KitFilterHelper.hashEventAttributeKey(EventType.Unknown, screenName, screenAttribute); - this.filterDictionary.screenAttributeFilters.push(hashedScreenAttribute); - }; - MPSideloadedKit.prototype.addUserIdentityFilter = function (userIdentity) { - var hashedIdentityType = KitFilterHelper.hashUserIdentity(userIdentity); - this.filterDictionary.userIdentityFilters.push(hashedIdentityType); - }; - MPSideloadedKit.prototype.addUserAttributeFilter = function (userAttributeKey) { - var hashedUserAttributeKey = KitFilterHelper.hashUserAttribute(userAttributeKey); - this.filterDictionary.userAttributeFilters.push(hashedUserAttributeKey); - }; - return MPSideloadedKit; - }(); - - if (!Array.prototype.forEach) { - Array.prototype.forEach = Polyfill.forEach; - } - if (!Array.prototype.map) { - Array.prototype.map = Polyfill.map; - } - if (!Array.prototype.filter) { - Array.prototype.filter = Polyfill.filter; - } - // https://go.mparticle.com/work/SQDSDKS-6768 - if (!Array.isArray) { - // @ts-ignore - Array.prototype.isArray = Polyfill.isArray; - } - function mParticleInstanceManager() { - var self = this; - // Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing - this.Store = {}; - this._instances = {}; - this.IdentityType = IdentityType; - this.EventType = EventType; - this.CommerceEventType = CommerceEventType; - this.PromotionType = PromotionActionType; - this.ProductActionType = ProductActionType; - this.MPSideloadedKit = MPSideloadedKit; - if (typeof window !== 'undefined') { - this.isIOS = window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false; - this.config = window.mParticle && window.mParticle.config ? window.mParticle.config : {}; - } - /** - * Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used. - *

- * If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below. - * @method init - * @param {String} apiKey your mParticle assigned API key - * @param {Object} [config] an options object for additional configuration - * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */ - this.init = function (apiKey, config, instanceName) { - if (!config && window.mParticle && window.mParticle.config) { - console.warn('You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly'); - config = window.mParticle ? window.mParticle.config : {}; - } - instanceName = (!instanceName || instanceName.length === 0 ? Constants.DefaultInstance : instanceName).toLowerCase(); - var client = self._instances[instanceName]; - if (client === undefined) { - client = new mParticleInstance(instanceName); - self._instances[instanceName] = client; - } - client.captureTiming(PerformanceMarkType.SdkStart); - client.setLauncherInstanceGuid(); - client.init(apiKey, config, instanceName); - }; - this.captureTiming = function (metricsName) { - self.getInstance().captureTiming(metricsName); - }; - this.getInstance = function getInstance(instanceName) { - var client; - if (!instanceName) { - instanceName = Constants.DefaultInstance; - client = self._instances[instanceName]; - if (!client) { - client = new mParticleInstance(instanceName); - self._instances[Constants.DefaultInstance] = client; - } - return client; - } else { - client = self._instances[instanceName.toLowerCase()]; - if (!client) { - console.log('You tried to initialize an instance named ' + instanceName + '. This instance does not exist. Check your instance name or initialize a new instance with this name before calling it.'); - return null; - } - return client; - } - }; - this.Rokt = self.getInstance()._RoktManager; - this.getDeviceId = function () { - return self.getInstance().getDeviceId(); - }; - this.setDeviceId = function (guid) { - return self.getInstance().setDeviceId(guid); - }; - this.isInitialized = function () { - return self.getInstance().isInitialized(); - }; - this.startNewSession = function () { - self.getInstance().startNewSession(); - }; - this.endSession = function () { - self.getInstance().endSession(); - }; - this.setLogLevel = function (newLogLevel) { - self.getInstance().setLogLevel(newLogLevel); - }; - this.ready = function (argument) { - self.getInstance().ready(argument); - }; - this.setAppVersion = function (version) { - self.getInstance().setAppVersion(version); - }; - this.getAppName = function () { - return self.getInstance().getAppName(); - }; - this.setAppName = function (name) { - self.getInstance().setAppName(name); - }; - this.getAppVersion = function () { - return self.getInstance().getAppVersion(); - }; - this.getEnvironment = function () { - return self.getInstance().getEnvironment(); - }; - this.stopTrackingLocation = function () { - self.getInstance().stopTrackingLocation(); - }; - this.startTrackingLocation = function (callback) { - self.getInstance().startTrackingLocation(callback); - }; - this.setPosition = function (lat, lng) { - self.getInstance().setPosition(lat, lng); - }; - this.logBaseEvent = function (event, eventOptions) { - self.getInstance().logBaseEvent(event, eventOptions); - }; - this.logEvent = function (eventName, eventType, eventInfo, customFlags, eventOptions) { - self.getInstance().logEvent(eventName, eventType, eventInfo, customFlags, eventOptions); - }; - this.logError = function (error, attrs) { - self.getInstance().logError(error, attrs); - }; - this.logLink = function (selector, eventName, eventType, eventInfo) { - self.getInstance().logLink(selector, eventName, eventType, eventInfo); - }; - this.logForm = function (selector, eventName, eventType, eventInfo) { - self.getInstance().logForm(selector, eventName, eventType, eventInfo); - }; - this.logPageView = function (eventName, attrs, customFlags, eventOptions) { - self.getInstance().logPageView(eventName, attrs, customFlags, eventOptions); - }; - this.upload = function () { - self.getInstance().upload(); - }; - this.eCommerce = { - Cart: { - add: function add(product, logEventBoolean) { - self.getInstance().eCommerce.Cart.add(product, logEventBoolean); - }, - remove: function remove(product, logEventBoolean) { - self.getInstance().eCommerce.Cart.remove(product, logEventBoolean); - }, - clear: function clear() { - self.getInstance().eCommerce.Cart.clear(); - } - }, - setCurrencyCode: function setCurrencyCode(code) { - self.getInstance().eCommerce.setCurrencyCode(code); - }, - createProduct: function createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) { - return self.getInstance().eCommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes); - }, - createPromotion: function createPromotion(id, creative, name, position) { - return self.getInstance().eCommerce.createPromotion(id, creative, name, position); - }, - createImpression: function createImpression(name, product) { - return self.getInstance().eCommerce.createImpression(name, product); - }, - createTransactionAttributes: function createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax) { - return self.getInstance().eCommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax); - }, - logCheckout: function logCheckout(step, options, attrs, customFlags) { - self.getInstance().eCommerce.logCheckout(step, options, attrs, customFlags); - }, - logProductAction: function logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions) { - self.getInstance().eCommerce.logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions); - }, - logPurchase: function logPurchase(transactionAttributes, product, clearCart, attrs, customFlags) { - self.getInstance().eCommerce.logPurchase(transactionAttributes, product, clearCart, attrs, customFlags); - }, - logPromotion: function logPromotion(type, promotion, attrs, customFlags, eventOptions) { - self.getInstance().eCommerce.logPromotion(type, promotion, attrs, customFlags, eventOptions); - }, - logImpression: function logImpression(impression, attrs, customFlags, eventOptions) { - self.getInstance().eCommerce.logImpression(impression, attrs, customFlags, eventOptions); - }, - logRefund: function logRefund(transactionAttributes, product, clearCart, attrs, customFlags) { - self.getInstance().eCommerce.logRefund(transactionAttributes, product, clearCart, attrs, customFlags); - }, - expandCommerceEvent: function expandCommerceEvent(event) { - return self.getInstance().eCommerce.expandCommerceEvent(event); - } - }; - this.setSessionAttribute = function (key, value) { - self.getInstance().setSessionAttribute(key, value); - }; - this.setOptOut = function (isOptingOut) { - self.getInstance().setOptOut(isOptingOut); - }; - this.setIntegrationAttribute = function (integrationId, attrs) { - self.getInstance().setIntegrationAttribute(integrationId, attrs); - }; - this.getIntegrationAttributes = function (moduleId) { - return self.getInstance().getIntegrationAttributes(moduleId); - }; - this.Identity = { - HTTPCodes: Constants.HTTPCodes, - aliasUsers: function aliasUsers(aliasRequest, callback) { - self.getInstance().Identity.aliasUsers(aliasRequest, callback); - }, - createAliasRequest: function createAliasRequest(sourceUser, destinationUser, scope) { - return self.getInstance().Identity.createAliasRequest(sourceUser, destinationUser, scope); - }, - getCurrentUser: function getCurrentUser() { - return self.getInstance().Identity.getCurrentUser(); - }, - getUser: function getUser(mpid) { - return self.getInstance().Identity.getUser(mpid); - }, - getUsers: function getUsers() { - return self.getInstance().Identity.getUsers(); - }, - identify: function identify(identityApiData, callback) { - self.getInstance().Identity.identify(identityApiData, callback); - }, - login: function login(identityApiData, callback) { - self.getInstance().Identity.login(identityApiData, callback); - }, - logout: function logout(identityApiData, callback) { - self.getInstance().Identity.logout(identityApiData, callback); - }, - modify: function modify(identityApiData, callback) { - self.getInstance().Identity.modify(identityApiData, callback); - } - }; - this.sessionManager = { - getSession: function getSession() { - return self.getInstance()._SessionManager.getSession(); - } - }; - this.Consent = { - createConsentState: function createConsentState() { - return self.getInstance().Consent.createConsentState(); - }, - createGDPRConsent: function createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId) { - return self.getInstance().Consent.createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId); - }, - createCCPAConsent: function createCCPAConsent(consented, timestamp, consentDocument, location, hardwareId) { - return self.getInstance().Consent.createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId); - } - }; - this.reset = function () { - self.getInstance().reset(self.getInstance()); - }; - this._resetForTests = function (MPConfig, keepPersistence) { - if (typeof keepPersistence === 'boolean') { - self.getInstance()._resetForTests(MPConfig, keepPersistence, self.getInstance()); - } else { - self.getInstance()._resetForTests(MPConfig, false, self.getInstance()); - } - }; - this.configurePixel = function (settings) { - self.getInstance().configurePixel(settings); - }; - this._setIntegrationDelay = function (moduleId, _boolean) { - self.getInstance()._setIntegrationDelay(moduleId, _boolean); - }; - this._getIntegrationDelays = function () { - return self.getInstance()._getIntegrationDelays(); - }; - this.getVersion = function () { - return self.getInstance().getVersion(); - }; - this.generateHash = function (string) { - return self.getInstance().generateHash(string); - }; - this.addForwarder = function (forwarder) { - self.getInstance().addForwarder(forwarder); - }; - this._getActiveForwarders = function () { - return self.getInstance()._getActiveForwarders(); - }; - this._setWrapperSDKInfo = function (name, version) { - self.getInstance()._setWrapperSDKInfo(name, version); - }; - this.registerErrorReportingService = function (service) { - self.getInstance().registerErrorReportingService(service); - }; - this.registerLoggingService = function (service) { - self.getInstance().registerLoggingService(service); - }; - } - var mParticleManager = new mParticleInstanceManager(); - if (typeof window !== 'undefined') { - // mParticle is the global object used to access the SDK and predates instance manager, - // when mParticle was a singleton. We now support multiple instances. Calling methods - // on mParticle directly will access the default instance, but mParticle can also be used - // as the instance manager in self hosted mode. - window.mParticle = mParticleManager; - // https://go.mparticle.com/work/SQDSDKS-5053 - window.mParticle._BatchValidator = new _BatchValidator(); - } - - return mParticleManager; - -})(); diff --git a/dist/mparticle.stub.js b/dist/mparticle.stub.js deleted file mode 100644 index 8275bb1d4..000000000 --- a/dist/mparticle.stub.js +++ /dev/null @@ -1,186 +0,0 @@ -var mParticle = (function () { - - let mParticle = { - endSession: voidFunction, - getAppName: returnString, - getAppVersion: returnString, - getDeviceId: returnString, - getEnvironment: returnString, - getVersion: returnString, - init: voidFunction, - logError: voidFunction, - logEvent: voidFunction, - logForm: voidFunction, - logLink: voidFunction, - logPageView: voidFunction, - ready: voidFunction, - reset: voidFunction, - _resetForTests: voidFunction, - setAppName: voidFunction, - setAppVersion: voidFunction, - setLogLevel: voidFunction, - setOptOut: voidFunction, - setPosition: voidFunction, - setSessionAttribute: voidFunction, - startNewSession: voidFunction, - startTrackingLocation: voidFunction, - stopTrackingLocation: voidFunction, - CommerceEventType: {}, - EventType: {}, - IdentityType: {}, - ProductActionType: {}, - PromotionType: {}, - eCommerce: { - createImpression: returnImpression, - createProduct: returnProduct, - createPromotion: returnPromotion, - createTransactionAttributes: returnTransactionAttributes, - logCheckout: voidFunction, - logImpression: voidFunction, - logProductAction: voidFunction, - logPromotion: voidFunction, - logPurchase: voidFunction, - logRefund: voidFunction, - setCurrencyCode: voidFunction, - Cart: new Cart(), - }, - Consent: { - createConsentState: createConsentState, - createGDPRConsent: returnGDPRConsent, - }, - Identity: { - aliasUsers: voidFunction, - createAliasRequest: createAliasRequest, - getCurrentUser: returnUser, - getUser: returnUser, - getUsers: returnUsers, - identify: voidFunction, - login: voidFunction, - logout: voidFunction, - modify: voidFunction, - }, - }; - - function voidFunction() {} - function returnString() { - return ''; - } - function returnObject() { - return {}; - } - function returnThis() { - return this; - } - function returnUser() { - return { - getUserIdentities: function() { - return { - userIdentities: {}, - }; - }, - getMPID: returnString, - setUserTag: voidFunction, - removeUserTag: voidFunction, - setUserAttribute: voidFunction, - setUserAttributes: voidFunction, - removeUserAttribute: voidFunction, - setUserAttributeList: voidFunction, - removeAllUserAttributes: voidFunction, - getUserAttributesLists: returnObject, - getAllUserAttributes: returnObject, - getCart: Cart, - getConsentState: createConsentState, - setConsentState: voidFunction, - }; - } - - function returnUsers() { - return [returnUser()]; - } - - function Cart() { - return { - add: voidFunction, - clear: voidFunction, - remove: voidFunction, - getCartProducts: function() { - return [returnProduct()]; - }, - }; - } - - function returnImpression() { - return { - Name: 'name', - Product: returnProduct(), - }; - } - - function returnProduct() { - return { - Name: 'name', - Sku: 'sku', - Price: 0, - Quantity: 0, - Brand: 'brand', - Variant: 'variant', - Category: 'category', - Position: 'position', - CouponCode: 'couponCode', - TotalAmount: 0, - Attributes: {}, - }; - } - - function returnPromotion() { - return { - Id: 'id', - Creative: 'creative', - Name: 'name', - Position: 0, - }; - } - - function returnTransactionAttributes() { - return { - Id: 'id', - Affiliation: 'affiliation', - CouponCode: 'couponCode', - Revenue: 0, - Shipping: 'shipping', - Tax: 0, - }; - } - - function returnGDPRConsent() { - return { - ConsentDocument: 'doc', - Consented: false, - HardwareId: 'id', - Location: 'location', - Timestamp: 1568648478988, - }; - } - - function createAliasRequest() { - return { - sourceMpid: 'a', - destinationMpid: 'b', - startTime: new Date().getTime(), - endTime: new Date().getTime(), - scope: 'device', - }; - } - - function createConsentState() { - return { - addGDPRConsentState: returnThis, - setGDPRConsentState: returnThis, - getGDPRConsentState: returnGDPRConsent, - removeGDPRConsentState: returnThis, - }; - } - - return mParticle; - -})(); diff --git a/dist/src/batchUploader.d.ts b/dist/src/batchUploader.d.ts deleted file mode 100644 index eafd5e14b..000000000 --- a/dist/src/batchUploader.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Batch } from '@mparticle/event-models'; -import { SDKEvent, MParticleWebSDK } from './sdkRuntimeModels'; -export declare class BatchUploader { - static readonly CONTENT_TYPE: string; - static readonly MINIMUM_INTERVAL_MILLIS: number; - uploadIntervalMillis: number; - pendingEvents: SDKEvent[]; - pendingUploads: Batch[]; - mpInstance: MParticleWebSDK; - uploadUrl: string; - batchingEnabled: boolean; - constructor(mpInstance: MParticleWebSDK, uploadInterval: number); - private addEventListeners; - private isBeaconAvailable; - queueEvent(event: SDKEvent): void; - /** - * This implements crucial logic to: - * - bucket pending events by MPID, and then by Session, and upload individual batches for each bucket. - * - * In the future this should enforce other requirements such as maximum batch size. - * - * @param sdkEvents current pending events - * @param defaultUser the user to reference for events that are missing data - */ - private static createNewUploads; - /** - * This is the main loop function: - * - take all pending events and turn them into batches - * - attempt to upload each batch - * - * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false - * @param useBeacon whether to use the beacon API - used when the page is being unloaded - */ - private prepareAndUpload; - private upload; -} diff --git a/dist/src/constants.d.ts b/dist/src/constants.d.ts deleted file mode 100644 index 7271faa4e..000000000 --- a/dist/src/constants.d.ts +++ /dev/null @@ -1,151 +0,0 @@ -declare const Constants: { - readonly sdkVersion: string; - readonly sdkVendor: "mparticle"; - readonly platform: "web"; - readonly Messages: { - readonly ErrorMessages: { - readonly NoToken: "A token must be specified."; - readonly EventNameInvalidType: "Event name must be a valid string value."; - readonly EventDataInvalidType: "Event data must be a valid object hash."; - readonly LoggingDisabled: "Event logging is currently disabled."; - readonly CookieParseError: "Could not parse cookie"; - readonly EventEmpty: "Event object is null or undefined, cancelling send"; - readonly APIRequestEmpty: "APIRequest is null or undefined, cancelling send"; - readonly NoEventType: "Event type must be specified."; - readonly TransactionIdRequired: "Transaction ID is required"; - readonly TransactionRequired: "A transaction attributes object is required"; - readonly PromotionIdRequired: "Promotion ID is required"; - readonly BadAttribute: "Attribute value cannot be object or array"; - readonly BadKey: "Key value cannot be object or array"; - readonly BadLogPurchase: "Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"; - }; - readonly InformationMessages: { - readonly CookieSearch: "Searching for cookie"; - readonly CookieFound: "Cookie found, parsing values"; - readonly CookieNotFound: "Cookies not found"; - readonly CookieSet: "Setting cookie"; - readonly CookieSync: "Performing cookie sync"; - readonly SendBegin: "Starting to send event"; - readonly SendIdentityBegin: "Starting to send event to identity server"; - readonly SendWindowsPhone: "Sending event to Windows Phone container"; - readonly SendIOS: "Calling iOS path: "; - readonly SendAndroid: "Calling Android JS interface method: "; - readonly SendHttp: "Sending event to mParticle HTTP service"; - readonly SendAliasHttp: "Sending alias request to mParticle HTTP service"; - readonly SendIdentityHttp: "Sending event to mParticle HTTP service"; - readonly StartingNewSession: "Starting new Session"; - readonly StartingLogEvent: "Starting to log event"; - readonly StartingLogOptOut: "Starting to log user opt in/out"; - readonly StartingEndSession: "Starting to end session"; - readonly StartingInitialization: "Starting to initialize"; - readonly StartingLogCommerceEvent: "Starting to log commerce event"; - readonly StartingAliasRequest: "Starting to Alias MPIDs"; - readonly LoadingConfig: "Loading configuration options"; - readonly AbandonLogEvent: "Cannot log event, logging disabled or developer token not set"; - readonly AbandonAliasUsers: "Cannot Alias Users, logging disabled or developer token not set"; - readonly AbandonStartSession: "Cannot start session, logging disabled or developer token not set"; - readonly AbandonEndSession: "Cannot end session, logging disabled or developer token not set"; - readonly NoSessionToEnd: "Cannot end session, no active session found"; - }; - readonly ValidationMessages: { - readonly ModifyIdentityRequestUserIdentitiesPresent: "identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again"; - readonly IdentityRequesetInvalidKey: "There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again."; - readonly OnUserAliasType: "The onUserAlias value must be a function."; - readonly UserIdentities: "The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again."; - readonly UserIdentitiesInvalidKey: "There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again."; - readonly UserIdentitiesInvalidValues: "All user identity values must be strings or null. Request not sent to server. Please fix and try again."; - readonly AliasMissingMpid: "Alias Request must contain both a destinationMpid and a sourceMpid"; - readonly AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique"; - readonly AliasMissingTime: "Alias Request must have both a startTime and an endTime"; - readonly AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime"; - }; - }; - readonly NativeSdkPaths: { - readonly LogEvent: "logEvent"; - readonly SetUserTag: "setUserTag"; - readonly RemoveUserTag: "removeUserTag"; - readonly SetUserAttribute: "setUserAttribute"; - readonly RemoveUserAttribute: "removeUserAttribute"; - readonly SetSessionAttribute: "setSessionAttribute"; - readonly AddToCart: "addToCart"; - readonly RemoveFromCart: "removeFromCart"; - readonly ClearCart: "clearCart"; - readonly LogOut: "logOut"; - readonly SetUserAttributeList: "setUserAttributeList"; - readonly RemoveAllUserAttributes: "removeAllUserAttributes"; - readonly GetUserAttributesLists: "getUserAttributesLists"; - readonly GetAllUserAttributes: "getAllUserAttributes"; - readonly Identify: "identify"; - readonly Logout: "logout"; - readonly Login: "login"; - readonly Modify: "modify"; - readonly Alias: "aliasUsers"; - readonly Upload: "upload"; - }; - readonly StorageNames: { - readonly localStorageName: "mprtcl-api"; - readonly localStorageNameV3: "mprtcl-v3"; - readonly cookieName: "mprtcl-api"; - readonly cookieNameV2: "mprtcl-v2"; - readonly cookieNameV3: "mprtcl-v3"; - readonly localStorageNameV4: "mprtcl-v4"; - readonly localStorageProductsV4: "mprtcl-prodv4"; - readonly cookieNameV4: "mprtcl-v4"; - readonly currentStorageName: "mprtcl-v4"; - readonly currentStorageProductsName: "mprtcl-prodv4"; - }; - readonly DefaultConfig: { - readonly cookieDomain: any; - readonly cookieExpiration: 365; - readonly logLevel: any; - readonly timeout: 300; - readonly sessionTimeout: 30; - readonly maxProducts: 20; - readonly forwarderStatsTimeout: 5000; - readonly integrationDelayTimeout: 5000; - readonly maxCookieSize: 3000; - readonly aliasMaxWindow: 90; - readonly uploadInterval: 0; - }; - readonly DefaultUrls: { - readonly v1SecureServiceUrl: "jssdks.mparticle.com/v1/JS/"; - readonly v2SecureServiceUrl: "jssdks.mparticle.com/v2/JS/"; - readonly v3SecureServiceUrl: "jssdks.mparticle.com/v3/JS/"; - readonly configUrl: "jssdkcdns.mparticle.com/JS/v2/"; - readonly identityUrl: "identity.mparticle.com/v1/"; - readonly aliasUrl: "jssdks.mparticle.com/v1/identity/"; - }; - readonly Base64CookieKeys: { - readonly csm: 1; - readonly sa: 1; - readonly ss: 1; - readonly ua: 1; - readonly ui: 1; - readonly csd: 1; - readonly ia: 1; - readonly con: 1; - }; - readonly SDKv2NonMPIDCookieKeys: { - readonly gs: 1; - readonly cu: 1; - readonly l: 1; - readonly globalSettings: 1; - readonly currentUserMPID: 1; - }; - readonly HTTPCodes: { - readonly noHttpCoverage: -1; - readonly activeIdentityRequest: -2; - readonly activeSession: -3; - readonly validationIssue: -4; - readonly nativeIdentityRequest: -5; - readonly loggingDisabledOrMissingAPIKey: -6; - readonly tooManyRequests: 429; - }; - readonly FeatureFlags: { - readonly ReportBatching: "reportBatching"; - readonly EventsV3: "eventsV3"; - readonly EventBatchingIntervalMillis: "eventBatchingIntervalMillis"; - }; - readonly DefaultInstance: "default_instance"; -}; -export default Constants; diff --git a/dist/src/kitBlocking.d.ts b/dist/src/kitBlocking.d.ts deleted file mode 100644 index 40ae6250b..000000000 --- a/dist/src/kitBlocking.d.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { SDKEvent, MParticleWebSDK, KitBlockerDataPlan } from './sdkRuntimeModels'; -import { BaseEvent } from '@mparticle/event-models'; -import { DataPlanPoint } from '@mparticle/data-planning-models'; -export default class KitBlocker { - dataPlanMatchLookups: { - [key: string]: {}; - }; - blockEvents: boolean; - blockEventAttributes: boolean; - blockUserAttributes: boolean; - blockUserIdentities: boolean; - kitBlockingEnabled: boolean; - mpInstance: MParticleWebSDK; - constructor(dataPlan: KitBlockerDataPlan, mpInstance: MParticleWebSDK); - addToMatchLookups(point: DataPlanPoint): void; - generateMatchKey(match: any): string | null; - generateProductAttributeMatchKey(match: any): string | null; - getPlannedProperties(type: any, validator: any): boolean | { - [key: string]: true; - } | null; - getProductProperties(type: any, validator: any): boolean | { - [key: string]: true; - } | null; - getMatchKey(eventToMatch: BaseEvent): string | null; - getProductAttributeMatchKey(eventToMatch: BaseEvent): string | null; - createBlockedEvent(event: SDKEvent): SDKEvent; - transformEventAndEventAttributes(event: SDKEvent): SDKEvent; - transformProductAttributes(event: SDKEvent): SDKEvent; - transformUserAttributes(event: SDKEvent): { - DeviceId: string; - IsFirstRun: boolean; - EventName: string; - EventCategory: number; - UserAttributes?: { - [key: string]: string | string[]; - }; - UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; - SourceMessageId: string; - MPID: string; - EventAttributes?: { - [key: string]: string; - }; - SDKVersion: string; - SessionId: string; - SessionStartDate: number; - SessionLength?: number; - currentSessionMPIDs?: string[]; - Timestamp: number; - EventDataType: number; - Debug: boolean; - Location?: import("./sdkRuntimeModels").SDKGeoLocation; - OptOut?: boolean; - CustomFlags?: { - [key: string]: string; - }; - AppVersion?: string; - AppName?: string; - Package?: string; - ConsentState?: import("./sdkRuntimeModels").SDKConsentState; - IntegrationAttributes?: { - [key: string]: { - [key: string]: string; - }; - }; - ProductAction?: import("./sdkRuntimeModels").SDKProductAction; - PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; - ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; - ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; - UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; - UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; - CurrencyCode: string; - DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; - LaunchReferral?: string; - }; - isAttributeKeyBlocked(key: string): boolean; - isIdentityBlocked(key: string): boolean; - transformUserIdentities(event: SDKEvent): { - DeviceId: string; - IsFirstRun: boolean; - EventName: string; - EventCategory: number; - UserAttributes?: { - [key: string]: string | string[]; - }; - UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; - SourceMessageId: string; - MPID: string; - EventAttributes?: { - [key: string]: string; - }; - SDKVersion: string; - SessionId: string; - SessionStartDate: number; - SessionLength?: number; - currentSessionMPIDs?: string[]; - Timestamp: number; - EventDataType: number; - Debug: boolean; - Location?: import("./sdkRuntimeModels").SDKGeoLocation; - OptOut?: boolean; - CustomFlags?: { - [key: string]: string; - }; - AppVersion?: string; - AppName?: string; - Package?: string; - ConsentState?: import("./sdkRuntimeModels").SDKConsentState; - IntegrationAttributes?: { - [key: string]: { - [key: string]: string; - }; - }; - ProductAction?: import("./sdkRuntimeModels").SDKProductAction; - PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; - ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; - ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; - UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; - UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; - CurrencyCode: string; - DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; - LaunchReferral?: string; - }; -} diff --git a/dist/src/mockBatchCreator.d.ts b/dist/src/mockBatchCreator.d.ts deleted file mode 100644 index 2be2d9c2e..000000000 --- a/dist/src/mockBatchCreator.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { BaseEvent } from './sdkRuntimeModels'; -import * as EventsApi from '@mparticle/event-models'; -export default class _BatchValidator { - private getMPInstance; - returnBatch(event: BaseEvent): EventsApi.Batch; -} diff --git a/dist/src/sdkRuntimeModels.d.ts b/dist/src/sdkRuntimeModels.d.ts deleted file mode 100644 index 253e653a2..000000000 --- a/dist/src/sdkRuntimeModels.d.ts +++ /dev/null @@ -1,303 +0,0 @@ -import * as EventsApi from '@mparticle/event-models'; -import { DataPlanVersion } from '@mparticle/data-planning-models'; -export interface SDKEvent { - DeviceId: string; - IsFirstRun: boolean; - EventName: string; - EventCategory: number; - UserAttributes?: { - [key: string]: string | string[] | null; - }; - UserIdentities?: SDKUserIdentity[]; - SourceMessageId: string; - MPID: string; - EventAttributes?: { - [key: string]: string; - }; - SDKVersion: string; - SessionId: string; - SessionStartDate: number; - SessionLength?: number; - currentSessionMPIDs?: string[]; - Timestamp: number; - EventDataType: number; - Debug: boolean; - Location?: SDKGeoLocation; - OptOut?: boolean; - CustomFlags?: { - [key: string]: string; - }; - AppVersion?: string; - AppName?: string; - Package?: string; - ConsentState?: SDKConsentState; - IntegrationAttributes?: { - [key: string]: { - [key: string]: string; - }; - }; - ProductAction?: SDKProductAction; - PromotionAction?: SDKPromotionAction; - ProductImpressions?: SDKProductImpression[]; - ShoppingCart?: SDKShoppingCart; - UserIdentityChanges?: SDKUserIdentityChangeData; - UserAttributeChanges?: SDKUserAttributeChangeData; - CurrencyCode: string; - DataPlan?: SDKDataPlan; - LaunchReferral?: string; -} -export interface SDKGeoLocation { - lat: number | string; - lng: number | string; -} -export interface SDKDataPlan { - PlanVersion?: number | null; - PlanId?: string | null; -} -export interface SDKUserIdentity { - Identity?: string; - Type: number; -} -export interface SDKShoppingCart { - ProductList?: SDKProduct[]; -} -export interface SDKPromotionAction { - PromotionActionType: string; - PromotionList?: SDKPromotion[]; -} -export interface SDKPromotion { - Id?: string; - Name?: string; - Creative?: string; - Position?: string; -} -export interface SDKProductImpression { - ProductImpressionList?: string; - ProductList?: SDKProduct[]; -} -export declare enum SDKProductActionType { - Unknown = 0, - AddToCart = 1, - RemoveFromCart = 2, - Checkout = 3, - CheckoutOption = 4, - Click = 5, - ViewDetail = 6, - Purchase = 7, - Refund = 8, - AddToWishlist = 9, - RemoveFromWishlist = 10 -} -export interface SDKProductAction { - ProductActionType: SDKProductActionType; - CheckoutStep?: number; - CheckoutOptions?: string; - ProductList?: SDKProduct[]; - TransactionId?: string; - Affiliation?: string; - CouponCode?: string; - TotalAmount?: number; - ShippingAmount?: number; - TaxAmount?: number; -} -export interface SDKProduct { - Sku?: string; - Name?: string; - Price?: number; - Quantity?: number; - Brand?: string; - Variant?: string; - Category?: string; - Position?: number; - CouponCode?: string; - TotalAmount?: number; - Attributes?: { - [key: string]: string; - }; -} -export interface MParticleWebSDK { - addForwarder(mockForwarder: any): any; - Identity: SDKIdentityApi; - Logger: SDKLoggerApi; - _Store: SDKStoreApi; - _Helpers: SDKHelpersApi; - config: SDKConfig; - _resetForTests(MPConfig: SDKConfig): void; - init(apiKey: string, config: SDKConfig): void; - getInstance(): any; - ServerModel(): any; - upload(): any; - setPosition(lat: number | string, lng: number | string): void; - logEvent(eventName: string, eventType?: number, attrs?: { - [key: string]: string; - }): void; - logBaseEvent(event: any): void; - eCommerce: any; - logLevel: string; - ProductActionType: SDKProductActionType; - generateHash(value: string): any; -} -export interface SDKConfig { - isDevelopmentMode?: boolean; - logger: { - error?(msg: any): any; - warning?(msg: any): any; - verbose?(msg: any): any; - }; - onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; - dataPlan: DataPlanConfig; - appVersion?: string; - package?: string; - flags?: { - [key: string]: string | number; - }; - kitConfigs: any; - appName?: string; - logLevel?: string; - sessionTimeout?: number; - useCookieStorage?: boolean; - cookieDomain?: string; - workspaceToken: string; - requiredWebviewBridgeName: string; - minWebviewBridgeVersion: number; - isIOS?: boolean; - identifyRequest: { - [key: string]: { - [key: string]: string; - }; - }; - identityCallback: (result: any) => void; - requestConfig: boolean; - dataPlanOptions: KitBlockerOptions; - dataPlanResult?: DataPlanResult; -} -export interface DataPlanConfig { - planId?: string; - planVersion?: number; - document?: DataPlanResult; -} -export interface SDKIdentityApi { - getCurrentUser(): any; - IdentityAPI: any; - identify: any; - login: any; - logout: any; - modify: any; -} -export interface SDKHelpersApi { - createServiceUrl(arg0: string, arg1: string): void; - parseNumber(value: number): any; - generateUniqueId(): any; - isObject(item: any): any; -} -export interface SDKLoggerApi { - error(arg0: string): void; - verbose(arg0: string): void; - warning(arg0: string): void; -} -export interface SDKStoreApi { - isFirstRun: boolean; - devToken: string; - SDKConfig: SDKConfigApi; - sessionId?: string; - deviceId?: string; -} -export interface SDKConfigApi { - v3SecureServiceUrl?: string; - isDevelopmentMode: boolean; - appVersion?: string; - onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; -} -export interface MParticleUser { - getMPID(): string; -} -export interface SDKConsentState { - getGDPRConsentState(): SDKGDPRConsentState; - getCCPAConsentState(): SDKCCPAConsentState; -} -export interface SDKGDPRConsentState { - [key: string]: SDKConsentStateData; -} -export interface SDKConsentStateData { - Consented: boolean; - Timestamp?: number; - ConsentDocument?: string; - Location?: string; - HardwareId?: string; -} -export interface SDKCCPAConsentState extends SDKConsentStateData { -} -export interface SDKUserIdentityChangeData { - New: Identity; - Old: Identity; -} -export interface Identity { - IdentityType: SDKIdentityTypeEnum; - Identity: string; - Timestamp: number; - CreatedThisBatch: boolean; -} -export interface SDKUserAttributeChangeData { - UserAttributeName: string; - New: string; - Old: string; - Deleted: boolean; - IsNewAttribute: boolean; -} -export interface BaseEvent { - messageType: number; - name: string; - eventType?: number; - data?: { - [key: string]: string; - }; - customFlags?: { - [key: string]: string; - }; -} -export interface KitBlockerOptions { - dataPlanVersion: DataPlanVersion; - blockUserAttributes: boolean; - blockEventAttributes: boolean; - blockEvents: boolean; - blockUserIdentities: boolean; -} -export interface KitBlockerDataPlan { - document: DataPlanResult; -} -export interface DataPlanResult { - dtpn?: { - vers: DataPlanVersion; - blok: { - ev: boolean; - ea: boolean; - ua: boolean; - id: boolean; - }; - }; - error_message?: string; -} -export declare enum SDKIdentityTypeEnum { - other = "other", - customerId = "customerid", - facebook = "facebook", - twitter = "twitter", - google = "google", - microsoft = "microsoft", - yahoo = "yahoo", - email = "email", - alias = "alias", - facebookCustomAudienceId = "facebookcustomaudienceid", - otherId2 = "other2", - otherId3 = "other3", - otherId4 = "other4", - otherId5 = "other5", - otherId6 = "other6", - otherId7 = "other7", - otherId8 = "other8", - otherId9 = "other9", - otherId10 = "other10", - mobileNumber = "mobile_number", - phoneNumber2 = "phone_number_2", - phoneNumber3 = "phone_number_3" -} diff --git a/dist/src/sdkToEventsApiConverter.d.ts b/dist/src/sdkToEventsApiConverter.d.ts deleted file mode 100644 index 08bf810a1..000000000 --- a/dist/src/sdkToEventsApiConverter.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { SDKEvent, SDKConsentState, SDKGDPRConsentState, SDKGeoLocation, SDKCCPAConsentState, SDKProduct, SDKPromotion, SDKUserIdentity, SDKProductActionType, MParticleWebSDK, SDKIdentityTypeEnum } from './sdkRuntimeModels'; -import * as EventsApi from '@mparticle/event-models'; -export declare function convertEvents(mpid: string, sdkEvents: SDKEvent[], mpInstance: MParticleWebSDK): EventsApi.Batch | null; -export declare function convertConsentState(sdkConsentState?: SDKConsentState): EventsApi.ConsentState | null; -export declare function convertGdprConsentState(sdkGdprConsentState: SDKGDPRConsentState): { - [key: string]: EventsApi.GDPRConsentState | null; -}; -export declare function convertCcpaConsentState(sdkCcpaConsentState: SDKCCPAConsentState): { - data_sale_opt_out: EventsApi.CCPAConsentState; -}; -export declare function convertUserIdentities(sdkUserIdentities?: SDKUserIdentity[]): EventsApi.BatchUserIdentities | null; -export declare function convertEvent(sdkEvent: SDKEvent): EventsApi.BaseEvent | null; -export declare function convertProductActionType(actionType: SDKProductActionType): EventsApi.ProductActionActionEnum; -export declare function convertProductAction(sdkEvent: SDKEvent): EventsApi.ProductAction | null; -export declare function convertProducts(sdkProducts: SDKProduct[]): EventsApi.Product[] | null; -export declare function convertPromotionAction(sdkEvent: SDKEvent): EventsApi.PromotionAction | null; -export declare function convertPromotions(sdkPromotions: SDKPromotion[]): EventsApi.Promotion[] | null; -export declare function convertImpressions(sdkEvent: SDKEvent): EventsApi.ProductImpression[] | null; -export declare function convertShoppingCart(sdkEvent: SDKEvent): EventsApi.ShoppingCart | null; -export declare function convertCommerceEvent(sdkEvent: SDKEvent): EventsApi.CommerceEvent; -export declare function convertCrashReportEvent(sdkEvent: SDKEvent): EventsApi.CrashReportEvent; -export declare function convertAST(sdkEvent: SDKEvent): EventsApi.ApplicationStateTransitionEvent; -export declare function convertSessionEndEvent(sdkEvent: SDKEvent): EventsApi.SessionEndEvent; -export declare function convertSessionStartEvent(sdkEvent: SDKEvent): EventsApi.SessionStartEvent; -export declare function convertPageViewEvent(sdkEvent: SDKEvent): EventsApi.ScreenViewEvent; -export declare function convertOptOutEvent(sdkEvent: SDKEvent): EventsApi.OptOutEvent; -export declare function convertCustomEvent(sdkEvent: SDKEvent): EventsApi.CustomEvent; -export declare function convertSdkEventType(sdkEventType: number): EventsApi.CustomEventDataCustomEventTypeEnum | EventsApi.CommerceEventDataCustomEventTypeEnum; -export declare function convertBaseEventData(sdkEvent: SDKEvent): EventsApi.CommonEventData; -export declare function convertSDKLocation(sdkEventLocation: SDKGeoLocation): EventsApi.GeoLocation; -export declare function convertUserAttributeChangeEvent(sdkEvent: SDKEvent): EventsApi.UserAttributeChangeEvent | null; -export declare function convertUserIdentityChangeEvent(sdkEvent: SDKEvent): EventsApi.UserIdentityChangeEvent | null; -export declare function convertUserIdentityTypeToServerIdentityType(identityType: SDKIdentityTypeEnum): EventsApi.IdentityType; diff --git a/dist/src/utils.d.ts b/dist/src/utils.d.ts deleted file mode 100644 index 65e815275..000000000 --- a/dist/src/utils.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare type valueof = T[keyof T]; -declare const inArray: (items: any[], name: string) => boolean; -declare const findKeyInObject: (obj: any, key: string) => string; -declare const isObject: (value: any) => boolean; -declare const parseNumber: (value: string | number) => number; -declare const returnConvertedBoolean: (data: string | boolean | number) => boolean; -declare const decoded: (s: string) => string; -declare const converted: (s: string) => string; -export { valueof, converted, decoded, findKeyInObject, inArray, isObject, parseNumber, returnConvertedBoolean, }; diff --git a/dist/src/validators.d.ts b/dist/src/validators.d.ts deleted file mode 100644 index a597733a3..000000000 --- a/dist/src/validators.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import Constants from './constants'; -import { IdentityApiData } from '@mparticle/web-sdk'; -import { valueof } from './utils'; -declare type IdentityAPIMethod = 'login' | 'logout' | 'identify' | 'modify'; -declare type ValidationIdentitiesReturn = { - valid: boolean; - error?: valueof; -}; -declare const Validators: { - isValidAttributeValue: (value: any) => boolean; - isValidKeyValue: (key: any) => boolean; - isStringOrNumber: (value: any) => boolean; - isNumber: (value: any) => boolean; - isFunction: (fn: any) => boolean; - validateIdentities: (identityApiData: IdentityApiData, method?: IdentityAPIMethod) => ValidationIdentitiesReturn; -}; -export default Validators; diff --git a/dist/test/src/tests-batchUploader.d.ts b/dist/test/src/tests-batchUploader.d.ts deleted file mode 100644 index 91747f762..000000000 --- a/dist/test/src/tests-batchUploader.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; -declare global { - interface Window { - mParticle: MParticleWebSDK; - fetchMock: any; - } -} diff --git a/dist/test/src/tests-kit-blocking.d.ts b/dist/test/src/tests-kit-blocking.d.ts deleted file mode 100644 index 80f99eb44..000000000 --- a/dist/test/src/tests-kit-blocking.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; -declare global { - interface Window { - mParticle: MParticleWebSDK; - MockForwarder1: any; - } -} diff --git a/dist/test/src/tests-mockBatchCreator.d.ts b/dist/test/src/tests-mockBatchCreator.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/dist/test/src/tests-mockBatchCreator.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/dist/test/src/tests-runtimeToBatchEventsDTO.d.ts b/dist/test/src/tests-runtimeToBatchEventsDTO.d.ts deleted file mode 100644 index 0bf9e0891..000000000 --- a/dist/test/src/tests-runtimeToBatchEventsDTO.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; -declare global { - interface Window { - mParticle: MParticleWebSDK; - } -} diff --git a/dist/test/src/tests-utils.d.ts b/dist/test/src/tests-utils.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/dist/test/src/tests-utils.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/dist/test/src/tests-validators.d.ts b/dist/test/src/tests-validators.d.ts deleted file mode 100644 index cb0ff5c3b..000000000 --- a/dist/test/src/tests-validators.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; From caf86dd5ca2132761098d726b720e64b4fcf23c0 Mon Sep 17 00:00:00 2001 From: Alexander Sapountzis Date: Fri, 20 Mar 2026 17:15:39 -0400 Subject: [PATCH 4/5] Revert "chore: remove dist/ from tracking (already in gitignore)" This reverts commit e573c1ff57418944451360dbdfe5b253f60b78f5. --- dist/build/src/batchUploader.d.ts | 36 + dist/build/src/constants.d.ts | 151 + dist/build/src/kitBlocking.d.ts | 123 + dist/build/src/mockBatchCreator.d.ts | 6 + dist/build/src/sdkRuntimeModels.d.ts | 303 + dist/build/src/sdkToEventsApiConverter.d.ts | 33 + dist/build/src/utils.d.ts | 9 + dist/build/src/validators.d.ts | 17 + dist/build/test/src/tests-batchUploader.d.ts | 7 + dist/build/test/src/tests-kit-blocking.d.ts | 7 + .../test/src/tests-mockBatchCreator.d.ts | 1 + .../src/tests-runtimeToBatchEventsDTO.d.ts | 6 + dist/build/test/src/tests-utils.d.ts | 1 + dist/build/test/src/tests-validators.d.ts | 1 + dist/mparticle.common.js | 1721 +++ dist/mparticle.esm.js | 1721 +++ dist/mparticle.js | 12110 ++++++++++++++++ dist/mparticle.stub.js | 186 + dist/src/batchUploader.d.ts | 36 + dist/src/constants.d.ts | 151 + dist/src/kitBlocking.d.ts | 123 + dist/src/mockBatchCreator.d.ts | 6 + dist/src/sdkRuntimeModels.d.ts | 303 + dist/src/sdkToEventsApiConverter.d.ts | 33 + dist/src/utils.d.ts | 9 + dist/src/validators.d.ts | 17 + dist/test/src/tests-batchUploader.d.ts | 7 + dist/test/src/tests-kit-blocking.d.ts | 7 + dist/test/src/tests-mockBatchCreator.d.ts | 1 + .../src/tests-runtimeToBatchEventsDTO.d.ts | 6 + dist/test/src/tests-utils.d.ts | 1 + dist/test/src/tests-validators.d.ts | 1 + 32 files changed, 17140 insertions(+) create mode 100644 dist/build/src/batchUploader.d.ts create mode 100644 dist/build/src/constants.d.ts create mode 100644 dist/build/src/kitBlocking.d.ts create mode 100644 dist/build/src/mockBatchCreator.d.ts create mode 100644 dist/build/src/sdkRuntimeModels.d.ts create mode 100644 dist/build/src/sdkToEventsApiConverter.d.ts create mode 100644 dist/build/src/utils.d.ts create mode 100644 dist/build/src/validators.d.ts create mode 100644 dist/build/test/src/tests-batchUploader.d.ts create mode 100644 dist/build/test/src/tests-kit-blocking.d.ts create mode 100644 dist/build/test/src/tests-mockBatchCreator.d.ts create mode 100644 dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts create mode 100644 dist/build/test/src/tests-utils.d.ts create mode 100644 dist/build/test/src/tests-validators.d.ts create mode 100644 dist/mparticle.common.js create mode 100644 dist/mparticle.esm.js create mode 100644 dist/mparticle.js create mode 100644 dist/mparticle.stub.js create mode 100644 dist/src/batchUploader.d.ts create mode 100644 dist/src/constants.d.ts create mode 100644 dist/src/kitBlocking.d.ts create mode 100644 dist/src/mockBatchCreator.d.ts create mode 100644 dist/src/sdkRuntimeModels.d.ts create mode 100644 dist/src/sdkToEventsApiConverter.d.ts create mode 100644 dist/src/utils.d.ts create mode 100644 dist/src/validators.d.ts create mode 100644 dist/test/src/tests-batchUploader.d.ts create mode 100644 dist/test/src/tests-kit-blocking.d.ts create mode 100644 dist/test/src/tests-mockBatchCreator.d.ts create mode 100644 dist/test/src/tests-runtimeToBatchEventsDTO.d.ts create mode 100644 dist/test/src/tests-utils.d.ts create mode 100644 dist/test/src/tests-validators.d.ts diff --git a/dist/build/src/batchUploader.d.ts b/dist/build/src/batchUploader.d.ts new file mode 100644 index 000000000..eafd5e14b --- /dev/null +++ b/dist/build/src/batchUploader.d.ts @@ -0,0 +1,36 @@ +import { Batch } from '@mparticle/event-models'; +import { SDKEvent, MParticleWebSDK } from './sdkRuntimeModels'; +export declare class BatchUploader { + static readonly CONTENT_TYPE: string; + static readonly MINIMUM_INTERVAL_MILLIS: number; + uploadIntervalMillis: number; + pendingEvents: SDKEvent[]; + pendingUploads: Batch[]; + mpInstance: MParticleWebSDK; + uploadUrl: string; + batchingEnabled: boolean; + constructor(mpInstance: MParticleWebSDK, uploadInterval: number); + private addEventListeners; + private isBeaconAvailable; + queueEvent(event: SDKEvent): void; + /** + * This implements crucial logic to: + * - bucket pending events by MPID, and then by Session, and upload individual batches for each bucket. + * + * In the future this should enforce other requirements such as maximum batch size. + * + * @param sdkEvents current pending events + * @param defaultUser the user to reference for events that are missing data + */ + private static createNewUploads; + /** + * This is the main loop function: + * - take all pending events and turn them into batches + * - attempt to upload each batch + * + * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false + * @param useBeacon whether to use the beacon API - used when the page is being unloaded + */ + private prepareAndUpload; + private upload; +} diff --git a/dist/build/src/constants.d.ts b/dist/build/src/constants.d.ts new file mode 100644 index 000000000..7271faa4e --- /dev/null +++ b/dist/build/src/constants.d.ts @@ -0,0 +1,151 @@ +declare const Constants: { + readonly sdkVersion: string; + readonly sdkVendor: "mparticle"; + readonly platform: "web"; + readonly Messages: { + readonly ErrorMessages: { + readonly NoToken: "A token must be specified."; + readonly EventNameInvalidType: "Event name must be a valid string value."; + readonly EventDataInvalidType: "Event data must be a valid object hash."; + readonly LoggingDisabled: "Event logging is currently disabled."; + readonly CookieParseError: "Could not parse cookie"; + readonly EventEmpty: "Event object is null or undefined, cancelling send"; + readonly APIRequestEmpty: "APIRequest is null or undefined, cancelling send"; + readonly NoEventType: "Event type must be specified."; + readonly TransactionIdRequired: "Transaction ID is required"; + readonly TransactionRequired: "A transaction attributes object is required"; + readonly PromotionIdRequired: "Promotion ID is required"; + readonly BadAttribute: "Attribute value cannot be object or array"; + readonly BadKey: "Key value cannot be object or array"; + readonly BadLogPurchase: "Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"; + }; + readonly InformationMessages: { + readonly CookieSearch: "Searching for cookie"; + readonly CookieFound: "Cookie found, parsing values"; + readonly CookieNotFound: "Cookies not found"; + readonly CookieSet: "Setting cookie"; + readonly CookieSync: "Performing cookie sync"; + readonly SendBegin: "Starting to send event"; + readonly SendIdentityBegin: "Starting to send event to identity server"; + readonly SendWindowsPhone: "Sending event to Windows Phone container"; + readonly SendIOS: "Calling iOS path: "; + readonly SendAndroid: "Calling Android JS interface method: "; + readonly SendHttp: "Sending event to mParticle HTTP service"; + readonly SendAliasHttp: "Sending alias request to mParticle HTTP service"; + readonly SendIdentityHttp: "Sending event to mParticle HTTP service"; + readonly StartingNewSession: "Starting new Session"; + readonly StartingLogEvent: "Starting to log event"; + readonly StartingLogOptOut: "Starting to log user opt in/out"; + readonly StartingEndSession: "Starting to end session"; + readonly StartingInitialization: "Starting to initialize"; + readonly StartingLogCommerceEvent: "Starting to log commerce event"; + readonly StartingAliasRequest: "Starting to Alias MPIDs"; + readonly LoadingConfig: "Loading configuration options"; + readonly AbandonLogEvent: "Cannot log event, logging disabled or developer token not set"; + readonly AbandonAliasUsers: "Cannot Alias Users, logging disabled or developer token not set"; + readonly AbandonStartSession: "Cannot start session, logging disabled or developer token not set"; + readonly AbandonEndSession: "Cannot end session, logging disabled or developer token not set"; + readonly NoSessionToEnd: "Cannot end session, no active session found"; + }; + readonly ValidationMessages: { + readonly ModifyIdentityRequestUserIdentitiesPresent: "identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again"; + readonly IdentityRequesetInvalidKey: "There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again."; + readonly OnUserAliasType: "The onUserAlias value must be a function."; + readonly UserIdentities: "The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again."; + readonly UserIdentitiesInvalidKey: "There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again."; + readonly UserIdentitiesInvalidValues: "All user identity values must be strings or null. Request not sent to server. Please fix and try again."; + readonly AliasMissingMpid: "Alias Request must contain both a destinationMpid and a sourceMpid"; + readonly AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique"; + readonly AliasMissingTime: "Alias Request must have both a startTime and an endTime"; + readonly AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime"; + }; + }; + readonly NativeSdkPaths: { + readonly LogEvent: "logEvent"; + readonly SetUserTag: "setUserTag"; + readonly RemoveUserTag: "removeUserTag"; + readonly SetUserAttribute: "setUserAttribute"; + readonly RemoveUserAttribute: "removeUserAttribute"; + readonly SetSessionAttribute: "setSessionAttribute"; + readonly AddToCart: "addToCart"; + readonly RemoveFromCart: "removeFromCart"; + readonly ClearCart: "clearCart"; + readonly LogOut: "logOut"; + readonly SetUserAttributeList: "setUserAttributeList"; + readonly RemoveAllUserAttributes: "removeAllUserAttributes"; + readonly GetUserAttributesLists: "getUserAttributesLists"; + readonly GetAllUserAttributes: "getAllUserAttributes"; + readonly Identify: "identify"; + readonly Logout: "logout"; + readonly Login: "login"; + readonly Modify: "modify"; + readonly Alias: "aliasUsers"; + readonly Upload: "upload"; + }; + readonly StorageNames: { + readonly localStorageName: "mprtcl-api"; + readonly localStorageNameV3: "mprtcl-v3"; + readonly cookieName: "mprtcl-api"; + readonly cookieNameV2: "mprtcl-v2"; + readonly cookieNameV3: "mprtcl-v3"; + readonly localStorageNameV4: "mprtcl-v4"; + readonly localStorageProductsV4: "mprtcl-prodv4"; + readonly cookieNameV4: "mprtcl-v4"; + readonly currentStorageName: "mprtcl-v4"; + readonly currentStorageProductsName: "mprtcl-prodv4"; + }; + readonly DefaultConfig: { + readonly cookieDomain: any; + readonly cookieExpiration: 365; + readonly logLevel: any; + readonly timeout: 300; + readonly sessionTimeout: 30; + readonly maxProducts: 20; + readonly forwarderStatsTimeout: 5000; + readonly integrationDelayTimeout: 5000; + readonly maxCookieSize: 3000; + readonly aliasMaxWindow: 90; + readonly uploadInterval: 0; + }; + readonly DefaultUrls: { + readonly v1SecureServiceUrl: "jssdks.mparticle.com/v1/JS/"; + readonly v2SecureServiceUrl: "jssdks.mparticle.com/v2/JS/"; + readonly v3SecureServiceUrl: "jssdks.mparticle.com/v3/JS/"; + readonly configUrl: "jssdkcdns.mparticle.com/JS/v2/"; + readonly identityUrl: "identity.mparticle.com/v1/"; + readonly aliasUrl: "jssdks.mparticle.com/v1/identity/"; + }; + readonly Base64CookieKeys: { + readonly csm: 1; + readonly sa: 1; + readonly ss: 1; + readonly ua: 1; + readonly ui: 1; + readonly csd: 1; + readonly ia: 1; + readonly con: 1; + }; + readonly SDKv2NonMPIDCookieKeys: { + readonly gs: 1; + readonly cu: 1; + readonly l: 1; + readonly globalSettings: 1; + readonly currentUserMPID: 1; + }; + readonly HTTPCodes: { + readonly noHttpCoverage: -1; + readonly activeIdentityRequest: -2; + readonly activeSession: -3; + readonly validationIssue: -4; + readonly nativeIdentityRequest: -5; + readonly loggingDisabledOrMissingAPIKey: -6; + readonly tooManyRequests: 429; + }; + readonly FeatureFlags: { + readonly ReportBatching: "reportBatching"; + readonly EventsV3: "eventsV3"; + readonly EventBatchingIntervalMillis: "eventBatchingIntervalMillis"; + }; + readonly DefaultInstance: "default_instance"; +}; +export default Constants; diff --git a/dist/build/src/kitBlocking.d.ts b/dist/build/src/kitBlocking.d.ts new file mode 100644 index 000000000..40ae6250b --- /dev/null +++ b/dist/build/src/kitBlocking.d.ts @@ -0,0 +1,123 @@ +import { SDKEvent, MParticleWebSDK, KitBlockerDataPlan } from './sdkRuntimeModels'; +import { BaseEvent } from '@mparticle/event-models'; +import { DataPlanPoint } from '@mparticle/data-planning-models'; +export default class KitBlocker { + dataPlanMatchLookups: { + [key: string]: {}; + }; + blockEvents: boolean; + blockEventAttributes: boolean; + blockUserAttributes: boolean; + blockUserIdentities: boolean; + kitBlockingEnabled: boolean; + mpInstance: MParticleWebSDK; + constructor(dataPlan: KitBlockerDataPlan, mpInstance: MParticleWebSDK); + addToMatchLookups(point: DataPlanPoint): void; + generateMatchKey(match: any): string | null; + generateProductAttributeMatchKey(match: any): string | null; + getPlannedProperties(type: any, validator: any): boolean | { + [key: string]: true; + } | null; + getProductProperties(type: any, validator: any): boolean | { + [key: string]: true; + } | null; + getMatchKey(eventToMatch: BaseEvent): string | null; + getProductAttributeMatchKey(eventToMatch: BaseEvent): string | null; + createBlockedEvent(event: SDKEvent): SDKEvent; + transformEventAndEventAttributes(event: SDKEvent): SDKEvent; + transformProductAttributes(event: SDKEvent): SDKEvent; + transformUserAttributes(event: SDKEvent): { + DeviceId: string; + IsFirstRun: boolean; + EventName: string; + EventCategory: number; + UserAttributes?: { + [key: string]: string | string[]; + }; + UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; + SourceMessageId: string; + MPID: string; + EventAttributes?: { + [key: string]: string; + }; + SDKVersion: string; + SessionId: string; + SessionStartDate: number; + SessionLength?: number; + currentSessionMPIDs?: string[]; + Timestamp: number; + EventDataType: number; + Debug: boolean; + Location?: import("./sdkRuntimeModels").SDKGeoLocation; + OptOut?: boolean; + CustomFlags?: { + [key: string]: string; + }; + AppVersion?: string; + AppName?: string; + Package?: string; + ConsentState?: import("./sdkRuntimeModels").SDKConsentState; + IntegrationAttributes?: { + [key: string]: { + [key: string]: string; + }; + }; + ProductAction?: import("./sdkRuntimeModels").SDKProductAction; + PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; + ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; + ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; + UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; + UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; + CurrencyCode: string; + DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; + LaunchReferral?: string; + }; + isAttributeKeyBlocked(key: string): boolean; + isIdentityBlocked(key: string): boolean; + transformUserIdentities(event: SDKEvent): { + DeviceId: string; + IsFirstRun: boolean; + EventName: string; + EventCategory: number; + UserAttributes?: { + [key: string]: string | string[]; + }; + UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; + SourceMessageId: string; + MPID: string; + EventAttributes?: { + [key: string]: string; + }; + SDKVersion: string; + SessionId: string; + SessionStartDate: number; + SessionLength?: number; + currentSessionMPIDs?: string[]; + Timestamp: number; + EventDataType: number; + Debug: boolean; + Location?: import("./sdkRuntimeModels").SDKGeoLocation; + OptOut?: boolean; + CustomFlags?: { + [key: string]: string; + }; + AppVersion?: string; + AppName?: string; + Package?: string; + ConsentState?: import("./sdkRuntimeModels").SDKConsentState; + IntegrationAttributes?: { + [key: string]: { + [key: string]: string; + }; + }; + ProductAction?: import("./sdkRuntimeModels").SDKProductAction; + PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; + ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; + ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; + UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; + UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; + CurrencyCode: string; + DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; + LaunchReferral?: string; + }; +} diff --git a/dist/build/src/mockBatchCreator.d.ts b/dist/build/src/mockBatchCreator.d.ts new file mode 100644 index 000000000..2be2d9c2e --- /dev/null +++ b/dist/build/src/mockBatchCreator.d.ts @@ -0,0 +1,6 @@ +import { BaseEvent } from './sdkRuntimeModels'; +import * as EventsApi from '@mparticle/event-models'; +export default class _BatchValidator { + private getMPInstance; + returnBatch(event: BaseEvent): EventsApi.Batch; +} diff --git a/dist/build/src/sdkRuntimeModels.d.ts b/dist/build/src/sdkRuntimeModels.d.ts new file mode 100644 index 000000000..253e653a2 --- /dev/null +++ b/dist/build/src/sdkRuntimeModels.d.ts @@ -0,0 +1,303 @@ +import * as EventsApi from '@mparticle/event-models'; +import { DataPlanVersion } from '@mparticle/data-planning-models'; +export interface SDKEvent { + DeviceId: string; + IsFirstRun: boolean; + EventName: string; + EventCategory: number; + UserAttributes?: { + [key: string]: string | string[] | null; + }; + UserIdentities?: SDKUserIdentity[]; + SourceMessageId: string; + MPID: string; + EventAttributes?: { + [key: string]: string; + }; + SDKVersion: string; + SessionId: string; + SessionStartDate: number; + SessionLength?: number; + currentSessionMPIDs?: string[]; + Timestamp: number; + EventDataType: number; + Debug: boolean; + Location?: SDKGeoLocation; + OptOut?: boolean; + CustomFlags?: { + [key: string]: string; + }; + AppVersion?: string; + AppName?: string; + Package?: string; + ConsentState?: SDKConsentState; + IntegrationAttributes?: { + [key: string]: { + [key: string]: string; + }; + }; + ProductAction?: SDKProductAction; + PromotionAction?: SDKPromotionAction; + ProductImpressions?: SDKProductImpression[]; + ShoppingCart?: SDKShoppingCart; + UserIdentityChanges?: SDKUserIdentityChangeData; + UserAttributeChanges?: SDKUserAttributeChangeData; + CurrencyCode: string; + DataPlan?: SDKDataPlan; + LaunchReferral?: string; +} +export interface SDKGeoLocation { + lat: number | string; + lng: number | string; +} +export interface SDKDataPlan { + PlanVersion?: number | null; + PlanId?: string | null; +} +export interface SDKUserIdentity { + Identity?: string; + Type: number; +} +export interface SDKShoppingCart { + ProductList?: SDKProduct[]; +} +export interface SDKPromotionAction { + PromotionActionType: string; + PromotionList?: SDKPromotion[]; +} +export interface SDKPromotion { + Id?: string; + Name?: string; + Creative?: string; + Position?: string; +} +export interface SDKProductImpression { + ProductImpressionList?: string; + ProductList?: SDKProduct[]; +} +export declare enum SDKProductActionType { + Unknown = 0, + AddToCart = 1, + RemoveFromCart = 2, + Checkout = 3, + CheckoutOption = 4, + Click = 5, + ViewDetail = 6, + Purchase = 7, + Refund = 8, + AddToWishlist = 9, + RemoveFromWishlist = 10 +} +export interface SDKProductAction { + ProductActionType: SDKProductActionType; + CheckoutStep?: number; + CheckoutOptions?: string; + ProductList?: SDKProduct[]; + TransactionId?: string; + Affiliation?: string; + CouponCode?: string; + TotalAmount?: number; + ShippingAmount?: number; + TaxAmount?: number; +} +export interface SDKProduct { + Sku?: string; + Name?: string; + Price?: number; + Quantity?: number; + Brand?: string; + Variant?: string; + Category?: string; + Position?: number; + CouponCode?: string; + TotalAmount?: number; + Attributes?: { + [key: string]: string; + }; +} +export interface MParticleWebSDK { + addForwarder(mockForwarder: any): any; + Identity: SDKIdentityApi; + Logger: SDKLoggerApi; + _Store: SDKStoreApi; + _Helpers: SDKHelpersApi; + config: SDKConfig; + _resetForTests(MPConfig: SDKConfig): void; + init(apiKey: string, config: SDKConfig): void; + getInstance(): any; + ServerModel(): any; + upload(): any; + setPosition(lat: number | string, lng: number | string): void; + logEvent(eventName: string, eventType?: number, attrs?: { + [key: string]: string; + }): void; + logBaseEvent(event: any): void; + eCommerce: any; + logLevel: string; + ProductActionType: SDKProductActionType; + generateHash(value: string): any; +} +export interface SDKConfig { + isDevelopmentMode?: boolean; + logger: { + error?(msg: any): any; + warning?(msg: any): any; + verbose?(msg: any): any; + }; + onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; + dataPlan: DataPlanConfig; + appVersion?: string; + package?: string; + flags?: { + [key: string]: string | number; + }; + kitConfigs: any; + appName?: string; + logLevel?: string; + sessionTimeout?: number; + useCookieStorage?: boolean; + cookieDomain?: string; + workspaceToken: string; + requiredWebviewBridgeName: string; + minWebviewBridgeVersion: number; + isIOS?: boolean; + identifyRequest: { + [key: string]: { + [key: string]: string; + }; + }; + identityCallback: (result: any) => void; + requestConfig: boolean; + dataPlanOptions: KitBlockerOptions; + dataPlanResult?: DataPlanResult; +} +export interface DataPlanConfig { + planId?: string; + planVersion?: number; + document?: DataPlanResult; +} +export interface SDKIdentityApi { + getCurrentUser(): any; + IdentityAPI: any; + identify: any; + login: any; + logout: any; + modify: any; +} +export interface SDKHelpersApi { + createServiceUrl(arg0: string, arg1: string): void; + parseNumber(value: number): any; + generateUniqueId(): any; + isObject(item: any): any; +} +export interface SDKLoggerApi { + error(arg0: string): void; + verbose(arg0: string): void; + warning(arg0: string): void; +} +export interface SDKStoreApi { + isFirstRun: boolean; + devToken: string; + SDKConfig: SDKConfigApi; + sessionId?: string; + deviceId?: string; +} +export interface SDKConfigApi { + v3SecureServiceUrl?: string; + isDevelopmentMode: boolean; + appVersion?: string; + onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; +} +export interface MParticleUser { + getMPID(): string; +} +export interface SDKConsentState { + getGDPRConsentState(): SDKGDPRConsentState; + getCCPAConsentState(): SDKCCPAConsentState; +} +export interface SDKGDPRConsentState { + [key: string]: SDKConsentStateData; +} +export interface SDKConsentStateData { + Consented: boolean; + Timestamp?: number; + ConsentDocument?: string; + Location?: string; + HardwareId?: string; +} +export interface SDKCCPAConsentState extends SDKConsentStateData { +} +export interface SDKUserIdentityChangeData { + New: Identity; + Old: Identity; +} +export interface Identity { + IdentityType: SDKIdentityTypeEnum; + Identity: string; + Timestamp: number; + CreatedThisBatch: boolean; +} +export interface SDKUserAttributeChangeData { + UserAttributeName: string; + New: string; + Old: string; + Deleted: boolean; + IsNewAttribute: boolean; +} +export interface BaseEvent { + messageType: number; + name: string; + eventType?: number; + data?: { + [key: string]: string; + }; + customFlags?: { + [key: string]: string; + }; +} +export interface KitBlockerOptions { + dataPlanVersion: DataPlanVersion; + blockUserAttributes: boolean; + blockEventAttributes: boolean; + blockEvents: boolean; + blockUserIdentities: boolean; +} +export interface KitBlockerDataPlan { + document: DataPlanResult; +} +export interface DataPlanResult { + dtpn?: { + vers: DataPlanVersion; + blok: { + ev: boolean; + ea: boolean; + ua: boolean; + id: boolean; + }; + }; + error_message?: string; +} +export declare enum SDKIdentityTypeEnum { + other = "other", + customerId = "customerid", + facebook = "facebook", + twitter = "twitter", + google = "google", + microsoft = "microsoft", + yahoo = "yahoo", + email = "email", + alias = "alias", + facebookCustomAudienceId = "facebookcustomaudienceid", + otherId2 = "other2", + otherId3 = "other3", + otherId4 = "other4", + otherId5 = "other5", + otherId6 = "other6", + otherId7 = "other7", + otherId8 = "other8", + otherId9 = "other9", + otherId10 = "other10", + mobileNumber = "mobile_number", + phoneNumber2 = "phone_number_2", + phoneNumber3 = "phone_number_3" +} diff --git a/dist/build/src/sdkToEventsApiConverter.d.ts b/dist/build/src/sdkToEventsApiConverter.d.ts new file mode 100644 index 000000000..08bf810a1 --- /dev/null +++ b/dist/build/src/sdkToEventsApiConverter.d.ts @@ -0,0 +1,33 @@ +import { SDKEvent, SDKConsentState, SDKGDPRConsentState, SDKGeoLocation, SDKCCPAConsentState, SDKProduct, SDKPromotion, SDKUserIdentity, SDKProductActionType, MParticleWebSDK, SDKIdentityTypeEnum } from './sdkRuntimeModels'; +import * as EventsApi from '@mparticle/event-models'; +export declare function convertEvents(mpid: string, sdkEvents: SDKEvent[], mpInstance: MParticleWebSDK): EventsApi.Batch | null; +export declare function convertConsentState(sdkConsentState?: SDKConsentState): EventsApi.ConsentState | null; +export declare function convertGdprConsentState(sdkGdprConsentState: SDKGDPRConsentState): { + [key: string]: EventsApi.GDPRConsentState | null; +}; +export declare function convertCcpaConsentState(sdkCcpaConsentState: SDKCCPAConsentState): { + data_sale_opt_out: EventsApi.CCPAConsentState; +}; +export declare function convertUserIdentities(sdkUserIdentities?: SDKUserIdentity[]): EventsApi.BatchUserIdentities | null; +export declare function convertEvent(sdkEvent: SDKEvent): EventsApi.BaseEvent | null; +export declare function convertProductActionType(actionType: SDKProductActionType): EventsApi.ProductActionActionEnum; +export declare function convertProductAction(sdkEvent: SDKEvent): EventsApi.ProductAction | null; +export declare function convertProducts(sdkProducts: SDKProduct[]): EventsApi.Product[] | null; +export declare function convertPromotionAction(sdkEvent: SDKEvent): EventsApi.PromotionAction | null; +export declare function convertPromotions(sdkPromotions: SDKPromotion[]): EventsApi.Promotion[] | null; +export declare function convertImpressions(sdkEvent: SDKEvent): EventsApi.ProductImpression[] | null; +export declare function convertShoppingCart(sdkEvent: SDKEvent): EventsApi.ShoppingCart | null; +export declare function convertCommerceEvent(sdkEvent: SDKEvent): EventsApi.CommerceEvent; +export declare function convertCrashReportEvent(sdkEvent: SDKEvent): EventsApi.CrashReportEvent; +export declare function convertAST(sdkEvent: SDKEvent): EventsApi.ApplicationStateTransitionEvent; +export declare function convertSessionEndEvent(sdkEvent: SDKEvent): EventsApi.SessionEndEvent; +export declare function convertSessionStartEvent(sdkEvent: SDKEvent): EventsApi.SessionStartEvent; +export declare function convertPageViewEvent(sdkEvent: SDKEvent): EventsApi.ScreenViewEvent; +export declare function convertOptOutEvent(sdkEvent: SDKEvent): EventsApi.OptOutEvent; +export declare function convertCustomEvent(sdkEvent: SDKEvent): EventsApi.CustomEvent; +export declare function convertSdkEventType(sdkEventType: number): EventsApi.CustomEventDataCustomEventTypeEnum | EventsApi.CommerceEventDataCustomEventTypeEnum; +export declare function convertBaseEventData(sdkEvent: SDKEvent): EventsApi.CommonEventData; +export declare function convertSDKLocation(sdkEventLocation: SDKGeoLocation): EventsApi.GeoLocation; +export declare function convertUserAttributeChangeEvent(sdkEvent: SDKEvent): EventsApi.UserAttributeChangeEvent | null; +export declare function convertUserIdentityChangeEvent(sdkEvent: SDKEvent): EventsApi.UserIdentityChangeEvent | null; +export declare function convertUserIdentityTypeToServerIdentityType(identityType: SDKIdentityTypeEnum): EventsApi.IdentityType; diff --git a/dist/build/src/utils.d.ts b/dist/build/src/utils.d.ts new file mode 100644 index 000000000..65e815275 --- /dev/null +++ b/dist/build/src/utils.d.ts @@ -0,0 +1,9 @@ +declare type valueof = T[keyof T]; +declare const inArray: (items: any[], name: string) => boolean; +declare const findKeyInObject: (obj: any, key: string) => string; +declare const isObject: (value: any) => boolean; +declare const parseNumber: (value: string | number) => number; +declare const returnConvertedBoolean: (data: string | boolean | number) => boolean; +declare const decoded: (s: string) => string; +declare const converted: (s: string) => string; +export { valueof, converted, decoded, findKeyInObject, inArray, isObject, parseNumber, returnConvertedBoolean, }; diff --git a/dist/build/src/validators.d.ts b/dist/build/src/validators.d.ts new file mode 100644 index 000000000..a597733a3 --- /dev/null +++ b/dist/build/src/validators.d.ts @@ -0,0 +1,17 @@ +import Constants from './constants'; +import { IdentityApiData } from '@mparticle/web-sdk'; +import { valueof } from './utils'; +declare type IdentityAPIMethod = 'login' | 'logout' | 'identify' | 'modify'; +declare type ValidationIdentitiesReturn = { + valid: boolean; + error?: valueof; +}; +declare const Validators: { + isValidAttributeValue: (value: any) => boolean; + isValidKeyValue: (key: any) => boolean; + isStringOrNumber: (value: any) => boolean; + isNumber: (value: any) => boolean; + isFunction: (fn: any) => boolean; + validateIdentities: (identityApiData: IdentityApiData, method?: IdentityAPIMethod) => ValidationIdentitiesReturn; +}; +export default Validators; diff --git a/dist/build/test/src/tests-batchUploader.d.ts b/dist/build/test/src/tests-batchUploader.d.ts new file mode 100644 index 000000000..91747f762 --- /dev/null +++ b/dist/build/test/src/tests-batchUploader.d.ts @@ -0,0 +1,7 @@ +import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; +declare global { + interface Window { + mParticle: MParticleWebSDK; + fetchMock: any; + } +} diff --git a/dist/build/test/src/tests-kit-blocking.d.ts b/dist/build/test/src/tests-kit-blocking.d.ts new file mode 100644 index 000000000..80f99eb44 --- /dev/null +++ b/dist/build/test/src/tests-kit-blocking.d.ts @@ -0,0 +1,7 @@ +import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; +declare global { + interface Window { + mParticle: MParticleWebSDK; + MockForwarder1: any; + } +} diff --git a/dist/build/test/src/tests-mockBatchCreator.d.ts b/dist/build/test/src/tests-mockBatchCreator.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/dist/build/test/src/tests-mockBatchCreator.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts b/dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts new file mode 100644 index 000000000..0bf9e0891 --- /dev/null +++ b/dist/build/test/src/tests-runtimeToBatchEventsDTO.d.ts @@ -0,0 +1,6 @@ +import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; +declare global { + interface Window { + mParticle: MParticleWebSDK; + } +} diff --git a/dist/build/test/src/tests-utils.d.ts b/dist/build/test/src/tests-utils.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/dist/build/test/src/tests-utils.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/build/test/src/tests-validators.d.ts b/dist/build/test/src/tests-validators.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/dist/build/test/src/tests-validators.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/mparticle.common.js b/dist/mparticle.common.js new file mode 100644 index 000000000..a15e079ae --- /dev/null +++ b/dist/mparticle.common.js @@ -0,0 +1,1721 @@ +if (typeof globalThis !== 'undefined') {globalThis.regeneratorRuntime = undefined} + +// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html +var Base64$1={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",// Input must be a string +encode:function(a){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(a)))}catch(a){console.error("Error encoding cookie values into Base64:"+a);}return this._encode(a)},_encode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=UTF8.encode(a);k>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),j=j+Base64$1._keyStr.charAt(e)+Base64$1._keyStr.charAt(f)+Base64$1._keyStr.charAt(g)+Base64$1._keyStr.charAt(h);return j},decode:function(a){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(a)))}catch(a){//log(e); +}return Base64$1._decode(a)},_decode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j+=String.fromCharCode(b),64!==g&&(j+=String.fromCharCode(c)),64!==h&&(j+=String.fromCharCode(d));return j=UTF8.decode(j),j}},UTF8={encode:function(a){for(var b,d="",e=0;eb?d+=String.fromCharCode(b):127b?(d+=String.fromCharCode(192|b>>6),d+=String.fromCharCode(128|63&b)):(d+=String.fromCharCode(224|b>>12),d+=String.fromCharCode(128|63&b>>6),d+=String.fromCharCode(128|63&b));return d},decode:function(a){for(var b="",d=0,e=0,f=0,g=0;de?(b+=String.fromCharCode(e),d++):191e?(f=a.charCodeAt(d+1),b+=String.fromCharCode((31&e)<<6|63&f),d+=2):(f=a.charCodeAt(d+1),g=a.charCodeAt(d+2),b+=String.fromCharCode((15&e)<<12|(63&f)<<6|63&g),d+=3);return b}};var Polyfill = {// forEach polyfill +// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +forEach:function forEach(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +var Messages$9=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return +?generateRandomValue()// if the placeholder was passed, return +:// [1e7] -> // 10000000 + +// -1e3 -> // -1000 + +// -4e3 -> // -4000 + +// -8e3 -> // -80000000 + +// -1e11 -> //-100000000000, +"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,// zeroes, ones, and eights with +generateUniqueId// random hex digits +)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d){var e=replaceAmpWithAmpersand(b),f=c?replaceAmpWithAmpersand(c):null,g=replaceMPID(e,a),h=f?replaceMPID(f,a):"",i=g+encodeURIComponent(h);if(d){var j=i.includes("?")?"&":"?";i+="".concat(j,"domain=").concat(d);}return i},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers +return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=e[a.toLowerCase()];b&&(d[a]=b);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie +var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys +// Parse cookies from document.cookie +// Filter cookies by keys if provided +return function filterCookies(a,b){for(var c={},d=0,e=a;db.length)return null;for(var d,e=c._IntegrationCapture,f=c._Helpers,g=f.getFeatureFlag,h=c.Identity.getCurrentUser(),i=[],j=null,k=0,l=b;k=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTimej.status)b.verbose("Upload success for request ID: ".concat(e[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later +return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads. +return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}(); + +var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$4=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache +if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back +var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$4||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so +// we sort the identities based on their enum. +// we create an array, set the user identity at the index of the user identity type +var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type +if(d){var f=[];// create an array where each index is equal to the user identity type +for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place +// before identify fires, so there may not be a cache. See what happens when +// the ? in idCache is removed to the following test +// "queued events contain login mpid instead of identify mpid when calling +// login immediately after mParticle initializes" +var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity +if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity +if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time. +// If the current time is greater than the expireTimestamp, it is not a valid +// cached identity. +var g=d[f].expireTimestamp;return !(ga._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$1.currentStorageName+"_"+a:StorageNames$1.currentStorageName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.parseStringOrNumber=parseStringOrNumber,this.generateHash=generateHash,this.generateUniqueId=generateUniqueId,this.Validators=Validators;} + +var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge +return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge +// TODO: what to do about people setting things on mParticle itself? +// android +},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName +},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var f,g,h=window[androidBridgeNameBase+"_"+e+"_v2"],i=iosBridgeNameBase+"_"+e+"_v2";return window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[i]&&(f=window.webkit.messageHandlers[i]),a.uiwebviewBridgeName===i&&(g=a[i]),h&&h.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void h[c](d)):void(f?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),f.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):g&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};} + +var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations +var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public +// Private +this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync +// dates. Skip cookie sync to avoid running it on every page load. +{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h=!1,j=e.filteringConsentRuleValues,k=e.pixelUrl,l=e.redirectUrl,m=e.moduleId,// Tells you how often we should do a cookie sync (in days) +n=e.frequencyCap,o=(j||{}).values;// set requiresConsent to false to start each additional pixel configuration +// set to true only if filteringConsenRuleValues.values.length exists +// Filtering rules as defined in UI +if(!isEmpty(k)&&(isEmpty(o)||(h=!0),!(h&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting()))// For Rokt, block cookie sync when noTargeting privacy flag is true +// If MPID is new to cookies, we should not try to perform the cookie sync +// because a cookie sync can only occur once a user either consents or doesn't. +// we should not check if it's enabled if the user has a blank consent +// The Trade Desk requires a URL parameter for GDPR enabled users. +// It is optional but to simplify the code, we add it for all Trade +// // Desk cookie syncs. +// Add domain parameter for Trade Desk +{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},r=q[m]||null;if(isLastSyncDateExpired(n,r)){var s=m===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,t=createCookieSyncUrl(c,k,l,s);b.performCookieSync(t,m.toString(),c,q);}}}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie +return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again +}; + +var Messages$6=Constants.Messages;function SessionManager(a){/** + * Checks if the session has expired based on the last event timestamp + * @param lastEventTimestamp - Unix timestamp in milliseconds of the last event + * @param sessionTimeout - Session timeout in minutes + * @returns true if the session has expired, false otherwise + */function b(a,b){if(!a||!b||0>=b)return !1;var c=Date.now()-a;return c>=6e4*b}/** + * Performs session end operations: + * - Logs a SessionEnd event + * - Nullifies the session ID and related data + * - Resets the time-on-site timer + */function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045 +// https://go.mparticle.com/work/SQDSDKS-6323 +var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab +if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};} + +var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// sanitizes any non number, non string value to 0 +this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801 +return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof$1(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0 +return a._Helpers.parseNumber(b)};} + +var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window +document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}(); + +function createSDKConfig(a){// TODO: Refactor to create a default config object +var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access +return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels +function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model +persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state +(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315 +var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g,h=a.workspaceToken,i=a.requiredWebviewBridgeName;a.flags&&(d.SDKConfig.flags=processFlags(a));var j=processBaseUrls(a,d.SDKConfig.flags,c);for(var k in j)d.SDKConfig[k]=j[k];if(h){d.SDKConfig.workspaceToken=h;var l=!0===(null===(g=null===a||void 0===a?void 0:a.launcherOptions)||void 0===g?void 0:g.noFunctional);b._timeOnSiteTimer=new ForegroundTimeTracker(h,l);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned +d.storageName=e(h),d.SDKConfig.requiredWebviewBridgeName=i||h,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317 +function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b):{};// https://go.mparticle.com/work/SQDSDKS-6317 +// Passed in config flags take priority over defaults +}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed +if(!c)return {};// Set default baseUrls +// When direct URL routing is false, update baseUrls based custom urls +// passed to the config +return b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a)}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c=Constants.CNAMEUrlPaths,d={};// newBaseUrls are default if the customer is not using a CNAME +// If a customer passes either config.domain or config.v3SecureServiceUrl, +// config.identityUrl, etc, the customer is using a CNAME. +// config.domain will take priority if a customer passes both. +// If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain. +// This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty +// if a customer is using a snippet prior to 2.6. +if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);return d}for(var f in b)d[f]=a[f]||b[f];return d}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that +// include the silo in the urls. mParticle API keys are prefixed with the +// silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo, +// and before other silos existed, there were no prefixes and all apiKeys +// were us1. As such, if we split on a '-' and the resulting array length +// is 1, then it is an older APIkey that should route to us1. +// When splitKey.length is greater than 1, then splitKey[0] will be +// us1, us2, eu1, au1, or st1, etc as new silos are added +for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct +// mapping to the silo. The most common use case is a customer provided CNAME. +if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} + +var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); + +var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 +// https://go.mparticle.com/work/SQDSDKS-6045 +// https://go.mparticle.com/work/SQDSDKS-5022 +// https://go.mparticle.com/work/SQDSDKS-6021 +// https://go.mparticle.com/work/SQDSDKS-5022 +// https://go.mparticle.com/work/SQDSDKS-6021 +/* This function determines if a cookie is greater than the configured maxCookieSize. + - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie. + - Once removed, check size, and repeat. + - Never remove the currentUser's MPID from the cookie. + + MPID removal priority: + 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie. + 2. If there are currentSessionMPIDs: + a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs + b. Then remove MPIDs based on order in currentSessionMPIDs array, which + stores MPIDs based on earliest login. +*/ // TODO: This should actually be decodePersistenceString or +// we should refactor this to take a string and return an object +// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible. +// For example subdomain.domain.co.uk would try the following combinations: +// "co.uk" -> fail +// "domain.co.uk" -> success, return +// "subdomain.domain.co.uk" -> skipped, because already found +// https://go.mparticle.com/work/SQDSDKS-6021 +/** + * set the "first seen" time for a user. the time will only be set once for a given + * mpid after which subsequent calls will be ignored + */ /** + * returns the "last seen" time for a user. If the mpid represents the current user, the + * return value will always be the current time, otherwise it will be to stored "last seen" + * time + */ // https://go.mparticle.com/work/SQDSDKS-6045 +// Forwarder Batching Code +this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var b,c,d=f.getLocalStorage(),e=f.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045 +// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle +// https://go.mparticle.com/work/SQDSDKS-6046 +// Stores all non-current user MPID information into the store +for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?a._Helpers.extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?a._Helpers.extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){var c;if(a._Store.isLocalStorageAvailable&&!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true +{var d=a._Store.storageName,e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(d),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;cf&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie +var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above +if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above +for(var n,o=0;of);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through +// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched +if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1= 0; --o) { + var i = this.tryEntries[o], + a = i.completion; + if ("root" === i.tryLoc) return handle("end"); + if (i.tryLoc <= this.prev) { + var c = n.call(i, "catchLoc"), + u = n.call(i, "finallyLoc"); + if (c && u) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } else if (c) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + } else { + if (!u) throw new Error("try statement without catch or finally"); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } + } + } + }, + abrupt: function abrupt(t, e) { + for (var r = this.tryEntries.length - 1; r >= 0; --r) { + var o = this.tryEntries[r]; + if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { + var i = o; + break; + } + } + i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); + var a = i ? i.completion : {}; + return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); + }, + complete: function complete(t, e) { + if ("throw" === t.type) throw t.arg; + return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; + }, + finish: function finish(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; + } + }, + "catch": function _catch(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.tryLoc === t) { + var n = r.completion; + if ("throw" === n.type) { + var o = n.arg; + resetTryEntry(r); + } + return o; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(e, r, n) { + return this.delegate = { + iterator: values(e), + resultName: r, + nextLoc: n + }, "next" === this.method && (this.arg = t), y; + } + }, e; + } + module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; +} (regeneratorRuntime$1)); + +var regeneratorRuntimeExports = regeneratorRuntime$1.exports; + +// TODO(Babel 8): Remove this file. + +var runtime = regeneratorRuntimeExports(); +var regenerator = runtime; + +// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } +} + +var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator); + +function filteredMparticleUser(a,b,c,d){var e=this;return {getUserIdentities:function getUserIdentities(){var e={},f=c._Store.getUserIdentities(a);for(var g in f)if(f.hasOwnProperty(g)){var h=Types.IdentityType.getIdentityName(c._Helpers.parseNumber(g));d&&(!d||d.isIdentityBlocked(h))||(//if identity type is not blocked +e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Store.getUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}} + +var _Constants$IdentityMe=Constants.IdentityMethods,Modify$2=_Constants$IdentityMe.Modify,Identify$1=_Constants$IdentityMe.Identify,Login$1=_Constants$IdentityMe.Login,Logout$1=_Constants$IdentityMe.Logout;function Forwarders(a,b){var c=this,d=this;this.forwarderStatsUploader=new APIClient(a,b).initializeForwarderStatsUploader();var e={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// TODO: https://go.mparticle.com/work/SQDSDKS-6036 +// Processing forwarders is a 2 step process: +// 1. Configure the kit +// 2. Initialize the kit +// There are 2 types of kits: +// 1. UI-enabled kits +// 2. Sideloaded kits. +// These are kits that are enabled via the mParticle UI. +// A kit that is UI-enabled will have a kit configuration that returns from +// the server, or in rare cases, is passed in by the developer. +// The kit configuration will be compared with the kit constructors to determine +// if there is a match before being initialized. +// Only kits that are configured properly can be active and used for kit forwarding. +// Unlike UI enabled kits, sideloaded kits are always added to active forwarders. +// TODO: Sideloading kits currently require the use of a register method +// which requires an object on which to be registered. +// In the future, when all kits are moved to the mpConfig rather than +// there being a separate process for MP configured kits and +// sideloaded kits, this will need to be refactored. +// kits can be included via mParticle UI, or via sideloaded kit config API +this.initForwarders=function(b,c){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!d.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!d.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=a._Helpers.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,c,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;var d,e,f;if(!c)return !1;f=c.getAllUserAttributes();var g=!1;try{if(f&&a._Helpers.isObject(f)&&Object.keys(f).length)for(var h in f)if(f.hasOwnProperty(h)&&(d=KitFilterHelper.hashAttributeConditionalForwarding(h),e=KitFilterHelper.hashAttributeConditionalForwarding(f[h]),d===b.userAttributeName&&e===b.userAttributeValue)){g=!0;break}return !b||b.includeOnMatch===g}catch(a){// in any error scenario, err on side of returning true and forwarding event +return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){var c,d,e,f=function(b,c){b.UserIdentities&&b.UserIdentities.length&&b.UserIdentities.forEach(function(d,e){a._Helpers.inArray(c,KitFilterHelper.hashUserIdentity(d.Type))&&(b.UserIdentities.splice(e,1),0e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate. +throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}(); + +var processReadyQueue=function(a){return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]};var processPreloadedItem=function(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it +if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(window.mParticle,b);else {var d=c.split(".");try{// Track both the function and its context +for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;hd?-1:1}),c},/** + * Initiate an alias request to the mParticle server + * @method aliasUsers + * @param {Object} aliasRequest object representing an AliasRequest + * @param {Function} [callback] A callback function that is called when the aliasUsers request completes + */aliasUsers:function aliasUsers(b,c){var d;if(b.destinationMpid&&b.sourceMpid||(d=Messages$2.ValidationMessages.AliasMissingMpid),b.destinationMpid===b.sourceMpid&&(d=Messages$2.ValidationMessages.AliasNonUniqueMpid),b.startTime&&b.endTime||(d=Messages$2.ValidationMessages.AliasMissingTime),b.startTime>b.endTime&&(d=Messages$2.ValidationMessages.AliasStartBeforeEndTime),d)return a.Logger.warning(d),void a._Helpers.invokeAliasCallback(c,HTTPCodes$2.validationIssue,d);if(!a._Helpers.canLog())a._Helpers.invokeAliasCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),a.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(a._Identity.IdentityRequest.convertAliasToNative(b))),a._Helpers.invokeAliasCallback(c,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {a.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+b.sourceMpid+" -> "+b.destinationMpid);var e=a._Identity.IdentityRequest.createAliasNetworkRequest(b);a._IdentityAPIClient.sendAliasRequest(e,c);}},/** + Create a default AliasRequest for 2 MParticleUsers. This will construct the request + using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime. + + In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only + be the case if they have not been the current user since this functionality was added, the + startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly, + if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time + + There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days. + If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime. + In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit, + after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() + validation that the startTime must be less than the endTime + */createAliasRequest:function createAliasRequest(b,c,d){try{if(!c||!b)return a.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var e=b.getFirstSeenTime();e||a.Identity.getUsers().forEach(function(a){a.getFirstSeenTime()&&(!e||a.getFirstSeenTime() + * Usage: const consent = mParticle.Consent.createConsentState() + *
+ * consent.setGDPRCoonsentState() + * + * @class Consent + */ /** + * Add a GDPR Consent State to the consent state object + * + * @method addGDPRConsentState + * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data + * @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...) + */function e(c,e){var f=d(c);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=b.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/** + * Remove a GDPR Consent State to the consent state object + * + * @method removeGDPRConsentState + * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data + */function g(a){var b=d(a);return b?(delete k[b],this):this}/** + * Gets the GDPR Consent State + * + * @method getGDPRConsentState + * @return {Object} A GDPR Consent State + */function h(){return Object.assign({},k)}/** + * Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out') + * + * @method setCCPAConsentState + * @param {Object} ccpaConsent CCPA Consent State + */function i(c){if(!isObject(c))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=b.createPrivacyConsent(c.Consented,c.Timestamp,c.ConsentDocument,c.Location,c.HardwareId);return d&&(l[CCPAPurpose]=d),this}/** + * Gets the CCPA Consent State + * + * @method getCCPAConsentStatensent + * @return {Object} A CCPA Consent State + */ /** + * Removes CCPA from the consent state object + * + * @method removeCCPAConsentState + */function j(){return delete l[CCPAPurpose],this}// TODO: Can we remove this? It is deprecated. +var k={},l={};if(c){var m=b.createConsentState();// TODO: Remove casting once `removeCCPAState` is removed; +return m.setGDPRConsentState(c.getGDPRConsentState()),m.setCCPAConsentState(c.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAState:function b(){// @ts-ignore +return a.Logger.warning("removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"),j()},removeCCPAConsentState:j}};} + +/* + TODO: Including this as a workaround because attempting to import it from + @mparticle/data-planning-models directly creates a build error. + */var DataPlanMatchType={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},KitBlocker=/** @class */function(){function a(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r=this;// if data plan is not requested, the data plan is {document: null} +if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,a&&!a.document)return void(this.kitBlockingEnabled=!1);this.kitBlockingEnabled=!0,this.mpInstance=b,this.blockEvents=null===(e=null===(d=null===(c=null===a||void 0===a?void 0:a.document)||void 0===c?void 0:c.dtpn)||void 0===d?void 0:d.blok)||void 0===e?void 0:e.ev,this.blockEventAttributes=null===(h=null===(g=null===(f=null===a||void 0===a?void 0:a.document)||void 0===f?void 0:f.dtpn)||void 0===g?void 0:g.blok)||void 0===h?void 0:h.ea,this.blockUserAttributes=null===(k=null===(j=null===(i=null===a||void 0===a?void 0:a.document)||void 0===i?void 0:i.dtpn)||void 0===j?void 0:j.blok)||void 0===k?void 0:k.ua,this.blockUserIdentities=null===(n=null===(m=null===(l=null===a||void 0===a?void 0:a.document)||void 0===l?void 0:l.dtpn)||void 0===m?void 0:m.blok)||void 0===n?void 0:n.id;var s=null===(q=null===(p=null===(o=null===a||void 0===a?void 0:a.document)||void 0===o?void 0:o.dtpn)||void 0===p?void 0:p.vers)||void 0===q?void 0:q.version_document,t=null===s||void 0===s?void 0:s.data_points;if(s)try{0<(null===t||void 0===t?void 0:t.length)&&t.forEach(function(a){return r.addToMatchLookups(a)});}catch(a){this.mpInstance.Logger.error("There was an issue with the data plan: "+a);}}return a.prototype.addToMatchLookups=function(a){var b,c,d;if(!a.match||!a.validator)return void this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(a));// match keys for non product custom attribute related data points +var e=this.generateMatchKey(a.match),f=this.getPlannedProperties(a.match.type,a.validator);this.dataPlanMatchLookups[e]=f,((null===(b=null===a||void 0===a?void 0:a.match)||void 0===b?void 0:b.type)===DataPlanMatchType.ProductImpression||(null===(c=null===a||void 0===a?void 0:a.match)||void 0===c?void 0:c.type)===DataPlanMatchType.ProductAction||(null===(d=null===a||void 0===a?void 0:a.match)||void 0===d?void 0:d.type)===DataPlanMatchType.PromotionAction)&&(e=this.generateProductAttributeMatchKey(a.match),f=this.getProductProperties(a.match.type,a.validator),this.dataPlanMatchLookups[e]=f);},a.prototype.generateMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.CustomEvent:var c=b;return [DataPlanMatchType.CustomEvent,c.custom_event_type,c.event_name].join(":");case DataPlanMatchType.ScreenView:return [DataPlanMatchType.ScreenView,"",b.screen_name].join(":");case DataPlanMatchType.ProductAction:return [a.type,b.action].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action].join(":");case DataPlanMatchType.ProductImpression:return [a.type,b.action].join(":");case DataPlanMatchType.UserIdentities:case DataPlanMatchType.UserAttributes:return [a.type].join(":");default:return null}},a.prototype.generateProductAttributeMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.ProductAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.ProductImpression:return [a.type,"ProductAttributes"].join(":");default:return null}},a.prototype.getPlannedProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l;switch(a){case DataPlanMatchType.CustomEvent:case DataPlanMatchType.ScreenView:case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction:case DataPlanMatchType.ProductImpression:if(k=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.custom_attributes,k){if(!0===k.additionalProperties||void 0===k.additionalProperties)return !0;for(var m,n={},o=0,p=Object.keys(k.properties);o=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} + +// The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: +// - version is always this prefix: fb +// - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2) +// - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value +// - is the value for the fbclid query parameter in the page URL. +// https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc +var facebookClickIdProcessor=function(a,b,c){if(!a||!b)return "";var d=null===b||void 0===b?void 0:b.split("//");if(!d)return "";var e=d[1].split("/"),f=e[0].split("."),g=1;// The rules for subdomainIndex are for parsing the domain portion +// of the URL for cookies, but in this case we are parsing the URL +// itself, so we can ignore the use of 0 for 'com' +3<=f.length&&(g=2);// If timestamp is not provided, use the current time +var h=c||Date.now();return "fb.".concat(g,".").concat(h,".").concat(a)};// Integration outputs are used to determine how click ids are used within the SDK +// CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject +// PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch +// INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created +var IntegrationOutputs={CUSTOM_FLAGS:"custom_flags",PARTNER_IDENTITIES:"partner_identities",INTEGRATION_ATTRIBUTES:"integration_attributes"},integrationMappingExternal={// Facebook / Meta +fbclid:{mappedKey:"Facebook.ClickId",processor:facebookClickIdProcessor,output:IntegrationOutputs.CUSTOM_FLAGS},_fbp:{mappedKey:"Facebook.BrowserId",output:IntegrationOutputs.CUSTOM_FLAGS},_fbc:{mappedKey:"Facebook.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Google +gclid:{mappedKey:"GoogleEnhancedConversions.Gclid",output:IntegrationOutputs.CUSTOM_FLAGS},gbraid:{mappedKey:"GoogleEnhancedConversions.Gbraid",output:IntegrationOutputs.CUSTOM_FLAGS},wbraid:{mappedKey:"GoogleEnhancedConversions.Wbraid",output:IntegrationOutputs.CUSTOM_FLAGS},// TIKTOK +ttclid:{mappedKey:"TikTok.Callback",output:IntegrationOutputs.CUSTOM_FLAGS},_ttp:{mappedKey:"tiktok_cookie_id",output:IntegrationOutputs.PARTNER_IDENTITIES},// Snapchat +// https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US +ScCid:{mappedKey:"SnapchatConversions.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Snapchat +// https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id +_scid:{mappedKey:"SnapchatConversions.Cookie1",output:IntegrationOutputs.CUSTOM_FLAGS}},integrationMappingRokt={// Rokt +// https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/ +// https://go.mparticle.com/work/SQDSDKS-7167 +rtid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},rclid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},RoktTransactionId:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277}},IntegrationCapture=/** @class */function(){function a(a){this.initialTimestamp=Date.now(),this.captureMode=a,this.filteredPartnerIdentityMappings=this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES),this.filteredCustomFlagMappings=this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS),this.filteredIntegrationAttributeMappings=this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);}/** + * Captures Integration Ids from cookies and query params and stores them in clickIds object + */return a.prototype.capture=function(){var a=this.captureQueryParams()||{},b=this.captureCookies()||{},c=this.captureLocalStorage()||{};a.fbclid&&b._fbc&&delete b._fbc;// ROKT Rules +// If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid +// If RoktTransactionId is present in both cookies and localStorage, +// prioritize localStorage +var d=a.rtid||a.rclid,e=c.RoktTransactionId,f=b.RoktTransactionId;d?(e&&delete c.RoktTransactionId,f&&delete b.RoktTransactionId):e&&f&&delete b.RoktTransactionId,this.clickIds=__assign(__assign(__assign(__assign({},this.clickIds),a),c),b);},a.prototype.captureCookies=function(){var a=this.getAllowedKeysForMode(),b=getCookies(a);return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.captureQueryParams=function(){var a=this.getQueryParams();return this.applyProcessors(a,getHref(),this.initialTimestamp)},a.prototype.captureLocalStorage=function(){for(var a=this.getAllowedKeysForMode(),b={},c=0,d=a;c": { +// "mappedKey": "clickIdValue" +// } +// } +// } +for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}(); + +// Rokt Web SDK via a Web Kit. +// The Rokt Manager should load before the Web Kit and stubs out many of the +// Rokt Web SDK functions with an internal message queue in case a Rokt function +// is requested before the Rokt Web Kit or SDK is finished loaded. +// Once the Rokt Kit is attached to the Rokt Manager, we can consider the +// Rokt Manager in a "ready" state and it can begin sending data to the kit. +// +// https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt +var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1;}/** + * Sets a callback to be invoked when RoktManager becomes ready + */return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g){var h,i,j=a||{},k=j.userAttributeFilters,l=j.settings,m=l||{},n=m.placementAttributesMapping,o=m.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(h=null===o||void 0===o?void 0:o.toLowerCase())&&void 0!==h?h:null,this.identityService=c,this.store=d,this.logger=e,this.captureTiming=g,null===(i=this.captureTiming)||void 0===i?void 0:i.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:k,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(n);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode +// It is set here and passed in to the createLauncher method in the Rokt Kit +// This is not to be confused for the `sandbox` flag in the selectPlacements attributes +// as that is independent of this setting, though they share the same name. +var p=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through +// to the Rokt Launcher. +this.launcherOptions=__assign({sandbox:p},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h;return __awaiter(this,void 0,void 0,function(){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A=this;return __generator(this,function(B){switch(B.label){case 0:// Queue if kit isn't ready OR if identity is in flight +if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];B.label=1;case 1:if(B.trys.push([1,6,,7]),i=a.attributes,j=(null===i||void 0===i?void 0:i.sandbox)||null,k=this.mapPlacementAttributes(i,this.placementAttributesMapping),null===(d=this.logger)||void 0===d?void 0:d.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(i,null,2))),this.currentUser=this.identityService.getCurrentUser(),l=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},m=l.email,n=k.email,o=void 0,p=void 0,q=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),q&&(o=l[this.mappedEmailShaIdentityType],p=k.emailsha256||k[this.mappedEmailShaIdentityType]||void 0),r=this.hasIdentityChanged(m,n),s=this.hasIdentityChanged(o,p),t={},r&&(t.email=n,n&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),s&&(t[this.mappedEmailShaIdentityType]=p,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(t))return [3/*break*/,5];B.label=2;case 2:return B.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){A.identityService.identify({userIdentities:__assign(__assign({},l),t)},function(){a();});})];case 3:return B.sent(),[3/*break*/,5];case 4:return u=B.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(u)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),v=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},this.setUserAttributes(k),w=__assign(__assign({},k),null===j?{}:{sandbox:j}),v.email&&!w.email&&(w.email=v.email),q&&(x=v[this.mappedEmailShaIdentityType],x&&!w.emailsha256&&!w[this.mappedEmailShaIdentityType]&&(w.emailsha256=x)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,y=__assign(__assign({},a),{attributes:w}),[2/*return*/,this.kit.selectPlacements(y)];case 6:return z=B.sent(),[2/*return*/,Promise.reject(z instanceof Error?z:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);fAll of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

+ *

In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.

+ *

This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().

+ *

If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:

+ * + * mParticle.init('apiKey', config, 'another_instance'); + * mParticle.getInstance('another_instance').logPageView(); + * + * + * @class mParticle & mParticleInstance + */function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption +this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization +// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization +// to it for it to be run after fetched +if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval +b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** + * Creates a CCPA Opt Out Consent State. + * + * @method createCCPAConsent + * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" + * @param {Number} timestamp Unix time (likely to be Date.now()) + * @param {String} consentDocument document version or experience that the user may have consented to + * @param {String} location location where the user gave consent + * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users + * @return {Object} CCPA Consent State + */createCCPAConsent:b._Consent.createPrivacyConsent,/** + * Creates a GDPR Consent State. + * + * @method createGDPRConsent + * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" + * @param {Number} timestamp Unix time (likely to be Date.now()) + * @param {String} consentDocument document version or experience that the user may have consented to + * @param {String} location location where the user gave consent + * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users + * @return {Object} GDPR Consent State + */createGDPRConsent:b._Consent.createPrivacyConsent,/** + * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states. + * + * @method createConsentState + * @return {Object} ConsentState object + */createConsentState:b._Consent.createConsentState},this.eCommerce={/** + * Invoke these methods on the mParticle.eCommerce.Cart object. + * Example: mParticle.eCommerce.Cart.add(...) + * @class mParticle.eCommerce.Cart + * @deprecated + */Cart:{/** + * Adds a product to the cart + * @method add + * @param {Object} product The product you want to add to the cart + * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. + * @deprecated + */add:function add(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** + * Removes a product from the cart + * @method remove + * @param {Object} product The product you want to add to the cart + * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. + * @deprecated + */remove:function remove(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** + * Clears the cart + * @method clear + * @deprecated + */clear:function clear(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));}},/** + * Sets the currency code + * @for mParticle.eCommerce + * @method setCurrencyCode + * @param {String} code The currency code + */setCurrencyCode:function setCurrencyCode(a){var c=queueIfNotInitialized(function(){b.eCommerce.setCurrencyCode(a);},b);return c?void 0:"string"==typeof a?void(b._SessionManager.resetSessionTimer(),b._Store.currencyCode=a):void b.Logger.error("Code must be a string")},/** + * Creates a product + * @for mParticle.eCommerce + * @method createProduct + * @param {String} name product name + * @param {String} sku product sku + * @param {Number} price product price + * @param {Number} [quantity] product quantity. If blank, defaults to 1. + * @param {String} [variant] product variant + * @param {String} [category] product category + * @param {String} [brand] product brand + * @param {Number} [position] product position + * @param {String} [coupon] product coupon + * @param {Object} [attributes] product attributes + */createProduct:function createProduct(a,c,d,e,f,g,h,i,j,k){return b._Ecommerce.createProduct(a,c,d,e,f,g,h,i,j,k)},/** + * Creates a promotion + * @for mParticle.eCommerce + * @method createPromotion + * @param {String} id a unique promotion id + * @param {String} [creative] promotion creative + * @param {String} [name] promotion name + * @param {Number} [position] promotion position + */createPromotion:function createPromotion(a,c,d,e){return b._Ecommerce.createPromotion(a,c,d,e)},/** + * Creates a product impression + * @for mParticle.eCommerce + * @method createImpression + * @param {String} name impression name + * @param {Object} product the product for which an impression is being created + */createImpression:function createImpression(a,c){return b._Ecommerce.createImpression(a,c)},/** + * Creates a transaction attributes object to be used with a checkout + * @for mParticle.eCommerce + * @method createTransactionAttributes + * @param {String or Number} id a unique transaction id + * @param {String} [affiliation] affilliation + * @param {String} [couponCode] the coupon code for which you are creating transaction attributes + * @param {Number} [revenue] total revenue for the product being purchased + * @param {String} [shipping] the shipping method + * @param {Number} [tax] the tax amount + */createTransactionAttributes:function createTransactionAttributes(a,c,d,e,f,g){return b._Ecommerce.createTransactionAttributes(a,c,d,e,f,g)},/** + * Logs a checkout action + * @for mParticle.eCommerce + * @method logCheckout + * @param {Number} step checkout step number + * @param {String} checkout option string + * @param {Object} attrs + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */logCheckout:function logCheckout(a,c,d,e){return b.Logger.warning("mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logCheckoutEvent(a,c,d,e)):void b.ready(function(){b.eCommerce.logCheckout(a,c,d,e);})},/** + * Logs a product action + * @for mParticle.eCommerce + * @method logProductAction + * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218) + * @param {Object} product the product for which you are creating the product action + * @param {Object} [attrs] attributes related to the product action + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [transactionAttributes] Transaction Attributes for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */logProductAction:function logProductAction(a,c,d,e,f,g){var h=queueIfNotInitialized(function(){b.eCommerce.logProductAction(a,c,d,e,f,g);},b);h||(b._SessionManager.resetSessionTimer(),b._Events.logProductActionEvent(a,c,d,e,f,g));},/** + * Logs a product purchase + * @for mParticle.eCommerce + * @method logPurchase + * @param {Object} transactionAttributes transactionAttributes object + * @param {Object} product the product being purchased + * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false + * @param {Object} [attrs] other attributes related to the product purchase + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */logPurchase:function logPurchase(a,c,d,e,f){return b.Logger.warning("mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?a&&c?void(b._SessionManager.resetSessionTimer(),b._Events.logPurchaseEvent(a,c,e,f)):void b.Logger.error(Messages.ErrorMessages.BadLogPurchase):void b.ready(function(){b.eCommerce.logPurchase(a,c,d,e,f);})},/** + * Logs a product promotion + * @for mParticle.eCommerce + * @method logPromotion + * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279) + * @param {Object} promotion promotion object + * @param {Object} [attrs] boolean to clear the cart after logging or not + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */logPromotion:function logPromotion(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.eCommerce.logPromotion(a,c,d,e,f);},b);g||(b._SessionManager.resetSessionTimer(),b._Events.logPromotionEvent(a,c,d,e,f));},/** + * Logs a product impression + * @for mParticle.eCommerce + * @method logImpression + * @param {Object} impression product impression object + * @param {Object} attrs attributes related to the impression log + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */logImpression:function logImpression(a,c,d,e){var f=queueIfNotInitialized(function(){b.eCommerce.logImpression(a,c,d,e);},b);f||(b._SessionManager.resetSessionTimer(),b._Events.logImpressionEvent(a,c,d,e));},/** + * Logs a refund + * @for mParticle.eCommerce + * @method logRefund + * @param {Object} transactionAttributes transaction attributes related to the refund + * @param {Object} product product being refunded + * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false. + * @param {Object} [attrs] attributes related to the refund + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie +// And logs to in-memory object +// Example: mParticle.setSessionAttribute('location', '33431'); +if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed +if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any +// other integration delays set to true. It not, process the queued events/. +var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment +function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's +// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not +// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize +// persistence or Identity directly. +if(c._APIClient=new APIClient(c,f),c._Forwarders=new Forwarders(c,f),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use +var h=c.Identity.getCurrentUser(),i=h?h.getMPID():null,j=h?h.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:j}:c._Store.SDKConfig.identifyRequest,g(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639 +var k=g(CaptureIntegrationSpecificIds),l=g(CaptureIntegrationSpecificIdsV2),m=l&&l!==CaptureIntegrationSpecificIdsV2Modes.None||!0===k;if(m){var n;k||l===CaptureIntegrationSpecificIdsV2Modes.All?n="all":l===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(n="roktonly"),c._IntegrationCapture=new IntegrationCapture(n),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user +var o=parseConfig(b,"Rokt",181);if(o){var p=null===(d=o.settings)||void 0===d?void 0:d.accountId;c._Store.setRoktAccountId(p);var q=o.userAttributeFilters,r=filteredMparticleUser(i,{userAttributeFilters:q},c),s={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339 +c._RoktManager.init(o,r,c.Identity,c._Store,c.Logger,s,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,h,i,j);}// We will continue to clear out the ready queue as part of the initial init flow +// if an identify request is unnecessary, such as if there is an existing session +(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),null===(e=c.processQueueOnNoFunctional)||void 0===e?void 0:e.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061 +function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK: + 1. Manually via config.dataPlanOptions (this takes priority) + If not passed in manually, we user the server provided via either + 2. Snippet via /mparticle.js endpoint (config.dataPlan.document) + 3. Self hosting via /config endpoint (config.dataPlanResult) + */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault +// ensures no identity response data is written to localStorage when noFunctional is true +return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions +var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs +// since we will need this for the current implementation of user persistence +// TODO: Refactor this when we refactor User Identity Persistence +try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never +// receive an MPID. Let these calls through so events can still reach forwarders immediately. +// sendEventToServer handles queuing for the MP server upload path separately. +return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)} + +// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise! +var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method +_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:mockFunction},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}(); + +var MPSideloadedKit=/** @class */function(){function a(a){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],// The below filtering members are optional, but we instantiate them +// to simplify public method assignment +filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=a;}return a.prototype.addEventTypeFilter=function(a){var b=KitFilterHelper.hashEventType(a);this.filterDictionary.eventTypeFilters.push(b);},a.prototype.addEventNameFilter=function(a,b){var c=KitFilterHelper.hashEventName(b,a);this.filterDictionary.eventNameFilters.push(c);},a.prototype.addEventAttributeFilter=function(a,b,c){var d=KitFilterHelper.hashEventAttributeKey(a,b,c);this.filterDictionary.attributeFilters.push(d);},a.prototype.addScreenNameFilter=function(a){var b=KitFilterHelper.hashEventName(a,EventType.Unknown);this.filterDictionary.screenNameFilters.push(b);},a.prototype.addScreenAttributeFilter=function(a,b){var c=KitFilterHelper.hashEventAttributeKey(EventType.Unknown,a,b);this.filterDictionary.screenAttributeFilters.push(c);},a.prototype.addUserIdentityFilter=function(a){var b=KitFilterHelper.hashUserIdentity(a);this.filterDictionary.userIdentityFilters.push(b);},a.prototype.addUserAttributeFilter=function(a){var b=KitFilterHelper.hashUserAttribute(a);this.filterDictionary.userAttributeFilters.push(b);},a}(); + +Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticleInstanceManager(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing +/** + * Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used. + *

+ * If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below. + * @method init + * @param {String} apiKey your mParticle assigned API key + * @param {Object} [config] an options object for additional configuration + * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. + */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); + +module.exports = mParticleManager; diff --git a/dist/mparticle.esm.js b/dist/mparticle.esm.js new file mode 100644 index 000000000..75a493c69 --- /dev/null +++ b/dist/mparticle.esm.js @@ -0,0 +1,1721 @@ +if (typeof globalThis !== 'undefined') {globalThis.regeneratorRuntime = undefined} + +// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html +var Base64$1={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",// Input must be a string +encode:function(a){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(a)))}catch(a){console.error("Error encoding cookie values into Base64:"+a);}return this._encode(a)},_encode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=UTF8.encode(a);k>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),j=j+Base64$1._keyStr.charAt(e)+Base64$1._keyStr.charAt(f)+Base64$1._keyStr.charAt(g)+Base64$1._keyStr.charAt(h);return j},decode:function(a){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(a)))}catch(a){//log(e); +}return Base64$1._decode(a)},_decode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j+=String.fromCharCode(b),64!==g&&(j+=String.fromCharCode(c)),64!==h&&(j+=String.fromCharCode(d));return j=UTF8.decode(j),j}},UTF8={encode:function(a){for(var b,d="",e=0;eb?d+=String.fromCharCode(b):127b?(d+=String.fromCharCode(192|b>>6),d+=String.fromCharCode(128|63&b)):(d+=String.fromCharCode(224|b>>12),d+=String.fromCharCode(128|63&b>>6),d+=String.fromCharCode(128|63&b));return d},decode:function(a){for(var b="",d=0,e=0,f=0,g=0;de?(b+=String.fromCharCode(e),d++):191e?(f=a.charCodeAt(d+1),b+=String.fromCharCode((31&e)<<6|63&f),d+=2):(f=a.charCodeAt(d+1),g=a.charCodeAt(d+2),b+=String.fromCharCode((15&e)<<12|(63&f)<<6|63&g),d+=3);return b}};var Polyfill = {// forEach polyfill +// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +forEach:function forEach(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +var Messages$9=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return +?generateRandomValue()// if the placeholder was passed, return +:// [1e7] -> // 10000000 + +// -1e3 -> // -1000 + +// -4e3 -> // -4000 + +// -8e3 -> // -80000000 + +// -1e11 -> //-100000000000, +"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,// zeroes, ones, and eights with +generateUniqueId// random hex digits +)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d){var e=replaceAmpWithAmpersand(b),f=c?replaceAmpWithAmpersand(c):null,g=replaceMPID(e,a),h=f?replaceMPID(f,a):"",i=g+encodeURIComponent(h);if(d){var j=i.includes("?")?"&":"?";i+="".concat(j,"domain=").concat(d);}return i},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers +return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=e[a.toLowerCase()];b&&(d[a]=b);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie +var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys +// Parse cookies from document.cookie +// Filter cookies by keys if provided +return function filterCookies(a,b){for(var c={},d=0,e=a;db.length)return null;for(var d,e=c._IntegrationCapture,f=c._Helpers,g=f.getFeatureFlag,h=c.Identity.getCurrentUser(),i=[],j=null,k=0,l=b;k=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTimej.status)b.verbose("Upload success for request ID: ".concat(e[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later +return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads. +return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}(); + +var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$4=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache +if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back +var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$4||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so +// we sort the identities based on their enum. +// we create an array, set the user identity at the index of the user identity type +var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type +if(d){var f=[];// create an array where each index is equal to the user identity type +for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place +// before identify fires, so there may not be a cache. See what happens when +// the ? in idCache is removed to the following test +// "queued events contain login mpid instead of identify mpid when calling +// login immediately after mParticle initializes" +var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity +if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity +if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time. +// If the current time is greater than the expireTimestamp, it is not a valid +// cached identity. +var g=d[f].expireTimestamp;return !(ga._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$1.currentStorageName+"_"+a:StorageNames$1.currentStorageName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.parseStringOrNumber=parseStringOrNumber,this.generateHash=generateHash,this.generateUniqueId=generateUniqueId,this.Validators=Validators;} + +var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge +return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge +// TODO: what to do about people setting things on mParticle itself? +// android +},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName +},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var f,g,h=window[androidBridgeNameBase+"_"+e+"_v2"],i=iosBridgeNameBase+"_"+e+"_v2";return window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[i]&&(f=window.webkit.messageHandlers[i]),a.uiwebviewBridgeName===i&&(g=a[i]),h&&h.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void h[c](d)):void(f?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),f.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):g&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};} + +var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations +var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public +// Private +this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync +// dates. Skip cookie sync to avoid running it on every page load. +{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h=!1,j=e.filteringConsentRuleValues,k=e.pixelUrl,l=e.redirectUrl,m=e.moduleId,// Tells you how often we should do a cookie sync (in days) +n=e.frequencyCap,o=(j||{}).values;// set requiresConsent to false to start each additional pixel configuration +// set to true only if filteringConsenRuleValues.values.length exists +// Filtering rules as defined in UI +if(!isEmpty(k)&&(isEmpty(o)||(h=!0),!(h&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting()))// For Rokt, block cookie sync when noTargeting privacy flag is true +// If MPID is new to cookies, we should not try to perform the cookie sync +// because a cookie sync can only occur once a user either consents or doesn't. +// we should not check if it's enabled if the user has a blank consent +// The Trade Desk requires a URL parameter for GDPR enabled users. +// It is optional but to simplify the code, we add it for all Trade +// // Desk cookie syncs. +// Add domain parameter for Trade Desk +{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},r=q[m]||null;if(isLastSyncDateExpired(n,r)){var s=m===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,t=createCookieSyncUrl(c,k,l,s);b.performCookieSync(t,m.toString(),c,q);}}}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie +return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again +}; + +var Messages$6=Constants.Messages;function SessionManager(a){/** + * Checks if the session has expired based on the last event timestamp + * @param lastEventTimestamp - Unix timestamp in milliseconds of the last event + * @param sessionTimeout - Session timeout in minutes + * @returns true if the session has expired, false otherwise + */function b(a,b){if(!a||!b||0>=b)return !1;var c=Date.now()-a;return c>=6e4*b}/** + * Performs session end operations: + * - Logs a SessionEnd event + * - Nullifies the session ID and related data + * - Resets the time-on-site timer + */function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045 +// https://go.mparticle.com/work/SQDSDKS-6323 +var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab +if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};} + +var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// https://go.mparticle.com/work/SQDSDKS-4801 +// sanitizes any non number, non string value to 0 +this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801 +return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof$1(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0 +return a._Helpers.parseNumber(b)};} + +var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window +document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}(); + +function createSDKConfig(a){// TODO: Refactor to create a default config object +var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access +return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels +function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model +persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state +(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315 +var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g,h=a.workspaceToken,i=a.requiredWebviewBridgeName;a.flags&&(d.SDKConfig.flags=processFlags(a));var j=processBaseUrls(a,d.SDKConfig.flags,c);for(var k in j)d.SDKConfig[k]=j[k];if(h){d.SDKConfig.workspaceToken=h;var l=!0===(null===(g=null===a||void 0===a?void 0:a.launcherOptions)||void 0===g?void 0:g.noFunctional);b._timeOnSiteTimer=new ForegroundTimeTracker(h,l);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned +d.storageName=e(h),d.SDKConfig.requiredWebviewBridgeName=i||h,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317 +function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b):{};// https://go.mparticle.com/work/SQDSDKS-6317 +// Passed in config flags take priority over defaults +}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed +if(!c)return {};// Set default baseUrls +// When direct URL routing is false, update baseUrls based custom urls +// passed to the config +return b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a)}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c=Constants.CNAMEUrlPaths,d={};// newBaseUrls are default if the customer is not using a CNAME +// If a customer passes either config.domain or config.v3SecureServiceUrl, +// config.identityUrl, etc, the customer is using a CNAME. +// config.domain will take priority if a customer passes both. +// If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain. +// This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty +// if a customer is using a snippet prior to 2.6. +if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);return d}for(var f in b)d[f]=a[f]||b[f];return d}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that +// include the silo in the urls. mParticle API keys are prefixed with the +// silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo, +// and before other silos existed, there were no prefixes and all apiKeys +// were us1. As such, if we split on a '-' and the resulting array length +// is 1, then it is an older APIkey that should route to us1. +// When splitKey.length is greater than 1, then splitKey[0] will be +// us1, us2, eu1, au1, or st1, etc as new silos are added +for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct +// mapping to the silo. The most common use case is a customer provided CNAME. +if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} + +var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); + +var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 +// https://go.mparticle.com/work/SQDSDKS-6045 +// https://go.mparticle.com/work/SQDSDKS-5022 +// https://go.mparticle.com/work/SQDSDKS-6021 +// https://go.mparticle.com/work/SQDSDKS-5022 +// https://go.mparticle.com/work/SQDSDKS-6021 +/* This function determines if a cookie is greater than the configured maxCookieSize. + - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie. + - Once removed, check size, and repeat. + - Never remove the currentUser's MPID from the cookie. + + MPID removal priority: + 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie. + 2. If there are currentSessionMPIDs: + a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs + b. Then remove MPIDs based on order in currentSessionMPIDs array, which + stores MPIDs based on earliest login. +*/ // TODO: This should actually be decodePersistenceString or +// we should refactor this to take a string and return an object +// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible. +// For example subdomain.domain.co.uk would try the following combinations: +// "co.uk" -> fail +// "domain.co.uk" -> success, return +// "subdomain.domain.co.uk" -> skipped, because already found +// https://go.mparticle.com/work/SQDSDKS-6021 +/** + * set the "first seen" time for a user. the time will only be set once for a given + * mpid after which subsequent calls will be ignored + */ /** + * returns the "last seen" time for a user. If the mpid represents the current user, the + * return value will always be the current time, otherwise it will be to stored "last seen" + * time + */ // https://go.mparticle.com/work/SQDSDKS-6045 +// Forwarder Batching Code +this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var b,c,d=f.getLocalStorage(),e=f.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045 +// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle +// https://go.mparticle.com/work/SQDSDKS-6046 +// Stores all non-current user MPID information into the store +for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?a._Helpers.extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?a._Helpers.extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){var c;if(a._Store.isLocalStorageAvailable&&!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true +{var d=a._Store.storageName,e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(d),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;cf&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie +var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above +if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above +for(var n,o=0;of);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through +// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched +if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1= 0; --o) { + var i = this.tryEntries[o], + a = i.completion; + if ("root" === i.tryLoc) return handle("end"); + if (i.tryLoc <= this.prev) { + var c = n.call(i, "catchLoc"), + u = n.call(i, "finallyLoc"); + if (c && u) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } else if (c) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + } else { + if (!u) throw new Error("try statement without catch or finally"); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } + } + } + }, + abrupt: function abrupt(t, e) { + for (var r = this.tryEntries.length - 1; r >= 0; --r) { + var o = this.tryEntries[r]; + if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { + var i = o; + break; + } + } + i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); + var a = i ? i.completion : {}; + return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); + }, + complete: function complete(t, e) { + if ("throw" === t.type) throw t.arg; + return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; + }, + finish: function finish(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; + } + }, + "catch": function _catch(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.tryLoc === t) { + var n = r.completion; + if ("throw" === n.type) { + var o = n.arg; + resetTryEntry(r); + } + return o; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(e, r, n) { + return this.delegate = { + iterator: values(e), + resultName: r, + nextLoc: n + }, "next" === this.method && (this.arg = t), y; + } + }, e; + } + module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; +} (regeneratorRuntime$1)); + +var regeneratorRuntimeExports = regeneratorRuntime$1.exports; + +// TODO(Babel 8): Remove this file. + +var runtime = regeneratorRuntimeExports(); +var regenerator = runtime; + +// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } +} + +var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator); + +function filteredMparticleUser(a,b,c,d){var e=this;return {getUserIdentities:function getUserIdentities(){var e={},f=c._Store.getUserIdentities(a);for(var g in f)if(f.hasOwnProperty(g)){var h=Types.IdentityType.getIdentityName(c._Helpers.parseNumber(g));d&&(!d||d.isIdentityBlocked(h))||(//if identity type is not blocked +e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Store.getUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}} + +var _Constants$IdentityMe=Constants.IdentityMethods,Modify$2=_Constants$IdentityMe.Modify,Identify$1=_Constants$IdentityMe.Identify,Login$1=_Constants$IdentityMe.Login,Logout$1=_Constants$IdentityMe.Logout;function Forwarders(a,b){var c=this,d=this;this.forwarderStatsUploader=new APIClient(a,b).initializeForwarderStatsUploader();var e={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// TODO: https://go.mparticle.com/work/SQDSDKS-6036 +// Processing forwarders is a 2 step process: +// 1. Configure the kit +// 2. Initialize the kit +// There are 2 types of kits: +// 1. UI-enabled kits +// 2. Sideloaded kits. +// These are kits that are enabled via the mParticle UI. +// A kit that is UI-enabled will have a kit configuration that returns from +// the server, or in rare cases, is passed in by the developer. +// The kit configuration will be compared with the kit constructors to determine +// if there is a match before being initialized. +// Only kits that are configured properly can be active and used for kit forwarding. +// Unlike UI enabled kits, sideloaded kits are always added to active forwarders. +// TODO: Sideloading kits currently require the use of a register method +// which requires an object on which to be registered. +// In the future, when all kits are moved to the mpConfig rather than +// there being a separate process for MP configured kits and +// sideloaded kits, this will need to be refactored. +// kits can be included via mParticle UI, or via sideloaded kit config API +this.initForwarders=function(b,c){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!d.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!d.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=a._Helpers.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,c,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;var d,e,f;if(!c)return !1;f=c.getAllUserAttributes();var g=!1;try{if(f&&a._Helpers.isObject(f)&&Object.keys(f).length)for(var h in f)if(f.hasOwnProperty(h)&&(d=KitFilterHelper.hashAttributeConditionalForwarding(h),e=KitFilterHelper.hashAttributeConditionalForwarding(f[h]),d===b.userAttributeName&&e===b.userAttributeValue)){g=!0;break}return !b||b.includeOnMatch===g}catch(a){// in any error scenario, err on side of returning true and forwarding event +return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){var c,d,e,f=function(b,c){b.UserIdentities&&b.UserIdentities.length&&b.UserIdentities.forEach(function(d,e){a._Helpers.inArray(c,KitFilterHelper.hashUserIdentity(d.Type))&&(b.UserIdentities.splice(e,1),0e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate. +throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}(); + +var processReadyQueue=function(a){return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]};var processPreloadedItem=function(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it +if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(window.mParticle,b);else {var d=c.split(".");try{// Track both the function and its context +for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;hd?-1:1}),c},/** + * Initiate an alias request to the mParticle server + * @method aliasUsers + * @param {Object} aliasRequest object representing an AliasRequest + * @param {Function} [callback] A callback function that is called when the aliasUsers request completes + */aliasUsers:function aliasUsers(b,c){var d;if(b.destinationMpid&&b.sourceMpid||(d=Messages$2.ValidationMessages.AliasMissingMpid),b.destinationMpid===b.sourceMpid&&(d=Messages$2.ValidationMessages.AliasNonUniqueMpid),b.startTime&&b.endTime||(d=Messages$2.ValidationMessages.AliasMissingTime),b.startTime>b.endTime&&(d=Messages$2.ValidationMessages.AliasStartBeforeEndTime),d)return a.Logger.warning(d),void a._Helpers.invokeAliasCallback(c,HTTPCodes$2.validationIssue,d);if(!a._Helpers.canLog())a._Helpers.invokeAliasCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),a.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(a._Identity.IdentityRequest.convertAliasToNative(b))),a._Helpers.invokeAliasCallback(c,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {a.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+b.sourceMpid+" -> "+b.destinationMpid);var e=a._Identity.IdentityRequest.createAliasNetworkRequest(b);a._IdentityAPIClient.sendAliasRequest(e,c);}},/** + Create a default AliasRequest for 2 MParticleUsers. This will construct the request + using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime. + + In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only + be the case if they have not been the current user since this functionality was added, the + startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly, + if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time + + There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days. + If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime. + In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit, + after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() + validation that the startTime must be less than the endTime + */createAliasRequest:function createAliasRequest(b,c,d){try{if(!c||!b)return a.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var e=b.getFirstSeenTime();e||a.Identity.getUsers().forEach(function(a){a.getFirstSeenTime()&&(!e||a.getFirstSeenTime() + * Usage: const consent = mParticle.Consent.createConsentState() + *
+ * consent.setGDPRCoonsentState() + * + * @class Consent + */ /** + * Add a GDPR Consent State to the consent state object + * + * @method addGDPRConsentState + * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data + * @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...) + */function e(c,e){var f=d(c);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=b.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/** + * Remove a GDPR Consent State to the consent state object + * + * @method removeGDPRConsentState + * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data + */function g(a){var b=d(a);return b?(delete k[b],this):this}/** + * Gets the GDPR Consent State + * + * @method getGDPRConsentState + * @return {Object} A GDPR Consent State + */function h(){return Object.assign({},k)}/** + * Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out') + * + * @method setCCPAConsentState + * @param {Object} ccpaConsent CCPA Consent State + */function i(c){if(!isObject(c))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=b.createPrivacyConsent(c.Consented,c.Timestamp,c.ConsentDocument,c.Location,c.HardwareId);return d&&(l[CCPAPurpose]=d),this}/** + * Gets the CCPA Consent State + * + * @method getCCPAConsentStatensent + * @return {Object} A CCPA Consent State + */ /** + * Removes CCPA from the consent state object + * + * @method removeCCPAConsentState + */function j(){return delete l[CCPAPurpose],this}// TODO: Can we remove this? It is deprecated. +var k={},l={};if(c){var m=b.createConsentState();// TODO: Remove casting once `removeCCPAState` is removed; +return m.setGDPRConsentState(c.getGDPRConsentState()),m.setCCPAConsentState(c.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAState:function b(){// @ts-ignore +return a.Logger.warning("removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"),j()},removeCCPAConsentState:j}};} + +/* + TODO: Including this as a workaround because attempting to import it from + @mparticle/data-planning-models directly creates a build error. + */var DataPlanMatchType={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},KitBlocker=/** @class */function(){function a(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r=this;// if data plan is not requested, the data plan is {document: null} +if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,a&&!a.document)return void(this.kitBlockingEnabled=!1);this.kitBlockingEnabled=!0,this.mpInstance=b,this.blockEvents=null===(e=null===(d=null===(c=null===a||void 0===a?void 0:a.document)||void 0===c?void 0:c.dtpn)||void 0===d?void 0:d.blok)||void 0===e?void 0:e.ev,this.blockEventAttributes=null===(h=null===(g=null===(f=null===a||void 0===a?void 0:a.document)||void 0===f?void 0:f.dtpn)||void 0===g?void 0:g.blok)||void 0===h?void 0:h.ea,this.blockUserAttributes=null===(k=null===(j=null===(i=null===a||void 0===a?void 0:a.document)||void 0===i?void 0:i.dtpn)||void 0===j?void 0:j.blok)||void 0===k?void 0:k.ua,this.blockUserIdentities=null===(n=null===(m=null===(l=null===a||void 0===a?void 0:a.document)||void 0===l?void 0:l.dtpn)||void 0===m?void 0:m.blok)||void 0===n?void 0:n.id;var s=null===(q=null===(p=null===(o=null===a||void 0===a?void 0:a.document)||void 0===o?void 0:o.dtpn)||void 0===p?void 0:p.vers)||void 0===q?void 0:q.version_document,t=null===s||void 0===s?void 0:s.data_points;if(s)try{0<(null===t||void 0===t?void 0:t.length)&&t.forEach(function(a){return r.addToMatchLookups(a)});}catch(a){this.mpInstance.Logger.error("There was an issue with the data plan: "+a);}}return a.prototype.addToMatchLookups=function(a){var b,c,d;if(!a.match||!a.validator)return void this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(a));// match keys for non product custom attribute related data points +var e=this.generateMatchKey(a.match),f=this.getPlannedProperties(a.match.type,a.validator);this.dataPlanMatchLookups[e]=f,((null===(b=null===a||void 0===a?void 0:a.match)||void 0===b?void 0:b.type)===DataPlanMatchType.ProductImpression||(null===(c=null===a||void 0===a?void 0:a.match)||void 0===c?void 0:c.type)===DataPlanMatchType.ProductAction||(null===(d=null===a||void 0===a?void 0:a.match)||void 0===d?void 0:d.type)===DataPlanMatchType.PromotionAction)&&(e=this.generateProductAttributeMatchKey(a.match),f=this.getProductProperties(a.match.type,a.validator),this.dataPlanMatchLookups[e]=f);},a.prototype.generateMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.CustomEvent:var c=b;return [DataPlanMatchType.CustomEvent,c.custom_event_type,c.event_name].join(":");case DataPlanMatchType.ScreenView:return [DataPlanMatchType.ScreenView,"",b.screen_name].join(":");case DataPlanMatchType.ProductAction:return [a.type,b.action].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action].join(":");case DataPlanMatchType.ProductImpression:return [a.type,b.action].join(":");case DataPlanMatchType.UserIdentities:case DataPlanMatchType.UserAttributes:return [a.type].join(":");default:return null}},a.prototype.generateProductAttributeMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.ProductAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.ProductImpression:return [a.type,"ProductAttributes"].join(":");default:return null}},a.prototype.getPlannedProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l;switch(a){case DataPlanMatchType.CustomEvent:case DataPlanMatchType.ScreenView:case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction:case DataPlanMatchType.ProductImpression:if(k=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.custom_attributes,k){if(!0===k.additionalProperties||void 0===k.additionalProperties)return !0;for(var m,n={},o=0,p=Object.keys(k.properties);o=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} + +// The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: +// - version is always this prefix: fb +// - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2) +// - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value +// - is the value for the fbclid query parameter in the page URL. +// https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc +var facebookClickIdProcessor=function(a,b,c){if(!a||!b)return "";var d=null===b||void 0===b?void 0:b.split("//");if(!d)return "";var e=d[1].split("/"),f=e[0].split("."),g=1;// The rules for subdomainIndex are for parsing the domain portion +// of the URL for cookies, but in this case we are parsing the URL +// itself, so we can ignore the use of 0 for 'com' +3<=f.length&&(g=2);// If timestamp is not provided, use the current time +var h=c||Date.now();return "fb.".concat(g,".").concat(h,".").concat(a)};// Integration outputs are used to determine how click ids are used within the SDK +// CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject +// PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch +// INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created +var IntegrationOutputs={CUSTOM_FLAGS:"custom_flags",PARTNER_IDENTITIES:"partner_identities",INTEGRATION_ATTRIBUTES:"integration_attributes"},integrationMappingExternal={// Facebook / Meta +fbclid:{mappedKey:"Facebook.ClickId",processor:facebookClickIdProcessor,output:IntegrationOutputs.CUSTOM_FLAGS},_fbp:{mappedKey:"Facebook.BrowserId",output:IntegrationOutputs.CUSTOM_FLAGS},_fbc:{mappedKey:"Facebook.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Google +gclid:{mappedKey:"GoogleEnhancedConversions.Gclid",output:IntegrationOutputs.CUSTOM_FLAGS},gbraid:{mappedKey:"GoogleEnhancedConversions.Gbraid",output:IntegrationOutputs.CUSTOM_FLAGS},wbraid:{mappedKey:"GoogleEnhancedConversions.Wbraid",output:IntegrationOutputs.CUSTOM_FLAGS},// TIKTOK +ttclid:{mappedKey:"TikTok.Callback",output:IntegrationOutputs.CUSTOM_FLAGS},_ttp:{mappedKey:"tiktok_cookie_id",output:IntegrationOutputs.PARTNER_IDENTITIES},// Snapchat +// https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US +ScCid:{mappedKey:"SnapchatConversions.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Snapchat +// https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id +_scid:{mappedKey:"SnapchatConversions.Cookie1",output:IntegrationOutputs.CUSTOM_FLAGS}},integrationMappingRokt={// Rokt +// https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/ +// https://go.mparticle.com/work/SQDSDKS-7167 +rtid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},rclid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},RoktTransactionId:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277}},IntegrationCapture=/** @class */function(){function a(a){this.initialTimestamp=Date.now(),this.captureMode=a,this.filteredPartnerIdentityMappings=this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES),this.filteredCustomFlagMappings=this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS),this.filteredIntegrationAttributeMappings=this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);}/** + * Captures Integration Ids from cookies and query params and stores them in clickIds object + */return a.prototype.capture=function(){var a=this.captureQueryParams()||{},b=this.captureCookies()||{},c=this.captureLocalStorage()||{};a.fbclid&&b._fbc&&delete b._fbc;// ROKT Rules +// If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid +// If RoktTransactionId is present in both cookies and localStorage, +// prioritize localStorage +var d=a.rtid||a.rclid,e=c.RoktTransactionId,f=b.RoktTransactionId;d?(e&&delete c.RoktTransactionId,f&&delete b.RoktTransactionId):e&&f&&delete b.RoktTransactionId,this.clickIds=__assign(__assign(__assign(__assign({},this.clickIds),a),c),b);},a.prototype.captureCookies=function(){var a=this.getAllowedKeysForMode(),b=getCookies(a);return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.captureQueryParams=function(){var a=this.getQueryParams();return this.applyProcessors(a,getHref(),this.initialTimestamp)},a.prototype.captureLocalStorage=function(){for(var a=this.getAllowedKeysForMode(),b={},c=0,d=a;c": { +// "mappedKey": "clickIdValue" +// } +// } +// } +for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}(); + +// Rokt Web SDK via a Web Kit. +// The Rokt Manager should load before the Web Kit and stubs out many of the +// Rokt Web SDK functions with an internal message queue in case a Rokt function +// is requested before the Rokt Web Kit or SDK is finished loaded. +// Once the Rokt Kit is attached to the Rokt Manager, we can consider the +// Rokt Manager in a "ready" state and it can begin sending data to the kit. +// +// https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt +var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1;}/** + * Sets a callback to be invoked when RoktManager becomes ready + */return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g){var h,i,j=a||{},k=j.userAttributeFilters,l=j.settings,m=l||{},n=m.placementAttributesMapping,o=m.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(h=null===o||void 0===o?void 0:o.toLowerCase())&&void 0!==h?h:null,this.identityService=c,this.store=d,this.logger=e,this.captureTiming=g,null===(i=this.captureTiming)||void 0===i?void 0:i.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:k,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(n);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode +// It is set here and passed in to the createLauncher method in the Rokt Kit +// This is not to be confused for the `sandbox` flag in the selectPlacements attributes +// as that is independent of this setting, though they share the same name. +var p=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through +// to the Rokt Launcher. +this.launcherOptions=__assign({sandbox:p},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h;return __awaiter(this,void 0,void 0,function(){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A=this;return __generator(this,function(B){switch(B.label){case 0:// Queue if kit isn't ready OR if identity is in flight +if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];B.label=1;case 1:if(B.trys.push([1,6,,7]),i=a.attributes,j=(null===i||void 0===i?void 0:i.sandbox)||null,k=this.mapPlacementAttributes(i,this.placementAttributesMapping),null===(d=this.logger)||void 0===d?void 0:d.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(i,null,2))),this.currentUser=this.identityService.getCurrentUser(),l=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},m=l.email,n=k.email,o=void 0,p=void 0,q=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),q&&(o=l[this.mappedEmailShaIdentityType],p=k.emailsha256||k[this.mappedEmailShaIdentityType]||void 0),r=this.hasIdentityChanged(m,n),s=this.hasIdentityChanged(o,p),t={},r&&(t.email=n,n&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),s&&(t[this.mappedEmailShaIdentityType]=p,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(t))return [3/*break*/,5];B.label=2;case 2:return B.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){A.identityService.identify({userIdentities:__assign(__assign({},l),t)},function(){a();});})];case 3:return B.sent(),[3/*break*/,5];case 4:return u=B.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(u)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),v=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},this.setUserAttributes(k),w=__assign(__assign({},k),null===j?{}:{sandbox:j}),v.email&&!w.email&&(w.email=v.email),q&&(x=v[this.mappedEmailShaIdentityType],x&&!w.emailsha256&&!w[this.mappedEmailShaIdentityType]&&(w.emailsha256=x)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,y=__assign(__assign({},a),{attributes:w}),[2/*return*/,this.kit.selectPlacements(y)];case 6:return z=B.sent(),[2/*return*/,Promise.reject(z instanceof Error?z:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);fAll of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

+ *

In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.

+ *

This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().

+ *

If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:

+ * + * mParticle.init('apiKey', config, 'another_instance'); + * mParticle.getInstance('another_instance').logPageView(); + * + * + * @class mParticle & mParticleInstance + */function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption +this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization +// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization +// to it for it to be run after fetched +if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval +b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** + * Creates a CCPA Opt Out Consent State. + * + * @method createCCPAConsent + * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" + * @param {Number} timestamp Unix time (likely to be Date.now()) + * @param {String} consentDocument document version or experience that the user may have consented to + * @param {String} location location where the user gave consent + * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users + * @return {Object} CCPA Consent State + */createCCPAConsent:b._Consent.createPrivacyConsent,/** + * Creates a GDPR Consent State. + * + * @method createGDPRConsent + * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" + * @param {Number} timestamp Unix time (likely to be Date.now()) + * @param {String} consentDocument document version or experience that the user may have consented to + * @param {String} location location where the user gave consent + * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users + * @return {Object} GDPR Consent State + */createGDPRConsent:b._Consent.createPrivacyConsent,/** + * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states. + * + * @method createConsentState + * @return {Object} ConsentState object + */createConsentState:b._Consent.createConsentState},this.eCommerce={/** + * Invoke these methods on the mParticle.eCommerce.Cart object. + * Example: mParticle.eCommerce.Cart.add(...) + * @class mParticle.eCommerce.Cart + * @deprecated + */Cart:{/** + * Adds a product to the cart + * @method add + * @param {Object} product The product you want to add to the cart + * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. + * @deprecated + */add:function add(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** + * Removes a product from the cart + * @method remove + * @param {Object} product The product you want to add to the cart + * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. + * @deprecated + */remove:function remove(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/** + * Clears the cart + * @method clear + * @deprecated + */clear:function clear(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));}},/** + * Sets the currency code + * @for mParticle.eCommerce + * @method setCurrencyCode + * @param {String} code The currency code + */setCurrencyCode:function setCurrencyCode(a){var c=queueIfNotInitialized(function(){b.eCommerce.setCurrencyCode(a);},b);return c?void 0:"string"==typeof a?void(b._SessionManager.resetSessionTimer(),b._Store.currencyCode=a):void b.Logger.error("Code must be a string")},/** + * Creates a product + * @for mParticle.eCommerce + * @method createProduct + * @param {String} name product name + * @param {String} sku product sku + * @param {Number} price product price + * @param {Number} [quantity] product quantity. If blank, defaults to 1. + * @param {String} [variant] product variant + * @param {String} [category] product category + * @param {String} [brand] product brand + * @param {Number} [position] product position + * @param {String} [coupon] product coupon + * @param {Object} [attributes] product attributes + */createProduct:function createProduct(a,c,d,e,f,g,h,i,j,k){return b._Ecommerce.createProduct(a,c,d,e,f,g,h,i,j,k)},/** + * Creates a promotion + * @for mParticle.eCommerce + * @method createPromotion + * @param {String} id a unique promotion id + * @param {String} [creative] promotion creative + * @param {String} [name] promotion name + * @param {Number} [position] promotion position + */createPromotion:function createPromotion(a,c,d,e){return b._Ecommerce.createPromotion(a,c,d,e)},/** + * Creates a product impression + * @for mParticle.eCommerce + * @method createImpression + * @param {String} name impression name + * @param {Object} product the product for which an impression is being created + */createImpression:function createImpression(a,c){return b._Ecommerce.createImpression(a,c)},/** + * Creates a transaction attributes object to be used with a checkout + * @for mParticle.eCommerce + * @method createTransactionAttributes + * @param {String or Number} id a unique transaction id + * @param {String} [affiliation] affilliation + * @param {String} [couponCode] the coupon code for which you are creating transaction attributes + * @param {Number} [revenue] total revenue for the product being purchased + * @param {String} [shipping] the shipping method + * @param {Number} [tax] the tax amount + */createTransactionAttributes:function createTransactionAttributes(a,c,d,e,f,g){return b._Ecommerce.createTransactionAttributes(a,c,d,e,f,g)},/** + * Logs a checkout action + * @for mParticle.eCommerce + * @method logCheckout + * @param {Number} step checkout step number + * @param {String} checkout option string + * @param {Object} attrs + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */logCheckout:function logCheckout(a,c,d,e){return b.Logger.warning("mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logCheckoutEvent(a,c,d,e)):void b.ready(function(){b.eCommerce.logCheckout(a,c,d,e);})},/** + * Logs a product action + * @for mParticle.eCommerce + * @method logProductAction + * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218) + * @param {Object} product the product for which you are creating the product action + * @param {Object} [attrs] attributes related to the product action + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [transactionAttributes] Transaction Attributes for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */logProductAction:function logProductAction(a,c,d,e,f,g){var h=queueIfNotInitialized(function(){b.eCommerce.logProductAction(a,c,d,e,f,g);},b);h||(b._SessionManager.resetSessionTimer(),b._Events.logProductActionEvent(a,c,d,e,f,g));},/** + * Logs a product purchase + * @for mParticle.eCommerce + * @method logPurchase + * @param {Object} transactionAttributes transactionAttributes object + * @param {Object} product the product being purchased + * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false + * @param {Object} [attrs] other attributes related to the product purchase + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */logPurchase:function logPurchase(a,c,d,e,f){return b.Logger.warning("mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?a&&c?void(b._SessionManager.resetSessionTimer(),b._Events.logPurchaseEvent(a,c,e,f)):void b.Logger.error(Messages.ErrorMessages.BadLogPurchase):void b.ready(function(){b.eCommerce.logPurchase(a,c,d,e,f);})},/** + * Logs a product promotion + * @for mParticle.eCommerce + * @method logPromotion + * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279) + * @param {Object} promotion promotion object + * @param {Object} [attrs] boolean to clear the cart after logging or not + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */logPromotion:function logPromotion(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.eCommerce.logPromotion(a,c,d,e,f);},b);g||(b._SessionManager.resetSessionTimer(),b._Events.logPromotionEvent(a,c,d,e,f));},/** + * Logs a product impression + * @for mParticle.eCommerce + * @method logImpression + * @param {Object} impression product impression object + * @param {Object} attrs attributes related to the impression log + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */logImpression:function logImpression(a,c,d,e){var f=queueIfNotInitialized(function(){b.eCommerce.logImpression(a,c,d,e);},b);f||(b._SessionManager.resetSessionTimer(),b._Events.logImpressionEvent(a,c,d,e));},/** + * Logs a refund + * @for mParticle.eCommerce + * @method logRefund + * @param {Object} transactionAttributes transaction attributes related to the refund + * @param {Object} product product being refunded + * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false. + * @param {Object} [attrs] attributes related to the refund + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie +// And logs to in-memory object +// Example: mParticle.setSessionAttribute('location', '33431'); +if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed +if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any +// other integration delays set to true. It not, process the queued events/. +var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment +function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's +// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not +// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize +// persistence or Identity directly. +if(c._APIClient=new APIClient(c,f),c._Forwarders=new Forwarders(c,f),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use +var h=c.Identity.getCurrentUser(),i=h?h.getMPID():null,j=h?h.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:j}:c._Store.SDKConfig.identifyRequest,g(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639 +var k=g(CaptureIntegrationSpecificIds),l=g(CaptureIntegrationSpecificIdsV2),m=l&&l!==CaptureIntegrationSpecificIdsV2Modes.None||!0===k;if(m){var n;k||l===CaptureIntegrationSpecificIdsV2Modes.All?n="all":l===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(n="roktonly"),c._IntegrationCapture=new IntegrationCapture(n),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user +var o=parseConfig(b,"Rokt",181);if(o){var p=null===(d=o.settings)||void 0===d?void 0:d.accountId;c._Store.setRoktAccountId(p);var q=o.userAttributeFilters,r=filteredMparticleUser(i,{userAttributeFilters:q},c),s={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339 +c._RoktManager.init(o,r,c.Identity,c._Store,c.Logger,s,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,h,i,j);}// We will continue to clear out the ready queue as part of the initial init flow +// if an identify request is unnecessary, such as if there is an existing session +(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),null===(e=c.processQueueOnNoFunctional)||void 0===e?void 0:e.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061 +function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK: + 1. Manually via config.dataPlanOptions (this takes priority) + If not passed in manually, we user the server provided via either + 2. Snippet via /mparticle.js endpoint (config.dataPlan.document) + 3. Self hosting via /config endpoint (config.dataPlanResult) + */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault +// ensures no identity response data is written to localStorage when noFunctional is true +return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions +var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs +// since we will need this for the current implementation of user persistence +// TODO: Refactor this when we refactor User Identity Persistence +try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never +// receive an MPID. Let these calls through so events can still reach forwarders immediately. +// sendEventToServer handles queuing for the MP server upload path separately. +return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)} + +// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise! +var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method +_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:mockFunction},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}(); + +var MPSideloadedKit=/** @class */function(){function a(a){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],// The below filtering members are optional, but we instantiate them +// to simplify public method assignment +filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=a;}return a.prototype.addEventTypeFilter=function(a){var b=KitFilterHelper.hashEventType(a);this.filterDictionary.eventTypeFilters.push(b);},a.prototype.addEventNameFilter=function(a,b){var c=KitFilterHelper.hashEventName(b,a);this.filterDictionary.eventNameFilters.push(c);},a.prototype.addEventAttributeFilter=function(a,b,c){var d=KitFilterHelper.hashEventAttributeKey(a,b,c);this.filterDictionary.attributeFilters.push(d);},a.prototype.addScreenNameFilter=function(a){var b=KitFilterHelper.hashEventName(a,EventType.Unknown);this.filterDictionary.screenNameFilters.push(b);},a.prototype.addScreenAttributeFilter=function(a,b){var c=KitFilterHelper.hashEventAttributeKey(EventType.Unknown,a,b);this.filterDictionary.screenAttributeFilters.push(c);},a.prototype.addUserIdentityFilter=function(a){var b=KitFilterHelper.hashUserIdentity(a);this.filterDictionary.userIdentityFilters.push(b);},a.prototype.addUserAttributeFilter=function(a){var b=KitFilterHelper.hashUserAttribute(a);this.filterDictionary.userAttributeFilters.push(b);},a}(); + +Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticleInstanceManager(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing +/** + * Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used. + *

+ * If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below. + * @method init + * @param {String} apiKey your mParticle assigned API key + * @param {Object} [config] an options object for additional configuration + * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. + */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); + +export { mParticleManager as default }; diff --git a/dist/mparticle.js b/dist/mparticle.js new file mode 100644 index 000000000..ff767ca7f --- /dev/null +++ b/dist/mparticle.js @@ -0,0 +1,12110 @@ +var mParticle = (function () { + + // Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html + var Base64$1 = { + _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + // Input must be a string + encode: function encode(input) { + try { + if (window.btoa && window.atob) { + return window.btoa(unescape(encodeURIComponent(input))); + } + } catch (e) { + console.error('Error encoding cookie values into Base64:' + e); + } + return this._encode(input); + }, + _encode: function _encode(input) { + var output = ''; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + input = UTF8.encode(input); + while (i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + enc1 = chr1 >> 2; + enc2 = (chr1 & 3) << 4 | chr2 >> 4; + enc3 = (chr2 & 15) << 2 | chr3 >> 6; + enc4 = chr3 & 63; + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + output = output + Base64$1._keyStr.charAt(enc1) + Base64$1._keyStr.charAt(enc2) + Base64$1._keyStr.charAt(enc3) + Base64$1._keyStr.charAt(enc4); + } + return output; + }, + decode: function decode(input) { + try { + if (window.btoa && window.atob) { + return decodeURIComponent(escape(window.atob(input))); + } + } catch (e) { + //log(e); + } + return Base64$1._decode(input); + }, + _decode: function _decode(input) { + var output = ''; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + while (i < input.length) { + enc1 = Base64$1._keyStr.indexOf(input.charAt(i++)); + enc2 = Base64$1._keyStr.indexOf(input.charAt(i++)); + enc3 = Base64$1._keyStr.indexOf(input.charAt(i++)); + enc4 = Base64$1._keyStr.indexOf(input.charAt(i++)); + chr1 = enc1 << 2 | enc2 >> 4; + chr2 = (enc2 & 15) << 4 | enc3 >> 2; + chr3 = (enc3 & 3) << 6 | enc4; + output = output + String.fromCharCode(chr1); + if (enc3 !== 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 !== 64) { + output = output + String.fromCharCode(chr3); + } + } + output = UTF8.decode(output); + return output; + } + }; + var UTF8 = { + encode: function encode(s) { + var utftext = ''; + for (var n = 0; n < s.length; n++) { + var c = s.charCodeAt(n); + if (c < 128) { + utftext += String.fromCharCode(c); + } else if (c > 127 && c < 2048) { + utftext += String.fromCharCode(c >> 6 | 192); + utftext += String.fromCharCode(c & 63 | 128); + } else { + utftext += String.fromCharCode(c >> 12 | 224); + utftext += String.fromCharCode(c >> 6 & 63 | 128); + utftext += String.fromCharCode(c & 63 | 128); + } + } + return utftext; + }, + decode: function decode(utftext) { + var s = ''; + var i = 0; + var c = 0, + c1 = 0, + c2 = 0; + while (i < utftext.length) { + c = utftext.charCodeAt(i); + if (c < 128) { + s += String.fromCharCode(c); + i++; + } else if (c > 191 && c < 224) { + c1 = utftext.charCodeAt(i + 1); + s += String.fromCharCode((c & 31) << 6 | c1 & 63); + i += 2; + } else { + c1 = utftext.charCodeAt(i + 1); + c2 = utftext.charCodeAt(i + 2); + s += String.fromCharCode((c & 15) << 12 | (c1 & 63) << 6 | c2 & 63); + i += 3; + } + } + return s; + } + }; + var Polyfill = { + // forEach polyfill + // Production steps of ECMA-262, Edition 5, 15.4.4.18 + // Reference: http://es5.github.io/#x15.4.4.18 + forEach: function forEach(callback, thisArg) { + var T, k; + if (this == null) { + throw new TypeError(' this is null or not defined'); + } + var O = Object(this); + var len = O.length >>> 0; + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + if (arguments.length > 1) { + T = thisArg; + } + k = 0; + while (k < len) { + var kValue; + if (k in O) { + kValue = O[k]; + callback.call(T, kValue, k, O); + } + k++; + } + }, + // map polyfill + // Production steps of ECMA-262, Edition 5, 15.4.4.19 + // Reference: http://es5.github.io/#x15.4.4.19 + map: function map(callback, thisArg) { + var T, A, k; + if (this === null) { + throw new TypeError(' this is null or not defined'); + } + var O = Object(this); + var len = O.length >>> 0; + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + if (arguments.length > 1) { + T = thisArg; + } + A = new Array(len); + k = 0; + while (k < len) { + var kValue, mappedValue; + if (k in O) { + kValue = O[k]; + mappedValue = callback.call(T, kValue, k, O); + A[k] = mappedValue; + } + k++; + } + return A; + }, + // filter polyfill + // Prodcution steps of ECMA-262, Edition 5 + // Reference: http://es5.github.io/#x15.4.4.20 + filter: function filter(fun /*, thisArg*/) { + + if (this === void 0 || this === null) { + throw new TypeError(); + } + var t = Object(this); + var len = t.length >>> 0; + if (typeof fun !== 'function') { + throw new TypeError(); + } + var res = []; + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + for (var i = 0; i < len; i++) { + if (i in t) { + var val = t[i]; + if (fun.call(thisArg, val, i, t)) { + res.push(val); + } + } + } + return res; + }, + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray + isArray: function isArray(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }, + Base64: Base64$1 + }; + + var version = "2.59.0"; + + var Constants = { + sdkVersion: version, + sdkVendor: 'mparticle', + platform: 'web', + Messages: { + DeprecationMessages: { + MethodHasBeenDeprecated: 'has been deprecated.', + MethodMarkedForDeprecationPostfix: 'is a deprecated method and will be removed in future releases.', + AlternativeMethodPrefix: 'Please use the alternate method:' + }, + ErrorMessages: { + NoToken: 'A token must be specified.', + EventNameInvalidType: 'Event name must be a valid string value.', + EventDataInvalidType: 'Event data must be a valid object hash.', + LoggingDisabled: 'Event logging is currently disabled.', + CookieParseError: 'Could not parse cookie', + EventEmpty: 'Event object is null or undefined, cancelling send', + APIRequestEmpty: 'APIRequest is null or undefined, cancelling send', + NoEventType: 'Event type must be specified.', + TransactionIdRequired: 'Transaction ID is required', + TransactionRequired: 'A transaction attributes object is required', + PromotionIdRequired: 'Promotion ID is required', + BadAttribute: 'Attribute value cannot be object or array', + BadKey: 'Key value cannot be object or array', + BadLogPurchase: 'Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions', + AudienceAPINotEnabled: 'Your workspace is not enabled to retrieve user audiences.' + }, + InformationMessages: { + CookieSearch: 'Searching for cookie', + CookieFound: 'Cookie found, parsing values', + CookieNotFound: 'Cookies not found', + CookieSet: 'Setting cookie', + CookieSync: 'Performing cookie sync', + SendBegin: 'Starting to send event', + SendIdentityBegin: 'Starting to send event to identity server', + SendWindowsPhone: 'Sending event to Windows Phone container', + SendIOS: 'Calling iOS path: ', + SendAndroid: 'Calling Android JS interface method: ', + SendHttp: 'Sending event to mParticle HTTP service', + SendAliasHttp: 'Sending alias request to mParticle HTTP service', + SendIdentityHttp: 'Sending event to mParticle HTTP service', + StartingNewSession: 'Starting new Session', + StartingLogEvent: 'Starting to log event', + StartingLogOptOut: 'Starting to log user opt in/out', + StartingEndSession: 'Starting to end session', + StartingInitialization: 'Starting to initialize', + StartingLogCommerceEvent: 'Starting to log commerce event', + StartingAliasRequest: 'Starting to Alias MPIDs', + LoadingConfig: 'Loading configuration options', + AbandonLogEvent: 'Cannot log event, logging disabled or developer token not set', + AbandonAliasUsers: 'Cannot Alias Users, logging disabled or developer token not set', + AbandonStartSession: 'Cannot start session, logging disabled or developer token not set', + AbandonEndSession: 'Cannot end session, logging disabled or developer token not set', + NoSessionToEnd: 'Cannot end session, no active session found' + }, + ValidationMessages: { + ModifyIdentityRequestUserIdentitiesPresent: 'identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again', + IdentityRequesetInvalidKey: 'There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.', + OnUserAliasType: 'The onUserAlias value must be a function.', + UserIdentities: 'The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.', + UserIdentitiesInvalidKey: 'There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.', + UserIdentitiesInvalidValues: 'All user identity values must be strings or null. Request not sent to server. Please fix and try again.', + AliasMissingMpid: 'Alias Request must contain both a destinationMpid and a sourceMpid', + AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique", + AliasMissingTime: 'Alias Request must have both a startTime and an endTime', + AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime" + } + }, + NativeSdkPaths: { + LogEvent: 'logEvent', + SetUserTag: 'setUserTag', + RemoveUserTag: 'removeUserTag', + SetUserAttribute: 'setUserAttribute', + RemoveUserAttribute: 'removeUserAttribute', + SetSessionAttribute: 'setSessionAttribute', + AddToCart: 'addToCart', + RemoveFromCart: 'removeFromCart', + ClearCart: 'clearCart', + LogOut: 'logOut', + SetUserAttributeList: 'setUserAttributeList', + RemoveAllUserAttributes: 'removeAllUserAttributes', + GetUserAttributesLists: 'getUserAttributesLists', + GetAllUserAttributes: 'getAllUserAttributes', + Identify: 'identify', + Logout: 'logout', + Login: 'login', + Modify: 'modify', + Alias: 'aliasUsers', + Upload: 'upload' + }, + StorageNames: { + localStorageName: 'mprtcl-api', + localStorageNameV3: 'mprtcl-v3', + cookieName: 'mprtcl-api', + cookieNameV2: 'mprtcl-v2', + cookieNameV3: 'mprtcl-v3', + localStorageNameV4: 'mprtcl-v4', + localStorageProductsV4: 'mprtcl-prodv4', + cookieNameV4: 'mprtcl-v4', + currentStorageName: 'mprtcl-v4', + currentStorageProductsName: 'mprtcl-prodv4' + }, + DefaultConfig: { + cookieDomain: null, + cookieExpiration: 365, + logLevel: null, + timeout: 300, + sessionTimeout: 30, + maxProducts: 20, + forwarderStatsTimeout: 5000, + integrationDelayTimeout: 5000, + maxCookieSize: 3000, + aliasMaxWindow: 90, + uploadInterval: 0 // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally + }, + + DefaultBaseUrls: { + v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/', + v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/', + v3SecureServiceUrl: 'jssdks.mparticle.com/v3/JS/', + configUrl: 'jssdkcdns.mparticle.com/JS/v2/', + identityUrl: 'identity.mparticle.com/v1/', + aliasUrl: 'jssdks.mparticle.com/v1/identity/', + userAudienceUrl: 'nativesdks.mparticle.com/v1/' + }, + // These are the paths that are used to construct the CNAME urls + CNAMEUrlPaths: { + v1SecureServiceUrl: '/webevents/v1/JS/', + v2SecureServiceUrl: '/webevents/v2/JS/', + v3SecureServiceUrl: '/webevents/v3/JS/', + configUrl: '/tags/JS/v2/', + identityUrl: '/identity/v1/', + aliasUrl: '/webevents/v1/identity/' + }, + Base64CookieKeys: { + csm: 1, + sa: 1, + ss: 1, + lsa: 1, + ua: 1, + ui: 1, + csd: 1, + ia: 1, + con: 1 + }, + // https://go.mparticle.com/work/SQDSDKS-6039 + SDKv2NonMPIDCookieKeys: { + gs: 1, + cu: 1, + l: 1, + globalSettings: 1, + currentUserMPID: 1 + }, + HTTPCodes: { + noHttpCoverage: -1, + activeIdentityRequest: -2, + activeSession: -3, + validationIssue: -4, + nativeIdentityRequest: -5, + loggingDisabledOrMissingAPIKey: -6, + tooManyRequests: 429 + }, + FeatureFlags: { + ReportBatching: 'reportBatching', + EventBatchingIntervalMillis: 'eventBatchingIntervalMillis', + OfflineStorage: 'offlineStorage', + DirectUrlRouting: 'directURLRouting', + CacheIdentity: 'cacheIdentity', + AudienceAPI: 'audienceAPI', + // CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI + // - 'True' → capture all integration-specific IDs + // - 'False' → capture none + CaptureIntegrationSpecificIds: 'captureIntegrationSpecificIds', + // CaptureIntegrationSpecificIdsV2 (new): string mode from server + // - 'all' → capture all IDs + // - 'none' → capture none + // - 'roktonly' → capture only Rokt-related IDs + CaptureIntegrationSpecificIdsV2: 'captureIntegrationSpecificIdsV2', + AstBackgroundEvents: 'astBackgroundEvents' + }, + DefaultInstance: 'default_instance', + CCPAPurpose: 'data_sale_opt_out', + IdentityMethods: { + Modify: 'modify', + Logout: 'logout', + Login: 'login', + Identify: 'identify' + }, + Environment: { + Development: 'development', + Production: 'production' + }, + CaptureIntegrationSpecificIdsV2Modes: { + All: 'all', + None: 'none', + RoktOnly: 'roktonly' + }, + Rokt: { + LauncherInstanceGuidKey: '__rokt_li_guid__' + } + }; + // https://go.mparticle.com/work/SQDSDKS-6080 + var ONE_DAY_IN_SECONDS = 60 * 60 * 24; + var MILLIS_IN_ONE_SEC = 1000; + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + var HTTP_OK = 200; + var HTTP_ACCEPTED = 202; + var HTTP_BAD_REQUEST = 400; + var HTTP_SERVER_ERROR = 500; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var Messages$9 = Constants.Messages; + var createCookieString = function createCookieString(value) { + return replaceCommasWithPipes(replaceQuotesWithApostrophes(value)); + }; + var revertCookieString = function revertCookieString(value) { + return replacePipesWithCommas(replaceApostrophesWithQuotes(value)); + }; + var inArray = function inArray(items, name) { + if (!items) { + return false; + } + var i = 0; + if (Array.prototype.indexOf) { + return items.indexOf(name, 0) >= 0; + } else { + for (var n = items.length; i < n; i++) { + if (i in items && items[i] === name) { + return true; + } + } + } + return false; + }; + var findKeyInObject = function findKeyInObject(obj, key) { + if (key && obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop) && prop.toLowerCase() === key.toLowerCase()) { + return prop; + } + } + } + return null; + }; + var generateDeprecationMessage = function generateDeprecationMessage(methodName, isDeprecated, alternateMethod, docsUrl) { + var messageArray = [methodName]; + if (isDeprecated) { + messageArray.push(Messages$9.DeprecationMessages.MethodHasBeenDeprecated); + } else { + messageArray.push(Messages$9.DeprecationMessages.MethodMarkedForDeprecationPostfix); + } + if (alternateMethod) { + messageArray.push(Messages$9.DeprecationMessages.AlternativeMethodPrefix); + messageArray.push(alternateMethod + "."); + } + if (docsUrl) { + messageArray.push("See - " + docsUrl); + } + return messageArray.join(' '); + }; + function generateHash(name) { + var hash = 0; + var character; + if (name === undefined || name === null) { + return 0; + } + name = name.toString().toLowerCase(); + if (Array.prototype.reduce) { + return name.split('').reduce(function (a, b) { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0); + } + if (name.length === 0) { + return hash; + } + for (var i = 0; i < name.length; i++) { + character = name.charCodeAt(i); + hash = (hash << 5) - hash + character; + hash = hash & hash; + } + return hash; + } + var generateRandomValue = function generateRandomValue(value) { + var randomValue; + var a; + if (window.crypto && window.crypto.getRandomValues) { + // @ts-ignore + randomValue = window.crypto.getRandomValues(new Uint8Array(1)); // eslint-disable-line no-undef + } + + if (randomValue) { + // @ts-ignore + return (a ^ randomValue[0] % 16 >> a / 4).toString(16); + } + return (a ^ Math.random() * 16 >> a / 4).toString(16); + }; + var generateUniqueId = function generateUniqueId(a) { + // https://gist.github.com/jed/982883 + // Added support for crypto for better random + if (a === void 0) { + a = ''; + } + return a // if the placeholder was passed, return + ? generateRandomValue() // if the placeholder was passed, return + : + // [1e7] -> // 10000000 + + // -1e3 -> // -1000 + + // -4e3 -> // -4000 + + // -8e3 -> // -80000000 + + // -1e11 -> //-100000000000, + "".concat(1e7, "-").concat(1e3, "-").concat(4e3, "-").concat(8e3, "-").concat(1e11).replace(/[018]/g, + // zeroes, ones, and eights with + generateUniqueId // random hex digits + ); + }; + /** + * Returns a value between 1-100 inclusive. + */ + var getRampNumber = function getRampNumber(value) { + if (!value) { + return 100; + } + var hash = generateHash(value); + return Math.abs(hash % 100) + 1; + }; + var isObject = function isObject(value) { + var objType = Object.prototype.toString.call(value); + return objType === '[object Object]' || objType === '[object Error]'; + }; + var parseNumber = function parseNumber(value) { + if (isNaN(value) || !isFinite(value)) { + return 0; + } + var floatValue = parseFloat(value); + return isNaN(floatValue) ? 0 : floatValue; + }; + var parseSettingsString = function parseSettingsString(settingsString) { + try { + return settingsString ? JSON.parse(settingsString.replace(/"/g, '"')) : []; + } catch (error) { + throw new Error('Settings string contains invalid JSON'); + } + }; + var parseStringOrNumber = function parseStringOrNumber(value) { + if (isStringOrNumber(value)) { + return value; + } else { + return null; + } + }; + var replaceCommasWithPipes = function replaceCommasWithPipes(value) { + return value.replace(/,/g, '|'); + }; + var replacePipesWithCommas = function replacePipesWithCommas(value) { + return value.replace(/\|/g, ','); + }; + var replaceApostrophesWithQuotes = function replaceApostrophesWithQuotes(value) { + return value.replace(/\'/g, '"'); + }; + var replaceQuotesWithApostrophes = function replaceQuotesWithApostrophes(value) { + return value.replace(/\"/g, "'"); + }; + var replaceMPID = function replaceMPID(value, mpid) { + return value.replace('%%mpid%%', mpid); + }; + var replaceAmpWithAmpersand = function replaceAmpWithAmpersand(value) { + return value.replace(/&/g, '&'); + }; + var createCookieSyncUrl = function createCookieSyncUrl(mpid, pixelUrl, redirectUrl, domain) { + var modifiedPixelUrl = replaceAmpWithAmpersand(pixelUrl); + var modifiedDirectUrl = redirectUrl ? replaceAmpWithAmpersand(redirectUrl) : null; + var url = replaceMPID(modifiedPixelUrl, mpid); + var redirect = modifiedDirectUrl ? replaceMPID(modifiedDirectUrl, mpid) : ''; + var fullUrl = url + encodeURIComponent(redirect); + if (domain) { + var separator = fullUrl.includes('?') ? '&' : '?'; + fullUrl += "".concat(separator, "domain=").concat(domain); + } + return fullUrl; + }; + // FIXME: REFACTOR for V3 + // only used in store.js to sanitize server-side formatting of + // booleans when checking for `isDevelopmentMode` + // Should be removed in v3 + var returnConvertedBoolean = function returnConvertedBoolean(data) { + if (data === 'false' || data === '0') { + return false; + } else { + return Boolean(data); + } + }; + var decoded = function decoded(s) { + return decodeURIComponent(s.replace(/\+/g, ' ')); + }; + var converted = function converted(s) { + if (s.indexOf('"') === 0) { + s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); + } + return s; + }; + var isString = function isString(value) { + return typeof value === 'string'; + }; + var isNumber = function isNumber(value) { + return typeof value === 'number'; + }; + var isBoolean = function isBoolean(value) { + return typeof value === 'boolean'; + }; + var isFunction = function isFunction(fn) { + return typeof fn === 'function'; + }; + var isValidAttributeValue = function isValidAttributeValue(value) { + return value !== undefined && !isObject(value) && !Array.isArray(value); + }; + var isValidCustomFlagProperty = function isValidCustomFlagProperty(value) { + return isNumber(value) || isString(value) || isBoolean(value); + }; + var toDataPlanSlug = function toDataPlanSlug(value) { + // Make sure we are only acting on strings or numbers + return isStringOrNumber(value) ? value.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g, '_') : ''; + }; + var isDataPlanSlug = function isDataPlanSlug(str) { + return str === toDataPlanSlug(str); + }; + var isStringOrNumber = function isStringOrNumber(value) { + return isString(value) || isNumber(value); + }; + var isEmpty = function isEmpty(value) { + return value == null || !(Object.keys(value) || value).length; + }; + var moveElementToEnd = function moveElementToEnd(array, index) { + return array.slice(0, index).concat(array.slice(index + 1), array[index]); + }; + var queryStringParser = function queryStringParser(url, keys) { + if (keys === void 0) { + keys = []; + } + var urlParams; + var results = {}; + var lowerCaseUrlParams = {}; + if (!url) return results; + if (typeof URL !== 'undefined' && typeof URLSearchParams !== 'undefined') { + var urlObject = new URL(url); + urlParams = new URLSearchParams(urlObject.search); + } else { + urlParams = queryStringParserFallback(url); + } + urlParams.forEach(function (value, key) { + lowerCaseUrlParams[key.toLowerCase()] = value; + }); + if (isEmpty(keys)) { + return lowerCaseUrlParams; + } else { + keys.forEach(function (key) { + var value = lowerCaseUrlParams[key.toLowerCase()]; + if (value) { + results[key] = value; + } + }); + } + return results; + }; + var queryStringParserFallback = function queryStringParserFallback(url) { + var params = {}; + var queryString = url.split('?')[1] || ''; + var pairs = queryString.split('&'); + pairs.forEach(function (pair) { + var _a = pair.split('='), + key = _a[0], + valueParts = _a.slice(1); + var value = valueParts.join('='); + if (key && value !== undefined) { + try { + params[key] = decodeURIComponent(value || ''); + } catch (e) { + console.error("Failed to decode value for key ".concat(key, ": ").concat(e)); + } + } + }); + return { + get: function get(key) { + return params[key]; + }, + forEach: function forEach(callback) { + for (var key in params) { + if (params.hasOwnProperty(key)) { + callback(params[key], key); + } + } + } + }; + }; + // Get cookies as a dictionary + var getCookies = function getCookies(keys) { + // Helper function to parse cookies from document.cookie + var parseCookies = function parseCookies() { + try { + if (typeof window === 'undefined') { + return []; + } + return window.document.cookie.split(';').map(function (cookie) { + return cookie.trim(); + }); + } catch (e) { + console.error('Unable to parse cookies', e); + return []; + } + }; + // Helper function to filter cookies by keys + var filterCookies = function filterCookies(cookies, keys) { + var results = {}; + for (var _i = 0, cookies_1 = cookies; _i < cookies_1.length; _i++) { + var cookie = cookies_1[_i]; + var _a = cookie.split('='), + key = _a[0], + value = _a[1]; + if (!keys || keys.includes(key)) { + results[key] = value; + } + } + return results; + }; + // Parse cookies from document.cookie + var parsedCookies = parseCookies(); + // Filter cookies by keys if provided + return filterCookies(parsedCookies, keys); + }; + var getHref = function getHref() { + return typeof window !== 'undefined' && window.location ? window.location.href : ''; + }; + var filterDictionaryWithHash = function filterDictionaryWithHash(dictionary, filterList, hashFn) { + var filtered = {}; + if (!isEmpty(dictionary)) { + for (var key in dictionary) { + if (dictionary.hasOwnProperty(key)) { + var hashedKey = hashFn(key); + if (!inArray(filterList, hashedKey)) { + filtered[key] = dictionary[key]; + } + } + } + } + return filtered; + }; + var parseConfig = function parseConfig(config, moduleName, moduleId) { + var _a; + return ((_a = config.kitConfigs) === null || _a === void 0 ? void 0 : _a.find(function (kitConfig) { + return kitConfig.name === moduleName && kitConfig.moduleId === moduleId; + })) || null; + }; + + var MessageType$1 = { + SessionStart: 1, + SessionEnd: 2, + PageView: 3, + PageEvent: 4, + CrashReport: 5, + OptOut: 6, + AppStateTransition: 10, + Profile: 14, + Commerce: 16, + Media: 20, + UserAttributeChange: 17, + UserIdentityChange: 18 + }; + var EventType = { + Unknown: 0, + Navigation: 1, + Location: 2, + Search: 3, + Transaction: 4, + UserContent: 5, + UserPreference: 6, + Social: 7, + Other: 8, + Media: 9, + getName: function getName(id) { + switch (id) { + case EventType.Unknown: + return 'Unknown'; + case EventType.Navigation: + return 'Navigation'; + case EventType.Location: + return 'Location'; + case EventType.Search: + return 'Search'; + case EventType.Transaction: + return 'Transaction'; + case EventType.UserContent: + return 'User Content'; + case EventType.UserPreference: + return 'User Preference'; + case EventType.Social: + return 'Social'; + case CommerceEventType.ProductAddToCart: + return 'Product Added to Cart'; + case CommerceEventType.ProductAddToWishlist: + return 'Product Added to Wishlist'; + case CommerceEventType.ProductCheckout: + return 'Product Checkout'; + case CommerceEventType.ProductCheckoutOption: + return 'Product Checkout Options'; + case CommerceEventType.ProductClick: + return 'Product Click'; + case CommerceEventType.ProductImpression: + return 'Product Impression'; + case CommerceEventType.ProductPurchase: + return 'Product Purchased'; + case CommerceEventType.ProductRefund: + return 'Product Refunded'; + case CommerceEventType.ProductRemoveFromCart: + return 'Product Removed From Cart'; + case CommerceEventType.ProductRemoveFromWishlist: + return 'Product Removed from Wishlist'; + case CommerceEventType.ProductViewDetail: + return 'Product View Details'; + case CommerceEventType.PromotionClick: + return 'Promotion Click'; + case CommerceEventType.PromotionView: + return 'Promotion View'; + default: + return 'Other'; + } + } + }; + // Continuation of EventType enum above, but in seperate object since we don't expose these to end user + var CommerceEventType = { + ProductAddToCart: 10, + ProductRemoveFromCart: 11, + ProductCheckout: 12, + ProductCheckoutOption: 13, + ProductClick: 14, + ProductViewDetail: 15, + ProductPurchase: 16, + ProductRefund: 17, + PromotionView: 18, + PromotionClick: 19, + ProductAddToWishlist: 20, + ProductRemoveFromWishlist: 21, + ProductImpression: 22 + }; + var IdentityType = { + Other: 0, + CustomerId: 1, + Facebook: 2, + Twitter: 3, + Google: 4, + Microsoft: 5, + Yahoo: 6, + Email: 7, + FacebookCustomAudienceId: 9, + Other2: 10, + Other3: 11, + Other4: 12, + Other5: 13, + Other6: 14, + Other7: 15, + Other8: 16, + Other9: 17, + Other10: 18, + MobileNumber: 19, + PhoneNumber2: 20, + PhoneNumber3: 21, + isValid: function isValid(identityType) { + if (typeof identityType === 'number') { + for (var prop in IdentityType) { + if (IdentityType.hasOwnProperty(prop)) { + if (IdentityType[prop] === identityType) { + return true; + } + } + } + } + return false; + }, + getName: function getName(identityType) { + switch (identityType) { + case window.mParticle.IdentityType.CustomerId: + return 'Customer ID'; + case window.mParticle.IdentityType.Facebook: + return 'Facebook ID'; + case window.mParticle.IdentityType.Twitter: + return 'Twitter ID'; + case window.mParticle.IdentityType.Google: + return 'Google ID'; + case window.mParticle.IdentityType.Microsoft: + return 'Microsoft ID'; + case window.mParticle.IdentityType.Yahoo: + return 'Yahoo ID'; + case window.mParticle.IdentityType.Email: + return 'Email'; + case window.mParticle.IdentityType.FacebookCustomAudienceId: + return 'Facebook App User ID'; + default: + return 'Other ID'; + } + }, + getIdentityType: function getIdentityType(identityName) { + switch (identityName) { + case 'other': + return IdentityType.Other; + case 'customerid': + return IdentityType.CustomerId; + case 'facebook': + return IdentityType.Facebook; + case 'twitter': + return IdentityType.Twitter; + case 'google': + return IdentityType.Google; + case 'microsoft': + return IdentityType.Microsoft; + case 'yahoo': + return IdentityType.Yahoo; + case 'email': + return IdentityType.Email; + case 'facebookcustomaudienceid': + return IdentityType.FacebookCustomAudienceId; + case 'other2': + return IdentityType.Other2; + case 'other3': + return IdentityType.Other3; + case 'other4': + return IdentityType.Other4; + case 'other5': + return IdentityType.Other5; + case 'other6': + return IdentityType.Other6; + case 'other7': + return IdentityType.Other7; + case 'other8': + return IdentityType.Other8; + case 'other9': + return IdentityType.Other9; + case 'other10': + return IdentityType.Other10; + case 'mobile_number': + return IdentityType.MobileNumber; + case 'phone_number_2': + return IdentityType.PhoneNumber2; + case 'phone_number_3': + return IdentityType.PhoneNumber3; + default: + return false; + } + }, + getIdentityName: function getIdentityName(identityType) { + switch (identityType) { + case IdentityType.Other: + return 'other'; + case IdentityType.CustomerId: + return 'customerid'; + case IdentityType.Facebook: + return 'facebook'; + case IdentityType.Twitter: + return 'twitter'; + case IdentityType.Google: + return 'google'; + case IdentityType.Microsoft: + return 'microsoft'; + case IdentityType.Yahoo: + return 'yahoo'; + case IdentityType.Email: + return 'email'; + case IdentityType.FacebookCustomAudienceId: + return 'facebookcustomaudienceid'; + case IdentityType.Other2: + return 'other2'; + case IdentityType.Other3: + return 'other3'; + case IdentityType.Other4: + return 'other4'; + case IdentityType.Other5: + return 'other5'; + case IdentityType.Other6: + return 'other6'; + case IdentityType.Other7: + return 'other7'; + case IdentityType.Other8: + return 'other8'; + case IdentityType.Other9: + return 'other9'; + case IdentityType.Other10: + return 'other10'; + case IdentityType.MobileNumber: + return 'mobile_number'; + case IdentityType.PhoneNumber2: + return 'phone_number_2'; + case IdentityType.PhoneNumber3: + return 'phone_number_3'; + default: + return null; + } + }, + // Strips out functions from Identity Types for easier lookups + getValuesAsStrings: function getValuesAsStrings() { + return Object.values(IdentityType).map(function (value) { + return isNumber(value) ? value.toString() : undefined; + }).filter(function (value) { + return value !== undefined; + }); + }, + getNewIdentitiesByName: function getNewIdentitiesByName(newIdentitiesByType) { + var newIdentitiesByName = {}; + var identityTypeValuesAsStrings = IdentityType.getValuesAsStrings(); + for (var key in newIdentitiesByType) { + // IdentityTypes are stored as numbers but are passed in as strings + if (identityTypeValuesAsStrings.includes(key)) { + var identityNameKey = IdentityType.getIdentityName(parseNumber(key)); + newIdentitiesByName[identityNameKey] = newIdentitiesByType[key]; + } + } + return newIdentitiesByName; + } + }; + var ProductActionType = { + Unknown: 0, + AddToCart: 1, + RemoveFromCart: 2, + Checkout: 3, + CheckoutOption: 4, + Click: 5, + ViewDetail: 6, + Purchase: 7, + Refund: 8, + AddToWishlist: 9, + RemoveFromWishlist: 10, + getName: function getName(id) { + switch (id) { + case ProductActionType.AddToCart: + return 'Add to Cart'; + case ProductActionType.RemoveFromCart: + return 'Remove from Cart'; + case ProductActionType.Checkout: + return 'Checkout'; + case ProductActionType.CheckoutOption: + return 'Checkout Option'; + case ProductActionType.Click: + return 'Click'; + case ProductActionType.ViewDetail: + return 'View Detail'; + case ProductActionType.Purchase: + return 'Purchase'; + case ProductActionType.Refund: + return 'Refund'; + case ProductActionType.AddToWishlist: + return 'Add to Wishlist'; + case ProductActionType.RemoveFromWishlist: + return 'Remove from Wishlist'; + default: + return 'Unknown'; + } + }, + // these are the action names used by server and mobile SDKs when expanding a CommerceEvent + getExpansionName: function getExpansionName(id) { + switch (id) { + case ProductActionType.AddToCart: + return 'add_to_cart'; + case ProductActionType.RemoveFromCart: + return 'remove_from_cart'; + case ProductActionType.Checkout: + return 'checkout'; + case ProductActionType.CheckoutOption: + return 'checkout_option'; + case ProductActionType.Click: + return 'click'; + case ProductActionType.ViewDetail: + return 'view_detail'; + case ProductActionType.Purchase: + return 'purchase'; + case ProductActionType.Refund: + return 'refund'; + case ProductActionType.AddToWishlist: + return 'add_to_wishlist'; + case ProductActionType.RemoveFromWishlist: + return 'remove_from_wishlist'; + default: + return 'unknown'; + } + } + }; + var PromotionActionType = { + Unknown: 0, + PromotionView: 1, + PromotionClick: 2, + getName: function getName(id) { + switch (id) { + case PromotionActionType.PromotionView: + return 'view'; + case PromotionActionType.PromotionClick: + return 'click'; + default: + return 'unknown'; + } + }, + // these are the names that the server and mobile SDKs use while expanding CommerceEvent + getExpansionName: function getExpansionName(id) { + switch (id) { + case PromotionActionType.PromotionView: + return 'view'; + case PromotionActionType.PromotionClick: + return 'click'; + default: + return 'unknown'; + } + } + }; + var ProfileMessageType = { + Logout: 3 + }; + var ApplicationTransitionType$1 = { + AppInit: 1 + }; + var PerformanceMarkType = { + SdkStart: 'mp:sdkStart', + JointSdkSelectPlacements: 'mp:jointSdkSelectPlacements', + JointSdkRoktKitInit: 'mp:jointSdkRoktKitInit' + }; + var Types = { + MessageType: MessageType$1, + EventType: EventType, + CommerceEventType: CommerceEventType, + IdentityType: IdentityType, + ProfileMessageType: ProfileMessageType, + ApplicationTransitionType: ApplicationTransitionType$1, + ProductActionType: ProductActionType, + PromotionActionType: PromotionActionType, + Environment: Constants.Environment + }; + + function _typeof$1(o) { + "@babel/helpers - typeof"; + + return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof$1(o); + } + + var SDKProductActionType; + (function (SDKProductActionType) { + SDKProductActionType[SDKProductActionType["Unknown"] = 0] = "Unknown"; + SDKProductActionType[SDKProductActionType["AddToCart"] = 1] = "AddToCart"; + SDKProductActionType[SDKProductActionType["RemoveFromCart"] = 2] = "RemoveFromCart"; + SDKProductActionType[SDKProductActionType["Checkout"] = 3] = "Checkout"; + SDKProductActionType[SDKProductActionType["CheckoutOption"] = 4] = "CheckoutOption"; + SDKProductActionType[SDKProductActionType["Click"] = 5] = "Click"; + SDKProductActionType[SDKProductActionType["ViewDetail"] = 6] = "ViewDetail"; + SDKProductActionType[SDKProductActionType["Purchase"] = 7] = "Purchase"; + SDKProductActionType[SDKProductActionType["Refund"] = 8] = "Refund"; + SDKProductActionType[SDKProductActionType["AddToWishlist"] = 9] = "AddToWishlist"; + SDKProductActionType[SDKProductActionType["RemoveFromWishlist"] = 10] = "RemoveFromWishlist"; + })(SDKProductActionType || (SDKProductActionType = {})); + var LogLevelType = { + None: 'none', + Verbose: 'verbose', + Warning: 'warning', + Error: 'error' + }; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + var dist = {}; + + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + (function (ApplicationInformationOsEnum) { + ApplicationInformationOsEnum["unknown"] = "Unknown"; + ApplicationInformationOsEnum["iOS"] = "IOS"; + ApplicationInformationOsEnum["android"] = "Android"; + ApplicationInformationOsEnum["windowsPhone"] = "WindowsPhone"; + ApplicationInformationOsEnum["mobileWeb"] = "MobileWeb"; + ApplicationInformationOsEnum["unityIOS"] = "UnityIOS"; + ApplicationInformationOsEnum["unityAndroid"] = "UnityAndroid"; + ApplicationInformationOsEnum["desktop"] = "Desktop"; + ApplicationInformationOsEnum["tvOS"] = "TVOS"; + ApplicationInformationOsEnum["roku"] = "Roku"; + ApplicationInformationOsEnum["outOfBand"] = "OutOfBand"; + ApplicationInformationOsEnum["alexa"] = "Alexa"; + ApplicationInformationOsEnum["smartTV"] = "SmartTV"; + ApplicationInformationOsEnum["fireTV"] = "FireTV"; + ApplicationInformationOsEnum["xbox"] = "Xbox"; + })(exports.ApplicationInformationOsEnum || (exports.ApplicationInformationOsEnum = {})); + (function (ApplicationStateTransitionEventEventTypeEnum) { + ApplicationStateTransitionEventEventTypeEnum["applicationStateTransition"] = "application_state_transition"; + })(exports.ApplicationStateTransitionEventEventTypeEnum || (exports.ApplicationStateTransitionEventEventTypeEnum = {})); + (function (ApplicationStateTransitionEventDataApplicationTransitionTypeEnum) { + ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationInitialized"] = "application_initialized"; + ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationExit"] = "application_exit"; + ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationBackground"] = "application_background"; + ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationForeground"] = "application_foreground"; + })(exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum || (exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum = {})); + (function (BatchEnvironmentEnum) { + BatchEnvironmentEnum["unknown"] = "unknown"; + BatchEnvironmentEnum["development"] = "development"; + BatchEnvironmentEnum["production"] = "production"; + })(exports.BatchEnvironmentEnum || (exports.BatchEnvironmentEnum = {})); + (function (BreadcrumbEventEventTypeEnum) { + BreadcrumbEventEventTypeEnum["breadcrumb"] = "breadcrumb"; + })(exports.BreadcrumbEventEventTypeEnum || (exports.BreadcrumbEventEventTypeEnum = {})); + (function (CommerceEventEventTypeEnum) { + CommerceEventEventTypeEnum["commerceEvent"] = "commerce_event"; + })(exports.CommerceEventEventTypeEnum || (exports.CommerceEventEventTypeEnum = {})); + (function (CommerceEventDataCustomEventTypeEnum) { + CommerceEventDataCustomEventTypeEnum["addToCart"] = "add_to_cart"; + CommerceEventDataCustomEventTypeEnum["removeFromCart"] = "remove_from_cart"; + CommerceEventDataCustomEventTypeEnum["checkout"] = "checkout"; + CommerceEventDataCustomEventTypeEnum["checkoutOption"] = "checkout_option"; + CommerceEventDataCustomEventTypeEnum["click"] = "click"; + CommerceEventDataCustomEventTypeEnum["viewDetail"] = "view_detail"; + CommerceEventDataCustomEventTypeEnum["purchase"] = "purchase"; + CommerceEventDataCustomEventTypeEnum["refund"] = "refund"; + CommerceEventDataCustomEventTypeEnum["promotionView"] = "promotion_view"; + CommerceEventDataCustomEventTypeEnum["promotionClick"] = "promotion_click"; + CommerceEventDataCustomEventTypeEnum["addToWishlist"] = "add_to_wishlist"; + CommerceEventDataCustomEventTypeEnum["removeFromWishlist"] = "remove_from_wishlist"; + CommerceEventDataCustomEventTypeEnum["impression"] = "impression"; + })(exports.CommerceEventDataCustomEventTypeEnum || (exports.CommerceEventDataCustomEventTypeEnum = {})); + (function (CrashReportEventEventTypeEnum) { + CrashReportEventEventTypeEnum["crashReport"] = "crash_report"; + })(exports.CrashReportEventEventTypeEnum || (exports.CrashReportEventEventTypeEnum = {})); + (function (CustomEventEventTypeEnum) { + CustomEventEventTypeEnum["customEvent"] = "custom_event"; + })(exports.CustomEventEventTypeEnum || (exports.CustomEventEventTypeEnum = {})); + (function (CustomEventDataCustomEventTypeEnum) { + CustomEventDataCustomEventTypeEnum["navigation"] = "navigation"; + CustomEventDataCustomEventTypeEnum["location"] = "location"; + CustomEventDataCustomEventTypeEnum["search"] = "search"; + CustomEventDataCustomEventTypeEnum["transaction"] = "transaction"; + CustomEventDataCustomEventTypeEnum["userContent"] = "user_content"; + CustomEventDataCustomEventTypeEnum["userPreference"] = "user_preference"; + CustomEventDataCustomEventTypeEnum["social"] = "social"; + CustomEventDataCustomEventTypeEnum["media"] = "media"; + CustomEventDataCustomEventTypeEnum["other"] = "other"; + CustomEventDataCustomEventTypeEnum["unknown"] = "unknown"; + })(exports.CustomEventDataCustomEventTypeEnum || (exports.CustomEventDataCustomEventTypeEnum = {})); + (function (DeviceCurrentStateDeviceOrientationEnum) { + DeviceCurrentStateDeviceOrientationEnum["portrait"] = "portrait"; + DeviceCurrentStateDeviceOrientationEnum["portraitUpsideDown"] = "portrait_upside_down"; + DeviceCurrentStateDeviceOrientationEnum["landscape"] = "landscape"; + DeviceCurrentStateDeviceOrientationEnum["landscapeLeft"] = "LandscapeLeft"; + DeviceCurrentStateDeviceOrientationEnum["landscapeRight"] = "LandscapeRight"; + DeviceCurrentStateDeviceOrientationEnum["faceUp"] = "FaceUp"; + DeviceCurrentStateDeviceOrientationEnum["faceDown"] = "FaceDown"; + DeviceCurrentStateDeviceOrientationEnum["square"] = "Square"; + })(exports.DeviceCurrentStateDeviceOrientationEnum || (exports.DeviceCurrentStateDeviceOrientationEnum = {})); + (function (DeviceCurrentStateStatusBarOrientationEnum) { + DeviceCurrentStateStatusBarOrientationEnum["portrait"] = "portrait"; + DeviceCurrentStateStatusBarOrientationEnum["portraitUpsideDown"] = "portrait_upside_down"; + DeviceCurrentStateStatusBarOrientationEnum["landscape"] = "landscape"; + DeviceCurrentStateStatusBarOrientationEnum["landscapeLeft"] = "LandscapeLeft"; + DeviceCurrentStateStatusBarOrientationEnum["landscapeRight"] = "LandscapeRight"; + DeviceCurrentStateStatusBarOrientationEnum["faceUp"] = "FaceUp"; + DeviceCurrentStateStatusBarOrientationEnum["faceDown"] = "FaceDown"; + DeviceCurrentStateStatusBarOrientationEnum["square"] = "Square"; + })(exports.DeviceCurrentStateStatusBarOrientationEnum || (exports.DeviceCurrentStateStatusBarOrientationEnum = {})); + (function (DeviceInformationPlatformEnum) { + DeviceInformationPlatformEnum["iOS"] = "iOS"; + DeviceInformationPlatformEnum["android"] = "Android"; + DeviceInformationPlatformEnum["web"] = "web"; + DeviceInformationPlatformEnum["desktop"] = "desktop"; + DeviceInformationPlatformEnum["tvOS"] = "tvOS"; + DeviceInformationPlatformEnum["roku"] = "roku"; + DeviceInformationPlatformEnum["outOfBand"] = "out_of_band"; + DeviceInformationPlatformEnum["smartTV"] = "smart_tv"; + DeviceInformationPlatformEnum["xbox"] = "xbox"; + })(exports.DeviceInformationPlatformEnum || (exports.DeviceInformationPlatformEnum = {})); + (function (EventTypeEnum) { + EventTypeEnum["unknown"] = "unknown"; + EventTypeEnum["sessionStart"] = "session_start"; + EventTypeEnum["sessionEnd"] = "session_end"; + EventTypeEnum["screenView"] = "screen_view"; + EventTypeEnum["customEvent"] = "custom_event"; + EventTypeEnum["crashReport"] = "crash_report"; + EventTypeEnum["optOut"] = "opt_out"; + EventTypeEnum["firstRun"] = "first_run"; + EventTypeEnum["preAttribution"] = "pre_attribution"; + EventTypeEnum["pushRegistration"] = "push_registration"; + EventTypeEnum["applicationStateTransition"] = "application_state_transition"; + EventTypeEnum["pushMessage"] = "push_message"; + EventTypeEnum["networkPerformance"] = "network_performance"; + EventTypeEnum["breadcrumb"] = "breadcrumb"; + EventTypeEnum["profile"] = "profile"; + EventTypeEnum["pushReaction"] = "push_reaction"; + EventTypeEnum["commerceEvent"] = "commerce_event"; + EventTypeEnum["userAttributeChange"] = "user_attribute_change"; + EventTypeEnum["userIdentityChange"] = "user_identity_change"; + EventTypeEnum["uninstall"] = "uninstall"; + EventTypeEnum["validationResult"] = "validation_result"; + })(exports.EventTypeEnum || (exports.EventTypeEnum = {})); + (function (IdentityTypeEnum) { + IdentityTypeEnum["other"] = "other"; + IdentityTypeEnum["customerId"] = "customer_id"; + IdentityTypeEnum["facebook"] = "facebook"; + IdentityTypeEnum["twitter"] = "twitter"; + IdentityTypeEnum["google"] = "google"; + IdentityTypeEnum["microsoft"] = "microsoft"; + IdentityTypeEnum["yahoo"] = "yahoo"; + IdentityTypeEnum["email"] = "email"; + IdentityTypeEnum["alias"] = "alias"; + IdentityTypeEnum["facebookCustomAudienceId"] = "facebook_custom_audience_id"; + IdentityTypeEnum["otherId2"] = "other_id_2"; + IdentityTypeEnum["otherId3"] = "other_id_3"; + IdentityTypeEnum["otherId4"] = "other_id_4"; + IdentityTypeEnum["otherId5"] = "other_id_5"; + IdentityTypeEnum["otherId6"] = "other_id_6"; + IdentityTypeEnum["otherId7"] = "other_id_7"; + IdentityTypeEnum["otherId8"] = "other_id_8"; + IdentityTypeEnum["otherId9"] = "other_id_9"; + IdentityTypeEnum["otherId10"] = "other_id_10"; + IdentityTypeEnum["mobileNumber"] = "mobile_number"; + IdentityTypeEnum["phoneNumber2"] = "phone_number_2"; + IdentityTypeEnum["phoneNumber3"] = "phone_number_3"; + })(exports.IdentityTypeEnum || (exports.IdentityTypeEnum = {})); + (function (NetworkPerformanceEventEventTypeEnum) { + NetworkPerformanceEventEventTypeEnum["networkPerformance"] = "network_performance"; + })(exports.NetworkPerformanceEventEventTypeEnum || (exports.NetworkPerformanceEventEventTypeEnum = {})); + (function (OptOutEventEnum) { + OptOutEventEnum["optOut"] = "opt_out"; + })(exports.OptOutEventEnum || (exports.OptOutEventEnum = {})); + (function (ProductActionActionEnum) { + ProductActionActionEnum["unknown"] = "unknown"; + ProductActionActionEnum["addToCart"] = "add_to_cart"; + ProductActionActionEnum["removeFromCart"] = "remove_from_cart"; + ProductActionActionEnum["checkout"] = "checkout"; + ProductActionActionEnum["checkoutOption"] = "checkout_option"; + ProductActionActionEnum["click"] = "click"; + ProductActionActionEnum["viewDetail"] = "view_detail"; + ProductActionActionEnum["purchase"] = "purchase"; + ProductActionActionEnum["refund"] = "refund"; + ProductActionActionEnum["addToWishlist"] = "add_to_wishlist"; + ProductActionActionEnum["removeFromWishlist"] = "remove_from_wish_list"; + })(exports.ProductActionActionEnum || (exports.ProductActionActionEnum = {})); + (function (ProfileEventEventTypeEnum) { + ProfileEventEventTypeEnum["profile"] = "profile"; + })(exports.ProfileEventEventTypeEnum || (exports.ProfileEventEventTypeEnum = {})); + (function (ProfileEventDataProfileEventTypeEnum) { + ProfileEventDataProfileEventTypeEnum["signup"] = "signup"; + ProfileEventDataProfileEventTypeEnum["login"] = "login"; + ProfileEventDataProfileEventTypeEnum["logout"] = "logout"; + ProfileEventDataProfileEventTypeEnum["update"] = "update"; + ProfileEventDataProfileEventTypeEnum["delete"] = "delete"; + })(exports.ProfileEventDataProfileEventTypeEnum || (exports.ProfileEventDataProfileEventTypeEnum = {})); + (function (PromotionActionActionEnum) { + PromotionActionActionEnum["view"] = "view"; + PromotionActionActionEnum["click"] = "click"; + })(exports.PromotionActionActionEnum || (exports.PromotionActionActionEnum = {})); + (function (PushMessageEventEventTypeEnum) { + PushMessageEventEventTypeEnum["pushMessage"] = "push_message"; + })(exports.PushMessageEventEventTypeEnum || (exports.PushMessageEventEventTypeEnum = {})); + (function (PushMessageEventDataPushMessageTypeEnum) { + PushMessageEventDataPushMessageTypeEnum["sent"] = "sent"; + PushMessageEventDataPushMessageTypeEnum["received"] = "received"; + PushMessageEventDataPushMessageTypeEnum["action"] = "action"; + })(exports.PushMessageEventDataPushMessageTypeEnum || (exports.PushMessageEventDataPushMessageTypeEnum = {})); + (function (PushMessageEventDataApplicationStateEnum) { + PushMessageEventDataApplicationStateEnum["notRunning"] = "not_running"; + PushMessageEventDataApplicationStateEnum["background"] = "background"; + PushMessageEventDataApplicationStateEnum["foreground"] = "foreground"; + })(exports.PushMessageEventDataApplicationStateEnum || (exports.PushMessageEventDataApplicationStateEnum = {})); + (function (PushMessageEventDataPushMessageBehaviorEnum) { + PushMessageEventDataPushMessageBehaviorEnum["received"] = "Received"; + PushMessageEventDataPushMessageBehaviorEnum["directOpen"] = "DirectOpen"; + PushMessageEventDataPushMessageBehaviorEnum["read"] = "Read"; + PushMessageEventDataPushMessageBehaviorEnum["influencedOpen"] = "InfluencedOpen"; + PushMessageEventDataPushMessageBehaviorEnum["displayed"] = "Displayed"; + })(exports.PushMessageEventDataPushMessageBehaviorEnum || (exports.PushMessageEventDataPushMessageBehaviorEnum = {})); + (function (PushRegistrationEventEventTypeEnum) { + PushRegistrationEventEventTypeEnum["pushRegistration"] = "push_registration"; + })(exports.PushRegistrationEventEventTypeEnum || (exports.PushRegistrationEventEventTypeEnum = {})); + (function (SessionEndEventEventTypeEnum) { + SessionEndEventEventTypeEnum["sessionEnd"] = "session_end"; + })(exports.SessionEndEventEventTypeEnum || (exports.SessionEndEventEventTypeEnum = {})); + (function (SessionStartEventEventTypeEnum) { + SessionStartEventEventTypeEnum["sessionStart"] = "session_start"; + })(exports.SessionStartEventEventTypeEnum || (exports.SessionStartEventEventTypeEnum = {})); + (function (SourceInformationChannelEnum) { + SourceInformationChannelEnum["native"] = "native"; + SourceInformationChannelEnum["javascript"] = "javascript"; + SourceInformationChannelEnum["pixel"] = "pixel"; + SourceInformationChannelEnum["desktop"] = "desktop"; + SourceInformationChannelEnum["partner"] = "partner"; + SourceInformationChannelEnum["serverToServer"] = "server_to_server"; + })(exports.SourceInformationChannelEnum || (exports.SourceInformationChannelEnum = {})); + (function (UserAttributeChangeEventEventTypeEnum) { + UserAttributeChangeEventEventTypeEnum["userAttributeChange"] = "user_attribute_change"; + })(exports.UserAttributeChangeEventEventTypeEnum || (exports.UserAttributeChangeEventEventTypeEnum = {})); + (function (UserIdentityChangeEventEventTypeEnum) { + UserIdentityChangeEventEventTypeEnum["userIdentityChange"] = "user_identity_change"; + })(exports.UserIdentityChangeEventEventTypeEnum || (exports.UserIdentityChangeEventEventTypeEnum = {})); + } (dist)); + + var SDKIdentityTypeEnum; + (function (SDKIdentityTypeEnum) { + SDKIdentityTypeEnum["other"] = "other"; + SDKIdentityTypeEnum["customerId"] = "customerid"; + SDKIdentityTypeEnum["facebook"] = "facebook"; + SDKIdentityTypeEnum["twitter"] = "twitter"; + SDKIdentityTypeEnum["google"] = "google"; + SDKIdentityTypeEnum["microsoft"] = "microsoft"; + SDKIdentityTypeEnum["yahoo"] = "yahoo"; + SDKIdentityTypeEnum["email"] = "email"; + SDKIdentityTypeEnum["alias"] = "alias"; + SDKIdentityTypeEnum["facebookCustomAudienceId"] = "facebookcustomaudienceid"; + SDKIdentityTypeEnum["otherId2"] = "other2"; + SDKIdentityTypeEnum["otherId3"] = "other3"; + SDKIdentityTypeEnum["otherId4"] = "other4"; + SDKIdentityTypeEnum["otherId5"] = "other5"; + SDKIdentityTypeEnum["otherId6"] = "other6"; + SDKIdentityTypeEnum["otherId7"] = "other7"; + SDKIdentityTypeEnum["otherId8"] = "other8"; + SDKIdentityTypeEnum["otherId9"] = "other9"; + SDKIdentityTypeEnum["otherId10"] = "other10"; + SDKIdentityTypeEnum["mobileNumber"] = "mobile_number"; + SDKIdentityTypeEnum["phoneNumber2"] = "phone_number_2"; + SDKIdentityTypeEnum["phoneNumber3"] = "phone_number_3"; + })(SDKIdentityTypeEnum || (SDKIdentityTypeEnum = {})); + + var FeatureFlags$2 = Constants.FeatureFlags; + var CaptureIntegrationSpecificIds$1 = FeatureFlags$2.CaptureIntegrationSpecificIds, + CaptureIntegrationSpecificIdsV2$1 = FeatureFlags$2.CaptureIntegrationSpecificIdsV2; + function convertEvents(mpid, sdkEvents, mpInstance) { + if (!mpid) { + return null; + } + if (!sdkEvents || sdkEvents.length < 1) { + return null; + } + var _IntegrationCapture = mpInstance._IntegrationCapture, + _Helpers = mpInstance._Helpers; + var getFeatureFlag = _Helpers.getFeatureFlag; + var user = mpInstance.Identity.getCurrentUser(); + var uploadEvents = []; + var lastEvent = null; + for (var _i = 0, sdkEvents_1 = sdkEvents; _i < sdkEvents_1.length; _i++) { + var sdkEvent = sdkEvents_1[_i]; + if (sdkEvent) { + lastEvent = sdkEvent; + var baseEvent = convertEvent(sdkEvent); + if (baseEvent) { + uploadEvents.push(baseEvent); + } + } + } + if (!lastEvent) { + return null; + } + var currentConsentState = null; + // Add the consent state from either the Last Event or the user + if (!isEmpty(lastEvent.ConsentState)) { + currentConsentState = lastEvent.ConsentState; + } else if (!isEmpty(user)) { + currentConsentState = user.getConsentState(); + } + var upload = { + source_request_id: mpInstance._Helpers.generateUniqueId(), + mpid: mpid, + timestamp_unixtime_ms: new Date().getTime(), + environment: lastEvent.Debug ? dist.BatchEnvironmentEnum.development : dist.BatchEnvironmentEnum.production, + events: uploadEvents, + mp_deviceid: lastEvent.DeviceId, + sdk_version: lastEvent.SDKVersion, + // TODO: Refactor this to read from _Store or a global config + application_info: { + application_version: lastEvent.AppVersion, + application_name: lastEvent.AppName, + "package": lastEvent.Package, + sideloaded_kits_count: mpInstance._Store.sideloadedKitsCount + }, + device_info: { + platform: dist.DeviceInformationPlatformEnum.web, + screen_width: typeof window !== 'undefined' && typeof window.screen !== 'undefined' ? window.screen.width : 0, + screen_height: typeof window !== 'undefined' && typeof window.screen !== 'undefined' ? window.screen.height : 0 + }, + user_attributes: lastEvent.UserAttributes, + user_identities: convertUserIdentities(lastEvent.UserIdentities), + consent_state: convertConsentState(currentConsentState), + integration_attributes: lastEvent.IntegrationAttributes + }; + if (lastEvent.DataPlan && lastEvent.DataPlan.PlanId) { + upload.context = { + data_plan: { + plan_id: lastEvent.DataPlan.PlanId, + plan_version: lastEvent.DataPlan.PlanVersion || undefined + } + }; + } + // https://go.mparticle.com/work/SQDSDKS-7639 + var integrationSpecificIds = getFeatureFlag && Boolean(getFeatureFlag(CaptureIntegrationSpecificIds$1)); + var integrationSpecificIdsV2 = getFeatureFlag && getFeatureFlag(CaptureIntegrationSpecificIdsV2$1); + var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; + if (isIntegrationCaptureEnabled) { + var capturedPartnerIdentities = _IntegrationCapture === null || _IntegrationCapture === void 0 ? void 0 : _IntegrationCapture.getClickIdsAsPartnerIdentities(); + if (!isEmpty(capturedPartnerIdentities)) { + upload.partner_identities = capturedPartnerIdentities; + } + } + return upload; + } + function convertConsentState(sdkConsentState) { + if (isEmpty(sdkConsentState)) { + return null; + } + var consentState = { + gdpr: convertGdprConsentState(sdkConsentState.getGDPRConsentState()), + ccpa: convertCcpaConsentState(sdkConsentState.getCCPAConsentState()) + }; + return consentState; + } + function convertGdprConsentState(sdkGdprConsentState) { + if (!sdkGdprConsentState) { + return null; + } + var state = {}; + for (var purpose in sdkGdprConsentState) { + if (sdkGdprConsentState.hasOwnProperty(purpose)) { + state[purpose] = { + consented: sdkGdprConsentState[purpose].Consented, + hardware_id: sdkGdprConsentState[purpose].HardwareId, + document: sdkGdprConsentState[purpose].ConsentDocument, + timestamp_unixtime_ms: sdkGdprConsentState[purpose].Timestamp, + location: sdkGdprConsentState[purpose].Location + }; + } + } + return state; + } + function convertCcpaConsentState(sdkCcpaConsentState) { + if (!sdkCcpaConsentState) { + return null; + } + var state = { + data_sale_opt_out: { + consented: sdkCcpaConsentState.Consented, + hardware_id: sdkCcpaConsentState.HardwareId, + document: sdkCcpaConsentState.ConsentDocument, + timestamp_unixtime_ms: sdkCcpaConsentState.Timestamp, + location: sdkCcpaConsentState.Location + } + }; + return state; + } + function convertUserIdentities(sdkUserIdentities) { + if (!sdkUserIdentities || !sdkUserIdentities.length) { + return null; + } + var batchIdentities = {}; + for (var _i = 0, sdkUserIdentities_1 = sdkUserIdentities; _i < sdkUserIdentities_1.length; _i++) { + var identity = sdkUserIdentities_1[_i]; + switch (identity.Type) { + case Types.IdentityType.CustomerId: + batchIdentities.customer_id = identity.Identity; + break; + case Types.IdentityType.Email: + batchIdentities.email = identity.Identity; + break; + case Types.IdentityType.Facebook: + batchIdentities.facebook = identity.Identity; + break; + case Types.IdentityType.FacebookCustomAudienceId: + batchIdentities.facebook_custom_audience_id = identity.Identity; + break; + case Types.IdentityType.Google: + batchIdentities.google = identity.Identity; + break; + case Types.IdentityType.Microsoft: + batchIdentities.microsoft = identity.Identity; + break; + case Types.IdentityType.Other: + batchIdentities.other = identity.Identity; + break; + case Types.IdentityType.Other2: + batchIdentities.other_id_2 = identity.Identity; + break; + case Types.IdentityType.Other3: + batchIdentities.other_id_3 = identity.Identity; + break; + case Types.IdentityType.Other4: + batchIdentities.other_id_4 = identity.Identity; + break; + case Types.IdentityType.Other5: + batchIdentities.other_id_5 = identity.Identity; + break; + case Types.IdentityType.Other6: + batchIdentities.other_id_6 = identity.Identity; + break; + case Types.IdentityType.Other7: + batchIdentities.other_id_7 = identity.Identity; + break; + case Types.IdentityType.Other8: + batchIdentities.other_id_8 = identity.Identity; + break; + case Types.IdentityType.Other9: + batchIdentities.other_id_9 = identity.Identity; + break; + case Types.IdentityType.Other10: + batchIdentities.other_id_10 = identity.Identity; + break; + case Types.IdentityType.MobileNumber: + batchIdentities.mobile_number = identity.Identity; + break; + case Types.IdentityType.PhoneNumber2: + batchIdentities.phone_number_2 = identity.Identity; + break; + case Types.IdentityType.PhoneNumber3: + batchIdentities.phone_number_3 = identity.Identity; + break; + } + } + return batchIdentities; + } + function convertEvent(sdkEvent) { + if (!sdkEvent) { + return null; + } + switch (sdkEvent.EventDataType) { + case Types.MessageType.AppStateTransition: + return convertAST(sdkEvent); + case Types.MessageType.Commerce: + return convertCommerceEvent(sdkEvent); + case Types.MessageType.CrashReport: + return convertCrashReportEvent(sdkEvent); + case Types.MessageType.OptOut: + return convertOptOutEvent(sdkEvent); + case Types.MessageType.PageEvent: + // Note: Media Events are also sent as PageEvents/CustomEvents + return convertCustomEvent(sdkEvent); + case Types.MessageType.PageView: + return convertPageViewEvent(sdkEvent); + case Types.MessageType.Profile: + //deprecated and not supported by the web SDK + return null; + case Types.MessageType.SessionEnd: + return convertSessionEndEvent(sdkEvent); + case Types.MessageType.SessionStart: + return convertSessionStartEvent(sdkEvent); + case Types.MessageType.UserAttributeChange: + return convertUserAttributeChangeEvent(sdkEvent); + case Types.MessageType.UserIdentityChange: + return convertUserIdentityChangeEvent(sdkEvent); + } + return null; + } + function convertProductActionType(actionType) { + if (!actionType) { + return dist.ProductActionActionEnum.unknown; + } + switch (actionType) { + case SDKProductActionType.AddToCart: + return dist.ProductActionActionEnum.addToCart; + case SDKProductActionType.AddToWishlist: + return dist.ProductActionActionEnum.addToWishlist; + case SDKProductActionType.Checkout: + return dist.ProductActionActionEnum.checkout; + case SDKProductActionType.CheckoutOption: + return dist.ProductActionActionEnum.checkoutOption; + case SDKProductActionType.Click: + return dist.ProductActionActionEnum.click; + case SDKProductActionType.Purchase: + return dist.ProductActionActionEnum.purchase; + case SDKProductActionType.Refund: + return dist.ProductActionActionEnum.refund; + case SDKProductActionType.RemoveFromCart: + return dist.ProductActionActionEnum.removeFromCart; + case SDKProductActionType.RemoveFromWishlist: + return dist.ProductActionActionEnum.removeFromWishlist; + case SDKProductActionType.ViewDetail: + return dist.ProductActionActionEnum.viewDetail; + default: + return dist.ProductActionActionEnum.unknown; + } + } + function convertProductAction(sdkEvent) { + if (!sdkEvent.ProductAction) { + return null; + } + var productAction = { + action: convertProductActionType(sdkEvent.ProductAction.ProductActionType), + checkout_step: sdkEvent.ProductAction.CheckoutStep, + checkout_options: sdkEvent.ProductAction.CheckoutOptions, + transaction_id: sdkEvent.ProductAction.TransactionId, + affiliation: sdkEvent.ProductAction.Affiliation, + total_amount: sdkEvent.ProductAction.TotalAmount, + tax_amount: sdkEvent.ProductAction.TaxAmount, + shipping_amount: sdkEvent.ProductAction.ShippingAmount, + coupon_code: sdkEvent.ProductAction.CouponCode, + products: convertProducts(sdkEvent.ProductAction.ProductList) + }; + return productAction; + } + function convertProducts(sdkProducts) { + if (!sdkProducts || !sdkProducts.length) { + return null; + } + var products = []; + for (var _i = 0, sdkProducts_1 = sdkProducts; _i < sdkProducts_1.length; _i++) { + var sdkProduct = sdkProducts_1[_i]; + var product = { + id: sdkProduct.Sku, + name: sdkProduct.Name, + brand: sdkProduct.Brand, + category: sdkProduct.Category, + variant: sdkProduct.Variant, + total_product_amount: sdkProduct.TotalAmount, + position: sdkProduct.Position, + price: sdkProduct.Price, + quantity: sdkProduct.Quantity, + coupon_code: sdkProduct.CouponCode, + custom_attributes: sdkProduct.Attributes + }; + products.push(product); + } + return products; + } + function convertPromotionAction(sdkEvent) { + if (!sdkEvent.PromotionAction) { + return null; + } + var promotionAction = { + action: sdkEvent.PromotionAction.PromotionActionType, + promotions: convertPromotions(sdkEvent.PromotionAction.PromotionList) + }; + return promotionAction; + } + function convertPromotions(sdkPromotions) { + if (!sdkPromotions || !sdkPromotions.length) { + return null; + } + var promotions = []; + for (var _i = 0, sdkPromotions_1 = sdkPromotions; _i < sdkPromotions_1.length; _i++) { + var sdkPromotion = sdkPromotions_1[_i]; + var promotion = { + id: sdkPromotion.Id, + name: sdkPromotion.Name, + creative: sdkPromotion.Creative, + position: sdkPromotion.Position + }; + promotions.push(promotion); + } + return promotions; + } + function convertImpressions(sdkEvent) { + if (!sdkEvent.ProductImpressions) { + return null; + } + var impressions = []; + for (var _i = 0, _a = sdkEvent.ProductImpressions; _i < _a.length; _i++) { + var sdkImpression = _a[_i]; + var impression = { + product_impression_list: sdkImpression.ProductImpressionList, + products: convertProducts(sdkImpression.ProductList) + }; + impressions.push(impression); + } + return impressions; + } + function convertShoppingCart(sdkEvent) { + if (!sdkEvent.ShoppingCart || !sdkEvent.ShoppingCart.ProductList || !sdkEvent.ShoppingCart.ProductList.length) { + return null; + } + var shoppingCart = { + products: convertProducts(sdkEvent.ShoppingCart.ProductList) + }; + return shoppingCart; + } + function convertCommerceEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var commerceEventData = { + custom_flags: sdkEvent.CustomFlags, + product_action: convertProductAction(sdkEvent), + promotion_action: convertPromotionAction(sdkEvent), + product_impressions: convertImpressions(sdkEvent), + shopping_cart: convertShoppingCart(sdkEvent), + currency_code: sdkEvent.CurrencyCode + }; + commerceEventData = Object.assign(commerceEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.commerceEvent, + data: commerceEventData + }; + } + function convertCrashReportEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var crashReportEventData = { + message: sdkEvent.EventName + }; + crashReportEventData = Object.assign(crashReportEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.crashReport, + data: crashReportEventData + }; + } + function convertAST(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + // Determine the transition type based on IsBackgroundAST flag + var _a = dist.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum, + applicationBackground = _a.applicationBackground, + applicationInitialized = _a.applicationInitialized; + var transitionType = sdkEvent.IsBackgroundAST ? applicationBackground : applicationInitialized; + var astEventData = { + application_transition_type: transitionType, + is_first_run: sdkEvent.IsFirstRun, + is_upgrade: false, + launch_referral: sdkEvent.LaunchReferral + }; + astEventData = Object.assign(astEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.applicationStateTransition, + data: astEventData + }; + } + function convertSessionEndEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var sessionEndEventData = { + session_duration_ms: sdkEvent.SessionLength + //note: External Events DTO does not support the session mpids array as of this time. + //spanning_mpids: sdkEvent.SessionMpids + }; + + sessionEndEventData = Object.assign(sessionEndEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.sessionEnd, + data: sessionEndEventData + }; + } + function convertSessionStartEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var sessionStartEventData = {}; + sessionStartEventData = Object.assign(sessionStartEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.sessionStart, + data: sessionStartEventData + }; + } + function convertPageViewEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var screenViewEventData = { + custom_flags: sdkEvent.CustomFlags, + screen_name: sdkEvent.EventName + }; + screenViewEventData = Object.assign(screenViewEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.screenView, + data: screenViewEventData + }; + } + function convertOptOutEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var optOutEventData = { + is_opted_out: sdkEvent.OptOut + }; + optOutEventData = Object.assign(optOutEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.optOut, + data: optOutEventData + }; + } + function convertCustomEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var customEventData = { + custom_event_type: convertSdkEventType(sdkEvent.EventCategory), + custom_flags: sdkEvent.CustomFlags, + event_name: sdkEvent.EventName + }; + customEventData = Object.assign(customEventData, commonEventData); + return { + event_type: dist.EventTypeEnum.customEvent, + data: customEventData + }; + } + function convertSdkEventType(sdkEventType) { + switch (sdkEventType) { + case Types.EventType.Other: + return dist.CustomEventDataCustomEventTypeEnum.other; + case Types.EventType.Location: + return dist.CustomEventDataCustomEventTypeEnum.location; + case Types.EventType.Navigation: + return dist.CustomEventDataCustomEventTypeEnum.navigation; + case Types.EventType.Search: + return dist.CustomEventDataCustomEventTypeEnum.search; + case Types.EventType.Social: + return dist.CustomEventDataCustomEventTypeEnum.social; + case Types.EventType.Transaction: + return dist.CustomEventDataCustomEventTypeEnum.transaction; + case Types.EventType.UserContent: + return dist.CustomEventDataCustomEventTypeEnum.userContent; + case Types.EventType.UserPreference: + return dist.CustomEventDataCustomEventTypeEnum.userPreference; + case Types.EventType.Media: + return dist.CustomEventDataCustomEventTypeEnum.media; + case Types.CommerceEventType.ProductAddToCart: + return dist.CommerceEventDataCustomEventTypeEnum.addToCart; + case Types.CommerceEventType.ProductAddToWishlist: + return dist.CommerceEventDataCustomEventTypeEnum.addToWishlist; + case Types.CommerceEventType.ProductCheckout: + return dist.CommerceEventDataCustomEventTypeEnum.checkout; + case Types.CommerceEventType.ProductCheckoutOption: + return dist.CommerceEventDataCustomEventTypeEnum.checkoutOption; + case Types.CommerceEventType.ProductClick: + return dist.CommerceEventDataCustomEventTypeEnum.click; + case Types.CommerceEventType.ProductImpression: + return dist.CommerceEventDataCustomEventTypeEnum.impression; + case Types.CommerceEventType.ProductPurchase: + return dist.CommerceEventDataCustomEventTypeEnum.purchase; + case Types.CommerceEventType.ProductRefund: + return dist.CommerceEventDataCustomEventTypeEnum.refund; + case Types.CommerceEventType.ProductRemoveFromCart: + return dist.CommerceEventDataCustomEventTypeEnum.removeFromCart; + case Types.CommerceEventType.ProductRemoveFromWishlist: + return dist.CommerceEventDataCustomEventTypeEnum.removeFromWishlist; + case Types.CommerceEventType.ProductViewDetail: + return dist.CommerceEventDataCustomEventTypeEnum.viewDetail; + case Types.CommerceEventType.PromotionClick: + return dist.CommerceEventDataCustomEventTypeEnum.promotionClick; + case Types.CommerceEventType.PromotionView: + return dist.CommerceEventDataCustomEventTypeEnum.promotionView; + default: + return dist.CustomEventDataCustomEventTypeEnum.unknown; + } + } + function convertBaseEventData(sdkEvent) { + var commonEventData = { + timestamp_unixtime_ms: sdkEvent.Timestamp, + session_uuid: sdkEvent.SessionId, + session_start_unixtime_ms: sdkEvent.SessionStartDate, + custom_attributes: sdkEvent.EventAttributes, + location: convertSDKLocation(sdkEvent.Location), + source_message_id: sdkEvent.SourceMessageId, + active_time_on_site_ms: sdkEvent.ActiveTimeOnSite + }; + return commonEventData; + } + function convertSDKLocation(sdkEventLocation) { + if (sdkEventLocation && Object.keys(sdkEventLocation).length) { + return { + latitude: sdkEventLocation.lat, + longitude: sdkEventLocation.lng + }; + } + return null; + } + function convertUserAttributeChangeEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var userAttributeChangeEvent = { + user_attribute_name: sdkEvent.UserAttributeChanges.UserAttributeName, + "new": sdkEvent.UserAttributeChanges.New, + old: sdkEvent.UserAttributeChanges.Old, + deleted: sdkEvent.UserAttributeChanges.Deleted, + is_new_attribute: sdkEvent.UserAttributeChanges.IsNewAttribute + }; + userAttributeChangeEvent = __assign(__assign({}, userAttributeChangeEvent), commonEventData); + return { + event_type: dist.EventTypeEnum.userAttributeChange, + data: userAttributeChangeEvent + }; + } + function convertUserIdentityChangeEvent(sdkEvent) { + var commonEventData = convertBaseEventData(sdkEvent); + var userIdentityChangeEvent = { + "new": { + identity_type: convertUserIdentityTypeToServerIdentityType(sdkEvent.UserIdentityChanges.New.IdentityType), + identity: sdkEvent.UserIdentityChanges.New.Identity || null, + timestamp_unixtime_ms: sdkEvent.Timestamp, + created_this_batch: sdkEvent.UserIdentityChanges.New.CreatedThisBatch + }, + old: { + identity_type: convertUserIdentityTypeToServerIdentityType(sdkEvent.UserIdentityChanges.Old.IdentityType), + identity: sdkEvent.UserIdentityChanges.Old.Identity || null, + timestamp_unixtime_ms: sdkEvent.Timestamp, + created_this_batch: sdkEvent.UserIdentityChanges.Old.CreatedThisBatch + } + }; + userIdentityChangeEvent = Object.assign(userIdentityChangeEvent, commonEventData); + return { + event_type: dist.EventTypeEnum.userIdentityChange, + data: userIdentityChangeEvent + }; + } + function convertUserIdentityTypeToServerIdentityType(identityType) { + switch (identityType) { + case SDKIdentityTypeEnum.other: + return dist.IdentityTypeEnum.other; + case SDKIdentityTypeEnum.customerId: + return dist.IdentityTypeEnum.customerId; + case SDKIdentityTypeEnum.facebook: + return dist.IdentityTypeEnum.facebook; + case SDKIdentityTypeEnum.twitter: + return dist.IdentityTypeEnum.twitter; + case SDKIdentityTypeEnum.google: + return dist.IdentityTypeEnum.google; + case SDKIdentityTypeEnum.microsoft: + return dist.IdentityTypeEnum.microsoft; + case SDKIdentityTypeEnum.yahoo: + return dist.IdentityTypeEnum.yahoo; + case SDKIdentityTypeEnum.email: + return dist.IdentityTypeEnum.email; + case SDKIdentityTypeEnum.alias: + return dist.IdentityTypeEnum.alias; + case SDKIdentityTypeEnum.facebookCustomAudienceId: + return dist.IdentityTypeEnum.facebookCustomAudienceId; + case SDKIdentityTypeEnum.otherId2: + return dist.IdentityTypeEnum.otherId2; + case SDKIdentityTypeEnum.otherId3: + return dist.IdentityTypeEnum.otherId3; + case SDKIdentityTypeEnum.otherId4: + return dist.IdentityTypeEnum.otherId4; + case SDKIdentityTypeEnum.otherId5: + return dist.IdentityTypeEnum.otherId5; + case SDKIdentityTypeEnum.otherId6: + return dist.IdentityTypeEnum.otherId6; + case SDKIdentityTypeEnum.otherId7: + return dist.IdentityTypeEnum.otherId7; + case SDKIdentityTypeEnum.otherId8: + return dist.IdentityTypeEnum.otherId8; + case SDKIdentityTypeEnum.otherId9: + return dist.IdentityTypeEnum.otherId9; + case SDKIdentityTypeEnum.otherId10: + return dist.IdentityTypeEnum.otherId10; + case SDKIdentityTypeEnum.mobileNumber: + return dist.IdentityTypeEnum.mobileNumber; + case SDKIdentityTypeEnum.phoneNumber2: + return dist.IdentityTypeEnum.phoneNumber2; + case SDKIdentityTypeEnum.phoneNumber3: + return dist.IdentityTypeEnum.phoneNumber3; + } + } + + var BaseVault = /** @class */function () { + /** + * + * @param {string} storageKey the local storage key string + * @param {Storage} Web API Storage object that is being used + * @param {IVaultOptions} options A Dictionary of IVaultOptions + */ + function BaseVault(storageKey, storageObject, options) { + this._storageKey = storageKey; + this.storageObject = storageObject; + // Add a fake logger in case one is not provided or needed + this.logger = (options === null || options === void 0 ? void 0 : options.logger) || { + verbose: function verbose() {}, + warning: function warning() {}, + error: function error() {} + }; + this.contents = this.retrieve(); + } + /** + * Stores a StorableItem to Storage + * @method store + * @param item {StorableItem} + */ + BaseVault.prototype.store = function (item) { + var stringifiedItem; + this.contents = item; + if (isNumber(item) || !isEmpty(item)) { + stringifiedItem = JSON.stringify(item); + } else { + stringifiedItem = ''; + } + try { + this.storageObject.setItem(this._storageKey, stringifiedItem); + this.logger.verbose("Saving item to Storage: ".concat(stringifiedItem)); + } catch (error) { + this.logger.error("Cannot Save items to Storage: ".concat(stringifiedItem)); + this.logger.error(error); + } + }; + /** + * Retrieve StorableItem from Storage + * @method retrieve + * @returns {StorableItem} + */ + BaseVault.prototype.retrieve = function () { + // TODO: Handle cases where Local Storage is unavailable + // https://go.mparticle.com/work/SQDSDKS-5022 + var item = this.storageObject.getItem(this._storageKey); + this.contents = item ? JSON.parse(item) : null; + this.logger.verbose("Retrieving item from Storage: ".concat(item)); + return this.contents; + }; + /** + * Removes all persisted data from Storage based on this vault's `key` + * Will remove storage key from Storage as well + * @method purge + */ + BaseVault.prototype.purge = function () { + this.logger.verbose('Purging Storage'); + this.contents = null; + this.storageObject.removeItem(this._storageKey); + }; + return BaseVault; + }(); + var LocalStorageVault = /** @class */function (_super) { + __extends(LocalStorageVault, _super); + function LocalStorageVault(storageKey, options) { + return _super.call(this, storageKey, window.localStorage, options) || this; + } + return LocalStorageVault; + }(BaseVault); + var SessionStorageVault = /** @class */function (_super) { + __extends(SessionStorageVault, _super); + function SessionStorageVault(storageKey, options) { + return _super.call(this, storageKey, window.sessionStorage, options) || this; + } + return SessionStorageVault; + }(BaseVault); + // DisabledVault is used when persistence is disabled by privacy flags. + var DisabledVault = /** @class */function (_super) { + __extends(DisabledVault, _super); + function DisabledVault(storageKey, options) { + var _this = _super.call(this, storageKey, window.localStorage, options) || this; + _this.contents = null; + _this.storageObject.removeItem(_this._storageKey); + return _this; + } + DisabledVault.prototype.store = function (_item) { + this.contents = null; + }; + DisabledVault.prototype.retrieve = function () { + return this.contents; + }; + DisabledVault.prototype.purge = function () { + this.contents = null; + }; + return DisabledVault; + }(BaseVault); + + var AsyncUploader = /** @class */function () { + function AsyncUploader(url) { + this.url = url; + } + return AsyncUploader; + }(); + var FetchUploader = /** @class */function (_super) { + __extends(FetchUploader, _super); + function FetchUploader() { + return _super !== null && _super.apply(this, arguments) || this; + } + FetchUploader.prototype.upload = function (fetchPayload, _url) { + return __awaiter(this, void 0, void 0, function () { + var url; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + url = _url || this.url; + return [4 /*yield*/, fetch(url, fetchPayload)]; + case 1: + return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + return FetchUploader; + }(AsyncUploader); + var XHRUploader = /** @class */function (_super) { + __extends(XHRUploader, _super); + function XHRUploader() { + return _super !== null && _super.apply(this, arguments) || this; + } + XHRUploader.prototype.upload = function (fetchPayload) { + return __awaiter(this, void 0, void 0, function () { + var response; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, this.makeRequest(this.url, fetchPayload.body, fetchPayload.method, fetchPayload.headers)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response]; + } + }); + }); + }; + // XHR Ready States + // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState + // 0 UNSENT open() has not been called yet. + // 1 OPENED send() has been called. + // 2 HEADERS_RECEIVED send() has been called, and headers and status are available. + // 3 LOADING Downloading; responseText holds partial data. + // 4 DONE The operation is complete. + // https://go.mparticle.com/work/SQDSDKS-6736 + XHRUploader.prototype.makeRequest = function (url, data, method, headers) { + if (method === void 0) { + method = 'post'; + } + if (headers === void 0) { + headers = {}; + } + return __awaiter(this, void 0, void 0, function () { + var xhr; + return __generator(this, function (_a) { + xhr = new XMLHttpRequest(); + return [2 /*return*/, new Promise(function (resolve, reject) { + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + // Process the response + // We resolve all xhr responses whose ready state is 4 regardless of HTTP codes that may be errors (400+) + // because these are valid HTTP responses. + resolve(xhr); + }; + // Reject a promise only when there is an xhr error + xhr.onerror = function () { + reject(xhr); + }; + xhr.open(method, url); + for (var key in headers) { + if (headers.hasOwnProperty(key)) { + xhr.setRequestHeader(key, headers[key]); + } + } + xhr.send(data); + })]; + }); + }); + }; + return XHRUploader; + }(AsyncUploader); + + function hasMPIDAndUserLoginChanged(previousUser, newUser) { + return !previousUser || newUser.getMPID() !== previousUser.getMPID() || previousUser.isLoggedIn() !== newUser.isLoggedIn(); + } + // https://go.mparticle.com/work/SQDSDKS-6504 + function hasMPIDChanged(prevUser, identityApiResult) { + return !prevUser || prevUser.getMPID() && identityApiResult.mpid && identityApiResult.mpid !== prevUser.getMPID(); + } + // https://go.mparticle.com/work/SQDSDKS-7136 + function appendUserInfo(user, event) { + if (!event) { + return; + } + if (!user) { + event.MPID = null; + event.ConsentState = null; + event.UserAttributes = null; + event.UserIdentities = null; + return; + } + if (event.MPID && event.MPID === user.getMPID()) { + return; + } + event.MPID = user.getMPID(); + event.ConsentState = user.getConsentState(); + event.UserAttributes = user.getAllUserAttributes(); + var userIdentities = user.getUserIdentities().userIdentities; + var dtoUserIdentities = {}; + for (var identityKey in userIdentities) { + var identityType = Types.IdentityType.getIdentityType(identityKey); + if (identityType !== false) { + dtoUserIdentities[identityType] = userIdentities[identityKey]; + } + } + var validUserIdentities = []; + if (isObject(dtoUserIdentities)) { + if (Object.keys(dtoUserIdentities).length) { + for (var key in dtoUserIdentities) { + var userIdentity = {}; + userIdentity.Identity = dtoUserIdentities[key]; + userIdentity.Type = parseNumber(key); + validUserIdentities.push(userIdentity); + } + } + } + event.UserIdentities = validUserIdentities; + } + + /** + * BatchUploader contains all the logic to store/retrieve events and batches + * to/from persistence, and upload batches to mParticle. + * It queues events as they come in, storing them in persistence, then at set + * intervals turns them into batches and transfers between event and batch + * persistence. + * It then attempts to upload them to mParticle, purging batch persistence if + * the upload is successful + * + * These uploads happen on an interval basis using window.fetch or XHR + * requests, depending on what is available in the browser. + * + * Uploads can also be triggered on browser visibility/focus changes via an + * event listener, which then uploads to mPartice via the browser's Beacon API. + */ + var BatchUploader = /** @class */function () { + /** + * Creates an instance of a BatchUploader + * @param {IMParticleWebSDKInstance} mpInstance - the mParticle SDK instance + * @param {number} uploadInterval - the desired upload interval in milliseconds + */ + function BatchUploader(mpInstance, uploadInterval) { + var _a; + var _b; + this.offlineStorageEnabled = false; + this.lastASTEventTime = 0; + this.AST_DEBOUNCE_MS = 1000; // 1 second debounce + this.mpInstance = mpInstance; + this.uploadIntervalMillis = uploadInterval; + this.batchingEnabled = uploadInterval >= BatchUploader.MINIMUM_INTERVAL_MILLIS; + if (this.uploadIntervalMillis < BatchUploader.MINIMUM_INTERVAL_MILLIS) { + this.uploadIntervalMillis = BatchUploader.MINIMUM_INTERVAL_MILLIS; + } + // Events will be queued during `queueEvents` method + this.eventsQueuedForProcessing = []; + // Batch queue should start empty and will be populated during + // `prepareAndUpload` method, either via Local Storage or after + // new batches are created. + this.batchesQueuedForProcessing = []; + // Cache Offline Storage Availability boolean + // so that we don't have to check it every time + this.offlineStorageEnabled = this.isOfflineStorageAvailable(); + // When noFunctional is true, prevent events/batches storage + var noFunctional = (_b = mpInstance._CookieConsentManager) === null || _b === void 0 ? void 0 : _b.getNoFunctional(); + if (this.offlineStorageEnabled && !noFunctional) { + this.eventVault = new SessionStorageVault("".concat(mpInstance._Store.storageName, "-events"), { + logger: mpInstance.Logger + }); + this.batchVault = new LocalStorageVault("".concat(mpInstance._Store.storageName, "-batches"), { + logger: mpInstance.Logger + }); + // Load Events from Session Storage in case we have any in storage + (_a = this.eventsQueuedForProcessing).push.apply(_a, this.eventVault.retrieve()); + } + var _c = this.mpInstance._Store, + SDKConfig = _c.SDKConfig, + devToken = _c.devToken; + var baseUrl = this.mpInstance._Helpers.createServiceUrl(SDKConfig.v3SecureServiceUrl, devToken); + this.uploadUrl = "".concat(baseUrl, "/events"); + this.uploader = window.fetch ? new FetchUploader(this.uploadUrl) : new XHRUploader(this.uploadUrl); + this.triggerUploadInterval(true, false); + this.addEventListeners(); + } + BatchUploader.prototype.isOfflineStorageAvailable = function () { + var _a = this.mpInstance, + getFeatureFlag = _a._Helpers.getFeatureFlag, + deviceId = _a._Store.deviceId; + // https://go.mparticle.com/work/SQDSDKS-6317 + var offlineStorageFeatureFlagValue = getFeatureFlag(Constants.FeatureFlags.OfflineStorage); + var offlineStoragePercentage = parseInt(offlineStorageFeatureFlagValue, 10); + var rampNumber = getRampNumber(deviceId); + // TODO: Handle cases where Local Storage is unavailable + // Potentially shared between Vault and Persistence as well + // https://go.mparticle.com/work/SQDSDKS-5022 + return offlineStoragePercentage >= rampNumber; + }; + // debounce AST just in case multiple events are fired in a short period of time due to browser differences + BatchUploader.prototype.shouldDebounceAndUpdateLastASTTime = function () { + var now = Date.now(); + if (now - this.lastASTEventTime < this.AST_DEBOUNCE_MS) { + return true; + } + this.lastASTEventTime = now; + return false; + }; + // https://go.mparticle.com/work/SQDSDKS-7133 + BatchUploader.prototype.createBackgroundASTEvent = function () { + var now = Date.now(); + var _a = this.mpInstance, + _Store = _a._Store, + Identity = _a.Identity, + _timeOnSiteTimer = _a._timeOnSiteTimer, + _Helpers = _a._Helpers; + var sessionId = _Store.sessionId, + deviceId = _Store.deviceId, + sessionStartDate = _Store.sessionStartDate, + SDKConfig = _Store.SDKConfig; + var generateUniqueId = _Helpers.generateUniqueId, + getFeatureFlag = _Helpers.getFeatureFlag; + var getCurrentUser = Identity.getCurrentUser; + var event = { + AppName: SDKConfig.appName, + AppVersion: SDKConfig.appVersion, + Package: SDKConfig["package"], + EventDataType: MessageType$1.AppStateTransition, + Timestamp: now, + SessionId: sessionId, + DeviceId: deviceId, + IsFirstRun: false, + SourceMessageId: generateUniqueId(), + SDKVersion: Constants.sdkVersion, + CustomFlags: {}, + EventAttributes: {}, + SessionStartDate: (sessionStartDate === null || sessionStartDate === void 0 ? void 0 : sessionStartDate.getTime()) || now, + Debug: SDKConfig.isDevelopmentMode, + ActiveTimeOnSite: (_timeOnSiteTimer === null || _timeOnSiteTimer === void 0 ? void 0 : _timeOnSiteTimer.getTimeInForeground()) || 0, + IsBackgroundAST: true + }; + var customFlags = __assign({}, event.CustomFlags); + var integrationAttributes = _Store.integrationAttributes; + var integrationSpecificIds = getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds); + var integrationSpecificIdsV2 = getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || ''; + var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; + // https://go.mparticle.com/work/SQDSDKS-5053 + if (isIntegrationCaptureEnabled) { + // Attempt to recapture click IDs in case a third party integration + // has added or updated new click IDs since the last event was sent. + this.mpInstance._IntegrationCapture.capture(); + var transformedClickIDs = this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags(); + customFlags = __assign(__assign({}, transformedClickIDs), customFlags); + var transformedIntegrationAttributes = this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes(); + integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes); + } + event.CustomFlags = customFlags; + event.IntegrationAttributes = integrationAttributes; + appendUserInfo(getCurrentUser(), event); + return event; + }; + // Adds listeners to be used trigger Navigator.sendBeacon if the browser + // loses focus for any reason, such as closing browser tab or minimizing window + BatchUploader.prototype.addEventListeners = function () { + var _this_1 = this; + var _this = this; + var handleExit = function handleExit() { + // Check for debounce before creating and queueing event + var getFeatureFlag = _this_1.mpInstance._Helpers.getFeatureFlag; + var AstBackgroundEvents = Constants.FeatureFlags.AstBackgroundEvents; + if (getFeatureFlag(AstBackgroundEvents)) { + if (_this.shouldDebounceAndUpdateLastASTTime()) { + return; + } + // Add application state transition event to queue + var event_1 = _this.createBackgroundASTEvent(); + _this.queueEvent(event_1); + } + // Then trigger the upload with beacon + _this.prepareAndUpload(false, _this.isBeaconAvailable()); + }; + // visibility change is a document property, not window + document.addEventListener('visibilitychange', function () { + if (document.visibilityState === 'hidden') { + handleExit(); + } + }); + window.addEventListener('beforeunload', handleExit); + window.addEventListener('pagehide', handleExit); + }; + BatchUploader.prototype.isBeaconAvailable = function () { + if (navigator.sendBeacon) { + return true; + } + return false; + }; + // Triggers a setTimeout for prepareAndUpload + BatchUploader.prototype.triggerUploadInterval = function (triggerFuture, useBeacon) { + var _this_1 = this; + if (triggerFuture === void 0) { + triggerFuture = false; + } + if (useBeacon === void 0) { + useBeacon = false; + } + setTimeout(function () { + _this_1.prepareAndUpload(triggerFuture, useBeacon); + }, this.uploadIntervalMillis); + }; + /** + * This method will queue a single Event which will eventually be processed into a Batch + * @param event event that should be queued + */ + BatchUploader.prototype.queueEvent = function (event) { + if (isEmpty(event)) { + return; + } + var Logger = this.mpInstance.Logger; + this.eventsQueuedForProcessing.push(event); + if (this.offlineStorageEnabled && this.eventVault) { + this.eventVault.store(this.eventsQueuedForProcessing); + } + Logger.verbose("Queuing event: ".concat(JSON.stringify(event))); + Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length)); + if (this.shouldTriggerImmediateUpload(event.EventDataType)) { + this.prepareAndUpload(false, false); + } + }; + // https://go.mparticle.com/work/SQDSDKS-3720 + BatchUploader.prototype.shouldTriggerImmediateUpload = function (eventDataType) { + var priorityEvents = [MessageType$1.Commerce, MessageType$1.UserIdentityChange]; + return !this.batchingEnabled || priorityEvents.includes(eventDataType); + }; + /** + * This implements crucial logic to: + * - bucket pending events by MPID, and then by Session, and upload individual batches for each bucket. + * + * In the future this should enforce other requirements such as maximum batch size. + * + * @param sdkEvents current pending events + * @param defaultUser the user to reference for events that are missing data + */ + BatchUploader.createNewBatches = function (sdkEvents, defaultUser, mpInstance) { + if (!defaultUser || !sdkEvents || !sdkEvents.length) { + return null; + } + //bucket by MPID, and then by session, ordered by timestamp + var newUploads = []; + var eventsByUser = new Map(); + for (var _i = 0, sdkEvents_1 = sdkEvents; _i < sdkEvents_1.length; _i++) { + var sdkEvent = sdkEvents_1[_i]; + //on initial startup, there may be events logged without an mpid. + if (!sdkEvent.MPID) { + var mpid = defaultUser.getMPID(); + sdkEvent.MPID = mpid; + } + var events = eventsByUser.get(sdkEvent.MPID); + if (!events) { + events = []; + } + events.push(sdkEvent); + eventsByUser.set(sdkEvent.MPID, events); + } + for (var _a = 0, _b = Array.from(eventsByUser.entries()); _a < _b.length; _a++) { + var entry = _b[_a]; + var mpid = entry[0]; + var userEvents = entry[1]; + var eventsBySession = new Map(); + for (var _c = 0, userEvents_1 = userEvents; _c < userEvents_1.length; _c++) { + var sdkEvent = userEvents_1[_c]; + var events = eventsBySession.get(sdkEvent.SessionId); + if (!events) { + events = []; + } + events.push(sdkEvent); + eventsBySession.set(sdkEvent.SessionId, events); + } + for (var _d = 0, _e = Array.from(eventsBySession.entries()); _d < _e.length; _d++) { + var entry_1 = _e[_d]; + var uploadBatchObject = convertEvents(mpid, entry_1[1], mpInstance); + var onCreateBatchCallback = mpInstance._Store.SDKConfig.onCreateBatch; + if (onCreateBatchCallback) { + uploadBatchObject = onCreateBatchCallback(uploadBatchObject); + if (uploadBatchObject) { + uploadBatchObject.modified = true; + } else { + mpInstance.Logger.warning('Skiping batch upload because no batch was returned from onCreateBatch callback'); + } + } + if (uploadBatchObject) { + newUploads.push(uploadBatchObject); + } + } + } + return newUploads; + }; + /** + * This is the main loop function: + * - take all pending events and turn them into batches + * - attempt to upload each batch + * + * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false + * @param useBeacon whether to use the beacon API - used when the page is being unloaded + */ + BatchUploader.prototype.prepareAndUpload = function (triggerFuture, useBeacon) { + if (triggerFuture === void 0) { + triggerFuture = false; + } + if (useBeacon === void 0) { + useBeacon = false; + } + return __awaiter(this, void 0, void 0, function () { + var currentUser, currentEvents, newBatches, batchesToUpload, batchesThatDidNotUpload; + var _a, _b, _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + currentUser = this.mpInstance.Identity.getCurrentUser(); + currentEvents = this.eventsQueuedForProcessing; + this.eventsQueuedForProcessing = []; + if (this.offlineStorageEnabled && this.eventVault) { + this.eventVault.store([]); + } + newBatches = []; + if (!isEmpty(currentEvents)) { + newBatches = BatchUploader.createNewBatches(currentEvents, currentUser, this.mpInstance); + } + // Top Load any older Batches from Offline Storage so they go out first + if (this.offlineStorageEnabled && this.batchVault) { + (_a = this.batchesQueuedForProcessing).unshift.apply(_a, this.batchVault.retrieve()); + // Remove batches from local storage before transmit to + // prevent duplication + this.batchVault.purge(); + } + if (!isEmpty(newBatches)) { + (_b = this.batchesQueuedForProcessing).push.apply(_b, newBatches); + } + batchesToUpload = this.batchesQueuedForProcessing; + this.batchesQueuedForProcessing = []; + return [4 /*yield*/, this.uploadBatches(this.mpInstance.Logger, batchesToUpload, useBeacon)]; + case 1: + batchesThatDidNotUpload = _d.sent(); + // Batches that do not successfully upload are added back to the process queue + // in the order they were created so that we can attempt re-transmission in + // the same sequence. This is to prevent any potential data corruption. + if (!isEmpty(batchesThatDidNotUpload)) { + // TODO: https://go.mparticle.com/work/SQDSDKS-5165 + (_c = this.batchesQueuedForProcessing).unshift.apply(_c, batchesThatDidNotUpload); + } + // Update Offline Storage with current state of batch queue + if (!useBeacon && this.offlineStorageEnabled && this.batchVault) { + // Note: since beacon is "Fire and forget" it will empty `batchesThatDidNotUplod` + // regardless of whether the batches were successfully uploaded or not. We should + // therefore NOT overwrite Offline Storage when beacon returns, so that we can retry + // uploading saved batches at a later time. Batches should only be removed from + // Local Storage once we can confirm they are successfully uploaded. + this.batchVault.store(this.batchesQueuedForProcessing); + // Clear batch queue since everything should be in Offline Storage + this.batchesQueuedForProcessing = []; + } + if (triggerFuture) { + this.triggerUploadInterval(triggerFuture, false); + } + return [2 /*return*/]; + } + }); + }); + }; + // TODO: Refactor to use logger as a class method + // https://go.mparticle.com/work/SQDSDKS-5167 + BatchUploader.prototype.uploadBatches = function (logger, batches, useBeacon) { + return __awaiter(this, void 0, void 0, function () { + var uploads, i, fetchPayload, blob, response, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + uploads = batches.filter(function (batch) { + return !isEmpty(batch.events); + }); + if (isEmpty(uploads)) { + return [2 /*return*/, null]; + } + logger.verbose("Uploading batches: ".concat(JSON.stringify(uploads))); + logger.verbose("Batch count: ".concat(uploads.length)); + i = 0; + _a.label = 1; + case 1: + if (!(i < uploads.length)) return [3 /*break*/, 6]; + fetchPayload = { + method: 'POST', + headers: { + Accept: BatchUploader.CONTENT_TYPE, + 'Content-Type': 'text/plain;charset=UTF-8' + }, + body: JSON.stringify(uploads[i]) + }; + if (!(useBeacon && this.isBeaconAvailable())) return [3 /*break*/, 2]; + blob = new Blob([fetchPayload.body], { + type: 'text/plain;charset=UTF-8' + }); + navigator.sendBeacon(this.uploadUrl, blob); + return [3 /*break*/, 5]; + case 2: + _a.trys.push([2, 4,, 5]); + return [4 /*yield*/, this.uploader.upload(fetchPayload)]; + case 3: + response = _a.sent(); + if (response.status >= 200 && response.status < 300) { + logger.verbose("Upload success for request ID: ".concat(uploads[i].source_request_id)); + } else if (response.status >= 500 || response.status === 429) { + logger.error("HTTP error status ".concat(response.status, " received")); + // Server error, add back current batches and try again later + return [2 /*return*/, uploads.slice(i, uploads.length)]; + } else if (response.status >= 401) { + logger.error("HTTP error status ".concat(response.status, " while uploading - please verify your API key.")); + //if we're getting a 401, assume we'll keep getting a 401 and clear the uploads. + return [2 /*return*/, null]; + } else { + // In case there is an HTTP error we did not anticipate. + console.error("HTTP error status ".concat(response.status, " while uploading events."), response); + throw new Error("Uncaught HTTP Error ".concat(response.status, ". Batch upload will be re-attempted.")); + } + return [3 /*break*/, 5]; + case 4: + e_1 = _a.sent(); + logger.error("Error sending event to mParticle servers. ".concat(e_1)); + return [2 /*return*/, uploads.slice(i, uploads.length)]; + case 5: + i++; + return [3 /*break*/, 1]; + case 6: + return [2 /*return*/, null]; + } + }); + }); + }; + // We upload JSON, but this content type is required to avoid a CORS preflight request + BatchUploader.CONTENT_TYPE = 'text/plain;charset=UTF-8'; + BatchUploader.MINIMUM_INTERVAL_MILLIS = 500; + return BatchUploader; + }(); + + var _a = Constants.IdentityMethods, + Identify$2 = _a.Identify, + Modify$4 = _a.Modify, + Login$2 = _a.Login, + Logout$2 = _a.Logout; + var CACHE_HEADER = 'x-mp-max-age'; + var cacheOrClearIdCache = function cacheOrClearIdCache(method, knownIdentities, idCache, identityResponse, parsingCachedResponse) { + // when parsing a response that has already been cached, simply return instead of attempting another cache + if (parsingCachedResponse) { + return; + } + // default the expire timestamp to one day in milliseconds unless a header comes back + var expireTimestamp = getExpireTimestamp(identityResponse === null || identityResponse === void 0 ? void 0 : identityResponse.cacheMaxAge); + switch (method) { + case Login$2: + case Identify$2: + cacheIdentityRequest(method, knownIdentities, expireTimestamp, idCache, identityResponse); + break; + case Modify$4: + case Logout$2: + idCache.purge(); + break; + } + }; + var cacheIdentityRequest = function cacheIdentityRequest(method, identities, expireTimestamp, idCache, identityResponse) { + var responseText = identityResponse.responseText, + status = identityResponse.status; + var cache = idCache.retrieve() || {}; + var cacheKey = concatenateIdentities(method, identities); + var hashedKey = generateHash(cacheKey); + var mpid = responseText.mpid, + is_logged_in = responseText.is_logged_in; + var cachedResponseBody = { + mpid: mpid, + is_logged_in: is_logged_in + }; + cache[hashedKey] = { + responseText: JSON.stringify(cachedResponseBody), + status: status, + expireTimestamp: expireTimestamp + }; + idCache.store(cache); + }; + // We need to ensure that identities are concatenated in a deterministic way, so + // we sort the identities based on their enum. + // we create an array, set the user identity at the index of the user identity type + var concatenateIdentities = function concatenateIdentities(method, userIdentities) { + var DEVICE_APPLICATION_STAMP = 'device_application_stamp'; + // set DAS first since it is not an official identity type + var cacheKey = "".concat(method, ":").concat(DEVICE_APPLICATION_STAMP, "=").concat(userIdentities.device_application_stamp, ";"); + var idLength = Object.keys(userIdentities).length; + var concatenatedIdentities = ''; + if (idLength) { + var userIDArray = new Array(); + // create an array where each index is equal to the user identity type + for (var key in userIdentities) { + if (key === DEVICE_APPLICATION_STAMP) { + continue; + } else { + userIDArray[Types.IdentityType.getIdentityType(key)] = userIdentities[key]; + } + } + concatenatedIdentities = userIDArray.reduce(function (prevValue, currentValue, index) { + var idName = Types.IdentityType.getIdentityName(index); + return "".concat(prevValue).concat(idName, "=").concat(currentValue, ";"); + }, cacheKey); + } + return concatenatedIdentities; + }; + var hasValidCachedIdentity = function hasValidCachedIdentity(method, proposedUserIdentities, idCache) { + // There is an edge case where multiple identity calls are taking place + // before identify fires, so there may not be a cache. See what happens when + // the ? in idCache is removed to the following test + // "queued events contain login mpid instead of identify mpid when calling + // login immediately after mParticle initializes" + var cache = idCache === null || idCache === void 0 ? void 0 : idCache.retrieve(); + // if there is no cache, then there is no valid cached identity + if (!cache) { + return false; + } + var cacheKey = concatenateIdentities(method, proposedUserIdentities); + var hashedKey = generateHash(cacheKey); + // if cache doesn't have the cacheKey, there is no valid cached identity + if (!cache.hasOwnProperty(hashedKey)) { + return false; + } + // If there is a valid cache key, compare the expireTimestamp to the current time. + // If the current time is greater than the expireTimestamp, it is not a valid + // cached identity. + var expireTimestamp = cache[hashedKey].expireTimestamp; + if (expireTimestamp < new Date().getTime()) { + return false; + } else { + return true; + } + }; + var getCachedIdentity = function getCachedIdentity(method, proposedUserIdentities, idCache) { + var cacheKey = concatenateIdentities(method, proposedUserIdentities); + var hashedKey = generateHash(cacheKey); + var cache = idCache.retrieve(); + var cachedIdentity = cache ? cache[hashedKey] : null; + return { + responseText: parseIdentityResponse(cachedIdentity.responseText), + expireTimestamp: cachedIdentity.expireTimestamp, + status: cachedIdentity.status + }; + }; + // https://go.mparticle.com/work/SQDSDKS-6079 + var createKnownIdentities = function createKnownIdentities(identityApiData, deviceId) { + var identitiesResult = {}; + if (isObject(identityApiData === null || identityApiData === void 0 ? void 0 : identityApiData.userIdentities)) { + for (var identity in identityApiData.userIdentities) { + identitiesResult[identity] = identityApiData.userIdentities[identity]; + } + } + identitiesResult.device_application_stamp = deviceId; + return identitiesResult; + }; + var removeExpiredIdentityCacheDates = function removeExpiredIdentityCacheDates(idCache) { + var cache = idCache.retrieve() || {}; + var currentTime = new Date().getTime(); + // Iterate over the cache and remove any key/value pairs that are expired + for (var key in cache) { + if (cache[key].expireTimestamp < currentTime) { + delete cache[key]; + } + } + idCache.store(cache); + }; + var tryCacheIdentity = function tryCacheIdentity(knownIdentities, idCache, parseIdentityResponse, mpid, callback, identityApiData, identityMethod) { + // https://go.mparticle.com/work/SQDSDKS-6095 + var shouldReturnCachedIdentity = hasValidCachedIdentity(identityMethod, knownIdentities, idCache); + // If Identity is cached, then immediately parse the identity response + if (shouldReturnCachedIdentity) { + var cachedIdentity = getCachedIdentity(identityMethod, knownIdentities, idCache); + parseIdentityResponse(cachedIdentity, mpid, callback, identityApiData, identityMethod, knownIdentities, true); + return true; + } + return false; + }; + var getExpireTimestamp = function getExpireTimestamp(maxAge) { + if (maxAge === void 0) { + maxAge = ONE_DAY_IN_SECONDS; + } + return new Date().getTime() + maxAge * MILLIS_IN_ONE_SEC; + }; + var parseIdentityResponse = function parseIdentityResponse(responseText) { + return responseText ? JSON.parse(responseText) : {}; + }; + var hasIdentityRequestChanged = function hasIdentityRequestChanged(currentUser, newIdentityRequest) { + if (!currentUser || !(newIdentityRequest === null || newIdentityRequest === void 0 ? void 0 : newIdentityRequest.userIdentities)) { + return false; + } + var currentUserIdentities = currentUser.getUserIdentities().userIdentities; + var newIdentities = newIdentityRequest.userIdentities; + return JSON.stringify(currentUserIdentities) !== JSON.stringify(newIdentities); + }; + /** + * Checks if deviceId or other user identifiers (like email) were explicitly provided + * by the partner via config.deviceId or config.identifyRequest.userIdentities. + * When noFunctional is true, then cookies are blocked, so the partner must explicitly + * pass deviceId or other identifiers to prevent new users from being created on each page load. + * + * @param store - The SDK store (provides SDKConfig.deviceId and SDKConfig.identifyRequest.userIdentities) + * @returns true if deviceId or other identifiers were explicitly provided in config, false otherwise + */ + var hasExplicitIdentifier = function hasExplicitIdentifier(store) { + var _a, _b, _c; + var userIdentities = (_b = (_a = store === null || store === void 0 ? void 0 : store.SDKConfig) === null || _a === void 0 ? void 0 : _a.identifyRequest) === null || _b === void 0 ? void 0 : _b.userIdentities; + if (userIdentities && isObject(userIdentities) && !isEmpty(userIdentities) && Object.values(userIdentities).some(Boolean)) { + return true; + } + return !!((_c = store === null || store === void 0 ? void 0 : store.SDKConfig) === null || _c === void 0 ? void 0 : _c.deviceId); + }; + + function APIClient(mpInstance, kitBlocker) { + this.uploader = null; + var self = this; + this.queueEventForBatchUpload = function (event) { + if (!this.uploader) { + // https://go.mparticle.com/work/SQDSDKS-6317 + var millis = parseNumber(mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis)); + this.uploader = new BatchUploader(mpInstance, millis); + } + this.uploader.queueEvent(event); + // https://go.mparticle.com/work/SQDSDKS-6038 + mpInstance._Persistence.update(); + }; + this.processQueuedEvents = function () { + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(); + if (currentUser) { + mpid = currentUser.getMPID(); + } + if (mpInstance._Store.eventQueue.length && mpid) { + var localQueueCopy = mpInstance._Store.eventQueue; + mpInstance._Store.eventQueue = []; + this.appendUserInfoToEvents(currentUser, localQueueCopy); + localQueueCopy.forEach(function (event) { + self.sendEventToServer(event); + }); + } + }; + this.appendUserInfoToEvents = function (user, events) { + events.forEach(function (event) { + if (!event.MPID) { + appendUserInfo(user, event); + } + }); + }; + // When noFunctional is set and there are no identities passed, the SDK will not fully initialize. + // In this case, there will be no MPID, but we still want kits to initialize and forward the event to kits. + // The original event is queued for the MP server upload path so it can be sent once an MPID is returned. + // Returns true if the event was handled by this path (caller should return early). + var handleNoFunctionalPreMpidEvent = function handleNoFunctionalPreMpidEvent(event, mpid) { + var _a; + var noFunctionalWithoutId = ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store); + if (!noFunctionalWithoutId || mpid || !mpInstance._Store.configurationLoaded || mpInstance._Store.requireDelay) { + return false; + } + var forwarderEvent = event; + if (kitBlocker === null || kitBlocker === void 0 ? void 0 : kitBlocker.kitBlockingEnabled) { + forwarderEvent = kitBlocker.createBlockedEvent(event); + } + if (forwarderEvent) { + mpInstance._Forwarders.sendEventToForwarders(forwarderEvent); + event.AlreadySentToForwarders = true; + } + mpInstance.Logger.verbose('noFunctional event forwarded to kits and queued for MP server upload when MPID is available.'); + mpInstance._Store.eventQueue.push(event); + return true; + }; + this.sendEventToServer = function (event, _options) { + var defaultOptions = { + shouldUploadEvent: true + }; + var options = mpInstance._Helpers.extend(defaultOptions, _options); + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent, JSON.stringify(event)); + return; + } + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(); + if (currentUser) { + mpid = currentUser.getMPID(); + } + mpInstance._Store.requireDelay = mpInstance._Helpers.isDelayedByIntegration(mpInstance._preInit.integrationDelays, mpInstance._Store.integrationDelayTimeoutStart, Date.now()); + if (handleNoFunctionalPreMpidEvent(event, mpid)) { + return; + } + // We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that + // require this to stall because integration attributes need to be set, or if we are still + // fetching the config (self hosted only), and so require delaying events + if (!mpid || mpInstance._Store.requireDelay || !mpInstance._Store.configurationLoaded) { + mpInstance.Logger.verbose('Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.'); + mpInstance._Store.eventQueue.push(event); + return; + } + this.processQueuedEvents(); + if (isEmpty(event)) { + return; + } + // https://go.mparticle.com/work/SQDSDKS-6038 + if (options.shouldUploadEvent) { + this.queueEventForBatchUpload(event); + } + // https://go.mparticle.com/work/SQDSDKS-6935 + // While Event Name is 'usually' a string, there are some cases where it is a number + // in that it could be a type of MessageType Enum + if (event.EventName !== Types.MessageType.AppStateTransition) { + if (kitBlocker && kitBlocker.kitBlockingEnabled) { + event = kitBlocker.createBlockedEvent(event); + } + // We need to check event again, because kitblocking + // can nullify the event. + // Skip if forwarders were already called in the noFunctional pre-MPID path + // to prevent double-sending when the event queue is later flushed. + if (event && !event.AlreadySentToForwarders) { + mpInstance._Forwarders.sendEventToForwarders(event); + } + } + }; + this.sendBatchForwardingStatsToServer = function (forwardingStatsData, xhr) { + var url; + var data; + try { + url = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.v2SecureServiceUrl, mpInstance._Store.devToken); + data = { + uuid: mpInstance._Helpers.generateUniqueId(), + data: forwardingStatsData + }; + if (xhr) { + xhr.open('post', url + '/Forwarding'); + xhr.send(JSON.stringify(data)); + } + } catch (e) { + mpInstance.Logger.error('Error sending forwarding stats to mParticle servers.'); + } + }; + this.initializeForwarderStatsUploader = function () { + var forwardingDomain = mpInstance._Store.SDKConfig.v1SecureServiceUrl; + var devToken = mpInstance._Store.devToken; + var uploadUrl = "https://".concat(forwardingDomain).concat(devToken, "/Forwarding"); + var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); + return uploader; + }; + this.prepareForwardingStats = function (forwarder, event) { + var forwardingStatsData; + var queue = mpInstance._Forwarders.getForwarderStatsQueue(); + if (forwarder && forwarder.isVisible) { + forwardingStatsData = { + mid: forwarder.id, + esid: forwarder.eventSubscriptionId, + n: event.EventName, + attrs: event.EventAttributes, + sdk: event.SDKVersion, + dt: event.EventDataType, + et: event.EventCategory, + dbg: event.Debug, + ct: event.Timestamp, + eec: event.ExpandedEventCount, + dp: event.DataPlan + }; + var _a = mpInstance._Forwarders, + sendSingleForwardingStatsToServer = _a.sendSingleForwardingStatsToServer, + setForwarderStatsQueue = _a.setForwarderStatsQueue; + if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)) { + queue.push(forwardingStatsData); + setForwarderStatsQueue(queue); + } else { + sendSingleForwardingStatsToServer(forwardingStatsData); + } + } + }; + } + + var Modify$3 = Constants.IdentityMethods.Modify; + var Validators = { + // From ./utils + // Utility Functions for backwards compatability + isNumber: isNumber, + isFunction: isFunction, + isStringOrNumber: isStringOrNumber, + // Validator Functions + isValidAttributeValue: isValidAttributeValue, + // Validator Functions + // Neither null nor undefined can be a valid Key + isValidKeyValue: function isValidKeyValue(key) { + return Boolean(key && !isObject(key) && !Array.isArray(key) && !this.isFunction(key)); + }, + removeFalsyIdentityValues: function removeFalsyIdentityValues(identityApiData, logger) { + if (!identityApiData || !identityApiData.userIdentities) { + return identityApiData; + } + var cleanedData = {}; + var cleanedUserIdentities = __assign({}, identityApiData.userIdentities); + for (var identityType in identityApiData.userIdentities) { + if (identityApiData.userIdentities.hasOwnProperty(identityType)) { + var value = identityApiData.userIdentities[identityType]; + // Check if value is falsy (undefined, false, 0, '', etc.) but not null + if (value !== null && !value) { + logger.warning("Identity value for '".concat(identityType, "' is falsy (").concat(value, "). This value will be removed from the request.")); + delete cleanedUserIdentities[identityType]; + } + } + } + cleanedData.userIdentities = cleanedUserIdentities; + return cleanedData; + }, + validateIdentities: function validateIdentities(identityApiData, method) { + var validIdentityRequestKeys = { + userIdentities: 1, + onUserAlias: 1, + copyUserAttributes: 1 + }; + if (identityApiData) { + if (method === Modify$3) { + if (isObject(identityApiData.userIdentities) && !Object.keys(identityApiData.userIdentities).length || !isObject(identityApiData.userIdentities)) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent + }; + } + } + for (var key in identityApiData) { + if (identityApiData.hasOwnProperty(key)) { + if (!validIdentityRequestKeys[key]) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey + }; + } + if (key === 'onUserAlias' && !Validators.isFunction(identityApiData[key])) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.OnUserAliasType + }; + } + } + } + if (Object.keys(identityApiData).length === 0) { + return { + valid: true + }; + } else { + // identityApiData.userIdentities can't be undefined + if (identityApiData.userIdentities === undefined) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.UserIdentities + }; + // identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object + } else if (identityApiData.userIdentities !== null && !isObject(identityApiData.userIdentities)) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.UserIdentities + }; + } + if (isObject(identityApiData.userIdentities) && Object.keys(identityApiData.userIdentities).length) { + for (var identityType in identityApiData.userIdentities) { + if (identityApiData.userIdentities.hasOwnProperty(identityType)) { + if (Types.IdentityType.getIdentityType(identityType) === false) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey + }; + } + if (!(typeof identityApiData.userIdentities[identityType] === 'string' || identityApiData.userIdentities[identityType] === null)) { + return { + valid: false, + error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues + }; + } + } + } + } + } + } + return { + valid: true + }; + } + }; + + var KitFilterHelper = /** @class */function () { + function KitFilterHelper() {} + KitFilterHelper.hashEventType = function (eventType) { + return generateHash(eventType); + }; + KitFilterHelper.hashEventName = function (eventName, eventType) { + return generateHash(eventType + eventName); + }; + KitFilterHelper.hashEventAttributeKey = function (eventType, eventName, customAttributeName) { + return generateHash(eventType + eventName + customAttributeName); + }; + KitFilterHelper.hashUserAttribute = function (userAttributeKey) { + return generateHash(userAttributeKey); + }; + // User Identities are not actually hashed, this method is named this way to + // be consistent with the filter class. UserIdentityType is also a number + KitFilterHelper.hashUserIdentity = function (userIdentity) { + return userIdentity; + }; + KitFilterHelper.hashConsentPurpose = function (prefix, purpose) { + return generateHash(prefix + purpose); + }; + // The methods below are for conditional forwarding, a type of filter + // hashAttributeCondiitonalForwarding is used for both User and Event + // attribute keys and attribute values + // The backend returns the hashes as strings for conditional forwarding + // but returns "regular" filters as arrays of numbers + // See IFilteringEventAttributeValue in configApiClient.ts as an example + KitFilterHelper.hashAttributeConditionalForwarding = function (attribute) { + return generateHash(attribute).toString(); + }; + KitFilterHelper.hashConsentPurposeConditionalForwarding = function (prefix, purpose) { + return this.hashConsentPurpose(prefix, purpose).toString(); + }; + var _a; + _a = KitFilterHelper; + KitFilterHelper.filterUserAttributes = function (userAttributes, filterList) { + return filterDictionaryWithHash(userAttributes, filterList, function (key) { + return _a.hashUserAttribute(key); + }); + }; + KitFilterHelper.filterUserIdentities = function (userIdentities, filterList) { + return filterDictionaryWithHash(userIdentities, filterList, function (key) { + return _a.hashUserIdentity(IdentityType.getIdentityType(key)); + }); + }; + KitFilterHelper.isFilteredUserAttribute = function (userAttributeKey, filterList) { + var hashedUserAttribute = _a.hashUserAttribute(userAttributeKey); + return filterList && inArray(filterList, hashedUserAttribute); + }; + return KitFilterHelper; + }(); + + var StorageNames$1 = Constants.StorageNames; + function Helpers(mpInstance) { + var self = this; + this.canLog = function () { + if (mpInstance._Store.isEnabled && (mpInstance._Store.devToken || mpInstance._Store.webviewBridgeEnabled)) { + return true; + } + return false; + }; + this.getFeatureFlag = function (feature) { + if (mpInstance._Store.SDKConfig.flags.hasOwnProperty(feature)) { + return mpInstance._Store.SDKConfig.flags[feature]; + } + return null; + }; + this.invokeCallback = function (callback, code, body, mParticleUser, previousMpid) { + if (!callback) { + mpInstance.Logger.warning('There is no callback provided'); + } + try { + if (self.Validators.isFunction(callback)) { + callback({ + httpCode: code, + body: body, + getUser: function getUser() { + if (mParticleUser) { + return mParticleUser; + } else { + return mpInstance.Identity.getCurrentUser(); + } + }, + getPreviousUser: function getPreviousUser() { + if (!previousMpid) { + var users = mpInstance.Identity.getUsers(); + var mostRecentUser = users.shift(); + var currentUser = mParticleUser || mpInstance.Identity.getCurrentUser(); + if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) { + mostRecentUser = users.shift(); + } + return mostRecentUser || null; + } else { + return mpInstance.Identity.getUser(previousMpid); + } + } + }); + } + } catch (e) { + mpInstance.Logger.error('There was an error with your callback: ' + e); + } + }; + this.invokeAliasCallback = function (callback, code, message) { + if (!callback) { + mpInstance.Logger.warning('There is no callback provided'); + } + try { + if (self.Validators.isFunction(callback)) { + var callbackMessage = { + httpCode: code + }; + if (message) { + callbackMessage.message = message; + } + callback(callbackMessage); + } + } catch (e) { + mpInstance.Logger.error('There was an error with your callback: ' + e); + } + }; + + // https://go.mparticle.com/work/SQDSDKS-6047 + // Standalone version of jQuery.extend, from https://github.com/dansdom/extend + this.extend = function () { + var options, + name, + src, + copy, + copyIsArray, + clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false, + // helper which replicates the jquery internal functions + objectHelper = { + hasOwn: Object.prototype.hasOwnProperty, + class2type: {}, + type: function type(obj) { + return obj == null ? String(obj) : objectHelper.class2type[Object.prototype.toString.call(obj)] || 'object'; + }, + isPlainObject: function isPlainObject(obj) { + if (!obj || objectHelper.type(obj) !== 'object' || obj.nodeType || objectHelper.isWindow(obj)) { + return false; + } + try { + if (obj.constructor && !objectHelper.hasOwn.call(obj, 'constructor') && !objectHelper.hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) { + return false; + } + } catch (e) { + return false; + } + var key; + for (key in obj) {} // eslint-disable-line no-empty + + return key === undefined || objectHelper.hasOwn.call(obj, key); + }, + isArray: Array.isArray || function (obj) { + return objectHelper.type(obj) === 'array'; + }, + isFunction: function isFunction(obj) { + return objectHelper.type(obj) === 'function'; + }, + isWindow: function isWindow(obj) { + return obj != null && obj == obj.window; + } + }; // end of objectHelper + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if (_typeof$1(target) !== 'object' && !objectHelper.isFunction(target)) { + target = {}; + } + + // If no second argument is used then this can extend an object that is using this method + if (length === i) { + target = this; + --i; + } + for (; i < length; i++) { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) { + // Extend the base object + for (name in options) { + // Prevent prototype pollution + // https://github.com/advisories/GHSA-jf85-cpcp-j695 + if (name === '__proto__' || name === 'constructor' || name === 'prototype') { + continue; + } + + // Only copy own properties + if (!Object.prototype.hasOwnProperty.call(options, name)) { + continue; + } + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (objectHelper.isPlainObject(copy) || (copyIsArray = objectHelper.isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && objectHelper.isArray(src) ? src : []; + } else { + clone = src && objectHelper.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = self.extend(deep, clone, copy); + + // Don't bring in undefined values + } else if (copy !== undefined) { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + }; + this.createServiceUrl = function (secureServiceUrl, devToken) { + var serviceScheme = window.mParticle && mpInstance._Store.SDKConfig.forceHttps ? 'https://' : window.location.protocol + '//'; + var baseUrl; + if (mpInstance._Store.SDKConfig.forceHttps) { + baseUrl = 'https://' + secureServiceUrl; + } else { + baseUrl = serviceScheme + secureServiceUrl; + } + if (devToken) { + baseUrl = baseUrl + devToken; + } + return baseUrl; + }; + this.createXHR = function (cb) { + var xhr; + try { + xhr = new window.XMLHttpRequest(); + } catch (e) { + mpInstance.Logger.error('Error creating XMLHttpRequest object.'); + } + if (xhr && cb && 'withCredentials' in xhr) { + xhr.onreadystatechange = cb; + } else if (typeof window.XDomainRequest !== 'undefined') { + mpInstance.Logger.verbose('Creating XDomainRequest object'); + try { + xhr = new window.XDomainRequest(); + xhr.onload = cb; + } catch (e) { + mpInstance.Logger.error('Error creating XDomainRequest object'); + } + } + return xhr; + }; + this.filterUserIdentities = function (userIdentitiesObject, filterList) { + var filteredUserIdentities = []; + if (userIdentitiesObject && Object.keys(userIdentitiesObject).length) { + for (var userIdentityName in userIdentitiesObject) { + if (userIdentitiesObject.hasOwnProperty(userIdentityName)) { + var userIdentityType = Types.IdentityType.getIdentityType(userIdentityName); + if (!self.inArray(filterList, userIdentityType)) { + var identity = { + Type: userIdentityType, + Identity: userIdentitiesObject[userIdentityName] + }; + if (userIdentityType === Types.IdentityType.CustomerId) { + filteredUserIdentities.unshift(identity); + } else { + filteredUserIdentities.push(identity); + } + } + } + } + } + return filteredUserIdentities; + }; + this.filterUserIdentitiesForForwarders = KitFilterHelper.filterUserIdentities; + this.filterUserAttributes = KitFilterHelper.filterUserAttributes; + this.isEventType = function (type) { + for (var prop in Types.EventType) { + if (Types.EventType.hasOwnProperty(prop)) { + if (Types.EventType[prop] === type) { + return true; + } + } + } + return false; + }; + this.sanitizeAttributes = function (attrs, name) { + if (!attrs || !self.isObject(attrs)) { + return null; + } + var sanitizedAttrs = {}; + for (var prop in attrs) { + // Make sure that attribute values are not objects or arrays, which are not valid + if (attrs.hasOwnProperty(prop) && self.Validators.isValidAttributeValue(attrs[prop])) { + sanitizedAttrs[prop] = attrs[prop]; + } else { + mpInstance.Logger.warning("For '" + name + "', the corresponding attribute value of '" + prop + "' must be a string, number, boolean, or null."); + } + } + return sanitizedAttrs; + }; + this.isDelayedByIntegration = function (delayedIntegrations, timeoutStart, now) { + if (now - timeoutStart > mpInstance._Store.SDKConfig.integrationDelayTimeout) { + return false; + } + for (var integration in delayedIntegrations) { + if (delayedIntegrations[integration] === true) { + return true; + } else { + continue; + } + } + return false; + }; + this.createMainStorageName = function (workspaceToken) { + if (workspaceToken) { + return StorageNames$1.currentStorageName + '_' + workspaceToken; + } else { + return StorageNames$1.currentStorageName; + } + }; + + // TODO: Refactor SDK to directly use these methods + // https://go.mparticle.com/work/SQDSDKS-5239 + // Utility Functions + this.converted = converted; + this.findKeyInObject = findKeyInObject; + this.parseNumber = parseNumber; + this.inArray = inArray; + this.isObject = isObject; + this.decoded = decoded; + this.parseStringOrNumber = parseStringOrNumber; + this.generateHash = generateHash; + this.generateUniqueId = generateUniqueId; + + // Imported Validators + this.Validators = Validators; + } + + var Messages$8 = Constants.Messages; + var androidBridgeNameBase = 'mParticleAndroid'; + var iosBridgeNameBase = 'mParticle'; + function NativeSdkHelpers(mpInstance) { + var self = this; + this.initializeSessionAttributes = function (apiKey) { + var SetSessionAttribute = Constants.NativeSdkPaths.SetSessionAttribute; + var env = JSON.stringify({ + key: '$src_env', + value: 'webview' + }); + var key = JSON.stringify({ + key: '$src_key', + value: apiKey + }); + self.sendToNative(SetSessionAttribute, env); + if (apiKey) { + self.sendToNative(SetSessionAttribute, key); + } + }; + this.isBridgeV2Available = function (bridgeName) { + if (!bridgeName) { + return false; + } + var androidBridgeName = androidBridgeNameBase + '_' + bridgeName + '_v2'; + var iosBridgeName = iosBridgeNameBase + '_' + bridgeName + '_v2'; + + // iOS v2 bridge + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)) { + return true; + } + // other iOS v2 bridge + // TODO: what to do about people setting things on mParticle itself? + if (window.mParticle && window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName === iosBridgeName) { + return true; + } + // android + if (window.hasOwnProperty(androidBridgeName)) { + return true; + } + return false; + }; + this.isWebviewEnabled = function (requiredWebviewBridgeName, minWebviewBridgeVersion) { + mpInstance._Store.bridgeV2Available = self.isBridgeV2Available(requiredWebviewBridgeName); + mpInstance._Store.bridgeV1Available = self.isBridgeV1Available(); + if (minWebviewBridgeVersion === 2) { + return mpInstance._Store.bridgeV2Available; + } + + // iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName + if (window.mParticle) { + if (window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName !== iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2') { + return false; + } + } + if (minWebviewBridgeVersion < 2) { + // ios + return mpInstance._Store.bridgeV2Available || mpInstance._Store.bridgeV1Available; + } + return false; + }; + this.isBridgeV1Available = function () { + if (mpInstance._Store.SDKConfig.useNativeSdk || window.mParticleAndroid || mpInstance._Store.SDKConfig.isIOS) { + return true; + } + return false; + }; + this.sendToNative = function (path, value) { + if (mpInstance._Store.bridgeV2Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion === 2) { + self.sendViaBridgeV2(path, value, mpInstance._Store.SDKConfig.requiredWebviewBridgeName); + return; + } + if (mpInstance._Store.bridgeV2Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2) { + self.sendViaBridgeV2(path, value, mpInstance._Store.SDKConfig.requiredWebviewBridgeName); + return; + } + if (mpInstance._Store.bridgeV1Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2) { + self.sendViaBridgeV1(path, value); + return; + } + }; + this.sendViaBridgeV1 = function (path, value) { + if (window.mParticleAndroid && window.mParticleAndroid.hasOwnProperty(path)) { + mpInstance.Logger.verbose(Messages$8.InformationMessages.SendAndroid + path); + window.mParticleAndroid[path](value); + } else if (mpInstance._Store.SDKConfig.isIOS) { + mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path); + self.sendViaIframeToIOS(path, value); + } + }; + this.sendViaIframeToIOS = function (path, value) { + var iframe = document.createElement('IFRAME'); + iframe.setAttribute('src', 'mp-sdk://' + path + '/' + encodeURIComponent(value)); + document.documentElement.appendChild(iframe); + iframe.parentNode.removeChild(iframe); + }; + this.sendViaBridgeV2 = function (path, value, requiredWebviewBridgeName) { + if (!requiredWebviewBridgeName) { + return; + } + var androidBridgeName = androidBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2', + androidBridge = window[androidBridgeName], + iosBridgeName = iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2', + iOSBridgeMessageHandler, + iOSBridgeNonMessageHandler; + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers[iosBridgeName]) { + iOSBridgeMessageHandler = window.webkit.messageHandlers[iosBridgeName]; + } + if (mpInstance.uiwebviewBridgeName === iosBridgeName) { + iOSBridgeNonMessageHandler = mpInstance[iosBridgeName]; + } + if (androidBridge && androidBridge.hasOwnProperty(path)) { + mpInstance.Logger.verbose(Messages$8.InformationMessages.SendAndroid + path); + androidBridge[path](value); + return; + } else if (iOSBridgeMessageHandler) { + mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path); + iOSBridgeMessageHandler.postMessage(JSON.stringify({ + path: path, + value: value ? JSON.parse(value) : null + })); + } else if (iOSBridgeNonMessageHandler) { + mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path); + self.sendViaIframeToIOS(path, value); + } + }; + } + + var Messages$7 = Constants.Messages; + var InformationMessages = Messages$7.InformationMessages; + var DAYS_IN_MILLISECONDS = 1000 * 60 * 60 * 24; + // Partner module IDs for cookie sync configurations + var PARTNER_MODULE_IDS = { + AdobeEventForwarder: 11, + DoubleclickDFP: 41, + AppNexus: 50, + Lotame: 58, + TradeDesk: 103, + VerizonMedia: 155, + Rokt: 1277 + }; + function CookieSyncManager(mpInstance) { + var self = this; + // Public + this.attemptCookieSync = function (mpid, mpidIsNotInCookies) { + var _a; + var _b = mpInstance._Store, + pixelConfigurations = _b.pixelConfigurations, + webviewBridgeEnabled = _b.webviewBridgeEnabled; + if (!mpid || webviewBridgeEnabled) { + return; + } + // When noFunctional is true, persistence is not saved, so we cannot track cookie sync + // dates. Skip cookie sync to avoid running it on every page load. + if ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) { + return; + } + var persistence = mpInstance._Persistence.getPersistence(); + if (isEmpty(persistence)) { + return; + } + pixelConfigurations.forEach(function (pixelSettings) { + var _a, _b; + // set requiresConsent to false to start each additional pixel configuration + // set to true only if filteringConsenRuleValues.values.length exists + var requiresConsent = false; + // Filtering rules as defined in UI + var filteringConsentRuleValues = pixelSettings.filteringConsentRuleValues, + pixelUrl = pixelSettings.pixelUrl, + redirectUrl = pixelSettings.redirectUrl, + moduleId = pixelSettings.moduleId, + // Tells you how often we should do a cookie sync (in days) + frequencyCap = pixelSettings.frequencyCap; + var values = (filteringConsentRuleValues || {}).values; + if (isEmpty(pixelUrl)) { + return; + } + if (!isEmpty(values)) { + requiresConsent = true; + } + // If MPID is new to cookies, we should not try to perform the cookie sync + // because a cookie sync can only occur once a user either consents or doesn't. + // we should not check if it's enabled if the user has a blank consent + if (requiresConsent && mpidIsNotInCookies) { + return; + } + // For Rokt, block cookie sync when noTargeting privacy flag is true + if (moduleId === PARTNER_MODULE_IDS.Rokt && mpInstance._CookieConsentManager.getNoTargeting()) { + return; + } + var isEnabledForUserConsent = mpInstance._Consent.isEnabledForUserConsent; + if (!isEnabledForUserConsent(filteringConsentRuleValues, mpInstance.Identity.getCurrentUser())) { + return; + } + var cookieSyncDates = (_b = (_a = persistence[mpid]) === null || _a === void 0 ? void 0 : _a.csd) !== null && _b !== void 0 ? _b : {}; + var lastSyncDateForModule = cookieSyncDates[moduleId] || null; + if (!isLastSyncDateExpired(frequencyCap, lastSyncDateForModule)) { + return; + } + // The Trade Desk requires a URL parameter for GDPR enabled users. + // It is optional but to simplify the code, we add it for all Trade + // // Desk cookie syncs. + var domain = moduleId === PARTNER_MODULE_IDS.TradeDesk ? window.location.hostname : undefined; + // Add domain parameter for Trade Desk + var fullUrl = createCookieSyncUrl(mpid, pixelUrl, redirectUrl, domain); + self.performCookieSync(fullUrl, moduleId.toString(), mpid, cookieSyncDates); + }); + }; + // Private + this.performCookieSync = function (url, moduleId, mpid, cookieSyncDates) { + var img = document.createElement('img'); + mpInstance.Logger.verbose(InformationMessages.CookieSync); + img.onload = function () { + cookieSyncDates[moduleId] = new Date().getTime(); + mpInstance._Persistence.saveUserCookieSyncDatesToPersistence(mpid, cookieSyncDates); + }; + img.src = url; + }; + } + var isLastSyncDateExpired = function isLastSyncDateExpired(frequencyCap, lastSyncDate) { + // If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie + if (!lastSyncDate) { + return true; + } + // Otherwise, compare the last sync date to determine if it should do a cookie sync again + return new Date().getTime() > new Date(lastSyncDate).getTime() + frequencyCap * DAYS_IN_MILLISECONDS; + }; + + var Messages$6 = Constants.Messages; + function SessionManager(mpInstance) { + var self = this; + this.initialize = function () { + var _a; + if (mpInstance._Store.sessionId) { + var _b = mpInstance._Store, + dateLastEventSent = _b.dateLastEventSent, + SDKConfig = _b.SDKConfig; + var sessionTimeout = SDKConfig.sessionTimeout; + if (hasSessionTimedOut(dateLastEventSent === null || dateLastEventSent === void 0 ? void 0 : dateLastEventSent.getTime(), sessionTimeout)) { + self.endSession(); + self.startNewSession(); + } else { + // https://go.mparticle.com/work/SQDSDKS-6045 + // https://go.mparticle.com/work/SQDSDKS-6323 + var currentUser = mpInstance.Identity.getCurrentUser(); + var sdkIdentityRequest = SDKConfig.identifyRequest; + var shouldSuppressIdentify = ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store); + if (!shouldSuppressIdentify && hasIdentityRequestChanged(currentUser, sdkIdentityRequest)) { + mpInstance.Identity.identify(sdkIdentityRequest, SDKConfig.identityCallback); + mpInstance._Store.identifyCalled = true; + mpInstance._Store.SDKConfig.identityCallback = null; + } + } + } else { + self.startNewSession(); + } + }; + this.getSession = function () { + mpInstance.Logger.warning(generateDeprecationMessage('SessionManager.getSession()', false, 'SessionManager.getSessionId()')); + return this.getSessionId(); + }; + this.getSessionId = function () { + return mpInstance._Store.sessionId; + }; + this.startNewSession = function () { + var _a; + mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingNewSession); + if (mpInstance._Helpers.canLog()) { + mpInstance._Store.sessionId = mpInstance._Helpers.generateUniqueId().toUpperCase(); + var currentUser = mpInstance.Identity.getCurrentUser(); + var mpid = currentUser ? currentUser.getMPID() : null; + if (mpid) { + mpInstance._Store.currentSessionMPIDs = [mpid]; + } + if (!mpInstance._Store.sessionStartDate) { + var date = new Date(); + mpInstance._Store.sessionStartDate = date; + mpInstance._Store.dateLastEventSent = date; + } + self.setSessionTimer(); + var shouldSuppressIdentify = ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store); + if (!mpInstance._Store.identifyCalled && !shouldSuppressIdentify) { + mpInstance.Identity.identify(mpInstance._Store.SDKConfig.identifyRequest, mpInstance._Store.SDKConfig.identityCallback); + mpInstance._Store.identifyCalled = true; + mpInstance._Store.SDKConfig.identityCallback = null; + } + mpInstance._Events.logEvent({ + messageType: Types.MessageType.SessionStart + }); + } else { + mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession); + } + }; + this.endSession = function (override) { + var _a, _b, _c, _d; + mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingEndSession); + if (override) { + performSessionEnd(); + return; + } + if (!mpInstance._Helpers.canLog()) { + // At this moment, an AbandonedEndSession is defined when one of three things occurs: + // - the SDK's store is not enabled because mParticle.setOptOut was called + // - the devToken is undefined + // - webviewBridgeEnabled is set to false + mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession); + (_a = mpInstance._timeOnSiteTimer) === null || _a === void 0 ? void 0 : _a.resetTimer(); + return; + } + var cookies = mpInstance._Persistence.getPersistence(); + if (!cookies || cookies.gs && !cookies.gs.sid) { + mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd); + (_b = mpInstance._timeOnSiteTimer) === null || _b === void 0 ? void 0 : _b.resetTimer(); + return; + } + // sessionId is not equal to cookies.sid if cookies.sid is changed in another tab + if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) { + mpInstance._Store.sessionId = cookies.gs.sid; + } + if ((_c = cookies === null || cookies === void 0 ? void 0 : cookies.gs) === null || _c === void 0 ? void 0 : _c.les) { + var sessionTimeout = mpInstance._Store.SDKConfig.sessionTimeout; + if (hasSessionTimedOut(cookies.gs.les, sessionTimeout)) { + performSessionEnd(); + } else { + self.setSessionTimer(); + (_d = mpInstance._timeOnSiteTimer) === null || _d === void 0 ? void 0 : _d.resetTimer(); + } + } + }; + this.setSessionTimer = function () { + var sessionTimeoutInMilliseconds = mpInstance._Store.SDKConfig.sessionTimeout * 60000; + mpInstance._Store.globalTimer = window.setTimeout(function () { + self.endSession(); + }, sessionTimeoutInMilliseconds); + }; + this.resetSessionTimer = function () { + if (!mpInstance._Store.webviewBridgeEnabled) { + if (!mpInstance._Store.sessionId) { + self.startNewSession(); + } + self.clearSessionTimeout(); + self.setSessionTimer(); + } + self.startNewSessionIfNeeded(); + }; + this.clearSessionTimeout = function () { + clearTimeout(mpInstance._Store.globalTimer); + }; + this.startNewSessionIfNeeded = function () { + if (!mpInstance._Store.webviewBridgeEnabled) { + var persistence = mpInstance._Persistence.getPersistence(); + if (!mpInstance._Store.sessionId && persistence) { + if (persistence.sid) { + mpInstance._Store.sessionId = persistence.sid; + } else { + self.startNewSession(); + } + } + } + }; + /** + * Checks if the session has expired based on the last event timestamp + * @param lastEventTimestamp - Unix timestamp in milliseconds of the last event + * @param sessionTimeout - Session timeout in minutes + * @returns true if the session has expired, false otherwise + */ + function hasSessionTimedOut(lastEventTimestamp, sessionTimeout) { + if (!lastEventTimestamp || !sessionTimeout || sessionTimeout <= 0) { + return false; + } + var sessionTimeoutInMilliseconds = sessionTimeout * 60000; + var timeSinceLastEvent = Date.now() - lastEventTimestamp; + return timeSinceLastEvent >= sessionTimeoutInMilliseconds; + } + /** + * Performs session end operations: + * - Logs a SessionEnd event + * - Nullifies the session ID and related data + * - Resets the time-on-site timer + */ + function performSessionEnd() { + var _a; + mpInstance._Events.logEvent({ + messageType: Types.MessageType.SessionEnd + }); + mpInstance._Store.nullifySession(); + (_a = mpInstance._timeOnSiteTimer) === null || _a === void 0 ? void 0 : _a.resetTimer(); + } + } + + var Messages$5 = Constants.Messages; + function Ecommerce(mpInstance) { + var self = this; + + // https://go.mparticle.com/work/SQDSDKS-4801 + this.convertTransactionAttributesToProductAction = function (transactionAttributes, productAction) { + if (transactionAttributes.hasOwnProperty('Id')) { + productAction.TransactionId = transactionAttributes.Id; + } + if (transactionAttributes.hasOwnProperty('Affiliation')) { + productAction.Affiliation = transactionAttributes.Affiliation; + } + if (transactionAttributes.hasOwnProperty('CouponCode')) { + productAction.CouponCode = transactionAttributes.CouponCode; + } + if (transactionAttributes.hasOwnProperty('Revenue')) { + productAction.TotalAmount = this.sanitizeAmount(transactionAttributes.Revenue, 'Revenue'); + } + if (transactionAttributes.hasOwnProperty('Shipping')) { + productAction.ShippingAmount = this.sanitizeAmount(transactionAttributes.Shipping, 'Shipping'); + } + if (transactionAttributes.hasOwnProperty('Tax')) { + productAction.TaxAmount = this.sanitizeAmount(transactionAttributes.Tax, 'Tax'); + } + if (transactionAttributes.hasOwnProperty('Step')) { + productAction.CheckoutStep = transactionAttributes.Step; + } + if (transactionAttributes.hasOwnProperty('Option')) { + productAction.CheckoutOptions = transactionAttributes.Option; + } + }; + this.getProductActionEventName = function (productActionType) { + switch (productActionType) { + case Types.ProductActionType.AddToCart: + return 'AddToCart'; + case Types.ProductActionType.AddToWishlist: + return 'AddToWishlist'; + case Types.ProductActionType.Checkout: + return 'Checkout'; + case Types.ProductActionType.CheckoutOption: + return 'CheckoutOption'; + case Types.ProductActionType.Click: + return 'Click'; + case Types.ProductActionType.Purchase: + return 'Purchase'; + case Types.ProductActionType.Refund: + return 'Refund'; + case Types.ProductActionType.RemoveFromCart: + return 'RemoveFromCart'; + case Types.ProductActionType.RemoveFromWishlist: + return 'RemoveFromWishlist'; + case Types.ProductActionType.ViewDetail: + return 'ViewDetail'; + case Types.ProductActionType.Unknown: + default: + return 'Unknown'; + } + }; + this.getPromotionActionEventName = function (promotionActionType) { + switch (promotionActionType) { + case Types.PromotionActionType.PromotionClick: + return 'PromotionClick'; + case Types.PromotionActionType.PromotionView: + return 'PromotionView'; + default: + return 'Unknown'; + } + }; + this.convertProductActionToEventType = function (productActionType) { + switch (productActionType) { + case Types.ProductActionType.AddToCart: + return Types.CommerceEventType.ProductAddToCart; + case Types.ProductActionType.AddToWishlist: + return Types.CommerceEventType.ProductAddToWishlist; + case Types.ProductActionType.Checkout: + return Types.CommerceEventType.ProductCheckout; + case Types.ProductActionType.CheckoutOption: + return Types.CommerceEventType.ProductCheckoutOption; + case Types.ProductActionType.Click: + return Types.CommerceEventType.ProductClick; + case Types.ProductActionType.Purchase: + return Types.CommerceEventType.ProductPurchase; + case Types.ProductActionType.Refund: + return Types.CommerceEventType.ProductRefund; + case Types.ProductActionType.RemoveFromCart: + return Types.CommerceEventType.ProductRemoveFromCart; + case Types.ProductActionType.RemoveFromWishlist: + return Types.CommerceEventType.ProductRemoveFromWishlist; + + // https://go.mparticle.com/work/SQDSDKS-4801 + case Types.ProductActionType.Unknown: + return Types.EventType.Unknown; + case Types.ProductActionType.ViewDetail: + return Types.CommerceEventType.ProductViewDetail; + default: + mpInstance.Logger.error('Could not convert product action type ' + productActionType + ' to event type'); + return null; + } + }; + this.convertPromotionActionToEventType = function (promotionActionType) { + switch (promotionActionType) { + case Types.PromotionActionType.PromotionClick: + return Types.CommerceEventType.PromotionClick; + case Types.PromotionActionType.PromotionView: + return Types.CommerceEventType.PromotionView; + default: + mpInstance.Logger.error('Could not convert promotion action type ' + promotionActionType + ' to event type'); + return null; + } + }; + this.generateExpandedEcommerceName = function (eventName, plusOne) { + return 'eCommerce - ' + eventName + ' - ' + (plusOne ? 'Total' : 'Item'); + }; + + // https://go.mparticle.com/work/SQDSDKS-4801 + this.extractProductAttributes = function (attributes, product) { + if (product.CouponCode) { + attributes['Coupon Code'] = product.CouponCode; + } + if (product.Brand) { + attributes['Brand'] = product.Brand; + } + if (product.Category) { + attributes['Category'] = product.Category; + } + if (product.Name) { + attributes['Name'] = product.Name; + } + if (product.Sku) { + attributes['Id'] = product.Sku; + } + if (product.Price) { + attributes['Item Price'] = product.Price; + } + if (product.Quantity) { + attributes['Quantity'] = product.Quantity; + } + if (product.Position) { + attributes['Position'] = product.Position; + } + if (product.Variant) { + attributes['Variant'] = product.Variant; + } + attributes['Total Product Amount'] = product.TotalAmount || 0; + }; + + // https://go.mparticle.com/work/SQDSDKS-4801 + this.extractTransactionId = function (attributes, productAction) { + if (productAction.TransactionId) { + attributes['Transaction Id'] = productAction.TransactionId; + } + }; + + // https://go.mparticle.com/work/SQDSDKS-4801 + this.extractActionAttributes = function (attributes, productAction) { + self.extractTransactionId(attributes, productAction); + if (productAction.Affiliation) { + attributes['Affiliation'] = productAction.Affiliation; + } + if (productAction.CouponCode) { + attributes['Coupon Code'] = productAction.CouponCode; + } + if (productAction.TotalAmount) { + attributes['Total Amount'] = productAction.TotalAmount; + } + if (productAction.ShippingAmount) { + attributes['Shipping Amount'] = productAction.ShippingAmount; + } + if (productAction.TaxAmount) { + attributes['Tax Amount'] = productAction.TaxAmount; + } + if (productAction.CheckoutOptions) { + attributes['Checkout Options'] = productAction.CheckoutOptions; + } + if (productAction.CheckoutStep) { + attributes['Checkout Step'] = productAction.CheckoutStep; + } + }; + + // https://go.mparticle.com/work/SQDSDKS-4801 + this.extractPromotionAttributes = function (attributes, promotion) { + if (promotion.Id) { + attributes['Id'] = promotion.Id; + } + if (promotion.Creative) { + attributes['Creative'] = promotion.Creative; + } + if (promotion.Name) { + attributes['Name'] = promotion.Name; + } + if (promotion.Position) { + attributes['Position'] = promotion.Position; + } + }; + this.buildProductList = function (event, product) { + if (product) { + if (Array.isArray(product)) { + return product; + } + return [product]; + } + return event.ShoppingCart.ProductList; + }; + this.createProduct = function (name, sku, price, quantity, variant, category, brand, position, couponCode, attributes) { + attributes = mpInstance._Helpers.sanitizeAttributes(attributes, name); + if (typeof name !== 'string') { + mpInstance.Logger.error('Name is required when creating a product'); + return null; + } + if (!mpInstance._Helpers.Validators.isStringOrNumber(sku)) { + mpInstance.Logger.error('SKU is required when creating a product, and must be a string or a number'); + return null; + } + if (!mpInstance._Helpers.Validators.isStringOrNumber(price)) { + mpInstance.Logger.error('Price is required when creating a product, and must be a string or a number'); + return null; + } else { + price = mpInstance._Helpers.parseNumber(price); + } + if (position && !mpInstance._Helpers.Validators.isNumber(position)) { + mpInstance.Logger.error('Position must be a number, it will be set to null.'); + position = null; + } + if (!mpInstance._Helpers.Validators.isStringOrNumber(quantity)) { + quantity = 1; + } else { + quantity = mpInstance._Helpers.parseNumber(quantity); + } + return { + Name: name, + Sku: sku, + Price: price, + Quantity: quantity, + Brand: brand, + Variant: variant, + Category: category, + Position: position, + CouponCode: couponCode, + TotalAmount: quantity * price, + Attributes: attributes + }; + }; + this.createPromotion = function (id, creative, name, position) { + if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) { + mpInstance.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired); + return null; + } + return { + Id: id, + Creative: creative, + Name: name, + Position: position + }; + }; + this.createImpression = function (name, product) { + if (typeof name !== 'string') { + mpInstance.Logger.error('Name is required when creating an impression.'); + return null; + } + if (!product) { + mpInstance.Logger.error('Product is required when creating an impression.'); + return null; + } + return { + Name: name, + Product: product + }; + }; + this.createTransactionAttributes = function (id, affiliation, couponCode, revenue, shipping, tax) { + if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) { + mpInstance.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired); + return null; + } + return { + Id: id, + Affiliation: affiliation, + CouponCode: couponCode, + Revenue: revenue, + Shipping: shipping, + Tax: tax + }; + }; + this.expandProductImpression = function (commerceEvent) { + var appEvents = []; + if (!commerceEvent.ProductImpressions) { + return appEvents; + } + commerceEvent.ProductImpressions.forEach(function (productImpression) { + if (productImpression.ProductList) { + productImpression.ProductList.forEach(function (product) { + var attributes = mpInstance._Helpers.extend(false, {}, commerceEvent.EventAttributes); + if (product.Attributes) { + for (var attribute in product.Attributes) { + attributes[attribute] = product.Attributes[attribute]; + } + } + self.extractProductAttributes(attributes, product); + if (productImpression.ProductImpressionList) { + attributes['Product Impression List'] = productImpression.ProductImpressionList; + } + var appEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.PageEvent, + name: self.generateExpandedEcommerceName('Impression'), + data: attributes, + eventType: Types.EventType.Transaction + }); + appEvents.push(appEvent); + }); + } + }); + return appEvents; + }; + this.expandCommerceEvent = function (event) { + if (!event) { + return null; + } + return self.expandProductAction(event).concat(self.expandPromotionAction(event)).concat(self.expandProductImpression(event)); + }; + this.expandPromotionAction = function (commerceEvent) { + var appEvents = []; + if (!commerceEvent.PromotionAction) { + return appEvents; + } + var promotions = commerceEvent.PromotionAction.PromotionList; + promotions.forEach(function (promotion) { + var attributes = mpInstance._Helpers.extend(false, {}, commerceEvent.EventAttributes); + self.extractPromotionAttributes(attributes, promotion); + var appEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.PageEvent, + name: self.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(commerceEvent.PromotionAction.PromotionActionType)), + data: attributes, + eventType: Types.EventType.Transaction + }); + appEvents.push(appEvent); + }); + return appEvents; + }; + this.expandProductAction = function (commerceEvent) { + var appEvents = []; + if (!commerceEvent.ProductAction) { + return appEvents; + } + var shouldExtractActionAttributes = false; + if (commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Purchase || commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Refund) { + var attributes = mpInstance._Helpers.extend(false, {}, commerceEvent.EventAttributes); + attributes['Product Count'] = commerceEvent.ProductAction.ProductList ? commerceEvent.ProductAction.ProductList.length : 0; + self.extractActionAttributes(attributes, commerceEvent.ProductAction); + if (commerceEvent.CurrencyCode) { + attributes['Currency Code'] = commerceEvent.CurrencyCode; + } + var plusOneEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.PageEvent, + name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType), true), + data: attributes, + eventType: Types.EventType.Transaction + }); + appEvents.push(plusOneEvent); + } else { + shouldExtractActionAttributes = true; + } + var products = commerceEvent.ProductAction.ProductList; + if (!products) { + return appEvents; + } + products.forEach(function (product) { + var attributes = mpInstance._Helpers.extend(false, commerceEvent.EventAttributes, product.Attributes); + if (shouldExtractActionAttributes) { + self.extractActionAttributes(attributes, commerceEvent.ProductAction); + } else { + self.extractTransactionId(attributes, commerceEvent.ProductAction); + } + self.extractProductAttributes(attributes, product); + var productEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.PageEvent, + name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType)), + data: attributes, + eventType: Types.EventType.Transaction + }); + appEvents.push(productEvent); + }); + return appEvents; + }; + this.createCommerceEventObject = function (customFlags, options) { + var baseEvent; + // https://go.mparticle.com/work/SQDSDKS-4801 + var extend = mpInstance._Helpers.extend; + mpInstance.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent); + if (mpInstance._Helpers.canLog()) { + baseEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.Commerce, + sourceMessageId: options === null || options === void 0 ? void 0 : options.sourceMessageId + }); + baseEvent.EventName = 'eCommerce - '; + baseEvent.CurrencyCode = mpInstance._Store.currencyCode; + baseEvent.ShoppingCart = []; + baseEvent.CustomFlags = extend(baseEvent.CustomFlags, customFlags); + return baseEvent; + } else { + mpInstance.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent); + } + return null; + }; + + // sanitizes any non number, non string value to 0 + this.sanitizeAmount = function (amount, category) { + if (!mpInstance._Helpers.Validators.isStringOrNumber(amount)) { + var message = [category, 'must be of type number. A', _typeof$1(amount), 'was passed. Converting to 0'].join(' '); + mpInstance.Logger.warning(message); + return 0; + } + + // if amount is a string, it will be parsed into a number if possible, or set to 0 + return mpInstance._Helpers.parseNumber(amount); + }; + } + + var ForegroundTimeTracker = /** @class */function () { + function ForegroundTimeTracker(timerKey, noFunctional) { + if (noFunctional === void 0) { + noFunctional = false; + } + this.noFunctional = noFunctional; + this.isTrackerActive = false; + this.localStorageName = ''; + this.startTime = 0; + this.totalTime = 0; + this.localStorageName = "mprtcl-tos-".concat(timerKey); + this.timerVault = new LocalStorageVault(this.localStorageName); + if (!this.noFunctional) { + this.loadTimeFromStorage(); + } + this.addHandlers(); + if (document.hidden === false) { + this.startTracking(); + } + } + ForegroundTimeTracker.prototype.addHandlers = function () { + var _this = this; + // when user switches tabs or minimizes the window + document.addEventListener('visibilitychange', function () { + return _this.handleVisibilityChange(); + }); + // when user switches to another application + window.addEventListener('blur', function () { + return _this.handleWindowBlur(); + }); + // when window gains focus + window.addEventListener('focus', function () { + return _this.handleWindowFocus(); + }); + // this ensures that timers between tabs are in sync + window.addEventListener('storage', function (event) { + return _this.syncAcrossTabs(event); + }); + // when user closes tab, refreshes, or navigates to another page via link + window.addEventListener('beforeunload', function () { + return _this.updateTimeInPersistence(); + }); + }; + ForegroundTimeTracker.prototype.handleVisibilityChange = function () { + if (document.hidden) { + this.stopTracking(); + } else { + this.startTracking(); + } + }; + ForegroundTimeTracker.prototype.handleWindowBlur = function () { + if (this.isTrackerActive) { + this.stopTracking(); + } + }; + ForegroundTimeTracker.prototype.handleWindowFocus = function () { + if (!this.isTrackerActive) { + this.startTracking(); + } + }; + ForegroundTimeTracker.prototype.syncAcrossTabs = function (event) { + if (event.key === this.localStorageName && event.newValue !== null) { + var newTime = parseFloat(event.newValue) || 0; + this.totalTime = newTime; + } + }; + ForegroundTimeTracker.prototype.updateTimeInPersistence = function () { + if (this.isTrackerActive && !this.noFunctional) { + this.timerVault.store(Math.round(this.totalTime)); + } + }; + ForegroundTimeTracker.prototype.loadTimeFromStorage = function () { + var storedTime = this.timerVault.retrieve(); + if (isNumber(storedTime) && storedTime !== null) { + this.totalTime = storedTime; + } + }; + ForegroundTimeTracker.prototype.startTracking = function () { + if (!document.hidden) { + this.startTime = Math.floor(performance.now()); + this.isTrackerActive = true; + } + }; + ForegroundTimeTracker.prototype.stopTracking = function () { + if (this.isTrackerActive) { + this.setTotalTime(); + this.updateTimeInPersistence(); + this.isTrackerActive = false; + } + }; + ForegroundTimeTracker.prototype.setTotalTime = function () { + if (this.isTrackerActive) { + var now = Math.floor(performance.now()); + this.totalTime += now - this.startTime; + this.startTime = now; + } + }; + ForegroundTimeTracker.prototype.getTimeInForeground = function () { + this.setTotalTime(); + this.updateTimeInPersistence(); + return this.totalTime; + }; + ForegroundTimeTracker.prototype.resetTimer = function () { + this.totalTime = 0; + this.updateTimeInPersistence(); + }; + return ForegroundTimeTracker; + }(); + + function createSDKConfig(config) { + // TODO: Refactor to create a default config object + var sdkConfig = {}; + for (var prop in Constants.DefaultConfig) { + if (Constants.DefaultConfig.hasOwnProperty(prop)) { + sdkConfig[prop] = Constants.DefaultConfig[prop]; + } + } + if (config) { + for (var prop in config) { + if (config.hasOwnProperty(prop)) { + sdkConfig[prop] = config[prop]; + } + } + } + for (var prop in Constants.DefaultBaseUrls) { + sdkConfig[prop] = Constants.DefaultBaseUrls[prop]; + } + // Always initialize flags to at least an empty object to prevent undefined access + sdkConfig.flags = sdkConfig.flags || {}; + return sdkConfig; + } + // TODO: Merge this with SDKStoreApi in sdkRuntimeModels + function Store(config, mpInstance, apiKey) { + var _this = this; + var createMainStorageName = mpInstance._Helpers.createMainStorageName; + var isWebviewEnabled = mpInstance._NativeSdkHelpers.isWebviewEnabled; + var defaultStore = { + isEnabled: true, + sessionAttributes: {}, + localSessionAttributes: {}, + currentSessionMPIDs: [], + consentState: null, + sessionId: null, + isFirstRun: null, + clientId: null, + deviceId: null, + devToken: null, + serverSettings: {}, + dateLastEventSent: null, + sessionStartDate: null, + currentPosition: null, + isTracking: false, + watchPositionId: null, + cartProducts: [], + eventQueue: [], + currencyCode: null, + globalTimer: null, + context: null, + configurationLoaded: false, + identityCallInFlight: false, + identityCallFailed: false, + identifyRequestCount: 0, + SDKConfig: {}, + nonCurrentUserMPIDs: {}, + identifyCalled: false, + isLoggedIn: false, + cookieSyncDates: {}, + integrationAttributes: {}, + requireDelay: true, + isLocalStorageAvailable: null, + storageName: null, + activeForwarders: [], + kits: {}, + sideloadedKits: [], + configuredForwarders: [], + pixelConfigurations: [], + wrapperSDKInfo: { + name: 'none', + version: null, + isInfoSet: false + }, + roktAccountId: null, + integrationName: null, + // Placeholder for in-memory persistence model + persistenceData: { + gs: {} + } + }; + for (var key in defaultStore) { + this[key] = defaultStore[key]; + } + this.devToken = apiKey || null; + this.integrationDelayTimeoutStart = Date.now(); + // Set configuration to default settings + this.SDKConfig = createSDKConfig(config); + if (config) { + if (!config.hasOwnProperty('flags')) { + this.SDKConfig.flags = {}; + } + this.SDKConfig.flags = processFlags(config); + if (config.deviceId) { + this.deviceId = config.deviceId; + } + if (config.hasOwnProperty('isDevelopmentMode')) { + this.SDKConfig.isDevelopmentMode = returnConvertedBoolean(config.isDevelopmentMode); + } else { + this.SDKConfig.isDevelopmentMode = false; + } + var baseUrls = processBaseUrls(config, this.SDKConfig.flags, apiKey); + for (var baseUrlKeys in baseUrls) { + this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys]; + } + this.SDKConfig.useNativeSdk = !!config.useNativeSdk; + this.SDKConfig.kits = config.kits || {}; + this.SDKConfig.sideloadedKits = config.sideloadedKits || []; + if (config.hasOwnProperty('isIOS')) { + this.SDKConfig.isIOS = config.isIOS; + } else { + this.SDKConfig.isIOS = window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false; + } + if (config.hasOwnProperty('useCookieStorage')) { + this.SDKConfig.useCookieStorage = config.useCookieStorage; + } else { + this.SDKConfig.useCookieStorage = false; + } + if (config.hasOwnProperty('maxProducts')) { + this.SDKConfig.maxProducts = config.maxProducts; + } else { + this.SDKConfig.maxProducts = Constants.DefaultConfig.maxProducts; + } + if (config.hasOwnProperty('maxCookieSize')) { + this.SDKConfig.maxCookieSize = config.maxCookieSize; + } else { + this.SDKConfig.maxCookieSize = Constants.DefaultConfig.maxCookieSize; + } + if (config.hasOwnProperty('appName')) { + this.SDKConfig.appName = config.appName; + } + if (config.hasOwnProperty('package')) { + this.SDKConfig["package"] = config["package"]; + } + if (config.hasOwnProperty('integrationDelayTimeout')) { + this.SDKConfig.integrationDelayTimeout = config.integrationDelayTimeout; + } else { + this.SDKConfig.integrationDelayTimeout = Constants.DefaultConfig.integrationDelayTimeout; + } + if (config.hasOwnProperty('identifyRequest')) { + this.SDKConfig.identifyRequest = config.identifyRequest; + } + if (config.hasOwnProperty('identityCallback')) { + var callback = config.identityCallback; + if (mpInstance._Helpers.Validators.isFunction(callback)) { + this.SDKConfig.identityCallback = config.identityCallback; + } else { + mpInstance.Logger.warning('The optional callback must be a function. You tried entering a(n) ' + _typeof$1(callback) + ' . Callback not set. Please set your callback again.'); + } + } + if (config.hasOwnProperty('appVersion')) { + this.SDKConfig.appVersion = config.appVersion; + } + if (config.hasOwnProperty('appName')) { + this.SDKConfig.appName = config.appName; + } + if (config.hasOwnProperty('sessionTimeout')) { + this.SDKConfig.sessionTimeout = config.sessionTimeout; + } + if (config.hasOwnProperty('dataPlan')) { + this.SDKConfig.dataPlan = { + PlanVersion: null, + PlanId: null + }; + var dataPlan = config.dataPlan; + if (dataPlan.planId) { + if (isDataPlanSlug(dataPlan.planId)) { + this.SDKConfig.dataPlan.PlanId = dataPlan.planId; + } else { + mpInstance.Logger.error('Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)'); + } + } + if (dataPlan.planVersion) { + if (isNumber(dataPlan.planVersion)) { + this.SDKConfig.dataPlan.PlanVersion = dataPlan.planVersion; + } else { + mpInstance.Logger.error('Your data plan version must be a number'); + } + } + } else { + this.SDKConfig.dataPlan = {}; + } + if (config.hasOwnProperty('forceHttps')) { + this.SDKConfig.forceHttps = config.forceHttps; + } else { + this.SDKConfig.forceHttps = true; + } + // Some forwarders require custom flags on initialization, so allow them to be set using config object + this.SDKConfig.customFlags = config.customFlags || {}; + if (config.hasOwnProperty('minWebviewBridgeVersion')) { + this.SDKConfig.minWebviewBridgeVersion = config.minWebviewBridgeVersion; + } else { + this.SDKConfig.minWebviewBridgeVersion = 1; + } + if (config.hasOwnProperty('aliasMaxWindow')) { + this.SDKConfig.aliasMaxWindow = config.aliasMaxWindow; + } else { + this.SDKConfig.aliasMaxWindow = Constants.DefaultConfig.aliasMaxWindow; + } + if (config.hasOwnProperty('dataPlanOptions')) { + var dataPlanOptions = config.dataPlanOptions; + if (!dataPlanOptions.hasOwnProperty('dataPlanVersion') || !dataPlanOptions.hasOwnProperty('blockUserAttributes') || !dataPlanOptions.hasOwnProperty('blockEventAttributes') || !dataPlanOptions.hasOwnProperty('blockEvents') || !dataPlanOptions.hasOwnProperty('blockUserIdentities')) { + mpInstance.Logger.error('Ensure your config.dataPlanOptions object has the following keys: a "dataPlanVersion" object, and "blockUserAttributes", "blockEventAttributes", "blockEvents", "blockUserIdentities" booleans'); + } + } + if (config.hasOwnProperty('onCreateBatch')) { + if (typeof config.onCreateBatch === 'function') { + this.SDKConfig.onCreateBatch = config.onCreateBatch; + } else { + mpInstance.Logger.error('config.onCreateBatch must be a function'); + // set to undefined because all items are set on createSDKConfig + this.SDKConfig.onCreateBatch = undefined; + } + } + } + this._getFromPersistence = function (mpid, key) { + if (!mpid) { + return null; + } + _this.syncPersistenceData(); + if (_this.persistenceData && _this.persistenceData[mpid] && _this.persistenceData[mpid][key]) { + return _this.persistenceData[mpid][key]; + } else { + return null; + } + }; + this._setPersistence = function (mpid, key, value) { + var _a; + if (!mpid) { + return; + } + _this.syncPersistenceData(); + if (_this.persistenceData) { + if (_this.persistenceData[mpid]) { + _this.persistenceData[mpid][key] = value; + } else { + _this.persistenceData[mpid] = (_a = {}, _a[key] = value, _a); + } + // Clear out persistence attributes that are empty + // so that we don't upload empty or undefined values + if (isObject(_this.persistenceData[mpid][key]) && isEmpty(_this.persistenceData[mpid][key])) { + delete _this.persistenceData[mpid][key]; + } + mpInstance._Persistence.savePersistence(_this.persistenceData); + } + }; + this.hasInvalidIdentifyRequest = function () { + var identifyRequest = _this.SDKConfig.identifyRequest; + return isObject(identifyRequest) && isObject(identifyRequest.userIdentities) && isEmpty(identifyRequest.userIdentities) || !identifyRequest; + }; + this.getConsentState = function (mpid) { + var fromMinifiedJsonObject = mpInstance._Consent.ConsentSerialization.fromMinifiedJsonObject; + var serializedConsentState = _this._getFromPersistence(mpid, 'con'); + if (!isEmpty(serializedConsentState)) { + return fromMinifiedJsonObject(serializedConsentState); + } + return null; + }; + this.setConsentState = function (mpid, consentState) { + var toMinifiedJsonObject = mpInstance._Consent.ConsentSerialization.toMinifiedJsonObject; + // If ConsentState is null, we assume the intent is to clear out the consent state + if (consentState || consentState === null) { + _this._setPersistence(mpid, 'con', toMinifiedJsonObject(consentState)); + } + }; + this.getDeviceId = function () { + return _this.deviceId; + }; + this.setDeviceId = function (deviceId) { + _this.deviceId = deviceId; + _this.persistenceData.gs.das = deviceId; + mpInstance._Persistence.update(); + }; + this.getFirstSeenTime = function (mpid) { + return _this._getFromPersistence(mpid, 'fst'); + }; + this.setFirstSeenTime = function (mpid, _time) { + if (!mpid) { + return; + } + var time = _time || new Date().getTime(); + _this._setPersistence(mpid, 'fst', time); + }; + this.getLastSeenTime = function (mpid) { + if (!mpid) { + return null; + } + // https://go.mparticle.com/work/SQDSDKS-6315 + var currentUser = mpInstance.Identity.getCurrentUser(); + if (mpid === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.getMPID())) { + // if the mpid is the current user, its last seen time is the current time + return new Date().getTime(); + } + return _this._getFromPersistence(mpid, 'lst'); + }; + this.setLastSeenTime = function (mpid, _time) { + if (!mpid) { + return; + } + var time = _time || new Date().getTime(); + _this._setPersistence(mpid, 'lst', time); + }; + this.getLocalSessionAttributes = function () { + return _this.localSessionAttributes || {}; + }; + this.setLocalSessionAttribute = function (key, value) { + var _a; + _this.localSessionAttributes[key] = value; + _this.persistenceData.gs.lsa = __assign(__assign({}, _this.persistenceData.gs.lsa || {}), (_a = {}, _a[key] = value, _a)); + mpInstance._Persistence.savePersistence(_this.persistenceData); + }; + this.syncPersistenceData = function () { + var persistenceData = mpInstance._Persistence.getPersistence(); + _this.persistenceData = mpInstance._Helpers.extend({}, _this.persistenceData, persistenceData); + }; + this.getUserAttributes = function (mpid) { + return _this._getFromPersistence(mpid, 'ua') || {}; + }; + this.setUserAttributes = function (mpid, userAttributes) { + return _this._setPersistence(mpid, 'ua', userAttributes); + }; + this.getUserIdentities = function (mpid) { + return _this._getFromPersistence(mpid, 'ui') || {}; + }; + this.setUserIdentities = function (mpid, userIdentities) { + _this._setPersistence(mpid, 'ui', userIdentities); + }; + this.getRoktAccountId = function () { + return _this.roktAccountId; + }; + this.setRoktAccountId = function (accountId) { + _this.roktAccountId = accountId; + }; + this.getIntegrationName = function () { + return _this.integrationName; + }; + this.setIntegrationName = function (integrationName) { + _this.integrationName = integrationName; + }; + this.addMpidToSessionHistory = function (mpid, previousMPID) { + var indexOfMPID = _this.currentSessionMPIDs.indexOf(mpid); + if (mpid && previousMPID !== mpid && indexOfMPID < 0) { + _this.currentSessionMPIDs.push(mpid); + return; + } + if (indexOfMPID >= 0) { + _this.currentSessionMPIDs = moveElementToEnd(_this.currentSessionMPIDs, indexOfMPID); + } + }; + this.nullifySession = function () { + _this.sessionId = null; + _this.dateLastEventSent = null; + _this.sessionStartDate = null; + _this.sessionAttributes = {}; + _this.localSessionAttributes = {}; + mpInstance._Persistence.update(); + }; + this.processConfig = function (config) { + var _a; + var workspaceToken = config.workspaceToken, + requiredWebviewBridgeName = config.requiredWebviewBridgeName; + // We should reprocess the flags and baseUrls in case they have changed when we request an updated config + // such as if the SDK is being self-hosted and the flags are different on the server config + // https://go.mparticle.com/work/SQDSDKS-6317 + // Only update flags if the config actually has flags (don't overwrite with empty object) + if (config.flags) { + _this.SDKConfig.flags = processFlags(config); + } + var baseUrls = processBaseUrls(config, _this.SDKConfig.flags, apiKey); + for (var baseUrlKeys in baseUrls) { + _this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys]; + } + if (workspaceToken) { + _this.SDKConfig.workspaceToken = workspaceToken; + var noFunctional = ((_a = config === null || config === void 0 ? void 0 : config.launcherOptions) === null || _a === void 0 ? void 0 : _a.noFunctional) === true; + mpInstance._timeOnSiteTimer = new ForegroundTimeTracker(workspaceToken, noFunctional); + } else { + mpInstance.Logger.warning('You should have a workspaceToken on your config object for security purposes.'); + } + // add a new function to apply items to the store that require config to be returned + _this.storageName = createMainStorageName(workspaceToken); + _this.SDKConfig.requiredWebviewBridgeName = requiredWebviewBridgeName || workspaceToken; + _this.webviewBridgeEnabled = isWebviewEnabled(_this.SDKConfig.requiredWebviewBridgeName, _this.SDKConfig.minWebviewBridgeVersion); + _this.configurationLoaded = true; + }; + } + // https://go.mparticle.com/work/SQDSDKS-6317 + function processFlags(config) { + var flags = {}; + var _a = Constants.FeatureFlags, + ReportBatching = _a.ReportBatching, + EventBatchingIntervalMillis = _a.EventBatchingIntervalMillis, + OfflineStorage = _a.OfflineStorage, + DirectUrlRouting = _a.DirectUrlRouting, + CacheIdentity = _a.CacheIdentity, + AudienceAPI = _a.AudienceAPI, + CaptureIntegrationSpecificIds = _a.CaptureIntegrationSpecificIds, + CaptureIntegrationSpecificIdsV2 = _a.CaptureIntegrationSpecificIdsV2, + AstBackgroundEvents = _a.AstBackgroundEvents; + if (!config.flags) { + return {}; + } + // https://go.mparticle.com/work/SQDSDKS-6317 + // Passed in config flags take priority over defaults + flags[ReportBatching] = config.flags[ReportBatching] || false; + // The server returns stringified numbers, sowe need to parse + flags[EventBatchingIntervalMillis] = parseNumber(config.flags[EventBatchingIntervalMillis]) || Constants.DefaultConfig.uploadInterval; + flags[OfflineStorage] = config.flags[OfflineStorage] || '0'; + flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === 'True'; + flags[CacheIdentity] = config.flags[CacheIdentity] === 'True'; + flags[AudienceAPI] = config.flags[AudienceAPI] === 'True'; + flags[CaptureIntegrationSpecificIds] = config.flags[CaptureIntegrationSpecificIds] === 'True'; + flags[CaptureIntegrationSpecificIdsV2] = config.flags[CaptureIntegrationSpecificIdsV2] || 'none'; + flags[AstBackgroundEvents] = config.flags[AstBackgroundEvents] === 'True'; + return flags; + } + function processBaseUrls(config, flags, apiKey) { + // an API key is not present in a webview only mode. In this case, no baseUrls are needed + if (!apiKey) { + return {}; + } + // When direct URL routing is false, update baseUrls based custom urls + // passed to the config + if (flags.directURLRouting) { + return processDirectBaseUrls(config, apiKey); + } else { + return processCustomBaseUrls(config); + } + } + function processCustomBaseUrls(config) { + var defaultBaseUrls = Constants.DefaultBaseUrls; + var CNAMEUrlPaths = Constants.CNAMEUrlPaths; + // newBaseUrls are default if the customer is not using a CNAME + // If a customer passes either config.domain or config.v3SecureServiceUrl, + // config.identityUrl, etc, the customer is using a CNAME. + // config.domain will take priority if a customer passes both. + var newBaseUrls = {}; + // If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain. + // This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty + // if a customer is using a snippet prior to 2.6. + if (!isEmpty(config.domain)) { + for (var pathKey in CNAMEUrlPaths) { + newBaseUrls[pathKey] = "".concat(config.domain).concat(CNAMEUrlPaths[pathKey]); + } + return newBaseUrls; + } + for (var baseUrlKey in defaultBaseUrls) { + newBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; + } + return newBaseUrls; + } + function processDirectBaseUrls(config, apiKey) { + var defaultBaseUrls = Constants.DefaultBaseUrls; + var directBaseUrls = {}; + // When Direct URL Routing is true, we create a new set of baseUrls that + // include the silo in the urls. mParticle API keys are prefixed with the + // silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo, + // and before other silos existed, there were no prefixes and all apiKeys + // were us1. As such, if we split on a '-' and the resulting array length + // is 1, then it is an older APIkey that should route to us1. + // When splitKey.length is greater than 1, then splitKey[0] will be + // us1, us2, eu1, au1, or st1, etc as new silos are added + var DEFAULT_SILO = 'us1'; + var splitKey = apiKey.split('-'); + var routingPrefix = splitKey.length <= 1 ? DEFAULT_SILO : splitKey[0]; + for (var baseUrlKey in defaultBaseUrls) { + // Any custom endpoints passed to mpConfig will take priority over direct + // mapping to the silo. The most common use case is a customer provided CNAME. + if (baseUrlKey === 'configUrl') { + directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; + continue; + } + if (config.hasOwnProperty(baseUrlKey)) { + directBaseUrls[baseUrlKey] = config[baseUrlKey]; + } else { + var urlparts = defaultBaseUrls[baseUrlKey].split('.'); + directBaseUrls[baseUrlKey] = __spreadArray([urlparts[0], routingPrefix], urlparts.slice(1), true).join('.'); + } + } + return directBaseUrls; + } + + var Logger = /** @class */function () { + function Logger(config) { + var _a, _b; + this.logLevel = (_a = config.logLevel) !== null && _a !== void 0 ? _a : LogLevelType.Warning; + this.logger = (_b = config.logger) !== null && _b !== void 0 ? _b : new ConsoleLogger(); + } + Logger.prototype.verbose = function (msg) { + if (this.logLevel === LogLevelType.None) return; + if (this.logger.verbose && this.logLevel === LogLevelType.Verbose) { + this.logger.verbose(msg); + } + }; + Logger.prototype.warning = function (msg) { + if (this.logLevel === LogLevelType.None) return; + if (this.logger.warning && (this.logLevel === LogLevelType.Verbose || this.logLevel === LogLevelType.Warning)) { + this.logger.warning(msg); + } + }; + Logger.prototype.error = function (msg) { + if (this.logLevel === LogLevelType.None) return; + if (this.logger.error) { + this.logger.error(msg); + } + }; + Logger.prototype.setLogLevel = function (newLogLevel) { + this.logLevel = newLogLevel; + }; + return Logger; + }(); + var ConsoleLogger = /** @class */function () { + function ConsoleLogger() {} + ConsoleLogger.prototype.verbose = function (msg) { + if (console && console.info) { + console.info(msg); + } + }; + ConsoleLogger.prototype.error = function (msg) { + if (console && console.error) { + console.error(msg); + } + }; + ConsoleLogger.prototype.warning = function (msg) { + if (console && console.warn) { + console.warn(msg); + } + }; + return ConsoleLogger; + }(); + + var Base64 = Polyfill.Base64, + Messages$4 = Constants.Messages, + Base64CookieKeys = Constants.Base64CookieKeys, + SDKv2NonMPIDCookieKeys = Constants.SDKv2NonMPIDCookieKeys, + StorageNames = Constants.StorageNames; + function _Persistence(mpInstance) { + var self = this; + + // https://go.mparticle.com/work/SQDSDKS-5022 + this.useLocalStorage = function () { + return !mpInstance._Store.SDKConfig.useCookieStorage && mpInstance._Store.isLocalStorageAvailable; + }; + this.initializeStorage = function () { + try { + var storage, + localStorageData = self.getLocalStorage(), + cookies = self.getCookie(), + allData; + + // https://go.mparticle.com/work/SQDSDKS-6045 + // Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle + if (!localStorageData && !cookies) { + mpInstance._Store.isFirstRun = true; + mpInstance._Store.mpid = 0; + } else { + mpInstance._Store.isFirstRun = false; + } + + // https://go.mparticle.com/work/SQDSDKS-6045 + if (!mpInstance._Store.isLocalStorageAvailable) { + mpInstance._Store.SDKConfig.useCookieStorage = true; + } + + // https://go.mparticle.com/work/SQDSDKS-6046 + if (mpInstance._Store.isLocalStorageAvailable) { + storage = window.localStorage; + if (mpInstance._Store.SDKConfig.useCookieStorage) { + // For migrating from localStorage to cookies -- If an instance switches from localStorage to cookies, then + // no mParticle cookie exists yet and there is localStorage. Get the localStorage, set them to cookies, then delete the localStorage item. + if (localStorageData) { + if (cookies) { + // https://go.mparticle.com/work/SQDSDKS-6047 + allData = mpInstance._Helpers.extend(false, localStorageData, cookies); + } else { + allData = localStorageData; + } + storage.removeItem(mpInstance._Store.storageName); + } else if (cookies) { + allData = cookies; + } + self.storeDataInMemory(allData); + } else { + // For migrating from cookie to localStorage -- If an instance is newly switching from cookies to localStorage, then + // no mParticle localStorage exists yet and there are cookies. Get the cookies, set them to localStorage, then delete the cookies. + if (cookies) { + if (localStorageData) { + // https://go.mparticle.com/work/SQDSDKS-6047 + allData = mpInstance._Helpers.extend(false, localStorageData, cookies); + } else { + allData = cookies; + } + self.storeDataInMemory(allData); + self.expireCookies(mpInstance._Store.storageName); + } else { + self.storeDataInMemory(localStorageData); + } + } + } else { + self.storeDataInMemory(cookies); + } + + // https://go.mparticle.com/work/SQDSDKS-6046 + // Stores all non-current user MPID information into the store + for (var key in allData) { + if (allData.hasOwnProperty(key)) { + if (!SDKv2NonMPIDCookieKeys[key]) { + mpInstance._Store.nonCurrentUserMPIDs[key] = allData[key]; + } + } + } + self.update(); + } catch (e) { + // If cookies or local storage is corrupt, we want to remove it + // so that in the future, initializeStorage will work + if (self.useLocalStorage() && mpInstance._Store.isLocalStorageAvailable) { + localStorage.removeItem(mpInstance._Store.storageName); + } else { + self.expireCookies(mpInstance._Store.storageName); + } + mpInstance.Logger.error('Error initializing storage: ' + e); + } + }; + this.update = function () { + if (!mpInstance._Store.webviewBridgeEnabled) { + if (mpInstance._Store.SDKConfig.useCookieStorage) { + self.setCookie(); + } + self.setLocalStorage(); + } + }; + + // https://go.mparticle.com/work/SQDSDKS-6045 + this.storeDataInMemory = function (obj, currentMPID) { + try { + if (!obj) { + mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieNotFound); + mpInstance._Store.clientId = mpInstance._Store.clientId || mpInstance._Helpers.generateUniqueId(); + mpInstance._Store.deviceId = mpInstance._Store.deviceId || mpInstance._Helpers.generateUniqueId(); + } else { + // Set MPID first, then change object to match MPID data + if (currentMPID) { + mpInstance._Store.mpid = currentMPID; + } else { + mpInstance._Store.mpid = obj.cu || 0; + } + obj.gs = obj.gs || {}; + mpInstance._Store.sessionId = obj.gs.sid || mpInstance._Store.sessionId; + mpInstance._Store.isEnabled = typeof obj.gs.ie !== 'undefined' ? obj.gs.ie : mpInstance._Store.isEnabled; + mpInstance._Store.sessionAttributes = obj.gs.sa || mpInstance._Store.sessionAttributes; + mpInstance._Store.localSessionAttributes = obj.gs.lsa || mpInstance._Store.localSessionAttributes; + mpInstance._Store.serverSettings = obj.gs.ss || mpInstance._Store.serverSettings; + mpInstance._Store.devToken = mpInstance._Store.devToken || obj.gs.dt; + mpInstance._Store.SDKConfig.appVersion = mpInstance._Store.SDKConfig.appVersion || obj.gs.av; + mpInstance._Store.clientId = obj.gs.cgid || mpInstance._Store.clientId || mpInstance._Helpers.generateUniqueId(); + + // For most persistence values, we prioritize localstorage/cookie values over + // Store. However, we allow device ID to be overriden via a config value and + // thus the priority of the deviceId value is + // 1. value passed via config.deviceId + // 2. previous value in persistence + // 3. generate new guid + mpInstance._Store.deviceId = mpInstance._Store.deviceId || obj.gs.das || mpInstance._Helpers.generateUniqueId(); + mpInstance._Store.integrationAttributes = obj.gs.ia || {}; + mpInstance._Store.context = obj.gs.c || mpInstance._Store.context; + mpInstance._Store.currentSessionMPIDs = obj.gs.csm || mpInstance._Store.currentSessionMPIDs; + mpInstance._Store.isLoggedIn = obj.l === true; + if (obj.gs.les) { + mpInstance._Store.dateLastEventSent = new Date(obj.gs.les); + } + if (obj.gs.ssd) { + mpInstance._Store.sessionStartDate = new Date(obj.gs.ssd); + } else { + mpInstance._Store.sessionStartDate = new Date(); + } + if (currentMPID) { + obj = obj[currentMPID]; + } else { + obj = obj[obj.cu]; + } + } + } catch (e) { + mpInstance.Logger.error(Messages$4.ErrorMessages.CookieParseError); + } + }; + + // https://go.mparticle.com/work/SQDSDKS-5022 + this.determineLocalStorageAvailability = function (storage) { + var result; + if (window.mParticle && window.mParticle._forceNoLocalStorage) { + storage = undefined; + } + try { + storage.setItem('mparticle', 'test'); + result = storage.getItem('mparticle') === 'test'; + storage.removeItem('mparticle'); + return result && storage; + } catch (e) { + return false; + } + }; + + // https://go.mparticle.com/work/SQDSDKS-6021 + this.setLocalStorage = function () { + var _mpInstance$_CookieCo; + if (!mpInstance._Store.isLocalStorageAvailable) { + return; + } + + // Block mprtcl-v4 localStorage when noFunctional is true + if ((_mpInstance$_CookieCo = mpInstance._CookieConsentManager) !== null && _mpInstance$_CookieCo !== void 0 && _mpInstance$_CookieCo.getNoFunctional()) { + return; + } + var key = mpInstance._Store.storageName, + localStorageData = self.getLocalStorage() || {}, + currentUser = mpInstance.Identity.getCurrentUser(), + mpid = currentUser ? currentUser.getMPID() : null; + if (!mpInstance._Store.SDKConfig.useCookieStorage) { + localStorageData.gs = localStorageData.gs || {}; + localStorageData.l = mpInstance._Store.isLoggedIn ? 1 : 0; + if (mpInstance._Store.sessionId) { + localStorageData.gs.csm = mpInstance._Store.currentSessionMPIDs; + } + localStorageData.gs.ie = mpInstance._Store.isEnabled; + if (mpid) { + localStorageData.cu = mpid; + } + if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) { + localStorageData = mpInstance._Helpers.extend({}, localStorageData, mpInstance._Store.nonCurrentUserMPIDs); + mpInstance._Store.nonCurrentUserMPIDs = {}; + } + localStorageData = setGlobalStorageAttributes(localStorageData); + try { + window.localStorage.setItem(encodeURIComponent(key), self.encodePersistence(JSON.stringify(localStorageData))); + } catch (e) { + mpInstance.Logger.error('Error with setting localStorage item.'); + } + } + }; + function setGlobalStorageAttributes(data) { + var store = mpInstance._Store; + data.gs.sid = store.sessionId; + data.gs.ie = store.isEnabled; + data.gs.sa = store.sessionAttributes; + data.gs.lsa = store.localSessionAttributes; + data.gs.ss = store.serverSettings; + data.gs.dt = store.devToken; + data.gs.les = store.dateLastEventSent ? store.dateLastEventSent.getTime() : null; + data.gs.av = store.SDKConfig.appVersion; + data.gs.cgid = store.clientId; + data.gs.das = store.deviceId; + data.gs.c = store.context; + data.gs.ssd = store.sessionStartDate ? store.sessionStartDate.getTime() : 0; + data.gs.ia = store.integrationAttributes; + return data; + } + this.getLocalStorage = function () { + if (!mpInstance._Store.isLocalStorageAvailable) { + return null; + } + var key = mpInstance._Store.storageName, + localStorageData = self.decodePersistence(window.localStorage.getItem(key)), + obj = {}, + j; + if (localStorageData) { + localStorageData = JSON.parse(localStorageData); + for (j in localStorageData) { + if (localStorageData.hasOwnProperty(j)) { + obj[j] = localStorageData[j]; + } + } + } + if (Object.keys(obj).length) { + return obj; + } + return null; + }; + function removeLocalStorage(localStorageName) { + localStorage.removeItem(localStorageName); + } + this.expireCookies = function (cookieName) { + var date = new Date(), + expires, + domain, + cookieDomain; + cookieDomain = self.getCookieDomain(); + if (cookieDomain === '') { + domain = ''; + } else { + domain = ';domain=' + cookieDomain; + } + date.setTime(date.getTime() - 24 * 60 * 60 * 1000); + expires = '; expires=' + date.toUTCString(); + document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain; + }; + this.getCookie = function () { + var cookies, + key = mpInstance._Store.storageName, + i, + l, + parts, + name, + cookie, + result = key ? undefined : {}; + mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSearch); + try { + cookies = window.document.cookie.split('; '); + } catch (e) { + mpInstance.Logger.verbose('Unable to parse undefined cookie'); + return null; + } + for (i = 0, l = cookies.length; i < l; i++) { + try { + parts = cookies[i].split('='); + name = parts.shift(); + cookie = parts.join('='); + } catch (e) { + mpInstance.Logger.verbose('Unable to parse cookie: ' + name + '. Skipping.'); + } + if (key && key === name) { + result = mpInstance._Helpers.converted(cookie); + break; + } + if (!key) { + result[name] = mpInstance._Helpers.converted(cookie); + } + } + if (result) { + mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieFound); + return JSON.parse(self.decodePersistence(result)); + } else { + return null; + } + }; + + // https://go.mparticle.com/work/SQDSDKS-5022 + // https://go.mparticle.com/work/SQDSDKS-6021 + this.setCookie = function () { + var _mpInstance$_CookieCo2; + // Block mprtcl-v4 cookies when noFunctional is true + if ((_mpInstance$_CookieCo2 = mpInstance._CookieConsentManager) !== null && _mpInstance$_CookieCo2 !== void 0 && _mpInstance$_CookieCo2.getNoFunctional()) { + return; + } + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(); + if (currentUser) { + mpid = currentUser.getMPID(); + } + var date = new Date(), + key = mpInstance._Store.storageName, + cookies = self.getCookie() || {}, + expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000).toGMTString(), + cookieDomain, + domain, + encodedCookiesWithExpirationAndPath; + cookieDomain = self.getCookieDomain(); + if (cookieDomain === '') { + domain = ''; + } else { + domain = ';domain=' + cookieDomain; + } + cookies.gs = cookies.gs || {}; + if (mpInstance._Store.sessionId) { + cookies.gs.csm = mpInstance._Store.currentSessionMPIDs; + } + if (mpid) { + cookies.cu = mpid; + } + cookies.l = mpInstance._Store.isLoggedIn ? 1 : 0; + cookies = setGlobalStorageAttributes(cookies); + if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) { + cookies = mpInstance._Helpers.extend({}, cookies, mpInstance._Store.nonCurrentUserMPIDs); + mpInstance._Store.nonCurrentUserMPIDs = {}; + } + encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(cookies, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize); + mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSet); + window.document.cookie = encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath; + }; + + /* This function determines if a cookie is greater than the configured maxCookieSize. + - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie. + - Once removed, check size, and repeat. + - Never remove the currentUser's MPID from the cookie. + MPID removal priority: + 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie. + 2. If there are currentSessionMPIDs: + a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs + b. Then remove MPIDs based on order in currentSessionMPIDs array, which + stores MPIDs based on earliest login. + */ + this.reduceAndEncodePersistence = function (persistence, expires, domain, maxCookieSize) { + var encodedCookiesWithExpirationAndPath, + currentSessionMPIDs = persistence.gs.csm ? persistence.gs.csm : []; + // Comment 1 above + if (!currentSessionMPIDs.length) { + for (var key in persistence) { + if (persistence.hasOwnProperty(key)) { + encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); + if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { + if (!SDKv2NonMPIDCookieKeys[key] && key !== persistence.cu) { + delete persistence[key]; + } + } + } + } + } else { + // Comment 2 above - First create an object of all MPIDs on the cookie + var MPIDsOnCookie = {}; + for (var potentialMPID in persistence) { + if (persistence.hasOwnProperty(potentialMPID)) { + if (!SDKv2NonMPIDCookieKeys[potentialMPID] && potentialMPID !== persistence.cu) { + MPIDsOnCookie[potentialMPID] = 1; + } + } + } + // Comment 2a above + if (Object.keys(MPIDsOnCookie).length) { + for (var mpid in MPIDsOnCookie) { + encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); + if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { + if (MPIDsOnCookie.hasOwnProperty(mpid)) { + if (currentSessionMPIDs.indexOf(mpid) === -1) { + delete persistence[mpid]; + } + } + } + } + } + // Comment 2b above + for (var i = 0; i < currentSessionMPIDs.length; i++) { + encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); + if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { + var MPIDtoRemove = currentSessionMPIDs[i]; + if (persistence[MPIDtoRemove]) { + mpInstance.Logger.verbose('Size of new encoded cookie is larger than maxCookieSize setting of ' + maxCookieSize + '. Removing from cookie the earliest logged in MPID containing: ' + JSON.stringify(persistence[MPIDtoRemove], 0, 2)); + delete persistence[MPIDtoRemove]; + } else { + mpInstance.Logger.error('Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' + maxCookieSize + '. We recommend using a maxCookieSize of 1500.'); + } + } else { + break; + } + } + } + return encodedCookiesWithExpirationAndPath; + }; + function createFullEncodedCookie(persistence, expires, domain) { + return self.encodePersistence(JSON.stringify(persistence)) + ';expires=' + expires + ';path=/' + domain; + } + this.findPrevCookiesBasedOnUI = function (identityApiData) { + var persistence = mpInstance._Persistence.getPersistence(); + var matchedUser; + if (identityApiData) { + for (var requestedIdentityType in identityApiData.userIdentities) { + if (persistence && Object.keys(persistence).length) { + for (var key in persistence) { + // any value in persistence that has an MPID key will be an MPID to search through + // other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched + if (persistence[key].mpid) { + var cookieUIs = persistence[key].ui; + for (var cookieUIType in cookieUIs) { + if (requestedIdentityType === cookieUIType && identityApiData.userIdentities[requestedIdentityType] === cookieUIs[cookieUIType]) { + matchedUser = key; + break; + } + } + } + } + } + } + } + if (matchedUser) { + self.storeDataInMemory(persistence, matchedUser); + } + }; + this.encodePersistence = function (persistence) { + persistence = JSON.parse(persistence); + for (var key in persistence.gs) { + if (persistence.gs.hasOwnProperty(key)) { + if (Base64CookieKeys[key]) { + if (persistence.gs[key]) { + // base64 encode any value that is an object or Array in globalSettings + if (Array.isArray(persistence.gs[key]) && persistence.gs[key].length || mpInstance._Helpers.isObject(persistence.gs[key]) && Object.keys(persistence.gs[key]).length) { + persistence.gs[key] = Base64.encode(JSON.stringify(persistence.gs[key])); + } else { + delete persistence.gs[key]; + } + } else { + delete persistence.gs[key]; + } + } else if (key === 'ie') { + persistence.gs[key] = persistence.gs[key] ? 1 : 0; + } else if (!persistence.gs[key]) { + delete persistence.gs[key]; + } + } + } + for (var mpid in persistence) { + if (persistence.hasOwnProperty(mpid)) { + if (!SDKv2NonMPIDCookieKeys[mpid]) { + for (key in persistence[mpid]) { + if (persistence[mpid].hasOwnProperty(key)) { + if (Base64CookieKeys[key]) { + if (mpInstance._Helpers.isObject(persistence[mpid][key]) && Object.keys(persistence[mpid][key]).length) { + persistence[mpid][key] = Base64.encode(JSON.stringify(persistence[mpid][key])); + } else { + delete persistence[mpid][key]; + } + } + } + } + } + } + } + return createCookieString(JSON.stringify(persistence)); + }; + + // TODO: This should actually be decodePersistenceString or + // we should refactor this to take a string and return an object + this.decodePersistence = function (persistence) { + try { + if (persistence) { + persistence = JSON.parse(revertCookieString(persistence)); + if (mpInstance._Helpers.isObject(persistence) && Object.keys(persistence).length) { + for (var key in persistence.gs) { + if (persistence.gs.hasOwnProperty(key)) { + if (Base64CookieKeys[key]) { + persistence.gs[key] = JSON.parse(Base64.decode(persistence.gs[key])); + } else if (key === 'ie') { + persistence.gs[key] = Boolean(persistence.gs[key]); + } + } + } + for (var mpid in persistence) { + if (persistence.hasOwnProperty(mpid)) { + if (!SDKv2NonMPIDCookieKeys[mpid]) { + for (key in persistence[mpid]) { + if (persistence[mpid].hasOwnProperty(key)) { + if (Base64CookieKeys[key]) { + if (persistence[mpid][key].length) { + persistence[mpid][key] = JSON.parse(Base64.decode(persistence[mpid][key])); + } + } + } + } + } else if (mpid === 'l') { + persistence[mpid] = Boolean(persistence[mpid]); + } + } + } + } + return JSON.stringify(persistence); + } + } catch (e) { + mpInstance.Logger.error('Problem with decoding cookie', e); + } + }; + this.getCookieDomain = function () { + if (mpInstance._Store.SDKConfig.cookieDomain) { + return mpInstance._Store.SDKConfig.cookieDomain; + } else { + var rootDomain = self.getDomain(document, location.hostname); + if (rootDomain === '') { + return ''; + } else { + return '.' + rootDomain; + } + } + }; + + // This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible. + // For example subdomain.domain.co.uk would try the following combinations: + // "co.uk" -> fail + // "domain.co.uk" -> success, return + // "subdomain.domain.co.uk" -> skipped, because already found + this.getDomain = function (doc, locationHostname) { + var i, + testParts, + mpTest = 'mptest=cookie', + hostname = locationHostname.split('.'); + for (i = hostname.length - 1; i >= 0; i--) { + testParts = hostname.slice(i).join('.'); + doc.cookie = mpTest + ';domain=.' + testParts + ';'; + if (doc.cookie.indexOf(mpTest) > -1) { + doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + return testParts; + } + } + return ''; + }; + this.saveUserCookieSyncDatesToPersistence = function (mpid, csd) { + if (csd) { + var persistence = self.getPersistence(); + if (persistence) { + if (persistence[mpid]) { + persistence[mpid].csd = csd; + } else { + persistence[mpid] = { + csd: csd + }; + } + } + self.savePersistence(persistence); + } + }; + this.swapCurrentUser = function (previousMPID, currentMPID, currentSessionMPIDs) { + if (previousMPID && currentMPID && previousMPID !== currentMPID) { + var persistence = self.getPersistence(); + if (persistence) { + persistence.cu = currentMPID; + persistence.gs.csm = currentSessionMPIDs; + self.savePersistence(persistence); + } + } + }; + + // https://go.mparticle.com/work/SQDSDKS-6021 + this.savePersistence = function (persistence) { + var _mpInstance$_CookieCo3; + // Block mprtcl-v4 persistence when noFunctional is true + if ((_mpInstance$_CookieCo3 = mpInstance._CookieConsentManager) !== null && _mpInstance$_CookieCo3 !== void 0 && _mpInstance$_CookieCo3.getNoFunctional()) { + return; + } + var encodedPersistence = self.encodePersistence(JSON.stringify(persistence)), + date = new Date(), + key = mpInstance._Store.storageName, + expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000).toGMTString(), + cookieDomain = self.getCookieDomain(), + domain; + if (cookieDomain === '') { + domain = ''; + } else { + domain = ';domain=' + cookieDomain; + } + if (mpInstance._Store.SDKConfig.useCookieStorage) { + var encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(persistence, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize); + window.document.cookie = encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath; + } else { + if (mpInstance._Store.isLocalStorageAvailable) { + localStorage.setItem(mpInstance._Store.storageName, encodedPersistence); + } + } + }; + this.getPersistence = function () { + var persistence = this.useLocalStorage() ? this.getLocalStorage() : this.getCookie(); + return persistence; + }; + this.getFirstSeenTime = function (mpid) { + if (!mpid) { + return null; + } + var persistence = self.getPersistence(); + if (persistence && persistence[mpid] && persistence[mpid].fst) { + return persistence[mpid].fst; + } else { + return null; + } + }; + + /** + * set the "first seen" time for a user. the time will only be set once for a given + * mpid after which subsequent calls will be ignored + */ + this.setFirstSeenTime = function (mpid, time) { + if (!mpid) { + return; + } + // https://go.mparticle.com/work/SQDSDKS-6329 + if (!time) { + time = new Date().getTime(); + } + var persistence = self.getPersistence(); + if (persistence) { + if (!persistence[mpid]) { + persistence[mpid] = {}; + } + if (!persistence[mpid].fst) { + persistence[mpid].fst = time; + self.savePersistence(persistence); + } + } + }; + + /** + * returns the "last seen" time for a user. If the mpid represents the current user, the + * return value will always be the current time, otherwise it will be to stored "last seen" + * time + */ + this.getLastSeenTime = function (mpid) { + if (!mpid) { + return null; + } + if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) { + //if the mpid is the current user, its last seen time is the current time + return new Date().getTime(); + } else { + var persistence = self.getPersistence(); + if (persistence && persistence[mpid] && persistence[mpid].lst) { + return persistence[mpid].lst; + } + return null; + } + }; + this.setLastSeenTime = function (mpid, time) { + if (!mpid) { + return; + } + // https://go.mparticle.com/work/SQDSDKS-6329 + if (!time) { + time = new Date().getTime(); + } + var persistence = self.getPersistence(); + if (persistence && persistence[mpid]) { + persistence[mpid].lst = time; + self.savePersistence(persistence); + } + }; + this.getDeviceId = function () { + return mpInstance._Store.deviceId; + }; + this.setDeviceId = function (guid) { + mpInstance._Store.deviceId = guid; + self.update(); + }; + this.resetPersistence = function () { + localStorage.clear(); + self.expireCookies(StorageNames.cookieName); + self.expireCookies(StorageNames.cookieNameV2); + self.expireCookies(StorageNames.cookieNameV3); + self.expireCookies(StorageNames.cookieNameV4); + self.expireCookies(mpInstance._Store.storageName); + if (mParticle._isTestEnv) { + var testWorkspaceToken = 'abcdef'; + removeLocalStorage(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); + self.expireCookies(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); + } + }; + + // https://go.mparticle.com/work/SQDSDKS-6045 + // Forwarder Batching Code + this.forwardingStatsBatches = { + uploadsTable: {}, + forwardingStatsEventQueue: [] + }; + } + + var Messages$3 = Constants.Messages; + function Events(mpInstance) { + var self = this; + this.logEvent = function (event, options) { + mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogEvent + ': ' + event.name); + if (mpInstance._Helpers.canLog()) { + var uploadObject = mpInstance._ServerModel.createEventObject(event); + mpInstance._APIClient.sendEventToServer(uploadObject, options); + } else { + mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); + } + }; + this.startTracking = function (callback) { + if (!mpInstance._Store.isTracking) { + if ('geolocation' in navigator) { + mpInstance._Store.watchPositionId = navigator.geolocation.watchPosition(successTracking, errorTracking); + } + } else { + var position = { + coords: { + latitude: mpInstance._Store.currentPosition.lat, + longitude: mpInstance._Store.currentPosition.lng + } + }; + triggerCallback(callback, position); + } + function successTracking(position) { + mpInstance._Store.currentPosition = { + lat: position.coords.latitude, + lng: position.coords.longitude + }; + triggerCallback(callback, position); + // prevents callback from being fired multiple times + callback = null; + mpInstance._Store.isTracking = true; + } + function errorTracking() { + triggerCallback(callback); + // prevents callback from being fired multiple times + callback = null; + mpInstance._Store.isTracking = false; + } + function triggerCallback(callback, position) { + if (callback) { + try { + if (position) { + callback(position); + } else { + callback(); + } + } catch (e) { + mpInstance.Logger.error('Error invoking the callback passed to startTrackingLocation.'); + mpInstance.Logger.error(e); + } + } + } + }; + this.stopTracking = function () { + if (mpInstance._Store.isTracking) { + navigator.geolocation.clearWatch(mpInstance._Store.watchPositionId); + mpInstance._Store.currentPosition = null; + mpInstance._Store.isTracking = false; + } + }; + this.logOptOut = function () { + mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut); + var event = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.OptOut, + eventType: Types.EventType.Other + }); + mpInstance._APIClient.sendEventToServer(event); + }; + this.logAST = function () { + self.logEvent({ + messageType: Types.MessageType.AppStateTransition + }); + }; + this.logCheckoutEvent = function (step, option, attrs, customFlags) { + var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); + if (event) { + event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout); + event.EventCategory = Types.CommerceEventType.ProductCheckout; + event.ProductAction = { + ProductActionType: Types.ProductActionType.Checkout, + CheckoutStep: step, + CheckoutOptions: option, + ProductList: [] + }; + self.logCommerceEvent(event, attrs); + } + }; + this.logProductActionEvent = function (productActionType, product, customAttrs, customFlags, transactionAttributes, options) { + var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags, options); + var productList = Array.isArray(product) ? product : [product]; + productList.forEach(function (product) { + if (product.TotalAmount) { + product.TotalAmount = mpInstance._Ecommerce.sanitizeAmount(product.TotalAmount, 'TotalAmount'); + } + if (product.Position) { + product.Position = mpInstance._Ecommerce.sanitizeAmount(product.Position, 'Position'); + } + if (product.Price) { + product.Price = mpInstance._Ecommerce.sanitizeAmount(product.Price, 'Price'); + } + if (product.Quantity) { + product.Quantity = mpInstance._Ecommerce.sanitizeAmount(product.Quantity, 'Quantity'); + } + }); + if (event) { + event.EventCategory = mpInstance._Ecommerce.convertProductActionToEventType(productActionType); + event.EventName += mpInstance._Ecommerce.getProductActionEventName(productActionType); + event.ProductAction = { + ProductActionType: productActionType, + ProductList: productList + }; + if (mpInstance._Helpers.isObject(transactionAttributes)) { + mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); + } + self.logCommerceEvent(event, customAttrs, options); + } + }; + this.logPurchaseEvent = function (transactionAttributes, product, attrs, customFlags) { + var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); + if (event) { + event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase); + event.EventCategory = Types.CommerceEventType.ProductPurchase; + event.ProductAction = { + ProductActionType: Types.ProductActionType.Purchase + }; + event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product); + mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); + self.logCommerceEvent(event, attrs); + } + }; + this.logRefundEvent = function (transactionAttributes, product, attrs, customFlags) { + if (!transactionAttributes) { + mpInstance.Logger.error(Messages$3.ErrorMessages.TransactionRequired); + return; + } + var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); + if (event) { + event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund); + event.EventCategory = Types.CommerceEventType.ProductRefund; + event.ProductAction = { + ProductActionType: Types.ProductActionType.Refund + }; + event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product); + mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); + self.logCommerceEvent(event, attrs); + } + }; + this.logPromotionEvent = function (promotionType, promotion, attrs, customFlags, eventOptions) { + var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); + if (event) { + event.EventName += mpInstance._Ecommerce.getPromotionActionEventName(promotionType); + event.EventCategory = mpInstance._Ecommerce.convertPromotionActionToEventType(promotionType); + event.PromotionAction = { + PromotionActionType: promotionType, + PromotionList: Array.isArray(promotion) ? promotion : [promotion] + }; + self.logCommerceEvent(event, attrs, eventOptions); + } + }; + this.logImpressionEvent = function (impression, attrs, customFlags, options) { + var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); + if (event) { + event.EventName += 'Impression'; + event.EventCategory = Types.CommerceEventType.ProductImpression; + if (!Array.isArray(impression)) { + impression = [impression]; + } + event.ProductImpressions = []; + impression.forEach(function (impression) { + event.ProductImpressions.push({ + ProductImpressionList: impression.Name, + ProductList: Array.isArray(impression.Product) ? impression.Product : [impression.Product] + }); + }); + self.logCommerceEvent(event, attrs, options); + } + }; + this.logCommerceEvent = function (commerceEvent, attrs, options) { + mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent); + + // If a developer typos the ProductActionType, the event category will be + // null, resulting in kit forwarding errors on the server. + // The check for `ProductAction` is required to denote that these are + // ProductAction events, and not impression or promotions + if (commerceEvent.ProductAction && commerceEvent.EventCategory === null) { + mpInstance.Logger.error('Commerce event not sent. The mParticle.ProductActionType you passed was invalid. Re-check your code.'); + return; + } + attrs = mpInstance._Helpers.sanitizeAttributes(attrs, commerceEvent.EventName); + if (mpInstance._Helpers.canLog()) { + if (mpInstance._Store.webviewBridgeEnabled) { + // Don't send shopping cart to parent sdks + commerceEvent.ShoppingCart = {}; + } + if (attrs) { + commerceEvent.EventAttributes = attrs; + } + mpInstance._APIClient.sendEventToServer(commerceEvent, options); + + // https://go.mparticle.com/work/SQDSDKS-6038 + mpInstance._Persistence.update(); + } else { + mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); + } + }; + this.addEventHandler = function (domEvent, selector, eventName, data, eventType) { + var elements = [], + handler = function handler(e) { + var timeoutHandler = function timeoutHandler() { + if (element.href) { + window.location.href = element.href; + } else if (element.submit) { + element.submit(); + } + }; + mpInstance.Logger.verbose('DOM event triggered, handling event'); + self.logEvent({ + messageType: Types.MessageType.PageEvent, + name: typeof eventName === 'function' ? eventName(element) : eventName, + data: typeof data === 'function' ? data(element) : data, + eventType: eventType || Types.EventType.Other + }); + + // TODO: Handle middle-clicks and special keys (ctrl, alt, etc) + if (element.href && element.target !== '_blank' || element.submit) { + // Give xmlhttprequest enough time to execute before navigating a link or submitting form + + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + setTimeout(timeoutHandler, mpInstance._Store.SDKConfig.timeout); + } + }, + element, + i; + if (!selector) { + mpInstance.Logger.error("Can't bind event, selector is required"); + return; + } + + // Handle a css selector string or a dom element + if (typeof selector === 'string') { + elements = document.querySelectorAll(selector); + } else if (selector.nodeType) { + elements = [selector]; + } + if (elements.length) { + mpInstance.Logger.verbose('Found ' + elements.length + ' element' + (elements.length > 1 ? 's' : '') + ', attaching event handlers'); + for (i = 0; i < elements.length; i++) { + element = elements[i]; + if (element.addEventListener) { + // Modern browsers + element.addEventListener(domEvent, handler, false); + } else if (element.attachEvent) { + // IE < 9 + element.attachEvent('on' + domEvent, handler); + } else { + // All other browsers + element['on' + domEvent] = handler; + } + } + } else { + mpInstance.Logger.verbose('No elements found'); + } + }; + } + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + _next(undefined); + }); + }; + } + + var regeneratorRuntime$1 = {exports: {}}; + + var _typeof = {exports: {}}; + + _typeof.exports; + + (function (module) { + function _typeof(o) { + "@babel/helpers - typeof"; + + return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o); + } + module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (_typeof)); + + var _typeofExports = _typeof.exports; + + regeneratorRuntime$1.exports; + + (function (module) { + var _typeof = _typeofExports["default"]; + function _regeneratorRuntime() { + module.exports = _regeneratorRuntime = function _regeneratorRuntime() { + return e; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + var t, + e = {}, + r = Object.prototype, + n = r.hasOwnProperty, + o = Object.defineProperty || function (t, e, r) { + t[e] = r.value; + }, + i = "function" == typeof Symbol ? Symbol : {}, + a = i.iterator || "@@iterator", + c = i.asyncIterator || "@@asyncIterator", + u = i.toStringTag || "@@toStringTag"; + function define(t, e, r) { + return Object.defineProperty(t, e, { + value: r, + enumerable: !0, + configurable: !0, + writable: !0 + }), t[e]; + } + try { + define({}, ""); + } catch (t) { + define = function define(t, e, r) { + return t[e] = r; + }; + } + function wrap(t, e, r, n) { + var i = e && e.prototype instanceof Generator ? e : Generator, + a = Object.create(i.prototype), + c = new Context(n || []); + return o(a, "_invoke", { + value: makeInvokeMethod(t, r, c) + }), a; + } + function tryCatch(t, e, r) { + try { + return { + type: "normal", + arg: t.call(e, r) + }; + } catch (t) { + return { + type: "throw", + arg: t + }; + } + } + e.wrap = wrap; + var h = "suspendedStart", + l = "suspendedYield", + f = "executing", + s = "completed", + y = {}; + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + var p = {}; + define(p, a, function () { + return this; + }); + var d = Object.getPrototypeOf, + v = d && d(d(values([]))); + v && v !== r && n.call(v, a) && (p = v); + var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); + function defineIteratorMethods(t) { + ["next", "throw", "return"].forEach(function (e) { + define(t, e, function (t) { + return this._invoke(e, t); + }); + }); + } + function AsyncIterator(t, e) { + function invoke(r, o, i, a) { + var c = tryCatch(t[r], t, o); + if ("throw" !== c.type) { + var u = c.arg, + h = u.value; + return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { + invoke("next", t, i, a); + }, function (t) { + invoke("throw", t, i, a); + }) : e.resolve(h).then(function (t) { + u.value = t, i(u); + }, function (t) { + return invoke("throw", t, i, a); + }); + } + a(c.arg); + } + var r; + o(this, "_invoke", { + value: function value(t, n) { + function callInvokeWithMethodAndArg() { + return new e(function (e, r) { + invoke(t, n, e, r); + }); + } + return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + }); + } + function makeInvokeMethod(e, r, n) { + var o = h; + return function (i, a) { + if (o === f) throw new Error("Generator is already running"); + if (o === s) { + if ("throw" === i) throw a; + return { + value: t, + done: !0 + }; + } + for (n.method = i, n.arg = a;;) { + var c = n.delegate; + if (c) { + var u = maybeInvokeDelegate(c, n); + if (u) { + if (u === y) continue; + return u; + } + } + if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { + if (o === h) throw o = s, n.arg; + n.dispatchException(n.arg); + } else "return" === n.method && n.abrupt("return", n.arg); + o = f; + var p = tryCatch(e, r, n); + if ("normal" === p.type) { + if (o = n.done ? s : l, p.arg === y) continue; + return { + value: p.arg, + done: n.done + }; + } + "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); + } + }; + } + function maybeInvokeDelegate(e, r) { + var n = r.method, + o = e.iterator[n]; + if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; + var i = tryCatch(o, e.iterator, r.arg); + if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; + var a = i.arg; + return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); + } + function pushTryEntry(t) { + var e = { + tryLoc: t[0] + }; + 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); + } + function resetTryEntry(t) { + var e = t.completion || {}; + e.type = "normal", delete e.arg, t.completion = e; + } + function Context(t) { + this.tryEntries = [{ + tryLoc: "root" + }], t.forEach(pushTryEntry, this), this.reset(!0); + } + function values(e) { + if (e || "" === e) { + var r = e[a]; + if (r) return r.call(e); + if ("function" == typeof e.next) return e; + if (!isNaN(e.length)) { + var o = -1, + i = function next() { + for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; + return next.value = t, next.done = !0, next; + }; + return i.next = i; + } + } + throw new TypeError(_typeof(e) + " is not iterable"); + } + return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { + value: GeneratorFunctionPrototype, + configurable: !0 + }), o(GeneratorFunctionPrototype, "constructor", { + value: GeneratorFunction, + configurable: !0 + }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { + var e = "function" == typeof t && t.constructor; + return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); + }, e.mark = function (t) { + return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; + }, e.awrap = function (t) { + return { + __await: t + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { + return this; + }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { + void 0 === i && (i = Promise); + var a = new AsyncIterator(wrap(t, r, n, o), i); + return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { + return t.done ? t.value : a.next(); + }); + }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { + return this; + }), define(g, "toString", function () { + return "[object Generator]"; + }), e.keys = function (t) { + var e = Object(t), + r = []; + for (var n in e) r.push(n); + return r.reverse(), function next() { + for (; r.length;) { + var t = r.pop(); + if (t in e) return next.value = t, next.done = !1, next; + } + return next.done = !0, next; + }; + }, e.values = values, Context.prototype = { + constructor: Context, + reset: function reset(e) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); + }, + stop: function stop() { + this.done = !0; + var t = this.tryEntries[0].completion; + if ("throw" === t.type) throw t.arg; + return this.rval; + }, + dispatchException: function dispatchException(e) { + if (this.done) throw e; + var r = this; + function handle(n, o) { + return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; + } + for (var o = this.tryEntries.length - 1; o >= 0; --o) { + var i = this.tryEntries[o], + a = i.completion; + if ("root" === i.tryLoc) return handle("end"); + if (i.tryLoc <= this.prev) { + var c = n.call(i, "catchLoc"), + u = n.call(i, "finallyLoc"); + if (c && u) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } else if (c) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + } else { + if (!u) throw new Error("try statement without catch or finally"); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } + } + } + }, + abrupt: function abrupt(t, e) { + for (var r = this.tryEntries.length - 1; r >= 0; --r) { + var o = this.tryEntries[r]; + if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { + var i = o; + break; + } + } + i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); + var a = i ? i.completion : {}; + return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); + }, + complete: function complete(t, e) { + if ("throw" === t.type) throw t.arg; + return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; + }, + finish: function finish(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; + } + }, + "catch": function _catch(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.tryLoc === t) { + var n = r.completion; + if ("throw" === n.type) { + var o = n.arg; + resetTryEntry(r); + } + return o; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(e, r, n) { + return this.delegate = { + iterator: values(e), + resultName: r, + nextLoc: n + }, "next" === this.method && (this.arg = t), y; + } + }, e; + } + module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (regeneratorRuntime$1)); + + var regeneratorRuntimeExports = regeneratorRuntime$1.exports; + + // TODO(Babel 8): Remove this file. + + var runtime = regeneratorRuntimeExports(); + var regenerator = runtime; + + // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } + } + + var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator); + + function filteredMparticleUser(mpid, forwarder, mpInstance, kitBlocker) { + var self = this; + return { + getUserIdentities: function getUserIdentities() { + var currentUserIdentities = {}; + var identities = mpInstance._Store.getUserIdentities(mpid); + for (var identityType in identities) { + if (identities.hasOwnProperty(identityType)) { + var identityName = Types.IdentityType.getIdentityName(mpInstance._Helpers.parseNumber(identityType)); + if (!kitBlocker || kitBlocker && !kitBlocker.isIdentityBlocked(identityName)) + //if identity type is not blocked + currentUserIdentities[identityName] = identities[identityType]; + } + } + currentUserIdentities = mpInstance._Helpers.filterUserIdentitiesForForwarders(currentUserIdentities, forwarder.userIdentityFilters); + return { + userIdentities: currentUserIdentities + }; + }, + getMPID: function getMPID() { + return mpid; + }, + getUserAttributesLists: function getUserAttributesLists(forwarder) { + var userAttributes, + userAttributesLists = {}; + userAttributes = self.getAllUserAttributes(); + for (var key in userAttributes) { + if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) { + if (!kitBlocker || kitBlocker && !kitBlocker.isAttributeKeyBlocked(key)) { + userAttributesLists[key] = userAttributes[key].slice(); + } + } + } + userAttributesLists = mpInstance._Helpers.filterUserAttributes(userAttributesLists, forwarder.userAttributeFilters); + return userAttributesLists; + }, + getAllUserAttributes: function getAllUserAttributes() { + var userAttributesCopy = {}; + var userAttributes = mpInstance._Store.getUserAttributes(mpid); + if (userAttributes) { + for (var prop in userAttributes) { + if (userAttributes.hasOwnProperty(prop)) { + if (!kitBlocker || kitBlocker && !kitBlocker.isAttributeKeyBlocked(prop)) { + if (Array.isArray(userAttributes[prop])) { + userAttributesCopy[prop] = userAttributes[prop].slice(); + } else { + userAttributesCopy[prop] = userAttributes[prop]; + } + } + } + } + } + userAttributesCopy = mpInstance._Helpers.filterUserAttributes(userAttributesCopy, forwarder.userAttributeFilters); + return userAttributesCopy; + } + }; + } + + var _Constants$IdentityMe = Constants.IdentityMethods, + Modify$2 = _Constants$IdentityMe.Modify, + Identify$1 = _Constants$IdentityMe.Identify, + Login$1 = _Constants$IdentityMe.Login, + Logout$1 = _Constants$IdentityMe.Logout; + function Forwarders(mpInstance, kitBlocker) { + var _this = this; + var self = this; + this.forwarderStatsUploader = new APIClient(mpInstance, kitBlocker).initializeForwarderStatsUploader(); + var UserAttributeActionTypes = { + setUserAttribute: 'setUserAttribute', + removeUserAttribute: 'removeUserAttribute' + }; + this.initForwarders = function (userIdentities, forwardingStatsCallback) { + var user = mpInstance.Identity.getCurrentUser(); + if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.configuredForwarders) { + // Some js libraries require that they be loaded first, or last, etc + mpInstance._Store.configuredForwarders.sort(function (x, y) { + x.settings.PriorityValue = x.settings.PriorityValue || 0; + y.settings.PriorityValue = y.settings.PriorityValue || 0; + return -1 * (x.settings.PriorityValue - y.settings.PriorityValue); + }); + mpInstance._Store.activeForwarders = mpInstance._Store.configuredForwarders.filter(function (forwarder) { + if (!mpInstance._Consent.isEnabledForUserConsent(forwarder.filteringConsentRuleValues, user)) { + return false; + } + if (!self.isEnabledForUserAttributes(forwarder.filteringUserAttributeValue, user)) { + return false; + } + if (!self.isEnabledForUnknownUser(forwarder.excludeAnonymousUser, user)) { + return false; + } + var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters); + var filteredUserAttributes = mpInstance._Helpers.filterUserAttributes(user ? user.getAllUserAttributes() : {}, forwarder.userAttributeFilters); + if (!forwarder.initialized) { + forwarder.logger = mpInstance.Logger; + forwarder.init(forwarder.settings, forwardingStatsCallback, false, null, filteredUserAttributes, filteredUserIdentities, mpInstance._Store.SDKConfig.appVersion, mpInstance._Store.SDKConfig.appName, mpInstance._Store.SDKConfig.customFlags, mpInstance._Store.clientId); + forwarder.initialized = true; + } + return true; + }); + } + }; + this.isEnabledForUserAttributes = function (filterObject, user) { + if (!filterObject || !mpInstance._Helpers.isObject(filterObject) || !Object.keys(filterObject).length) { + return true; + } + var attrHash, valueHash, userAttributes; + if (!user) { + return false; + } else { + userAttributes = user.getAllUserAttributes(); + } + var isMatch = false; + try { + if (userAttributes && mpInstance._Helpers.isObject(userAttributes) && Object.keys(userAttributes).length) { + for (var attrName in userAttributes) { + if (userAttributes.hasOwnProperty(attrName)) { + attrHash = KitFilterHelper.hashAttributeConditionalForwarding(attrName); + valueHash = KitFilterHelper.hashAttributeConditionalForwarding(userAttributes[attrName]); + if (attrHash === filterObject.userAttributeName && valueHash === filterObject.userAttributeValue) { + isMatch = true; + break; + } + } + } + } + if (filterObject) { + return filterObject.includeOnMatch === isMatch; + } else { + return true; + } + } catch (e) { + // in any error scenario, err on side of returning true and forwarding event + return true; + } + }; + this.isEnabledForUnknownUser = function (excludeAnonymousUserBoolean, user) { + if (!user || !user.isLoggedIn()) { + if (excludeAnonymousUserBoolean) { + return false; + } + } + return true; + }; + this.applyToForwarders = function (functionName, functionArgs) { + if (mpInstance._Store.activeForwarders.length) { + mpInstance._Store.activeForwarders.forEach(function (forwarder) { + var forwarderFunction = forwarder[functionName]; + if (forwarderFunction) { + try { + var result = forwarder[functionName](functionArgs); + if (result) { + mpInstance.Logger.verbose(result); + } + } catch (e) { + mpInstance.Logger.verbose(e); + } + } + }); + } + }; + this.sendEventToForwarders = function (event) { + var clonedEvent, + hashedEventName, + hashedEventType, + filterUserIdentities = function filterUserIdentities(event, filterList) { + if (event.UserIdentities && event.UserIdentities.length) { + event.UserIdentities.forEach(function (userIdentity, i) { + if (mpInstance._Helpers.inArray(filterList, KitFilterHelper.hashUserIdentity(userIdentity.Type))) { + event.UserIdentities.splice(i, 1); + if (i > 0) { + i--; + } + } + }); + } + }, + filterAttributes = function filterAttributes(event, filterList) { + var hash; + if (!filterList) { + return; + } + for (var attrName in event.EventAttributes) { + if (event.EventAttributes.hasOwnProperty(attrName)) { + hash = KitFilterHelper.hashEventAttributeKey(event.EventCategory, event.EventName, attrName); + if (mpInstance._Helpers.inArray(filterList, hash)) { + delete event.EventAttributes[attrName]; + } + } + } + }, + inFilteredList = function inFilteredList(filterList, hash) { + if (filterList && filterList.length) { + if (mpInstance._Helpers.inArray(filterList, hash)) { + return true; + } + } + return false; + }, + forwardingRuleMessageTypes = [Types.MessageType.PageEvent, Types.MessageType.PageView, Types.MessageType.Commerce]; + if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.activeForwarders) { + hashedEventName = KitFilterHelper.hashEventName(event.EventName, event.EventCategory); + hashedEventType = KitFilterHelper.hashEventType(event.EventCategory); + for (var i = 0; i < mpInstance._Store.activeForwarders.length; i++) { + // Check attribute forwarding rule. This rule allows users to only forward an event if a + // specific attribute exists and has a specific value. Alternatively, they can specify + // that an event not be forwarded if the specified attribute name and value exists. + // The two cases are controlled by the "includeOnMatch" boolean value. + // Supported message types for attribute forwarding rules are defined in the forwardingRuleMessageTypes array + + if (forwardingRuleMessageTypes.indexOf(event.EventDataType) > -1 && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue) { + var foundProp = null; + + // Attempt to find the attribute in the collection of event attributes + if (event.EventAttributes) { + for (var prop in event.EventAttributes) { + var hashedEventAttributeName; + hashedEventAttributeName = KitFilterHelper.hashAttributeConditionalForwarding(prop); + if (hashedEventAttributeName === mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName) { + foundProp = { + name: hashedEventAttributeName, + value: KitFilterHelper.hashAttributeConditionalForwarding(event.EventAttributes[prop]) + }; + } + if (foundProp) { + break; + } + } + } + var isMatch = foundProp !== null && foundProp.value === mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue; + var shouldInclude = mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.includeOnMatch === true ? isMatch : !isMatch; + if (!shouldInclude) { + continue; + } + } + + // Clone the event object, as we could be sending different attributes to each forwarder + clonedEvent = {}; + clonedEvent = mpInstance._Helpers.extend(true, clonedEvent, event); + // Check event filtering rules + if (event.EventDataType === Types.MessageType.PageEvent && (inFilteredList(mpInstance._Store.activeForwarders[i].eventNameFilters, hashedEventName) || inFilteredList(mpInstance._Store.activeForwarders[i].eventTypeFilters, hashedEventType))) { + continue; + } else if (event.EventDataType === Types.MessageType.Commerce && inFilteredList(mpInstance._Store.activeForwarders[i].eventTypeFilters, hashedEventType)) { + continue; + } else if (event.EventDataType === Types.MessageType.PageView && inFilteredList(mpInstance._Store.activeForwarders[i].screenNameFilters, hashedEventName)) { + continue; + } + + // Check attribute filtering rules + if (clonedEvent.EventAttributes) { + if (event.EventDataType === Types.MessageType.PageEvent) { + filterAttributes(clonedEvent, mpInstance._Store.activeForwarders[i].attributeFilters); + } else if (event.EventDataType === Types.MessageType.PageView) { + filterAttributes(clonedEvent, mpInstance._Store.activeForwarders[i].screenAttributeFilters); + } + } + + // Check user identity filtering rules + filterUserIdentities(clonedEvent, mpInstance._Store.activeForwarders[i].userIdentityFilters); + + // Check user attribute filtering rules + clonedEvent.UserAttributes = mpInstance._Helpers.filterUserAttributes(clonedEvent.UserAttributes, mpInstance._Store.activeForwarders[i].userAttributeFilters); + if (mpInstance._Store.activeForwarders[i].process) { + mpInstance.Logger.verbose('Sending message to forwarder: ' + mpInstance._Store.activeForwarders[i].name); + var result = mpInstance._Store.activeForwarders[i].process(clonedEvent); + if (result) { + mpInstance.Logger.verbose(result); + } + } + } + } + }; + this.handleForwarderUserAttributes = function (functionNameKey, key, value) { + if (kitBlocker && kitBlocker.isAttributeKeyBlocked(key) || !mpInstance._Store.activeForwarders.length) { + return; + } + mpInstance._Store.activeForwarders.forEach(function (forwarder) { + var forwarderFunction = forwarder[functionNameKey]; + if (!forwarderFunction || KitFilterHelper.isFilteredUserAttribute(key, forwarder.userAttributeFilters)) { + return; + } + try { + var result; + if (functionNameKey === UserAttributeActionTypes.setUserAttribute) { + result = forwarder.setUserAttribute(key, value); + } else if (functionNameKey === UserAttributeActionTypes.removeUserAttribute) { + result = forwarder.removeUserAttribute(key); + } + if (result) { + mpInstance.Logger.verbose(result); + } + } catch (e) { + mpInstance.Logger.error(e); + } + }); + }; + + // TODO: https://go.mparticle.com/work/SQDSDKS-6036 + this.setForwarderUserIdentities = function (userIdentities) { + mpInstance._Store.activeForwarders.forEach(function (forwarder) { + var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters); + if (forwarder.setUserIdentity) { + filteredUserIdentities.forEach(function (identity) { + var result = forwarder.setUserIdentity(identity.Identity, identity.Type); + if (result) { + mpInstance.Logger.verbose(result); + } + }); + } + }); + }; + this.setForwarderOnUserIdentified = function (user) { + mpInstance._Store.activeForwarders.forEach(function (forwarder) { + var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); + if (forwarder.onUserIdentified) { + var result = forwarder.onUserIdentified(filteredUser); + if (result) { + mpInstance.Logger.verbose(result); + } + } + }); + }; + this.setForwarderOnIdentityComplete = function (user, identityMethod) { + var result; + mpInstance._Store.activeForwarders.forEach(function (forwarder) { + var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); + var filteredUserIdentities = filteredUser.getUserIdentities(); + if (identityMethod === Identify$1) { + if (forwarder.onIdentifyComplete) { + result = forwarder.onIdentifyComplete(filteredUser, filteredUserIdentities); + if (result) { + mpInstance.Logger.verbose(result); + } + } + } else if (identityMethod === Login$1) { + if (forwarder.onLoginComplete) { + result = forwarder.onLoginComplete(filteredUser, filteredUserIdentities); + if (result) { + mpInstance.Logger.verbose(result); + } + } + } else if (identityMethod === Logout$1) { + if (forwarder.onLogoutComplete) { + result = forwarder.onLogoutComplete(filteredUser, filteredUserIdentities); + if (result) { + mpInstance.Logger.verbose(result); + } + } + } else if (identityMethod === Modify$2) { + if (forwarder.onModifyComplete) { + result = forwarder.onModifyComplete(filteredUser, filteredUserIdentities); + if (result) { + mpInstance.Logger.verbose(result); + } + } + } + }); + }; + this.getForwarderStatsQueue = function () { + return mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue; + }; + this.setForwarderStatsQueue = function (queue) { + mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue; + }; + + // Processing forwarders is a 2 step process: + // 1. Configure the kit + // 2. Initialize the kit + // There are 2 types of kits: + // 1. UI-enabled kits + // 2. Sideloaded kits. + this.processForwarders = function (config, forwardingStatsCallback) { + if (!config) { + mpInstance.Logger.warning('No config was passed. Cannot process forwarders'); + } else { + this.processUIEnabledKits(config); + this.processSideloadedKits(config); + self.initForwarders(mpInstance._Store.SDKConfig.identifyRequest.userIdentities, forwardingStatsCallback); + } + }; + + // These are kits that are enabled via the mParticle UI. + // A kit that is UI-enabled will have a kit configuration that returns from + // the server, or in rare cases, is passed in by the developer. + // The kit configuration will be compared with the kit constructors to determine + // if there is a match before being initialized. + // Only kits that are configured properly can be active and used for kit forwarding. + this.processUIEnabledKits = function (config) { + var kits = this.returnKitConstructors(); + try { + if (Array.isArray(config.kitConfigs) && config.kitConfigs.length) { + config.kitConfigs.forEach(function (kitConfig) { + self.configureUIEnabledKit(kitConfig, kits); + }); + } + } catch (e) { + mpInstance.Logger.error('MP Kits not configured propertly. Kits may not be initialized. ' + e); + } + }; + this.returnKitConstructors = function () { + var kits = {}; + // If there are kits inside of mpInstance._Store.SDKConfig.kits, then mParticle is self hosted + if (!isEmpty(mpInstance._Store.SDKConfig.kits)) { + kits = mpInstance._Store.SDKConfig.kits; + // otherwise mParticle is loaded via script tag + } else if (!isEmpty(mpInstance._preInit.forwarderConstructors)) { + mpInstance._preInit.forwarderConstructors.forEach(function (kitConstructor) { + // A suffix is added to a kitConstructor and kit config if there are multiple different + // versions of a client kit. This matches the suffix in the DB. As an example + // the GA4 kit has a client kit and a server side kit which has a client side + // component. They share the same name/module ID in the DB, so we include a + // suffix to distinguish them in the kits object. + // If a customer wanted simultaneous GA4 client and server connections, + // a suffix allows the SDK to distinguish the two. + if (kitConstructor.suffix) { + var kitNameWithConstructorSuffix = "".concat(kitConstructor.name, "-").concat(kitConstructor.suffix); + kits[kitNameWithConstructorSuffix] = kitConstructor; + } else { + kits[kitConstructor.name] = kitConstructor; + } + }); + } + return kits; + }; + this.configureUIEnabledKit = function (configuration, kits) { + var newKit = null; + var config = configuration; + for (var name in kits) { + // Configs are returned with suffixes also. We need to consider the + // config suffix here to match the constructor suffix + var kitNameWithConfigSuffix = void 0; + if (config.suffix) { + kitNameWithConfigSuffix = "".concat(config.name, "-").concat(config.suffix); + } + if (name === kitNameWithConfigSuffix || name === config.name) { + if (config.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || config.isSandbox === mpInstance._Store.SDKConfig.isDevelopmentMode) { + newKit = this.returnConfiguredKit(kits[name], config); + mpInstance._Store.configuredForwarders.push(newKit); + break; + } + } + } + }; + + // Unlike UI enabled kits, sideloaded kits are always added to active forwarders. + + // TODO: Sideloading kits currently require the use of a register method + // which requires an object on which to be registered. + // In the future, when all kits are moved to the mpConfig rather than + // there being a separate process for MP configured kits and + // sideloaded kits, this will need to be refactored. + this.processSideloadedKits = function (mpConfig) { + try { + if (Array.isArray(mpConfig.sideloadedKits)) { + var registeredSideloadedKits = { + kits: {} + }; + var unregisteredSideloadedKits = mpConfig.sideloadedKits; + unregisteredSideloadedKits.forEach(function (unregisteredKit) { + try { + // Register each sideloaded kit, which adds a key of the sideloaded kit name + // and a value of the sideloaded kit constructor. + unregisteredKit.kitInstance.register(registeredSideloadedKits); + var kitName = unregisteredKit.kitInstance.name; + // Then add the kit filters to each registered kit. + registeredSideloadedKits.kits[kitName].filters = unregisteredKit.filterDictionary; + } catch (e) { + console.error('Error registering sideloaded kit ' + unregisteredKit.kitInstance.name); + } + }); + + // Then configure each registered kit + for (var registeredKitKey in registeredSideloadedKits.kits) { + var registeredKit = registeredSideloadedKits.kits[registeredKitKey]; + self.configureSideloadedKit(registeredKit); + } + + // If Sideloaded Kits are successfully registered, + // record this in the Store. + if (!isEmpty(registeredSideloadedKits.kits)) { + var kitKeys = Object.keys(registeredSideloadedKits.kits); + mpInstance._Store.sideloadedKitsCount = kitKeys.length; + } + } + } catch (e) { + mpInstance.Logger.error('Sideloaded Kits not configured propertly. Kits may not be initialized. ' + e); + } + }; + + // kits can be included via mParticle UI, or via sideloaded kit config API + this.configureSideloadedKit = function (kitConstructor) { + mpInstance._Store.configuredForwarders.push(this.returnConfiguredKit(kitConstructor, kitConstructor.filters)); + }; + this.returnConfiguredKit = function (forwarder) { + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var newForwarder = new forwarder.constructor(); + newForwarder.id = config.moduleId; + + // TODO: isSandbox, hasSandbox is never used in any kit or in core SDK. + // isVisible. Investigate is only used in 1 place. It is always true if + // it is sent to JS. Investigate further to determine if these can be removed. + // https://go.mparticle.com/work/SQDSDKS-5156 + newForwarder.isSandbox = config.isDebug || config.isSandbox; + newForwarder.hasSandbox = config.hasDebugString === 'true'; + newForwarder.isVisible = config.isVisible || true; + newForwarder.settings = config.settings || {}; + newForwarder.eventNameFilters = config.eventNameFilters || []; + newForwarder.eventTypeFilters = config.eventTypeFilters || []; + newForwarder.attributeFilters = config.attributeFilters || []; + newForwarder.screenNameFilters = config.screenNameFilters || []; + newForwarder.screenAttributeFilters = config.screenAttributeFilters || []; + newForwarder.userIdentityFilters = config.userIdentityFilters || []; + newForwarder.userAttributeFilters = config.userAttributeFilters || []; + newForwarder.filteringEventAttributeValue = config.filteringEventAttributeValue || {}; + newForwarder.filteringUserAttributeValue = config.filteringUserAttributeValue || {}; + newForwarder.eventSubscriptionId = config.eventSubscriptionId || null; + newForwarder.filteringConsentRuleValues = config.filteringConsentRuleValues || {}; + newForwarder.excludeAnonymousUser = config.excludeAnonymousUser || false; + return newForwarder; + }; + this.configurePixel = function (settings) { + if (settings.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || settings.isProduction !== mpInstance._Store.SDKConfig.isDevelopmentMode) { + mpInstance._Store.pixelConfigurations.push(settings); + } + }; + this.processPixelConfigs = function (config) { + try { + if (!isEmpty(config.pixelConfigs)) { + config.pixelConfigs.forEach(function (pixelConfig) { + self.configurePixel(pixelConfig); + }); + } + } catch (e) { + mpInstance.Logger.error('Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. ' + e); + } + }; + this.sendSingleForwardingStatsToServer = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(forwardingStatsData) { + var _mpInstance$Logger; + var fetchPayload, response, message; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + // https://go.mparticle.com/work/SQDSDKS-6568 + fetchPayload = { + method: 'post', + body: JSON.stringify(forwardingStatsData), + headers: { + Accept: 'text/plain;charset=UTF-8', + 'Content-Type': 'text/plain;charset=UTF-8' + } + }; + _context.next = 3; + return _this.forwarderStatsUploader.upload(fetchPayload); + case 3: + response = _context.sent; + // This is a fire and forget, so we only need to log the response based on the code, and not return any response body + if (response.status === 202) { + // https://go.mparticle.com/work/SQDSDKS-6670 + message = 'Successfully sent forwarding stats to mParticle Servers'; + } else { + message = 'Issue with forwarding stats to mParticle Servers, received HTTP Code of ' + response.statusText; + } + mpInstance === null || mpInstance === void 0 || (_mpInstance$Logger = mpInstance.Logger) === null || _mpInstance$Logger === void 0 || _mpInstance$Logger.verbose(message); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); + } + + // TODO: This file is no longer the server model because the web SDK payload + var MessageType = Types.MessageType; + var ApplicationTransitionType = Types.ApplicationTransitionType; + // TODO: Make this a pure function that returns a new object + function convertCustomFlags(event, dto) { + var valueArray = []; + dto.flags = {}; + for (var prop in event.CustomFlags) { + valueArray = []; + if (event.CustomFlags.hasOwnProperty(prop)) { + if (Array.isArray(event.CustomFlags[prop])) { + event.CustomFlags[prop].forEach(function (customFlagProperty) { + if (isValidCustomFlagProperty(customFlagProperty)) { + valueArray.push(customFlagProperty.toString()); + } + }); + } else if (isValidCustomFlagProperty(event.CustomFlags[prop])) { + valueArray.push(event.CustomFlags[prop].toString()); + } + if (valueArray.length) { + dto.flags[prop] = valueArray; + } + } + } + } + function convertProductToV2DTO(product) { + return { + id: parseStringOrNumber(product.Sku), + nm: parseStringOrNumber(product.Name), + pr: parseNumber(product.Price), + qt: parseNumber(product.Quantity), + br: parseStringOrNumber(product.Brand), + va: parseStringOrNumber(product.Variant), + ca: parseStringOrNumber(product.Category), + ps: parseNumber(product.Position), + cc: parseStringOrNumber(product.CouponCode), + tpa: parseNumber(product.TotalAmount), + attrs: product.Attributes + }; + } + function convertProductListToV2DTO(productList) { + if (!productList) { + return []; + } + return productList.map(function (product) { + return convertProductToV2DTO(product); + }); + } + function ServerModel(mpInstance) { + var self = this; + this.convertToConsentStateV2DTO = function (state) { + if (!state) { + return null; + } + var jsonObject = {}; + var gdprConsentState = state.getGDPRConsentState(); + if (gdprConsentState) { + var gdpr = {}; + jsonObject.gdpr = gdpr; + for (var purpose in gdprConsentState) { + if (gdprConsentState.hasOwnProperty(purpose)) { + var gdprConsent = gdprConsentState[purpose]; + jsonObject.gdpr[purpose] = {}; + if (typeof gdprConsent.Consented === 'boolean') { + gdpr[purpose].c = gdprConsent.Consented; + } + if (typeof gdprConsent.Timestamp === 'number') { + gdpr[purpose].ts = gdprConsent.Timestamp; + } + if (typeof gdprConsent.ConsentDocument === 'string') { + gdpr[purpose].d = gdprConsent.ConsentDocument; + } + if (typeof gdprConsent.Location === 'string') { + gdpr[purpose].l = gdprConsent.Location; + } + if (typeof gdprConsent.HardwareId === 'string') { + gdpr[purpose].h = gdprConsent.HardwareId; + } + } + } + } + var ccpaConsentState = state.getCCPAConsentState(); + if (ccpaConsentState) { + jsonObject.ccpa = { + data_sale_opt_out: { + c: ccpaConsentState.Consented, + ts: ccpaConsentState.Timestamp, + d: ccpaConsentState.ConsentDocument, + l: ccpaConsentState.Location, + h: ccpaConsentState.HardwareId + } + }; + } + return jsonObject; + }; + this.createEventObject = function (event, user) { + var _a; + var uploadObject = {}; + var eventObject = {}; + // The `optOut` variable is passed later in this method to the `uploadObject` + // so that it can be used to denote whether or not a user has "opted out" of being + // tracked. If this is an `optOut` Event, we set `optOut` to the inverse of the SDK's + // `isEnabled` boolean which is controlled via `MPInstanceManager.setOptOut`. + var optOut = event.messageType === Types.MessageType.OptOut ? !mpInstance._Store.isEnabled : null; + // TODO: Why is Webview Bridge Enabled or Opt Out necessary here? + if (mpInstance._Store.sessionId || event.messageType === Types.MessageType.OptOut || mpInstance._Store.webviewBridgeEnabled) { + var customFlags = __assign({}, event.customFlags); + var integrationAttributes = mpInstance._Store.integrationAttributes; + var getFeatureFlag = mpInstance._Helpers.getFeatureFlag; + // https://go.mparticle.com/work/SQDSDKS-5053 + // https://go.mparticle.com/work/SQDSDKS-7639 + var integrationSpecificIds = getFeatureFlag && getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds); + var integrationSpecificIdsV2 = getFeatureFlag && (getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || ''); + var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; + if (isIntegrationCaptureEnabled) { + // Attempt to recapture click IDs in case a third party integration + // has added or updated new click IDs since the last event was sent. + mpInstance._IntegrationCapture.capture(); + var transformedClickIDs = mpInstance._IntegrationCapture.getClickIdsAsCustomFlags(); + customFlags = __assign(__assign({}, transformedClickIDs), customFlags); + var transformedIntegrationAttributes = mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes(); + integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes); + } + if (event.hasOwnProperty('toEventAPIObject')) { + eventObject = event.toEventAPIObject(); + } else { + eventObject = { + // This is an artifact from v2 events where SessionStart/End and AST event + // names are numbers (1, 2, or 10), but going forward with v3, these lifecycle + // events do not have names, but are denoted by their `event_type` + EventName: event.name || event.messageType, + EventCategory: event.eventType, + EventAttributes: mpInstance._Helpers.sanitizeAttributes(event.data, event.name), + ActiveTimeOnSite: (_a = mpInstance._timeOnSiteTimer) === null || _a === void 0 ? void 0 : _a.getTimeInForeground(), + SourceMessageId: event.sourceMessageId || mpInstance._Helpers.generateUniqueId(), + EventDataType: event.messageType, + CustomFlags: customFlags, + UserAttributeChanges: event.userAttributeChanges, + UserIdentityChanges: event.userIdentityChanges + }; + } + // TODO: Should we move this side effect outside of this method? + if (event.messageType !== Types.MessageType.SessionEnd) { + mpInstance._Store.dateLastEventSent = new Date(); + } + uploadObject = { + // FIXME: Deprecate when we get rid of V2 + Store: mpInstance._Store.serverSettings, + SDKVersion: Constants.sdkVersion, + SessionId: mpInstance._Store.sessionId, + SessionStartDate: mpInstance._Store.sessionStartDate ? mpInstance._Store.sessionStartDate.getTime() : 0, + Debug: mpInstance._Store.SDKConfig.isDevelopmentMode, + Location: mpInstance._Store.currentPosition, + OptOut: optOut, + ExpandedEventCount: 0, + AppVersion: mpInstance.getAppVersion(), + AppName: mpInstance.getAppName(), + Package: mpInstance._Store.SDKConfig["package"], + ClientGeneratedId: mpInstance._Store.clientId, + DeviceId: mpInstance._Store.deviceId, + IntegrationAttributes: integrationAttributes, + CurrencyCode: mpInstance._Store.currencyCode, + DataPlan: mpInstance._Store.SDKConfig.dataPlan ? mpInstance._Store.SDKConfig.dataPlan : {} + }; + if (eventObject.EventDataType === MessageType.AppStateTransition) { + eventObject.IsFirstRun = mpInstance._Store.isFirstRun; + eventObject.LaunchReferral = window.location.href || null; + } + // FIXME: Remove duplicate occurence + eventObject.CurrencyCode = mpInstance._Store.currencyCode; + var currentUser = user || mpInstance.Identity.getCurrentUser(); + appendUserInfo(currentUser, eventObject); + if (event.messageType === Types.MessageType.SessionEnd) { + eventObject.SessionLength = mpInstance._Store.dateLastEventSent.getTime() - mpInstance._Store.sessionStartDate.getTime(); + eventObject.currentSessionMPIDs = mpInstance._Store.currentSessionMPIDs; + // Session attributes are assigned on a session level, but only uploaded + // when a session ends. As there is no way to attach event attributes to + // a `SessionEnd` event, we are uploading the session level attributes + // as event level attributes in a `SessionEnd` event. + eventObject.EventAttributes = mpInstance._Store.sessionAttributes; + // TODO: We should move this out of here to avoid side effects + mpInstance._Store.currentSessionMPIDs = []; + mpInstance._Store.sessionStartDate = null; + } + uploadObject.Timestamp = mpInstance._Store.dateLastEventSent.getTime(); + return mpInstance._Helpers.extend({}, eventObject, uploadObject); + } + return null; + }; + this.convertEventToV2DTO = function (event) { + var dto = { + n: event.EventName, + et: event.EventCategory, + ua: event.UserAttributes, + ui: event.UserIdentities, + ia: event.IntegrationAttributes, + str: event.Store, + attrs: event.EventAttributes, + sdk: event.SDKVersion, + sid: event.SessionId, + sl: event.SessionLength, + ssd: event.SessionStartDate, + dt: event.EventDataType, + dbg: event.Debug, + ct: event.Timestamp, + lc: event.Location, + o: event.OptOut, + eec: event.ExpandedEventCount, + av: event.AppVersion, + cgid: event.ClientGeneratedId, + das: event.DeviceId, + mpid: event.MPID, + smpids: event.currentSessionMPIDs + }; + if (event.DataPlan && event.DataPlan.PlanId) { + dto.dp_id = event.DataPlan.PlanId; + if (event.DataPlan.PlanVersion) { + dto.dp_v = event.DataPlan.PlanVersion; + } + } + var consent = self.convertToConsentStateV2DTO(event.ConsentState); + if (consent) { + dto.con = consent; + } + if (event.EventDataType === MessageType.AppStateTransition) { + dto.fr = event.IsFirstRun; + dto.iu = false; + dto.at = ApplicationTransitionType.AppInit; + dto.lr = event.LaunchReferral; + // Nullify Attributes in case AST Was logged manually or + // via logBaseEvent. AST should not have any attributes + dto.attrs = null; + } + if (event.CustomFlags) { + convertCustomFlags(event, dto); + } + if (event.EventDataType === MessageType.Commerce) { + dto.cu = event.CurrencyCode; + // TODO: If Cart is deprecated, we should deprecate this too + if (event.ShoppingCart) { + dto.sc = { + pl: convertProductListToV2DTO(event.ShoppingCart.ProductList) + }; + } + if (event.ProductAction) { + dto.pd = { + an: event.ProductAction.ProductActionType, + cs: mpInstance._Helpers.parseNumber(event.ProductAction.CheckoutStep), + co: event.ProductAction.CheckoutOptions, + pl: convertProductListToV2DTO(event.ProductAction.ProductList), + ti: event.ProductAction.TransactionId, + ta: event.ProductAction.Affiliation, + tcc: event.ProductAction.CouponCode, + tr: mpInstance._Helpers.parseNumber(event.ProductAction.TotalAmount), + ts: mpInstance._Helpers.parseNumber(event.ProductAction.ShippingAmount), + tt: mpInstance._Helpers.parseNumber(event.ProductAction.TaxAmount) + }; + } else if (event.PromotionAction) { + dto.pm = { + an: event.PromotionAction.PromotionActionType, + pl: event.PromotionAction.PromotionList.map(function (promotion) { + return { + id: promotion.Id, + nm: promotion.Name, + cr: promotion.Creative, + ps: promotion.Position ? promotion.Position : 0 + }; + }) + }; + } else if (event.ProductImpressions) { + dto.pi = event.ProductImpressions.map(function (impression) { + return { + pil: impression.ProductImpressionList, + pl: convertProductListToV2DTO(impression.ProductList) + }; + }); + } + } else if (event.EventDataType === MessageType.Profile) { + dto.pet = event.ProfileMessageType; + } + return dto; + }; + } + + function forwardingStatsUploader(mpInstance) { + this.startForwardingStatsTimer = function () { + mParticle._forwardingStatsTimer = setInterval(function () { + prepareAndSendForwardingStatsBatch(); + }, mpInstance._Store.SDKConfig.forwarderStatsTimeout); + }; + function prepareAndSendForwardingStatsBatch() { + var forwarderQueue = mpInstance._Forwarders.getForwarderStatsQueue(), + uploadsTable = mpInstance._Persistence.forwardingStatsBatches.uploadsTable, + now = Date.now(); + if (forwarderQueue.length) { + uploadsTable[now] = { + uploading: false, + data: forwarderQueue + }; + mpInstance._Forwarders.setForwarderStatsQueue([]); + } + for (var date in uploadsTable) { + (function (date) { + if (uploadsTable.hasOwnProperty(date)) { + if (uploadsTable[date].uploading === false) { + var xhrCallback = function xhrCallback() { + if (xhr.readyState === 4) { + if (xhr.status === 200 || xhr.status === 202) { + mpInstance.Logger.verbose('Successfully sent ' + xhr.statusText + ' from server'); + delete uploadsTable[date]; + } else if (xhr.status.toString()[0] === '4') { + if (xhr.status !== 429) { + delete uploadsTable[date]; + } + } else { + uploadsTable[date].uploading = false; + } + } + }; + var xhr = mpInstance._Helpers.createXHR(xhrCallback); + var forwardingStatsData = uploadsTable[date].data; + uploadsTable[date].uploading = true; + mpInstance._APIClient.sendBatchForwardingStatsToServer(forwardingStatsData, xhr); + } + } + })(date); + } + } + } + + var AudienceManager = /** @class */function () { + function AudienceManager(userAudienceUrl, apiKey, logger) { + this.url = ''; + this.logger = logger; + this.url = "https://".concat(userAudienceUrl).concat(apiKey, "/audience"); + this.userAudienceAPI = window.fetch ? new FetchUploader(this.url) : new XHRUploader(this.url); + } + AudienceManager.prototype.sendGetUserAudienceRequest = function (mpid, callback) { + return __awaiter(this, void 0, void 0, function () { + var fetchPayload, audienceURLWithMPID, userAudiencePromise, userAudienceMembershipsServerResponse, parsedUserAudienceMemberships, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + this.logger.verbose('Fetching user audiences from server'); + fetchPayload = { + method: 'GET', + headers: { + Accept: '*/*' + } + }; + audienceURLWithMPID = "".concat(this.url, "?mpid=").concat(mpid); + _a.label = 1; + case 1: + _a.trys.push([1, 6,, 7]); + return [4 /*yield*/, this.userAudienceAPI.upload(fetchPayload, audienceURLWithMPID)]; + case 2: + userAudiencePromise = _a.sent(); + if (!(userAudiencePromise.status >= 200 && userAudiencePromise.status < 300)) return [3 /*break*/, 4]; + this.logger.verbose("User Audiences successfully received"); + return [4 /*yield*/, userAudiencePromise.json()]; + case 3: + userAudienceMembershipsServerResponse = _a.sent(); + parsedUserAudienceMemberships = { + currentAudienceMemberships: userAudienceMembershipsServerResponse === null || userAudienceMembershipsServerResponse === void 0 ? void 0 : userAudienceMembershipsServerResponse.audience_memberships + }; + try { + callback(parsedUserAudienceMemberships); + } catch (e) { + throw new Error('Error invoking callback on user audience response.'); + } + return [3 /*break*/, 5]; + case 4: + if (userAudiencePromise.status === 401) { + throw new Error('`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`'); + } else if (userAudiencePromise.status === 403) { + throw new Error('`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`'); + } else { + // In case there is an HTTP error we did not anticipate. + throw new Error("Uncaught HTTP Error ".concat(userAudiencePromise.status, ".")); + } + case 5: + return [3 /*break*/, 7]; + case 6: + e_1 = _a.sent(); + this.logger.error("Error retrieving audiences. ".concat(e_1)); + return [3 /*break*/, 7]; + case 7: + return [2 /*return*/]; + } + }); + }); + }; + + return AudienceManager; + }(); + + var processReadyQueue = function processReadyQueue(readyQueue) { + if (!isEmpty(readyQueue)) { + readyQueue.forEach(function (readyQueueItem) { + if (isFunction(readyQueueItem)) { + readyQueueItem(); + } else if (Array.isArray(readyQueueItem)) { + processPreloadedItem(readyQueueItem); + } + }); + } + return []; + }; + var processPreloadedItem = function processPreloadedItem(readyQueueItem) { + var args = readyQueueItem; + var method = args.splice(0, 1)[0]; + // if the first argument is a method on the base mParticle object, run it + if (typeof window !== 'undefined' && window.mParticle && window.mParticle[args[0]]) { + window.mParticle[method].apply(window.mParticle, args); + // otherwise, the method is on either eCommerce or Identity objects, ie. "eCommerce.setCurrencyCode", "Identity.login" + } else { + var methodArray = method.split('.'); + try { + var computedMPFunction = window.mParticle; + var context_1 = window.mParticle; + // Track both the function and its context + for (var _i = 0, methodArray_1 = methodArray; _i < methodArray_1.length; _i++) { + var currentMethod = methodArray_1[_i]; + context_1 = computedMPFunction; // Keep track of the parent object + computedMPFunction = computedMPFunction[currentMethod]; + } + // Apply the function with its proper context + computedMPFunction.apply(context_1, args); + } catch (e) { + throw new Error('Unable to compute proper mParticle function ' + e); + } + } + }; + + var Messages$2 = Constants.Messages, + HTTPCodes$2 = Constants.HTTPCodes, + FeatureFlags$1 = Constants.FeatureFlags, + IdentityMethods$1 = Constants.IdentityMethods; + var ErrorMessages = Messages$2.ErrorMessages; + var CacheIdentity = FeatureFlags$1.CacheIdentity; + var Identify = IdentityMethods$1.Identify, + Modify$1 = IdentityMethods$1.Modify, + Login = IdentityMethods$1.Login, + Logout = IdentityMethods$1.Logout; + function Identity(mpInstance) { + var _mpInstance$_Helpers = mpInstance._Helpers, + getFeatureFlag = _mpInstance$_Helpers.getFeatureFlag, + extend = _mpInstance$_Helpers.extend; + var self = this; + this.idCache = null; + this.audienceManager = null; + + // https://go.mparticle.com/work/SQDSDKS-6353 + this.IdentityRequest = { + preProcessIdentityRequest: function preProcessIdentityRequest(identityApiData, callback, method) { + mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent + ': ' + method); + + // First, remove any falsy identity values and warn about them + var cleanedIdentityApiData = mpInstance._Helpers.Validators.removeFalsyIdentityValues(identityApiData, mpInstance.Logger); + var identityValidationResult = mpInstance._Helpers.Validators.validateIdentities(cleanedIdentityApiData, method); + if (!identityValidationResult.valid) { + mpInstance.Logger.error('ERROR: ' + identityValidationResult.error); + return { + valid: false, + error: identityValidationResult.error + }; + } + if (callback && !mpInstance._Helpers.Validators.isFunction(callback)) { + var error = 'The optional callback must be a function. You tried entering a(n) ' + _typeof$1(callback); + mpInstance.Logger.error(error); + return { + valid: false, + error: error + }; + } + return { + valid: true, + cleanedIdentities: cleanedIdentityApiData + }; + }, + createIdentityRequest: function createIdentityRequest(identityApiData, platform, sdkVendor, sdkVersion, deviceId, context, mpid) { + var APIRequest = { + client_sdk: { + platform: platform, + sdk_vendor: sdkVendor, + sdk_version: sdkVersion + }, + context: context, + environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? 'development' : 'production', + request_id: mpInstance._Helpers.generateUniqueId(), + request_timestamp_ms: new Date().getTime(), + previous_mpid: mpid || null, + known_identities: createKnownIdentities(identityApiData, deviceId) + }; + return APIRequest; + }, + createModifyIdentityRequest: function createModifyIdentityRequest(currentUserIdentities, newUserIdentities, platform, sdkVendor, sdkVersion, context) { + return { + client_sdk: { + platform: platform, + sdk_vendor: sdkVendor, + sdk_version: sdkVersion + }, + context: context, + environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? 'development' : 'production', + request_id: mpInstance._Helpers.generateUniqueId(), + request_timestamp_ms: new Date().getTime(), + identity_changes: this.createIdentityChanges(currentUserIdentities, newUserIdentities) + }; + }, + createIdentityChanges: function createIdentityChanges(previousIdentities, newIdentities) { + var identityChanges = []; + var key; + if (newIdentities && isObject(newIdentities) && previousIdentities && isObject(previousIdentities)) { + for (key in newIdentities) { + identityChanges.push({ + old_value: previousIdentities[key] || null, + new_value: newIdentities[key], + identity_type: key + }); + } + } + return identityChanges; + }, + // takes 2 UI objects keyed by name, combines them, returns them keyed by type + combineUserIdentities: function combineUserIdentities(previousUIByName, newUIByName) { + var combinedUIByType = {}; + var combinedUIByName = extend({}, previousUIByName, newUIByName); + for (var key in combinedUIByName) { + var type = Types.IdentityType.getIdentityType(key); + // this check removes anything that is not whitelisted as an identity type + if (type !== false && type >= 0) { + combinedUIByType[Types.IdentityType.getIdentityType(key)] = combinedUIByName[key]; + } + } + return combinedUIByType; + }, + createAliasNetworkRequest: function createAliasNetworkRequest(aliasRequest) { + return { + request_id: mpInstance._Helpers.generateUniqueId(), + request_type: 'alias', + environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? 'development' : 'production', + api_key: mpInstance._Store.devToken, + data: { + destination_mpid: aliasRequest.destinationMpid, + source_mpid: aliasRequest.sourceMpid, + start_unixtime_ms: aliasRequest.startTime, + end_unixtime_ms: aliasRequest.endTime, + scope: aliasRequest.scope, + device_application_stamp: mpInstance._Store.deviceId + } + }; + }, + convertAliasToNative: function convertAliasToNative(aliasRequest) { + return { + DestinationMpid: aliasRequest.destinationMpid, + SourceMpid: aliasRequest.sourceMpid, + StartUnixtimeMs: aliasRequest.startTime, + EndUnixtimeMs: aliasRequest.endTime, + Scope: aliasRequest.scope + }; + }, + convertToNative: function convertToNative(identityApiData) { + var nativeIdentityRequest = []; + if (identityApiData && identityApiData.userIdentities) { + for (var key in identityApiData.userIdentities) { + if (identityApiData.userIdentities.hasOwnProperty(key)) { + nativeIdentityRequest.push({ + Type: Types.IdentityType.getIdentityType(key), + Identity: identityApiData.userIdentities[key] + }); + } + } + return { + UserIdentities: nativeIdentityRequest + }; + } + } + }; + /** + * Invoke these methods on the mParticle.Identity object. + * Example: mParticle.Identity.getCurrentUser(). + * @class mParticle.Identity + */ + this.IdentityAPI = { + HTTPCodes: HTTPCodes$2, + /** + * Initiate a logout request to the mParticle server + * @method identify + * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) + * @param {Function} [callback] A callback function that is called when the identify request completes + */ + identify: function identify(identityApiData, callback) { + // https://go.mparticle.com/work/SQDSDKS-6337 + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(), + preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Identify); + if (currentUser) { + mpid = currentUser.getMPID(); + } + if (preProcessResult.valid) { + var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); + if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) { + var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Identify); + if (successfullyCachedIdentity) { + return; + } + } + if (mpInstance._Helpers.canLog()) { + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Identify request sent to native sdk'); + } else { + mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Identify, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); + mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); + mpInstance.Logger.verbose(preProcessResult); + } + }, + /** + * Initiate a logout request to the mParticle server + * @method logout + * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) + * @param {Function} [callback] A callback function that is called when the logout request completes + */ + logout: function logout(identityApiData, callback) { + // https://go.mparticle.com/work/SQDSDKS-6337 + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(), + preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Logout); + if (currentUser) { + mpid = currentUser.getMPID(); + } + if (preProcessResult.valid) { + var evt, + identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); + if (mpInstance._Helpers.canLog()) { + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Logout request sent to native sdk'); + } else { + mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Logout, callback, identityApiData, self.parseIdentityResponse, mpid); + evt = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.Profile + }); + evt.ProfileMessageType = Types.ProfileMessageType.Logout; + if (mpInstance._Store.activeForwarders.length) { + mpInstance._Store.activeForwarders.forEach(function (forwarder) { + if (forwarder.logOut) { + forwarder.logOut(evt); + } + }); + } + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); + mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); + mpInstance.Logger.verbose(preProcessResult); + } + }, + /** + * Initiate a login request to the mParticle server + * @method login + * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) + * @param {Function} [callback] A callback function that is called when the login request completes + */ + login: function login(identityApiData, callback) { + // https://go.mparticle.com/work/SQDSDKS-6337 + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(), + preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Login); + if (currentUser) { + mpid = currentUser.getMPID(); + } + if (preProcessResult.valid) { + var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); + if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) { + var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Login); + if (successfullyCachedIdentity) { + return; + } + } + if (mpInstance._Helpers.canLog()) { + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Login request sent to native sdk'); + } else { + mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Login, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); + mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); + mpInstance.Logger.verbose(preProcessResult); + } + }, + /** + * Initiate a modify request to the mParticle server + * @method modify + * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) + * @param {Function} [callback] A callback function that is called when the modify request completes + */ + modify: function modify(identityApiData, callback) { + // https://go.mparticle.com/work/SQDSDKS-6337 + var mpid, + currentUser = mpInstance.Identity.getCurrentUser(), + preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Modify$1); + if (currentUser) { + mpid = currentUser.getMPID(); + } + if (preProcessResult.valid) { + var newUserIdentities = identityApiData && identityApiData.userIdentities ? preProcessResult.cleanedIdentities.userIdentities : {}; + var identityApiRequest = mpInstance._Identity.IdentityRequest.createModifyIdentityRequest(currentUser ? currentUser.getUserIdentities().userIdentities : {}, newUserIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.context); + if (mpInstance._Helpers.canLog()) { + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Modify request sent to native sdk'); + } else { + mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Modify$1, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); + mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); + } + } else { + mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); + mpInstance.Logger.verbose(preProcessResult); + } + }, + /** + * Returns a user object with methods to interact with the current user + * @method getCurrentUser + * @return {Object} the current user object + */ + getCurrentUser: function getCurrentUser() { + var mpid; + if (mpInstance._Store) { + mpid = mpInstance._Store.mpid; + if (mpid) { + mpid = mpInstance._Store.mpid.slice(); + return self.mParticleUser(mpid, mpInstance._Store.isLoggedIn); + } else if (mpInstance._Store.webviewBridgeEnabled) { + return self.mParticleUser(); + } else { + return null; + } + } else { + return null; + } + }, + /** + * Returns a the user object associated with the mpid parameter or 'null' if no such + * user exists + * @method getUser + * @param {String} mpid of the desired user + * @return {Object} the user for mpid + */ + getUser: function getUser(mpid) { + var persistence = mpInstance._Persistence.getPersistence(); + if (persistence) { + if (persistence[mpid] && !Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(mpid)) { + return self.mParticleUser(mpid); + } else { + return null; + } + } else { + return null; + } + }, + /** + * Returns all users, including the current user and all previous users that are stored on the device. + * @method getUsers + * @return {Array} array of users + */ + getUsers: function getUsers() { + var persistence = mpInstance._Persistence.getPersistence(); + var users = []; + if (persistence) { + for (var key in persistence) { + if (!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(key)) { + users.push(self.mParticleUser(key)); + } + } + } + users.sort(function (a, b) { + var aLastSeen = a.getLastSeenTime() || 0; + var bLastSeen = b.getLastSeenTime() || 0; + if (aLastSeen > bLastSeen) { + return -1; + } else { + return 1; + } + }); + return users; + }, + /** + * Initiate an alias request to the mParticle server + * @method aliasUsers + * @param {Object} aliasRequest object representing an AliasRequest + * @param {Function} [callback] A callback function that is called when the aliasUsers request completes + */ + aliasUsers: function aliasUsers(aliasRequest, callback) { + var message; + if (!aliasRequest.destinationMpid || !aliasRequest.sourceMpid) { + message = Messages$2.ValidationMessages.AliasMissingMpid; + } + if (aliasRequest.destinationMpid === aliasRequest.sourceMpid) { + message = Messages$2.ValidationMessages.AliasNonUniqueMpid; + } + if (!aliasRequest.startTime || !aliasRequest.endTime) { + message = Messages$2.ValidationMessages.AliasMissingTime; + } + if (aliasRequest.startTime > aliasRequest.endTime) { + message = Messages$2.ValidationMessages.AliasStartBeforeEndTime; + } + if (message) { + mpInstance.Logger.warning(message); + mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.validationIssue, message); + return; + } + if (mpInstance._Helpers.canLog()) { + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias, JSON.stringify(mpInstance._Identity.IdentityRequest.convertAliasToNative(aliasRequest))); + mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.nativeIdentityRequest, 'Alias request sent to native sdk'); + } else { + mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest + ': ' + aliasRequest.sourceMpid + ' -> ' + aliasRequest.destinationMpid); + var aliasRequestMessage = mpInstance._Identity.IdentityRequest.createAliasNetworkRequest(aliasRequest); + mpInstance._IdentityAPIClient.sendAliasRequest(aliasRequestMessage, callback); + } + } else { + mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonAliasUsers); + mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers); + } + }, + /** + Create a default AliasRequest for 2 MParticleUsers. This will construct the request + using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime. + + In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only + be the case if they have not been the current user since this functionality was added, the + startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly, + if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time + + There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days. + If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime. + In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit, + after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() + validation that the startTime must be less than the endTime + */ + createAliasRequest: function createAliasRequest(sourceUser, destinationUser, scope) { + try { + if (!destinationUser || !sourceUser) { + mpInstance.Logger.error("'destinationUser' and 'sourceUser' must both be present"); + return null; + } + var startTime = sourceUser.getFirstSeenTime(); + if (!startTime) { + mpInstance.Identity.getUsers().forEach(function (user) { + if (user.getFirstSeenTime() && (!startTime || user.getFirstSeenTime() < startTime)) { + startTime = user.getFirstSeenTime(); + } + }); + } + var minFirstSeenTimeMs = new Date().getTime() - mpInstance._Store.SDKConfig.aliasMaxWindow * 24 * 60 * 60 * 1000; + var endTime = sourceUser.getLastSeenTime() || new Date().getTime(); + //if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed + if (startTime < minFirstSeenTimeMs) { + startTime = minFirstSeenTimeMs; + if (endTime < startTime) { + mpInstance.Logger.warning('Source User has not been seen in the last ' + mpInstance._Store.SDKConfig.maxAliasWindow + ' days, Alias Request will likely fail'); + } + } + return { + destinationMpid: destinationUser.getMPID(), + sourceMpid: sourceUser.getMPID(), + startTime: startTime, + endTime: endTime, + scope: scope || 'device' + }; + } catch (e) { + mpInstance.Logger.error('There was a problem with creating an alias request: ' + e); + return null; + } + } + }; + + // https://go.mparticle.com/work/SQDSDKS-6354 + /** + * Invoke these methods on the mParticle.Identity.getCurrentUser() object. + * Example: mParticle.Identity.getCurrentUser().getAllUserAttributes() + * @class mParticle.Identity.getCurrentUser() + */ + this.mParticleUser = function (mpid, _isLoggedIn) { + var self = this; + return { + /** + * Get user identities for current user + * @method getUserIdentities + * @return {Object} an object with userIdentities as its key + */ + getUserIdentities: function getUserIdentities() { + var currentUserIdentities = {}; + var identities = mpInstance._Store.getUserIdentities(mpid); + for (var identityType in identities) { + if (identities.hasOwnProperty(identityType)) { + currentUserIdentities[Types.IdentityType.getIdentityName(mpInstance._Helpers.parseNumber(identityType))] = identities[identityType]; + } + } + return { + userIdentities: currentUserIdentities + }; + }, + /** + * Get the MPID of the current user + * @method getMPID + * @return {String} the current user MPID as a string + */ + getMPID: function getMPID() { + return mpid; + }, + /** + * Sets a user tag + * @method setUserTag + * @param {String} tagName + */ + setUserTag: function setUserTag(tagName) { + if (!mpInstance._Helpers.Validators.isValidKeyValue(tagName)) { + mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); + return; + } + this.setUserAttribute(tagName, null); + }, + /** + * Removes a user tag + * @method removeUserTag + * @param {String} tagName + */ + removeUserTag: function removeUserTag(tagName) { + if (!mpInstance._Helpers.Validators.isValidKeyValue(tagName)) { + mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); + return; + } + this.removeUserAttribute(tagName); + }, + /** + * Sets a user attribute + * @method setUserAttribute + * @param {String} key + * @param {String} value + */ + // https://go.mparticle.com/work/SQDSDKS-4576 + // https://go.mparticle.com/work/SQDSDKS-6373 + setUserAttribute: function setUserAttribute(key, newValue) { + mpInstance._SessionManager.resetSessionTimer(); + if (mpInstance._Helpers.canLog()) { + if (!mpInstance._Helpers.Validators.isValidAttributeValue(newValue)) { + mpInstance.Logger.error(Messages$2.ErrorMessages.BadAttribute); + return; + } + if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) { + mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); + return; + } + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute, JSON.stringify({ + key: key, + value: newValue + })); + } else { + var userAttributes = this.getAllUserAttributes(); + var previousUserAttributeValue; + var isNewAttribute; + var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key); + if (existingProp) { + isNewAttribute = false; + previousUserAttributeValue = userAttributes[existingProp]; + delete userAttributes[existingProp]; + } else { + isNewAttribute = true; + } + userAttributes[key] = newValue; + mpInstance._Store.setUserAttributes(mpid, userAttributes); + self.sendUserAttributeChangeEvent(key, newValue, previousUserAttributeValue, isNewAttribute, false, this); + mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); + mpInstance._Forwarders.handleForwarderUserAttributes('setUserAttribute', key, newValue); + } + } + }, + /** + * Set multiple user attributes + * @method setUserAttributes + * @param {Object} user attribute object with keys of the attribute type, and value of the attribute value + */ + // https://go.mparticle.com/work/SQDSDKS-6373 + setUserAttributes: function setUserAttributes(userAttributes) { + mpInstance._SessionManager.resetSessionTimer(); + if (isObject(userAttributes)) { + if (mpInstance._Helpers.canLog()) { + for (var key in userAttributes) { + if (userAttributes.hasOwnProperty(key)) { + this.setUserAttribute(key, userAttributes[key]); + } + } + } + } else { + mpInstance.Logger.error('Must pass an object into setUserAttributes. You passed a ' + _typeof$1(userAttributes)); + } + }, + /** + * Removes a specific user attribute + * @method removeUserAttribute + * @param {String} key + */ + removeUserAttribute: function removeUserAttribute(key) { + var cookies, userAttributes; + mpInstance._SessionManager.resetSessionTimer(); + if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) { + mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); + return; + } + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute, JSON.stringify({ + key: key, + value: null + })); + } else { + cookies = mpInstance._Persistence.getPersistence(); + userAttributes = this.getAllUserAttributes(); + var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key); + if (existingProp) { + key = existingProp; + } + var deletedUAKeyCopy = userAttributes[key] ? userAttributes[key].toString() : null; + delete userAttributes[key]; + if (cookies && cookies[mpid]) { + cookies[mpid].ua = userAttributes; + mpInstance._Persistence.savePersistence(cookies, mpid); + } + self.sendUserAttributeChangeEvent(key, null, deletedUAKeyCopy, false, true, this); + mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); + mpInstance._Forwarders.handleForwarderUserAttributes('removeUserAttribute', key, null); + } + }, + /** + * Sets a list of user attributes + * @method setUserAttributeList + * @param {String} key + * @param {Array} value an array of values + */ + // https://go.mparticle.com/work/SQDSDKS-6373 + setUserAttributeList: function setUserAttributeList(key, newValue) { + mpInstance._SessionManager.resetSessionTimer(); + if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) { + mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey); + return; + } + if (!Array.isArray(newValue)) { + mpInstance.Logger.error('The value you passed in to setUserAttributeList must be an array. You passed in a ' + (typeof value === "undefined" ? "undefined" : _typeof$1(value))); + return; + } + var arrayCopy = newValue.slice(); + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList, JSON.stringify({ + key: key, + value: arrayCopy + })); + } else { + var userAttributes = this.getAllUserAttributes(); + var previousUserAttributeValue; + var isNewAttribute; + var userAttributeChange; + var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key); + if (existingProp) { + isNewAttribute = false; + previousUserAttributeValue = userAttributes[existingProp]; + delete userAttributes[existingProp]; + } else { + isNewAttribute = true; + } + userAttributes[key] = arrayCopy; + mpInstance._Store.setUserAttributes(mpid, userAttributes); + + // If the new attributeList length is different than the previous, then there is a change event. + // Loop through new attributes list, see if they are all in the same index as previous user attributes list + // If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value + if (!previousUserAttributeValue || !Array.isArray(previousUserAttributeValue)) { + userAttributeChange = true; + } else if (newValue.length !== previousUserAttributeValue.length) { + userAttributeChange = true; + } else { + for (var i = 0; i < newValue.length; i++) { + if (previousUserAttributeValue[i] !== newValue[i]) { + userAttributeChange = true; + break; + } + } + } + if (userAttributeChange) { + self.sendUserAttributeChangeEvent(key, newValue, previousUserAttributeValue, isNewAttribute, false, this); + } + mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); + mpInstance._Forwarders.handleForwarderUserAttributes('setUserAttribute', key, arrayCopy); + } + }, + /** + * Removes all user attributes + * @method removeAllUserAttributes + */ + removeAllUserAttributes: function removeAllUserAttributes() { + var userAttributes; + mpInstance._SessionManager.resetSessionTimer(); + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes); + } else { + userAttributes = this.getAllUserAttributes(); + mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats); + if (userAttributes) { + for (var prop in userAttributes) { + if (userAttributes.hasOwnProperty(prop)) { + mpInstance._Forwarders.handleForwarderUserAttributes('removeUserAttribute', prop, null); + } + this.removeUserAttribute(prop); + } + } + } + }, + /** + * Returns all user attribute keys that have values that are arrays + * @method getUserAttributesLists + * @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] } + */ + getUserAttributesLists: function getUserAttributesLists() { + var userAttributes, + userAttributesLists = {}; + userAttributes = this.getAllUserAttributes(); + for (var key in userAttributes) { + if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) { + userAttributesLists[key] = userAttributes[key].slice(); + } + } + return userAttributesLists; + }, + /** + * Returns all user attributes + * @method getAllUserAttributes + * @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] } + */ + getAllUserAttributes: function getAllUserAttributes() { + var getUserAttributes = mpInstance._Store.getUserAttributes; + var userAttributesCopy = {}; + var userAttributes = getUserAttributes(mpid); + if (userAttributes) { + for (var prop in userAttributes) { + if (userAttributes.hasOwnProperty(prop)) { + if (Array.isArray(userAttributes[prop])) { + userAttributesCopy[prop] = userAttributes[prop].slice(); + } else { + userAttributesCopy[prop] = userAttributes[prop]; + } + } + } + } + return userAttributesCopy; + }, + /** + * Returns the cart object for the current user + * @method getCart + * @return a cart object + */ + getCart: function getCart() { + mpInstance.Logger.warning('Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases'); + return self.mParticleUserCart(); + }, + /** + * Returns the Consent State stored locally for this user. + * @method getConsentState + * @return a ConsentState object + */ + getConsentState: function getConsentState() { + return mpInstance._Store.getConsentState(mpid); + }, + /** + * Sets the Consent State stored locally for this user. + * @method setConsentState + * @param {Object} consent state + */ + setConsentState: function setConsentState(state) { + mpInstance._Store.setConsentState(mpid, state); + mpInstance._Forwarders.initForwarders(this.getUserIdentities().userIdentities, mpInstance._APIClient.prepareForwardingStats); + mpInstance._CookieSyncManager.attemptCookieSync(this.getMPID()); + }, + isLoggedIn: function isLoggedIn() { + return _isLoggedIn; + }, + getLastSeenTime: function getLastSeenTime() { + return mpInstance._Persistence.getLastSeenTime(mpid); + }, + getFirstSeenTime: function getFirstSeenTime() { + return mpInstance._Persistence.getFirstSeenTime(mpid); + }, + /** + * Get user audiences + * @method getuserAudiences + * @param {Function} [callback] A callback function that is invoked when the user audience request completes + */ + // https://go.mparticle.com/work/SQDSDKS-6436 + getUserAudiences: function getUserAudiences(callback) { + // user audience API is feature flagged + if (!mpInstance._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)) { + mpInstance.Logger.error(ErrorMessages.AudienceAPINotEnabled); + return; + } + if (self.audienceManager === null) { + self.audienceManager = new AudienceManager(mpInstance._Store.SDKConfig.userAudienceUrl, mpInstance._Store.devToken, mpInstance.Logger, mpid); + } + self.audienceManager.sendGetUserAudienceRequest(mpid, callback); + } + }; + }; + + /** + * Invoke these methods on the mParticle.Identity.getCurrentUser().getCart() object. + * Example: mParticle.Identity.getCurrentUser().getCart().add(...); + * @class mParticle.Identity.getCurrentUser().getCart() + * @deprecated + */ + this.mParticleUserCart = function () { + return { + /** + * Adds a cart product to the user cart + * @method add + * @deprecated + */ + add: function add() { + mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().add()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + }, + /** + * Removes a cart product from the current user cart + * @method remove + * @deprecated + */ + remove: function remove() { + mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().remove()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + }, + /** + * Clears the user's cart + * @method clear + * @deprecated + */ + clear: function clear() { + mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().clear()', true, '', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + }, + /** + * Returns all cart products + * @method getCartProducts + * @return {Array} array of cart products + * @deprecated + */ + getCartProducts: function getCartProducts() { + mpInstance.Logger.warning(generateDeprecationMessage('Identity.getCurrentUser().getCart().getCartProducts()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + return []; + } + }; + }; + + // https://go.mparticle.com/work/SQDSDKS-6355 + this.parseIdentityResponse = function (identityResponse, previousMPID, callback, identityApiData, method, knownIdentities, parsingCachedResponse) { + var prevUser = mpInstance.Identity.getUser(previousMPID); + var prevUserMPID = prevUser ? prevUser.getMPID() : null; + var previousUIByName = prevUser ? prevUser.getUserIdentities().userIdentities : {}; + var mpidIsNotInCookies; + var identityApiResult; + var newUser; + var newIdentitiesByType = {}; + mpInstance._Store.identityCallInFlight = false; + try { + var _identityResponse$res, _identityApiResult, _mpInstance$_APIClien; + mpInstance.Logger.verbose('Parsing "' + method + '" identity response from server'); + identityApiResult = (_identityResponse$res = identityResponse.responseText) !== null && _identityResponse$res !== void 0 ? _identityResponse$res : null; + mpInstance._Store.isLoggedIn = ((_identityApiResult = identityApiResult) === null || _identityApiResult === void 0 ? void 0 : _identityApiResult.is_logged_in) || false; + + // https://go.mparticle.com/work/SQDSDKS-6504 + // set currentUser + if (hasMPIDChanged(prevUser, identityApiResult)) { + mpInstance._Store.mpid = identityApiResult.mpid; + if (prevUser) { + // https://go.mparticle.com/work/SQDSDKS-6329 + mpInstance._Persistence.setLastSeenTime(previousMPID); + } + mpidIsNotInCookies = !mpInstance._Persistence.getFirstSeenTime(identityApiResult.mpid); + + // https://go.mparticle.com/work/SQDSDKS-6329 + mpInstance._Persistence.setFirstSeenTime(identityApiResult.mpid); + } + if (identityResponse.status === HTTP_OK) { + if (getFeatureFlag(CacheIdentity)) { + cacheOrClearIdCache(method, knownIdentities, self.idCache, identityResponse, parsingCachedResponse); + } + var incomingUser = self.IdentityAPI.getUser(identityApiResult.mpid); + var incomingUIByName = incomingUser ? incomingUser.getUserIdentities().userIdentities : {}; + if (method === Modify$1) { + newIdentitiesByType = mpInstance._Identity.IdentityRequest.combineUserIdentities(previousUIByName, identityApiData.userIdentities); + mpInstance._Store.setUserIdentities(previousMPID, newIdentitiesByType); + } else { + // https://go.mparticle.com/work/SQDSDKS-6356 + //this covers an edge case where, users stored before "firstSeenTime" was introduced + //will not have a value for "fst" until the current MPID changes, and in some cases, + //the current MPID will never change + if (method === Identify && prevUser && identityApiResult.mpid === prevUserMPID) { + // https://go.mparticle.com/work/SQDSDKS-6329 + mpInstance._Persistence.setFirstSeenTime(identityApiResult.mpid); + } + mpInstance._Store.addMpidToSessionHistory(identityApiResult.mpid, previousMPID); + mpInstance._CookieSyncManager.attemptCookieSync(identityApiResult.mpid, mpidIsNotInCookies); + mpInstance._Persistence.swapCurrentUser(previousMPID, identityApiResult.mpid, mpInstance._Store.currentSessionMPIDs); + if (identityApiData && !isEmpty(identityApiData.userIdentities)) { + newIdentitiesByType = self.IdentityRequest.combineUserIdentities(incomingUIByName, identityApiData.userIdentities); + } + + // https://go.mparticle.com/work/SQDSDKS-6041 + mpInstance._Store.setUserIdentities(identityApiResult.mpid, newIdentitiesByType); + mpInstance._Persistence.update(); + mpInstance._Store.syncPersistenceData(); + mpInstance._Persistence.findPrevCookiesBasedOnUI(identityApiData); + + // https://go.mparticle.com/work/SQDSDKS-6357 + mpInstance._Store.context = identityApiResult.context || mpInstance._Store.context; + } + newUser = mpInstance.Identity.getCurrentUser(); + + // https://go.mparticle.com/work/SQDSDKS-6359 + tryOnUserAlias(prevUser, newUser, identityApiData, mpInstance.Logger); + var persistence = mpInstance._Persistence.getPersistence(); + if (newUser) { + mpInstance._Persistence.storeDataInMemory(persistence, newUser.getMPID()); + self.reinitForwardersOnUserChange(prevUser, newUser); + self.setForwarderCallbacks(newUser, method); + } + var newIdentitiesByName = IdentityType.getNewIdentitiesByName(newIdentitiesByType); + var uiByName = method === Modify$1 ? previousUIByName : incomingUIByName; + + // https://go.mparticle.com/work/SQDSDKS-6501 + self.sendUserIdentityChangeEvent(newIdentitiesByName, method, identityApiResult.mpid, uiByName); + } + if (callback) { + var callbackCode = identityResponse.status === 0 ? HTTPCodes$2.noHttpCoverage : identityResponse.status; + mpInstance._Helpers.invokeCallback(callback, callbackCode, identityApiResult || null, newUser); + } else if (identityApiResult && !isEmpty(identityApiResult.errors)) { + // https://go.mparticle.com/work/SQDSDKS-6500 + mpInstance.Logger.error('Received HTTP response code of ' + identityResponse.status + ' - ' + identityApiResult.errors[0].message); + } + mpInstance.Logger.verbose('Successfully parsed Identity Response'); + + // https://go.mparticle.com/work/SQDSDKS-6654 + (_mpInstance$_APIClien = mpInstance._APIClient) === null || _mpInstance$_APIClien === void 0 || _mpInstance$_APIClien.processQueuedEvents(); + } catch (e) { + if (callback) { + mpInstance._Helpers.invokeCallback(callback, identityResponse.status, identityApiResult || null); + } + mpInstance.Logger.error('Error parsing JSON response from Identity server: ' + e); + } + mpInstance._Store.isInitialized = true; + mpInstance._RoktManager.onIdentityComplete(); + mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue); + }; + + // send a user identity change request on identify, login, logout, modify when any values change. + // compare what identities exist vs what is previously was for the specific user if they were in memory before. + // if it's the first time the user is logging in, send a user identity change request with + this.sendUserIdentityChangeEvent = function (newUserIdentities, method, mpid, prevUserIdentities) { + if (!mpid) { + // https://go.mparticle.com/work/SQDSDKS-6501 + if (method !== Modify$1) { + return; + } + } + + // https://go.mparticle.com/work/SQDSDKS-6354 + var currentUserInMemory = this.IdentityAPI.getUser(mpid); + for (var identityType in newUserIdentities) { + // Verifies a change actually happened + if (prevUserIdentities[identityType] !== newUserIdentities[identityType]) { + var _mpInstance$_APIClien2; + // If a new identity type was introduced when the identity changes + // we need to notify the server so that the user profile is updated in + // the mParticle UI. + var isNewUserIdentityType = !prevUserIdentities[identityType]; + var userIdentityChangeEvent = self.createUserIdentityChange(identityType, newUserIdentities[identityType], prevUserIdentities[identityType], isNewUserIdentityType, currentUserInMemory); + (_mpInstance$_APIClien2 = mpInstance._APIClient) === null || _mpInstance$_APIClien2 === void 0 || _mpInstance$_APIClien2.sendEventToServer(userIdentityChangeEvent); + } + } + }; + this.createUserIdentityChange = function (identityType, newIdentity, oldIdentity, isIdentityTypeNewToBatch, userInMemory) { + var userIdentityChangeEvent; + + // https://go.mparticle.com/work/SQDSDKS-6439 + userIdentityChangeEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.UserIdentityChange, + userIdentityChanges: { + New: { + IdentityType: identityType, + Identity: newIdentity, + CreatedThisBatch: isIdentityTypeNewToBatch + }, + Old: { + IdentityType: identityType, + Identity: oldIdentity, + CreatedThisBatch: false + } + }, + userInMemory: userInMemory + }); + return userIdentityChangeEvent; + }; + this.sendUserAttributeChangeEvent = function (attributeKey, newUserAttributeValue, previousUserAttributeValue, isNewAttribute, deleted, user) { + var userAttributeChangeEvent = self.createUserAttributeChange(attributeKey, newUserAttributeValue, previousUserAttributeValue, isNewAttribute, deleted, user); + if (userAttributeChangeEvent) { + var _mpInstance$_APIClien3; + (_mpInstance$_APIClien3 = mpInstance._APIClient) === null || _mpInstance$_APIClien3 === void 0 || _mpInstance$_APIClien3.sendEventToServer(userAttributeChangeEvent); + } + }; + this.createUserAttributeChange = function (key, newValue, previousUserAttributeValue, isNewAttribute, deleted, user) { + if (typeof previousUserAttributeValue === 'undefined') { + previousUserAttributeValue = null; + } + var userAttributeChangeEvent; + if (newValue !== previousUserAttributeValue) { + // https://go.mparticle.com/work/SQDSDKS-6439 + userAttributeChangeEvent = mpInstance._ServerModel.createEventObject({ + messageType: Types.MessageType.UserAttributeChange, + userAttributeChanges: { + UserAttributeName: key, + New: newValue, + Old: previousUserAttributeValue, + Deleted: deleted, + IsNewAttribute: isNewAttribute + } + }, user); + } + return userAttributeChangeEvent; + }; + this.reinitForwardersOnUserChange = function (prevUser, newUser) { + if (hasMPIDAndUserLoginChanged(prevUser, newUser)) { + var _mpInstance$_Forwarde; + (_mpInstance$_Forwarde = mpInstance._Forwarders) === null || _mpInstance$_Forwarde === void 0 || _mpInstance$_Forwarde.initForwarders(newUser.getUserIdentities().userIdentities, mpInstance._APIClient.prepareForwardingStats); + } + }; + this.setForwarderCallbacks = function (user, method) { + var _mpInstance$_Forwarde2, _mpInstance$_Forwarde3, _mpInstance$_Forwarde4; + // https://go.mparticle.com/work/SQDSDKS-6036 + (_mpInstance$_Forwarde2 = mpInstance._Forwarders) === null || _mpInstance$_Forwarde2 === void 0 || _mpInstance$_Forwarde2.setForwarderUserIdentities(user.getUserIdentities().userIdentities); + (_mpInstance$_Forwarde3 = mpInstance._Forwarders) === null || _mpInstance$_Forwarde3 === void 0 || _mpInstance$_Forwarde3.setForwarderOnIdentityComplete(user, method); + (_mpInstance$_Forwarde4 = mpInstance._Forwarders) === null || _mpInstance$_Forwarde4 === void 0 || _mpInstance$_Forwarde4.setForwarderOnUserIdentified(user); + }; + } + + // https://go.mparticle.com/work/SQDSDKS-6359 + function tryOnUserAlias(previousUser, newUser, identityApiData, logger) { + if (identityApiData && identityApiData.onUserAlias && isFunction(identityApiData.onUserAlias)) { + try { + logger.warning(generateDeprecationMessage('onUserAlias')); + identityApiData.onUserAlias(previousUser, newUser); + } catch (e) { + logger.error('There was an error with your onUserAlias function - ' + e); + } + } + } + + var CCPAPurpose = Constants.CCPAPurpose; + function Consent(mpInstance) { + var self = this; + // this function is called when consent is required to + // determine if a cookie sync should happen, or a + // forwarder should be initialized + this.isEnabledForUserConsent = function (consentRules, user) { + if (!consentRules || !consentRules.values || !consentRules.values.length) { + return true; + } + if (!user) { + return false; + } + var purposeHashes = {}; + var consentState = user.getConsentState(); + var purposeHash; + if (consentState) { + // the server hashes consent purposes in the following way: + // GDPR - '1' + purpose name + // CCPA - '2data_sale_opt_out' (there is only 1 purpose of data_sale_opt_out for CCPA) + var GDPRConsentHashPrefix = '1'; + var CCPAHashPrefix = '2'; + var gdprConsentState = consentState.getGDPRConsentState(); + if (gdprConsentState) { + for (var purpose in gdprConsentState) { + if (gdprConsentState.hasOwnProperty(purpose)) { + purposeHash = KitFilterHelper.hashConsentPurposeConditionalForwarding(GDPRConsentHashPrefix, purpose); + purposeHashes[purposeHash] = gdprConsentState[purpose].Consented; + } + } + } + var CCPAConsentState = consentState.getCCPAConsentState(); + if (CCPAConsentState) { + purposeHash = KitFilterHelper.hashConsentPurposeConditionalForwarding(CCPAHashPrefix, CCPAPurpose); + purposeHashes[purposeHash] = CCPAConsentState.Consented; + } + } + var isMatch = consentRules.values.some(function (consentRule) { + var consentPurposeHash = consentRule.consentPurpose; + var hasConsented = consentRule.hasConsented; + if (purposeHashes.hasOwnProperty(consentPurposeHash)) { + return purposeHashes[consentPurposeHash] === hasConsented; + } + return false; + }); + return consentRules.includeOnMatch === isMatch; + }; + this.createPrivacyConsent = function (consented, timestamp, consentDocument, location, hardwareId) { + if (typeof consented !== 'boolean') { + mpInstance.Logger.error('Consented boolean is required when constructing a Consent object.'); + return null; + } + if (timestamp && isNaN(timestamp)) { + mpInstance.Logger.error('Timestamp must be a valid number when constructing a Consent object.'); + return null; + } + if (consentDocument && typeof consentDocument !== 'string') { + mpInstance.Logger.error('Document must be a valid string when constructing a Consent object.'); + return null; + } + if (location && typeof location !== 'string') { + mpInstance.Logger.error('Location must be a valid string when constructing a Consent object.'); + return null; + } + if (hardwareId && typeof hardwareId !== 'string') { + mpInstance.Logger.error('Hardware ID must be a valid string when constructing a Consent object.'); + return null; + } + return { + Consented: consented, + Timestamp: timestamp || Date.now(), + ConsentDocument: consentDocument, + Location: location, + HardwareId: hardwareId + }; + }; + this.ConsentSerialization = { + toMinifiedJsonObject: function toMinifiedJsonObject(state) { + var _a; + var jsonObject = {}; + if (state) { + var gdprConsentState = state.getGDPRConsentState(); + if (gdprConsentState) { + jsonObject.gdpr = {}; + for (var purpose in gdprConsentState) { + if (gdprConsentState.hasOwnProperty(purpose)) { + var gdprConsent = gdprConsentState[purpose]; + jsonObject.gdpr[purpose] = {}; + if (typeof gdprConsent.Consented === 'boolean') { + jsonObject.gdpr[purpose].c = gdprConsent.Consented; + } + if (typeof gdprConsent.Timestamp === 'number') { + jsonObject.gdpr[purpose].ts = gdprConsent.Timestamp; + } + if (typeof gdprConsent.ConsentDocument === 'string') { + jsonObject.gdpr[purpose].d = gdprConsent.ConsentDocument; + } + if (typeof gdprConsent.Location === 'string') { + jsonObject.gdpr[purpose].l = gdprConsent.Location; + } + if (typeof gdprConsent.HardwareId === 'string') { + jsonObject.gdpr[purpose].h = gdprConsent.HardwareId; + } + } + } + } + var ccpaConsentState = state.getCCPAConsentState(); + if (ccpaConsentState) { + jsonObject.ccpa = (_a = {}, _a[CCPAPurpose] = {}, _a); + if (typeof ccpaConsentState.Consented === 'boolean') { + jsonObject.ccpa[CCPAPurpose].c = ccpaConsentState.Consented; + } + if (typeof ccpaConsentState.Timestamp === 'number') { + jsonObject.ccpa[CCPAPurpose].ts = ccpaConsentState.Timestamp; + } + if (typeof ccpaConsentState.ConsentDocument === 'string') { + jsonObject.ccpa[CCPAPurpose].d = ccpaConsentState.ConsentDocument; + } + if (typeof ccpaConsentState.Location === 'string') { + jsonObject.ccpa[CCPAPurpose].l = ccpaConsentState.Location; + } + if (typeof ccpaConsentState.HardwareId === 'string') { + jsonObject.ccpa[CCPAPurpose].h = ccpaConsentState.HardwareId; + } + } + } + return jsonObject; + }, + fromMinifiedJsonObject: function fromMinifiedJsonObject(json) { + var state = self.createConsentState(); + if (json.gdpr) { + for (var purpose in json.gdpr) { + if (json.gdpr.hasOwnProperty(purpose)) { + var gdprConsent = self.createPrivacyConsent(json.gdpr[purpose].c, json.gdpr[purpose].ts, json.gdpr[purpose].d, json.gdpr[purpose].l, json.gdpr[purpose].h); + state.addGDPRConsentState(purpose, gdprConsent); + } + } + } + if (json.ccpa) { + if (json.ccpa.hasOwnProperty(CCPAPurpose)) { + var ccpaConsent = self.createPrivacyConsent(json.ccpa[CCPAPurpose].c, json.ccpa[CCPAPurpose].ts, json.ccpa[CCPAPurpose].d, json.ccpa[CCPAPurpose].l, json.ccpa[CCPAPurpose].h); + state.setCCPAConsentState(ccpaConsent); + } + } + return state; + } + }; + // TODO: Refactor this method into a constructor + this.createConsentState = function (consentState) { + var gdpr = {}; + var ccpa = {}; + if (consentState) { + var consentStateCopy = self.createConsentState(); + consentStateCopy.setGDPRConsentState(consentState.getGDPRConsentState()); + consentStateCopy.setCCPAConsentState(consentState.getCCPAConsentState()); + // TODO: Remove casting once `removeCCPAState` is removed; + return consentStateCopy; + } + function canonicalizeForDeduplication(purpose) { + if (typeof purpose !== 'string') { + return null; + } + var trimmedPurpose = purpose.trim(); + if (!trimmedPurpose.length) { + return null; + } + return trimmedPurpose.toLowerCase(); + } + /** + * Invoke these methods on a consent state object. + *

+ * Usage: const consent = mParticle.Consent.createConsentState() + *
+ * consent.setGDPRCoonsentState() + * + * @class Consent + */ + /** + * Add a GDPR Consent State to the consent state object + * + * @method addGDPRConsentState + * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data + * @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...) + */ + function addGDPRConsentState(purpose, gdprConsent) { + var normalizedPurpose = canonicalizeForDeduplication(purpose); + if (!normalizedPurpose) { + mpInstance.Logger.error('Purpose must be a string.'); + return this; + } + if (!isObject(gdprConsent)) { + mpInstance.Logger.error('Invoked with a bad or empty consent object.'); + return this; + } + var gdprConsentCopy = self.createPrivacyConsent(gdprConsent.Consented, gdprConsent.Timestamp, gdprConsent.ConsentDocument, gdprConsent.Location, gdprConsent.HardwareId); + if (gdprConsentCopy) { + gdpr[normalizedPurpose] = gdprConsentCopy; + } + return this; + } + function setGDPRConsentState(gdprConsentState) { + if (!gdprConsentState) { + gdpr = {}; + } else if (isObject(gdprConsentState)) { + gdpr = {}; + for (var purpose in gdprConsentState) { + if (gdprConsentState.hasOwnProperty(purpose)) { + this.addGDPRConsentState(purpose, gdprConsentState[purpose]); + } + } + } + return this; + } + /** + * Remove a GDPR Consent State to the consent state object + * + * @method removeGDPRConsentState + * @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data + */ + function removeGDPRConsentState(purpose) { + var normalizedPurpose = canonicalizeForDeduplication(purpose); + if (!normalizedPurpose) { + return this; + } + delete gdpr[normalizedPurpose]; + return this; + } + /** + * Gets the GDPR Consent State + * + * @method getGDPRConsentState + * @return {Object} A GDPR Consent State + */ + function getGDPRConsentState() { + return Object.assign({}, gdpr); + } + /** + * Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out') + * + * @method setCCPAConsentState + * @param {Object} ccpaConsent CCPA Consent State + */ + function setCCPAConsentState(ccpaConsent) { + if (!isObject(ccpaConsent)) { + mpInstance.Logger.error('Invoked with a bad or empty CCPA consent object.'); + return this; + } + var ccpaConsentCopy = self.createPrivacyConsent(ccpaConsent.Consented, ccpaConsent.Timestamp, ccpaConsent.ConsentDocument, ccpaConsent.Location, ccpaConsent.HardwareId); + if (ccpaConsentCopy) { + ccpa[CCPAPurpose] = ccpaConsentCopy; + } + return this; + } + /** + * Gets the CCPA Consent State + * + * @method getCCPAConsentStatensent + * @return {Object} A CCPA Consent State + */ + function getCCPAConsentState() { + return ccpa[CCPAPurpose]; + } + /** + * Removes CCPA from the consent state object + * + * @method removeCCPAConsentState + */ + function removeCCPAConsentState() { + delete ccpa[CCPAPurpose]; + return this; + } + // TODO: Can we remove this? It is deprecated. + function removeCCPAState() { + mpInstance.Logger.warning('removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead'); + // @ts-ignore + return removeCCPAConsentState(); + } + return { + setGDPRConsentState: setGDPRConsentState, + addGDPRConsentState: addGDPRConsentState, + setCCPAConsentState: setCCPAConsentState, + getCCPAConsentState: getCCPAConsentState, + getGDPRConsentState: getGDPRConsentState, + removeGDPRConsentState: removeGDPRConsentState, + removeCCPAState: removeCCPAState, + removeCCPAConsentState: removeCCPAConsentState + }; + }; + } + + /* + TODO: Including this as a workaround because attempting to import it from + @mparticle/data-planning-models directly creates a build error. + */ + var DataPlanMatchType = { + ScreenView: "screen_view", + CustomEvent: "custom_event", + Commerce: "commerce", + UserAttributes: "user_attributes", + UserIdentities: "user_identities", + ProductAction: "product_action", + PromotionAction: "promotion_action", + ProductImpression: "product_impression" + }; + /* + inspiration from https://github.com/mParticle/data-planning-node/blob/master/src/data_planning/data_plan_event_validator.ts + but modified to only include commerce events, custom events, screen views, and removes validation + + The purpose of the KitBlocker class is to parse a data plan and determine what events, event/user/product attributes, and user identities should be blocked from downstream forwarders. + + KitBlocker is instantiated with a data plan on mParticle initialization. KitBlocker.kitBlockingEnabled is false if no data plan is passed. + It parses the data plan by creating a `dataPlanMatchLookups` object in the following manner: + 1. For all events and user attributes/identities, it generates a `matchKey` in the shape of `typeOfEvent:eventType:nameOfEvent` + a. The matchKeys' value will return `true` if additionalProperties for the custom attributes/identities is `true`, otherwise it will return an object of planned attribute/identities + 2. For commerce events, after step 1 and 1a, a second `matchKey` is included that appends `Products`. This is used to determine productAttributes blocked + + When an event is logged in mParticle, it is sent to our server and then calls `KitBlocker.createBlockedEvent` before passing the event to each forwarder. + If the event is blocked, it will not send to the forwarder. If the event is not blocked, event/user/product attributes and user identities will be removed from the returned event if blocked. + */ + var KitBlocker = /** @class */function () { + function KitBlocker(dataPlan, mpInstance) { + var _this = this; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; + this.dataPlanMatchLookups = {}; + this.blockEvents = false; + this.blockEventAttributes = false; + this.blockUserAttributes = false; + this.blockUserIdentities = false; + this.kitBlockingEnabled = false; + // if data plan is not requested, the data plan is {document: null} + if (dataPlan && !dataPlan.document) { + this.kitBlockingEnabled = false; + return; + } + this.kitBlockingEnabled = true; + this.mpInstance = mpInstance; + this.blockEvents = (_c = (_b = (_a = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _a === void 0 ? void 0 : _a.dtpn) === null || _b === void 0 ? void 0 : _b.blok) === null || _c === void 0 ? void 0 : _c.ev; + this.blockEventAttributes = (_f = (_e = (_d = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _d === void 0 ? void 0 : _d.dtpn) === null || _e === void 0 ? void 0 : _e.blok) === null || _f === void 0 ? void 0 : _f.ea; + this.blockUserAttributes = (_j = (_h = (_g = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _g === void 0 ? void 0 : _g.dtpn) === null || _h === void 0 ? void 0 : _h.blok) === null || _j === void 0 ? void 0 : _j.ua; + this.blockUserIdentities = (_m = (_l = (_k = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _k === void 0 ? void 0 : _k.dtpn) === null || _l === void 0 ? void 0 : _l.blok) === null || _m === void 0 ? void 0 : _m.id; + var versionDocument = (_q = (_p = (_o = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _o === void 0 ? void 0 : _o.dtpn) === null || _p === void 0 ? void 0 : _p.vers) === null || _q === void 0 ? void 0 : _q.version_document; + var dataPoints = versionDocument === null || versionDocument === void 0 ? void 0 : versionDocument.data_points; + if (versionDocument) { + try { + if ((dataPoints === null || dataPoints === void 0 ? void 0 : dataPoints.length) > 0) { + dataPoints.forEach(function (point) { + return _this.addToMatchLookups(point); + }); + } + } catch (e) { + this.mpInstance.Logger.error('There was an issue with the data plan: ' + e); + } + } + } + KitBlocker.prototype.addToMatchLookups = function (point) { + var _a, _b, _c; + if (!point.match || !point.validator) { + this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(point)); + return; + } + // match keys for non product custom attribute related data points + var matchKey = this.generateMatchKey(point.match); + var properties = this.getPlannedProperties(point.match.type, point.validator); + this.dataPlanMatchLookups[matchKey] = properties; + // match keys for product custom attribute related data points + if (((_a = point === null || point === void 0 ? void 0 : point.match) === null || _a === void 0 ? void 0 : _a.type) === DataPlanMatchType.ProductImpression || ((_b = point === null || point === void 0 ? void 0 : point.match) === null || _b === void 0 ? void 0 : _b.type) === DataPlanMatchType.ProductAction || ((_c = point === null || point === void 0 ? void 0 : point.match) === null || _c === void 0 ? void 0 : _c.type) === DataPlanMatchType.PromotionAction) { + matchKey = this.generateProductAttributeMatchKey(point.match); + properties = this.getProductProperties(point.match.type, point.validator); + this.dataPlanMatchLookups[matchKey] = properties; + } + }; + KitBlocker.prototype.generateMatchKey = function (match) { + var criteria = match.criteria || ''; + switch (match.type) { + case DataPlanMatchType.CustomEvent: + var customEventCriteria = criteria; + return [DataPlanMatchType.CustomEvent, customEventCriteria.custom_event_type, customEventCriteria.event_name].join(':'); + case DataPlanMatchType.ScreenView: + var screenViewCriteria = criteria; + return [DataPlanMatchType.ScreenView, '', screenViewCriteria.screen_name].join(':'); + case DataPlanMatchType.ProductAction: + var productActionMatch = criteria; + return [match.type, productActionMatch.action].join(':'); + case DataPlanMatchType.PromotionAction: + var promoActionMatch = criteria; + return [match.type, promoActionMatch.action].join(':'); + case DataPlanMatchType.ProductImpression: + var productImpressionActionMatch = criteria; + return [match.type, productImpressionActionMatch.action].join(':'); + case DataPlanMatchType.UserIdentities: + case DataPlanMatchType.UserAttributes: + return [match.type].join(':'); + default: + return null; + } + }; + KitBlocker.prototype.generateProductAttributeMatchKey = function (match) { + var criteria = match.criteria || ''; + switch (match.type) { + case DataPlanMatchType.ProductAction: + var productActionMatch = criteria; + return [match.type, productActionMatch.action, 'ProductAttributes'].join(':'); + case DataPlanMatchType.PromotionAction: + var promoActionMatch = criteria; + return [match.type, promoActionMatch.action, 'ProductAttributes'].join(':'); + case DataPlanMatchType.ProductImpression: + return [match.type, 'ProductAttributes'].join(':'); + default: + return null; + } + }; + KitBlocker.prototype.getPlannedProperties = function (type, validator) { + var _a, _b, _c, _d, _e, _f, _g, _h; + var customAttributes; + var userAdditionalProperties; + switch (type) { + case DataPlanMatchType.CustomEvent: + case DataPlanMatchType.ScreenView: + case DataPlanMatchType.ProductAction: + case DataPlanMatchType.PromotionAction: + case DataPlanMatchType.ProductImpression: + customAttributes = (_d = (_c = (_b = (_a = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.custom_attributes; + if (customAttributes) { + if (customAttributes.additionalProperties === true || customAttributes.additionalProperties === undefined) { + return true; + } else { + var properties = {}; + for (var _i = 0, _j = Object.keys(customAttributes.properties); _i < _j.length; _i++) { + var property = _j[_i]; + properties[property] = true; + } + return properties; + } + } else { + if (((_g = (_f = (_e = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _e === void 0 ? void 0 : _e.properties) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.additionalProperties) === false) { + return {}; + } else { + return true; + } + } + case DataPlanMatchType.UserAttributes: + case DataPlanMatchType.UserIdentities: + userAdditionalProperties = (_h = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _h === void 0 ? void 0 : _h.additionalProperties; + if (userAdditionalProperties === true || userAdditionalProperties === undefined) { + return true; + } else { + var properties = {}; + var userProperties = validator.definition.properties; + for (var _k = 0, _l = Object.keys(userProperties); _k < _l.length; _k++) { + var property = _l[_k]; + properties[property] = true; + } + return properties; + } + default: + return null; + } + }; + KitBlocker.prototype.getProductProperties = function (type, validator) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u; + var productCustomAttributes; + switch (type) { + case DataPlanMatchType.ProductImpression: + productCustomAttributes = (_k = (_j = (_h = (_g = (_f = (_e = (_d = (_c = (_b = (_a = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.product_impressions) === null || _e === void 0 ? void 0 : _e.items) === null || _f === void 0 ? void 0 : _f.properties) === null || _g === void 0 ? void 0 : _g.products) === null || _h === void 0 ? void 0 : _h.items) === null || _j === void 0 ? void 0 : _j.properties) === null || _k === void 0 ? void 0 : _k.custom_attributes; + //product item attributes + if ((productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.additionalProperties) === false) { + var properties = {}; + for (var _i = 0, _v = Object.keys(productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.properties); _i < _v.length; _i++) { + var property = _v[_i]; + properties[property] = true; + } + return properties; + } + return true; + case DataPlanMatchType.ProductAction: + case DataPlanMatchType.PromotionAction: + productCustomAttributes = (_u = (_t = (_s = (_r = (_q = (_p = (_o = (_m = (_l = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _l === void 0 ? void 0 : _l.properties) === null || _m === void 0 ? void 0 : _m.data) === null || _o === void 0 ? void 0 : _o.properties) === null || _p === void 0 ? void 0 : _p.product_action) === null || _q === void 0 ? void 0 : _q.properties) === null || _r === void 0 ? void 0 : _r.products) === null || _s === void 0 ? void 0 : _s.items) === null || _t === void 0 ? void 0 : _t.properties) === null || _u === void 0 ? void 0 : _u.custom_attributes; + //product item attributes + if (productCustomAttributes) { + if (productCustomAttributes.additionalProperties === false) { + var properties = {}; + for (var _w = 0, _x = Object.keys(productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.properties); _w < _x.length; _w++) { + var property = _x[_w]; + properties[property] = true; + } + return properties; + } + } + return true; + default: + return null; + } + }; + KitBlocker.prototype.getMatchKey = function (eventToMatch) { + switch (eventToMatch.event_type) { + case dist.EventTypeEnum.screenView: + var screenViewEvent = eventToMatch; + if (screenViewEvent.data) { + return ['screen_view', '', screenViewEvent.data.screen_name].join(':'); + } + return null; + case dist.EventTypeEnum.commerceEvent: + var commerceEvent = eventToMatch; + var matchKey = []; + if (commerceEvent && commerceEvent.data) { + var _a = commerceEvent.data, + product_action = _a.product_action, + product_impressions = _a.product_impressions, + promotion_action = _a.promotion_action; + if (product_action) { + matchKey.push(DataPlanMatchType.ProductAction); + matchKey.push(product_action.action); + } else if (promotion_action) { + matchKey.push(DataPlanMatchType.PromotionAction); + matchKey.push(promotion_action.action); + } else if (product_impressions) { + matchKey.push(DataPlanMatchType.ProductImpression); + } + } + return matchKey.join(':'); + case dist.EventTypeEnum.customEvent: + var customEvent = eventToMatch; + if (customEvent.data) { + return ['custom_event', customEvent.data.custom_event_type, customEvent.data.event_name].join(':'); + } + return null; + default: + return null; + } + }; + KitBlocker.prototype.getProductAttributeMatchKey = function (eventToMatch) { + switch (eventToMatch.event_type) { + case dist.EventTypeEnum.commerceEvent: + var commerceEvent = eventToMatch; + var matchKey = []; + var _a = commerceEvent.data, + product_action = _a.product_action, + product_impressions = _a.product_impressions, + promotion_action = _a.promotion_action; + if (product_action) { + matchKey.push(DataPlanMatchType.ProductAction); + matchKey.push(product_action.action); + matchKey.push('ProductAttributes'); + } else if (promotion_action) { + matchKey.push(DataPlanMatchType.PromotionAction); + matchKey.push(promotion_action.action); + matchKey.push('ProductAttributes'); + } else if (product_impressions) { + matchKey.push(DataPlanMatchType.ProductImpression); + matchKey.push('ProductAttributes'); + } + return matchKey.join(':'); + default: + return null; + } + }; + KitBlocker.prototype.createBlockedEvent = function (event) { + /* + return a transformed event based on event/event attributes, + then product attributes if applicable, then user attributes, + then the user identities + */ + try { + if (event) { + event = this.transformEventAndEventAttributes(event); + } + if (event && event.EventDataType === Types.MessageType.Commerce) { + event = this.transformProductAttributes(event); + } + if (event) { + event = this.transformUserAttributes(event); + event = this.transformUserIdentities(event); + } + return event; + } catch (e) { + return event; + } + }; + KitBlocker.prototype.transformEventAndEventAttributes = function (event) { + var clonedEvent = __assign({}, event); + var baseEvent = convertEvent(clonedEvent); + var matchKey = this.getMatchKey(baseEvent); + var matchedEvent = this.dataPlanMatchLookups[matchKey]; + if (this.blockEvents) { + /* + If the event is not planned, it doesn't exist in dataPlanMatchLookups + and should be blocked (return null to not send anything to forwarders) + */ + if (!matchedEvent) { + return null; + } + } + if (this.blockEventAttributes) { + /* + matchedEvent is set to `true` if additionalProperties is `true` + otherwise, delete attributes that exist on event.EventAttributes + that aren't on + */ + if (matchedEvent === true) { + return clonedEvent; + } + if (matchedEvent) { + for (var _i = 0, _a = Object.keys(clonedEvent.EventAttributes); _i < _a.length; _i++) { + var key = _a[_i]; + if (!matchedEvent[key]) { + delete clonedEvent.EventAttributes[key]; + } + } + return clonedEvent; + } else { + return clonedEvent; + } + } + return clonedEvent; + }; + KitBlocker.prototype.transformProductAttributes = function (event) { + var _a; + var clonedEvent = __assign({}, event); + var baseEvent = convertEvent(clonedEvent); + var matchKey = this.getProductAttributeMatchKey(baseEvent); + var matchedEvent = this.dataPlanMatchLookups[matchKey]; + function removeAttribute(matchedEvent, productList) { + productList.forEach(function (product) { + for (var _i = 0, _a = Object.keys(product.Attributes); _i < _a.length; _i++) { + var productKey = _a[_i]; + if (!matchedEvent[productKey]) { + delete product.Attributes[productKey]; + } + } + }); + } + if (this.blockEvents) { + /* + If the event is not planned, it doesn't exist in dataPlanMatchLookups + and should be blocked (return null to not send anything to forwarders) + */ + if (!matchedEvent) { + return null; + } + } + if (this.blockEventAttributes) { + /* + matchedEvent is set to `true` if additionalProperties is `true` + otherwise, delete attributes that exist on event.EventAttributes + that aren't on + */ + if (matchedEvent === true) { + return clonedEvent; + } + if (matchedEvent) { + switch (event.EventCategory) { + case Types.CommerceEventType.ProductImpression: + clonedEvent.ProductImpressions.forEach(function (impression) { + removeAttribute(matchedEvent, impression === null || impression === void 0 ? void 0 : impression.ProductList); + }); + break; + case Types.CommerceEventType.ProductPurchase: + removeAttribute(matchedEvent, (_a = clonedEvent.ProductAction) === null || _a === void 0 ? void 0 : _a.ProductList); + break; + default: + this.mpInstance.Logger.warning('Product Not Supported '); + } + return clonedEvent; + } else { + return clonedEvent; + } + } + return clonedEvent; + }; + KitBlocker.prototype.transformUserAttributes = function (event) { + var clonedEvent = __assign({}, event); + if (this.blockUserAttributes) { + /* + If the user attribute is not found in the matchedAttributes + then remove it from event.UserAttributes as it is blocked + */ + var matchedAttributes = this.dataPlanMatchLookups['user_attributes']; + if (this.mpInstance._Helpers.isObject(matchedAttributes)) { + for (var _i = 0, _a = Object.keys(clonedEvent.UserAttributes); _i < _a.length; _i++) { + var ua = _a[_i]; + if (!matchedAttributes[ua]) { + delete clonedEvent.UserAttributes[ua]; + } + } + } + } + return clonedEvent; + }; + KitBlocker.prototype.isAttributeKeyBlocked = function (key) { + /* used when an attribute is added to the user */ + if (!this.blockUserAttributes) { + return false; + } + var matchedAttributes = this.dataPlanMatchLookups['user_attributes']; + // When additionalProperties is set to true, matchedAttributes + // will be a boolean, otherwise it will return an object + if (typeof matchedAttributes === 'boolean' && matchedAttributes) { + return false; + } + if (_typeof$1(matchedAttributes) === "object") { + if (matchedAttributes[key] === true) { + return false; + } else { + return true; + } + } + // When "Block unplanned user attributes" is enabled and "Allow unplanned user + // attributes" is also enabled in the UI, allowing unplanned user attributes will be prioritized + return false; + }; + KitBlocker.prototype.isIdentityBlocked = function (key) { + /* used when an attribute is added to the user */ + if (!this.blockUserIdentities) { + return false; + } + if (this.blockUserIdentities) { + var matchedIdentities = this.dataPlanMatchLookups['user_identities']; + if (matchedIdentities === true) { + return false; + } + if (!matchedIdentities[key]) { + return true; + } + } else { + return false; + } + return false; + }; + KitBlocker.prototype.transformUserIdentities = function (event) { + var _this = this; + var _a; + /* + If the user identity is not found in matchedIdentities + then remove it from event.UserIdentities as it is blocked. + event.UserIdentities is of type [{Identity: 'id1', Type: 7}, ...] + and so to compare properly in matchedIdentities, each Type needs + to be converted to an identityName + */ + var clonedEvent = __assign({}, event); + if (this.blockUserIdentities) { + var matchedIdentities_1 = this.dataPlanMatchLookups['user_identities']; + if (this.mpInstance._Helpers.isObject(matchedIdentities_1)) { + if ((_a = clonedEvent === null || clonedEvent === void 0 ? void 0 : clonedEvent.UserIdentities) === null || _a === void 0 ? void 0 : _a.length) { + clonedEvent.UserIdentities.forEach(function (uiByType, i) { + var identityName = Types.IdentityType.getIdentityName(_this.mpInstance._Helpers.parseNumber(uiByType.Type)); + if (!matchedIdentities_1[identityName]) { + clonedEvent.UserIdentities.splice(i, 1); + } + }); + } + } + } + return clonedEvent; + }; + return KitBlocker; + }(); + + var buildUrl = function buildUrl(configUrl, apiKey, dataPlanConfig, isDevelopmentMode) { + var url = configUrl + apiKey + '/config'; + var env = isDevelopmentMode ? '1' : '0'; + var queryParams = ["env=".concat(env)]; + var _a = dataPlanConfig || {}, + planId = _a.planId, + planVersion = _a.planVersion; + if (planId) { + queryParams.push("plan_id=".concat(planId)); + } + if (planVersion) { + queryParams.push("plan_version=".concat(planVersion)); + } + return "".concat(url, "?").concat(queryParams.join('&')); + }; + function ConfigAPIClient(apiKey, config, mpInstance) { + var _this = this; + var baseUrl = 'https://' + mpInstance._Store.SDKConfig.configUrl; + var isDevelopmentMode = config.isDevelopmentMode; + var dataPlan = config.dataPlan; + var uploadUrl = buildUrl(baseUrl, apiKey, dataPlan, isDevelopmentMode); + var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); + this.getSDKConfiguration = function () { + return __awaiter(_this, void 0, void 0, function () { + var configResponse, fetchPayload, response, xhrResponse; + var _a, _b, _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + fetchPayload = { + method: 'get', + headers: { + Accept: 'text/plain;charset=UTF-8', + 'Content-Type': 'text/plain;charset=UTF-8' + }, + body: null + }; + _d.label = 1; + case 1: + _d.trys.push([1, 6,, 7]); + return [4 /*yield*/, uploader.upload(fetchPayload)]; + case 2: + response = _d.sent(); + if (!(response.status === 200)) return [3 /*break*/, 5]; + (_a = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _a === void 0 ? void 0 : _a.verbose('Successfully received configuration from server'); + if (!response.json) return [3 /*break*/, 4]; + return [4 /*yield*/, response.json()]; + case 3: + configResponse = _d.sent(); + return [2 /*return*/, configResponse]; + case 4: + xhrResponse = response; + configResponse = JSON.parse(xhrResponse.responseText); + return [2 /*return*/, configResponse]; + case 5: + (_b = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _b === void 0 ? void 0 : _b.verbose('Issue with receiving configuration from server, received HTTP Code of ' + response.statusText); + return [3 /*break*/, 7]; + case 6: + _d.sent(); + (_c = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _c === void 0 ? void 0 : _c.error('Error getting forwarder configuration from mParticle servers.'); + return [3 /*break*/, 7]; + case 7: + // Returns the original config object if we cannot retrieve the remote config + return [2 /*return*/, config]; + } + }); + }); + }; + } + + var ErrorCodes = { + UNKNOWN_ERROR: 'UNKNOWN_ERROR', + UNHANDLED_EXCEPTION: 'UNHANDLED_EXCEPTION', + IDENTITY_REQUEST: 'IDENTITY_REQUEST' + }; + var WSDKErrorSeverity = { + ERROR: 'ERROR', + INFO: 'INFO', + WARNING: 'WARNING' + }; + + var HTTPCodes$1 = Constants.HTTPCodes, + Messages$1 = Constants.Messages, + IdentityMethods = Constants.IdentityMethods; + var Modify = IdentityMethods.Modify; + function IdentityAPIClient(mpInstance) { + this.sendAliasRequest = function (aliasRequest, aliasCallback) { + return __awaiter(this, void 0, void 0, function () { + var Logger, invokeAliasCallback, aliasUrl, apiKey, uploadUrl, uploader, uploadPayload, response, aliasResponseBody, message, errorMessage, _a, xhrResponse, errorResponse, e_2, errorMessage; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + Logger = mpInstance.Logger; + invokeAliasCallback = mpInstance._Helpers.invokeAliasCallback; + aliasUrl = mpInstance._Store.SDKConfig.aliasUrl; + apiKey = mpInstance._Store.devToken; + Logger.verbose(Messages$1.InformationMessages.SendAliasHttp); + uploadUrl = "https://".concat(aliasUrl).concat(apiKey, "/Alias"); + uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); + uploadPayload = { + method: 'post', + headers: { + Accept: 'text/plain;charset=UTF-8', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(aliasRequest) + }; + _b.label = 1; + case 1: + _b.trys.push([1, 13,, 14]); + return [4 /*yield*/, uploader.upload(uploadPayload)]; + case 2: + response = _b.sent(); + aliasResponseBody = void 0; + message = void 0; + errorMessage = void 0; + _a = response.status; + switch (_a) { + case HTTP_ACCEPTED: + return [3 /*break*/, 3]; + case HTTP_OK: + return [3 /*break*/, 3]; + case HTTP_BAD_REQUEST: + return [3 /*break*/, 4]; + } + return [3 /*break*/, 11]; + case 3: + // https://go.mparticle.com/work/SQDSDKS-6670 + message = 'Received Alias Response from server: ' + JSON.stringify(response.status); + return [3 /*break*/, 12]; + case 4: + if (!response.json) return [3 /*break*/, 9]; + _b.label = 5; + case 5: + _b.trys.push([5, 7,, 8]); + return [4 /*yield*/, response.json()]; + case 6: + aliasResponseBody = _b.sent(); + return [3 /*break*/, 8]; + case 7: + _b.sent(); + Logger.verbose('The request has no response body'); + return [3 /*break*/, 8]; + case 8: + return [3 /*break*/, 10]; + case 9: + xhrResponse = response; + aliasResponseBody = xhrResponse.responseText ? JSON.parse(xhrResponse.responseText) : ''; + _b.label = 10; + case 10: + errorResponse = aliasResponseBody; + if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.message) { + errorMessage = errorResponse.message; + } + message = 'Issue with sending Alias Request to mParticle Servers, received HTTP Code of ' + response.status; + if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.code) { + message += ' - ' + errorResponse.code; + } + return [3 /*break*/, 12]; + case 11: + { + throw new Error('Received HTTP Code of ' + response.status); + } + case 12: + Logger.verbose(message); + invokeAliasCallback(aliasCallback, response.status, errorMessage); + return [3 /*break*/, 14]; + case 13: + e_2 = _b.sent(); + errorMessage = e_2.message || e_2.toString(); + Logger.error('Error sending alias request to mParticle servers. ' + errorMessage); + invokeAliasCallback(aliasCallback, HTTPCodes$1.noHttpCoverage, errorMessage); + return [3 /*break*/, 14]; + case 14: + return [2 /*return*/]; + } + }); + }); + }; + + this.sendIdentityRequest = function (identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid, knownIdentities) { + var _a, _b, _c, _d, _e; + return __awaiter(this, void 0, void 0, function () { + var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _f, responseBody, errorResponse, errorMessage, errorMessage, requestCount, err_1, requestCount, errorMessage, msg; + return __generator(this, function (_g) { + switch (_g.label) { + case 0: + if ((_a = mpInstance._RoktManager) === null || _a === void 0 ? void 0 : _a.isInitialized) { + mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1; + requestCount = mpInstance._Store.identifyRequestCount; + mpInstance.captureTiming("".concat(requestCount, "-identityRequestStart")); + } + invokeCallback = mpInstance._Helpers.invokeCallback; + Logger = mpInstance.Logger; + Logger.verbose(Messages$1.InformationMessages.SendIdentityBegin); + if (!identityApiRequest) { + Logger.error(Messages$1.ErrorMessages.APIRequestEmpty); + return [2 /*return*/]; + } + + Logger.verbose(Messages$1.InformationMessages.SendIdentityHttp); + if (mpInstance._Store.identityCallInFlight) { + invokeCallback(callback, HTTPCodes$1.activeIdentityRequest, 'There is currently an Identity request processing. Please wait for this to return before requesting again'); + return [2 /*return*/]; + } + + previousMPID = mpid || null; + uploadUrl = this.getUploadUrl(method, mpid); + uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); + fetchPayload = { + method: 'post', + headers: { + Accept: 'text/plain;charset=UTF-8', + 'Content-Type': 'application/json', + 'x-mp-key': mpInstance._Store.devToken + }, + body: JSON.stringify(identityApiRequest) + }; + mpInstance._Store.identityCallInFlight = true; + _g.label = 1; + case 1: + _g.trys.push([1, 9,, 10]); + return [4 /*yield*/, uploader.upload(fetchPayload)]; + case 2: + response = _g.sent(); + identityResponse = void 0; + message = void 0; + _f = response.status; + switch (_f) { + case HTTP_ACCEPTED: + return [3 /*break*/, 3]; + case HTTP_OK: + return [3 /*break*/, 3]; + case HTTP_BAD_REQUEST: + return [3 /*break*/, 3]; + } + return [3 /*break*/, 7]; + case 3: + if (!response.json) return [3 /*break*/, 5]; + return [4 /*yield*/, response.json()]; + case 4: + responseBody = _g.sent(); + identityResponse = this.getIdentityResponseFromFetch(response, responseBody); + return [3 /*break*/, 6]; + case 5: + identityResponse = this.getIdentityResponseFromXHR(response); + _g.label = 6; + case 6: + if (identityResponse.status === HTTP_BAD_REQUEST) { + errorResponse = identityResponse.responseText; + message = 'Issue with sending Identity Request to mParticle Servers, received HTTP Code of ' + identityResponse.status; + if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.Errors) { + errorMessage = errorResponse.Errors.map(function (error) { + return error.message; + }).join(', '); + message += ' - ' + errorMessage; + } + } else { + message = 'Received Identity Response from server: '; + message += JSON.stringify(identityResponse.responseText); + } + return [3 /*break*/, 8]; + case 7: + { + if (response.status >= HTTP_SERVER_ERROR) { + throw new Error('Received HTTP Code of ' + response.status); + } + mpInstance._Store.identityCallInFlight = false; + mpInstance._Store.identityCallFailed = false; + errorMessage = 'Received HTTP Code of ' + response.status; + Logger.error('Error sending identity request to servers - ' + errorMessage); + invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); + return [2 /*return*/]; + } + case 8: + mpInstance._Store.identityCallInFlight = false; + mpInstance._Store.identityCallFailed = false; + Logger.verbose(message); + if ((_b = mpInstance._RoktManager) === null || _b === void 0 ? void 0 : _b.isInitialized) { + requestCount = mpInstance._Store.identifyRequestCount; + mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); + } + parseIdentityResponse(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false); + return [3 /*break*/, 10]; + case 9: + err_1 = _g.sent(); + mpInstance._Store.identityCallInFlight = false; + mpInstance._Store.identityCallFailed = true; + if ((_c = mpInstance._RoktManager) === null || _c === void 0 ? void 0 : _c.isInitialized) { + requestCount = mpInstance._Store.identifyRequestCount; + mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); + } + errorMessage = err_1.message || err_1.toString(); + msg = 'Error sending identity request to servers' + ' - ' + errorMessage; + Logger.error(msg); + (_d = mpInstance._ErrorReportingDispatcher) === null || _d === void 0 ? void 0 : _d.report({ + message: msg, + code: ErrorCodes.IDENTITY_REQUEST, + severity: WSDKErrorSeverity.ERROR + }); + (_e = mpInstance.processQueueOnIdentityFailure) === null || _e === void 0 ? void 0 : _e.call(mpInstance); + invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); + return [3 /*break*/, 10]; + case 10: + return [2 /*return*/]; + } + }); + }); + }; + + this.getUploadUrl = function (method, mpid) { + var uploadServiceUrl = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.identityUrl); + var uploadUrl = method === Modify ? uploadServiceUrl + mpid + '/' + method : uploadServiceUrl + method; + return uploadUrl; + }; + this.getIdentityResponseFromFetch = function (response, responseBody) { + return { + status: response.status, + responseText: responseBody, + cacheMaxAge: parseInt(response.headers.get(CACHE_HEADER)) || 0, + expireTimestamp: 0 + }; + }; + this.getIdentityResponseFromXHR = function (response) { + return { + status: response.status, + responseText: response.responseText ? JSON.parse(response.responseText) : {}, + cacheMaxAge: parseNumber(response.getResponseHeader(CACHE_HEADER) || ''), + expireTimestamp: 0 + }; + }; + } + + // Facebook Click ID has specific formatting rules + // The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: + // - version is always this prefix: fb + // - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2) + // - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value + // - is the value for the fbclid query parameter in the page URL. + // https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc + var facebookClickIdProcessor = function facebookClickIdProcessor(clickId, url, timestamp) { + if (!clickId || !url) { + return ''; + } + var urlSegments = url === null || url === void 0 ? void 0 : url.split('//'); + if (!urlSegments) { + return ''; + } + var urlParts = urlSegments[1].split('/'); + var domainParts = urlParts[0].split('.'); + var subdomainIndex = 1; + // The rules for subdomainIndex are for parsing the domain portion + // of the URL for cookies, but in this case we are parsing the URL + // itself, so we can ignore the use of 0 for 'com' + if (domainParts.length >= 3) { + subdomainIndex = 2; + } + // If timestamp is not provided, use the current time + var _timestamp = timestamp || Date.now(); + return "fb.".concat(subdomainIndex, ".").concat(_timestamp, ".").concat(clickId); + }; + // Integration outputs are used to determine how click ids are used within the SDK + // CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject + // PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch + // INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created + var IntegrationOutputs = { + CUSTOM_FLAGS: 'custom_flags', + PARTNER_IDENTITIES: 'partner_identities', + INTEGRATION_ATTRIBUTES: 'integration_attributes' + }; + var integrationMappingExternal = { + // Facebook / Meta + fbclid: { + mappedKey: 'Facebook.ClickId', + processor: facebookClickIdProcessor, + output: IntegrationOutputs.CUSTOM_FLAGS + }, + _fbp: { + mappedKey: 'Facebook.BrowserId', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + _fbc: { + mappedKey: 'Facebook.ClickId', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + // Google + gclid: { + mappedKey: 'GoogleEnhancedConversions.Gclid', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + gbraid: { + mappedKey: 'GoogleEnhancedConversions.Gbraid', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + wbraid: { + mappedKey: 'GoogleEnhancedConversions.Wbraid', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + // TIKTOK + ttclid: { + mappedKey: 'TikTok.Callback', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + _ttp: { + mappedKey: 'tiktok_cookie_id', + output: IntegrationOutputs.PARTNER_IDENTITIES + }, + // Snapchat + // https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US + ScCid: { + mappedKey: 'SnapchatConversions.ClickId', + output: IntegrationOutputs.CUSTOM_FLAGS + }, + // Snapchat + // https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id + _scid: { + mappedKey: 'SnapchatConversions.Cookie1', + output: IntegrationOutputs.CUSTOM_FLAGS + } + }; + var integrationMappingRokt = { + // Rokt + // https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/ + // https://go.mparticle.com/work/SQDSDKS-7167 + rtid: { + mappedKey: 'passbackconversiontrackingid', + output: IntegrationOutputs.INTEGRATION_ATTRIBUTES, + moduleId: 1277 + }, + rclid: { + mappedKey: 'passbackconversiontrackingid', + output: IntegrationOutputs.INTEGRATION_ATTRIBUTES, + moduleId: 1277 + }, + RoktTransactionId: { + mappedKey: 'passbackconversiontrackingid', + output: IntegrationOutputs.INTEGRATION_ATTRIBUTES, + moduleId: 1277 + } + }; + var IntegrationCapture = /** @class */function () { + function IntegrationCapture(captureMode) { + this.initialTimestamp = Date.now(); + this.captureMode = captureMode; + // Cache filtered mappings for faster access + this.filteredPartnerIdentityMappings = this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES); + this.filteredCustomFlagMappings = this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS); + this.filteredIntegrationAttributeMappings = this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES); + } + /** + * Captures Integration Ids from cookies and query params and stores them in clickIds object + */ + IntegrationCapture.prototype.capture = function () { + var queryParams = this.captureQueryParams() || {}; + var cookies = this.captureCookies() || {}; + var localStorage = this.captureLocalStorage() || {}; + // Facebook Rules + // Exclude _fbc if fbclid is present + // https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc#retrieve-from-fbclid-url-query-parameter + if (queryParams['fbclid'] && cookies['_fbc']) { + delete cookies['_fbc']; + } + // ROKT Rules + // If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid + // If RoktTransactionId is present in both cookies and localStorage, + // prioritize localStorage + var hasQueryParamId = queryParams['rtid'] || queryParams['rclid']; + var hasLocalStorageId = localStorage['RoktTransactionId']; + var hasCookieId = cookies['RoktTransactionId']; + if (hasQueryParamId) { + // Query param takes precedence, remove both localStorage and cookie if present + if (hasLocalStorageId) { + delete localStorage['RoktTransactionId']; + } + if (hasCookieId) { + delete cookies['RoktTransactionId']; + } + } else if (hasLocalStorageId && hasCookieId) { + // No query param, but both localStorage and cookie exist + // localStorage takes precedence over cookie + delete cookies['RoktTransactionId']; + } + this.clickIds = __assign(__assign(__assign(__assign({}, this.clickIds), queryParams), localStorage), cookies); + }; + /** + * Captures cookies based on the integration ID mapping. + */ + IntegrationCapture.prototype.captureCookies = function () { + var integrationKeys = this.getAllowedKeysForMode(); + var cookies = getCookies(integrationKeys); + return this.applyProcessors(cookies, getHref(), this.initialTimestamp); + }; + /** + * Captures query parameters based on the integration ID mapping. + */ + IntegrationCapture.prototype.captureQueryParams = function () { + var queryParams = this.getQueryParams(); + return this.applyProcessors(queryParams, getHref(), this.initialTimestamp); + }; + /** + * Captures local storage based on the integration ID mapping. + */ + IntegrationCapture.prototype.captureLocalStorage = function () { + var integrationKeys = this.getAllowedKeysForMode(); + var localStorageItems = {}; + for (var _i = 0, integrationKeys_1 = integrationKeys; _i < integrationKeys_1.length; _i++) { + var key = integrationKeys_1[_i]; + var localStorageItem = localStorage.getItem(key); + if (localStorageItem) { + localStorageItems[key] = localStorageItem; + } + } + return this.applyProcessors(localStorageItems, getHref(), this.initialTimestamp); + }; + /** + * Gets the query parameters based on the integration ID mapping. + * @returns {Dictionary} The query parameters. + */ + IntegrationCapture.prototype.getQueryParams = function () { + var integrationKeys = this.getAllowedKeysForMode(); + return queryStringParser(getHref(), integrationKeys); + }; + /** + * Converts captured click IDs to custom flags for SDK events. + * @returns {SDKEventCustomFlags} The custom flags. + */ + IntegrationCapture.prototype.getClickIdsAsCustomFlags = function () { + return this.getClickIds(this.clickIds, this.filteredCustomFlagMappings); + }; + /** + * Returns only the `partner_identities` mapped integration output. + * @returns {Dictionary} The partner identities. + */ + IntegrationCapture.prototype.getClickIdsAsPartnerIdentities = function () { + return this.getClickIds(this.clickIds, this.filteredPartnerIdentityMappings); + }; + /** + * Returns only the `integration_attributes` mapped integration output. + * @returns {IntegrationAttributes} The integration attributes. + */ + IntegrationCapture.prototype.getClickIdsAsIntegrationAttributes = function () { + var _a; + var _b, _c; + // Integration IDs are stored in the following format: + // { + // "integration_attributes": { + // "": { + // "mappedKey": "clickIdValue" + // } + // } + // } + var mappedClickIds = {}; + for (var key in this.clickIds) { + if (this.clickIds.hasOwnProperty(key)) { + var value = this.clickIds[key]; + var mappingKey = (_b = this.filteredIntegrationAttributeMappings[key]) === null || _b === void 0 ? void 0 : _b.mappedKey; + if (!isEmpty(mappingKey)) { + var moduleId = (_c = this.filteredIntegrationAttributeMappings[key]) === null || _c === void 0 ? void 0 : _c.moduleId; + if (moduleId && !mappedClickIds[moduleId]) { + mappedClickIds[moduleId] = (_a = {}, _a[mappingKey] = value, _a); + } + } + } + } + return mappedClickIds; + }; + IntegrationCapture.prototype.getClickIds = function (clickIds, mappingList) { + var _a; + var mappedClickIds = {}; + if (!clickIds) { + return mappedClickIds; + } + for (var key in clickIds) { + if (clickIds.hasOwnProperty(key)) { + var value = clickIds[key]; + var mappedKey = (_a = mappingList[key]) === null || _a === void 0 ? void 0 : _a.mappedKey; + if (!isEmpty(mappedKey)) { + mappedClickIds[mappedKey] = value; + } + } + } + return mappedClickIds; + }; + IntegrationCapture.prototype.applyProcessors = function (clickIds, url, timestamp) { + var _a; + var processedClickIds = {}; + var integrationKeys = this.getActiveIntegrationMapping(); + for (var key in clickIds) { + if (clickIds.hasOwnProperty(key)) { + var value = clickIds[key]; + var processor = (_a = integrationKeys[key]) === null || _a === void 0 ? void 0 : _a.processor; + processedClickIds[key] = processor ? processor(value, url, timestamp) : value; + } + } + return processedClickIds; + }; + IntegrationCapture.prototype.filterMappings = function (outputType) { + var filteredMappings = {}; + var integrationKeys = this.getActiveIntegrationMapping(); + for (var key in integrationKeys) { + if (integrationKeys[key].output === outputType) { + filteredMappings[key] = integrationKeys[key]; + } + } + return filteredMappings; + }; + /** + * Returns the allowed keys to capture based on the current mode. + * For RoktOnly, limit capture to Rokt keys; for All, capture all mapped keys. + */ + IntegrationCapture.prototype.getAllowedKeysForMode = function () { + return Object.keys(this.getActiveIntegrationMapping()); + }; + /** + * Selects the active integration mapping for the current captureMode. + * - 'roktonly': only Rokt IDs are considered + * - 'all': both External and Rokt IDs are considered + * - else: returns an empty mapping and nothing will be captured + */ + IntegrationCapture.prototype.getActiveIntegrationMapping = function () { + if (this.captureMode === Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly) { + return integrationMappingRokt; + } + if (this.captureMode === Constants.CaptureIntegrationSpecificIdsV2Modes.All) { + return __assign(__assign({}, integrationMappingExternal), integrationMappingRokt); + } + return {}; + }; + return IntegrationCapture; + }(); + + // The purpose of this class is to create a link between the Core mParticle SDK and the + // Rokt Web SDK via a Web Kit. + // The Rokt Manager should load before the Web Kit and stubs out many of the + // Rokt Web SDK functions with an internal message queue in case a Rokt function + // is requested before the Rokt Web Kit or SDK is finished loaded. + // Once the Rokt Kit is attached to the Rokt Manager, we can consider the + // Rokt Manager in a "ready" state and it can begin sending data to the kit. + // + // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt + var RoktManager = /** @class */function () { + function RoktManager() { + this.kit = null; + this.filters = {}; + this.currentUser = null; + this.messageQueue = new Map(); + this.sandbox = null; + this.placementAttributesMapping = []; + this.onReadyCallback = null; + this.initialized = false; + } + /** + * Sets a callback to be invoked when RoktManager becomes ready + */ + RoktManager.prototype.setOnReadyCallback = function (callback) { + this.onReadyCallback = callback; + }; + /** + * Initializes the RoktManager with configuration settings and user data. + * + * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings + * @param {IMParticleUser} filteredUser - User object with filtered attributes + * @param {SDKIdentityApi} identityService - The mParticle Identity instance + * @param {SDKLoggerApi} logger - The mParticle Logger instance + * @param {IRoktOptions} options - Options for the RoktManager + * @param {Function} captureTiming - Function to capture performance timing marks + * + * @throws Logs error to console if placementAttributesMapping parsing fails + */ + RoktManager.prototype.init = function (roktConfig, filteredUser, identityService, store, logger, options, captureTiming) { + var _a, _b; + var _c = roktConfig || {}, + userAttributeFilters = _c.userAttributeFilters, + settings = _c.settings; + var _d = settings || {}, + placementAttributesMapping = _d.placementAttributesMapping, + hashedEmailUserIdentityType = _d.hashedEmailUserIdentityType; + this.mappedEmailShaIdentityType = (_a = hashedEmailUserIdentityType === null || hashedEmailUserIdentityType === void 0 ? void 0 : hashedEmailUserIdentityType.toLowerCase()) !== null && _a !== void 0 ? _a : null; + this.identityService = identityService; + this.store = store; + this.logger = logger; + this.captureTiming = captureTiming; + (_b = this.captureTiming) === null || _b === void 0 ? void 0 : _b.call(this, PerformanceMarkType.JointSdkRoktKitInit); + this.filters = { + userAttributeFilters: userAttributeFilters, + filterUserAttributes: KitFilterHelper.filterUserAttributes, + filteredUser: filteredUser + }; + try { + this.placementAttributesMapping = parseSettingsString(placementAttributesMapping); + } catch (error) { + this.logger.error('Error parsing placement attributes mapping from config: ' + error); + } + // This is the global setting for sandbox mode + // It is set here and passed in to the createLauncher method in the Rokt Kit + // This is not to be confused for the `sandbox` flag in the selectPlacements attributes + // as that is independent of this setting, though they share the same name. + var sandbox = (options === null || options === void 0 ? void 0 : options.sandbox) || false; + // Launcher options are set here for the kit to pick up and pass through + // to the Rokt Launcher. + this.launcherOptions = __assign({ + sandbox: sandbox + }, options === null || options === void 0 ? void 0 : options.launcherOptions); + if (options === null || options === void 0 ? void 0 : options.domain) { + this.domain = options.domain; + } + // initialized indicates that init() has been called and the RoktManager has been initialized. + // This is different from isReady(), which only returns true once the kit has been attached + // (which is asynchronous), and has a launcher. + this.initialized = true; + }; + Object.defineProperty(RoktManager.prototype, "isInitialized", { + get: function get() { + return this.initialized; + }, + enumerable: false, + configurable: true + }); + RoktManager.prototype.attachKit = function (kit) { + var _a, _b, _c, _d; + this.kit = kit; + if ((_a = kit.settings) === null || _a === void 0 ? void 0 : _a.accountId) { + this.store.setRoktAccountId(kit.settings.accountId); + } + if (kit.integrationName) { + (_b = this.store) === null || _b === void 0 ? void 0 : _b.setIntegrationName(kit.integrationName); + } + this.processMessageQueue(); + try { + (_c = this.onReadyCallback) === null || _c === void 0 ? void 0 : _c.call(this); + } catch (e) { + (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error('RoktManager: Error in onReadyCallback: ' + e); + } + }; + /** + * Renders ads based on the options provided + * + * @param {IRoktSelectPlacementsOptions} options - The options for selecting placements, including attributes and optional identifier + * @returns {Promise} A promise that resolves to the selection + * + * @example + * // Correct usage with await + * await window.mParticle.Rokt.selectPlacements({ + * attributes: { + * email: 'user@example.com', + * customAttr: 'value' + * } + * }); + */ + RoktManager.prototype.selectPlacements = function (options) { + var _a, _b, _c, _d, _e, _f, _g; + return __awaiter(this, void 0, void 0, function () { + var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail, currentHashedEmail, newHashedEmail, isValidHashedEmailIdentityType, emailChanged, hashedEmailChanged, newIdentities_1, error_1, finalUserIdentities, enrichedAttributes, hashedEmail, enrichedOptions, error_2; + var _this = this; + return __generator(this, function (_h) { + switch (_h.label) { + case 0: + (_a = this.captureTiming) === null || _a === void 0 ? void 0 : _a.call(this, PerformanceMarkType.JointSdkSelectPlacements); + // Queue if kit isn't ready OR if identity is in flight + if (!this.isReady() || ((_b = this.store) === null || _b === void 0 ? void 0 : _b.identityCallInFlight)) { + return [2 /*return*/, this.deferredCall('selectPlacements', options)]; + } + _h.label = 1; + case 1: + _h.trys.push([1, 6,, 7]); + attributes = options.attributes; + sandboxValue = (attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) || null; + mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping); + (_c = this.logger) === null || _c === void 0 ? void 0 : _c.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(attributes, null, 2))); + this.currentUser = this.identityService.getCurrentUser(); + currentUserIdentities_1 = ((_e = (_d = this.currentUser) === null || _d === void 0 ? void 0 : _d.getUserIdentities()) === null || _e === void 0 ? void 0 : _e.userIdentities) || {}; + currentEmail = currentUserIdentities_1.email; + newEmail = mappedAttributes.email; + currentHashedEmail = void 0; + newHashedEmail = void 0; + isValidHashedEmailIdentityType = this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false; + if (isValidHashedEmailIdentityType) { + currentHashedEmail = currentUserIdentities_1[this.mappedEmailShaIdentityType]; + newHashedEmail = mappedAttributes['emailsha256'] || mappedAttributes[this.mappedEmailShaIdentityType] || undefined; + } + emailChanged = this.hasIdentityChanged(currentEmail, newEmail); + hashedEmailChanged = this.hasIdentityChanged(currentHashedEmail, newHashedEmail); + newIdentities_1 = {}; + if (emailChanged) { + newIdentities_1.email = newEmail; + if (newEmail) { + this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation."); + } + } + if (hashedEmailChanged) { + newIdentities_1[this.mappedEmailShaIdentityType] = newHashedEmail; + this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation."); + } + if (!!isEmpty(newIdentities_1)) return [3 /*break*/, 5]; + _h.label = 2; + case 2: + _h.trys.push([2, 4,, 5]); + return [4 /*yield*/, new Promise(function (resolve, reject) { + _this.identityService.identify({ + userIdentities: __assign(__assign({}, currentUserIdentities_1), newIdentities_1) + }, function () { + resolve(); + }); + })]; + case 3: + _h.sent(); + return [3 /*break*/, 5]; + case 4: + error_1 = _h.sent(); + this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error_1)); + return [3 /*break*/, 5]; + case 5: + // Refresh current user identities to ensure we have the latest values before building enrichedAttributes + this.currentUser = this.identityService.getCurrentUser(); + finalUserIdentities = ((_g = (_f = this.currentUser) === null || _f === void 0 ? void 0 : _f.getUserIdentities()) === null || _g === void 0 ? void 0 : _g.userIdentities) || {}; + this.setUserAttributes(mappedAttributes); + enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? { + sandbox: sandboxValue + } : {}); + // Propagate email from current user identities if not already in attributes + if (finalUserIdentities.email && !enrichedAttributes.email) { + enrichedAttributes.email = finalUserIdentities.email; + } + // Propagate emailsha256 from current user identities if not already in attributes + if (isValidHashedEmailIdentityType) { + hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType]; + if (hashedEmail && !enrichedAttributes.emailsha256 && !enrichedAttributes[this.mappedEmailShaIdentityType]) { + enrichedAttributes.emailsha256 = hashedEmail; + } + } + this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null; + enrichedOptions = __assign(__assign({}, options), { + attributes: enrichedAttributes + }); + return [2 /*return*/, this.kit.selectPlacements(enrichedOptions)]; + case 6: + error_2 = _h.sent(); + return [2 /*return*/, Promise.reject(error_2 instanceof Error ? error_2 : new Error('Unknown error occurred'))]; + case 7: + return [2 /*return*/]; + } + }); + }); + }; + /** + * Hashes attributes and returns both original and hashed versions + * with Rokt-compatible key names (like emailsha256, mobilesha256) + * + * + * @param {RoktAttributes} attributes - Attributes to hash + * @returns {Promise} Object with both original and hashed attributes + * + */ + RoktManager.prototype.hashAttributes = function (attributes) { + return __awaiter(this, void 0, void 0, function () { + var keys, hashPromises, results, hashedAttributes, _i, results_1, _a, key, attributeValue, hashedValue, error_3, errorMessage; + var _this = this; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2,, 3]); + if (!attributes || _typeof$1(attributes) !== 'object') { + return [2 /*return*/, {}]; + } + keys = Object.keys(attributes); + if (keys.length === 0) { + return [2 /*return*/, {}]; + } + hashPromises = keys.map(function (key) { + return __awaiter(_this, void 0, void 0, function () { + var attributeValue, hashedValue; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + attributeValue = attributes[key]; + return [4 /*yield*/, this.hashSha256(attributeValue)]; + case 1: + hashedValue = _a.sent(); + return [2 /*return*/, { + key: key, + attributeValue: attributeValue, + hashedValue: hashedValue + }]; + } + }); + }); + }); + return [4 /*yield*/, Promise.all(hashPromises)]; + case 1: + results = _b.sent(); + hashedAttributes = {}; + for (_i = 0, results_1 = results; _i < results_1.length; _i++) { + _a = results_1[_i], key = _a.key, attributeValue = _a.attributeValue, hashedValue = _a.hashedValue; + hashedAttributes[key] = attributeValue; + if (hashedValue) { + hashedAttributes["".concat(key, "sha256")] = hashedValue; + } + } + return [2 /*return*/, hashedAttributes]; + case 2: + error_3 = _b.sent(); + errorMessage = error_3 instanceof Error ? error_3.message : String(error_3); + this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(errorMessage)); + return [2 /*return*/, {}]; + case 3: + return [2 /*return*/]; + } + }); + }); + }; + + RoktManager.prototype.setExtensionData = function (extensionData) { + if (!this.isReady()) { + this.deferredCall('setExtensionData', extensionData); + return; + } + try { + this.kit.setExtensionData(extensionData); + } catch (error) { + var errorMessage = error instanceof Error ? error.message : String(error); + throw new Error('Error setting extension data: ' + errorMessage); + } + }; + RoktManager.prototype.use = function (name) { + if (!this.isReady()) { + return this.deferredCall('use', name); + } + try { + return this.kit.use(name); + } catch (error) { + return Promise.reject(error instanceof Error ? error : new Error('Error using extension: ' + name)); + } + }; + /** + * Hashes an attribute using SHA-256 + * + * @param {string | number | boolean | undefined | null} attribute - The value to hash + * @returns {Promise} SHA-256 hashed value or undefined/null + * + */ + RoktManager.prototype.hashSha256 = function (attribute) { + return __awaiter(this, void 0, void 0, function () { + var normalizedValue, error_4, errorMessage; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (attribute === null || attribute === undefined) { + this.logger.warning("hashSha256 received null/undefined as input"); + return [2 /*return*/, attribute]; + } + _a.label = 1; + case 1: + _a.trys.push([1, 3,, 4]); + normalizedValue = String(attribute).trim().toLocaleLowerCase(); + return [4 /*yield*/, this.sha256Hex(normalizedValue)]; + case 2: + return [2 /*return*/, _a.sent()]; + case 3: + error_4 = _a.sent(); + errorMessage = error_4 instanceof Error ? error_4.message : String(error_4); + this.logger.error("Failed to hashSha256, returning undefined: ".concat(errorMessage)); + return [2 /*return*/, undefined]; + case 4: + return [2 /*return*/]; + } + }); + }); + }; + + RoktManager.prototype.getLocalSessionAttributes = function () { + return this.store.getLocalSessionAttributes(); + }; + RoktManager.prototype.setLocalSessionAttribute = function (key, value) { + this.store.setLocalSessionAttribute(key, value); + }; + RoktManager.prototype.isReady = function () { + // The Rokt Manager is ready when a kit is attached and has a launcher + return Boolean(this.kit && this.kit.launcher); + }; + RoktManager.prototype.setUserAttributes = function (attributes) { + var reservedAttributes = ['sandbox']; + var filteredAttributes = {}; + for (var key in attributes) { + if (attributes.hasOwnProperty(key) && reservedAttributes.indexOf(key) === -1) { + var value = attributes[key]; + filteredAttributes[key] = Array.isArray(value) ? JSON.stringify(value) : value; + } + } + try { + this.currentUser.setUserAttributes(filteredAttributes); + } catch (error) { + this.logger.error('Error setting user attributes: ' + error); + } + }; + RoktManager.prototype.mapPlacementAttributes = function (attributes, placementAttributesMapping) { + var mappingLookup = {}; + for (var _i = 0, placementAttributesMapping_1 = placementAttributesMapping; _i < placementAttributesMapping_1.length; _i++) { + var mapping = placementAttributesMapping_1[_i]; + mappingLookup[mapping.map] = mapping.value; + } + var mappedAttributes = {}; + for (var key in attributes) { + if (attributes.hasOwnProperty(key)) { + var newKey = mappingLookup[key] || key; + mappedAttributes[newKey] = attributes[key]; + } + } + return mappedAttributes; + }; + RoktManager.prototype.onIdentityComplete = function () { + if (this.isReady()) { + this.currentUser = this.identityService.getCurrentUser(); + // Process any queued selectPlacements calls that were waiting for identity + this.processMessageQueue(); + } + }; + RoktManager.prototype.processMessageQueue = function () { + var _this = this; + var _a; + if (!this.isReady() || this.messageQueue.size === 0) { + return; + } + (_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages")); + var messagesToProcess = Array.from(this.messageQueue.values()); + // Clear the queue immediately to prevent re-processing + this.messageQueue.clear(); + messagesToProcess.forEach(function (message) { + var _a, _b; + if (!(message.methodName in _this) || !isFunction(_this[message.methodName])) { + (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Method ".concat(message.methodName, " not found")); + return; + } + (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.verbose("RoktManager: Processing queued message: ".concat(message.methodName, " with payload: ").concat(JSON.stringify(message.payload))); + // Capture resolve/reject functions before async processing + var resolve = message.resolve; + var reject = message.reject; + var handleError = function handleError(error) { + var _a; + var errorMessage = error instanceof Error ? error.message : String(error); + (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage)); + if (reject) { + reject(error); + } + }; + try { + var result = _this[message.methodName](message.payload); + // Handle both sync and async methods + Promise.resolve(result).then(function (resolvedResult) { + if (resolve) { + resolve(resolvedResult); + } + })["catch"](handleError); + } catch (error) { + handleError(error); + } + }); + }; + RoktManager.prototype.queueMessage = function (message) { + this.messageQueue.set(message.messageId, message); + }; + RoktManager.prototype.deferredCall = function (methodName, payload) { + var _this = this; + return new Promise(function (resolve, reject) { + var messageId = "".concat(methodName, "_").concat(generateUniqueId()); + _this.queueMessage({ + messageId: messageId, + methodName: methodName, + payload: payload, + resolve: resolve, + reject: reject + }); + }); + }; + /** + * Hashes a string input using SHA-256 and returns the hex digest + * Uses the Web Crypto API for secure hashing + * + * @param {string} input - The string to hash + * @returns {Promise} The SHA-256 hash as a hexadecimal string + */ + RoktManager.prototype.sha256Hex = function (input) { + return __awaiter(this, void 0, void 0, function () { + var encoder, encodedInput, digest; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + encoder = new TextEncoder(); + encodedInput = encoder.encode(input); + return [4 /*yield*/, crypto.subtle.digest('SHA-256', encodedInput)]; + case 1: + digest = _a.sent(); + return [2 /*return*/, this.arrayBufferToHex(digest)]; + } + }); + }); + }; + /** + * Converts an ArrayBuffer to a hexadecimal string representation + * Each byte is converted to a 2-character hex string with leading zeros + * + * @param {ArrayBuffer} buffer - The buffer to convert + * @returns {string} The hexadecimal string representation + */ + RoktManager.prototype.arrayBufferToHex = function (buffer) { + var bytes = new Uint8Array(buffer); + var hexString = ''; + for (var i = 0; i < bytes.length; i++) { + var hexByte = bytes[i].toString(16).padStart(2, '0'); + hexString += hexByte; + } + return hexString; + }; + /** + * Checks if an identity value has changed by comparing current and new values + * + * @param {string | undefined} currentValue - The current identity value + * @param {string | undefined} newValue - The new identity value to compare against + * @returns {boolean} True if the identity has changed (new value exists and differs from current), false otherwise + */ + RoktManager.prototype.hasIdentityChanged = function (currentValue, newValue) { + if (!newValue) { + return false; + } + if (!currentValue) { + return true; // New value exists but no current value + } + + if (currentValue !== newValue) { + return true; // Values are different + } + + return false; // Values are the same + }; + + return RoktManager; + }(); + + /** + * CookieConsentManager handles storage and access of consent flags (noFunctional, noTargeting) + * that are passed via launcherOptions during SDK initialization. + * + * These flags allow Rokt integration to respect user privacy choices. + * + * Default behavior: Both flags default to false, meaning all features are allowed + * unless explicitly opted out by the user. + */ + var CookieConsentManager = /** @class */function () { + function CookieConsentManager(flags) { + this.flags = flags; + this.flags = { + noFunctional: flags.noFunctional === true, + noTargeting: flags.noTargeting === true + }; + } + /** + * Returns true if third-party targeting is disabled. + * Targeting is allowed when noTargeting is false (default). + */ + CookieConsentManager.prototype.getNoTargeting = function () { + return this.flags.noTargeting; + }; + /** + * Returns true if functional tracking is disabled. + * Functional tracking is allowed when noFunctional is false (default). + */ + CookieConsentManager.prototype.getNoFunctional = function () { + return this.flags.noFunctional; + }; + return CookieConsentManager; + }(); + + var ErrorReportingDispatcher = /** @class */function () { + function ErrorReportingDispatcher() { + this.services = []; + } + ErrorReportingDispatcher.prototype.register = function (service) { + this.services.push(service); + }; + ErrorReportingDispatcher.prototype.report = function (error) { + this.services.forEach(function (s) { + return s.report(error); + }); + }; + return ErrorReportingDispatcher; + }(); + + var LoggingDispatcher = /** @class */function () { + function LoggingDispatcher() { + this.services = []; + } + LoggingDispatcher.prototype.register = function (service) { + this.services.push(service); + }; + LoggingDispatcher.prototype.log = function (entry) { + this.services.forEach(function (s) { + return s.log(entry); + }); + }; + return LoggingDispatcher; + }(); + + var Messages = Constants.Messages, + HTTPCodes = Constants.HTTPCodes, + FeatureFlags = Constants.FeatureFlags, + CaptureIntegrationSpecificIdsV2Modes = Constants.CaptureIntegrationSpecificIdsV2Modes; + var ReportBatching = FeatureFlags.ReportBatching, + CaptureIntegrationSpecificIds = FeatureFlags.CaptureIntegrationSpecificIds, + CaptureIntegrationSpecificIdsV2 = FeatureFlags.CaptureIntegrationSpecificIdsV2; + var StartingInitialization = Messages.InformationMessages.StartingInitialization; + /** + *

All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

+ *

In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.

+ *

This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().

+ *

If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:

+ * + * mParticle.init('apiKey', config, 'another_instance'); + * mParticle.getInstance('another_instance').logPageView(); + * + * + * @class mParticle & mParticleInstance + */ + function mParticleInstance(instanceName) { + var self = this; + // These classes are for internal use only. Not documented for public consumption + this._instanceName = instanceName; + this._NativeSdkHelpers = new NativeSdkHelpers(this); + this._SessionManager = new SessionManager(this); + this._Persistence = new _Persistence(this); + this._Helpers = new Helpers(this); + this._Events = new Events(this); + this._CookieSyncManager = new CookieSyncManager(this); + this._ServerModel = new ServerModel(this); + this._Ecommerce = new Ecommerce(this); + this._ForwardingStatsUploader = new forwardingStatsUploader(this); + this._Consent = new Consent(this); + this._IdentityAPIClient = new IdentityAPIClient(this); + this._preInit = { + readyQueue: [], + integrationDelays: {}, + forwarderConstructors: [] + }; + this._RoktManager = new RoktManager(); + this._RoktManager.setOnReadyCallback(function () { + self.processQueueOnIdentityFailure(); + }); + /** + * Processes message and ready queue when identity requests fails but Rokt is ready. + */ + this.processQueueOnIdentityFailure = function () { + var _a, _b, _c; + if ((_a = self._Store) === null || _a === void 0 ? void 0 : _a.isInitialized) { + return; + } + if (((_b = self._Store) === null || _b === void 0 ? void 0 : _b.identityCallFailed) && ((_c = self._RoktManager) === null || _c === void 0 ? void 0 : _c.isReady())) { + self._RoktManager.processMessageQueue(); + self._preInit.readyQueue = processReadyQueue(self._preInit.readyQueue); + } + }; + /** + * Drains the ready queue for noFunctional sessions with no explicit identity. + */ + this.processQueueOnNoFunctional = function () { + var _a, _b; + if ((_a = self._Store) === null || _a === void 0 ? void 0 : _a.isInitialized) { + return; + } + var noFunctionalWithoutId = ((_b = self._CookieConsentManager) === null || _b === void 0 ? void 0 : _b.getNoFunctional()) && !hasExplicitIdentifier(self._Store); + if (noFunctionalWithoutId) { + self._preInit.readyQueue = processReadyQueue(self._preInit.readyQueue); + } + }; + // required for forwarders once they reference the mparticle instance + this.IdentityType = IdentityType; + this.EventType = EventType; + this.CommerceEventType = CommerceEventType; + this.PromotionType = PromotionActionType; + this.ProductActionType = ProductActionType; + this._Identity = new Identity(this); + this.Identity = this._Identity.IdentityAPI; + this.generateHash = this._Helpers.generateHash; + // https://go.mparticle.com/work/SQDSDKS-6289 + // TODO: Replace this with Store once Store is moved earlier in the init process + this.getDeviceId = this._Persistence.getDeviceId; + if (typeof window !== 'undefined') { + if (window.mParticle && window.mParticle.config) { + if (window.mParticle.config.hasOwnProperty('rq')) { + this._preInit.readyQueue = window.mParticle.config.rq; + } + } + } + this.init = function (apiKey, config) { + var _this = this; + if (!config) { + console.warn('You did not pass a config object to init(). mParticle will not initialize properly'); + } + runPreConfigFetchInitialization(this, apiKey, config); + // config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization + // Since fetching the configuration is asynchronous, we must pass completeSDKInitialization + // to it for it to be run after fetched + if (config) { + if (!config.hasOwnProperty('requestConfig') || config.requestConfig) { + var configApiClient = new ConfigAPIClient(apiKey, config, this); + configApiClient.getSDKConfiguration().then(function (result) { + var mergedConfig = _this._Helpers.extend({}, config, result); + completeSDKInitialization(apiKey, mergedConfig, _this); + }); + } else { + completeSDKInitialization(apiKey, config, this); + } + } else { + console.error('No config available on the window, please pass a config object to mParticle.init()'); + return; + } + }; + /** + * Resets the SDK to an uninitialized state and removes cookies/localStorage. You MUST call mParticle.init(apiKey, window.mParticle.config) + * before any other mParticle methods or the SDK will not function as intended. + * @method setLogLevel + * @param {String} logLevel verbose, warning, or none. By default, `warning` is chosen. + */ + this.setLogLevel = function (newLogLevel) { + self.Logger.setLogLevel(newLogLevel); + }; + /** + * Resets the SDK to an uninitialized state and removes cookies/localStorage. You MUST call mParticle.init(apiKey, window.mParticle.config) + * before any other mParticle methods or the SDK will not function as intended. + * @method reset + */ + this.reset = function (instance) { + try { + instance._Persistence.resetPersistence(); + if (instance._Store) { + delete instance._Store; + } + } catch (error) { + console.error('Cannot reset mParticle', error); + } + }; + this._resetForTests = function (config, keepPersistence, instance) { + if (instance._Store) { + delete instance._Store; + } + instance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); + instance._LoggingDispatcher = new LoggingDispatcher(); + instance.Logger = new Logger(config); + instance._Store = new Store(config, instance); + instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability(window.localStorage); + instance._Events.stopTracking(); + if (!keepPersistence) { + instance._Persistence.resetPersistence(); + } + instance._Persistence.forwardingStatsBatches.uploadsTable = {}; + instance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = []; + instance._preInit = { + readyQueue: [], + pixelConfigurations: [], + integrationDelays: {}, + forwarderConstructors: [], + isDevelopmentMode: false + }; + }; + /** + * Executes callback when the SDK is ready, or Rokt is ready but identify requests fail due to server errors. + * This ensures Rokt methods like selectPlacements continue to work during backend outages. + * @method ready + * @param {Function} f Callback to execute + */ + this.ready = function (f) { + var _a, _b, _c; + var noFunctionalWithoutId = ((_a = self._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(self._Store); + var shouldExecute = isFunction(f) && (((_b = self._Store) === null || _b === void 0 ? void 0 : _b.isInitialized) || ((_c = self._Store) === null || _c === void 0 ? void 0 : _c.identityCallFailed) && self._RoktManager.isReady() || noFunctionalWithoutId); + if (shouldExecute) { + f(); + } else { + self._preInit.readyQueue.push(f); + } + }; + /** + * Returns the current mParticle environment setting + * @method getEnvironment + * @returns {String} mParticle environment setting + */ + this.getEnvironment = function () { + return self._Store.SDKConfig.isDevelopmentMode ? Constants.Environment.Development : Constants.Environment.Production; + }; + /** + * Returns the mParticle SDK version number + * @method getVersion + * @return {String} mParticle SDK version number + */ + this.getVersion = function () { + return Constants.sdkVersion; + }; + /** + * Sets the app version + * @method setAppVersion + * @param {String} version version number + */ + this.setAppVersion = function (version) { + var queued = queueIfNotInitialized(function () { + self.setAppVersion(version); + }, self); + if (queued) return; + self._Store.SDKConfig.appVersion = version; + self._Persistence.update(); + }; + /** + * Sets the device id + * @method setDeviceId + * @param {String} name device ID (UUIDv4-formatted string) + */ + this.setDeviceId = function (guid) { + var queued = queueIfNotInitialized(function () { + self.setDeviceId(guid); + }, self); + if (queued) return; + this._Store.setDeviceId(guid); + }; + /** + * Returns a boolean for whether or not the SDKhas been fully initialized + * @method isInitialized + * @return {Boolean} a boolean for whether or not the SDK has been fully initialized + */ + this.isInitialized = function () { + return self._Store ? self._Store.isInitialized : false; + }; + /** + * Gets the app name + * @method getAppName + * @return {String} App name + */ + this.getAppName = function () { + return self._Store.SDKConfig.appName; + }; + /** + * Sets the app name + * @method setAppName + * @param {String} name App Name + */ + this.setAppName = function (name) { + var queued = queueIfNotInitialized(function () { + self.setAppName(name); + }, self); + if (queued) return; + self._Store.SDKConfig.appName = name; + }; + /** + * Gets the app version + * @method getAppVersion + * @return {String} App version + */ + this.getAppVersion = function () { + return self._Store.SDKConfig.appVersion; + }; + /** + * Stops tracking the location of the user + * @method stopTrackingLocation + */ + this.stopTrackingLocation = function () { + self._SessionManager.resetSessionTimer(); + self._Events.stopTracking(); + }; + /** + * Starts tracking the location of the user + * @method startTrackingLocation + * @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback + */ + this.startTrackingLocation = function (callback) { + if (!isFunction(callback)) { + self.Logger.warning('Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.'); + } + self._SessionManager.resetSessionTimer(); + self._Events.startTracking(callback); + }; + /** + * Sets the position of the user + * @method setPosition + * @param {Number} lattitude lattitude digit + * @param {Number} longitude longitude digit + */ + this.setPosition = function (lat, lng) { + var queued = queueIfNotInitialized(function () { + self.setPosition(lat, lng); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + if (typeof lat === 'number' && typeof lng === 'number') { + self._Store.currentPosition = { + lat: lat, + lng: lng + }; + } else { + self.Logger.error('Position latitude and/or longitude must both be of type number'); + } + }; + /** + * Starts a new session + * @method startNewSession + */ + this.startNewSession = function () { + self._SessionManager.startNewSession(); + }; + /** + * Ends the current session + * @method endSession + */ + this.endSession = function () { + // Sends true as an over ride vs when endSession is called from the setInterval + self._SessionManager.endSession(true); + }; + /** + * Logs a Base Event to mParticle's servers + * @param {Object} event Base Event Object + * @param {Object} [eventOptions] For Event-level Configuration Options + */ + this.logBaseEvent = function (event, eventOptions) { + var queued = queueIfNotInitialized(function () { + self.logBaseEvent(event, eventOptions); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + if (typeof event.name !== 'string') { + self.Logger.error(Messages.ErrorMessages.EventNameInvalidType); + return; + } + if (!event.eventType) { + event.eventType = EventType.Unknown; + } + if (!self._Helpers.canLog()) { + self.Logger.error(Messages.ErrorMessages.LoggingDisabled); + return; + } + self._Events.logEvent(event, eventOptions); + }; + /** + * Logs an event to mParticle's servers + * @method logEvent + * @param {String} eventName The name of the event + * @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type) + * @param {Object} [eventInfo] Attributes for the event + * @param {Object} [customFlags] Additional customFlags + * @param {Object} [eventOptions] For Event-level Configuration Options + */ + this.logEvent = function (eventName, eventType, eventInfo, customFlags, eventOptions) { + var queued = queueIfNotInitialized(function () { + self.logEvent(eventName, eventType, eventInfo, customFlags, eventOptions); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + if (typeof eventName !== 'string') { + self.Logger.error(Messages.ErrorMessages.EventNameInvalidType); + return; + } + if (!eventType) { + eventType = EventType.Unknown; + } + if (!self._Helpers.isEventType(eventType)) { + self.Logger.error('Invalid event type: ' + eventType + ', must be one of: \n' + JSON.stringify(EventType)); + return; + } + if (!self._Helpers.canLog()) { + self.Logger.error(Messages.ErrorMessages.LoggingDisabled); + return; + } + self._Events.logEvent({ + messageType: MessageType$1.PageEvent, + name: eventName, + data: eventInfo, + eventType: eventType, + customFlags: customFlags + }, eventOptions); + }; + /** + * Used to log custom errors + * + * @method logError + * @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'} + * @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean + */ + this.logError = function (error, attrs) { + var queued = queueIfNotInitialized(function () { + self.logError(error, attrs); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + if (!error) { + return; + } + if (typeof error === 'string') { + error = { + message: error + }; + } + var data = { + m: error.message ? error.message : error, + s: 'Error', + t: error.stack || null + }; + if (attrs) { + var sanitized = self._Helpers.sanitizeAttributes(attrs, data.m); + for (var prop in sanitized) { + data[prop] = sanitized[prop]; + } + } + self._Events.logEvent({ + messageType: MessageType$1.CrashReport, + name: error.name ? error.name : 'Error', + eventType: EventType.Other, + data: data + }); + }; + /** + * Logs `click` events + * @method logLink + * @param {String} selector The selector to add a 'click' event to (ex. #purchase-event) + * @param {String} [eventName] The name of the event + * @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type) + * @param {Object} [eventInfo] Attributes for the event + */ + this.logLink = function (selector, eventName, eventType, eventInfo) { + self._Events.addEventHandler('click', selector, eventName, eventInfo, eventType); + }; + /** + * Logs `submit` events + * @method logForm + * @param {String} selector The selector to add the event handler to (ex. #search-event) + * @param {String} [eventName] The name of the event + * @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type) + * @param {Object} [eventInfo] Attributes for the event + */ + this.logForm = function (selector, eventName, eventType, eventInfo) { + self._Events.addEventHandler('submit', selector, eventName, eventInfo, eventType); + }; + /** + * Logs a page view + * @method logPageView + * @param {String} eventName The name of the event. Defaults to 'PageView'. + * @param {Object} [attrs] Attributes for the event + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */ + this.logPageView = function (eventName, attrs, customFlags, eventOptions) { + var queued = queueIfNotInitialized(function () { + self.logPageView(eventName, attrs, customFlags, eventOptions); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + if (self._Helpers.canLog()) { + if (!self._Helpers.Validators.isStringOrNumber(eventName)) { + eventName = 'PageView'; + } + if (!attrs) { + attrs = { + hostname: window.location.hostname, + title: window.document.title + }; + } else if (!self._Helpers.isObject(attrs)) { + self.Logger.error('The attributes argument must be an object. A ' + _typeof$1(attrs) + ' was entered. Please correct and retry.'); + return; + } + if (customFlags && !self._Helpers.isObject(customFlags)) { + self.Logger.error('The customFlags argument must be an object. A ' + _typeof$1(customFlags) + ' was entered. Please correct and retry.'); + return; + } + } + self._Events.logEvent({ + messageType: MessageType$1.PageView, + name: eventName, + data: attrs, + eventType: EventType.Unknown, + customFlags: customFlags + }, eventOptions); + }; + /** + * Forces an upload of the batch + * @method upload + */ + this.upload = function () { + var _a, _b; + if (self._Helpers.canLog()) { + if (self._Store.webviewBridgeEnabled) { + self._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload); + } else { + (_b = (_a = self._APIClient) === null || _a === void 0 ? void 0 : _a.uploader) === null || _b === void 0 ? void 0 : _b.prepareAndUpload(false, false); + } + } + }; + /** + * Invoke these methods on the mParticle.Consent object. + * Example: mParticle.Consent.createConsentState() + * + * @class mParticle.Consent + */ + this.Consent = { + /** + * Creates a CCPA Opt Out Consent State. + * + * @method createCCPAConsent + * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" + * @param {Number} timestamp Unix time (likely to be Date.now()) + * @param {String} consentDocument document version or experience that the user may have consented to + * @param {String} location location where the user gave consent + * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users + * @return {Object} CCPA Consent State + */ + createCCPAConsent: self._Consent.createPrivacyConsent, + /** + * Creates a GDPR Consent State. + * + * @method createGDPRConsent + * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out" + * @param {Number} timestamp Unix time (likely to be Date.now()) + * @param {String} consentDocument document version or experience that the user may have consented to + * @param {String} location location where the user gave consent + * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users + * @return {Object} GDPR Consent State + */ + createGDPRConsent: self._Consent.createPrivacyConsent, + /** + * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states. + * + * @method createConsentState + * @return {Object} ConsentState object + */ + createConsentState: self._Consent.createConsentState + }; + /** + * Invoke these methods on the mParticle.eCommerce object. + * Example: mParticle.eCommerce.createImpresion(...) + * @class mParticle.eCommerce + */ + this.eCommerce = { + /** + * Invoke these methods on the mParticle.eCommerce.Cart object. + * Example: mParticle.eCommerce.Cart.add(...) + * @class mParticle.eCommerce.Cart + * @deprecated + */ + Cart: { + /** + * Adds a product to the cart + * @method add + * @param {Object} product The product you want to add to the cart + * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. + * @deprecated + */ + add: function add(product, logEventBoolean) { + self.Logger.warning(generateDeprecationMessage('eCommerce.Cart.add()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + }, + /** + * Removes a product from the cart + * @method remove + * @param {Object} product The product you want to add to the cart + * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs. + * @deprecated + */ + remove: function remove(product, logEventBoolean) { + self.Logger.warning(generateDeprecationMessage('eCommerce.Cart.remove()', true, 'eCommerce.logProductAction()', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + }, + /** + * Clears the cart + * @method clear + * @deprecated + */ + clear: function clear() { + self.Logger.warning(generateDeprecationMessage('eCommerce.Cart.clear()', true, '', 'https://docs.mparticle.com/developers/sdk/web/commerce-tracking')); + } + }, + /** + * Sets the currency code + * @for mParticle.eCommerce + * @method setCurrencyCode + * @param {String} code The currency code + */ + setCurrencyCode: function setCurrencyCode(code) { + var queued = queueIfNotInitialized(function () { + self.eCommerce.setCurrencyCode(code); + }, self); + if (queued) return; + if (typeof code !== 'string') { + self.Logger.error('Code must be a string'); + return; + } + self._SessionManager.resetSessionTimer(); + self._Store.currencyCode = code; + }, + /** + * Creates a product + * @for mParticle.eCommerce + * @method createProduct + * @param {String} name product name + * @param {String} sku product sku + * @param {Number} price product price + * @param {Number} [quantity] product quantity. If blank, defaults to 1. + * @param {String} [variant] product variant + * @param {String} [category] product category + * @param {String} [brand] product brand + * @param {Number} [position] product position + * @param {String} [coupon] product coupon + * @param {Object} [attributes] product attributes + */ + createProduct: function createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) { + return self._Ecommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes); + }, + /** + * Creates a promotion + * @for mParticle.eCommerce + * @method createPromotion + * @param {String} id a unique promotion id + * @param {String} [creative] promotion creative + * @param {String} [name] promotion name + * @param {Number} [position] promotion position + */ + createPromotion: function createPromotion(id, creative, name, position) { + return self._Ecommerce.createPromotion(id, creative, name, position); + }, + /** + * Creates a product impression + * @for mParticle.eCommerce + * @method createImpression + * @param {String} name impression name + * @param {Object} product the product for which an impression is being created + */ + createImpression: function createImpression(name, product) { + return self._Ecommerce.createImpression(name, product); + }, + /** + * Creates a transaction attributes object to be used with a checkout + * @for mParticle.eCommerce + * @method createTransactionAttributes + * @param {String or Number} id a unique transaction id + * @param {String} [affiliation] affilliation + * @param {String} [couponCode] the coupon code for which you are creating transaction attributes + * @param {Number} [revenue] total revenue for the product being purchased + * @param {String} [shipping] the shipping method + * @param {Number} [tax] the tax amount + */ + createTransactionAttributes: function createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax) { + return self._Ecommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax); + }, + /** + * Logs a checkout action + * @for mParticle.eCommerce + * @method logCheckout + * @param {Number} step checkout step number + * @param {String} checkout option string + * @param {Object} attrs + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */ + logCheckout: function logCheckout(step, option, attrs, customFlags) { + self.Logger.warning('mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead'); + if (!self._Store.isInitialized) { + self.ready(function () { + self.eCommerce.logCheckout(step, option, attrs, customFlags); + }); + return; + } + self._SessionManager.resetSessionTimer(); + self._Events.logCheckoutEvent(step, option, attrs, customFlags); + }, + /** + * Logs a product action + * @for mParticle.eCommerce + * @method logProductAction + * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218) + * @param {Object} product the product for which you are creating the product action + * @param {Object} [attrs] attributes related to the product action + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [transactionAttributes] Transaction Attributes for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */ + logProductAction: function logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions) { + var queued = queueIfNotInitialized(function () { + self.eCommerce.logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + self._Events.logProductActionEvent(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions); + }, + /** + * Logs a product purchase + * @for mParticle.eCommerce + * @method logPurchase + * @param {Object} transactionAttributes transactionAttributes object + * @param {Object} product the product being purchased + * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false + * @param {Object} [attrs] other attributes related to the product purchase + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */ + logPurchase: function logPurchase(transactionAttributes, product, clearCart, attrs, customFlags) { + self.Logger.warning('mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead'); + if (!self._Store.isInitialized) { + self.ready(function () { + self.eCommerce.logPurchase(transactionAttributes, product, clearCart, attrs, customFlags); + }); + return; + } + if (!transactionAttributes || !product) { + self.Logger.error(Messages.ErrorMessages.BadLogPurchase); + return; + } + self._SessionManager.resetSessionTimer(); + self._Events.logPurchaseEvent(transactionAttributes, product, attrs, customFlags); + }, + /** + * Logs a product promotion + * @for mParticle.eCommerce + * @method logPromotion + * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279) + * @param {Object} promotion promotion object + * @param {Object} [attrs] boolean to clear the cart after logging or not + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */ + logPromotion: function logPromotion(type, promotion, attrs, customFlags, eventOptions) { + var queued = queueIfNotInitialized(function () { + self.eCommerce.logPromotion(type, promotion, attrs, customFlags, eventOptions); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + self._Events.logPromotionEvent(type, promotion, attrs, customFlags, eventOptions); + }, + /** + * Logs a product impression + * @for mParticle.eCommerce + * @method logImpression + * @param {Object} impression product impression object + * @param {Object} attrs attributes related to the impression log + * @param {Object} [customFlags] Custom flags for the event + * @param {Object} [eventOptions] For Event-level Configuration Options + */ + logImpression: function logImpression(impression, attrs, customFlags, eventOptions) { + var queued = queueIfNotInitialized(function () { + self.eCommerce.logImpression(impression, attrs, customFlags, eventOptions); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + self._Events.logImpressionEvent(impression, attrs, customFlags, eventOptions); + }, + /** + * Logs a refund + * @for mParticle.eCommerce + * @method logRefund + * @param {Object} transactionAttributes transaction attributes related to the refund + * @param {Object} product product being refunded + * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false. + * @param {Object} [attrs] attributes related to the refund + * @param {Object} [customFlags] Custom flags for the event + * @deprecated + */ + logRefund: function logRefund(transactionAttributes, product, clearCart, attrs, customFlags) { + self.Logger.warning('mParticle.logRefund is deprecated, please use mParticle.logProductAction instead'); + if (!self._Store.isInitialized) { + self.ready(function () { + self.eCommerce.logRefund(transactionAttributes, product, clearCart, attrs, customFlags); + }); + return; + } + self._SessionManager.resetSessionTimer(); + self._Events.logRefundEvent(transactionAttributes, product, attrs, customFlags); + }, + expandCommerceEvent: function expandCommerceEvent(event) { + return self._Ecommerce.expandCommerceEvent(event); + } + }; + /** + * Sets a session attribute + * @method setSessionAttribute + * @param {String} key key for session attribute + * @param {String or Number} value value for session attribute + */ + this.setSessionAttribute = function (key, value) { + var _a; + var skipQueue = ((_a = self._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(self._Store); + if (!skipQueue) { + var queued = queueIfNotInitialized(function () { + self.setSessionAttribute(key, value); + }, self); + if (queued) return; + } + // Logs to cookie + // And logs to in-memory object + // Example: mParticle.setSessionAttribute('location', '33431'); + if (self._Helpers.canLog()) { + if (!self._Helpers.Validators.isValidAttributeValue(value)) { + self.Logger.error(Messages.ErrorMessages.BadAttribute); + return; + } + if (!self._Helpers.Validators.isValidKeyValue(key)) { + self.Logger.error(Messages.ErrorMessages.BadKey); + return; + } + if (self._Store.webviewBridgeEnabled) { + self._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ + key: key, + value: value + })); + } else { + var existingProp = self._Helpers.findKeyInObject(self._Store.sessionAttributes, key); + if (existingProp) { + key = existingProp; + } + self._Store.sessionAttributes[key] = value; + self._Persistence.update(); + self._Forwarders.applyToForwarders('setSessionAttribute', [key, value]); + } + } + }; + /** + * Set opt out of logging + * @method setOptOut + * @param {Boolean} isOptingOut boolean to opt out or not. When set to true, opt out of logging. + */ + this.setOptOut = function (isOptingOut) { + var queued = queueIfNotInitialized(function () { + self.setOptOut(isOptingOut); + }, self); + if (queued) return; + self._SessionManager.resetSessionTimer(); + self._Store.isEnabled = !isOptingOut; + self._Events.logOptOut(); + self._Persistence.update(); + if (self._Store.activeForwarders.length) { + self._Store.activeForwarders.forEach(function (forwarder) { + if (forwarder.setOptOut) { + var result = forwarder.setOptOut(isOptingOut); + if (result) { + self.Logger.verbose(result); + } + } + }); + } + }; + /** + * Set or remove the integration attributes for a given integration ID. + * Integration attributes are keys and values specific to a given integration. For example, + * many integrations have their own internal user/device ID. mParticle will store integration attributes + * for a given device, and will be able to use these values for server-to-server communication to services. + * This is often useful when used in combination with a server-to-server feed, allowing the feed to be enriched + * with the necessary integration attributes to be properly forwarded to the given integration. + * @method setIntegrationAttribute + * @param {Number} integrationId mParticle integration ID + * @param {Object} attrs a map of attributes that will replace any current attributes. The keys are predefined by mParticle. + * Please consult with the mParticle docs or your solutions consultant for the correct value. You may + * also pass a null or empty map here to remove all of the attributes. + */ + this.setIntegrationAttribute = function (integrationId, attrs) { + var queued = queueIfNotInitialized(function () { + self.setIntegrationAttribute(integrationId, attrs); + }, self); + if (queued) return; + if (typeof integrationId !== 'number') { + self.Logger.error('integrationId must be a number'); + return; + } + if (attrs === null) { + self._Store.integrationAttributes[integrationId] = {}; + } else if (self._Helpers.isObject(attrs)) { + if (Object.keys(attrs).length === 0) { + self._Store.integrationAttributes[integrationId] = {}; + } else { + for (var key in attrs) { + if (typeof key === 'string') { + if (typeof attrs[key] === 'string') { + if (self._Helpers.isObject(self._Store.integrationAttributes[integrationId])) { + self._Store.integrationAttributes[integrationId][key] = attrs[key]; + } else { + self._Store.integrationAttributes[integrationId] = {}; + self._Store.integrationAttributes[integrationId][key] = attrs[key]; + } + } else { + self.Logger.error('Values for integration attributes must be strings. You entered a ' + _typeof$1(attrs[key])); + continue; + } + } else { + self.Logger.error('Keys must be strings, you entered a ' + _typeof$1(key)); + continue; + } + } + } + } else { + self.Logger.error('Attrs must be an object with keys and values. You entered a ' + _typeof$1(attrs)); + return; + } + self._Persistence.update(); + }; + /** + * Get integration attributes for a given integration ID. + * @method getIntegrationAttributes + * @param {Number} integrationId mParticle integration ID + * @return {Object} an object map of the integrationId's attributes + */ + this.getIntegrationAttributes = function (integrationId) { + if (self._Store.integrationAttributes[integrationId]) { + return self._Store.integrationAttributes[integrationId]; + } else { + return {}; + } + }; + // Used by our forwarders + this.addForwarder = function (forwarder) { + self._preInit.forwarderConstructors.push(forwarder); + }; + this.configurePixel = function (settings) { + self._Forwarders.configurePixel(settings); + }; + this._getActiveForwarders = function () { + return self._Store.activeForwarders; + }; + this._getIntegrationDelays = function () { + return self._preInit.integrationDelays; + }; + /* + An integration delay is a workaround that prevents events from being sent when it is necessary to do so. + Some server side integrations require a client side value to be included in the payload to successfully + forward. This value can only be pulled from the client side partner SDK. + During the kit initialization, the kit: + * sets an integration delay to `true` + * grabs the required value from the partner SDK, + * sets it via `setIntegrationAttribute` + * sets the integration delay to `false` + The core SDK can then read via `isDelayedByIntegration` to no longer delay sending events. + This integration attribute is now on the batch payload for the server side to read. + If there is no delay, then the events sent before an integration attribute is included would not + be forwarded successfully server side. + */ + this._setIntegrationDelay = function (module, shouldDelayIntegration) { + self._preInit.integrationDelays[module] = shouldDelayIntegration; + // If the integration delay is set to true, no further action needed + if (shouldDelayIntegration === true) { + return; + } + // If the integration delay is set to false, check to see if there are any + // other integration delays set to true. It not, process the queued events/. + var integrationDelaysKeys = Object.keys(self._preInit.integrationDelays); + if (integrationDelaysKeys.length === 0) { + return; + } + var hasIntegrationDelays = integrationDelaysKeys.some(function (integration) { + return self._preInit.integrationDelays[integration] === true; + }); + if (!hasIntegrationDelays) { + self._APIClient.processQueuedEvents(); + } + }; + // Internal use only. Used by our wrapper SDKs to identify themselves during initialization. + this._setWrapperSDKInfo = function (name, version) { + var queued = queueIfNotInitialized(function () { + self._setWrapperSDKInfo(name, version); + }, self); + if (queued) return; + if (self._Store.wrapperSDKInfo === undefined || !self._Store.wrapperSDKInfo.isInfoSet) { + self._Store.wrapperSDKInfo = { + name: name, + version: version, + isInfoSet: true + }; + } + }; + this.registerErrorReportingService = function (service) { + self._ErrorReportingDispatcher.register(service); + }; + this.registerLoggingService = function (service) { + self._LoggingDispatcher.register(service); + }; + var launcherInstanceGuidKey = Constants.Rokt.LauncherInstanceGuidKey; + this.setLauncherInstanceGuid = function () { + if (!window[launcherInstanceGuidKey] || typeof window[launcherInstanceGuidKey] !== 'string') { + window[launcherInstanceGuidKey] = self._Helpers.generateUniqueId(); + } + }; + this.getLauncherInstanceGuid = function () { + return window[launcherInstanceGuidKey]; + }; + this.captureTiming = function (metricsName) { + var _a; + if (typeof window !== 'undefined' && ((_a = window.performance) === null || _a === void 0 ? void 0 : _a.mark)) { + window.performance.mark(metricsName); + } + }; + } + // Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment + function completeSDKInitialization(apiKey, config, mpInstance) { + var _a, _b; + var kitBlocker = createKitBlocker(config, mpInstance); + var getFeatureFlag = mpInstance._Helpers.getFeatureFlag; + mpInstance._APIClient = new APIClient(mpInstance, kitBlocker); + mpInstance._Forwarders = new Forwarders(mpInstance, kitBlocker); + mpInstance._Store.processConfig(config); + mpInstance._Identity.idCache = createIdentityCache(mpInstance); + removeExpiredIdentityCacheDates(mpInstance._Identity.idCache); + // Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's + // Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not + // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize + // persistence or Identity directly. + if (mpInstance._Store.webviewBridgeEnabled) { + mpInstance._NativeSdkHelpers.initializeSessionAttributes(apiKey); + } else { + // Main SDK initialization flow + // Load any settings/identities/attributes from cookie or localStorage + mpInstance._Persistence.initializeStorage(); + mpInstance._Store.syncPersistenceData(); + // Set up user identitiy variables for later use + var currentUser = mpInstance.Identity.getCurrentUser(); + var currentUserMPID = currentUser ? currentUser.getMPID() : null; + var currentUserIdentities = currentUser ? currentUser.getUserIdentities().userIdentities : {}; + mpInstance._Store.SDKConfig.identifyRequest = mpInstance._Store.hasInvalidIdentifyRequest() ? { + userIdentities: currentUserIdentities + } : mpInstance._Store.SDKConfig.identifyRequest; + if (getFeatureFlag(ReportBatching)) { + mpInstance._ForwardingStatsUploader.startForwardingStatsTimer(); + } + // https://go.mparticle.com/work/SQDSDKS-7639 + var integrationSpecificIds = getFeatureFlag(CaptureIntegrationSpecificIds); + var integrationSpecificIdsV2 = getFeatureFlag(CaptureIntegrationSpecificIdsV2); + var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; + if (isIntegrationCaptureEnabled) { + var captureMode = void 0; + if (integrationSpecificIds || integrationSpecificIdsV2 === CaptureIntegrationSpecificIdsV2Modes.All) { + captureMode = 'all'; + } else if (integrationSpecificIdsV2 === CaptureIntegrationSpecificIdsV2Modes.RoktOnly) { + captureMode = 'roktonly'; + } + mpInstance._IntegrationCapture = new IntegrationCapture(captureMode); + mpInstance._IntegrationCapture.capture(); + } + // Configure Rokt Manager with user and filtered user + var roktConfig = parseConfig(config, 'Rokt', 181); + if (roktConfig) { + var accountId = (_a = roktConfig.settings) === null || _a === void 0 ? void 0 : _a.accountId; + mpInstance._Store.setRoktAccountId(accountId); + var userAttributeFilters = roktConfig.userAttributeFilters; + var roktFilteredUser = filteredMparticleUser(currentUserMPID, { + userAttributeFilters: userAttributeFilters + }, mpInstance); + var roktOptions = { + sandbox: config === null || config === void 0 ? void 0 : config.isDevelopmentMode, + launcherOptions: config === null || config === void 0 ? void 0 : config.launcherOptions, + domain: config === null || config === void 0 ? void 0 : config.domain + }; + // https://go.mparticle.com/work/SQDSDKS-7339 + mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance._Store, mpInstance.Logger, roktOptions, mpInstance.captureTiming); + } + mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats); + mpInstance._Forwarders.processPixelConfigs(config); + // Checks if session is created, resumed, or needs to be ended + // Logs a session start or session end event accordingly + mpInstance._SessionManager.initialize(); + mpInstance._Events.logAST(); + processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities); + } + // We will continue to clear out the ready queue as part of the initial init flow + // if an identify request is unnecessary, such as if there is an existing session + if (mpInstance._Store.mpid && !mpInstance._Store.identifyCalled || mpInstance._Store.webviewBridgeEnabled) { + mpInstance._Store.isInitialized = true; + mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue); + } + // For noFunctional sessions with no identity, drain any pre-init ready callbacks + // that were queued before _CookieConsentManager was available to evaluate the condition. + (_b = mpInstance.processQueueOnNoFunctional) === null || _b === void 0 ? void 0 : _b.call(mpInstance); + // https://go.mparticle.com/work/SQDSDKS-6040 + if (mpInstance._Store.isFirstRun) { + mpInstance._Store.isFirstRun = false; + } + } + // https://go.mparticle.com/work/SQDSDKS-7061 + function createKitBlocker(config, mpInstance) { + var kitBlocker; + var dataPlanForKitBlocker; + var kitBlockError; + var kitBlockOptions; + /* There are three ways a data plan object for blocking can be passed to the SDK: + 1. Manually via config.dataPlanOptions (this takes priority) + If not passed in manually, we user the server provided via either + 2. Snippet via /mparticle.js endpoint (config.dataPlan.document) + 3. Self hosting via /config endpoint (config.dataPlanResult) + */ + if (config.dataPlanOptions) { + mpInstance.Logger.verbose('Customer provided data plan found'); + kitBlockOptions = config.dataPlanOptions; + dataPlanForKitBlocker = { + document: { + dtpn: { + vers: kitBlockOptions.dataPlanVersion, + blok: { + ev: kitBlockOptions.blockEvents, + ea: kitBlockOptions.blockEventAttributes, + ua: kitBlockOptions.blockUserAttributes, + id: kitBlockOptions.blockUserIdentities + } + } + } + }; + } + if (!dataPlanForKitBlocker) { + // config.dataPlan.document returns on /mparticle.js endpoint + if (config.dataPlan && config.dataPlan.document) { + if (config.dataPlan.document.error_message) { + kitBlockError = config.dataPlan.document.error_message; + } else { + mpInstance.Logger.verbose('Data plan found from mParticle.js'); + dataPlanForKitBlocker = config.dataPlan; + } + } + // config.dataPlanResult returns on /config endpoint + else if (config.dataPlanResult) { + if (config.dataPlanResult.error_message) { + kitBlockError = config.dataPlanResult.error_message; + } else { + mpInstance.Logger.verbose('Data plan found from /config'); + dataPlanForKitBlocker = { + document: config.dataPlanResult + }; + } + } + } + if (kitBlockError) { + mpInstance.Logger.error(kitBlockError); + } + if (dataPlanForKitBlocker) { + kitBlocker = new KitBlocker(dataPlanForKitBlocker, mpInstance); + } + return kitBlocker; + } + function createIdentityCache(mpInstance) { + var _a; + // Identity expects mpInstance._Identity.idCache to always exist. DisabledVault + // ensures no identity response data is written to localStorage when noFunctional is true + if ((_a = mpInstance._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) { + return new DisabledVault("".concat(mpInstance._Store.storageName, "-id-cache"), { + logger: mpInstance.Logger + }); + } + return new LocalStorageVault("".concat(mpInstance._Store.storageName, "-id-cache"), { + logger: mpInstance.Logger + }); + } + function runPreConfigFetchInitialization(mpInstance, apiKey, config) { + var _a; + mpInstance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); + mpInstance._LoggingDispatcher = new LoggingDispatcher(); + mpInstance.Logger = new Logger(config); + mpInstance._Store = new Store(config, mpInstance, apiKey); + window.mParticle.Store = mpInstance._Store; + mpInstance.Logger.verbose(StartingInitialization); + // Initialize CookieConsentManager with privacy flags from launcherOptions + var _b = (_a = config === null || config === void 0 ? void 0 : config.launcherOptions) !== null && _a !== void 0 ? _a : {}, + noFunctional = _b.noFunctional, + noTargeting = _b.noTargeting; + mpInstance._CookieConsentManager = new CookieConsentManager({ + noFunctional: noFunctional, + noTargeting: noTargeting + }); + // Check to see if localStorage is available before main configuration runs + // since we will need this for the current implementation of user persistence + // TODO: Refactor this when we refactor User Identity Persistence + try { + mpInstance._Store.isLocalStorageAvailable = mpInstance._Persistence.determineLocalStorageAvailability(window.localStorage); + } catch (e) { + mpInstance.Logger.warning('localStorage is not available, using cookies if available'); + mpInstance._Store.isLocalStorageAvailable = false; + } + } + function processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities) { + // https://go.mparticle.com/work/SQDSDKS-6323 + // Call mParticle._Store.SDKConfig.identityCallback when identify was not called + // due to a reload or a sessionId already existing + // Any identity callback should always be ran regardless if an identity call + // is made + if (!mpInstance._Store.identifyCalled && mpInstance._Store.SDKConfig.identityCallback && currentUser && currentUserMPID) { + mpInstance._Store.SDKConfig.identityCallback({ + httpCode: HTTPCodes.activeSession, + getUser: function getUser() { + return mpInstance._Identity.mParticleUser(currentUserMPID); + }, + getPreviousUser: function getPreviousUser() { + var users = mpInstance.Identity.getUsers(); + var mostRecentUser = users.shift(); + var mostRecentUserMPID = mostRecentUser.getMPID(); + if (mostRecentUser && mostRecentUserMPID === currentUserMPID) { + mostRecentUser = users.shift(); + } + return mostRecentUser || null; + }, + body: { + mpid: currentUserMPID, + is_logged_in: mpInstance._Store.isLoggedIn, + matched_identities: currentUserIdentities, + context: null, + is_ephemeral: false + } + }); + } + } + function queueIfNotInitialized(func, self) { + var _a, _b; + // When noFunctional is true with no explicit identifier, the SDK will never + // receive an MPID. Let these calls through so events can still reach forwarders immediately. + // sendEventToServer handles queuing for the MP server upload path separately. + var noFunctionalWithoutId = ((_a = self._CookieConsentManager) === null || _a === void 0 ? void 0 : _a.getNoFunctional()) && !hasExplicitIdentifier(self._Store); + if (((_b = self._Store) === null || _b === void 0 ? void 0 : _b.isInitialized) || noFunctionalWithoutId) { + return false; + } + self._preInit.readyQueue.push(function () { + var _a; + if ((_a = self._Store) === null || _a === void 0 ? void 0 : _a.isInitialized) { + func(); + } + }); + return true; + } + + // This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise! + var mockFunction = function mockFunction() { + return null; + }; + var _BatchValidator = /** @class */function () { + function _BatchValidator() {} + _BatchValidator.prototype.getMPInstance = function () { + return { + // Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method + _Helpers: { + sanitizeAttributes: window.mParticle.getInstance()._Helpers.sanitizeAttributes, + generateHash: function generateHash() { + return 'mockHash'; + }, + generateUniqueId: function generateUniqueId() { + return 'mockId'; + }, + extend: window.mParticle.getInstance()._Helpers.extend, + createServiceUrl: mockFunction, + parseNumber: mockFunction, + isObject: mockFunction, + Validators: null + }, + _resetForTests: mockFunction, + _APIClient: null, + _timeOnSiteTimer: { + getTimeInForeground: mockFunction + }, + MPSideloadedKit: null, + _Consent: null, + _Events: null, + _Forwarders: null, + _NativeSdkHelpers: null, + _Persistence: null, + _preInit: null, + Consent: null, + _ServerModel: null, + _SessionManager: null, + _Store: { + sessionId: 'mockSessionId', + sideloadedKits: [], + devToken: 'test_dev_token', + isFirstRun: true, + isEnabled: true, + sessionAttributes: {}, + currentSessionMPIDs: [], + consentState: null, + clientId: null, + deviceId: null, + serverSettings: {}, + dateLastEventSent: null, + sessionStartDate: null, + currentPosition: null, + isTracking: false, + watchPositionId: null, + cartProducts: [], + eventQueue: [], + currencyCode: null, + globalTimer: null, + context: null, + configurationLoaded: false, + identityCallInFlight: false, + nonCurrentUserMPIDs: {}, + identifyCalled: false, + isLoggedIn: false, + cookieSyncDates: {}, + integrationAttributes: {}, + requireDelay: true, + isLocalStorageAvailable: null, + integrationDelayTimeoutStart: null, + storageName: null, + prodStorageName: null, + activeForwarders: [], + kits: {}, + configuredForwarders: [], + pixelConfigurations: [], + wrapperSDKInfo: { + name: 'none', + version: null, + isInfoSet: false + }, + SDKConfig: { + isDevelopmentMode: false, + onCreateBatch: mockFunction + } + }, + config: null, + eCommerce: null, + Identity: { + getCurrentUser: mockFunction, + IdentityAPI: {}, + identify: mockFunction, + login: mockFunction, + logout: mockFunction, + modify: mockFunction + }, + Logger: { + verbose: mockFunction, + error: mockFunction, + warning: mockFunction + }, + ProductActionType: null, + ServerModel: null, + addForwarder: mockFunction, + generateHash: mockFunction, + getAppVersion: mockFunction, + getAppName: mockFunction, + getInstance: mockFunction, + getDeviceId: mockFunction, + init: mockFunction, + logBaseEvent: mockFunction, + logEvent: mockFunction, + logLevel: 'none', + setPosition: mockFunction, + upload: mockFunction + }; + }; + _BatchValidator.prototype.createSDKEventFunction = function (event) { + return new ServerModel(this.getMPInstance()).createEventObject(event); + }; + _BatchValidator.prototype.returnBatch = function (events) { + var _this = this; + var mpInstance = this.getMPInstance(); + var sdkEvents = Array.isArray(events) ? events.map(function (event) { + return _this.createSDKEventFunction(event); + }) : [this.createSDKEventFunction(events)]; + var batch = convertEvents('0', sdkEvents, mpInstance); + return batch; + }; + return _BatchValidator; + }(); + + var MPSideloadedKit = /** @class */function () { + function MPSideloadedKit(unregisteredKitInstance) { + this.filterDictionary = { + eventTypeFilters: [], + eventNameFilters: [], + screenNameFilters: [], + screenAttributeFilters: [], + userIdentityFilters: [], + userAttributeFilters: [], + attributeFilters: [], + consentRegulationFilters: [], + consentRegulationPurposeFilters: [], + messageTypeFilters: [], + messageTypeStateFilters: [], + // The below filtering members are optional, but we instantiate them + // to simplify public method assignment + filteringEventAttributeValue: {}, + filteringUserAttributeValue: {}, + filteringConsentRuleValues: {} + }; + this.kitInstance = unregisteredKitInstance; + } + MPSideloadedKit.prototype.addEventTypeFilter = function (eventType) { + var hashedEventType = KitFilterHelper.hashEventType(eventType); + this.filterDictionary.eventTypeFilters.push(hashedEventType); + }; + MPSideloadedKit.prototype.addEventNameFilter = function (eventType, eventName) { + var hashedEventName = KitFilterHelper.hashEventName(eventName, eventType); + this.filterDictionary.eventNameFilters.push(hashedEventName); + }; + MPSideloadedKit.prototype.addEventAttributeFilter = function (eventType, eventName, customAttributeKey) { + var hashedEventAttribute = KitFilterHelper.hashEventAttributeKey(eventType, eventName, customAttributeKey); + this.filterDictionary.attributeFilters.push(hashedEventAttribute); + }; + MPSideloadedKit.prototype.addScreenNameFilter = function (screenName) { + var hashedScreenName = KitFilterHelper.hashEventName(screenName, EventType.Unknown); + this.filterDictionary.screenNameFilters.push(hashedScreenName); + }; + MPSideloadedKit.prototype.addScreenAttributeFilter = function (screenName, screenAttribute) { + var hashedScreenAttribute = KitFilterHelper.hashEventAttributeKey(EventType.Unknown, screenName, screenAttribute); + this.filterDictionary.screenAttributeFilters.push(hashedScreenAttribute); + }; + MPSideloadedKit.prototype.addUserIdentityFilter = function (userIdentity) { + var hashedIdentityType = KitFilterHelper.hashUserIdentity(userIdentity); + this.filterDictionary.userIdentityFilters.push(hashedIdentityType); + }; + MPSideloadedKit.prototype.addUserAttributeFilter = function (userAttributeKey) { + var hashedUserAttributeKey = KitFilterHelper.hashUserAttribute(userAttributeKey); + this.filterDictionary.userAttributeFilters.push(hashedUserAttributeKey); + }; + return MPSideloadedKit; + }(); + + if (!Array.prototype.forEach) { + Array.prototype.forEach = Polyfill.forEach; + } + if (!Array.prototype.map) { + Array.prototype.map = Polyfill.map; + } + if (!Array.prototype.filter) { + Array.prototype.filter = Polyfill.filter; + } + // https://go.mparticle.com/work/SQDSDKS-6768 + if (!Array.isArray) { + // @ts-ignore + Array.prototype.isArray = Polyfill.isArray; + } + function mParticleInstanceManager() { + var self = this; + // Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing + this.Store = {}; + this._instances = {}; + this.IdentityType = IdentityType; + this.EventType = EventType; + this.CommerceEventType = CommerceEventType; + this.PromotionType = PromotionActionType; + this.ProductActionType = ProductActionType; + this.MPSideloadedKit = MPSideloadedKit; + if (typeof window !== 'undefined') { + this.isIOS = window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false; + this.config = window.mParticle && window.mParticle.config ? window.mParticle.config : {}; + } + /** + * Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used. + *

+ * If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below. + * @method init + * @param {String} apiKey your mParticle assigned API key + * @param {Object} [config] an options object for additional configuration + * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. + */ + this.init = function (apiKey, config, instanceName) { + if (!config && window.mParticle && window.mParticle.config) { + console.warn('You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly'); + config = window.mParticle ? window.mParticle.config : {}; + } + instanceName = (!instanceName || instanceName.length === 0 ? Constants.DefaultInstance : instanceName).toLowerCase(); + var client = self._instances[instanceName]; + if (client === undefined) { + client = new mParticleInstance(instanceName); + self._instances[instanceName] = client; + } + client.captureTiming(PerformanceMarkType.SdkStart); + client.setLauncherInstanceGuid(); + client.init(apiKey, config, instanceName); + }; + this.captureTiming = function (metricsName) { + self.getInstance().captureTiming(metricsName); + }; + this.getInstance = function getInstance(instanceName) { + var client; + if (!instanceName) { + instanceName = Constants.DefaultInstance; + client = self._instances[instanceName]; + if (!client) { + client = new mParticleInstance(instanceName); + self._instances[Constants.DefaultInstance] = client; + } + return client; + } else { + client = self._instances[instanceName.toLowerCase()]; + if (!client) { + console.log('You tried to initialize an instance named ' + instanceName + '. This instance does not exist. Check your instance name or initialize a new instance with this name before calling it.'); + return null; + } + return client; + } + }; + this.Rokt = self.getInstance()._RoktManager; + this.getDeviceId = function () { + return self.getInstance().getDeviceId(); + }; + this.setDeviceId = function (guid) { + return self.getInstance().setDeviceId(guid); + }; + this.isInitialized = function () { + return self.getInstance().isInitialized(); + }; + this.startNewSession = function () { + self.getInstance().startNewSession(); + }; + this.endSession = function () { + self.getInstance().endSession(); + }; + this.setLogLevel = function (newLogLevel) { + self.getInstance().setLogLevel(newLogLevel); + }; + this.ready = function (argument) { + self.getInstance().ready(argument); + }; + this.setAppVersion = function (version) { + self.getInstance().setAppVersion(version); + }; + this.getAppName = function () { + return self.getInstance().getAppName(); + }; + this.setAppName = function (name) { + self.getInstance().setAppName(name); + }; + this.getAppVersion = function () { + return self.getInstance().getAppVersion(); + }; + this.getEnvironment = function () { + return self.getInstance().getEnvironment(); + }; + this.stopTrackingLocation = function () { + self.getInstance().stopTrackingLocation(); + }; + this.startTrackingLocation = function (callback) { + self.getInstance().startTrackingLocation(callback); + }; + this.setPosition = function (lat, lng) { + self.getInstance().setPosition(lat, lng); + }; + this.logBaseEvent = function (event, eventOptions) { + self.getInstance().logBaseEvent(event, eventOptions); + }; + this.logEvent = function (eventName, eventType, eventInfo, customFlags, eventOptions) { + self.getInstance().logEvent(eventName, eventType, eventInfo, customFlags, eventOptions); + }; + this.logError = function (error, attrs) { + self.getInstance().logError(error, attrs); + }; + this.logLink = function (selector, eventName, eventType, eventInfo) { + self.getInstance().logLink(selector, eventName, eventType, eventInfo); + }; + this.logForm = function (selector, eventName, eventType, eventInfo) { + self.getInstance().logForm(selector, eventName, eventType, eventInfo); + }; + this.logPageView = function (eventName, attrs, customFlags, eventOptions) { + self.getInstance().logPageView(eventName, attrs, customFlags, eventOptions); + }; + this.upload = function () { + self.getInstance().upload(); + }; + this.eCommerce = { + Cart: { + add: function add(product, logEventBoolean) { + self.getInstance().eCommerce.Cart.add(product, logEventBoolean); + }, + remove: function remove(product, logEventBoolean) { + self.getInstance().eCommerce.Cart.remove(product, logEventBoolean); + }, + clear: function clear() { + self.getInstance().eCommerce.Cart.clear(); + } + }, + setCurrencyCode: function setCurrencyCode(code) { + self.getInstance().eCommerce.setCurrencyCode(code); + }, + createProduct: function createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) { + return self.getInstance().eCommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes); + }, + createPromotion: function createPromotion(id, creative, name, position) { + return self.getInstance().eCommerce.createPromotion(id, creative, name, position); + }, + createImpression: function createImpression(name, product) { + return self.getInstance().eCommerce.createImpression(name, product); + }, + createTransactionAttributes: function createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax) { + return self.getInstance().eCommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax); + }, + logCheckout: function logCheckout(step, options, attrs, customFlags) { + self.getInstance().eCommerce.logCheckout(step, options, attrs, customFlags); + }, + logProductAction: function logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions) { + self.getInstance().eCommerce.logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions); + }, + logPurchase: function logPurchase(transactionAttributes, product, clearCart, attrs, customFlags) { + self.getInstance().eCommerce.logPurchase(transactionAttributes, product, clearCart, attrs, customFlags); + }, + logPromotion: function logPromotion(type, promotion, attrs, customFlags, eventOptions) { + self.getInstance().eCommerce.logPromotion(type, promotion, attrs, customFlags, eventOptions); + }, + logImpression: function logImpression(impression, attrs, customFlags, eventOptions) { + self.getInstance().eCommerce.logImpression(impression, attrs, customFlags, eventOptions); + }, + logRefund: function logRefund(transactionAttributes, product, clearCart, attrs, customFlags) { + self.getInstance().eCommerce.logRefund(transactionAttributes, product, clearCart, attrs, customFlags); + }, + expandCommerceEvent: function expandCommerceEvent(event) { + return self.getInstance().eCommerce.expandCommerceEvent(event); + } + }; + this.setSessionAttribute = function (key, value) { + self.getInstance().setSessionAttribute(key, value); + }; + this.setOptOut = function (isOptingOut) { + self.getInstance().setOptOut(isOptingOut); + }; + this.setIntegrationAttribute = function (integrationId, attrs) { + self.getInstance().setIntegrationAttribute(integrationId, attrs); + }; + this.getIntegrationAttributes = function (moduleId) { + return self.getInstance().getIntegrationAttributes(moduleId); + }; + this.Identity = { + HTTPCodes: Constants.HTTPCodes, + aliasUsers: function aliasUsers(aliasRequest, callback) { + self.getInstance().Identity.aliasUsers(aliasRequest, callback); + }, + createAliasRequest: function createAliasRequest(sourceUser, destinationUser, scope) { + return self.getInstance().Identity.createAliasRequest(sourceUser, destinationUser, scope); + }, + getCurrentUser: function getCurrentUser() { + return self.getInstance().Identity.getCurrentUser(); + }, + getUser: function getUser(mpid) { + return self.getInstance().Identity.getUser(mpid); + }, + getUsers: function getUsers() { + return self.getInstance().Identity.getUsers(); + }, + identify: function identify(identityApiData, callback) { + self.getInstance().Identity.identify(identityApiData, callback); + }, + login: function login(identityApiData, callback) { + self.getInstance().Identity.login(identityApiData, callback); + }, + logout: function logout(identityApiData, callback) { + self.getInstance().Identity.logout(identityApiData, callback); + }, + modify: function modify(identityApiData, callback) { + self.getInstance().Identity.modify(identityApiData, callback); + } + }; + this.sessionManager = { + getSession: function getSession() { + return self.getInstance()._SessionManager.getSession(); + } + }; + this.Consent = { + createConsentState: function createConsentState() { + return self.getInstance().Consent.createConsentState(); + }, + createGDPRConsent: function createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId) { + return self.getInstance().Consent.createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId); + }, + createCCPAConsent: function createCCPAConsent(consented, timestamp, consentDocument, location, hardwareId) { + return self.getInstance().Consent.createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId); + } + }; + this.reset = function () { + self.getInstance().reset(self.getInstance()); + }; + this._resetForTests = function (MPConfig, keepPersistence) { + if (typeof keepPersistence === 'boolean') { + self.getInstance()._resetForTests(MPConfig, keepPersistence, self.getInstance()); + } else { + self.getInstance()._resetForTests(MPConfig, false, self.getInstance()); + } + }; + this.configurePixel = function (settings) { + self.getInstance().configurePixel(settings); + }; + this._setIntegrationDelay = function (moduleId, _boolean) { + self.getInstance()._setIntegrationDelay(moduleId, _boolean); + }; + this._getIntegrationDelays = function () { + return self.getInstance()._getIntegrationDelays(); + }; + this.getVersion = function () { + return self.getInstance().getVersion(); + }; + this.generateHash = function (string) { + return self.getInstance().generateHash(string); + }; + this.addForwarder = function (forwarder) { + self.getInstance().addForwarder(forwarder); + }; + this._getActiveForwarders = function () { + return self.getInstance()._getActiveForwarders(); + }; + this._setWrapperSDKInfo = function (name, version) { + self.getInstance()._setWrapperSDKInfo(name, version); + }; + this.registerErrorReportingService = function (service) { + self.getInstance().registerErrorReportingService(service); + }; + this.registerLoggingService = function (service) { + self.getInstance().registerLoggingService(service); + }; + } + var mParticleManager = new mParticleInstanceManager(); + if (typeof window !== 'undefined') { + // mParticle is the global object used to access the SDK and predates instance manager, + // when mParticle was a singleton. We now support multiple instances. Calling methods + // on mParticle directly will access the default instance, but mParticle can also be used + // as the instance manager in self hosted mode. + window.mParticle = mParticleManager; + // https://go.mparticle.com/work/SQDSDKS-5053 + window.mParticle._BatchValidator = new _BatchValidator(); + } + + return mParticleManager; + +})(); diff --git a/dist/mparticle.stub.js b/dist/mparticle.stub.js new file mode 100644 index 000000000..8275bb1d4 --- /dev/null +++ b/dist/mparticle.stub.js @@ -0,0 +1,186 @@ +var mParticle = (function () { + + let mParticle = { + endSession: voidFunction, + getAppName: returnString, + getAppVersion: returnString, + getDeviceId: returnString, + getEnvironment: returnString, + getVersion: returnString, + init: voidFunction, + logError: voidFunction, + logEvent: voidFunction, + logForm: voidFunction, + logLink: voidFunction, + logPageView: voidFunction, + ready: voidFunction, + reset: voidFunction, + _resetForTests: voidFunction, + setAppName: voidFunction, + setAppVersion: voidFunction, + setLogLevel: voidFunction, + setOptOut: voidFunction, + setPosition: voidFunction, + setSessionAttribute: voidFunction, + startNewSession: voidFunction, + startTrackingLocation: voidFunction, + stopTrackingLocation: voidFunction, + CommerceEventType: {}, + EventType: {}, + IdentityType: {}, + ProductActionType: {}, + PromotionType: {}, + eCommerce: { + createImpression: returnImpression, + createProduct: returnProduct, + createPromotion: returnPromotion, + createTransactionAttributes: returnTransactionAttributes, + logCheckout: voidFunction, + logImpression: voidFunction, + logProductAction: voidFunction, + logPromotion: voidFunction, + logPurchase: voidFunction, + logRefund: voidFunction, + setCurrencyCode: voidFunction, + Cart: new Cart(), + }, + Consent: { + createConsentState: createConsentState, + createGDPRConsent: returnGDPRConsent, + }, + Identity: { + aliasUsers: voidFunction, + createAliasRequest: createAliasRequest, + getCurrentUser: returnUser, + getUser: returnUser, + getUsers: returnUsers, + identify: voidFunction, + login: voidFunction, + logout: voidFunction, + modify: voidFunction, + }, + }; + + function voidFunction() {} + function returnString() { + return ''; + } + function returnObject() { + return {}; + } + function returnThis() { + return this; + } + function returnUser() { + return { + getUserIdentities: function() { + return { + userIdentities: {}, + }; + }, + getMPID: returnString, + setUserTag: voidFunction, + removeUserTag: voidFunction, + setUserAttribute: voidFunction, + setUserAttributes: voidFunction, + removeUserAttribute: voidFunction, + setUserAttributeList: voidFunction, + removeAllUserAttributes: voidFunction, + getUserAttributesLists: returnObject, + getAllUserAttributes: returnObject, + getCart: Cart, + getConsentState: createConsentState, + setConsentState: voidFunction, + }; + } + + function returnUsers() { + return [returnUser()]; + } + + function Cart() { + return { + add: voidFunction, + clear: voidFunction, + remove: voidFunction, + getCartProducts: function() { + return [returnProduct()]; + }, + }; + } + + function returnImpression() { + return { + Name: 'name', + Product: returnProduct(), + }; + } + + function returnProduct() { + return { + Name: 'name', + Sku: 'sku', + Price: 0, + Quantity: 0, + Brand: 'brand', + Variant: 'variant', + Category: 'category', + Position: 'position', + CouponCode: 'couponCode', + TotalAmount: 0, + Attributes: {}, + }; + } + + function returnPromotion() { + return { + Id: 'id', + Creative: 'creative', + Name: 'name', + Position: 0, + }; + } + + function returnTransactionAttributes() { + return { + Id: 'id', + Affiliation: 'affiliation', + CouponCode: 'couponCode', + Revenue: 0, + Shipping: 'shipping', + Tax: 0, + }; + } + + function returnGDPRConsent() { + return { + ConsentDocument: 'doc', + Consented: false, + HardwareId: 'id', + Location: 'location', + Timestamp: 1568648478988, + }; + } + + function createAliasRequest() { + return { + sourceMpid: 'a', + destinationMpid: 'b', + startTime: new Date().getTime(), + endTime: new Date().getTime(), + scope: 'device', + }; + } + + function createConsentState() { + return { + addGDPRConsentState: returnThis, + setGDPRConsentState: returnThis, + getGDPRConsentState: returnGDPRConsent, + removeGDPRConsentState: returnThis, + }; + } + + return mParticle; + +})(); diff --git a/dist/src/batchUploader.d.ts b/dist/src/batchUploader.d.ts new file mode 100644 index 000000000..eafd5e14b --- /dev/null +++ b/dist/src/batchUploader.d.ts @@ -0,0 +1,36 @@ +import { Batch } from '@mparticle/event-models'; +import { SDKEvent, MParticleWebSDK } from './sdkRuntimeModels'; +export declare class BatchUploader { + static readonly CONTENT_TYPE: string; + static readonly MINIMUM_INTERVAL_MILLIS: number; + uploadIntervalMillis: number; + pendingEvents: SDKEvent[]; + pendingUploads: Batch[]; + mpInstance: MParticleWebSDK; + uploadUrl: string; + batchingEnabled: boolean; + constructor(mpInstance: MParticleWebSDK, uploadInterval: number); + private addEventListeners; + private isBeaconAvailable; + queueEvent(event: SDKEvent): void; + /** + * This implements crucial logic to: + * - bucket pending events by MPID, and then by Session, and upload individual batches for each bucket. + * + * In the future this should enforce other requirements such as maximum batch size. + * + * @param sdkEvents current pending events + * @param defaultUser the user to reference for events that are missing data + */ + private static createNewUploads; + /** + * This is the main loop function: + * - take all pending events and turn them into batches + * - attempt to upload each batch + * + * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false + * @param useBeacon whether to use the beacon API - used when the page is being unloaded + */ + private prepareAndUpload; + private upload; +} diff --git a/dist/src/constants.d.ts b/dist/src/constants.d.ts new file mode 100644 index 000000000..7271faa4e --- /dev/null +++ b/dist/src/constants.d.ts @@ -0,0 +1,151 @@ +declare const Constants: { + readonly sdkVersion: string; + readonly sdkVendor: "mparticle"; + readonly platform: "web"; + readonly Messages: { + readonly ErrorMessages: { + readonly NoToken: "A token must be specified."; + readonly EventNameInvalidType: "Event name must be a valid string value."; + readonly EventDataInvalidType: "Event data must be a valid object hash."; + readonly LoggingDisabled: "Event logging is currently disabled."; + readonly CookieParseError: "Could not parse cookie"; + readonly EventEmpty: "Event object is null or undefined, cancelling send"; + readonly APIRequestEmpty: "APIRequest is null or undefined, cancelling send"; + readonly NoEventType: "Event type must be specified."; + readonly TransactionIdRequired: "Transaction ID is required"; + readonly TransactionRequired: "A transaction attributes object is required"; + readonly PromotionIdRequired: "Promotion ID is required"; + readonly BadAttribute: "Attribute value cannot be object or array"; + readonly BadKey: "Key value cannot be object or array"; + readonly BadLogPurchase: "Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"; + }; + readonly InformationMessages: { + readonly CookieSearch: "Searching for cookie"; + readonly CookieFound: "Cookie found, parsing values"; + readonly CookieNotFound: "Cookies not found"; + readonly CookieSet: "Setting cookie"; + readonly CookieSync: "Performing cookie sync"; + readonly SendBegin: "Starting to send event"; + readonly SendIdentityBegin: "Starting to send event to identity server"; + readonly SendWindowsPhone: "Sending event to Windows Phone container"; + readonly SendIOS: "Calling iOS path: "; + readonly SendAndroid: "Calling Android JS interface method: "; + readonly SendHttp: "Sending event to mParticle HTTP service"; + readonly SendAliasHttp: "Sending alias request to mParticle HTTP service"; + readonly SendIdentityHttp: "Sending event to mParticle HTTP service"; + readonly StartingNewSession: "Starting new Session"; + readonly StartingLogEvent: "Starting to log event"; + readonly StartingLogOptOut: "Starting to log user opt in/out"; + readonly StartingEndSession: "Starting to end session"; + readonly StartingInitialization: "Starting to initialize"; + readonly StartingLogCommerceEvent: "Starting to log commerce event"; + readonly StartingAliasRequest: "Starting to Alias MPIDs"; + readonly LoadingConfig: "Loading configuration options"; + readonly AbandonLogEvent: "Cannot log event, logging disabled or developer token not set"; + readonly AbandonAliasUsers: "Cannot Alias Users, logging disabled or developer token not set"; + readonly AbandonStartSession: "Cannot start session, logging disabled or developer token not set"; + readonly AbandonEndSession: "Cannot end session, logging disabled or developer token not set"; + readonly NoSessionToEnd: "Cannot end session, no active session found"; + }; + readonly ValidationMessages: { + readonly ModifyIdentityRequestUserIdentitiesPresent: "identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again"; + readonly IdentityRequesetInvalidKey: "There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again."; + readonly OnUserAliasType: "The onUserAlias value must be a function."; + readonly UserIdentities: "The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again."; + readonly UserIdentitiesInvalidKey: "There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again."; + readonly UserIdentitiesInvalidValues: "All user identity values must be strings or null. Request not sent to server. Please fix and try again."; + readonly AliasMissingMpid: "Alias Request must contain both a destinationMpid and a sourceMpid"; + readonly AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique"; + readonly AliasMissingTime: "Alias Request must have both a startTime and an endTime"; + readonly AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime"; + }; + }; + readonly NativeSdkPaths: { + readonly LogEvent: "logEvent"; + readonly SetUserTag: "setUserTag"; + readonly RemoveUserTag: "removeUserTag"; + readonly SetUserAttribute: "setUserAttribute"; + readonly RemoveUserAttribute: "removeUserAttribute"; + readonly SetSessionAttribute: "setSessionAttribute"; + readonly AddToCart: "addToCart"; + readonly RemoveFromCart: "removeFromCart"; + readonly ClearCart: "clearCart"; + readonly LogOut: "logOut"; + readonly SetUserAttributeList: "setUserAttributeList"; + readonly RemoveAllUserAttributes: "removeAllUserAttributes"; + readonly GetUserAttributesLists: "getUserAttributesLists"; + readonly GetAllUserAttributes: "getAllUserAttributes"; + readonly Identify: "identify"; + readonly Logout: "logout"; + readonly Login: "login"; + readonly Modify: "modify"; + readonly Alias: "aliasUsers"; + readonly Upload: "upload"; + }; + readonly StorageNames: { + readonly localStorageName: "mprtcl-api"; + readonly localStorageNameV3: "mprtcl-v3"; + readonly cookieName: "mprtcl-api"; + readonly cookieNameV2: "mprtcl-v2"; + readonly cookieNameV3: "mprtcl-v3"; + readonly localStorageNameV4: "mprtcl-v4"; + readonly localStorageProductsV4: "mprtcl-prodv4"; + readonly cookieNameV4: "mprtcl-v4"; + readonly currentStorageName: "mprtcl-v4"; + readonly currentStorageProductsName: "mprtcl-prodv4"; + }; + readonly DefaultConfig: { + readonly cookieDomain: any; + readonly cookieExpiration: 365; + readonly logLevel: any; + readonly timeout: 300; + readonly sessionTimeout: 30; + readonly maxProducts: 20; + readonly forwarderStatsTimeout: 5000; + readonly integrationDelayTimeout: 5000; + readonly maxCookieSize: 3000; + readonly aliasMaxWindow: 90; + readonly uploadInterval: 0; + }; + readonly DefaultUrls: { + readonly v1SecureServiceUrl: "jssdks.mparticle.com/v1/JS/"; + readonly v2SecureServiceUrl: "jssdks.mparticle.com/v2/JS/"; + readonly v3SecureServiceUrl: "jssdks.mparticle.com/v3/JS/"; + readonly configUrl: "jssdkcdns.mparticle.com/JS/v2/"; + readonly identityUrl: "identity.mparticle.com/v1/"; + readonly aliasUrl: "jssdks.mparticle.com/v1/identity/"; + }; + readonly Base64CookieKeys: { + readonly csm: 1; + readonly sa: 1; + readonly ss: 1; + readonly ua: 1; + readonly ui: 1; + readonly csd: 1; + readonly ia: 1; + readonly con: 1; + }; + readonly SDKv2NonMPIDCookieKeys: { + readonly gs: 1; + readonly cu: 1; + readonly l: 1; + readonly globalSettings: 1; + readonly currentUserMPID: 1; + }; + readonly HTTPCodes: { + readonly noHttpCoverage: -1; + readonly activeIdentityRequest: -2; + readonly activeSession: -3; + readonly validationIssue: -4; + readonly nativeIdentityRequest: -5; + readonly loggingDisabledOrMissingAPIKey: -6; + readonly tooManyRequests: 429; + }; + readonly FeatureFlags: { + readonly ReportBatching: "reportBatching"; + readonly EventsV3: "eventsV3"; + readonly EventBatchingIntervalMillis: "eventBatchingIntervalMillis"; + }; + readonly DefaultInstance: "default_instance"; +}; +export default Constants; diff --git a/dist/src/kitBlocking.d.ts b/dist/src/kitBlocking.d.ts new file mode 100644 index 000000000..40ae6250b --- /dev/null +++ b/dist/src/kitBlocking.d.ts @@ -0,0 +1,123 @@ +import { SDKEvent, MParticleWebSDK, KitBlockerDataPlan } from './sdkRuntimeModels'; +import { BaseEvent } from '@mparticle/event-models'; +import { DataPlanPoint } from '@mparticle/data-planning-models'; +export default class KitBlocker { + dataPlanMatchLookups: { + [key: string]: {}; + }; + blockEvents: boolean; + blockEventAttributes: boolean; + blockUserAttributes: boolean; + blockUserIdentities: boolean; + kitBlockingEnabled: boolean; + mpInstance: MParticleWebSDK; + constructor(dataPlan: KitBlockerDataPlan, mpInstance: MParticleWebSDK); + addToMatchLookups(point: DataPlanPoint): void; + generateMatchKey(match: any): string | null; + generateProductAttributeMatchKey(match: any): string | null; + getPlannedProperties(type: any, validator: any): boolean | { + [key: string]: true; + } | null; + getProductProperties(type: any, validator: any): boolean | { + [key: string]: true; + } | null; + getMatchKey(eventToMatch: BaseEvent): string | null; + getProductAttributeMatchKey(eventToMatch: BaseEvent): string | null; + createBlockedEvent(event: SDKEvent): SDKEvent; + transformEventAndEventAttributes(event: SDKEvent): SDKEvent; + transformProductAttributes(event: SDKEvent): SDKEvent; + transformUserAttributes(event: SDKEvent): { + DeviceId: string; + IsFirstRun: boolean; + EventName: string; + EventCategory: number; + UserAttributes?: { + [key: string]: string | string[]; + }; + UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; + SourceMessageId: string; + MPID: string; + EventAttributes?: { + [key: string]: string; + }; + SDKVersion: string; + SessionId: string; + SessionStartDate: number; + SessionLength?: number; + currentSessionMPIDs?: string[]; + Timestamp: number; + EventDataType: number; + Debug: boolean; + Location?: import("./sdkRuntimeModels").SDKGeoLocation; + OptOut?: boolean; + CustomFlags?: { + [key: string]: string; + }; + AppVersion?: string; + AppName?: string; + Package?: string; + ConsentState?: import("./sdkRuntimeModels").SDKConsentState; + IntegrationAttributes?: { + [key: string]: { + [key: string]: string; + }; + }; + ProductAction?: import("./sdkRuntimeModels").SDKProductAction; + PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; + ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; + ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; + UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; + UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; + CurrencyCode: string; + DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; + LaunchReferral?: string; + }; + isAttributeKeyBlocked(key: string): boolean; + isIdentityBlocked(key: string): boolean; + transformUserIdentities(event: SDKEvent): { + DeviceId: string; + IsFirstRun: boolean; + EventName: string; + EventCategory: number; + UserAttributes?: { + [key: string]: string | string[]; + }; + UserIdentities?: import("./sdkRuntimeModels").SDKUserIdentity[]; + SourceMessageId: string; + MPID: string; + EventAttributes?: { + [key: string]: string; + }; + SDKVersion: string; + SessionId: string; + SessionStartDate: number; + SessionLength?: number; + currentSessionMPIDs?: string[]; + Timestamp: number; + EventDataType: number; + Debug: boolean; + Location?: import("./sdkRuntimeModels").SDKGeoLocation; + OptOut?: boolean; + CustomFlags?: { + [key: string]: string; + }; + AppVersion?: string; + AppName?: string; + Package?: string; + ConsentState?: import("./sdkRuntimeModels").SDKConsentState; + IntegrationAttributes?: { + [key: string]: { + [key: string]: string; + }; + }; + ProductAction?: import("./sdkRuntimeModels").SDKProductAction; + PromotionAction?: import("./sdkRuntimeModels").SDKPromotionAction; + ProductImpressions?: import("./sdkRuntimeModels").SDKProductImpression[]; + ShoppingCart?: import("./sdkRuntimeModels").SDKShoppingCart; + UserIdentityChanges?: import("./sdkRuntimeModels").SDKUserIdentityChangeData; + UserAttributeChanges?: import("./sdkRuntimeModels").SDKUserAttributeChangeData; + CurrencyCode: string; + DataPlan?: import("./sdkRuntimeModels").SDKDataPlan; + LaunchReferral?: string; + }; +} diff --git a/dist/src/mockBatchCreator.d.ts b/dist/src/mockBatchCreator.d.ts new file mode 100644 index 000000000..2be2d9c2e --- /dev/null +++ b/dist/src/mockBatchCreator.d.ts @@ -0,0 +1,6 @@ +import { BaseEvent } from './sdkRuntimeModels'; +import * as EventsApi from '@mparticle/event-models'; +export default class _BatchValidator { + private getMPInstance; + returnBatch(event: BaseEvent): EventsApi.Batch; +} diff --git a/dist/src/sdkRuntimeModels.d.ts b/dist/src/sdkRuntimeModels.d.ts new file mode 100644 index 000000000..253e653a2 --- /dev/null +++ b/dist/src/sdkRuntimeModels.d.ts @@ -0,0 +1,303 @@ +import * as EventsApi from '@mparticle/event-models'; +import { DataPlanVersion } from '@mparticle/data-planning-models'; +export interface SDKEvent { + DeviceId: string; + IsFirstRun: boolean; + EventName: string; + EventCategory: number; + UserAttributes?: { + [key: string]: string | string[] | null; + }; + UserIdentities?: SDKUserIdentity[]; + SourceMessageId: string; + MPID: string; + EventAttributes?: { + [key: string]: string; + }; + SDKVersion: string; + SessionId: string; + SessionStartDate: number; + SessionLength?: number; + currentSessionMPIDs?: string[]; + Timestamp: number; + EventDataType: number; + Debug: boolean; + Location?: SDKGeoLocation; + OptOut?: boolean; + CustomFlags?: { + [key: string]: string; + }; + AppVersion?: string; + AppName?: string; + Package?: string; + ConsentState?: SDKConsentState; + IntegrationAttributes?: { + [key: string]: { + [key: string]: string; + }; + }; + ProductAction?: SDKProductAction; + PromotionAction?: SDKPromotionAction; + ProductImpressions?: SDKProductImpression[]; + ShoppingCart?: SDKShoppingCart; + UserIdentityChanges?: SDKUserIdentityChangeData; + UserAttributeChanges?: SDKUserAttributeChangeData; + CurrencyCode: string; + DataPlan?: SDKDataPlan; + LaunchReferral?: string; +} +export interface SDKGeoLocation { + lat: number | string; + lng: number | string; +} +export interface SDKDataPlan { + PlanVersion?: number | null; + PlanId?: string | null; +} +export interface SDKUserIdentity { + Identity?: string; + Type: number; +} +export interface SDKShoppingCart { + ProductList?: SDKProduct[]; +} +export interface SDKPromotionAction { + PromotionActionType: string; + PromotionList?: SDKPromotion[]; +} +export interface SDKPromotion { + Id?: string; + Name?: string; + Creative?: string; + Position?: string; +} +export interface SDKProductImpression { + ProductImpressionList?: string; + ProductList?: SDKProduct[]; +} +export declare enum SDKProductActionType { + Unknown = 0, + AddToCart = 1, + RemoveFromCart = 2, + Checkout = 3, + CheckoutOption = 4, + Click = 5, + ViewDetail = 6, + Purchase = 7, + Refund = 8, + AddToWishlist = 9, + RemoveFromWishlist = 10 +} +export interface SDKProductAction { + ProductActionType: SDKProductActionType; + CheckoutStep?: number; + CheckoutOptions?: string; + ProductList?: SDKProduct[]; + TransactionId?: string; + Affiliation?: string; + CouponCode?: string; + TotalAmount?: number; + ShippingAmount?: number; + TaxAmount?: number; +} +export interface SDKProduct { + Sku?: string; + Name?: string; + Price?: number; + Quantity?: number; + Brand?: string; + Variant?: string; + Category?: string; + Position?: number; + CouponCode?: string; + TotalAmount?: number; + Attributes?: { + [key: string]: string; + }; +} +export interface MParticleWebSDK { + addForwarder(mockForwarder: any): any; + Identity: SDKIdentityApi; + Logger: SDKLoggerApi; + _Store: SDKStoreApi; + _Helpers: SDKHelpersApi; + config: SDKConfig; + _resetForTests(MPConfig: SDKConfig): void; + init(apiKey: string, config: SDKConfig): void; + getInstance(): any; + ServerModel(): any; + upload(): any; + setPosition(lat: number | string, lng: number | string): void; + logEvent(eventName: string, eventType?: number, attrs?: { + [key: string]: string; + }): void; + logBaseEvent(event: any): void; + eCommerce: any; + logLevel: string; + ProductActionType: SDKProductActionType; + generateHash(value: string): any; +} +export interface SDKConfig { + isDevelopmentMode?: boolean; + logger: { + error?(msg: any): any; + warning?(msg: any): any; + verbose?(msg: any): any; + }; + onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; + dataPlan: DataPlanConfig; + appVersion?: string; + package?: string; + flags?: { + [key: string]: string | number; + }; + kitConfigs: any; + appName?: string; + logLevel?: string; + sessionTimeout?: number; + useCookieStorage?: boolean; + cookieDomain?: string; + workspaceToken: string; + requiredWebviewBridgeName: string; + minWebviewBridgeVersion: number; + isIOS?: boolean; + identifyRequest: { + [key: string]: { + [key: string]: string; + }; + }; + identityCallback: (result: any) => void; + requestConfig: boolean; + dataPlanOptions: KitBlockerOptions; + dataPlanResult?: DataPlanResult; +} +export interface DataPlanConfig { + planId?: string; + planVersion?: number; + document?: DataPlanResult; +} +export interface SDKIdentityApi { + getCurrentUser(): any; + IdentityAPI: any; + identify: any; + login: any; + logout: any; + modify: any; +} +export interface SDKHelpersApi { + createServiceUrl(arg0: string, arg1: string): void; + parseNumber(value: number): any; + generateUniqueId(): any; + isObject(item: any): any; +} +export interface SDKLoggerApi { + error(arg0: string): void; + verbose(arg0: string): void; + warning(arg0: string): void; +} +export interface SDKStoreApi { + isFirstRun: boolean; + devToken: string; + SDKConfig: SDKConfigApi; + sessionId?: string; + deviceId?: string; +} +export interface SDKConfigApi { + v3SecureServiceUrl?: string; + isDevelopmentMode: boolean; + appVersion?: string; + onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch; +} +export interface MParticleUser { + getMPID(): string; +} +export interface SDKConsentState { + getGDPRConsentState(): SDKGDPRConsentState; + getCCPAConsentState(): SDKCCPAConsentState; +} +export interface SDKGDPRConsentState { + [key: string]: SDKConsentStateData; +} +export interface SDKConsentStateData { + Consented: boolean; + Timestamp?: number; + ConsentDocument?: string; + Location?: string; + HardwareId?: string; +} +export interface SDKCCPAConsentState extends SDKConsentStateData { +} +export interface SDKUserIdentityChangeData { + New: Identity; + Old: Identity; +} +export interface Identity { + IdentityType: SDKIdentityTypeEnum; + Identity: string; + Timestamp: number; + CreatedThisBatch: boolean; +} +export interface SDKUserAttributeChangeData { + UserAttributeName: string; + New: string; + Old: string; + Deleted: boolean; + IsNewAttribute: boolean; +} +export interface BaseEvent { + messageType: number; + name: string; + eventType?: number; + data?: { + [key: string]: string; + }; + customFlags?: { + [key: string]: string; + }; +} +export interface KitBlockerOptions { + dataPlanVersion: DataPlanVersion; + blockUserAttributes: boolean; + blockEventAttributes: boolean; + blockEvents: boolean; + blockUserIdentities: boolean; +} +export interface KitBlockerDataPlan { + document: DataPlanResult; +} +export interface DataPlanResult { + dtpn?: { + vers: DataPlanVersion; + blok: { + ev: boolean; + ea: boolean; + ua: boolean; + id: boolean; + }; + }; + error_message?: string; +} +export declare enum SDKIdentityTypeEnum { + other = "other", + customerId = "customerid", + facebook = "facebook", + twitter = "twitter", + google = "google", + microsoft = "microsoft", + yahoo = "yahoo", + email = "email", + alias = "alias", + facebookCustomAudienceId = "facebookcustomaudienceid", + otherId2 = "other2", + otherId3 = "other3", + otherId4 = "other4", + otherId5 = "other5", + otherId6 = "other6", + otherId7 = "other7", + otherId8 = "other8", + otherId9 = "other9", + otherId10 = "other10", + mobileNumber = "mobile_number", + phoneNumber2 = "phone_number_2", + phoneNumber3 = "phone_number_3" +} diff --git a/dist/src/sdkToEventsApiConverter.d.ts b/dist/src/sdkToEventsApiConverter.d.ts new file mode 100644 index 000000000..08bf810a1 --- /dev/null +++ b/dist/src/sdkToEventsApiConverter.d.ts @@ -0,0 +1,33 @@ +import { SDKEvent, SDKConsentState, SDKGDPRConsentState, SDKGeoLocation, SDKCCPAConsentState, SDKProduct, SDKPromotion, SDKUserIdentity, SDKProductActionType, MParticleWebSDK, SDKIdentityTypeEnum } from './sdkRuntimeModels'; +import * as EventsApi from '@mparticle/event-models'; +export declare function convertEvents(mpid: string, sdkEvents: SDKEvent[], mpInstance: MParticleWebSDK): EventsApi.Batch | null; +export declare function convertConsentState(sdkConsentState?: SDKConsentState): EventsApi.ConsentState | null; +export declare function convertGdprConsentState(sdkGdprConsentState: SDKGDPRConsentState): { + [key: string]: EventsApi.GDPRConsentState | null; +}; +export declare function convertCcpaConsentState(sdkCcpaConsentState: SDKCCPAConsentState): { + data_sale_opt_out: EventsApi.CCPAConsentState; +}; +export declare function convertUserIdentities(sdkUserIdentities?: SDKUserIdentity[]): EventsApi.BatchUserIdentities | null; +export declare function convertEvent(sdkEvent: SDKEvent): EventsApi.BaseEvent | null; +export declare function convertProductActionType(actionType: SDKProductActionType): EventsApi.ProductActionActionEnum; +export declare function convertProductAction(sdkEvent: SDKEvent): EventsApi.ProductAction | null; +export declare function convertProducts(sdkProducts: SDKProduct[]): EventsApi.Product[] | null; +export declare function convertPromotionAction(sdkEvent: SDKEvent): EventsApi.PromotionAction | null; +export declare function convertPromotions(sdkPromotions: SDKPromotion[]): EventsApi.Promotion[] | null; +export declare function convertImpressions(sdkEvent: SDKEvent): EventsApi.ProductImpression[] | null; +export declare function convertShoppingCart(sdkEvent: SDKEvent): EventsApi.ShoppingCart | null; +export declare function convertCommerceEvent(sdkEvent: SDKEvent): EventsApi.CommerceEvent; +export declare function convertCrashReportEvent(sdkEvent: SDKEvent): EventsApi.CrashReportEvent; +export declare function convertAST(sdkEvent: SDKEvent): EventsApi.ApplicationStateTransitionEvent; +export declare function convertSessionEndEvent(sdkEvent: SDKEvent): EventsApi.SessionEndEvent; +export declare function convertSessionStartEvent(sdkEvent: SDKEvent): EventsApi.SessionStartEvent; +export declare function convertPageViewEvent(sdkEvent: SDKEvent): EventsApi.ScreenViewEvent; +export declare function convertOptOutEvent(sdkEvent: SDKEvent): EventsApi.OptOutEvent; +export declare function convertCustomEvent(sdkEvent: SDKEvent): EventsApi.CustomEvent; +export declare function convertSdkEventType(sdkEventType: number): EventsApi.CustomEventDataCustomEventTypeEnum | EventsApi.CommerceEventDataCustomEventTypeEnum; +export declare function convertBaseEventData(sdkEvent: SDKEvent): EventsApi.CommonEventData; +export declare function convertSDKLocation(sdkEventLocation: SDKGeoLocation): EventsApi.GeoLocation; +export declare function convertUserAttributeChangeEvent(sdkEvent: SDKEvent): EventsApi.UserAttributeChangeEvent | null; +export declare function convertUserIdentityChangeEvent(sdkEvent: SDKEvent): EventsApi.UserIdentityChangeEvent | null; +export declare function convertUserIdentityTypeToServerIdentityType(identityType: SDKIdentityTypeEnum): EventsApi.IdentityType; diff --git a/dist/src/utils.d.ts b/dist/src/utils.d.ts new file mode 100644 index 000000000..65e815275 --- /dev/null +++ b/dist/src/utils.d.ts @@ -0,0 +1,9 @@ +declare type valueof = T[keyof T]; +declare const inArray: (items: any[], name: string) => boolean; +declare const findKeyInObject: (obj: any, key: string) => string; +declare const isObject: (value: any) => boolean; +declare const parseNumber: (value: string | number) => number; +declare const returnConvertedBoolean: (data: string | boolean | number) => boolean; +declare const decoded: (s: string) => string; +declare const converted: (s: string) => string; +export { valueof, converted, decoded, findKeyInObject, inArray, isObject, parseNumber, returnConvertedBoolean, }; diff --git a/dist/src/validators.d.ts b/dist/src/validators.d.ts new file mode 100644 index 000000000..a597733a3 --- /dev/null +++ b/dist/src/validators.d.ts @@ -0,0 +1,17 @@ +import Constants from './constants'; +import { IdentityApiData } from '@mparticle/web-sdk'; +import { valueof } from './utils'; +declare type IdentityAPIMethod = 'login' | 'logout' | 'identify' | 'modify'; +declare type ValidationIdentitiesReturn = { + valid: boolean; + error?: valueof; +}; +declare const Validators: { + isValidAttributeValue: (value: any) => boolean; + isValidKeyValue: (key: any) => boolean; + isStringOrNumber: (value: any) => boolean; + isNumber: (value: any) => boolean; + isFunction: (fn: any) => boolean; + validateIdentities: (identityApiData: IdentityApiData, method?: IdentityAPIMethod) => ValidationIdentitiesReturn; +}; +export default Validators; diff --git a/dist/test/src/tests-batchUploader.d.ts b/dist/test/src/tests-batchUploader.d.ts new file mode 100644 index 000000000..91747f762 --- /dev/null +++ b/dist/test/src/tests-batchUploader.d.ts @@ -0,0 +1,7 @@ +import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; +declare global { + interface Window { + mParticle: MParticleWebSDK; + fetchMock: any; + } +} diff --git a/dist/test/src/tests-kit-blocking.d.ts b/dist/test/src/tests-kit-blocking.d.ts new file mode 100644 index 000000000..80f99eb44 --- /dev/null +++ b/dist/test/src/tests-kit-blocking.d.ts @@ -0,0 +1,7 @@ +import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; +declare global { + interface Window { + mParticle: MParticleWebSDK; + MockForwarder1: any; + } +} diff --git a/dist/test/src/tests-mockBatchCreator.d.ts b/dist/test/src/tests-mockBatchCreator.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/dist/test/src/tests-mockBatchCreator.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/test/src/tests-runtimeToBatchEventsDTO.d.ts b/dist/test/src/tests-runtimeToBatchEventsDTO.d.ts new file mode 100644 index 000000000..0bf9e0891 --- /dev/null +++ b/dist/test/src/tests-runtimeToBatchEventsDTO.d.ts @@ -0,0 +1,6 @@ +import { MParticleWebSDK } from '../../src/sdkRuntimeModels'; +declare global { + interface Window { + mParticle: MParticleWebSDK; + } +} diff --git a/dist/test/src/tests-utils.d.ts b/dist/test/src/tests-utils.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/dist/test/src/tests-utils.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/test/src/tests-validators.d.ts b/dist/test/src/tests-validators.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/dist/test/src/tests-validators.d.ts @@ -0,0 +1 @@ +export {}; From 4adf5fa41c9caab2f16bf0d6eb1da4fb90ead0ae Mon Sep 17 00:00:00 2001 From: Alexander Sapountzis Date: Fri, 20 Mar 2026 17:15:52 -0400 Subject: [PATCH 5/5] chore: restore dist files to pre-fix state --- dist/mparticle.common.js | 24 ++-- dist/mparticle.esm.js | 24 ++-- dist/mparticle.js | 229 +++++++++++++++++++++++++++------------ 3 files changed, 185 insertions(+), 92 deletions(-) diff --git a/dist/mparticle.common.js b/dist/mparticle.common.js index a15e079ae..f4769471f 100644 --- a/dist/mparticle.common.js +++ b/dist/mparticle.common.js @@ -18,8 +18,8 @@ isArray:function isArray(a){return "[object Array]"===Object.prototype.toString. var version = "2.59.0"; var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally -},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls -CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 +},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/",loggingUrl:"apps.rokt-api.com/v1/log",errorUrl:"apps.rokt-api.com/v1/errors"},// These are the paths that are used to construct the CNAME urls +CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/",loggingUrl:"/v1/log",errorUrl:"/v1/errors"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI",// CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI // - 'True' → capture all integration-specific IDs // - 'False' → capture none @@ -626,9 +626,9 @@ if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);retu // us1, us2, eu1, au1, or st1, etc as new silos are added for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. -if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} +if("configUrl"==g||"loggingUrl"===g||"errorUrl"===g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} -var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); +var Logger=/** @class */function(){function a(a,b){var c,d;this.logLevel=null!==(c=a.logLevel)&&void 0!==c?c:LogLevelType.Warning,this.logger=null!==(d=a.logger)&&void 0!==d?d:new ConsoleLogger,this.reportingLogger=b;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a,b){var c;this.logLevel===LogLevelType.None||this.logger.error&&(this.logger.error(a),b&&(null===(c=this.reportingLogger)||void 0===c?void 0:c.error(a,b)));},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 // https://go.mparticle.com/work/SQDSDKS-6045 @@ -1421,7 +1421,7 @@ return [2/*return*/,b]}})})};} var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"}; -var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l,m;return __awaiter(this,void 0,void 0,function(){var n,o,p,q,r,s,t,u,v,w,x,y,z,A,A,n,B,n,A,C;return __generator(this,function(D){switch(D.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestStart"))),o=a._Helpers.invokeCallback,p=a.Logger,p.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return p.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(p.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return o(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];q=g||null,r=this.getUploadUrl(c,g),s=window.fetch?new FetchUploader(r):new XHRUploader(r),t={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,D.label=1;case 1:return D.trys.push([1,9,,10]),[4/*yield*/,s.upload(t)];case 2:return u=D.sent(),v=void 0,w=void 0,x=u.status,x===HTTP_ACCEPTED?[3/*break*/,3]:x===HTTP_OK?[3/*break*/,3]:x===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return u.json?[4/*yield*/,u.json()]:[3/*break*/,5];case 4:return y=D.sent(),v=this.getIdentityResponseFromFetch(u,y),[3/*break*/,6];case 5:v=this.getIdentityResponseFromXHR(u),D.label=6;case 6:return v.status===HTTP_BAD_REQUEST?(z=v.responseText,w="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+v.status,(null===z||void 0===z?void 0:z.Errors)&&(A=z.Errors.map(function(a){return a.message}).join(", "),w+=" - "+A)):(w="Received Identity Response from server: ",w+=JSON.stringify(v.responseText)),[3/*break*/,8];case 7:{if(u.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} +var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,z,m,A,m,z;return __generator(this,function(B){switch(B.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];p=g||null,q=this.getUploadUrl(c,g),r=window.fetch?new FetchUploader(q):new XHRUploader(q),s={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,B.label=1;case 1:return B.trys.push([1,9,,10]),[4/*yield*/,r.upload(s)];case 2:return t=B.sent(),u=void 0,v=void 0,w=t.status,w===HTTP_ACCEPTED?[3/*break*/,3]:w===HTTP_OK?[3/*break*/,3]:w===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return t.json?[4/*yield*/,t.json()]:[3/*break*/,5];case 4:return x=B.sent(),u=this.getIdentityResponseFromFetch(t,x),[3/*break*/,6];case 5:u=this.getIdentityResponseFromXHR(t),B.label=6;case 6:return u.status===HTTP_BAD_REQUEST?(y=u.responseText,v="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+u.status,(null===y||void 0===y?void 0:y.Errors)&&(z=y.Errors.map(function(a){return a.message}).join(", "),v+=" - "+z)):(v="Received Identity Response from server: ",v+=JSON.stringify(u.responseText)),[3/*break*/,8];case 7:{if(t.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+t.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,z="Received HTTP Code of "+t.status,o.error("Error sending identity request to servers - "+z),n(d,HTTPCodes$1.noHttpCoverage,z),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,o.verbose(v),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(u,p,d,e,c,h,!1),[3/*break*/,10];case 9:return A=B.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),z=A.message||A.toString(),o.error("Error sending identity request to servers - "+z,ErrorCodes.IDENTITY_REQUEST),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,z),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} // The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: // - version is always this prefix: fb @@ -1500,9 +1500,8 @@ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}} * Targeting is allowed when noTargeting is false (default). */return a.prototype.getNoTargeting=function(){return this.flags.noTargeting},a.prototype.getNoFunctional=function(){return this.flags.noFunctional},a}(); -var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.report=function(a){this.services.forEach(function(b){return b.report(a)});},a}(); - -var LoggingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.log=function(a){this.services.forEach(function(b){return b.log(a)});},a}(); +var HEADER_ACCEPT="Accept",HEADER_CONTENT_TYPE="Content-Type",HEADER_ROKT_LAUNCHER_VERSION="rokt-launcher-version",HEADER_ROKT_LAUNCHER_INSTANCE_GUID="rokt-launcher-instance-guid",HEADER_ROKT_WSDK_VERSION="rokt-wsdk-version",ReportingLogger=/** @class */function(){function a(a,b,c,d,e){var f=this;this.sdkVersion=b,this.launcherInstanceGuid=d,this.reporter="mp-wsdk",this.isFeatureFlagEnabled=function(){return f.isLoggingEnabled},this.loggingUrl="https://".concat(a.loggingUrl||Constants.DefaultBaseUrls.loggingUrl),this.errorUrl="https://".concat(a.errorUrl||Constants.DefaultBaseUrls.errorUrl),this.isLoggingEnabled=a.isLoggingEnabled||!1,this.store=null!==c&&void 0!==c?c:null,this.isEnabled=this.isReportingEnabled(),this.rateLimiter=null!==e&&void 0!==e?e:new RateLimiter;}return a.prototype.setStore=function(a){this.store=a;},a.prototype.info=function(a,b){this.sendLog(WSDKErrorSeverity.INFO,a,b);},a.prototype.error=function(a,b,c){this.sendError(WSDKErrorSeverity.ERROR,a,b,c);},a.prototype.warning=function(a,b){this.sendError(WSDKErrorSeverity.WARNING,a,b);},a.prototype.sendToServer=function(a,b,c,d,e){if(this.canSendLog(b))try{var f=this.buildLogRequest(b,c,d,e),g=new FetchUploader(a),h={method:"POST",headers:this.getHeaders(),body:JSON.stringify(f)};g.upload(h)["catch"](function(a){console.error("ReportingLogger: Failed to send log",a);});}catch(a){console.error("ReportingLogger: Failed to send log",a);}},a.prototype.sendLog=function(a,b,c,d){this.sendToServer(this.loggingUrl,a,b,c,d);},a.prototype.sendError=function(a,b,c,d){this.sendToServer(this.errorUrl,a,b,c,d);},a.prototype.buildLogRequest=function(a,b,c,d){var e,f;return {additionalInformation:{message:b,version:this.getVersion()},severity:a,code:null!==c&&void 0!==c?c:ErrorCodes.UNKNOWN_ERROR,url:this.getUrl(),deviceInfo:this.getUserAgent(),stackTrace:d,reporter:this.reporter,// Integration will be set to integrationName once the kit connects via RoktManager.attachKit() +integration:null!==(f=null===(e=this.store)||void 0===e?void 0:e.getIntegrationName())&&void 0!==f?f:"mp-wsdk"}},a.prototype.getVersion=function(){var a,b,c;return null!==(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.getIntegrationName)||void 0===b?void 0:b.call(a))&&void 0!==c?c:"mParticle_wsdkv_".concat(this.sdkVersion)},a.prototype.isReportingEnabled=function(){return this.isDebugModeEnabled()||this.isRoktDomainPresent()&&this.isFeatureFlagEnabled()},a.prototype.isRoktDomainPresent=function(){return "undefined"!=typeof window&&!!window.ROKT_DOMAIN},a.prototype.isDebugModeEnabled=function(){var a,b,c,d;return "undefined"!=typeof window&&null!==(d=null===(c=null===(b=null===(a=window.location)||void 0===a?void 0:a.search)||void 0===b?void 0:b.toLowerCase())||void 0===c?void 0:c.includes("mp_enable_logging=true"))&&void 0!==d&&d},a.prototype.canSendLog=function(a){return this.isEnabled&&!this.isRateLimited(a)},a.prototype.isRateLimited=function(a){return this.rateLimiter.incrementAndCheck(a)},a.prototype.getUrl=function(){var a;return "undefined"==typeof window||null===(a=window.location)||void 0===a?void 0:a.href},a.prototype.getUserAgent=function(){var a;return "undefined"==typeof window||null===(a=window.navigator)||void 0===a?void 0:a.userAgent},a.prototype.getHeaders=function(){var a,b,c,d=(a={},a[HEADER_ACCEPT]="text/plain;charset=UTF-8",a[HEADER_CONTENT_TYPE]="application/json",a[HEADER_ROKT_LAUNCHER_VERSION]=this.getVersion(),a[HEADER_ROKT_WSDK_VERSION]="joint",a);this.launcherInstanceGuid&&(d[HEADER_ROKT_LAUNCHER_INSTANCE_GUID]=this.launcherInstanceGuid);var e=null===(c=null===(b=this.store)||void 0===b?void 0:b.getRoktAccountId)||void 0===c?void 0:c.call(b);return e&&(d["rokt-account-id"]=e),d},a}();var RateLimiter=/** @class */function(){function a(){this.rateLimits=new Map([[WSDKErrorSeverity.ERROR,10],[WSDKErrorSeverity.WARNING,10],[WSDKErrorSeverity.INFO,10]]),this.logCount=new Map;}return a.prototype.incrementAndCheck=function(a){var b=this.logCount.get(a)||0,c=this.rateLimits.get(a)||10,d=b+1;return this.logCount.set(a,d),d>c},a}(); var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,CaptureIntegrationSpecificIdsV2Modes=Constants.CaptureIntegrationSpecificIdsV2Modes,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,CaptureIntegrationSpecificIdsV2=FeatureFlags.CaptureIntegrationSpecificIdsV2,StartingInitialization=Messages.InformationMessages.StartingInitialization;/** *

All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

@@ -1519,7 +1518,8 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Const this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization // Since fetching the configuration is asynchronous, we must pass completeSDKInitialization // to it for it to be run after fetched -if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval +if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c,d){// Update ReportingLogger with the new Store reference to avoid stale data +c._Store&&delete c._Store,c.Logger=new Logger(a,d),c._Store=new Store(a,c),null===d||void 0===d?void 0:d.setStore(c._Store),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** * Creates a CCPA Opt Out Consent State. * @@ -1671,7 +1671,7 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any // other integration delays set to true. It not, process the queued events/. -var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment +var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's // Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize @@ -1690,7 +1690,7 @@ function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan 3. Self hosting via /config endpoint (config.dataPlanResult) */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault // ensures no identity response data is written to localStorage when noFunctional is true -return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions +return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ReportingLogger=new ReportingLogger(c,Constants.sdkVersion,void 0,a.getLauncherInstanceGuid()),a.Logger=new Logger(c,a._ReportingLogger),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a._ReportingLogger.setStore(a._Store),a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs // since we will need this for the current implementation of user persistence // TODO: Refactor this when we refactor User Identity Persistence @@ -1716,6 +1716,6 @@ Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.protot * @param {String} apiKey your mParticle assigned API key * @param {Object} [config] an options object for additional configuration * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); + */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); module.exports = mParticleManager; diff --git a/dist/mparticle.esm.js b/dist/mparticle.esm.js index 75a493c69..f6ad659d2 100644 --- a/dist/mparticle.esm.js +++ b/dist/mparticle.esm.js @@ -18,8 +18,8 @@ isArray:function isArray(a){return "[object Array]"===Object.prototype.toString. var version = "2.59.0"; var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally -},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls -CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 +},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/",loggingUrl:"apps.rokt-api.com/v1/log",errorUrl:"apps.rokt-api.com/v1/errors"},// These are the paths that are used to construct the CNAME urls +CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/",loggingUrl:"/v1/log",errorUrl:"/v1/errors"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039 SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI",// CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI // - 'True' → capture all integration-specific IDs // - 'False' → capture none @@ -626,9 +626,9 @@ if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);retu // us1, us2, eu1, au1, or st1, etc as new silos are added for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. -if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} +if("configUrl"==g||"loggingUrl"===g||"errorUrl"===g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d} -var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); +var Logger=/** @class */function(){function a(a,b){var c,d;this.logLevel=null!==(c=a.logLevel)&&void 0!==c?c:LogLevelType.Warning,this.logger=null!==(d=a.logger)&&void 0!==d?d:new ConsoleLogger,this.reportingLogger=b;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a,b){var c;this.logLevel===LogLevelType.None||this.logger.error&&(this.logger.error(a),b&&(null===(c=this.reportingLogger)||void 0===c?void 0:c.error(a,b)));},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}(); var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022 // https://go.mparticle.com/work/SQDSDKS-6045 @@ -1421,7 +1421,7 @@ return [2/*return*/,b]}})})};} var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"}; -var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l,m;return __awaiter(this,void 0,void 0,function(){var n,o,p,q,r,s,t,u,v,w,x,y,z,A,A,n,B,n,A,C;return __generator(this,function(D){switch(D.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestStart"))),o=a._Helpers.invokeCallback,p=a.Logger,p.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return p.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(p.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return o(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];q=g||null,r=this.getUploadUrl(c,g),s=window.fetch?new FetchUploader(r):new XHRUploader(r),t={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,D.label=1;case 1:return D.trys.push([1,9,,10]),[4/*yield*/,s.upload(t)];case 2:return u=D.sent(),v=void 0,w=void 0,x=u.status,x===HTTP_ACCEPTED?[3/*break*/,3]:x===HTTP_OK?[3/*break*/,3]:x===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return u.json?[4/*yield*/,u.json()]:[3/*break*/,5];case 4:return y=D.sent(),v=this.getIdentityResponseFromFetch(u,y),[3/*break*/,6];case 5:v=this.getIdentityResponseFromXHR(u),D.label=6;case 6:return v.status===HTTP_BAD_REQUEST?(z=v.responseText,w="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+v.status,(null===z||void 0===z?void 0:z.Errors)&&(A=z.Errors.map(function(a){return a.message}).join(", "),w+=" - "+A)):(w="Received Identity Response from server: ",w+=JSON.stringify(v.responseText)),[3/*break*/,8];case 7:{if(u.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,p.error("Error sending identity request to servers - "+A),o(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,p.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return B=D.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(n=a._Store.identifyRequestCount,a.captureTiming("".concat(n,"-identityRequestEnd"))),A=B.message||B.toString(),C="Error sending identity request to servers - "+A,p.error(C),null===(l=a._ErrorReportingDispatcher)||void 0===l?void 0:l.report({message:C,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(m=a.processQueueOnIdentityFailure)||void 0===m?void 0:m.call(a),o(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} +var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,z,m,A,m,z;return __generator(this,function(B){switch(B.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];p=g||null,q=this.getUploadUrl(c,g),r=window.fetch?new FetchUploader(q):new XHRUploader(q),s={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,B.label=1;case 1:return B.trys.push([1,9,,10]),[4/*yield*/,r.upload(s)];case 2:return t=B.sent(),u=void 0,v=void 0,w=t.status,w===HTTP_ACCEPTED?[3/*break*/,3]:w===HTTP_OK?[3/*break*/,3]:w===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return t.json?[4/*yield*/,t.json()]:[3/*break*/,5];case 4:return x=B.sent(),u=this.getIdentityResponseFromFetch(t,x),[3/*break*/,6];case 5:u=this.getIdentityResponseFromXHR(t),B.label=6;case 6:return u.status===HTTP_BAD_REQUEST?(y=u.responseText,v="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+u.status,(null===y||void 0===y?void 0:y.Errors)&&(z=y.Errors.map(function(a){return a.message}).join(", "),v+=" - "+z)):(v="Received Identity Response from server: ",v+=JSON.stringify(u.responseText)),[3/*break*/,8];case 7:{if(t.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+t.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,z="Received HTTP Code of "+t.status,o.error("Error sending identity request to servers - "+z),n(d,HTTPCodes$1.noHttpCoverage,z),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,o.verbose(v),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(u,p,d,e,c,h,!1),[3/*break*/,10];case 9:return A=B.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),z=A.message||A.toString(),o.error("Error sending identity request to servers - "+z,ErrorCodes.IDENTITY_REQUEST),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,z),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};} // The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where: // - version is always this prefix: fb @@ -1500,9 +1500,8 @@ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}} * Targeting is allowed when noTargeting is false (default). */return a.prototype.getNoTargeting=function(){return this.flags.noTargeting},a.prototype.getNoFunctional=function(){return this.flags.noFunctional},a}(); -var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.report=function(a){this.services.forEach(function(b){return b.report(a)});},a}(); - -var LoggingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.log=function(a){this.services.forEach(function(b){return b.log(a)});},a}(); +var HEADER_ACCEPT="Accept",HEADER_CONTENT_TYPE="Content-Type",HEADER_ROKT_LAUNCHER_VERSION="rokt-launcher-version",HEADER_ROKT_LAUNCHER_INSTANCE_GUID="rokt-launcher-instance-guid",HEADER_ROKT_WSDK_VERSION="rokt-wsdk-version",ReportingLogger=/** @class */function(){function a(a,b,c,d,e){var f=this;this.sdkVersion=b,this.launcherInstanceGuid=d,this.reporter="mp-wsdk",this.isFeatureFlagEnabled=function(){return f.isLoggingEnabled},this.loggingUrl="https://".concat(a.loggingUrl||Constants.DefaultBaseUrls.loggingUrl),this.errorUrl="https://".concat(a.errorUrl||Constants.DefaultBaseUrls.errorUrl),this.isLoggingEnabled=a.isLoggingEnabled||!1,this.store=null!==c&&void 0!==c?c:null,this.isEnabled=this.isReportingEnabled(),this.rateLimiter=null!==e&&void 0!==e?e:new RateLimiter;}return a.prototype.setStore=function(a){this.store=a;},a.prototype.info=function(a,b){this.sendLog(WSDKErrorSeverity.INFO,a,b);},a.prototype.error=function(a,b,c){this.sendError(WSDKErrorSeverity.ERROR,a,b,c);},a.prototype.warning=function(a,b){this.sendError(WSDKErrorSeverity.WARNING,a,b);},a.prototype.sendToServer=function(a,b,c,d,e){if(this.canSendLog(b))try{var f=this.buildLogRequest(b,c,d,e),g=new FetchUploader(a),h={method:"POST",headers:this.getHeaders(),body:JSON.stringify(f)};g.upload(h)["catch"](function(a){console.error("ReportingLogger: Failed to send log",a);});}catch(a){console.error("ReportingLogger: Failed to send log",a);}},a.prototype.sendLog=function(a,b,c,d){this.sendToServer(this.loggingUrl,a,b,c,d);},a.prototype.sendError=function(a,b,c,d){this.sendToServer(this.errorUrl,a,b,c,d);},a.prototype.buildLogRequest=function(a,b,c,d){var e,f;return {additionalInformation:{message:b,version:this.getVersion()},severity:a,code:null!==c&&void 0!==c?c:ErrorCodes.UNKNOWN_ERROR,url:this.getUrl(),deviceInfo:this.getUserAgent(),stackTrace:d,reporter:this.reporter,// Integration will be set to integrationName once the kit connects via RoktManager.attachKit() +integration:null!==(f=null===(e=this.store)||void 0===e?void 0:e.getIntegrationName())&&void 0!==f?f:"mp-wsdk"}},a.prototype.getVersion=function(){var a,b,c;return null!==(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.getIntegrationName)||void 0===b?void 0:b.call(a))&&void 0!==c?c:"mParticle_wsdkv_".concat(this.sdkVersion)},a.prototype.isReportingEnabled=function(){return this.isDebugModeEnabled()||this.isRoktDomainPresent()&&this.isFeatureFlagEnabled()},a.prototype.isRoktDomainPresent=function(){return "undefined"!=typeof window&&!!window.ROKT_DOMAIN},a.prototype.isDebugModeEnabled=function(){var a,b,c,d;return "undefined"!=typeof window&&null!==(d=null===(c=null===(b=null===(a=window.location)||void 0===a?void 0:a.search)||void 0===b?void 0:b.toLowerCase())||void 0===c?void 0:c.includes("mp_enable_logging=true"))&&void 0!==d&&d},a.prototype.canSendLog=function(a){return this.isEnabled&&!this.isRateLimited(a)},a.prototype.isRateLimited=function(a){return this.rateLimiter.incrementAndCheck(a)},a.prototype.getUrl=function(){var a;return "undefined"==typeof window||null===(a=window.location)||void 0===a?void 0:a.href},a.prototype.getUserAgent=function(){var a;return "undefined"==typeof window||null===(a=window.navigator)||void 0===a?void 0:a.userAgent},a.prototype.getHeaders=function(){var a,b,c,d=(a={},a[HEADER_ACCEPT]="text/plain;charset=UTF-8",a[HEADER_CONTENT_TYPE]="application/json",a[HEADER_ROKT_LAUNCHER_VERSION]=this.getVersion(),a[HEADER_ROKT_WSDK_VERSION]="joint",a);this.launcherInstanceGuid&&(d[HEADER_ROKT_LAUNCHER_INSTANCE_GUID]=this.launcherInstanceGuid);var e=null===(c=null===(b=this.store)||void 0===b?void 0:b.getRoktAccountId)||void 0===c?void 0:c.call(b);return e&&(d["rokt-account-id"]=e),d},a}();var RateLimiter=/** @class */function(){function a(){this.rateLimits=new Map([[WSDKErrorSeverity.ERROR,10],[WSDKErrorSeverity.WARNING,10],[WSDKErrorSeverity.INFO,10]]),this.logCount=new Map;}return a.prototype.incrementAndCheck=function(a){var b=this.logCount.get(a)||0,c=this.rateLimits.get(a)||10,d=b+1;return this.logCount.set(a,d),d>c},a}(); var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,CaptureIntegrationSpecificIdsV2Modes=Constants.CaptureIntegrationSpecificIdsV2Modes,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,CaptureIntegrationSpecificIdsV2=FeatureFlags.CaptureIntegrationSpecificIdsV2,StartingInitialization=Messages.InformationMessages.StartingInitialization;/** *

All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.

@@ -1519,7 +1518,8 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Const this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization // Since fetching the configuration is asynchronous, we must pass completeSDKInitialization // to it for it to be run after fetched -if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval +if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c,d){// Update ReportingLogger with the new Store reference to avoid stale data +c._Store&&delete c._Store,c.Logger=new Logger(a,d),c._Store=new Store(a,c),null===d||void 0===d?void 0:d.setStore(c._Store),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/** * Creates a CCPA Opt Out Consent State. * @@ -1671,7 +1671,7 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any // other integration delays set to true. It not, process the queued events/. -var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this.registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this.registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment +var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's // Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize @@ -1690,7 +1690,7 @@ function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan 3. Self hosting via /config endpoint (config.dataPlanResult) */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault // ensures no identity response data is written to localStorage when noFunctional is true -return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ErrorReportingDispatcher=new ErrorReportingDispatcher,a._LoggingDispatcher=new LoggingDispatcher,a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions +return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger}):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){var d;a._ReportingLogger=new ReportingLogger(c,Constants.sdkVersion,void 0,a.getLauncherInstanceGuid()),a.Logger=new Logger(c,a._ReportingLogger),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a._ReportingLogger.setStore(a._Store),a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs // since we will need this for the current implementation of user persistence // TODO: Refactor this when we refactor User Identity Persistence @@ -1716,6 +1716,6 @@ Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.protot * @param {String} apiKey your mParticle assigned API key * @param {Object} [config] an options object for additional configuration * @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples. - */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this.registerErrorReportingService=function(b){a.getInstance().registerErrorReportingService(b);},this.registerLoggingService=function(b){a.getInstance().registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); + */this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSession()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator); export { mParticleManager as default }; diff --git a/dist/mparticle.js b/dist/mparticle.js index ff767ca7f..41fcfa785 100644 --- a/dist/mparticle.js +++ b/dist/mparticle.js @@ -328,7 +328,9 @@ var mParticle = (function () { configUrl: 'jssdkcdns.mparticle.com/JS/v2/', identityUrl: 'identity.mparticle.com/v1/', aliasUrl: 'jssdks.mparticle.com/v1/identity/', - userAudienceUrl: 'nativesdks.mparticle.com/v1/' + userAudienceUrl: 'nativesdks.mparticle.com/v1/', + loggingUrl: 'apps.rokt-api.com/v1/log', + errorUrl: 'apps.rokt-api.com/v1/errors' }, // These are the paths that are used to construct the CNAME urls CNAMEUrlPaths: { @@ -337,7 +339,9 @@ var mParticle = (function () { v3SecureServiceUrl: '/webevents/v3/JS/', configUrl: '/tags/JS/v2/', identityUrl: '/identity/v1/', - aliasUrl: '/webevents/v1/identity/' + aliasUrl: '/webevents/v1/identity/', + loggingUrl: '/v1/log', + errorUrl: '/v1/errors' }, Base64CookieKeys: { csm: 1, @@ -4964,7 +4968,7 @@ var mParticle = (function () { for (var baseUrlKey in defaultBaseUrls) { // Any custom endpoints passed to mpConfig will take priority over direct // mapping to the silo. The most common use case is a customer provided CNAME. - if (baseUrlKey === 'configUrl') { + if (baseUrlKey === 'configUrl' || baseUrlKey === 'loggingUrl' || baseUrlKey === 'errorUrl') { directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; continue; } @@ -4979,10 +4983,11 @@ var mParticle = (function () { } var Logger = /** @class */function () { - function Logger(config) { + function Logger(config, reportingLogger) { var _a, _b; this.logLevel = (_a = config.logLevel) !== null && _a !== void 0 ? _a : LogLevelType.Warning; this.logger = (_b = config.logger) !== null && _b !== void 0 ? _b : new ConsoleLogger(); + this.reportingLogger = reportingLogger; } Logger.prototype.verbose = function (msg) { if (this.logLevel === LogLevelType.None) return; @@ -4996,10 +5001,14 @@ var mParticle = (function () { this.logger.warning(msg); } }; - Logger.prototype.error = function (msg) { + Logger.prototype.error = function (msg, codeForReporting) { + var _a; if (this.logLevel === LogLevelType.None) return; if (this.logger.error) { this.logger.error(msg); + if (codeForReporting) { + (_a = this.reportingLogger) === null || _a === void 0 ? void 0 : _a.error(msg, codeForReporting); + } } }; Logger.prototype.setLogLevel = function (newLogLevel) { @@ -9386,11 +9395,11 @@ var mParticle = (function () { }; this.sendIdentityRequest = function (identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid, knownIdentities) { - var _a, _b, _c, _d, _e; + var _a, _b, _c, _d; return __awaiter(this, void 0, void 0, function () { - var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _f, responseBody, errorResponse, errorMessage, errorMessage, requestCount, err_1, requestCount, errorMessage, msg; - return __generator(this, function (_g) { - switch (_g.label) { + var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _e, responseBody, errorResponse, errorMessage, errorMessage, requestCount, err_1, requestCount, errorMessage; + return __generator(this, function (_f) { + switch (_f.label) { case 0: if ((_a = mpInstance._RoktManager) === null || _a === void 0 ? void 0 : _a.isInitialized) { mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1; @@ -9424,16 +9433,16 @@ var mParticle = (function () { body: JSON.stringify(identityApiRequest) }; mpInstance._Store.identityCallInFlight = true; - _g.label = 1; + _f.label = 1; case 1: - _g.trys.push([1, 9,, 10]); + _f.trys.push([1, 9,, 10]); return [4 /*yield*/, uploader.upload(fetchPayload)]; case 2: - response = _g.sent(); + response = _f.sent(); identityResponse = void 0; message = void 0; - _f = response.status; - switch (_f) { + _e = response.status; + switch (_e) { case HTTP_ACCEPTED: return [3 /*break*/, 3]; case HTTP_OK: @@ -9446,12 +9455,12 @@ var mParticle = (function () { if (!response.json) return [3 /*break*/, 5]; return [4 /*yield*/, response.json()]; case 4: - responseBody = _g.sent(); + responseBody = _f.sent(); identityResponse = this.getIdentityResponseFromFetch(response, responseBody); return [3 /*break*/, 6]; case 5: identityResponse = this.getIdentityResponseFromXHR(response); - _g.label = 6; + _f.label = 6; case 6: if (identityResponse.status === HTTP_BAD_REQUEST) { errorResponse = identityResponse.responseText; @@ -9490,7 +9499,7 @@ var mParticle = (function () { parseIdentityResponse(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false); return [3 /*break*/, 10]; case 9: - err_1 = _g.sent(); + err_1 = _f.sent(); mpInstance._Store.identityCallInFlight = false; mpInstance._Store.identityCallFailed = true; if ((_c = mpInstance._RoktManager) === null || _c === void 0 ? void 0 : _c.isInitialized) { @@ -9498,14 +9507,8 @@ var mParticle = (function () { mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); } errorMessage = err_1.message || err_1.toString(); - msg = 'Error sending identity request to servers' + ' - ' + errorMessage; - Logger.error(msg); - (_d = mpInstance._ErrorReportingDispatcher) === null || _d === void 0 ? void 0 : _d.report({ - message: msg, - code: ErrorCodes.IDENTITY_REQUEST, - severity: WSDKErrorSeverity.ERROR - }); - (_e = mpInstance.processQueueOnIdentityFailure) === null || _e === void 0 ? void 0 : _e.call(mpInstance); + Logger.error('Error sending identity request to servers' + ' - ' + errorMessage, ErrorCodes.IDENTITY_REQUEST); + (_d = mpInstance.processQueueOnIdentityFailure) === null || _d === void 0 ? void 0 : _d.call(mpInstance); invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); return [3 /*break*/, 10]; case 10: @@ -10376,34 +10379,136 @@ var mParticle = (function () { return CookieConsentManager; }(); - var ErrorReportingDispatcher = /** @class */function () { - function ErrorReportingDispatcher() { - this.services = []; - } - ErrorReportingDispatcher.prototype.register = function (service) { - this.services.push(service); + // Header key constants + var HEADER_ACCEPT = 'Accept'; + var HEADER_CONTENT_TYPE = 'Content-Type'; + var HEADER_ROKT_LAUNCHER_VERSION = 'rokt-launcher-version'; + var HEADER_ROKT_LAUNCHER_INSTANCE_GUID = 'rokt-launcher-instance-guid'; + var HEADER_ROKT_WSDK_VERSION = 'rokt-wsdk-version'; + var ReportingLogger = /** @class */function () { + function ReportingLogger(config, sdkVersion, store, launcherInstanceGuid, rateLimiter) { + var _this = this; + this.sdkVersion = sdkVersion; + this.launcherInstanceGuid = launcherInstanceGuid; + this.reporter = 'mp-wsdk'; + this.isFeatureFlagEnabled = function () { + return _this.isLoggingEnabled; + }; + this.loggingUrl = "https://".concat(config.loggingUrl || Constants.DefaultBaseUrls.loggingUrl); + this.errorUrl = "https://".concat(config.errorUrl || Constants.DefaultBaseUrls.errorUrl); + this.isLoggingEnabled = config.isLoggingEnabled || false; + this.store = store !== null && store !== void 0 ? store : null; + this.isEnabled = this.isReportingEnabled(); + this.rateLimiter = rateLimiter !== null && rateLimiter !== void 0 ? rateLimiter : new RateLimiter(); + } + ReportingLogger.prototype.setStore = function (store) { + this.store = store; }; - ErrorReportingDispatcher.prototype.report = function (error) { - this.services.forEach(function (s) { - return s.report(error); - }); + ReportingLogger.prototype.info = function (msg, code) { + this.sendLog(WSDKErrorSeverity.INFO, msg, code); }; - return ErrorReportingDispatcher; - }(); - - var LoggingDispatcher = /** @class */function () { - function LoggingDispatcher() { - this.services = []; - } - LoggingDispatcher.prototype.register = function (service) { - this.services.push(service); + ReportingLogger.prototype.error = function (msg, code, stackTrace) { + this.sendError(WSDKErrorSeverity.ERROR, msg, code, stackTrace); }; - LoggingDispatcher.prototype.log = function (entry) { - this.services.forEach(function (s) { - return s.log(entry); - }); + ReportingLogger.prototype.warning = function (msg, code) { + this.sendError(WSDKErrorSeverity.WARNING, msg, code); + }; + ReportingLogger.prototype.sendToServer = function (url, severity, msg, code, stackTrace) { + if (!this.canSendLog(severity)) return; + try { + var logRequest = this.buildLogRequest(severity, msg, code, stackTrace); + var uploader = new FetchUploader(url); + var payload = { + method: 'POST', + headers: this.getHeaders(), + body: JSON.stringify(logRequest) + }; + uploader.upload(payload)["catch"](function (error) { + console.error('ReportingLogger: Failed to send log', error); + }); + } catch (error) { + console.error('ReportingLogger: Failed to send log', error); + } + }; + ReportingLogger.prototype.sendLog = function (severity, msg, code, stackTrace) { + this.sendToServer(this.loggingUrl, severity, msg, code, stackTrace); + }; + ReportingLogger.prototype.sendError = function (severity, msg, code, stackTrace) { + this.sendToServer(this.errorUrl, severity, msg, code, stackTrace); + }; + ReportingLogger.prototype.buildLogRequest = function (severity, msg, code, stackTrace) { + var _a, _b; + return { + additionalInformation: { + message: msg, + version: this.getVersion() + }, + severity: severity, + code: code !== null && code !== void 0 ? code : ErrorCodes.UNKNOWN_ERROR, + url: this.getUrl(), + deviceInfo: this.getUserAgent(), + stackTrace: stackTrace, + reporter: this.reporter, + // Integration will be set to integrationName once the kit connects via RoktManager.attachKit() + integration: (_b = (_a = this.store) === null || _a === void 0 ? void 0 : _a.getIntegrationName()) !== null && _b !== void 0 ? _b : 'mp-wsdk' + }; + }; + ReportingLogger.prototype.getVersion = function () { + var _a, _b, _c; + return (_c = (_b = (_a = this.store) === null || _a === void 0 ? void 0 : _a.getIntegrationName) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : "mParticle_wsdkv_".concat(this.sdkVersion); + }; + ReportingLogger.prototype.isReportingEnabled = function () { + return this.isDebugModeEnabled() || this.isRoktDomainPresent() && this.isFeatureFlagEnabled(); + }; + ReportingLogger.prototype.isRoktDomainPresent = function () { + return typeof window !== 'undefined' && Boolean(window['ROKT_DOMAIN']); + }; + ReportingLogger.prototype.isDebugModeEnabled = function () { + var _a, _b, _c, _d; + return typeof window !== 'undefined' && ((_d = (_c = (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.search) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === null || _c === void 0 ? void 0 : _c.includes('mp_enable_logging=true')) !== null && _d !== void 0 ? _d : false); + }; + ReportingLogger.prototype.canSendLog = function (severity) { + return this.isEnabled && !this.isRateLimited(severity); + }; + ReportingLogger.prototype.isRateLimited = function (severity) { + return this.rateLimiter.incrementAndCheck(severity); + }; + ReportingLogger.prototype.getUrl = function () { + var _a; + return typeof window !== 'undefined' ? (_a = window.location) === null || _a === void 0 ? void 0 : _a.href : undefined; }; - return LoggingDispatcher; + ReportingLogger.prototype.getUserAgent = function () { + var _a; + return typeof window !== 'undefined' ? (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent : undefined; + }; + ReportingLogger.prototype.getHeaders = function () { + var _a; + var _b, _c; + var headers = (_a = {}, _a[HEADER_ACCEPT] = 'text/plain;charset=UTF-8', _a[HEADER_CONTENT_TYPE] = 'application/json', _a[HEADER_ROKT_LAUNCHER_VERSION] = this.getVersion(), _a[HEADER_ROKT_WSDK_VERSION] = 'joint', _a); + if (this.launcherInstanceGuid) { + headers[HEADER_ROKT_LAUNCHER_INSTANCE_GUID] = this.launcherInstanceGuid; + } + var accountId = (_c = (_b = this.store) === null || _b === void 0 ? void 0 : _b.getRoktAccountId) === null || _c === void 0 ? void 0 : _c.call(_b); + if (accountId) { + headers['rokt-account-id'] = accountId; + } + return headers; + }; + return ReportingLogger; + }(); + var RateLimiter = /** @class */function () { + function RateLimiter() { + this.rateLimits = new Map([[WSDKErrorSeverity.ERROR, 10], [WSDKErrorSeverity.WARNING, 10], [WSDKErrorSeverity.INFO, 10]]); + this.logCount = new Map(); + } + RateLimiter.prototype.incrementAndCheck = function (severity) { + var count = this.logCount.get(severity) || 0; + var limit = this.rateLimits.get(severity) || 10; + var newCount = count + 1; + this.logCount.set(severity, newCount); + return newCount > limit; + }; + return RateLimiter; }(); var Messages = Constants.Messages, @@ -10543,14 +10648,14 @@ var mParticle = (function () { console.error('Cannot reset mParticle', error); } }; - this._resetForTests = function (config, keepPersistence, instance) { + this._resetForTests = function (config, keepPersistence, instance, reportingLogger) { if (instance._Store) { delete instance._Store; } - instance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); - instance._LoggingDispatcher = new LoggingDispatcher(); - instance.Logger = new Logger(config); + instance.Logger = new Logger(config, reportingLogger); instance._Store = new Store(config, instance); + // Update ReportingLogger with the new Store reference to avoid stale data + reportingLogger === null || reportingLogger === void 0 ? void 0 : reportingLogger.setStore(instance._Store); instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability(window.localStorage); instance._Events.stopTracking(); if (!keepPersistence) { @@ -11366,12 +11471,6 @@ var mParticle = (function () { }; } }; - this.registerErrorReportingService = function (service) { - self._ErrorReportingDispatcher.register(service); - }; - this.registerLoggingService = function (service) { - self._LoggingDispatcher.register(service); - }; var launcherInstanceGuidKey = Constants.Rokt.LauncherInstanceGuidKey; this.setLauncherInstanceGuid = function () { if (!window[launcherInstanceGuidKey] || typeof window[launcherInstanceGuidKey] !== 'string') { @@ -11546,11 +11645,11 @@ var mParticle = (function () { } function runPreConfigFetchInitialization(mpInstance, apiKey, config) { var _a; - mpInstance._ErrorReportingDispatcher = new ErrorReportingDispatcher(); - mpInstance._LoggingDispatcher = new LoggingDispatcher(); - mpInstance.Logger = new Logger(config); + mpInstance._ReportingLogger = new ReportingLogger(config, Constants.sdkVersion, undefined, mpInstance.getLauncherInstanceGuid()); + mpInstance.Logger = new Logger(config, mpInstance._ReportingLogger); mpInstance._Store = new Store(config, mpInstance, apiKey); window.mParticle.Store = mpInstance._Store; + mpInstance._ReportingLogger.setStore(mpInstance._Store); mpInstance.Logger.verbose(StartingInitialization); // Initialize CookieConsentManager with privacy flags from launcherOptions var _b = (_a = config === null || config === void 0 ? void 0 : config.launcherOptions) !== null && _a !== void 0 ? _a : {}, @@ -12087,12 +12186,6 @@ var mParticle = (function () { this._setWrapperSDKInfo = function (name, version) { self.getInstance()._setWrapperSDKInfo(name, version); }; - this.registerErrorReportingService = function (service) { - self.getInstance().registerErrorReportingService(service); - }; - this.registerLoggingService = function (service) { - self.getInstance().registerLoggingService(service); - }; } var mParticleManager = new mParticleInstanceManager(); if (typeof window !== 'undefined') {