"use strict"; var mParticle = (function() { 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 > 2; enc2 = (chr1 & 3) > 4; enc3 = (chr2 & 15) > 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) { } 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 > 4; chr2 = (enc2 & 15) > 2; chr3 = (enc3 & 3) 127 && 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 191 && c >> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k >> 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 >> 0; if (typeof fun !== "function") { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] = 0; } else { for (var n = items.length; i > a / 4).toString(16); } return (a ^ Math.random() * 16 >> a / 4).toString(16); }; var generateUniqueId = function generateUniqueId2(a) { if (a === void 0) { a = ""; } return a ? generateRandomValue() : ( // [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 generateUniqueId2 // random hex digits ) ); }; var getRampNumber = function getRampNumber2(value) { if (!value) { return 100; } var hash = generateHash(value); return Math.abs(hash % 100) + 1; }; var isObject = function isObject2(value) { var objType = Object.prototype.toString.call(value); return objType === "[object Object]" || objType === "[object Error]"; }; var parseNumber = function parseNumber2(value) { if (isNaN(value) || !isFinite(value)) { return 0; } var floatValue = parseFloat(value); return isNaN(floatValue) ? 0 : floatValue; }; var parseSettingsString = function parseSettingsString2(settingsString) { try { return settingsString ? JSON.parse(settingsString.replace(/"/g, '"')) : []; } catch (error) { throw new Error("Settings string contains invalid JSON"); } }; var parseStringOrNumber = function parseStringOrNumber2(value) { if (isStringOrNumber(value)) { return value; } else { return null; } }; var replaceCommasWithPipes = function replaceCommasWithPipes2(value) { return value.replace(/,/g, "|"); }; var replacePipesWithCommas = function replacePipesWithCommas2(value) { return value.replace(/\|/g, ","); }; var replaceApostrophesWithQuotes = function replaceApostrophesWithQuotes2(value) { return value.replace(/\'/g, '"'); }; var replaceQuotesWithApostrophes = function replaceQuotesWithApostrophes2(value) { return value.replace(/\"/g, "'"); }; var replaceMPID = function replaceMPID2(value, mpid) { return value.replace("%%mpid%%", mpid); }; var replaceAmpWithAmpersand = function replaceAmpWithAmpersand2(value) { return value.replace(/&/g, "&"); }; var createCookieSyncUrl = function createCookieSyncUrl2(mpid, pixelUrl, redirectUrl, domain, base64Mpid) { 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); } if (base64Mpid) { var separator = fullUrl.includes("?") ? "&" : "?"; fullUrl += "".concat(separator, "google_hm=").concat(base64Mpid); } return fullUrl; }; var WEB_SAFE_BASE64_REPLACEMENTS = { "+": "-", "/": "_", "=": "" }; var toWebSafeBase64 = function toWebSafeBase642(value) { return btoa(value).replace(/[+/=]/g, function(c) { return WEB_SAFE_BASE64_REPLACEMENTS[c]; }); }; var returnConvertedBoolean = function returnConvertedBoolean2(data) { if (data === "false" || data === "0") { return false; } else { return Boolean(data); } }; var decoded = function decoded2(s) { return decodeURIComponent(s.replace(/\+/g, " ")); }; var converted = function converted2(s) { if (s.indexOf('"') === 0) { s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\"); } return s; }; var isString = function isString2(value) { return typeof value === "string"; }; var isNumber = function isNumber2(value) { return typeof value === "number"; }; var isBoolean = function isBoolean2(value) { return typeof value === "boolean"; }; var isFunction = function isFunction2(fn) { return typeof fn === "function"; }; var isValidAttributeValue = function isValidAttributeValue2(value) { return value !== void 0 && !isObject(value) && !Array.isArray(value); }; var isValidCustomFlagProperty = function isValidCustomFlagProperty2(value) { return isNumber(value) || isString(value) || isBoolean(value); }; var toDataPlanSlug = function toDataPlanSlug2(value) { return isStringOrNumber(value) ? value.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g, "_") : ""; }; var isDataPlanSlug = function isDataPlanSlug2(str) { return str === toDataPlanSlug(str); }; var isStringOrNumber = function isStringOrNumber2(value) { return isString(value) || isNumber(value); }; var isEmpty = function isEmpty2(value) { return value == null || !(Object.keys(value) || value).length; }; var moveElementToEnd = function moveElementToEnd2(array, index) { return array.slice(0, index).concat(array.slice(index + 1), array[index]); }; var queryStringParser = function queryStringParser2(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 queryStringParserFallback2(url) { var params = {}; var queryString = url.split("?")[1] || ""; var pairs = queryString.split("&"); pairs.forEach(function(pair) { var _a2 = pair.split("="), key = _a2[0], valueParts = _a2.slice(1); var value = valueParts.join("="); if (key && value !== void 0) { 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); } } } }; }; var getCookies = function getCookies2(keys) { var parseCookies = function parseCookies2() { 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 []; } }; var filterCookies = function filterCookies2(cookies, keys2) { var results = {}; for (var _i = 0, cookies_1 = cookies; _i = ProductActionType.ViewCart && id = BatchUploader2.MINIMUM_INTERVAL_MILLIS; if (this.uploadIntervalMillis = rampNumber; }; BatchUploader2.prototype.shouldDebounceAndUpdateLastASTTime = function() { var now = Date.now(); if (now - this.lastASTEventTime 0) { this.mpInstance.Logger.warning("Offline batch storage is over quota. Dropped " + "".concat(droppedBatchCount, " oldest batch(es).")); } }; BatchUploader2.prototype.uploadBatches = function(batches, useBeacon) { return __awaiter(this, void 0, void 0, function() { var uploads, uploadsToLog, i, fetchPayload, blob, response, e_1; return __generator(this, function(_a2) { switch (_a2.label) { case 0: uploads = batches.filter(function(batch) { return !isEmpty(batch.events); }); if (isEmpty(uploads)) { return [2, null]; } if (this.mpInstance.Logger.isVerbose()) { uploadsToLog = obfuscateDevData(uploads, this.mpInstance._Store.SDKConfig.isDevelopmentMode); this.mpInstance.Logger.verbose("Uploading batches: ".concat(JSON.stringify(uploadsToLog))); this.mpInstance.Logger.verbose("Batch count: ".concat(uploads.length)); } i = 0; _a2.label = 1; case 1: if (!(i = 200 && response.status = 500 || response.status === 429) { this.mpInstance.Logger.error("HTTP error status ".concat(response.status, " received")); return [2, uploads.slice(i, uploads.length)]; } else if (response.status >= 401) { this.mpInstance.Logger.error("HTTP error status ".concat(response.status, " while uploading - please verify your API key.")); return [2, null]; } else { 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, 5]; case 4: e_1 = _a2.sent(); this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(e_1)); return [2, uploads.slice(i, uploads.length)]; case 5: i++; return [3, 1]; case 6: return [2, null]; } }); }); }; BatchUploader2.CONTENT_TYPE = "text/plain;charset=UTF-8"; BatchUploader2.MINIMUM_INTERVAL_MILLIS = 500; return BatchUploader2; })() ); var ErrorCodes = { UNKNOWN_ERROR: "UNKNOWN_ERROR", UNHANDLED_EXCEPTION: "UNHANDLED_EXCEPTION", IDENTITY_REQUEST: "IDENTITY_REQUEST", IDENTITY_MISMATCH: "IDENTITY_MISMATCH", MP_DEPRECATED_METHOD_USAGE: "MP_DEPRECATED_METHOD_USAGE" }; var WSDKErrorSeverity = { ERROR: "ERROR", INFO: "INFO", WARNING: "WARNING" }; var Modify$4 = Constants.IdentityMethods.Modify; var Validators = { // From ./utils // Utility Functions for backwards compatability isNumber, isFunction, isStringOrNumber, // Validator Functions 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]; 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$4) { 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 { if (identityApiData.userIdentities === void 0) { return { valid: false, error: Constants.Messages.ValidationMessages.UserIdentities }; } 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 HTTPCodes$4 = Constants.HTTPCodes; var sendSearchRequest = function sendSearchRequest2(knownIdentities, apiKey, requestBuilder, searchUrl, callback, logger, uploader, errorReporter) { return __awaiter(void 0, void 0, void 0, function() { var safeInvoke, cleanedKnownIdentities, requestEnvelope, requestBody, fetchPayload, api, response, body, xhrLike, e_2, message, reportMessage; return __generator(this, function(_a2) { switch (_a2.label) { case 0: if (!isFunction(callback)) { logger.error("search called without a callback function; skipping request."); return [ 2 /*return*/ ]; } safeInvoke = function safeInvoke2(result) { try { callback(result); } catch (e) { logger.error("Error invoking search callback: " + getErrorMessage(e)); } }; cleanedKnownIdentities = Validators.removeFalsyIdentityValues({ userIdentities: knownIdentities !== null && knownIdentities !== void 0 ? knownIdentities : {} }, logger).userIdentities; if (!Object.values(cleanedKnownIdentities !== null && cleanedKnownIdentities !== void 0 ? cleanedKnownIdentities : {}).some(function(v) { return typeof v === "string" && v.length > 0; })) { logger.verbose("Identity search called with empty identifiers; skipping request."); safeInvoke({ httpCode: HTTPCodes$4.noHttpCoverage }); return [ 2 /*return*/ ]; } if (!apiKey) { logger.verbose("search called without a workspace API key; skipping request."); safeInvoke({ httpCode: HTTPCodes$4.noHttpCoverage }); return [ 2 /*return*/ ]; } _a2.label = 1; case 1: _a2.trys.push([1, 9, , 10]); requestEnvelope = requestBuilder(); requestBody = __assign(__assign({}, requestEnvelope), { known_identities: __assign({}, cleanedKnownIdentities) }); fetchPayload = { method: "post", headers: { Accept: "application/json", "Content-Type": "application/json", "x-mp-key": apiKey }, body: JSON.stringify(requestBody) }; api = uploader || (window.fetch ? new FetchUploader(searchUrl) : new XHRUploader(searchUrl)); logger.verbose("Sending search request to " + searchUrl); return [4, api.upload(fetchPayload, searchUrl)]; case 2: response = _a2.sent(); body = void 0; if (!isFunction(response.json)) return [3, 7]; _a2.label = 3; case 3: _a2.trys.push([3, 5, , 6]); return [4, response.json()]; case 4: body = _a2.sent(); return [3, 6]; case 5: _a2.sent(); logger.verbose("search response had no parseable JSON body."); return [3, 6]; case 6: return [3, 8]; case 7: xhrLike = response; if (xhrLike === null || xhrLike === void 0 ? void 0 : xhrLike.responseText) { try { body = JSON.parse(xhrLike.responseText); } catch (e) { logger.verbose("search XHR response was not valid JSON."); } } _a2.label = 8; case 8: if (response.status === HTTP_OK) { logger.verbose("search received 200 OK."); } else if (response.status === HTTP_NOT_FOUND) { logger.verbose("search received 404 (no match)."); } else { logger.verbose("search received non-success status " + response.status); } safeInvoke({ httpCode: response.status, body }); return [3, 10]; case 9: e_2 = _a2.sent(); message = getErrorMessage(e_2); reportMessage = "Error sending search request: " + message; logger.error(reportMessage); errorReporter === null || errorReporter === void 0 ? void 0 : errorReporter.report({ message: reportMessage, code: ErrorCodes.IDENTITY_REQUEST, severity: WSDKErrorSeverity.ERROR }); safeInvoke({ httpCode: HTTPCodes$4.noHttpCoverage }); return [3, 10]; case 10: return [ 2 /*return*/ ]; } }); }); }; var _a$1 = Constants.IdentityMethods, Identify$2 = _a$1.Identify, Modify$3 = _a$1.Modify, Login$2 = _a$1.Login, Logout$2 = _a$1.Logout; var HTTPCodes$3 = Constants.HTTPCodes, Messages$9 = Constants.Messages; var CACHE_HEADER = "x-mp-max-age"; var cacheOrClearIdCache = function cacheOrClearIdCache2(method, knownIdentities, idCache, identityResponse, parsingCachedResponse) { if (parsingCachedResponse) { return; } 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$3: case Logout$2: idCache.purge(); break; } }; var cacheIdentityRequest = function cacheIdentityRequest2(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, is_logged_in }; cache[hashedKey] = { responseText: JSON.stringify(cachedResponseBody), status, expireTimestamp }; idCache.store(cache); }; var concatenateIdentities = function concatenateIdentities2(method, userIdentities) { var DEVICE_APPLICATION_STAMP = "device_application_stamp"; 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(); 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 hasValidCachedIdentity2(method, proposedUserIdentities, idCache) { var cache = idCache === null || idCache === void 0 ? void 0 : idCache.retrieve(); if (!cache) { return false; } var cacheKey = concatenateIdentities(method, proposedUserIdentities); var hashedKey = generateHash(cacheKey); if (!cache.hasOwnProperty(hashedKey)) { return false; } var expireTimestamp = cache[hashedKey].expireTimestamp; if (expireTimestamp 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; } }; 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; var androidBridgeNameBase = "mParticleAndroid"; var iosBridgeNameBase = "mParticle"; function getAndroidBridge(name) { if (!Object.prototype.hasOwnProperty.call(window, name)) { return void 0; } return window[name]; } function getInstanceNamedValue(instance, name) { return instance[name]; } 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) { var _a2, _b2; if (!bridgeName) { return false; } var androidBridgeName = androidBridgeNameBase + "_" + bridgeName + "_v2"; var iosBridgeName = iosBridgeNameBase + "_" + bridgeName + "_v2"; if ((_b2 = (_a2 = window.webkit) === null || _a2 === void 0 ? void 0 : _a2.messageHandlers) === null || _b2 === void 0 ? void 0 : _b2.hasOwnProperty(iosBridgeName)) { return true; } if (window.mParticle && window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName === iosBridgeName) { return true; } 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; } if (window.mParticle) { if (window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName !== iosBridgeNameBase + "_" + requiredWebviewBridgeName + "_v2") { return false; } } if (minWebviewBridgeVersion new Date(lastSyncDate).getTime() + frequencyCap * DAYS_IN_MILLISECONDS; }; function logDeprecatedMethodUsage(usage, logger, errorReporter) { logger.warning(usage.warningMessage); errorReporter === null || errorReporter === void 0 ? void 0 : errorReporter.report({ message: usage.methodName, code: ErrorCodes.MP_DEPRECATED_METHOD_USAGE, severity: WSDKErrorSeverity.WARNING }); } var Messages$6 = Constants.Messages; function SessionManager(mpInstance) { var self = this; this.initialize = function() { var _a2; if (mpInstance._Store.sessionId) { var _b2 = mpInstance._Store, dateLastEventSent = _b2.dateLastEventSent, SDKConfig = _b2.SDKConfig; var sessionTimeout = SDKConfig.sessionTimeout; if (hasSessionTimedOut(dateLastEventSent === null || dateLastEventSent === void 0 ? void 0 : dateLastEventSent.getTime(), sessionTimeout)) { self.endSession(); self.startNewSession(); } else { var currentUser = mpInstance.Identity.getCurrentUser(); var sdkIdentityRequest = SDKConfig.identifyRequest; var shouldSuppressIdentify = ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.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() { logDeprecatedMethodUsage({ methodName: "SessionManager.getSession()", warningMessage: generateDeprecationMessage("SessionManager.getSession()", false, "SessionManager.getSessionId()") }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher); return this.getSessionId(); }; this.getSessionId = function() { return mpInstance._Store.sessionId; }; this.startNewSession = function() { var _a2; 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 = /* @__PURE__ */ new Date(); mpInstance._Store.sessionStartDate = date; mpInstance._Store.dateLastEventSent = date; } self.setSessionTimer(); var shouldSuppressIdentify = ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.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 _a2, _b2, _c, _d; mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingEndSession); if (override) { performSessionEnd(); return; } if (!mpInstance._Helpers.canLog()) { mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession); (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.resetTimer(); return; } var cookies = mpInstance._Persistence.getPersistence(); if (!cookies || cookies.gs && !cookies.gs.sid) { mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd); (_b2 = mpInstance._timeOnSiteTimer) === null || _b2 === void 0 ? void 0 : _b2.resetTimer(); return; } 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 * 6e4; 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(); } } } }; function hasSessionTimedOut(lastEventTimestamp, sessionTimeout) { if (!lastEventTimestamp || !sessionTimeout || sessionTimeout = sessionTimeoutInMilliseconds; } function performSessionEnd() { var _a2; mpInstance._Events.logEvent({ messageType: Types.MessageType.SessionEnd }); mpInstance._Store.nullifySession(); (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.resetTimer(); } } var Messages$5 = Constants.Messages; function Ecommerce(mpInstance) { var self = this; 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.calculateProductActionTotalAmount = function(productAction) { if (!productAction || productAction.TotalAmount != null) { return productAction; } var totalAmount = 0; if (Array.isArray(productAction.ProductList)) { productAction.ProductList.forEach(function(product) { totalAmount += parseNumber(product.Quantity) * parseNumber(product.Price); }); } totalAmount += parseNumber(productAction.ShippingAmount) + parseNumber(productAction.TaxAmount); productAction.TotalAmount = totalAmount; return productAction; }; 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.ViewCart: return "ViewCart"; case Types.ProductActionType.AddShippingInfo: return "AddShippingInfo"; case Types.ProductActionType.AddPaymentInfo: return "AddPaymentInfo"; case Types.ProductActionType.PaymentMethodSelected: return "PaymentMethodSelected"; case Types.ProductActionType.PaymentAttempted: return "PaymentAttempted"; case Types.ProductActionType.PaymentSucceeded: return "PaymentSucceeded"; case Types.ProductActionType.PaymentFailed: return "PaymentFailed"; case Types.ProductActionType.RefundInitiated: return "RefundInitiated"; 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; // Rokt Brain commerce-adjacent types map to Unknown on server case Types.ProductActionType.ViewCart: case Types.ProductActionType.AddShippingInfo: case Types.ProductActionType.AddPaymentInfo: case Types.ProductActionType.PaymentMethodSelected: case Types.ProductActionType.PaymentAttempted: case Types.ProductActionType.PaymentSucceeded: case Types.ProductActionType.PaymentFailed: case Types.ProductActionType.RefundInitiated: return Types.EventType.Unknown; 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"); }; 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; }; this.extractTransactionId = function(attributes, productAction) { if (productAction.TransactionId) { attributes["Transaction Id"] = productAction.TransactionId; } }; 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; } }; 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 = 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 = 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 = 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 attributes2 = extend(false, commerceEvent.EventAttributes, product.Attributes); if (shouldExtractActionAttributes) { self.extractActionAttributes(attributes2, commerceEvent.ProductAction); } else { self.extractTransactionId(attributes2, commerceEvent.ProductAction); } self.extractProductAttributes(attributes2, product); var productEvent = mpInstance._ServerModel.createEventObject({ messageType: Types.MessageType.PageEvent, name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType)), data: attributes2, eventType: Types.EventType.Transaction }); appEvents.push(productEvent); }); return appEvents; }; this.createCommerceEventObject = function(customFlags, options) { var baseEvent; var extend2 = 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 = extend2(baseEvent.CustomFlags, customFlags); return baseEvent; } else { mpInstance.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent); } return null; }; this.sanitizeAmount = function(amount, category) { if (!mpInstance._Helpers.Validators.isStringOrNumber(amount)) { var message = [category, "must be of type number. A", _typeof(amount), "was passed. Converting to 0"].join(" "); mpInstance.Logger.warning(message); return 0; } return mpInstance._Helpers.parseNumber(amount); }; } var ForegroundTimeTracker = ( /** @class */ (function() { function ForegroundTimeTracker2(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(); } } ForegroundTimeTracker2.prototype.addHandlers = function() { var _this = this; document.addEventListener("visibilitychange", function() { return _this.handleVisibilityChange(); }); window.addEventListener("blur", function() { return _this.handleWindowBlur(); }); window.addEventListener("focus", function() { return _this.handleWindowFocus(); }); window.addEventListener("storage", function(event) { return _this.syncAcrossTabs(event); }); window.addEventListener("beforeunload", function() { return _this.updateTimeInPersistence(); }); }; ForegroundTimeTracker2.prototype.handleVisibilityChange = function() { if (document.hidden) { this.stopTracking(); } else { this.startTracking(); } }; ForegroundTimeTracker2.prototype.handleWindowBlur = function() { if (this.isTrackerActive) { this.stopTracking(); } }; ForegroundTimeTracker2.prototype.handleWindowFocus = function() { if (!this.isTrackerActive) { this.startTracking(); } }; ForegroundTimeTracker2.prototype.syncAcrossTabs = function(event) { if (event.key === this.localStorageName && event.newValue !== null) { var newTime = parseFloat(event.newValue) || 0; this.totalTime = newTime; } }; ForegroundTimeTracker2.prototype.updateTimeInPersistence = function() { if (this.isTrackerActive && !this.noFunctional) { this.timerVault.store(Math.round(this.totalTime)); } }; ForegroundTimeTracker2.prototype.loadTimeFromStorage = function() { var storedTime = this.timerVault.retrieve(); if (isNumber(storedTime) && storedTime !== null) { this.totalTime = storedTime; } }; ForegroundTimeTracker2.prototype.startTracking = function() { if (!document.hidden) { this.startTime = Math.floor(performance.now()); this.isTrackerActive = true; } }; ForegroundTimeTracker2.prototype.stopTracking = function() { if (this.isTrackerActive) { this.setTotalTime(); this.updateTimeInPersistence(); this.isTrackerActive = false; } }; ForegroundTimeTracker2.prototype.setTotalTime = function() { if (this.isTrackerActive) { var now = Math.floor(performance.now()); this.totalTime += now - this.startTime; this.startTime = now; } }; ForegroundTimeTracker2.prototype.getTimeInForeground = function() { this.setTotalTime(); this.updateTimeInPersistence(); return this.totalTime; }; ForegroundTimeTracker2.prototype.resetTimer = function() { this.totalTime = 0; this.updateTimeInPersistence(); }; return ForegroundTimeTracker2; })() ); function normalizeRoktLauncherOptions(launcherOptions) { var normalizedOptions = launcherOptions ? __assign({}, launcherOptions) : {}; var hasNoDeviceId = normalizedOptions.noDeviceId === true || normalizedOptions.noDeviceID === true; if (hasNoDeviceId) { normalizedOptions.noDeviceId = true; normalizedOptions.noFunctional = true; normalizedOptions.noTargeting = true; } return normalizedOptions; } function createSDKConfig(config) { 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]; } sdkConfig.flags = sdkConfig.flags || {}; return sdkConfig; } 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(); 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(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; } 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"); this.SDKConfig.onCreateBatch = void 0; } } } this._getFromPersistence = function(mpid, key2) { if (!mpid) { return null; } _this.syncPersistenceData(); if (_this.persistenceData && _this.persistenceData[mpid] && _this.persistenceData[mpid][key2]) { return _this.persistenceData[mpid][key2]; } else { return null; } }; this._setPersistence = function(mpid, key2, value) { var _a2; if (!mpid) { return; } _this.syncPersistenceData(); if (_this.persistenceData) { if (_this.persistenceData[mpid]) { _this.persistenceData[mpid][key2] = value; } else { _this.persistenceData[mpid] = (_a2 = {}, _a2[key2] = value, _a2); } if (isObject(_this.persistenceData[mpid][key2]) && isEmpty(_this.persistenceData[mpid][key2])) { delete _this.persistenceData[mpid][key2]; } 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 || 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 || (/* @__PURE__ */ new Date()).getTime(); _this._setPersistence(mpid, "fst", time); }; this.getLastSeenTime = function(mpid) { if (!mpid) { return null; } var currentUser = mpInstance.Identity.getCurrentUser(); if (mpid === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.getMPID())) { return (/* @__PURE__ */ new Date()).getTime(); } return _this._getFromPersistence(mpid, "lst"); }; this.setLastSeenTime = function(mpid, _time) { if (!mpid) { return; } var time = _time || (/* @__PURE__ */ new Date()).getTime(); _this._setPersistence(mpid, "lst", time); }; this.getLocalSessionAttributes = function() { return _this.localSessionAttributes || {}; }; this.setLocalSessionAttribute = function(key2, value) { var _a2; _this.localSessionAttributes[key2] = value; _this.persistenceData.gs.lsa = __assign(__assign({}, _this.persistenceData.gs.lsa || {}), (_a2 = {}, _a2[key2] = value, _a2)); mpInstance._Persistence.savePersistence(_this.persistenceData); }; this.syncPersistenceData = function() { var persistenceData = mpInstance._Persistence.getPersistence(); _this.persistenceData = 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.getTimeOnSite = function() { var _a2; return (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.getTimeInForeground(); }; this.getTotalTimeOnSite = function() { return _this.sessionStartDate ? Date.now() - _this.sessionStartDate.getTime() : void 0; }; this.addMpidToSessionHistory = function(mpid, previousMPID) { var indexOfMPID = _this.currentSessionMPIDs.indexOf(mpid); if (mpid && previousMPID !== mpid && 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(config2) { var workspaceToken = config2.workspaceToken, requiredWebviewBridgeName = config2.requiredWebviewBridgeName; if (config2.flags) { _this.SDKConfig.flags = processFlags(config2); } var baseUrls2 = processBaseUrls(config2, _this.SDKConfig.flags, apiKey); for (var baseUrlKeys2 in baseUrls2) { _this.SDKConfig[baseUrlKeys2] = baseUrls2[baseUrlKeys2]; } if (workspaceToken) { _this.SDKConfig.workspaceToken = workspaceToken; var noFunctional = normalizeRoktLauncherOptions(config2 === null || config2 === void 0 ? void 0 : config2.launcherOptions).noFunctional; mpInstance._timeOnSiteTimer = new ForegroundTimeTracker(workspaceToken, noFunctional); } else { mpInstance.Logger.warning("You should have a workspaceToken on your config object for security purposes."); } _this.storageName = createMainStorageName(workspaceToken); _this.SDKConfig.requiredWebviewBridgeName = requiredWebviewBridgeName || workspaceToken; _this.webviewBridgeEnabled = isWebviewEnabled(_this.SDKConfig.requiredWebviewBridgeName, _this.SDKConfig.minWebviewBridgeVersion); _this.configurationLoaded = true; }; } function processFlags(config) { var flags = {}; var _a2 = Constants.FeatureFlags, ReportBatching2 = _a2.ReportBatching, EventBatchingIntervalMillis = _a2.EventBatchingIntervalMillis, OfflineStorage = _a2.OfflineStorage, DirectUrlRouting = _a2.DirectUrlRouting, CacheIdentity2 = _a2.CacheIdentity, AudienceAPI = _a2.AudienceAPI, CaptureIntegrationSpecificIds2 = _a2.CaptureIntegrationSpecificIds, CaptureIntegrationSpecificIdsV22 = _a2.CaptureIntegrationSpecificIdsV2, AstBackgroundEvents = _a2.AstBackgroundEvents, AutoLogPageView = _a2.AutoLogPageView; if (!config.flags) { return {}; } flags[ReportBatching2] = config.flags[ReportBatching2] || false; flags[EventBatchingIntervalMillis] = parseNumber(config.flags[EventBatchingIntervalMillis]) || Constants.DefaultConfig.uploadInterval; flags[OfflineStorage] = config.flags[OfflineStorage] || "0"; flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === "True"; flags[CacheIdentity2] = config.flags[CacheIdentity2] === "True"; flags[AudienceAPI] = config.flags[AudienceAPI] === "True"; flags[CaptureIntegrationSpecificIds2] = config.flags[CaptureIntegrationSpecificIds2] === "True"; flags[CaptureIntegrationSpecificIdsV22] = config.flags[CaptureIntegrationSpecificIdsV22] || "none"; flags[AstBackgroundEvents] = config.flags[AstBackgroundEvents] === "True"; flags[AutoLogPageView] = config.flags[AutoLogPageView] === "True"; return flags; } function processBaseUrls(config, flags, apiKey) { if (!apiKey) { return {}; } if (!isEmpty(config.domain)) { return processCustomBaseUrls(config); } if (flags.directURLRouting) { return processDirectBaseUrls(config, apiKey); } else { return processCustomBaseUrls(config); } } function processCustomBaseUrls(config) { var defaultBaseUrls = Constants.DefaultBaseUrls; var CNAMEUrlPaths = Constants.CNAMEUrlPaths; var newBaseUrls = {}; 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 = {}; var DEFAULT_SILO = "us1"; var splitKey = apiKey.split("-"); var routingPrefix = splitKey.length maxCookieSize; } function removeUnsessionedMpidsWhenOversized(persistence, expires, domain, maxCookieSize) { var encodedCookiesWithExpirationAndPath; for (var key in persistence) { if (!persistence.hasOwnProperty(key)) { continue; } encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); if (!isEncodedCookieTooLarge(encodedCookiesWithExpirationAndPath, maxCookieSize)) { continue; } if (SDKv2NonMPIDCookieKeys[key] || key === persistence.cu) { continue; } delete persistence[key]; } return encodedCookiesWithExpirationAndPath; } function collectRemovableMpids(persistence) { var MPIDsOnCookie = {}; for (var potentialMPID in persistence) { if (!persistence.hasOwnProperty(potentialMPID)) { continue; } if (SDKv2NonMPIDCookieKeys[potentialMPID] || potentialMPID === persistence.cu) { continue; } MPIDsOnCookie[potentialMPID] = 1; } return MPIDsOnCookie; } function removeMpidsNotInCurrentSession(persistence, MPIDsOnCookie, currentSessionMPIDs, expires, domain, maxCookieSize) { var encodedCookiesWithExpirationAndPath; for (var mpid in MPIDsOnCookie) { encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); if (!isEncodedCookieTooLarge(encodedCookiesWithExpirationAndPath, maxCookieSize)) { continue; } if (!MPIDsOnCookie.hasOwnProperty(mpid)) { continue; } if (currentSessionMPIDs.indexOf(mpid) === -1) { delete persistence[mpid]; } } return encodedCookiesWithExpirationAndPath; } function logAndRemoveOversizedMpid(persistence, MPIDtoRemove, maxCookieSize) { 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], null, 2)); delete persistence[MPIDtoRemove]; return; } 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."); } function removeCurrentSessionMpidsByAge(persistence, currentSessionMPIDs, expires, domain, maxCookieSize) { var encodedCookiesWithExpirationAndPath; for (var i = 0; i 0; } if (!mpInstance._Helpers.isObject(value)) { return false; } return Object.keys(value).length > 0; } function encodeGsBase64Field(gs, key) { if (!gs[key] || !isNonEmptyArrayOrObject(gs[key])) { delete gs[key]; return; } gs[key] = Base64.encode(JSON.stringify(gs[key])); } function encodeGlobalSettings(gs) { for (var key in gs) { if (!gs.hasOwnProperty(key)) { continue; } if (Base64CookieKeys[key]) { encodeGsBase64Field(gs, key); continue; } if (key === "ie") { gs[key] = gs[key] ? 1 : 0; continue; } if (!gs[key]) { delete gs[key]; } } } function encodeMpidBase64Field(container, key) { var value = container[key]; if (mpInstance._Helpers.isObject(value) && Object.keys(value).length) { container[key] = Base64.encode(JSON.stringify(value)); return; } delete container[key]; } function encodeMpidRecord(record) { for (var key in record) { if (!record.hasOwnProperty(key)) { continue; } if (Base64CookieKeys[key]) { encodeMpidBase64Field(record, key); } } } function encodeMpidRecords(persistence) { for (var mpid in persistence) { if (!persistence.hasOwnProperty(mpid)) { continue; } if (SDKv2NonMPIDCookieKeys[mpid]) { continue; } encodeMpidRecord(persistence[mpid]); } } this.encodePersistence = function(persistenceString) { var persistence = JSON.parse(persistenceString); encodeGlobalSettings(persistence.gs); encodeMpidRecords(persistence); return createCookieString(JSON.stringify(persistence)); }; function decodeGlobalSettings(gs) { for (var key in gs) { if (!gs.hasOwnProperty(key)) { continue; } if (Base64CookieKeys[key]) { gs[key] = JSON.parse(Base64.decode(gs[key])); continue; } if (key === "ie") { gs[key] = Boolean(gs[key]); } } } function decodeMpidRecord(record) { for (var key in record) { if (!record.hasOwnProperty(key)) { continue; } if (!Base64CookieKeys[key]) { continue; } if (record[key].length) { record[key] = JSON.parse(Base64.decode(record[key])); } } } function decodeMpidRecords(persistence) { for (var mpid in persistence) { if (!persistence.hasOwnProperty(mpid)) { continue; } if (!SDKv2NonMPIDCookieKeys[mpid]) { decodeMpidRecord(persistence[mpid]); continue; } if (mpid === "l") { persistence[mpid] = Boolean(persistence[mpid]); } } } this.decodePersistence = function(persistenceString) { try { if (!persistenceString) { return; } var persistence = JSON.parse(revertCookieString(persistenceString)); if (mpInstance._Helpers.isObject(persistence) && Object.keys(persistence).length) { decodeGlobalSettings(persistence.gs); decodeMpidRecords(persistence); } return JSON.stringify(persistence); } catch (e) { mpInstance.Logger.error("Problem with decoding cookie"); } }; 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.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 }; } } 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); } } }; this.savePersistence = function(persistence) { var _a2; if ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) { return; } var encodedPersistence = self.encodePersistence(JSON.stringify(persistence)), date = /* @__PURE__ */ new Date(), key = mpInstance._Store.storageName, expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1e3).toUTCString(), 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) { try { localStorage.setItem(mpInstance._Store.storageName, encodedPersistence); } catch (e) { mpInstance.Logger.error("Error saving persistence to localStorage."); } } } }; 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; } }; this.setFirstSeenTime = function(mpid, time) { if (!mpid) { return; } if (!time) { time = (/* @__PURE__ */ 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); } } }; this.getLastSeenTime = function(mpid) { if (!mpid) { return null; } if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) { return (/* @__PURE__ */ 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; } if (!time) { time = (/* @__PURE__ */ 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); var mParticleManager2 = getMParticleManager(); if (mParticleManager2 === null || mParticleManager2 === void 0 ? void 0 : mParticleManager2._isTestEnv) { var testWorkspaceToken = "abcdef"; localStorage.removeItem(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); self.expireCookies(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); } }; this.forwardingStatsBatches = { uploadsTable: {}, forwardingStatsEventQueue: [] }; } var HISTORY_METHODS = ["pushState", "replaceState"]; var WRAPPED_MARKER = "__mpApvWrapped__"; var WIN_APV_KEY = "__mpApv__"; var ALLOWED_QUERY_PARAMS = [ // Campaign attribution "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "utm_id", // Ad-network click ids "gclid", "gbraid", "wbraid", "fbclid", "msclkid", "ttclid", "twclid", "li_fat_id", "dclid", // OAuth / OIDC — see the SECURITY note above "client_id", "redirect_uri", "response_type", "scope", "state", "code", "nonce", // Pagination and search "page", "limit", "offset", "cursor", "per_page", "q", "search", // Referral "ref", "referrer" ]; var allowedQueryParams = function allowedQueryParams2(href) { return queryStringParser(href, ALLOWED_QUERY_PARAMS); }; var capturedNames = function capturedNames2(params) { return ALLOWED_QUERY_PARAMS.filter(function(name) { return name in params; }); }; var pageKey = function pageKey2(page) { var query = capturedNames(page.params).map(function(name) { return "".concat(name, "=").concat(encodeURIComponent(page.params[name])); }).join("&"); return query ? "".concat(page.path, "?").concat(query) : page.path; }; var isNewPage = function isNewPage2(lastKey, candidateKey) { return candidateKey !== lastKey; }; var supportsHistoryTracking = function supportsHistoryTracking2(win) { return !!win && win.history !== void 0 && typeof win.history.pushState === "function" && typeof win.addEventListener === "function"; }; var buildPageViewEvent = function buildPageViewEvent2(_a2) { var params = _a2.params, hostname = _a2.hostname, title = _a2.title, path = _a2.path; return { messageType: MessageType$1.PageView, name: "PageView", // Params spread first, then the core fields by name, so a core field always // wins. No allowlist entry collides with hostname/title/path today; naming // them here is what keeps a later addition from silently overwriting one. data: __assign(__assign({}, params), { hostname, title, path }), eventType: EventType.Unknown }; }; var apvWindow = function apvWindow2() { return typeof window === "undefined" ? null : window; }; var freshState = function freshState2() { return { initialPageViewFired: false }; }; var readState = function readState2() { var win = apvWindow(); return win ? win[WIN_APV_KEY] : void 0; }; var writeState = function writeState2() { var win = apvWindow(); if (!win) { return null; } if (!win[WIN_APV_KEY]) { win[WIN_APV_KEY] = freshState(); } return win[WIN_APV_KEY]; }; var getActiveTracker = function getActiveTracker2() { var state = readState(); return state ? state.tracker : void 0; }; var hasInitialPageViewFired = function hasInitialPageViewFired2() { var state = readState(); return !!(state && state.initialPageViewFired); }; var markInitialPageViewFired = function markInitialPageViewFired2() { var state = writeState(); if (state) { state.initialPageViewFired = true; } }; var resetPageViewTracking = function resetPageViewTracking2() { var win = apvWindow(); if (!win) { return; } var active = getActiveTracker(); if (active) { active.teardown(); } win[WIN_APV_KEY] = freshState(); }; var setActiveTracker = function setActiveTracker2(tracker) { var state = writeState(); if (state) { state.tracker = tracker; } }; var clearActiveTracker = function clearActiveTracker2(tracker) { var state = readState(); if (state && state.tracker === tracker) { state.tracker = void 0; } }; var currentPage = function currentPage2() { return { path: window.location.pathname, params: allowedQueryParams(getHref()) }; }; var describePage = function describePage2(page) { if (!page) { return ""; } var names = capturedNames(page.params); return names.length ? "".concat(page.path, " (params: ").concat(names.join(), ")") : page.path; }; var patchHistory = function patchHistory2(onNavigate, log) { if (window.history.pushState[WRAPPED_MARKER]) { log("[patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DETECTED"); return null; } var originals = {}; var wrappers = {}; HISTORY_METHODS.forEach(function(name) { var original = window.history[name]; originals[name] = original; var wrapper = function wrapper2() { var args = []; for (var _i = 0; _i _Events.logEvent(PageView) (page: ".concat(describePage(page), ", title: ").concat(title, ")")); this.mpInstance._Events.logEvent(event); }; PageViewTracker2.prototype.log = function(message) { this.mpInstance.Logger.verbose("mParticle APV: ".concat(message)); }; return PageViewTracker2; })() ); 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(position2) { mpInstance._Store.currentPosition = { lat: position2.coords.latitude, lng: position2.coords.longitude }; triggerCallback(callback, position2); callback = null; mpInstance._Store.isTracking = true; } function errorTracking() { triggerCallback(callback); callback = null; mpInstance._Store.isTracking = false; } function triggerCallback(callback2, position2) { if (callback2) { try { if (position2) { callback2(position2); } else { callback2(); } } 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.logPageView = function() { self.logEvent({ messageType: Types.MessageType.PageView, name: "PageView", data: __assign(__assign({}, allowedQueryParams(getHref())), { hostname: window.location.hostname, title: window.document.title }), eventType: Types.EventType.Unknown }); }; 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(product2) { if (product2.TotalAmount) { product2.TotalAmount = mpInstance._Ecommerce.sanitizeAmount(product2.TotalAmount, "TotalAmount"); } if (product2.Position) { product2.Position = mpInstance._Ecommerce.sanitizeAmount(product2.Position, "Position"); } if (product2.Price) { product2.Price = mpInstance._Ecommerce.sanitizeAmount(product2.Price, "Price"); } if (product2.Quantity) { product2.Quantity = mpInstance._Ecommerce.sanitizeAmount(product2.Quantity, "Quantity"); } }); if (event) { event.EventCategory = mpInstance._Ecommerce.convertProductActionToEventType(productActionType); event.EventName += mpInstance._Ecommerce.getProductActionEventName(productActionType); event.ProductAction = { ProductActionType: productActionType, ProductList: productList }; if (Types.ProductActionType.isRoktCommerceType(productActionType)) { event.CustomFlags = event.CustomFlags || {}; event.CustomFlags["Rokt.CommerceEventType"] = Types.ProductActionType.getExpansionName(productActionType); } 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(impression2) { event.ProductImpressions.push({ ProductImpressionList: impression2.Name, ProductList: Array.isArray(impression2.Product) ? impression2.Product : [impression2.Product] }); }); self.logCommerceEvent(event, attrs, options); } }; this.logCommerceEvent = function(commerceEvent, attrs, options) { mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent); 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; } var sanitizedAttrs = mpInstance._Helpers.sanitizeAttributes(attrs, commerceEvent.EventName); if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { commerceEvent.ShoppingCart = {}; } if (sanitizedAttrs) { commerceEvent.EventAttributes = sanitizedAttrs; } if (commerceEvent.ProductAction) { mpInstance._Ecommerce.calculateProductActionTotalAmount(commerceEvent.ProductAction); } mpInstance._APIClient.sendEventToServer(commerceEvent, options); mpInstance._Persistence.update(); } else { mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); } }; this.addEventHandler = function(domEvent, selector, eventName, data, eventType) { var elements = [], handler = function handler2(e) { var timeoutHandler = function timeoutHandler2() { 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 }); if (element.href && element.target !== "_blank" || element.submit) { 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; } 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 0; var isMatch = hasUserAttributes ? userAttributesMatchFilter(userAttributes, filterObject) : false; return filterObject.includeOnMatch === isMatch; } catch (e) { 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) { if (mpInstance._Store.webviewBridgeEnabled || !mpInstance._Store.activeForwarders) { return; } var hashedEventName = KitFilterHelper.hashEventName(event.EventName, event.EventCategory); var hashedEventType = KitFilterHelper.hashEventType(event.EventCategory); var forwardEvent = function forwardEvent2(forwarder) { if (isBlockedByForwardingRule(event.EventDataType, event.EventAttributes, forwarder)) { return; } var clonedEvent = extend(true, {}, event); if (isBlockedByEventFilter(event.EventDataType, hashedEventName, hashedEventType, forwarder)) { return; } clonedEvent.EventAttributes = filterEventAttributes(event.EventDataType, event.EventCategory, event.EventName, clonedEvent.EventAttributes, forwarder); clonedEvent.UserIdentities = filterUserIdentities(clonedEvent.UserIdentities, forwarder.userIdentityFilters); clonedEvent.UserAttributes = KitFilterHelper.filterUserAttributes(clonedEvent.UserAttributes, forwarder.userAttributeFilters); if (!forwarder.process) { return; } mpInstance.Logger.verbose("Sending message to forwarder: " + forwarder.name); var result = forwarder.process(clonedEvent); if (result) { mpInstance.Logger.verbose(result); } }; mpInstance._Store.activeForwarders.forEach(function(forwarder) { forwardEvent(forwarder); }); }; 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 = void 0; 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); } }); }; 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 kitMethodName = identityCompleteKitMethods[identityMethod]; if (!kitMethodName) { return; } mpInstance._Store.activeForwarders.forEach(function(forwarder) { var onIdentityComplete = forwarder[kitMethodName]; if (!onIdentityComplete) { return; } var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); var result = onIdentityComplete.call(forwarder, filteredUser, filteredUser.getUserIdentities()); if (result) { mpInstance.Logger.verbose(result); } }); }; this.getForwarderStatsQueue = function() { return mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue; }; this.setForwarderStatsQueue = function(queue) { mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue; }; 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); } }; 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 (!isEmpty(mpInstance._Store.SDKConfig.kits)) { kits = mpInstance._Store.SDKConfig.kits; } else if (!isEmpty(mpInstance._preInit.forwarderConstructors)) { mpInstance._preInit.forwarderConstructors.forEach(function(kitConstructor) { 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_1 in kits) { var kitNameWithConfigSuffix = void 0; if (config.suffix) { kitNameWithConfigSuffix = "".concat(config.name, "-").concat(config.suffix); } if (name_1 === kitNameWithConfigSuffix || name_1 === config.name) { if (config.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || config.isSandbox === mpInstance._Store.SDKConfig.isDevelopmentMode) { newKit = this.returnConfiguredKit(kits[name_1], config); mpInstance._Store.configuredForwarders.push(newKit); break; } } } }; this.processSideloadedKits = function(mpConfig) { try { if (Array.isArray(mpConfig.sideloadedKits)) { var registeredSideloadedKits_1 = { kits: {} }; var unregisteredSideloadedKits = mpConfig.sideloadedKits; unregisteredSideloadedKits.forEach(function(unregisteredKit) { try { unregisteredKit.kitInstance.register(registeredSideloadedKits_1); var kitName = unregisteredKit.kitInstance.name; registeredSideloadedKits_1.kits[kitName].filters = unregisteredKit.filterDictionary; } catch (e) { console.error("Error registering sideloaded kit " + unregisteredKit.kitInstance.name); } }); for (var registeredKitKey in registeredSideloadedKits_1.kits) { var registeredKit = registeredSideloadedKits_1.kits[registeredKitKey]; self.configureSideloadedKit(registeredKit); } if (!isEmpty(registeredSideloadedKits_1.kits)) { var kitKeys = Object.keys(registeredSideloadedKits_1.kits); mpInstance._Store.sideloadedKitsCount = kitKeys.length; } } } catch (e) { mpInstance.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. " + e); } }; this.configureSideloadedKit = function(kitConstructor) { mpInstance._Store.configuredForwarders.push(this.returnConfiguredKit(kitConstructor, kitConstructor.filters)); }; this.returnConfiguredKit = function(forwarder, config) { if (config === void 0) { config = {}; } var newForwarder = new forwarder.constructor(); newForwarder.id = config.moduleId; 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 = function(forwardingStatsData) { return __awaiter(_this, void 0, void 0, function() { var fetchPayload, response, message; var _a2; return __generator(this, function(_b2) { switch (_b2.label) { case 0: fetchPayload = { method: "post", body: JSON.stringify(forwardingStatsData), headers: { Accept: "text/plain;charset=UTF-8", "Content-Type": "text/plain;charset=UTF-8" } }; return [4, this.forwarderStatsUploader.upload(fetchPayload)]; case 1: response = _b2.sent(); if (response.status === 202) { message = "Successfully sent forwarding stats to mParticle Servers"; } else { message = "Issue with forwarding stats to mParticle Servers, received HTTP Code of " + response.statusText; } (_a2 = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _a2 === void 0 ? void 0 : _a2.verbose(message); return [ 2 /*return*/ ]; } }); }); }; } var MessageType = Types.MessageType; var ApplicationTransitionType = Types.ApplicationTransitionType; 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 _a2, _b2, _c; var uploadObject = {}; var eventObject = {}; var optOut = event.messageType === Types.MessageType.OptOut ? !mpInstance._Store.isEnabled : null; 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; 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) { 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 || String(event.messageType), EventCategory: event.eventType, EventAttributes: mpInstance._Helpers.sanitizeAttributes(event.data, event.name), ActiveTimeOnSite: (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.getTimeInForeground(), TotalTimeOnSite: (_c = (_b2 = mpInstance._Store).getTotalTimeOnSite) === null || _c === void 0 ? void 0 : _c.call(_b2), PageUrl: getHref() || null, SourceMessageId: event.sourceMessageId || mpInstance._Helpers.generateUniqueId(), EventDataType: event.messageType, CustomFlags: customFlags, UserAttributeChanges: event.userAttributeChanges, UserIdentityChanges: event.userIdentityChanges }; } if (event.messageType !== Types.MessageType.SessionEnd) { mpInstance._Store.dateLastEventSent = /* @__PURE__ */ 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; } 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; eventObject.EventAttributes = mpInstance._Store.sessionAttributes; mpInstance._Store.currentSessionMPIDs = []; mpInstance._Store.sessionStartDate = null; } uploadObject.Timestamp = mpInstance._Store.dateLastEventSent.getTime(); return 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; dto.attrs = null; } if (event.CustomFlags) { convertCustomFlags(event, dto); } if (event.EventDataType === MessageType.Commerce) { dto.cu = event.CurrencyCode; 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() { window.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(date2) { if (uploadsTable.hasOwnProperty(date2)) { if (uploadsTable[date2].uploading === false) { var xhrCallback = function xhrCallback2() { if (xhr_1.readyState === 4) { if (xhr_1.status === 200 || xhr_1.status === 202) { mpInstance.Logger.verbose("Successfully sent " + xhr_1.statusText + " from server"); delete uploadsTable[date2]; } else if (xhr_1.status.toString()[0] === "4") { if (xhr_1.status !== 429) { delete uploadsTable[date2]; } } else { uploadsTable[date2].uploading = false; } } }; var xhr_1 = mpInstance._Helpers.createXHR(xhrCallback); var forwardingStatsData = uploadsTable[date2].data; uploadsTable[date2].uploading = true; mpInstance._APIClient.sendBatchForwardingStatsToServer(forwardingStatsData, xhr_1); } } })(date); } } } var AudienceManager = ( /** @class */ (function() { function AudienceManager2(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); } AudienceManager2.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(_a2) { switch (_a2.label) { case 0: this.logger.verbose("Fetching user audiences from server"); fetchPayload = { method: "GET", headers: { Accept: "*/*" } }; audienceURLWithMPID = "".concat(this.url, "?mpid=").concat(mpid); _a2.label = 1; case 1: _a2.trys.push([1, 6, , 7]); return [4, this.userAudienceAPI.upload(fetchPayload, audienceURLWithMPID)]; case 2: userAudiencePromise = _a2.sent(); if (!(userAudiencePromise.status >= 200 && userAudiencePromise.status = 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 === null || identityApiData === void 0 ? void 0 : 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 }; } return void 0; } }; 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) { var mpid; var currentUser = mpInstance.Identity.getCurrentUser(); var 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) { var mpid; var currentUser = mpInstance.Identity.getCurrentUser(); var preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Logout); if (currentUser) { mpid = currentUser.getMPID(); } if (preProcessResult.valid) { var evt_1; var 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_1 = mpInstance._ServerModel.createEventObject({ messageType: Types.MessageType.Profile }); evt_1.ProfileMessageType = Types.ProfileMessageType.Logout; if (mpInstance._Store.activeForwarders.length) { mpInstance._Store.activeForwarders.forEach(function(forwarder) { var kit = forwarder; if (kit.logOut) { kit.logOut(evt_1); } }); } } } 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) { var mpid; var currentUser = mpInstance.Identity.getCurrentUser(); var 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) { var mpid; var currentUser = mpInstance.Identity.getCurrentUser(); var preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Modify$1); if (currentUser) { mpid = currentUser.getMPID(); } if (preProcessResult.valid) { var newUserIdentities = (identityApiData === null || identityApiData === void 0 ? void 0 : 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); } } 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); } }, /** * Search the IDSync Workspace endpoint for a known identity. * * POSTs to mParticle's `/v1/search` endpoint and invokes `callback` * with `{ httpCode, body? }`. * * The `workspaceApiKey` is a workspace-specific API key supplied by * the caller (passed in from a kit's settings). It is intentionally * NOT read from the SDK's own workspace token, so that workspace * searches can be authorised independently of the host SDK's * workspace. * * @method search * @param {String} workspaceApiKey Workspace API key (sent as x-mp-key). * @param {Object} knownIdentities A `UserIdentities` map. * @param {Function} callback Invoked with the `IIdentitySearchResult`. */ search: function search(workspaceApiKey, knownIdentities, callback) { executeSearchRequest(mpInstance, workspaceApiKey, knownIdentities, callback); }, /** 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_1 = sourceUser.getFirstSeenTime(); if (!startTime_1) { mpInstance.Identity.getUsers().forEach(function(user) { if (user.getFirstSeenTime() && (!startTime_1 || user.getFirstSeenTime() 0) { dataPoints.forEach(function(point) { return _this.addToMatchLookups(point); }); } } catch (e) { this.mpInstance.Logger.error("There was an issue with the data plan: " + e); } } } KitBlocker2.prototype.addToMatchLookups = function(point) { var _a2, _b2, _c; if (!point.match || !point.validator) { this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(point)); return; } var matchKey = this.generateMatchKey(point.match); var properties = this.getPlannedProperties(point.match.type, point.validator); this.dataPlanMatchLookups[matchKey] = properties; if (((_a2 = point === null || point === void 0 ? void 0 : point.match) === null || _a2 === void 0 ? void 0 : _a2.type) === DataPlanMatchType.ProductImpression || ((_b2 = point === null || point === void 0 ? void 0 : point.match) === null || _b2 === void 0 ? void 0 : _b2.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; } }; KitBlocker2.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; } }; KitBlocker2.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; } }; KitBlocker2.prototype.getPlannedProperties = function(type, validator) { var _a2, _b2, _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 = (_b2 = (_a2 = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a2 === void 0 ? void 0 : _a2.properties) === null || _b2 === void 0 ? void 0 : _b2.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 === void 0) { return true; } else { var properties = {}; for (var _i = 0, _j = Object.keys(customAttributes.properties); _i = 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; Logger2.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; if (message) { Logger2.verbose(message); } if ((_b2 = mpInstance._RoktManager) === null || _b2 === void 0 ? void 0 : _b2.isInitialized) { requestCount = mpInstance._Store.identifyRequestCount; mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd")); } parseIdentityResponse2(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false); return [3, 10]; case 9: err_1 = _f.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 = getErrorMessage(err_1); msg = "Error sending identity request to servers - " + errorMessage; Logger2.error(msg); errorReporter === null || errorReporter === void 0 ? void 0 : errorReporter.report({ message: msg, code: ErrorCodes.IDENTITY_REQUEST, severity: WSDKErrorSeverity.ERROR }); (_d = mpInstance.processQueueOnIdentityFailure) === null || _d === void 0 ? void 0 : _d.call(mpInstance); invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage); return [3, 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 }; }; } var facebookClickIdProcessor = function facebookClickIdProcessor2(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; if (domainParts.length >= 3) { subdomainIndex = 2; } var _timestamp = timestamp || Date.now(); return "fb.".concat(subdomainIndex, ".").concat(_timestamp, ".").concat(clickId); }; 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 IntegrationCapture2(captureMode) { this.initialTimestamp = Date.now(); this.captureMode = captureMode; this.filteredPartnerIdentityMappings = this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES); this.filteredCustomFlagMappings = this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS); this.filteredIntegrationAttributeMappings = this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES); } IntegrationCapture2.prototype.capture = function() { var queryParams = this.captureQueryParams() || {}; var cookies = this.captureCookies() || {}; var localStorage2 = this.captureLocalStorage() || {}; if (queryParams["fbclid"] && cookies["_fbc"]) { delete cookies["_fbc"]; } var hasQueryParamId = queryParams["rtid"] || queryParams["rclid"]; var hasLocalStorageId = localStorage2["RoktTransactionId"]; var hasCookieId = cookies["RoktTransactionId"]; if (hasQueryParamId) { if (hasLocalStorageId) { delete localStorage2["RoktTransactionId"]; } if (hasCookieId) { delete cookies["RoktTransactionId"]; } } else if (hasLocalStorageId && hasCookieId) { delete cookies["RoktTransactionId"]; } this.clickIds = __assign(__assign(__assign(__assign({}, this.clickIds), queryParams), localStorage2), cookies); }; IntegrationCapture2.prototype.captureCookies = function() { var integrationKeys = this.getAllowedKeysForMode(); var cookies = getCookies(integrationKeys); return this.applyProcessors(cookies, getHref(), this.initialTimestamp); }; IntegrationCapture2.prototype.captureQueryParams = function() { var queryParams = this.getQueryParams(); return this.applyProcessors(queryParams, getHref(), this.initialTimestamp); }; IntegrationCapture2.prototype.captureLocalStorage = function() { var integrationKeys = this.getAllowedKeysForMode(); var localStorageItems = {}; for (var _i = 0, integrationKeys_1 = integrationKeys; _i = 400 || httpCode