@mparticle/web-sdk
Version:
mParticle core SDK for web applications
1,270 lines (1,246 loc) • 516 kB
JavaScript
var mParticle = (function () {
// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html
var Base64$1 = {
_keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
// Input must be a string
encode: function encode(input) {
try {
if (window.btoa && window.atob) {
return window.btoa(unescape(encodeURIComponent(input)));
}
} catch (e) {
console.error('Error encoding cookie values into Base64:' + e);
}
return this._encode(input);
},
_encode: function _encode(input) {
var output = '';
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = UTF8.encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = (chr1 & 3) << 4 | chr2 >> 4;
enc3 = (chr2 & 15) << 2 | chr3 >> 6;
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + Base64$1._keyStr.charAt(enc1) + Base64$1._keyStr.charAt(enc2) + Base64$1._keyStr.charAt(enc3) + Base64$1._keyStr.charAt(enc4);
}
return output;
},
decode: function decode(input) {
try {
if (window.btoa && window.atob) {
return decodeURIComponent(escape(window.atob(input)));
}
} catch (e) {
//log(e);
}
return Base64$1._decode(input);
},
_decode: function _decode(input) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
while (i < input.length) {
enc1 = Base64$1._keyStr.indexOf(input.charAt(i++));
enc2 = Base64$1._keyStr.indexOf(input.charAt(i++));
enc3 = Base64$1._keyStr.indexOf(input.charAt(i++));
enc4 = Base64$1._keyStr.indexOf(input.charAt(i++));
chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 !== 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output = output + String.fromCharCode(chr3);
}
}
output = UTF8.decode(output);
return output;
}
};
var UTF8 = {
encode: function encode(s) {
var utftext = '';
for (var n = 0; n < s.length; n++) {
var c = s.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
utftext += String.fromCharCode(c >> 6 | 192);
utftext += String.fromCharCode(c & 63 | 128);
} else {
utftext += String.fromCharCode(c >> 12 | 224);
utftext += String.fromCharCode(c >> 6 & 63 | 128);
utftext += String.fromCharCode(c & 63 | 128);
}
}
return utftext;
},
decode: function decode(utftext) {
var s = '';
var i = 0;
var c = 0,
c1 = 0,
c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
s += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
c1 = utftext.charCodeAt(i + 1);
s += String.fromCharCode((c & 31) << 6 | c1 & 63);
i += 2;
} else {
c1 = utftext.charCodeAt(i + 1);
c2 = utftext.charCodeAt(i + 2);
s += String.fromCharCode((c & 15) << 12 | (c1 & 63) << 6 | c2 & 63);
i += 3;
}
}
return s;
}
};
var Polyfill = {
// forEach polyfill
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
forEach: function forEach(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
},
// map polyfill
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
map: function map(callback, thisArg) {
var T, A, k;
if (this === null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
A = new Array(len);
k = 0;
while (k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
A[k] = mappedValue;
}
k++;
}
return A;
},
// filter polyfill
// Prodcution steps of ECMA-262, Edition 5
// Reference: http://es5.github.io/#x15.4.4.20
filter: function filter(fun /*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
},
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isArray: function isArray(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
},
Base64: Base64$1
};
var version = "2.40.0";
var Constants = {
sdkVersion: version,
sdkVendor: 'mparticle',
platform: 'web',
Messages: {
DeprecationMessages: {
MethodIsDeprecatedPostfix: 'is a deprecated method and will be removed in future releases',
AlternativeMethodPrefix: 'Please use the alternate method:'
},
ErrorMessages: {
NoToken: 'A token must be specified.',
EventNameInvalidType: 'Event name must be a valid string value.',
EventDataInvalidType: 'Event data must be a valid object hash.',
LoggingDisabled: 'Event logging is currently disabled.',
CookieParseError: 'Could not parse cookie',
EventEmpty: 'Event object is null or undefined, cancelling send',
APIRequestEmpty: 'APIRequest is null or undefined, cancelling send',
NoEventType: 'Event type must be specified.',
TransactionIdRequired: 'Transaction ID is required',
TransactionRequired: 'A transaction attributes object is required',
PromotionIdRequired: 'Promotion ID is required',
BadAttribute: 'Attribute value cannot be object or array',
BadKey: 'Key value cannot be object or array',
BadLogPurchase: 'Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions',
AudienceAPINotEnabled: 'Your workspace is not enabled to retrieve user audiences.'
},
InformationMessages: {
CookieSearch: 'Searching for cookie',
CookieFound: 'Cookie found, parsing values',
CookieNotFound: 'Cookies not found',
CookieSet: 'Setting cookie',
CookieSync: 'Performing cookie sync',
SendBegin: 'Starting to send event',
SendIdentityBegin: 'Starting to send event to identity server',
SendWindowsPhone: 'Sending event to Windows Phone container',
SendIOS: 'Calling iOS path: ',
SendAndroid: 'Calling Android JS interface method: ',
SendHttp: 'Sending event to mParticle HTTP service',
SendAliasHttp: 'Sending alias request to mParticle HTTP service',
SendIdentityHttp: 'Sending event to mParticle HTTP service',
StartingNewSession: 'Starting new Session',
StartingLogEvent: 'Starting to log event',
StartingLogOptOut: 'Starting to log user opt in/out',
StartingEndSession: 'Starting to end session',
StartingInitialization: 'Starting to initialize',
StartingLogCommerceEvent: 'Starting to log commerce event',
StartingAliasRequest: 'Starting to Alias MPIDs',
LoadingConfig: 'Loading configuration options',
AbandonLogEvent: 'Cannot log event, logging disabled or developer token not set',
AbandonAliasUsers: 'Cannot Alias Users, logging disabled or developer token not set',
AbandonStartSession: 'Cannot start session, logging disabled or developer token not set',
AbandonEndSession: 'Cannot end session, logging disabled or developer token not set',
NoSessionToEnd: 'Cannot end session, no active session found'
},
ValidationMessages: {
ModifyIdentityRequestUserIdentitiesPresent: 'identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again',
IdentityRequesetInvalidKey: 'There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.',
OnUserAliasType: 'The onUserAlias value must be a function.',
UserIdentities: 'The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.',
UserIdentitiesInvalidKey: 'There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.',
UserIdentitiesInvalidValues: 'All user identity values must be strings or null. Request not sent to server. Please fix and try again.',
AliasMissingMpid: 'Alias Request must contain both a destinationMpid and a sourceMpid',
AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique",
AliasMissingTime: 'Alias Request must have both a startTime and an endTime',
AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime"
}
},
NativeSdkPaths: {
LogEvent: 'logEvent',
SetUserTag: 'setUserTag',
RemoveUserTag: 'removeUserTag',
SetUserAttribute: 'setUserAttribute',
RemoveUserAttribute: 'removeUserAttribute',
SetSessionAttribute: 'setSessionAttribute',
AddToCart: 'addToCart',
RemoveFromCart: 'removeFromCart',
ClearCart: 'clearCart',
LogOut: 'logOut',
SetUserAttributeList: 'setUserAttributeList',
RemoveAllUserAttributes: 'removeAllUserAttributes',
GetUserAttributesLists: 'getUserAttributesLists',
GetAllUserAttributes: 'getAllUserAttributes',
Identify: 'identify',
Logout: 'logout',
Login: 'login',
Modify: 'modify',
Alias: 'aliasUsers',
Upload: 'upload'
},
StorageNames: {
localStorageName: 'mprtcl-api',
localStorageNameV3: 'mprtcl-v3',
cookieName: 'mprtcl-api',
cookieNameV2: 'mprtcl-v2',
cookieNameV3: 'mprtcl-v3',
localStorageNameV4: 'mprtcl-v4',
localStorageProductsV4: 'mprtcl-prodv4',
cookieNameV4: 'mprtcl-v4',
currentStorageName: 'mprtcl-v4',
currentStorageProductsName: 'mprtcl-prodv4'
},
DefaultConfig: {
cookieDomain: null,
cookieExpiration: 365,
logLevel: null,
timeout: 300,
sessionTimeout: 30,
maxProducts: 20,
forwarderStatsTimeout: 5000,
integrationDelayTimeout: 5000,
maxCookieSize: 3000,
aliasMaxWindow: 90,
uploadInterval: 0 // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
},
DefaultBaseUrls: {
v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/',
v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/',
v3SecureServiceUrl: 'jssdks.mparticle.com/v3/JS/',
configUrl: 'jssdkcdns.mparticle.com/JS/v2/',
identityUrl: 'identity.mparticle.com/v1/',
aliasUrl: 'jssdks.mparticle.com/v1/identity/',
userAudienceUrl: 'nativesdks.mparticle.com/v1/'
},
Base64CookieKeys: {
csm: 1,
sa: 1,
ss: 1,
ua: 1,
ui: 1,
csd: 1,
ia: 1,
con: 1
},
// https://go.mparticle.com/work/SQDSDKS-6039
SDKv2NonMPIDCookieKeys: {
gs: 1,
cu: 1,
l: 1,
globalSettings: 1,
currentUserMPID: 1
},
HTTPCodes: {
noHttpCoverage: -1,
activeIdentityRequest: -2,
activeSession: -3,
validationIssue: -4,
nativeIdentityRequest: -5,
loggingDisabledOrMissingAPIKey: -6,
tooManyRequests: 429
},
FeatureFlags: {
ReportBatching: 'reportBatching',
EventBatchingIntervalMillis: 'eventBatchingIntervalMillis',
OfflineStorage: 'offlineStorage',
DirectUrlRouting: 'directURLRouting',
CacheIdentity: 'cacheIdentity',
AudienceAPI: 'audienceAPI',
CaptureIntegrationSpecificIds: 'captureIntegrationSpecificIds',
AstBackgroundEvents: 'astBackgroundEvents'
},
DefaultInstance: 'default_instance',
CCPAPurpose: 'data_sale_opt_out',
IdentityMethods: {
Modify: 'modify',
Logout: 'logout',
Login: 'login',
Identify: 'identify'
},
Environment: {
Development: 'development',
Production: 'production'
}
};
// https://go.mparticle.com/work/SQDSDKS-6080
var ONE_DAY_IN_SECONDS = 60 * 60 * 24;
var MILLIS_IN_ONE_SEC = 1000;
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
var HTTP_OK = 200;
var HTTP_ACCEPTED = 202;
var HTTP_BAD_REQUEST = 400;
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var Messages$9 = Constants.Messages;
var createCookieString = function createCookieString(value) {
return replaceCommasWithPipes(replaceQuotesWithApostrophes(value));
};
var revertCookieString = function revertCookieString(value) {
return replacePipesWithCommas(replaceApostrophesWithQuotes(value));
};
var inArray = function inArray(items, name) {
if (!items) {
return false;
}
var i = 0;
if (Array.prototype.indexOf) {
return items.indexOf(name, 0) >= 0;
} else {
for (var n = items.length; i < n; i++) {
if (i in items && items[i] === name) {
return true;
}
}
}
return false;
};
var findKeyInObject = function findKeyInObject(obj, key) {
if (key && obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && prop.toLowerCase() === key.toLowerCase()) {
return prop;
}
}
}
return null;
};
var generateDeprecationMessage = function generateDeprecationMessage(methodName, alternateMethod) {
var messageArray = [methodName, Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix];
if (alternateMethod) {
messageArray.push(alternateMethod);
messageArray.push(Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix);
}
return messageArray.join(' ');
};
function generateHash(name) {
var hash = 0;
var character;
if (name === undefined || name === null) {
return 0;
}
name = name.toString().toLowerCase();
if (Array.prototype.reduce) {
return name.split('').reduce(function (a, b) {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}
if (name.length === 0) {
return hash;
}
for (var i = 0; i < name.length; i++) {
character = name.charCodeAt(i);
hash = (hash << 5) - hash + character;
hash = hash & hash;
}
return hash;
}
var generateRandomValue = function generateRandomValue(value) {
var randomValue;
var a;
if (window.crypto && window.crypto.getRandomValues) {
// @ts-ignore
randomValue = window.crypto.getRandomValues(new Uint8Array(1)); // eslint-disable-line no-undef
}
if (randomValue) {
// @ts-ignore
return (a ^ randomValue[0] % 16 >> a / 4).toString(16);
}
return (a ^ Math.random() * 16 >> a / 4).toString(16);
};
var generateUniqueId = function generateUniqueId(a) {
// https://gist.github.com/jed/982883
// Added support for crypto for better random
if (a === void 0) {
a = '';
}
return a // if the placeholder was passed, return
? generateRandomValue() // if the placeholder was passed, return
:
// [1e7] -> // 10000000 +
// -1e3 -> // -1000 +
// -4e3 -> // -4000 +
// -8e3 -> // -80000000 +
// -1e11 -> //-100000000000,
"".concat(1e7, "-").concat(1e3, "-").concat(4e3, "-").concat(8e3, "-").concat(1e11).replace(/[018]/g,
// zeroes, ones, and eights with
generateUniqueId // random hex digits
);
};
/**
* Returns a value between 1-100 inclusive.
*/
var getRampNumber = function getRampNumber(value) {
if (!value) {
return 100;
}
var hash = generateHash(value);
return Math.abs(hash % 100) + 1;
};
var isObject = function isObject(value) {
var objType = Object.prototype.toString.call(value);
return objType === '[object Object]' || objType === '[object Error]';
};
var parseNumber = function parseNumber(value) {
if (isNaN(value) || !isFinite(value)) {
return 0;
}
var floatValue = parseFloat(value);
return isNaN(floatValue) ? 0 : floatValue;
};
var parseSettingsString = function parseSettingsString(settingsString) {
try {
return settingsString ? JSON.parse(settingsString.replace(/"/g, '"')) : [];
} catch (error) {
throw new Error('Settings string contains invalid JSON');
}
};
var parseStringOrNumber = function parseStringOrNumber(value) {
if (isStringOrNumber(value)) {
return value;
} else {
return null;
}
};
var replaceCommasWithPipes = function replaceCommasWithPipes(value) {
return value.replace(/,/g, '|');
};
var replacePipesWithCommas = function replacePipesWithCommas(value) {
return value.replace(/\|/g, ',');
};
var replaceApostrophesWithQuotes = function replaceApostrophesWithQuotes(value) {
return value.replace(/\'/g, '"');
};
var replaceQuotesWithApostrophes = function replaceQuotesWithApostrophes(value) {
return value.replace(/\"/g, "'");
};
var replaceMPID = function replaceMPID(value, mpid) {
return value.replace('%%mpid%%', mpid);
};
var replaceAmpWithAmpersand = function replaceAmpWithAmpersand(value) {
return value.replace(/&/g, '&');
};
var createCookieSyncUrl = function createCookieSyncUrl(mpid, pixelUrl, redirectUrl) {
var modifiedPixelUrl = replaceAmpWithAmpersand(pixelUrl);
var modifiedDirectUrl = redirectUrl ? replaceAmpWithAmpersand(redirectUrl) : null;
var url = replaceMPID(modifiedPixelUrl, mpid);
var redirect = modifiedDirectUrl ? replaceMPID(modifiedDirectUrl, mpid) : '';
return url + encodeURIComponent(redirect);
};
// FIXME: REFACTOR for V3
// only used in store.js to sanitize server-side formatting of
// booleans when checking for `isDevelopmentMode`
// Should be removed in v3
var returnConvertedBoolean = function returnConvertedBoolean(data) {
if (data === 'false' || data === '0') {
return false;
} else {
return Boolean(data);
}
};
var decoded = function decoded(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
};
var converted = function converted(s) {
if (s.indexOf('"') === 0) {
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
return s;
};
var isString = function isString(value) {
return typeof value === 'string';
};
var isNumber = function isNumber(value) {
return typeof value === 'number';
};
var isBoolean = function isBoolean(value) {
return typeof value === 'boolean';
};
var isFunction = function isFunction(fn) {
return typeof fn === 'function';
};
var isValidCustomFlagProperty = function isValidCustomFlagProperty(value) {
return isNumber(value) || isString(value) || isBoolean(value);
};
var toDataPlanSlug = function toDataPlanSlug(value) {
// Make sure we are only acting on strings or numbers
return isStringOrNumber(value) ? value.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g, '_') : '';
};
var isDataPlanSlug = function isDataPlanSlug(str) {
return str === toDataPlanSlug(str);
};
var isStringOrNumber = function isStringOrNumber(value) {
return isString(value) || isNumber(value);
};
var isEmpty = function isEmpty(value) {
return value == null || !(Object.keys(value) || value).length;
};
var moveElementToEnd = function moveElementToEnd(array, index) {
return array.slice(0, index).concat(array.slice(index + 1), array[index]);
};
var queryStringParser = function queryStringParser(url, keys) {
if (keys === void 0) {
keys = [];
}
var urlParams;
var results = {};
var lowerCaseUrlParams = {};
if (!url) return results;
if (typeof URL !== 'undefined' && typeof URLSearchParams !== 'undefined') {
var urlObject = new URL(url);
urlParams = new URLSearchParams(urlObject.search);
} else {
urlParams = queryStringParserFallback(url);
}
urlParams.forEach(function (value, key) {
lowerCaseUrlParams[key.toLowerCase()] = value;
});
if (isEmpty(keys)) {
return lowerCaseUrlParams;
} else {
keys.forEach(function (key) {
var value = lowerCaseUrlParams[key.toLowerCase()];
if (value) {
results[key] = value;
}
});
}
return results;
};
var queryStringParserFallback = function queryStringParserFallback(url) {
var params = {};
var queryString = url.split('?')[1] || '';
var pairs = queryString.split('&');
pairs.forEach(function (pair) {
var _a = pair.split('='),
key = _a[0],
valueParts = _a.slice(1);
var value = valueParts.join('=');
if (key && value !== undefined) {
try {
params[key] = decodeURIComponent(value || '');
} catch (e) {
console.error("Failed to decode value for key ".concat(key, ": ").concat(e));
}
}
});
return {
get: function get(key) {
return params[key];
},
forEach: function forEach(callback) {
for (var key in params) {
if (params.hasOwnProperty(key)) {
callback(params[key], key);
}
}
}
};
};
// Get cookies as a dictionary
var getCookies = function getCookies(keys) {
// Helper function to parse cookies from document.cookie
var parseCookies = function parseCookies() {
try {
if (typeof window === 'undefined') {
return [];
}
return window.document.cookie.split(';').map(function (cookie) {
return cookie.trim();
});
} catch (e) {
console.error('Unable to parse cookies', e);
return [];
}
};
// Helper function to filter cookies by keys
var filterCookies = function filterCookies(cookies, keys) {
var results = {};
for (var _i = 0, cookies_1 = cookies; _i < cookies_1.length; _i++) {
var cookie = cookies_1[_i];
var _a = cookie.split('='),
key = _a[0],
value = _a[1];
if (!keys || keys.includes(key)) {
results[key] = value;
}
}
return results;
};
// Parse cookies from document.cookie
var parsedCookies = parseCookies();
// Filter cookies by keys if provided
return filterCookies(parsedCookies, keys);
};
var getHref = function getHref() {
return typeof window !== 'undefined' && window.location ? window.location.href : '';
};
var filterDictionaryWithHash = function filterDictionaryWithHash(dictionary, filterList, hashFn) {
var filtered = {};
if (!isEmpty(dictionary)) {
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
var hashedKey = hashFn(key);
if (!inArray(filterList, hashedKey)) {
filtered[key] = dictionary[key];
}
}
}
}
return filtered;
};
var parseConfig = function parseConfig(config, moduleName, moduleId) {
var _a;
return ((_a = config.kitConfigs) === null || _a === void 0 ? void 0 : _a.find(function (kitConfig) {
return kitConfig.name === moduleName && kitConfig.moduleId === moduleId;
})) || null;
};
var MessageType$1 = {
SessionStart: 1,
SessionEnd: 2,
PageView: 3,
PageEvent: 4,
CrashReport: 5,
OptOut: 6,
AppStateTransition: 10,
Profile: 14,
Commerce: 16,
Media: 20,
UserAttributeChange: 17,
UserIdentityChange: 18
};
var EventType = {
Unknown: 0,
Navigation: 1,
Location: 2,
Search: 3,
Transaction: 4,
UserContent: 5,
UserPreference: 6,
Social: 7,
Other: 8,
Media: 9,
getName: function getName(id) {
switch (id) {
case EventType.Unknown:
return 'Unknown';
case EventType.Navigation:
return 'Navigation';
case EventType.Location:
return 'Location';
case EventType.Search:
return 'Search';
case EventType.Transaction:
return 'Transaction';
case EventType.UserContent:
return 'User Content';
case EventType.UserPreference:
return 'User Preference';
case EventType.Social:
return 'Social';
case CommerceEventType.ProductAddToCart:
return 'Product Added to Cart';
case CommerceEventType.ProductAddToWishlist:
return 'Product Added to Wishlist';
case CommerceEventType.ProductCheckout:
return 'Product Checkout';
case CommerceEventType.ProductCheckoutOption:
return 'Product Checkout Options';
case CommerceEventType.ProductClick:
return 'Product Click';
case CommerceEventType.ProductImpression:
return 'Product Impression';
case CommerceEventType.ProductPurchase:
return 'Product Purchased';
case CommerceEventType.ProductRefund:
return 'Product Refunded';
case CommerceEventType.ProductRemoveFromCart:
return 'Product Removed From Cart';
case CommerceEventType.ProductRemoveFromWishlist:
return 'Product Removed from Wishlist';
case CommerceEventType.ProductViewDetail:
return 'Product View Details';
case CommerceEventType.PromotionClick:
return 'Promotion Click';
case CommerceEventType.PromotionView:
return 'Promotion View';
default:
return 'Other';
}
}
};
// Continuation of EventType enum above, but in seperate object since we don't expose these to end user
var CommerceEventType = {
ProductAddToCart: 10,
ProductRemoveFromCart: 11,
ProductCheckout: 12,
ProductCheckoutOption: 13,
ProductClick: 14,
ProductViewDetail: 15,
ProductPurchase: 16,
ProductRefund: 17,
PromotionView: 18,
PromotionClick: 19,
ProductAddToWishlist: 20,
ProductRemoveFromWishlist: 21,
ProductImpression: 22
};
var IdentityType = {
Other: 0,
CustomerId: 1,
Facebook: 2,
Twitter: 3,
Google: 4,
Microsoft: 5,
Yahoo: 6,
Email: 7,
FacebookCustomAudienceId: 9,
Other2: 10,
Other3: 11,
Other4: 12,
Other5: 13,
Other6: 14,
Other7: 15,
Other8: 16,
Other9: 17,
Other10: 18,
MobileNumber: 19,
PhoneNumber2: 20,
PhoneNumber3: 21,
isValid: function isValid(identityType) {
if (typeof identityType === 'number') {
for (var prop in IdentityType) {
if (IdentityType.hasOwnProperty(prop)) {
if (IdentityType[prop] === identityType) {
return true;
}
}
}
}
return false;
},
getName: function getName(identityType) {
switch (identityType) {
case window.mParticle.IdentityType.CustomerId:
return 'Customer ID';
case window.mParticle.IdentityType.Facebook:
return 'Facebook ID';
case window.mParticle.IdentityType.Twitter:
return 'Twitter ID';
case window.mParticle.IdentityType.Google:
return 'Google ID';
case window.mParticle.IdentityType.Microsoft:
return 'Microsoft ID';
case window.mParticle.IdentityType.Yahoo:
return 'Yahoo ID';
case window.mParticle.IdentityType.Email:
return 'Email';
case window.mParticle.IdentityType.FacebookCustomAudienceId:
return 'Facebook App User ID';
default:
return 'Other ID';
}
},
getIdentityType: function getIdentityType(identityName) {
switch (identityName) {
case 'other':
return IdentityType.Other;
case 'customerid':
return IdentityType.CustomerId;
case 'facebook':
return IdentityType.Facebook;
case 'twitter':
return IdentityType.Twitter;
case 'google':
return IdentityType.Google;
case 'microsoft':
return IdentityType.Microsoft;
case 'yahoo':
return IdentityType.Yahoo;
case 'email':
return IdentityType.Email;
case 'facebookcustomaudienceid':
return IdentityType.FacebookCustomAudienceId;
case 'other2':
return IdentityType.Other2;
case 'other3':
return IdentityType.Other3;
case 'other4':
return IdentityType.Other4;
case 'other5':
return IdentityType.Other5;
case 'other6':
return IdentityType.Other6;
case 'other7':
return IdentityType.Other7;
case 'other8':
return IdentityType.Other8;
case 'other9':
return IdentityType.Other9;
case 'other10':
return IdentityType.Other10;
case 'mobile_number':
return IdentityType.MobileNumber;
case 'phone_number_2':
return IdentityType.PhoneNumber2;
case 'phone_number_3':
return IdentityType.PhoneNumber3;
default:
return false;
}
},
getIdentityName: function getIdentityName(identityType) {
switch (identityType) {
case IdentityType.Other:
return 'other';
case IdentityType.CustomerId:
return 'customerid';
case IdentityType.Facebook:
return 'facebook';
case IdentityType.Twitter:
return 'twitter';
case IdentityType.Google:
return 'google';
case IdentityType.Microsoft:
return 'microsoft';
case IdentityType.Yahoo:
return 'yahoo';
case IdentityType.Email:
return 'email';
case IdentityType.FacebookCustomAudienceId:
return 'facebookcustomaudienceid';
case IdentityType.Other2:
return 'other2';
case IdentityType.Other3:
return 'other3';
case IdentityType.Other4:
return 'other4';
case IdentityType.Other5:
return 'other5';
case IdentityType.Other6:
return 'other6';
case IdentityType.Other7:
return 'other7';
case IdentityType.Other8:
return 'other8';
case IdentityType.Other9:
return 'other9';
case IdentityType.Other10:
return 'other10';
case IdentityType.MobileNumber:
return 'mobile_number';
case IdentityType.PhoneNumber2:
return 'phone_number_2';
case IdentityType.PhoneNumber3:
return 'phone_number_3';
default:
return null;
}
},
// Strips out functions from Identity Types for easier lookups
getValuesAsStrings: function getValuesAsStrings() {
return Object.values(IdentityType).map(function (value) {
return isNumber(value) ? value.toString() : undefined;
}).filter(function (value) {
return value !== undefined;
});
},
getNewIdentitiesByName: function getNewIdentitiesByName(newIdentitiesByType) {
var newIdentitiesByName = {};
var identityTypeValuesAsStrings = IdentityType.getValuesAsStrings();
for (var key in newIdentitiesByType) {
// IdentityTypes are stored as numbers but are passed in as strings
if (identityTypeValuesAsStrings.includes(key)) {
var identityNameKey = IdentityType.getIdentityName(parseNumber(key));
newIdentitiesByName[identityNameKey] = newIdentitiesByType[key];
}
}
return newIdentitiesByName;
}
};
var ProductActionType = {
Unknown: 0,
AddToCart: 1,
RemoveFromCart: 2,
Checkout: 3,
CheckoutOption: 4,
Click: 5,
ViewDetail: 6,
Purchase: 7,
Refund: 8,
AddToWishlist: 9,
RemoveFromWishlist: 10,
getName: function getName(id) {
switch (id) {
case ProductActionType.AddToCart:
return 'Add to Cart';
case ProductActionType.RemoveFromCart:
return 'Remove from Cart';
case ProductActionType.Checkout:
return 'Checkout';
case ProductActionType.CheckoutOption:
return 'Checkout Option';
case ProductActionType.Click:
return 'Click';
case ProductActionType.ViewDetail:
return 'View Detail';
case ProductActionType.Purchase:
return 'Purchase';
case ProductActionType.Refund:
return 'Refund';
case ProductActionType.AddToWishlist:
return 'Add to Wishlist';
case ProductActionType.RemoveFromWishlist:
return 'Remove from Wishlist';
default:
return 'Unknown';
}
},
// these are the action names used by server and mobile SDKs when expanding a CommerceEvent
getExpansionName: function getExpansionName(id) {
switch (id) {
case ProductActionType.AddToCart:
return 'add_to_cart';
case ProductActionType.RemoveFromCart:
return 'remove_from_cart';
case ProductActionType.Checkout:
return 'checkout';
case ProductActionType.CheckoutOption:
return 'checkout_option';
case ProductActionType.Click:
return 'click';
case ProductActionType.ViewDetail:
return 'view_detail';
case ProductActionType.Purchase:
return 'purchase';
case ProductActionType.Refund:
return 'refund';
case ProductActionType.AddToWishlist:
return 'add_to_wishlist';
case ProductActionType.RemoveFromWishlist:
return 'remove_from_wishlist';
default:
return 'unknown';
}
}
};
var PromotionActionType = {
Unknown: 0,
PromotionView: 1,
PromotionClick: 2,
getName: function getName(id) {
switch (id) {
case PromotionActionType.PromotionView:
return 'view';
case PromotionActionType.PromotionClick:
return 'click';
default:
return 'unknown';
}
},
// these are the names that the server and mobile SDKs use while expanding CommerceEvent
getExpansionName: function getExpansionName(id) {
switch (id) {
case PromotionActionType.PromotionView:
return 'view';
case PromotionActionType.PromotionClick:
return 'click';
default:
return 'unknown';
}
}
};
var ProfileMessageType = {
Logout: 3
};
var ApplicationTransitionType$1 = {
AppInit: 1
};
var Types = {
MessageType: MessageType$1,
EventType: EventType,
CommerceEventType: CommerceEventType,
IdentityType: IdentityType,
ProfileMessageType: ProfileMessageType,
ApplicationTransitionType: ApplicationTransitionType$1,
ProductActionType: ProductActionType,
PromotionActionType: PromotionActionType,
Environment: Constants.Environment
};
function _typeof$1(o) {
"@babel/helpers - typeof";
return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof$1(o);
}
var SDKProductActionType;
(function (SDKProductActionType) {
SDKProductActionType[SDKProductActionType["Unknown"] = 0] = "Unknown";
SDKProductActionType[SDKProductActionType["AddToCart"] = 1] = "AddToCart";
SDKProductActionType[SDKProductActionType["RemoveFromCart"] = 2] = "RemoveFromCart";
SDKProductActionType[SDKProductActionType["Checkout"] = 3] = "Checkout";
SDKProductActionType[SDKProductActionType["CheckoutOption"] = 4] = "CheckoutOption";
SDKProductActionType[SDKProductActionType["Click"] = 5] = "Click";
SDKProductActionType[SDKProductActionType["ViewDetail"] = 6] = "ViewDetail";
SDKProductActionType[SDKProductActionType["Purchase"] = 7] = "Purchase";
SDKProductActionType[SDKProductActionType["Refund"] = 8] = "Refund";
SDKProductActionType[SDKProductActionType["AddToWishlist"] = 9] = "AddToWishlist";
SDKProductActionType[SDKProductActionType["RemoveFromWishlist"] = 10] = "RemoveFromWishlist";
})(SDKProductActionType || (SDKProductActionType = {}));
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var dist = {};
(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
(function (ApplicationInformationOsEnum) {
ApplicationInformationOsEnum["unknown"] = "Unknown";
ApplicationInformationOsEnum["iOS"] = "IOS";
ApplicationInformationOsEnum["android"] = "Android";
ApplicationInformationOsEnum["windowsPhone"] = "WindowsPhone";
ApplicationInformationOsEnum["mobileWeb"] = "MobileWeb";
ApplicationInformationOsEnum["unityIOS"] = "UnityIOS";
ApplicationInformationOsEnum["unityAndroid"] = "UnityAndroid";
ApplicationInformationOsEnum["desktop"] = "Desktop";
ApplicationInformationOsEnum["tvOS"] = "TVOS";
ApplicationInformationOsEnum["roku"] = "Roku";
ApplicationInformationOsEnum["outOfBand"] = "OutOfBand";
ApplicationInformationOsEnum["alexa"] = "Alexa";
ApplicationInformationOsEnum["smartTV"] = "SmartTV";
ApplicationInformationOsEnum["fireTV"] = "FireTV";
ApplicationInformationOsEnum["xbox"] = "Xbox";
})(exports.ApplicationInformationOsEnum || (exports.ApplicationInformationOsEnum = {}));
(function (ApplicationStateTransitionEventEventTypeEnum) {
ApplicationStateTransitionEventEventTypeEnum["applicationStateTransition"] = "application_state_transition";
})(exports.ApplicationStateTransitionEventEventTypeEnum || (exports.ApplicationStateTransitionEventEventTypeEnum = {}));
(function (ApplicationStateTransitionEventDataApplicationTransitionTypeEnum) {
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationInitialized"] = "application_initialized";
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationExit"] = "application_exit";
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationBackground"] = "application_background";
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationForeground"] = "application_foreground";
})(exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum || (exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum = {}));
(function (BatchEnvironmentEnum) {
BatchEnvironmentEnum["unknown"] = "unknown";
BatchEnvironmentEnum["development"] = "development";
BatchEnvironmentEnum["production"] = "production";
})(exports.BatchEnvironmentEnum || (exports.BatchEnvironmentEnum = {}));
(function (BreadcrumbEventEventTypeEnum) {
BreadcrumbEventEventTypeEnum["breadcrumb"] = "breadcrumb";
})(exports.BreadcrumbEventEventTypeEnum || (exports.BreadcrumbEventEventTypeEnum = {}));
(function (CommerceEventEventTypeEnum) {
CommerceEventEventTypeEnum["commerceEvent"] = "commerce_event";
})(exports.CommerceEventEventTypeEnum || (exports.CommerceEventEventTypeEnum = {}));
(function (CommerceEventDataCustomEventTypeEnum) {
CommerceEventDataCustomEventTypeEnum["addToCart"] = "add_to_cart";
CommerceEventDataCustomEventTypeEnum["removeFromCart"] = "remove_from_cart";
CommerceEventDataCustomEventTypeEnum["checkout"] = "checkout";
CommerceEventDataCustomEventTypeEnum["checkoutOption"] = "checkout_option";
CommerceEventDataCustomEventTypeEnum["click"] = "click";
CommerceEventDataCustomEventTypeEnum["viewDetail"] = "view_detail";
CommerceEventDataCustomEventTypeEnum["purchase"] = "purchase";
CommerceEventDataCustomEventTypeEnum["refund"] = "refund";
CommerceEventDataCustomEventTypeEnum["promotionView"] = "promotion_view";
CommerceEventDataCustomEventTypeEnum["promotionClick"] = "promotion_click";
CommerceEventDataCustomEventTypeEnum["addToWishlist"] = "add_to_wishlist";
CommerceEventDataCustomEventTypeEnum["removeFromWishlist"] = "remove_from_wishlist";
CommerceEventDataCustomEventTypeEnum["impression"] = "impression";
})(exports.CommerceEventDataCustomEventTypeEnum || (exports.CommerceEventDataCustomEventTypeEnum = {}));
(function (CrashReportEventEventTypeEnum) {
CrashReportEventEventTypeEnum["crashReport"] = "cras