@mparticle/web-sdk 3.23.0 → 3.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mparticle.common.js +1 -1688
- package/dist/mparticle.esm.js +1 -1688
- package/dist/mparticle.js +706 -197
- package/dist/types/src/buttonTracking/buttonClickEvent.d.ts +4 -0
- package/dist/types/src/buttonTracking/buttonDescription.d.ts +2 -2
- package/dist/types/src/buttonTracking/buttonTracker.d.ts +2 -0
- package/dist/types/src/buttonTracking/checkoutIntent.d.ts +2 -2
- package/dist/types/src/buttonTracking/controls.d.ts +6 -3
- package/dist/types/src/buttonTracking/labelMasking.d.ts +1 -0
- package/dist/types/src/configAPIClient.d.ts +1 -0
- package/dist/types/src/forwarder-utils.d.ts +3 -0
- package/dist/types/src/pageViewTracker.d.ts +19 -3
- package/dist/types/src/roktManager.d.ts +3 -1
- package/dist/types/src/sdkRuntimeModels.d.ts +1 -0
- package/dist/types/src/store.d.ts +2 -0
- package/package.json +21 -14
- package/src/buttonTracking/buttonClickEvent.ts +76 -1
- package/src/buttonTracking/buttonDescription.ts +236 -46
- package/src/buttonTracking/buttonTracker.ts +122 -7
- package/src/buttonTracking/checkoutIntent.ts +51 -9
- package/src/buttonTracking/controls.ts +160 -50
- package/src/buttonTracking/labelMasking.ts +4 -1
- package/src/configAPIClient.ts +1 -0
- package/src/events.ts +9 -3
- package/src/forwarder-utils.ts +38 -0
- package/src/forwarders.ts +2 -28
- package/src/mp-instance.ts +18 -2
- package/src/pageUrl.ts +43 -2
- package/src/pageViewTracker.ts +193 -111
- package/src/roktManager.ts +19 -4
- package/src/sdkRuntimeModels.ts +1 -0
- package/src/store.ts +14 -0
package/dist/mparticle.esm.js
CHANGED
|
@@ -1,1688 +1 @@
|
|
|
1
|
-
if (typeof globalThis !== 'undefined') {globalThis.regeneratorRuntime = undefined}
|
|
2
|
-
|
|
3
|
-
// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html
|
|
4
|
-
var Base64$1={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",// Input must be a string
|
|
5
|
-
encode:function(a){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(a)))}catch(a){console.error("Error encoding cookie values into Base64:"+a);}return this._encode(a)},_encode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=UTF8.encode(a);k<a.length;)b=a.charCodeAt(k++),c=a.charCodeAt(k++),d=a.charCodeAt(k++),e=b>>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),j=j+Base64$1._keyStr.charAt(e)+Base64$1._keyStr.charAt(f)+Base64$1._keyStr.charAt(g)+Base64$1._keyStr.charAt(h);return j},decode:function(a){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(a)))}catch(a){//log(e);
|
|
6
|
-
}return Base64$1._decode(a)},_decode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k<a.length;)e=Base64$1._keyStr.indexOf(a.charAt(k++)),f=Base64$1._keyStr.indexOf(a.charAt(k++)),g=Base64$1._keyStr.indexOf(a.charAt(k++)),h=Base64$1._keyStr.indexOf(a.charAt(k++)),b=e<<2|f>>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j+=String.fromCharCode(b),64!==g&&(j+=String.fromCharCode(c)),64!==h&&(j+=String.fromCharCode(d));return j=UTF8.decode(j),j}},UTF8={encode:function(a){for(var b,d="",e=0;e<a.length;e++)b=a.charCodeAt(e),128>b?d+=String.fromCharCode(b):127<b&&2048>b?(d+=String.fromCharCode(192|b>>6),d+=String.fromCharCode(128|63&b)):(d+=String.fromCharCode(224|b>>12),d+=String.fromCharCode(128|63&b>>6),d+=String.fromCharCode(128|63&b));return d},decode:function(a){for(var b="",d=0,e=0,f=0,g=0;d<a.length;)e=a.charCodeAt(d),128>e?(b+=String.fromCharCode(e),d++):191<e&&224>e?(f=a.charCodeAt(d+1),b+=String.fromCharCode((31&e)<<6|63&f),d+=2):(f=a.charCodeAt(d+1),g=a.charCodeAt(d+2),b+=String.fromCharCode((15&e)<<12|(63&f)<<6|63&g),d+=3);return b}};var Polyfill = {// forEach polyfill
|
|
7
|
-
// Production steps of ECMA-262, Edition 5, 15.4.4.18
|
|
8
|
-
// Reference: http://es5.github.io/#x15.4.4.18
|
|
9
|
-
forEach:function forEach(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1<arguments.length&&(c=b),d=0;d<f;){var g=void 0;d in e&&(g=e[d],a.call(c,g,d,e)),d++;}},// map polyfill
|
|
10
|
-
// Production steps of ECMA-262, Edition 5, 15.4.4.19
|
|
11
|
-
// Reference: http://es5.github.io/#x15.4.4.19
|
|
12
|
-
map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is null or not defined");var f=Object(this),g=f.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1<arguments.length&&(c=b),d=Array(g),e=0;e<g;){var h=void 0,i=void 0;e in f&&(h=f[e],i=a.call(c,h,e,f),d[e]=i),e++;}return d},// filter polyfill
|
|
13
|
-
// Prodcution steps of ECMA-262, Edition 5
|
|
14
|
-
// Reference: http://es5.github.io/#x15.4.4.20
|
|
15
|
-
filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
|
|
16
|
-
isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
|
|
17
|
-
|
|
18
|
-
var version = "3.23.0";
|
|
19
|
-
|
|
20
|
-
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",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",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
|
|
21
|
-
},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls
|
|
22
|
-
CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
|
|
23
|
-
SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI",// CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI
|
|
24
|
-
// - 'True' \u2192 capture all integration-specific IDs
|
|
25
|
-
// - 'False' \u2192 capture none
|
|
26
|
-
CaptureIntegrationSpecificIds:"captureIntegrationSpecificIds",// CaptureIntegrationSpecificIdsV2 (new): string mode from server
|
|
27
|
-
// - 'all' \u2192 capture all IDs
|
|
28
|
-
// - 'none' \u2192 capture none
|
|
29
|
-
// - 'roktonly' \u2192 capture only Rokt-related IDs
|
|
30
|
-
CaptureIntegrationSpecificIdsV2:"captureIntegrationSpecificIds.V2",AstBackgroundEvents:"astBackgroundEvents",AutoLogPageView:"autoLogPageView",AutoButtonTracking:"autoButtonTracking"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"},Environment:{Development:"development",Production:"production"},CaptureIntegrationSpecificIdsV2Modes:{All:"all",None:"none",RoktOnly:"roktonly"},Rokt:{LauncherInstanceGuidKey:"__rokt_li_guid__"}};var ONE_DAY_IN_SECONDS=86400;var MILLIS_IN_ONE_SEC=1e3;// User attribute set when the end user opts out of ad targeting via
|
|
31
|
-
// launcherOptions.noTargeting. Server-side systems use this attribute
|
|
32
|
-
// to exclude the user from retargeting audiences.
|
|
33
|
-
var NO_TARGETING_ATTRIBUTE="$NoTargeting";// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
|
|
34
|
-
var HTTP_OK=200;var HTTP_ACCEPTED=202;var HTTP_BAD_REQUEST=400;var HTTP_NOT_FOUND=404;var HTTP_SERVER_ERROR=500;
|
|
35
|
-
|
|
36
|
-
function _typeof(o) {
|
|
37
|
-
"@babel/helpers - typeof";
|
|
38
|
-
|
|
39
|
-
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
|
40
|
-
return typeof o;
|
|
41
|
-
} : function (o) {
|
|
42
|
-
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
43
|
-
}, _typeof(o);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/******************************************************************************
|
|
47
|
-
Copyright (c) Microsoft Corporation.
|
|
48
|
-
|
|
49
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
50
|
-
purpose with or without fee is hereby granted.
|
|
51
|
-
|
|
52
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
53
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
54
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
55
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
56
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
57
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
58
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
59
|
-
***************************************************************************** */
|
|
60
|
-
/* global Reflect, Promise, SuppressedError, Symbol */
|
|
61
|
-
|
|
62
|
-
var extendStatics = function(d, b) {
|
|
63
|
-
extendStatics = Object.setPrototypeOf ||
|
|
64
|
-
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
|
65
|
-
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
|
66
|
-
return extendStatics(d, b);
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
function __extends(d, b) {
|
|
70
|
-
if (typeof b !== "function" && b !== null)
|
|
71
|
-
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
|
72
|
-
extendStatics(d, b);
|
|
73
|
-
function __() { this.constructor = d; }
|
|
74
|
-
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
var __assign = function() {
|
|
78
|
-
__assign = Object.assign || function __assign(t) {
|
|
79
|
-
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
80
|
-
s = arguments[i];
|
|
81
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
|
|
82
|
-
}
|
|
83
|
-
return t;
|
|
84
|
-
};
|
|
85
|
-
return __assign.apply(this, arguments);
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
function __awaiter(thisArg, _arguments, P, generator) {
|
|
89
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
90
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
91
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
92
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
93
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
94
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function __generator(thisArg, body) {
|
|
99
|
-
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
|
100
|
-
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
101
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
102
|
-
function step(op) {
|
|
103
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
104
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
105
|
-
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;
|
|
106
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
107
|
-
switch (op[0]) {
|
|
108
|
-
case 0: case 1: t = op; break;
|
|
109
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
110
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
111
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
112
|
-
default:
|
|
113
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
114
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
115
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
116
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
117
|
-
if (t[2]) _.ops.pop();
|
|
118
|
-
_.trys.pop(); continue;
|
|
119
|
-
}
|
|
120
|
-
op = body.call(thisArg, _);
|
|
121
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
122
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
function __spreadArray(to, from, pack) {
|
|
127
|
-
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
128
|
-
if (ar || !(i in from)) {
|
|
129
|
-
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
130
|
-
ar[i] = from[i];
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return to.concat(ar || Array.prototype.slice.call(from));
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
137
|
-
var e = new Error(message);
|
|
138
|
-
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
var Messages$a=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(hasOwnProp(a,c)&&c.toLowerCase()===b.toLowerCase())return c;return null},generateDeprecationMessage=function(a,b,c,d){var e=[a];return b?e.push(Messages$a.DeprecationMessages.MethodHasBeenDeprecated):e.push(Messages$a.DeprecationMessages.MethodMarkedForDeprecationPostfix),c&&(e.push(Messages$a.DeprecationMessages.AlternativeMethodPrefix),e.push(c+".")),d&&e.push("See - "+d),e.join(" ")};function generateHash(a){var b,c=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(var d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c}var generateRandomValue=function(){var b,c;return window.crypto&&window.crypto.getRandomValues&&(b=window.crypto.getRandomValues(new Uint8Array(1))),b?(c^b[0]%16>>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
|
|
142
|
-
?generateRandomValue()// if the placeholder was passed, return
|
|
143
|
-
:// [1e7] -> // 10000000 +
|
|
144
|
-
// -1e3 -> // -1000 +
|
|
145
|
-
// -4e3 -> // -4000 +
|
|
146
|
-
// -8e3 -> // -80000000 +
|
|
147
|
-
// -1e11 -> //-100000000000,
|
|
148
|
-
"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,// zeroes, ones, and eights with
|
|
149
|
-
generateUniqueId// random hex digits
|
|
150
|
-
)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d,e){var f=replaceAmpWithAmpersand(b),g=c?replaceAmpWithAmpersand(c):null,h=replaceMPID(f,a),i=g?replaceMPID(g,a):"",j=h+encodeURIComponent(i);if(d){var k=j.includes("?")?"&":"?";j+="".concat(k,"domain=").concat(d);}if(e){var k=j.includes("?")?"&":"?";j+="".concat(k,"google_hm=").concat(e);}return j},WEB_SAFE_BASE64_REPLACEMENTS={"+":"-","/":"_","=":""},isLatin1=function(a){return !/[^\u0000-\u00ff]/.test(a)},toWebSafeBase64=function(a){return isLatin1(a)?btoa(a).replace(/[+/=]/g,function(a){return WEB_SAFE_BASE64_REPLACEMENTS[a]}):void 0},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers
|
|
151
|
-
return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},hasOwnProp=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)},isReservedStoredPropertyName=function(a){return "__proto__"===a||"constructor"===a},isUncopyableMergeName=function(a){return isReservedStoredPropertyName(a)||"prototype"===a},isReservedKitPropertyName=function(a){return isReservedStoredPropertyName(a)||"hasOwnProperty"===a},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=a.toLowerCase();// Callers pass their own key list, so `name` may not be from this URL.
|
|
152
|
-
hasOwnProp(e,b)&&e[b]&&(d[a]=e[b]);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("#")[0].split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)// Keys come straight off the URL, so `?hasOwnProperty=1` would
|
|
153
|
-
// shadow the method and `params.hasOwnProperty(key)` would throw.
|
|
154
|
-
hasOwnProp(b,c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie
|
|
155
|
-
var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys
|
|
156
|
-
// Parse cookies from document.cookie
|
|
157
|
-
// Filter cookies by keys if provided
|
|
158
|
-
return function filterCookies(a,b){for(var c={},d=0,e=a;d<e.length;d++){var f=e[d],g=f.split("="),h=g[0],i=g[1];(!b||b.includes(h))&&(c[h]=i);}return c}(b,a)},getHref=function(){return "undefined"!=typeof window&&window.location?window.location.href:""},filterDictionaryWithHash=function(a,b,c){var d={};if(!isEmpty(a))for(var e in a)if(hasOwnProp(a,e)&&!isReservedKitPropertyName(e)){var f=c(e);inArray(b,f)||(d[e]=a[e]);}return d},parseConfig=function(a,b,c){var d;return (null===(d=a.kitConfigs)||void 0===d?void 0:d.find(function(a){return a.name===b&&a.moduleId===c}))||null},obfuscateData=function(a){// Preserve null and undefined
|
|
159
|
-
if(null===a||a===void 0)return a;// Handle arrays - recursively obfuscate each element
|
|
160
|
-
if(Array.isArray(a))return a.map(function(a){return obfuscateData(a)});// Handle objects - recursively obfuscate each property
|
|
161
|
-
if(isObject(a)){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=obfuscateData(a[c]));return b}// For primitives and other types, return the type as a string
|
|
162
|
-
return _typeof(a)},obfuscateDevData=function(a,b){return b?a:obfuscateData(a)};/**
|
|
163
|
-
* Returns a value between 1-100 inclusive.
|
|
164
|
-
*/ // Google's cookie matching service requires `google_hm` values to be web-safe
|
|
165
|
-
// base64 (RFC 4648 \u00A75) without padding, otherwise the write to the hosted
|
|
166
|
-
// match table fails: https://developers.google.com/authorized-buyers/rtb/cookie-guide
|
|
167
|
-
// (String#replaceAll is not available in our ES5 browser targets.)
|
|
168
|
-
// btoa is defined only over Latin-1 and throws InvalidCharacterError above U+00FF
|
|
169
|
-
// FIXME: REFACTOR for V3
|
|
170
|
-
// only used in store.js to sanitize server-side formatting of
|
|
171
|
-
// booleans when checking for `isDevelopmentMode`
|
|
172
|
-
// Should be removed in v3
|
|
173
|
-
// For keys that did not come from the object itself: `obj[name]` and `name in obj`
|
|
174
|
-
// both walk the prototype chain, so `constructor` is truthy on any plain object.
|
|
175
|
-
//
|
|
176
|
-
// Not `Object.hasOwn`, which Sonar recommends here (typescript:S6653). It is ES2022 and
|
|
177
|
-
// does not compile under this project's `lib: ["es5", "es6", "dom"]`; widening that
|
|
178
|
-
// would emit a call absent from every browser before 2021, and this same file still
|
|
179
|
-
// carries a fallback for browsers with no URLSearchParams.
|
|
180
|
-
// Assigning `__proto__` replaces the target's prototype instead of adding an own
|
|
181
|
-
// property; `constructor` is reserved alongside it by the stored-record contract.
|
|
182
|
-
// `prototype` is deliberately absent: isValidKeyValue accepts it, so setUserAttribute
|
|
183
|
-
// persists it and the getters must hand it back.
|
|
184
|
-
// extend's historical set, which additionally refuses `prototype` when merging.
|
|
185
|
-
// Kit-facing copies stay compatible with conventional own-property iteration, such as
|
|
186
|
-
// attributes.hasOwnProperty(key), which is the one read pattern an attribute of that name
|
|
187
|
-
// interferes with. The public getters keep the name; only this filter drops it.
|
|
188
|
-
// Get cookies as a dictionary
|
|
189
|
-
/**
|
|
190
|
-
* Obfuscates an object by replacing all primitive values with their type names,
|
|
191
|
-
* while preserving the structure of nested objects and arrays.
|
|
192
|
-
* This is useful for logging data structures without exposing PII.
|
|
193
|
-
*
|
|
194
|
-
* @param value - The value to obfuscate
|
|
195
|
-
* @returns The obfuscated value with types instead of actual values
|
|
196
|
-
*
|
|
197
|
-
* @example
|
|
198
|
-
* obfuscateData({ email: 'user@email.com', age: 30 })
|
|
199
|
-
* // Returns: { email: 'string', age: 'number' }
|
|
200
|
-
*
|
|
201
|
-
* obfuscateData({ tags: ['premium', 'verified'] })
|
|
202
|
-
* // Returns: { tags: ['string', 'string'] }
|
|
203
|
-
*/ /**
|
|
204
|
-
* For verbose logging: returns raw data when isDevelopmentMode is true, else obfuscated data.
|
|
205
|
-
* Used when logging payloads so PII is not exposed in production.
|
|
206
|
-
*
|
|
207
|
-
* @param data - The value to log
|
|
208
|
-
* @param isDevelopmentMode - When true, returns data unchanged, when false or undefined, returns obfuscated data
|
|
209
|
-
* @returns Raw data when isDevelopmentMode is true, otherwise obfuscated structure
|
|
210
|
-
*
|
|
211
|
-
* @example
|
|
212
|
-
* obfuscateDevData({ email: 'user@email.com' }, true)
|
|
213
|
-
* // Returns: { email: 'user@email.com' }
|
|
214
|
-
*
|
|
215
|
-
* obfuscateDevData({ email: 'user@email.com' }, false)
|
|
216
|
-
* // Returns: { email: 'string' }
|
|
217
|
-
*/ // Standalone version of jQuery.extend, from https://github.com/dansdom/extend
|
|
218
|
-
// https://go.mparticle.com/work/SQDSDKS-6047
|
|
219
|
-
function extend(){for(var a=[],b=0;b<arguments.length;b++)a[b]=arguments[b];var c,d,e,f,g,h,j={hasOwn:Object.prototype.hasOwnProperty,class2type:{},type:function type(a){return null==a?a+"":j.class2type[Object.prototype.toString.call(a)]||"object"},isPlainObject:function isPlainObject(a){if(!a||"object"!==j.type(a)||a.nodeType||j.isWindow(a))return !1;try{if(a.constructor&&!j.hasOwn.call(a,"constructor")&&!j.hasOwn.call(a.constructor.prototype,"isPrototypeOf"))return !1}catch(a){return !1}for(var b in a);// eslint-disable-line no-empty
|
|
220
|
-
return b===void 0||j.hasOwn.call(a,b)},isArray:Array.isArray||function(a){return "array"===j.type(a)},isFunction:function(a){return "function"===j.type(a)},isWindow:function isWindow(a){return null!=a&&a==a.window}},k=a[0]||{},l=1,m=!1,n=a.length;for("boolean"==typeof k&&(m=k,k=a[1]||{},l=2),"object"===_typeof(k)||j.isFunction(k)||(k={}),n===l&&(k={},--l);l<n;l++)if(null!=(c=a[l]))for(d in c)isUncopyableMergeName(d)||Object.prototype.hasOwnProperty.call(c,d)&&(e=k[d],f=c[d],k!==f)&&(m&&f&&(j.isPlainObject(f)||(g=j.isArray(f)))?(g?(g=!1,h=e&&j.isArray(e)?e:[]):h=e&&j.isPlainObject(e)?e:{},k[d]=extend(m,h,f)):void 0!==f&&(k[d]=f));return k}var getErrorMessage=function(a,b){return void 0===b&&(b="unknown error"),a instanceof Error?a.message:"string"==typeof a?a:a&&"object"===_typeof(a)&&"string"==typeof a.message?a.message:b;// fetch-mock and some network libs reject with { message } rather than Error
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
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(a){return a===EventType.Unknown?"Unknown":a===EventType.Navigation?"Navigation":a===EventType.Location?"Location":a===EventType.Search?"Search":a===EventType.Transaction?"Transaction":a===EventType.UserContent?"User Content":a===EventType.UserPreference?"User Preference":a===EventType.Social?"Social":a===CommerceEventType.ProductAddToCart?"Product Added to Cart":a===CommerceEventType.ProductAddToWishlist?"Product Added to Wishlist":a===CommerceEventType.ProductCheckout?"Product Checkout":a===CommerceEventType.ProductCheckoutOption?"Product Checkout Options":a===CommerceEventType.ProductClick?"Product Click":a===CommerceEventType.ProductImpression?"Product Impression":a===CommerceEventType.ProductPurchase?"Product Purchased":a===CommerceEventType.ProductRefund?"Product Refunded":a===CommerceEventType.ProductRemoveFromCart?"Product Removed From Cart":a===CommerceEventType.ProductRemoveFromWishlist?"Product Removed from Wishlist":a===CommerceEventType.ProductViewDetail?"Product View Details":a===CommerceEventType.PromotionClick?"Promotion Click":a===CommerceEventType.PromotionView?"Promotion View":"Other"}};// Continuation of EventType enum above, but in seperate object since we don't expose these to end user
|
|
224
|
-
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(a){if("number"==typeof a)for(var b in IdentityType)if(IdentityType.hasOwnProperty(b)&&IdentityType[b]===a)return !0;return !1},getName:function getName(a){return a===window.mParticle.IdentityType.CustomerId?"Customer ID":a===window.mParticle.IdentityType.Facebook?"Facebook ID":a===window.mParticle.IdentityType.Twitter?"Twitter ID":a===window.mParticle.IdentityType.Google?"Google ID":a===window.mParticle.IdentityType.Microsoft?"Microsoft ID":a===window.mParticle.IdentityType.Yahoo?"Yahoo ID":a===window.mParticle.IdentityType.Email?"Email":a===window.mParticle.IdentityType.FacebookCustomAudienceId?"Facebook App User ID":"Other ID"},getIdentityType:function getIdentityType(a){return "other"===a?IdentityType.Other:"customerid"===a?IdentityType.CustomerId:"facebook"===a?IdentityType.Facebook:"twitter"===a?IdentityType.Twitter:"google"===a?IdentityType.Google:"microsoft"===a?IdentityType.Microsoft:"yahoo"===a?IdentityType.Yahoo:"email"===a?IdentityType.Email:"facebookcustomaudienceid"===a?IdentityType.FacebookCustomAudienceId:"other2"===a?IdentityType.Other2:"other3"===a?IdentityType.Other3:"other4"===a?IdentityType.Other4:"other5"===a?IdentityType.Other5:"other6"===a?IdentityType.Other6:"other7"===a?IdentityType.Other7:"other8"===a?IdentityType.Other8:"other9"===a?IdentityType.Other9:"other10"===a?IdentityType.Other10:"mobile_number"===a?IdentityType.MobileNumber:"phone_number_2"===a?IdentityType.PhoneNumber2:"phone_number_3"===a?IdentityType.PhoneNumber3:"email_sha256"===a?IdentityType.Other:!("mobile_sha256"!=a)&&IdentityType.Other2},getIdentityName:function getIdentityName(a){return a===IdentityType.Other?"other":a===IdentityType.CustomerId?"customerid":a===IdentityType.Facebook?"facebook":a===IdentityType.Twitter?"twitter":a===IdentityType.Google?"google":a===IdentityType.Microsoft?"microsoft":a===IdentityType.Yahoo?"yahoo":a===IdentityType.Email?"email":a===IdentityType.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType.Other2?"other2":a===IdentityType.Other3?"other3":a===IdentityType.Other4?"other4":a===IdentityType.Other5?"other5":a===IdentityType.Other6?"other6":a===IdentityType.Other7?"other7":a===IdentityType.Other8?"other8":a===IdentityType.Other9?"other9":a===IdentityType.Other10?"other10":a===IdentityType.MobileNumber?"mobile_number":a===IdentityType.PhoneNumber2?"phone_number_2":a===IdentityType.PhoneNumber3?"phone_number_3":null},// Strips out functions from Identity Types for easier lookups
|
|
225
|
-
getValuesAsStrings:function getValuesAsStrings(){return Object.values(IdentityType).map(function(a){return isNumber(a)?a.toString():void 0}).filter(function(a){return a!==void 0})},getNewIdentitiesByName:function getNewIdentitiesByName(a){var b={},c=IdentityType.getValuesAsStrings();for(var d in a)// IdentityTypes are stored as numbers but are passed in as strings
|
|
226
|
-
if(c.includes(d)){var e=IdentityType.getIdentityName(parseNumber(d));b[e]=a[d];}return b}};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10,// Rokt Brain commerce-adjacent types
|
|
227
|
-
ViewCart:11,AddShippingInfo:12,AddPaymentInfo:13,PaymentMethodSelected:14,PaymentAttempted:15,PaymentSucceeded:16,PaymentFailed:17,RefundInitiated:18,isRoktCommerceType:function isRoktCommerceType(a){return a>=ProductActionType.ViewCart&&a<=ProductActionType.RefundInitiated},getName:function getName(a){return a===ProductActionType.AddToCart?"Add to Cart":a===ProductActionType.RemoveFromCart?"Remove from Cart":a===ProductActionType.Checkout?"Checkout":a===ProductActionType.CheckoutOption?"Checkout Option":a===ProductActionType.Click?"Click":a===ProductActionType.ViewDetail?"View Detail":a===ProductActionType.Purchase?"Purchase":a===ProductActionType.Refund?"Refund":a===ProductActionType.AddToWishlist?"Add to Wishlist":a===ProductActionType.RemoveFromWishlist?"Remove from Wishlist":a===ProductActionType.ViewCart?"View Cart":a===ProductActionType.AddShippingInfo?"Add Shipping Info":a===ProductActionType.AddPaymentInfo?"Add Payment Info":a===ProductActionType.PaymentMethodSelected?"Payment Method Selected":a===ProductActionType.PaymentAttempted?"Payment Attempted":a===ProductActionType.PaymentSucceeded?"Payment Succeeded":a===ProductActionType.PaymentFailed?"Payment Failed":a===ProductActionType.RefundInitiated?"Refund Initiated":"Unknown"},// these are the action names used by server and mobile SDKs when expanding a CommerceEvent
|
|
228
|
-
getExpansionName:function getExpansionName(a){return a===ProductActionType.AddToCart?"add_to_cart":a===ProductActionType.RemoveFromCart?"remove_from_cart":a===ProductActionType.Checkout?"checkout":a===ProductActionType.CheckoutOption?"checkout_option":a===ProductActionType.Click?"click":a===ProductActionType.ViewDetail?"view_detail":a===ProductActionType.Purchase?"purchase":a===ProductActionType.Refund?"refund":a===ProductActionType.AddToWishlist?"add_to_wishlist":a===ProductActionType.RemoveFromWishlist?"remove_from_wishlist":a===ProductActionType.ViewCart?"view_cart":a===ProductActionType.AddShippingInfo?"add_shipping_info":a===ProductActionType.AddPaymentInfo?"add_payment_info":a===ProductActionType.PaymentMethodSelected?"payment_method_selected":a===ProductActionType.PaymentAttempted?"payment_attempted":a===ProductActionType.PaymentSucceeded?"payment_succeeded":a===ProductActionType.PaymentFailed?"payment_failed":a===ProductActionType.RefundInitiated?"refund_initiated":"unknown"}};var RoktEvents={SignUp:"sign_up",Subscribe:"subscribe",StartTrial:"start_trial",GenerateLead:"generate_lead",Search:"search",Upsell:"upsell",EarnVirtualCurrency:"earn_virtual_currency",DwellTime:"dwell_time",Hover:"hover",Scroll:"scroll",ClickToExpand:"click_to_expand"};var PromotionActionType={Unknown:0,PromotionView:1,PromotionClick:2,getName:function getName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},// these are the names that the server and mobile SDKs use while expanding CommerceEvent
|
|
229
|
-
getExpansionName:function getExpansionName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"}};var ProfileMessageType={Logout:3};var ApplicationTransitionType$1={AppInit:1};var PerformanceMarkType={SdkStart:"mp:sdkStart",JointSdkSelectPlacements:"mp:jointSdkSelectPlacements",JointSdkRoktKitInit:"mp:jointSdkRoktKitInit"};// not written by this SDK. The round-trip comparison is load bearing: parseNumber
|
|
230
|
-
// returns 0 for any non-numeric key and IdentityType.Other is 0, so after parsing
|
|
231
|
-
// alone a stored "hasOwnProperty" is indistinguishable from a genuine Other entry.
|
|
232
|
-
function getIdentityTypeFromStoredKey(a){var b=parseNumber(a);return b+""===a&&IdentityType.isValid(b)?b:null}var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,RoktEvents:RoktEvents,Environment:Constants.Environment};
|
|
233
|
-
|
|
234
|
-
var SDKProductActionType;(function(a){a[a.Unknown=0]="Unknown",a[a.AddToCart=1]="AddToCart",a[a.RemoveFromCart=2]="RemoveFromCart",a[a.Checkout=3]="Checkout",a[a.CheckoutOption=4]="CheckoutOption",a[a.Click=5]="Click",a[a.ViewDetail=6]="ViewDetail",a[a.Purchase=7]="Purchase",a[a.Refund=8]="Refund",a[a.AddToWishlist=9]="AddToWishlist",a[a.RemoveFromWishlist=10]="RemoveFromWishlist",a[a.ViewCart=11]="ViewCart",a[a.AddShippingInfo=12]="AddShippingInfo",a[a.AddPaymentInfo=13]="AddPaymentInfo",a[a.PaymentMethodSelected=14]="PaymentMethodSelected",a[a.PaymentAttempted=15]="PaymentAttempted",a[a.PaymentSucceeded=16]="PaymentSucceeded",a[a.PaymentFailed=17]="PaymentFailed",a[a.RefundInitiated=18]="RefundInitiated";})(SDKProductActionType||(SDKProductActionType={}));var LogLevelType={None:"none",Verbose:"verbose",Warning:"warning",Error:"error"};
|
|
235
|
-
|
|
236
|
-
var dist = {};
|
|
237
|
-
|
|
238
|
-
(function (exports) {
|
|
239
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
240
|
-
(function (ApplicationInformationOsEnum) {
|
|
241
|
-
ApplicationInformationOsEnum["unknown"] = "Unknown";
|
|
242
|
-
ApplicationInformationOsEnum["iOS"] = "IOS";
|
|
243
|
-
ApplicationInformationOsEnum["android"] = "Android";
|
|
244
|
-
ApplicationInformationOsEnum["windowsPhone"] = "WindowsPhone";
|
|
245
|
-
ApplicationInformationOsEnum["mobileWeb"] = "MobileWeb";
|
|
246
|
-
ApplicationInformationOsEnum["unityIOS"] = "UnityIOS";
|
|
247
|
-
ApplicationInformationOsEnum["unityAndroid"] = "UnityAndroid";
|
|
248
|
-
ApplicationInformationOsEnum["desktop"] = "Desktop";
|
|
249
|
-
ApplicationInformationOsEnum["tvOS"] = "TVOS";
|
|
250
|
-
ApplicationInformationOsEnum["roku"] = "Roku";
|
|
251
|
-
ApplicationInformationOsEnum["outOfBand"] = "OutOfBand";
|
|
252
|
-
ApplicationInformationOsEnum["alexa"] = "Alexa";
|
|
253
|
-
ApplicationInformationOsEnum["smartTV"] = "SmartTV";
|
|
254
|
-
ApplicationInformationOsEnum["fireTV"] = "FireTV";
|
|
255
|
-
ApplicationInformationOsEnum["xbox"] = "Xbox";
|
|
256
|
-
})(exports.ApplicationInformationOsEnum || (exports.ApplicationInformationOsEnum = {}));
|
|
257
|
-
(function (ApplicationStateTransitionEventEventTypeEnum) {
|
|
258
|
-
ApplicationStateTransitionEventEventTypeEnum["applicationStateTransition"] = "application_state_transition";
|
|
259
|
-
})(exports.ApplicationStateTransitionEventEventTypeEnum || (exports.ApplicationStateTransitionEventEventTypeEnum = {}));
|
|
260
|
-
(function (ApplicationStateTransitionEventDataApplicationTransitionTypeEnum) {
|
|
261
|
-
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationInitialized"] = "application_initialized";
|
|
262
|
-
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationExit"] = "application_exit";
|
|
263
|
-
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationBackground"] = "application_background";
|
|
264
|
-
ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationForeground"] = "application_foreground";
|
|
265
|
-
})(exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum || (exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum = {}));
|
|
266
|
-
(function (BatchEnvironmentEnum) {
|
|
267
|
-
BatchEnvironmentEnum["unknown"] = "unknown";
|
|
268
|
-
BatchEnvironmentEnum["development"] = "development";
|
|
269
|
-
BatchEnvironmentEnum["production"] = "production";
|
|
270
|
-
})(exports.BatchEnvironmentEnum || (exports.BatchEnvironmentEnum = {}));
|
|
271
|
-
(function (BreadcrumbEventEventTypeEnum) {
|
|
272
|
-
BreadcrumbEventEventTypeEnum["breadcrumb"] = "breadcrumb";
|
|
273
|
-
})(exports.BreadcrumbEventEventTypeEnum || (exports.BreadcrumbEventEventTypeEnum = {}));
|
|
274
|
-
(function (CommerceEventEventTypeEnum) {
|
|
275
|
-
CommerceEventEventTypeEnum["commerceEvent"] = "commerce_event";
|
|
276
|
-
})(exports.CommerceEventEventTypeEnum || (exports.CommerceEventEventTypeEnum = {}));
|
|
277
|
-
(function (CommerceEventDataCustomEventTypeEnum) {
|
|
278
|
-
CommerceEventDataCustomEventTypeEnum["addToCart"] = "add_to_cart";
|
|
279
|
-
CommerceEventDataCustomEventTypeEnum["removeFromCart"] = "remove_from_cart";
|
|
280
|
-
CommerceEventDataCustomEventTypeEnum["checkout"] = "checkout";
|
|
281
|
-
CommerceEventDataCustomEventTypeEnum["checkoutOption"] = "checkout_option";
|
|
282
|
-
CommerceEventDataCustomEventTypeEnum["click"] = "click";
|
|
283
|
-
CommerceEventDataCustomEventTypeEnum["viewDetail"] = "view_detail";
|
|
284
|
-
CommerceEventDataCustomEventTypeEnum["purchase"] = "purchase";
|
|
285
|
-
CommerceEventDataCustomEventTypeEnum["refund"] = "refund";
|
|
286
|
-
CommerceEventDataCustomEventTypeEnum["promotionView"] = "promotion_view";
|
|
287
|
-
CommerceEventDataCustomEventTypeEnum["promotionClick"] = "promotion_click";
|
|
288
|
-
CommerceEventDataCustomEventTypeEnum["addToWishlist"] = "add_to_wishlist";
|
|
289
|
-
CommerceEventDataCustomEventTypeEnum["removeFromWishlist"] = "remove_from_wishlist";
|
|
290
|
-
CommerceEventDataCustomEventTypeEnum["impression"] = "impression";
|
|
291
|
-
})(exports.CommerceEventDataCustomEventTypeEnum || (exports.CommerceEventDataCustomEventTypeEnum = {}));
|
|
292
|
-
(function (CrashReportEventEventTypeEnum) {
|
|
293
|
-
CrashReportEventEventTypeEnum["crashReport"] = "crash_report";
|
|
294
|
-
})(exports.CrashReportEventEventTypeEnum || (exports.CrashReportEventEventTypeEnum = {}));
|
|
295
|
-
(function (CustomEventEventTypeEnum) {
|
|
296
|
-
CustomEventEventTypeEnum["customEvent"] = "custom_event";
|
|
297
|
-
})(exports.CustomEventEventTypeEnum || (exports.CustomEventEventTypeEnum = {}));
|
|
298
|
-
(function (CustomEventDataCustomEventTypeEnum) {
|
|
299
|
-
CustomEventDataCustomEventTypeEnum["navigation"] = "navigation";
|
|
300
|
-
CustomEventDataCustomEventTypeEnum["location"] = "location";
|
|
301
|
-
CustomEventDataCustomEventTypeEnum["search"] = "search";
|
|
302
|
-
CustomEventDataCustomEventTypeEnum["transaction"] = "transaction";
|
|
303
|
-
CustomEventDataCustomEventTypeEnum["userContent"] = "user_content";
|
|
304
|
-
CustomEventDataCustomEventTypeEnum["userPreference"] = "user_preference";
|
|
305
|
-
CustomEventDataCustomEventTypeEnum["social"] = "social";
|
|
306
|
-
CustomEventDataCustomEventTypeEnum["media"] = "media";
|
|
307
|
-
CustomEventDataCustomEventTypeEnum["other"] = "other";
|
|
308
|
-
CustomEventDataCustomEventTypeEnum["unknown"] = "unknown";
|
|
309
|
-
})(exports.CustomEventDataCustomEventTypeEnum || (exports.CustomEventDataCustomEventTypeEnum = {}));
|
|
310
|
-
(function (DeviceCurrentStateDeviceOrientationEnum) {
|
|
311
|
-
DeviceCurrentStateDeviceOrientationEnum["portrait"] = "portrait";
|
|
312
|
-
DeviceCurrentStateDeviceOrientationEnum["portraitUpsideDown"] = "portrait_upside_down";
|
|
313
|
-
DeviceCurrentStateDeviceOrientationEnum["landscape"] = "landscape";
|
|
314
|
-
DeviceCurrentStateDeviceOrientationEnum["landscapeLeft"] = "LandscapeLeft";
|
|
315
|
-
DeviceCurrentStateDeviceOrientationEnum["landscapeRight"] = "LandscapeRight";
|
|
316
|
-
DeviceCurrentStateDeviceOrientationEnum["faceUp"] = "FaceUp";
|
|
317
|
-
DeviceCurrentStateDeviceOrientationEnum["faceDown"] = "FaceDown";
|
|
318
|
-
DeviceCurrentStateDeviceOrientationEnum["square"] = "Square";
|
|
319
|
-
})(exports.DeviceCurrentStateDeviceOrientationEnum || (exports.DeviceCurrentStateDeviceOrientationEnum = {}));
|
|
320
|
-
(function (DeviceCurrentStateStatusBarOrientationEnum) {
|
|
321
|
-
DeviceCurrentStateStatusBarOrientationEnum["portrait"] = "portrait";
|
|
322
|
-
DeviceCurrentStateStatusBarOrientationEnum["portraitUpsideDown"] = "portrait_upside_down";
|
|
323
|
-
DeviceCurrentStateStatusBarOrientationEnum["landscape"] = "landscape";
|
|
324
|
-
DeviceCurrentStateStatusBarOrientationEnum["landscapeLeft"] = "LandscapeLeft";
|
|
325
|
-
DeviceCurrentStateStatusBarOrientationEnum["landscapeRight"] = "LandscapeRight";
|
|
326
|
-
DeviceCurrentStateStatusBarOrientationEnum["faceUp"] = "FaceUp";
|
|
327
|
-
DeviceCurrentStateStatusBarOrientationEnum["faceDown"] = "FaceDown";
|
|
328
|
-
DeviceCurrentStateStatusBarOrientationEnum["square"] = "Square";
|
|
329
|
-
})(exports.DeviceCurrentStateStatusBarOrientationEnum || (exports.DeviceCurrentStateStatusBarOrientationEnum = {}));
|
|
330
|
-
(function (DeviceInformationPlatformEnum) {
|
|
331
|
-
DeviceInformationPlatformEnum["iOS"] = "iOS";
|
|
332
|
-
DeviceInformationPlatformEnum["android"] = "Android";
|
|
333
|
-
DeviceInformationPlatformEnum["web"] = "web";
|
|
334
|
-
DeviceInformationPlatformEnum["desktop"] = "desktop";
|
|
335
|
-
DeviceInformationPlatformEnum["tvOS"] = "tvOS";
|
|
336
|
-
DeviceInformationPlatformEnum["roku"] = "roku";
|
|
337
|
-
DeviceInformationPlatformEnum["outOfBand"] = "out_of_band";
|
|
338
|
-
DeviceInformationPlatformEnum["smartTV"] = "smart_tv";
|
|
339
|
-
DeviceInformationPlatformEnum["xbox"] = "xbox";
|
|
340
|
-
})(exports.DeviceInformationPlatformEnum || (exports.DeviceInformationPlatformEnum = {}));
|
|
341
|
-
(function (EventTypeEnum) {
|
|
342
|
-
EventTypeEnum["unknown"] = "unknown";
|
|
343
|
-
EventTypeEnum["sessionStart"] = "session_start";
|
|
344
|
-
EventTypeEnum["sessionEnd"] = "session_end";
|
|
345
|
-
EventTypeEnum["screenView"] = "screen_view";
|
|
346
|
-
EventTypeEnum["customEvent"] = "custom_event";
|
|
347
|
-
EventTypeEnum["crashReport"] = "crash_report";
|
|
348
|
-
EventTypeEnum["optOut"] = "opt_out";
|
|
349
|
-
EventTypeEnum["firstRun"] = "first_run";
|
|
350
|
-
EventTypeEnum["preAttribution"] = "pre_attribution";
|
|
351
|
-
EventTypeEnum["pushRegistration"] = "push_registration";
|
|
352
|
-
EventTypeEnum["applicationStateTransition"] = "application_state_transition";
|
|
353
|
-
EventTypeEnum["pushMessage"] = "push_message";
|
|
354
|
-
EventTypeEnum["networkPerformance"] = "network_performance";
|
|
355
|
-
EventTypeEnum["breadcrumb"] = "breadcrumb";
|
|
356
|
-
EventTypeEnum["profile"] = "profile";
|
|
357
|
-
EventTypeEnum["pushReaction"] = "push_reaction";
|
|
358
|
-
EventTypeEnum["commerceEvent"] = "commerce_event";
|
|
359
|
-
EventTypeEnum["userAttributeChange"] = "user_attribute_change";
|
|
360
|
-
EventTypeEnum["userIdentityChange"] = "user_identity_change";
|
|
361
|
-
EventTypeEnum["uninstall"] = "uninstall";
|
|
362
|
-
EventTypeEnum["validationResult"] = "validation_result";
|
|
363
|
-
})(exports.EventTypeEnum || (exports.EventTypeEnum = {}));
|
|
364
|
-
(function (IdentityTypeEnum) {
|
|
365
|
-
IdentityTypeEnum["other"] = "other";
|
|
366
|
-
IdentityTypeEnum["customerId"] = "customer_id";
|
|
367
|
-
IdentityTypeEnum["facebook"] = "facebook";
|
|
368
|
-
IdentityTypeEnum["twitter"] = "twitter";
|
|
369
|
-
IdentityTypeEnum["google"] = "google";
|
|
370
|
-
IdentityTypeEnum["microsoft"] = "microsoft";
|
|
371
|
-
IdentityTypeEnum["yahoo"] = "yahoo";
|
|
372
|
-
IdentityTypeEnum["email"] = "email";
|
|
373
|
-
IdentityTypeEnum["alias"] = "alias";
|
|
374
|
-
IdentityTypeEnum["facebookCustomAudienceId"] = "facebook_custom_audience_id";
|
|
375
|
-
IdentityTypeEnum["otherId2"] = "other_id_2";
|
|
376
|
-
IdentityTypeEnum["otherId3"] = "other_id_3";
|
|
377
|
-
IdentityTypeEnum["otherId4"] = "other_id_4";
|
|
378
|
-
IdentityTypeEnum["otherId5"] = "other_id_5";
|
|
379
|
-
IdentityTypeEnum["otherId6"] = "other_id_6";
|
|
380
|
-
IdentityTypeEnum["otherId7"] = "other_id_7";
|
|
381
|
-
IdentityTypeEnum["otherId8"] = "other_id_8";
|
|
382
|
-
IdentityTypeEnum["otherId9"] = "other_id_9";
|
|
383
|
-
IdentityTypeEnum["otherId10"] = "other_id_10";
|
|
384
|
-
IdentityTypeEnum["mobileNumber"] = "mobile_number";
|
|
385
|
-
IdentityTypeEnum["phoneNumber2"] = "phone_number_2";
|
|
386
|
-
IdentityTypeEnum["phoneNumber3"] = "phone_number_3";
|
|
387
|
-
})(exports.IdentityTypeEnum || (exports.IdentityTypeEnum = {}));
|
|
388
|
-
(function (NetworkPerformanceEventEventTypeEnum) {
|
|
389
|
-
NetworkPerformanceEventEventTypeEnum["networkPerformance"] = "network_performance";
|
|
390
|
-
})(exports.NetworkPerformanceEventEventTypeEnum || (exports.NetworkPerformanceEventEventTypeEnum = {}));
|
|
391
|
-
(function (OptOutEventEnum) {
|
|
392
|
-
OptOutEventEnum["optOut"] = "opt_out";
|
|
393
|
-
})(exports.OptOutEventEnum || (exports.OptOutEventEnum = {}));
|
|
394
|
-
(function (ProductActionActionEnum) {
|
|
395
|
-
ProductActionActionEnum["unknown"] = "unknown";
|
|
396
|
-
ProductActionActionEnum["addToCart"] = "add_to_cart";
|
|
397
|
-
ProductActionActionEnum["removeFromCart"] = "remove_from_cart";
|
|
398
|
-
ProductActionActionEnum["checkout"] = "checkout";
|
|
399
|
-
ProductActionActionEnum["checkoutOption"] = "checkout_option";
|
|
400
|
-
ProductActionActionEnum["click"] = "click";
|
|
401
|
-
ProductActionActionEnum["viewDetail"] = "view_detail";
|
|
402
|
-
ProductActionActionEnum["purchase"] = "purchase";
|
|
403
|
-
ProductActionActionEnum["refund"] = "refund";
|
|
404
|
-
ProductActionActionEnum["addToWishlist"] = "add_to_wishlist";
|
|
405
|
-
ProductActionActionEnum["removeFromWishlist"] = "remove_from_wish_list";
|
|
406
|
-
})(exports.ProductActionActionEnum || (exports.ProductActionActionEnum = {}));
|
|
407
|
-
(function (ProfileEventEventTypeEnum) {
|
|
408
|
-
ProfileEventEventTypeEnum["profile"] = "profile";
|
|
409
|
-
})(exports.ProfileEventEventTypeEnum || (exports.ProfileEventEventTypeEnum = {}));
|
|
410
|
-
(function (ProfileEventDataProfileEventTypeEnum) {
|
|
411
|
-
ProfileEventDataProfileEventTypeEnum["signup"] = "signup";
|
|
412
|
-
ProfileEventDataProfileEventTypeEnum["login"] = "login";
|
|
413
|
-
ProfileEventDataProfileEventTypeEnum["logout"] = "logout";
|
|
414
|
-
ProfileEventDataProfileEventTypeEnum["update"] = "update";
|
|
415
|
-
ProfileEventDataProfileEventTypeEnum["delete"] = "delete";
|
|
416
|
-
})(exports.ProfileEventDataProfileEventTypeEnum || (exports.ProfileEventDataProfileEventTypeEnum = {}));
|
|
417
|
-
(function (PromotionActionActionEnum) {
|
|
418
|
-
PromotionActionActionEnum["view"] = "view";
|
|
419
|
-
PromotionActionActionEnum["click"] = "click";
|
|
420
|
-
})(exports.PromotionActionActionEnum || (exports.PromotionActionActionEnum = {}));
|
|
421
|
-
(function (PushMessageEventEventTypeEnum) {
|
|
422
|
-
PushMessageEventEventTypeEnum["pushMessage"] = "push_message";
|
|
423
|
-
})(exports.PushMessageEventEventTypeEnum || (exports.PushMessageEventEventTypeEnum = {}));
|
|
424
|
-
(function (PushMessageEventDataPushMessageTypeEnum) {
|
|
425
|
-
PushMessageEventDataPushMessageTypeEnum["sent"] = "sent";
|
|
426
|
-
PushMessageEventDataPushMessageTypeEnum["received"] = "received";
|
|
427
|
-
PushMessageEventDataPushMessageTypeEnum["action"] = "action";
|
|
428
|
-
})(exports.PushMessageEventDataPushMessageTypeEnum || (exports.PushMessageEventDataPushMessageTypeEnum = {}));
|
|
429
|
-
(function (PushMessageEventDataApplicationStateEnum) {
|
|
430
|
-
PushMessageEventDataApplicationStateEnum["notRunning"] = "not_running";
|
|
431
|
-
PushMessageEventDataApplicationStateEnum["background"] = "background";
|
|
432
|
-
PushMessageEventDataApplicationStateEnum["foreground"] = "foreground";
|
|
433
|
-
})(exports.PushMessageEventDataApplicationStateEnum || (exports.PushMessageEventDataApplicationStateEnum = {}));
|
|
434
|
-
(function (PushMessageEventDataPushMessageBehaviorEnum) {
|
|
435
|
-
PushMessageEventDataPushMessageBehaviorEnum["received"] = "Received";
|
|
436
|
-
PushMessageEventDataPushMessageBehaviorEnum["directOpen"] = "DirectOpen";
|
|
437
|
-
PushMessageEventDataPushMessageBehaviorEnum["read"] = "Read";
|
|
438
|
-
PushMessageEventDataPushMessageBehaviorEnum["influencedOpen"] = "InfluencedOpen";
|
|
439
|
-
PushMessageEventDataPushMessageBehaviorEnum["displayed"] = "Displayed";
|
|
440
|
-
})(exports.PushMessageEventDataPushMessageBehaviorEnum || (exports.PushMessageEventDataPushMessageBehaviorEnum = {}));
|
|
441
|
-
(function (PushRegistrationEventEventTypeEnum) {
|
|
442
|
-
PushRegistrationEventEventTypeEnum["pushRegistration"] = "push_registration";
|
|
443
|
-
})(exports.PushRegistrationEventEventTypeEnum || (exports.PushRegistrationEventEventTypeEnum = {}));
|
|
444
|
-
(function (SessionEndEventEventTypeEnum) {
|
|
445
|
-
SessionEndEventEventTypeEnum["sessionEnd"] = "session_end";
|
|
446
|
-
})(exports.SessionEndEventEventTypeEnum || (exports.SessionEndEventEventTypeEnum = {}));
|
|
447
|
-
(function (SessionStartEventEventTypeEnum) {
|
|
448
|
-
SessionStartEventEventTypeEnum["sessionStart"] = "session_start";
|
|
449
|
-
})(exports.SessionStartEventEventTypeEnum || (exports.SessionStartEventEventTypeEnum = {}));
|
|
450
|
-
(function (SourceInformationChannelEnum) {
|
|
451
|
-
SourceInformationChannelEnum["native"] = "native";
|
|
452
|
-
SourceInformationChannelEnum["javascript"] = "javascript";
|
|
453
|
-
SourceInformationChannelEnum["pixel"] = "pixel";
|
|
454
|
-
SourceInformationChannelEnum["desktop"] = "desktop";
|
|
455
|
-
SourceInformationChannelEnum["partner"] = "partner";
|
|
456
|
-
SourceInformationChannelEnum["serverToServer"] = "server_to_server";
|
|
457
|
-
})(exports.SourceInformationChannelEnum || (exports.SourceInformationChannelEnum = {}));
|
|
458
|
-
(function (UserAttributeChangeEventEventTypeEnum) {
|
|
459
|
-
UserAttributeChangeEventEventTypeEnum["userAttributeChange"] = "user_attribute_change";
|
|
460
|
-
})(exports.UserAttributeChangeEventEventTypeEnum || (exports.UserAttributeChangeEventEventTypeEnum = {}));
|
|
461
|
-
(function (UserIdentityChangeEventEventTypeEnum) {
|
|
462
|
-
UserIdentityChangeEventEventTypeEnum["userIdentityChange"] = "user_identity_change";
|
|
463
|
-
})(exports.UserIdentityChangeEventEventTypeEnum || (exports.UserIdentityChangeEventEventTypeEnum = {}));
|
|
464
|
-
} (dist));
|
|
465
|
-
|
|
466
|
-
var SDKIdentityTypeEnum;(function(a){a.other="other",a.customerId="customerid",a.facebook="facebook",a.twitter="twitter",a.google="google",a.microsoft="microsoft",a.yahoo="yahoo",a.email="email",a.alias="alias",a.facebookCustomAudienceId="facebookcustomaudienceid",a.otherId2="other2",a.otherId3="other3",a.otherId4="other4",a.otherId5="other5",a.otherId6="other6",a.otherId7="other7",a.otherId8="other8",a.otherId9="other9",a.otherId10="other10",a.mobileNumber="mobile_number",a.phoneNumber2="phone_number_2",a.phoneNumber3="phone_number_3";})(SDKIdentityTypeEnum||(SDKIdentityTypeEnum={}));
|
|
467
|
-
|
|
468
|
-
// The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
|
|
469
|
-
// - version is always this prefix: fb
|
|
470
|
-
// - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2)
|
|
471
|
-
// - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value
|
|
472
|
-
// - <fbclid> is the value for the fbclid query parameter in the page URL.
|
|
473
|
-
// https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc
|
|
474
|
-
var facebookClickIdProcessor=function(a,b,c){if(!a||!b)return "";var d=null===b||void 0===b?void 0:b.split("//");if(!d)return "";var e=d[1].split("/"),f=e[0].split("."),g=1;// The rules for subdomainIndex are for parsing the domain portion
|
|
475
|
-
// of the URL for cookies, but in this case we are parsing the URL
|
|
476
|
-
// itself, so we can ignore the use of 0 for 'com'
|
|
477
|
-
3<=f.length&&(g=2);// If timestamp is not provided, use the current time
|
|
478
|
-
var h=c||Date.now();return "fb.".concat(g,".").concat(h,".").concat(a)};// Integration outputs are used to determine how click ids are used within the SDK
|
|
479
|
-
// CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject
|
|
480
|
-
// PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch
|
|
481
|
-
// INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created
|
|
482
|
-
var IntegrationOutputs={CUSTOM_FLAGS:"custom_flags",PARTNER_IDENTITIES:"partner_identities",INTEGRATION_ATTRIBUTES:"integration_attributes"},integrationMappingExternal={// Facebook / Meta
|
|
483
|
-
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
|
|
484
|
-
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
|
|
485
|
-
ttclid:{mappedKey:"TikTok.Callback",output:IntegrationOutputs.CUSTOM_FLAGS},_ttp:{mappedKey:"tiktok_cookie_id",output:IntegrationOutputs.PARTNER_IDENTITIES},// Snapchat
|
|
486
|
-
// https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US
|
|
487
|
-
ScCid:{mappedKey:"SnapchatConversions.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Pinterest
|
|
488
|
-
// https://developers.pinterest.com/docs/track-conversions/track-conversions-in-the-api/
|
|
489
|
-
// https://help.pinterest.com/en/business/article/pinterest-tag-parameters-and-cookies
|
|
490
|
-
epik:{mappedKey:"Pinterest.click_id",output:IntegrationOutputs.CUSTOM_FLAGS},_epik:{mappedKey:"Pinterest.click_id",output:IntegrationOutputs.CUSTOM_FLAGS},// Snapchat
|
|
491
|
-
// https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id
|
|
492
|
-
_scid:{mappedKey:"SnapchatConversions.Cookie1",output:IntegrationOutputs.CUSTOM_FLAGS}},integrationMappingRokt={// Rokt
|
|
493
|
-
// https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/
|
|
494
|
-
// https://go.mparticle.com/work/SQDSDKS-7167
|
|
495
|
-
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}};function isIntegrationCaptureEnabled(a){if(!a)return !1;var b=a(Constants.FeatureFlags.CaptureIntegrationSpecificIds),c=a(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2);return !!c&&c!==Constants.CaptureIntegrationSpecificIdsV2Modes.None||!0===b}var IntegrationCapture=/** @class */function(){function a(a){this.initialTimestamp=Date.now(),this.captureMode=a,this.filteredPartnerIdentityMappings=this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES),this.filteredCustomFlagMappings=this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS),this.filteredIntegrationAttributeMappings=this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);}/**
|
|
496
|
-
* Captures Integration Ids from cookies and query params and stores them in clickIds object
|
|
497
|
-
*/return a.prototype.capture=function(){var a=this.captureQueryParams()||{},b=this.captureCookies()||{},c=this.captureLocalStorage()||{};this.normalizePinterestClickId(a),this.normalizePinterestClickId(c),this.normalizePinterestClickId(b),this.applySourcePrecedence([a,c,b,this.clickIds||{}]),this.clickIds=__assign(__assign(__assign(__assign({},this.clickIds),b),c),a);},a.prototype.captureCookies=function(){var a=this.getAllowedKeysForMode(),b=getCookies(a);return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.captureQueryParams=function(){var a=this.getQueryParams();return this.applyProcessors(a,getHref(),this.initialTimestamp)},a.prototype.captureLocalStorage=function(){for(var a=this.getAllowedKeysForMode(),b={},c=0,d=a;c<d.length;c++){var e=d[c],f=localStorage.getItem(e);f&&(b[e]=f);}return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.getQueryParams=function(){var a=this.getAllowedKeysForMode();return queryStringParser(getHref(),a)},a.prototype.getClickIdsAsCustomFlags=function(){return this.getClickIds(this.clickIds,this.filteredCustomFlagMappings)},a.prototype.getClickIdsAsPartnerIdentities=function(){return this.getClickIds(this.clickIds,this.filteredPartnerIdentityMappings)},a.prototype.getClickIdsAsIntegrationAttributes=function(){var a,b,c,d={};// Integration IDs are stored in the following format:
|
|
498
|
-
// {
|
|
499
|
-
// "integration_attributes": {
|
|
500
|
-
// "<moduleId>": {
|
|
501
|
-
// "mappedKey": "clickIdValue"
|
|
502
|
-
// }
|
|
503
|
-
// }
|
|
504
|
-
// }
|
|
505
|
-
for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.normalizePinterestClickId=function(a){isEmpty(null===a||void 0===a?void 0:a._epik)||isEmpty(null===a||void 0===a?void 0:a.epik)||delete a.epik;},a.prototype.applySourcePrecedence=function(a){for(var b=this.getActiveIntegrationMapping(),c=function outputOf(a){var c;return (null===(c=b[a])||void 0===c?void 0:c.mappedKey)||a},d=[],e=0,f=a;e<f.length;e++){var g=f[e],h=[];for(var i in g){var j=c(i);-1===d.indexOf(j)?!isEmpty(g[i])&&h.push(j):delete g[i];}d.push.apply(d,h);}},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}();
|
|
506
|
-
|
|
507
|
-
function convertEvents(a,b,c){if(!a)return null;if(!b||1>b.length)return null;for(var d,e=c._IntegrationCapture,f=c._Helpers,g=f.getFeatureFlag,h=c.Identity.getCurrentUser(),i=[],j=null,k=0,l=b;k<l.length;k++)if(d=l[k],d){j=d;var m=convertEvent(d);m&&i.push(m);}if(!j)return null;var n=null;// Add the consent state from either the Last Event or the user
|
|
508
|
-
isEmpty(j.ConsentState)?!isEmpty(h)&&(n=h.getConsentState()):n=j.ConsentState;var o={source_request_id:c._Helpers.generateUniqueId(),mpid:a,timestamp_unixtime_ms:new Date().getTime(),environment:j.Debug?dist.BatchEnvironmentEnum.development:dist.BatchEnvironmentEnum.production,events:i,mp_deviceid:j.DeviceId,sdk_version:j.SDKVersion,// TODO: Refactor this to read from _Store or a global config
|
|
509
|
-
application_info:{application_version:j.AppVersion,application_name:j.AppName,package:j.Package,sideloaded_kits_count:c._Store.sideloadedKitsCount},device_info:{platform:dist.DeviceInformationPlatformEnum.web,screen_width:"undefined"!=typeof window&&"undefined"!=typeof window.screen?window.screen.width:0,screen_height:"undefined"!=typeof window&&"undefined"!=typeof window.screen?window.screen.height:0},user_attributes:j.UserAttributes,user_identities:convertUserIdentities(j.UserIdentities),consent_state:convertConsentState(n),integration_attributes:j.IntegrationAttributes};// https://go.mparticle.com/work/SQDSDKS-7639
|
|
510
|
-
if(j.DataPlan&&j.DataPlan.PlanId&&(o.context={data_plan:{plan_id:j.DataPlan.PlanId,plan_version:j.DataPlan.PlanVersion||void 0}}),isIntegrationCaptureEnabled(g)){null===e||void 0===e?void 0:e.capture();var p=null===e||void 0===e?void 0:e.getClickIdsAsPartnerIdentities();isEmpty(p)||(o.partner_identities=p);}return o}function convertConsentState(a){if(isEmpty(a))return null;var b={gdpr:convertGdprConsentState(a.getGDPRConsentState()),ccpa:convertCcpaConsentState(a.getCCPAConsentState())};return b}function convertGdprConsentState(a){if(!a)return null;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]={consented:a[c].Consented,hardware_id:a[c].HardwareId,document:a[c].ConsentDocument,timestamp_unixtime_ms:a[c].Timestamp,location:a[c].Location});return b}function convertCcpaConsentState(a){if(!a)return null;var b={data_sale_opt_out:{consented:a.Consented,hardware_id:a.HardwareId,document:a.ConsentDocument,timestamp_unixtime_ms:a.Timestamp,location:a.Location}};return b}function convertUserIdentities(a){if(!a||!a.length)return null;for(var b,c={},d=0,e=a;d<e.length;d++)switch(b=e[d],b.Type){case Types.IdentityType.CustomerId:c.customer_id=b.Identity;break;case Types.IdentityType.Email:c.email=b.Identity;break;case Types.IdentityType.Facebook:c.facebook=b.Identity;break;case Types.IdentityType.FacebookCustomAudienceId:c.facebook_custom_audience_id=b.Identity;break;case Types.IdentityType.Google:c.google=b.Identity;break;case Types.IdentityType.Microsoft:c.microsoft=b.Identity;break;case Types.IdentityType.Other:c.other=b.Identity;break;case Types.IdentityType.Other2:c.other_id_2=b.Identity;break;case Types.IdentityType.Other3:c.other_id_3=b.Identity;break;case Types.IdentityType.Other4:c.other_id_4=b.Identity;break;case Types.IdentityType.Other5:c.other_id_5=b.Identity;break;case Types.IdentityType.Other6:c.other_id_6=b.Identity;break;case Types.IdentityType.Other7:c.other_id_7=b.Identity;break;case Types.IdentityType.Other8:c.other_id_8=b.Identity;break;case Types.IdentityType.Other9:c.other_id_9=b.Identity;break;case Types.IdentityType.Other10:c.other_id_10=b.Identity;break;case Types.IdentityType.MobileNumber:c.mobile_number=b.Identity;break;case Types.IdentityType.PhoneNumber2:c.phone_number_2=b.Identity;break;case Types.IdentityType.PhoneNumber3:c.phone_number_3=b.Identity;break;}return c}function convertEvent(a){if(!a)return null;switch(a.EventDataType){case Types.MessageType.AppStateTransition:return convertAST(a);case Types.MessageType.Commerce:return convertCommerceEvent(a);case Types.MessageType.CrashReport:return convertCrashReportEvent(a);case Types.MessageType.OptOut:return convertOptOutEvent(a);case Types.MessageType.PageEvent:// Note: Media Events are also sent as PageEvents/CustomEvents
|
|
511
|
-
return convertCustomEvent(a);case Types.MessageType.PageView:return convertPageViewEvent(a);case Types.MessageType.Profile://deprecated and not supported by the web SDK
|
|
512
|
-
return null;case Types.MessageType.SessionEnd:return convertSessionEndEvent(a);case Types.MessageType.SessionStart:return convertSessionStartEvent(a);case Types.MessageType.UserAttributeChange:return convertUserAttributeChangeEvent(a);case Types.MessageType.UserIdentityChange:return convertUserIdentityChangeEvent(a);}return null}function convertProductActionType(a){if(!a)return dist.ProductActionActionEnum.unknown;return a===SDKProductActionType.AddToCart?dist.ProductActionActionEnum.addToCart:a===SDKProductActionType.AddToWishlist?dist.ProductActionActionEnum.addToWishlist:a===SDKProductActionType.Checkout?dist.ProductActionActionEnum.checkout:a===SDKProductActionType.CheckoutOption?dist.ProductActionActionEnum.checkoutOption:a===SDKProductActionType.Click?dist.ProductActionActionEnum.click:a===SDKProductActionType.Purchase?dist.ProductActionActionEnum.purchase:a===SDKProductActionType.Refund?dist.ProductActionActionEnum.refund:a===SDKProductActionType.RemoveFromCart?dist.ProductActionActionEnum.removeFromCart:a===SDKProductActionType.RemoveFromWishlist?dist.ProductActionActionEnum.removeFromWishlist:a===SDKProductActionType.ViewDetail?dist.ProductActionActionEnum.viewDetail:dist.ProductActionActionEnum.unknown}function convertProductAction(a){if(!a.ProductAction)return null;var b={action:convertProductActionType(a.ProductAction.ProductActionType),checkout_step:a.ProductAction.CheckoutStep,checkout_options:a.ProductAction.CheckoutOptions,transaction_id:a.ProductAction.TransactionId,affiliation:a.ProductAction.Affiliation,total_amount:a.ProductAction.TotalAmount,tax_amount:a.ProductAction.TaxAmount,shipping_amount:a.ProductAction.ShippingAmount,coupon_code:a.ProductAction.CouponCode,products:convertProducts(a.ProductAction.ProductList)};return b}function convertProducts(a){if(!a||!a.length)return null;for(var b=[],c=0,d=a;c<d.length;c++){var e=d[c],f={id:e.Sku,name:e.Name,brand:e.Brand,category:e.Category,variant:e.Variant,total_product_amount:e.TotalAmount,position:e.Position,price:e.Price,quantity:e.Quantity,coupon_code:e.CouponCode,custom_attributes:e.Attributes};b.push(f);}return b}function convertPromotionAction(a){if(!a.PromotionAction)return null;var b={action:a.PromotionAction.PromotionActionType,promotions:convertPromotions(a.PromotionAction.PromotionList)};return b}function convertPromotions(a){if(!a||!a.length)return null;for(var b=[],c=0,d=a;c<d.length;c++){var e=d[c],f={id:e.Id,name:e.Name,creative:e.Creative,position:e.Position};b.push(f);}return b}function convertImpressions(a){if(!a.ProductImpressions)return null;for(var b=[],c=0,d=a.ProductImpressions;c<d.length;c++){var e=d[c],f={product_impression_list:e.ProductImpressionList,products:convertProducts(e.ProductList)};b.push(f);}return b}function convertCommerceEvent(a){var b=convertBaseEventData(a),c={custom_flags:a.CustomFlags,product_action:convertProductAction(a),promotion_action:convertPromotionAction(a),product_impressions:convertImpressions(a),currency_code:a.CurrencyCode};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.commerceEvent,data:c}}function convertCrashReportEvent(a){var b=convertBaseEventData(a),c={message:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.crashReport,data:c}}function convertAST(a){var b=convertBaseEventData(a),c=dist.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum,d=c.applicationBackground,e=c.applicationInitialized,f=a.IsBackgroundAST?d:e,g={application_transition_type:f,is_first_run:a.IsFirstRun,is_upgrade:!1,launch_referral:a.LaunchReferral};// Determine the transition type based on IsBackgroundAST flag
|
|
513
|
-
return g=Object.assign(g,b),{event_type:dist.EventTypeEnum.applicationStateTransition,data:g}}function convertSessionEndEvent(a){var b=convertBaseEventData(a),c={session_duration_ms:a.SessionLength//note: External Events DTO does not support the session mpids array as of this time.
|
|
514
|
-
//spanning_mpids: sdkEvent.SessionMpids
|
|
515
|
-
};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.sessionEnd,data:c}}function convertSessionStartEvent(a){var b=convertBaseEventData(a),c={};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.sessionStart,data:c}}function convertPageViewEvent(a){var b=convertBaseEventData(a),c={custom_flags:a.CustomFlags,screen_name:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.screenView,data:c}}function convertOptOutEvent(a){var b=convertBaseEventData(a),c={is_opted_out:a.OptOut};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.optOut,data:c}}function convertCustomEvent(a){var b=convertBaseEventData(a),c={custom_event_type:convertSdkEventType(a.EventCategory),custom_flags:a.CustomFlags,event_name:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.customEvent,data:c}}function convertSdkEventType(a){return a===Types.EventType.Other?dist.CustomEventDataCustomEventTypeEnum.other:a===Types.EventType.Location?dist.CustomEventDataCustomEventTypeEnum.location:a===Types.EventType.Navigation?dist.CustomEventDataCustomEventTypeEnum.navigation:a===Types.EventType.Search?dist.CustomEventDataCustomEventTypeEnum.search:a===Types.EventType.Social?dist.CustomEventDataCustomEventTypeEnum.social:a===Types.EventType.Transaction?dist.CustomEventDataCustomEventTypeEnum.transaction:a===Types.EventType.UserContent?dist.CustomEventDataCustomEventTypeEnum.userContent:a===Types.EventType.UserPreference?dist.CustomEventDataCustomEventTypeEnum.userPreference:a===Types.EventType.Media?dist.CustomEventDataCustomEventTypeEnum.media:a===Types.CommerceEventType.ProductAddToCart?dist.CommerceEventDataCustomEventTypeEnum.addToCart:a===Types.CommerceEventType.ProductAddToWishlist?dist.CommerceEventDataCustomEventTypeEnum.addToWishlist:a===Types.CommerceEventType.ProductCheckout?dist.CommerceEventDataCustomEventTypeEnum.checkout:a===Types.CommerceEventType.ProductCheckoutOption?dist.CommerceEventDataCustomEventTypeEnum.checkoutOption:a===Types.CommerceEventType.ProductClick?dist.CommerceEventDataCustomEventTypeEnum.click:a===Types.CommerceEventType.ProductImpression?dist.CommerceEventDataCustomEventTypeEnum.impression:a===Types.CommerceEventType.ProductPurchase?dist.CommerceEventDataCustomEventTypeEnum.purchase:a===Types.CommerceEventType.ProductRefund?dist.CommerceEventDataCustomEventTypeEnum.refund:a===Types.CommerceEventType.ProductRemoveFromCart?dist.CommerceEventDataCustomEventTypeEnum.removeFromCart:a===Types.CommerceEventType.ProductRemoveFromWishlist?dist.CommerceEventDataCustomEventTypeEnum.removeFromWishlist:a===Types.CommerceEventType.ProductViewDetail?dist.CommerceEventDataCustomEventTypeEnum.viewDetail:a===Types.CommerceEventType.PromotionClick?dist.CommerceEventDataCustomEventTypeEnum.promotionClick:a===Types.CommerceEventType.PromotionView?dist.CommerceEventDataCustomEventTypeEnum.promotionView:dist.CustomEventDataCustomEventTypeEnum.unknown}function convertBaseEventData(a){var b={timestamp_unixtime_ms:a.Timestamp,session_uuid:a.SessionId,session_start_unixtime_ms:a.SessionStartDate,custom_attributes:a.EventAttributes,location:convertSDKLocation(a.Location),source_message_id:a.SourceMessageId,active_time_on_site_ms:a.ActiveTimeOnSite,total_time_on_site_ms:a.TotalTimeOnSite,page_url:a.PageUrl};return b}function convertSDKLocation(a){return a&&Object.keys(a).length?{latitude:a.lat,longitude:a.lng}:null}function convertUserAttributeChangeEvent(a){var b=convertBaseEventData(a),c={user_attribute_name:a.UserAttributeChanges.UserAttributeName,new:a.UserAttributeChanges.New,old:a.UserAttributeChanges.Old,deleted:a.UserAttributeChanges.Deleted,is_new_attribute:a.UserAttributeChanges.IsNewAttribute};return c=__assign(__assign({},c),b),{event_type:dist.EventTypeEnum.userAttributeChange,data:c}}function convertUserIdentityChangeEvent(a){var b=convertBaseEventData(a),c={new:{identity_type:convertUserIdentityTypeToServerIdentityType(a.UserIdentityChanges.New.IdentityType),identity:a.UserIdentityChanges.New.Identity||null,timestamp_unixtime_ms:a.Timestamp,created_this_batch:a.UserIdentityChanges.New.CreatedThisBatch},old:{identity_type:convertUserIdentityTypeToServerIdentityType(a.UserIdentityChanges.Old.IdentityType),identity:a.UserIdentityChanges.Old.Identity||null,timestamp_unixtime_ms:a.Timestamp,created_this_batch:a.UserIdentityChanges.Old.CreatedThisBatch}};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.userIdentityChange,data:c}}function convertUserIdentityTypeToServerIdentityType(a){return a===SDKIdentityTypeEnum.other?dist.IdentityTypeEnum.other:a===SDKIdentityTypeEnum.customerId?dist.IdentityTypeEnum.customerId:a===SDKIdentityTypeEnum.facebook?dist.IdentityTypeEnum.facebook:a===SDKIdentityTypeEnum.twitter?dist.IdentityTypeEnum.twitter:a===SDKIdentityTypeEnum.google?dist.IdentityTypeEnum.google:a===SDKIdentityTypeEnum.microsoft?dist.IdentityTypeEnum.microsoft:a===SDKIdentityTypeEnum.yahoo?dist.IdentityTypeEnum.yahoo:a===SDKIdentityTypeEnum.email?dist.IdentityTypeEnum.email:a===SDKIdentityTypeEnum.alias?dist.IdentityTypeEnum.alias:a===SDKIdentityTypeEnum.facebookCustomAudienceId?dist.IdentityTypeEnum.facebookCustomAudienceId:a===SDKIdentityTypeEnum.otherId2?dist.IdentityTypeEnum.otherId2:a===SDKIdentityTypeEnum.otherId3?dist.IdentityTypeEnum.otherId3:a===SDKIdentityTypeEnum.otherId4?dist.IdentityTypeEnum.otherId4:a===SDKIdentityTypeEnum.otherId5?dist.IdentityTypeEnum.otherId5:a===SDKIdentityTypeEnum.otherId6?dist.IdentityTypeEnum.otherId6:a===SDKIdentityTypeEnum.otherId7?dist.IdentityTypeEnum.otherId7:a===SDKIdentityTypeEnum.otherId8?dist.IdentityTypeEnum.otherId8:a===SDKIdentityTypeEnum.otherId9?dist.IdentityTypeEnum.otherId9:a===SDKIdentityTypeEnum.otherId10?dist.IdentityTypeEnum.otherId10:a===SDKIdentityTypeEnum.mobileNumber?dist.IdentityTypeEnum.mobileNumber:a===SDKIdentityTypeEnum.phoneNumber2?dist.IdentityTypeEnum.phoneNumber2:a===SDKIdentityTypeEnum.phoneNumber3?dist.IdentityTypeEnum.phoneNumber3:void 0}
|
|
516
|
-
|
|
517
|
-
var HISTORY_METHODS=["pushState","replaceState"],WRAPPED_MARKER="__mpApvWrapped__";var supportsHistoryTracking=function(a){return !!a&&a.history!==void 0&&"function"==typeof a.history.pushState&&"function"==typeof a.addEventListener};// Wraps pushState/replaceState so `onNavigate` runs after the real method, and
|
|
518
|
-
// returns the single function that undoes it \u2014 or null when nothing was
|
|
519
|
-
// installed (history is already wrapped, or a frozen/sealed History rejected the
|
|
520
|
-
// assignment). Handing back one undo closure keeps the wrapper and original
|
|
521
|
-
// references out of the tracker entirely: there is no half-patched state for a
|
|
522
|
-
// caller to inspect, and no way to restore the wrong pair.
|
|
523
|
-
var patchHistory=function(a,b){if(window.history.pushState[WRAPPED_MARKER])return b("[patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DETECTED"),null;var c={},d={};HISTORY_METHODS.forEach(function(b){var e=window.history[b];c[b]=e;var f=function(){for(var c=[],d=0;d<arguments.length;d++)c[d]=arguments[d];var f=e.apply(this,c);return a(b),f};Object.defineProperty(f,WRAPPED_MARKER,{value:!0,enumerable:!1}),d[b]=f;});// Restore per method: a third party may have patched one of the two on top of
|
|
524
|
-
// ours after we installed. Clobbering theirs would break their tracking, so
|
|
525
|
-
// leave anything that is no longer ours in place.
|
|
526
|
-
var e=function(){return HISTORY_METHODS.forEach(function(a){window.history[a]===d[a]?(window.history[a]=c[a],b("[teardown] restored original ".concat(a))):b("[teardown] ".concat(a," no longer ours; leaving in place, gating callback to no-op"));})};try{HISTORY_METHODS.forEach(function(a){window.history[a]=d[a];});}catch(a){b("[error] failed to patch history methods (frozen/sealed), rolling back: ".concat(a));try{e();}catch(a){b("[error] failed to restore history methods after patch failure: ".concat(a));}return null}return e};// One History patch for the whole SDK, so page-view tracking and preselection do not
|
|
527
|
-
// stack two wrappers.
|
|
528
|
-
//
|
|
529
|
-
// State lives on `window`, not module scope, because Next.js re-executes the bundle per
|
|
530
|
-
// SPA navigation while the patch from the previous execution stays installed.
|
|
531
|
-
var WIN_ROUTE_MONITOR_KEY="__mpRouteMonitor__";var monitorState=function(){var a=window;return a[WIN_ROUTE_MONITOR_KEY]||(a[WIN_ROUTE_MONITOR_KEY]={listeners:{},undoHistoryPatch:null,popStateListener:null}),a[WIN_ROUTE_MONITOR_KEY]},emit=function(a){Object.values(monitorState().listeners).forEach(function(b){try{b(a);}catch(a){// One subscriber must not stop the others, and must never break navigation.
|
|
532
|
-
}});},install=function(a,b){a.undoHistoryPatch||a.popStateListener||(a.undoHistoryPatch=patchHistory(emit,b),a.popStateListener=function(){return emit("popstate")},window.addEventListener("popstate",a.popStateListener));},uninstall=function(a){a.popStateListener&&(window.removeEventListener("popstate",a.popStateListener),a.popStateListener=null),a.undoHistoryPatch&&(a.undoHistoryPatch(),a.undoHistoryPatch=null);};// Reads the shared state at call time, so a wrapper installed by a previous bundle
|
|
533
|
-
// execution still reaches the current listeners.
|
|
534
|
-
// Installs on the first subscriber and tears down after the last leaves, so a workspace
|
|
535
|
-
// that needs neither is never patched. Unsubscribing only removes the listener while it
|
|
536
|
-
// still owns its key, so an outgoing instance cannot remove its replacement.
|
|
537
|
-
var subscribeToRouteChange=function(a,b,c){if(void 0===c&&(c=function(){}),!supportsHistoryTracking("undefined"==typeof window?null:window))return function(){};var d=monitorState();return d.listeners[a]=b,install(d,c),function(){d.listeners[a]!==b||(delete d.listeners[a],0===Object.keys(d.listeners).length&&uninstall(d));}};
|
|
538
|
-
|
|
539
|
-
// contract: `window.__mpApv__` is what you inspect in a console to see whether
|
|
540
|
-
// tracking is live.
|
|
541
|
-
//
|
|
542
|
-
// It lives on `window` rather than in module scope because Next.js re-executes
|
|
543
|
-
// the SDK bundle on every SPA navigation: module-level state is reset each time,
|
|
544
|
-
// but `window` persists for the lifetime of the tab.
|
|
545
|
-
//
|
|
546
|
-
// One object rather than a key per flag, so resetting is a single reassignment.
|
|
547
|
-
// Nothing has to be deleted, and there is no ordering in which half the state
|
|
548
|
-
// survives the reset.
|
|
549
|
-
var WIN_APV_KEY="__mpApv__";// The query params an auto page view may carry. An allowlist, not a denylist:
|
|
550
|
-
// partner URLs routinely hold order ids, email addresses and session tokens, and
|
|
551
|
-
// none of those should reach the event stream because someone forgot to exclude
|
|
552
|
-
// them. Anything absent from this list is dropped.
|
|
553
|
-
//
|
|
554
|
-
// SECURITY: `code`, `state` and `nonce` are the OAuth 2.0 / OIDC authorization
|
|
555
|
-
// code and the CSRF/replay tokens. They are credentials until redeemed, and
|
|
556
|
-
// attaching them here persists them in the event store and forwards them to
|
|
557
|
-
// every configured kit. They are on the list by explicit product decision \u2014
|
|
558
|
-
// deleting that line is the whole of the fix if that decision is revisited.
|
|
559
|
-
var ALLOWED_QUERY_PARAMS=[// Campaign attribution
|
|
560
|
-
"utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","utm_source_platform","utm_creative_format","utm_marketing_tactic","gad_source","gad_campaignid","mc_cid",// Ad-network click ids
|
|
561
|
-
"gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","dclid","srsltid","epik","ScCid","irclickid","rtid","rclid",// OAuth / OIDC \u2014 see the SECURITY note above
|
|
562
|
-
"client_id","redirect_uri","response_type","scope","state","code","nonce",// Pagination
|
|
563
|
-
"page","limit","offset","cursor","per_page",// Site search term, as the common platforms spell it. Matching is
|
|
564
|
-
// case-insensitive. `s` is WordPress and WooCommerce search; other
|
|
565
|
-
// single-letter names are too generic. `oq` is a storefront search term.
|
|
566
|
-
"q","s","oq","search","query","keyword","keywords","term","text","searchTerm","searchText","search_query","search_text","Ntt",// Product and variant identifiers. `cid` is not a category: it is a
|
|
567
|
-
// customer id on many sites.
|
|
568
|
-
"pid","productId","sku","skuId","variant","color","colour","size",// Category
|
|
569
|
-
"category",// Referral
|
|
570
|
-
"ref","referrer"];// Params matched by name prefix, for platforms that put a per-product id in the
|
|
571
|
-
// name. Salesforce Commerce Cloud spells a variant choice
|
|
572
|
-
// `dwvar_<productId>_<attribute>`, e.g. `dwvar_12345_color=navy`.
|
|
573
|
-
var ALLOWED_QUERY_PARAM_PREFIXES=["dwvar_"];var hasAllowedPrefix=function(a){return ALLOWED_QUERY_PARAM_PREFIXES.some(function(b){return 0===a.indexOf(b)})},ALLOWED_QUERY_PARAMS_LOWER=ALLOWED_QUERY_PARAMS.map(function(a){return a.toLowerCase()});// Whether a query param name, in any case, is one an auto page view captures.
|
|
574
|
-
var isAllowedQueryParam=function(a){var b=a.toLowerCase();return -1!==ALLOWED_QUERY_PARAMS_LOWER.indexOf(b)||hasAllowedPrefix(b)};// ---------------------------------------------------------------------------
|
|
575
|
-
// Pure helpers. No `this`, no globals, no side effects \u2014 callable and assertable
|
|
576
|
-
// on their own, which is where the interesting rules live.
|
|
577
|
-
// ---------------------------------------------------------------------------
|
|
578
|
-
// Pulls the allowlisted query params off a URL. Delegates to the SDK's own
|
|
579
|
-
// parser, which lowercases keys (so `?UTM_Source=` and `?utm_source=` land on one
|
|
580
|
-
// attribute), drops empty values, and carries the fallback for browsers without
|
|
581
|
-
// URLSearchParams. Tolerates an empty href, so SSR yields no params rather than
|
|
582
|
-
// throwing.
|
|
583
|
-
var allowedQueryParams=function(a){var b=queryStringParser(a,ALLOWED_QUERY_PARAMS),c=queryStringParser(a);return Object.keys(c).filter(function(a){return hasAllowedPrefix(a)&&c[a]}).forEach(function(a){b[a]=c[a];}),b};var AUTO_PAGE_VIEW_ATTRIBUTE="is_auto_page_view";// Absent rather than false on a manual page view, so the attribute is only ever
|
|
584
|
-
// added by the automatic emitters. Shared by both of them so the key and that
|
|
585
|
-
// rule have one definition instead of two that can drift.
|
|
586
|
-
var autoPageViewAttribute=function(a){var b;return a?(b={},b[AUTO_PAGE_VIEW_ATTRIBUTE]=!0,b):{}};// The captured params, in allowlist order, then prefix-matched names sorted.
|
|
587
|
-
// Neither depends on the object's insertion order, so reordering the query
|
|
588
|
-
// string cannot produce a different key.
|
|
589
|
-
//
|
|
590
|
-
// Membership is an own-property check, not `in`. `in` walks the prototype
|
|
591
|
-
// chain, so a name matching an Object.prototype member reports as present on
|
|
592
|
-
// any plain object. ALLOWED_QUERY_PARAMS contains no such name, which was the
|
|
593
|
-
// only thing making `in` safe here \u2014 and it stops being a safe assumption the
|
|
594
|
-
// moment this list can be extended from configuration.
|
|
595
|
-
var capturedNames=function(a){return ALLOWED_QUERY_PARAMS.filter(function(b){return hasOwnProp(a,b)}).concat(Object.keys(a).filter(hasAllowedPrefix).sort())};// The dedup key: pathname plus the allowlisted params in a fixed order, so that
|
|
596
|
-
// reordering the query string is not a new page. Params outside the allowlist
|
|
597
|
-
// never make it into `page.params` and so cannot key a view \u2014 nor can the hash.
|
|
598
|
-
//
|
|
599
|
-
// Values are re-encoded because queryStringParser hands them back DECODED. A
|
|
600
|
-
// value holding the pair delimiters would otherwise serialize exactly like two
|
|
601
|
-
// separate params \u2014 `{q: 'a&search=b'}` and `{q: 'a', search: 'b'}` both becoming
|
|
602
|
-
// `q=a&search=b` \u2014 and dedup would treat a real navigation between them as the
|
|
603
|
-
// same page and drop the view. `q`, `search` and `redirect_uri` carry `&` and `=`
|
|
604
|
-
// routinely, so this is reachable rather than theoretical.
|
|
605
|
-
var pageKey=function(a){var b=capturedNames(a.params).map(function(b){return "".concat(b,"=").concat(encodeURIComponent(a.params[b]))}).join("&");return b?"".concat(a.path,"?").concat(b):a.path};// Dedup keys on the pageKey above: a change to any captured param is a new page
|
|
606
|
-
// (`?page=2` is a distinct pagination view), while a hash-only change, or a
|
|
607
|
-
// change confined to params we do not capture, is the same page.
|
|
608
|
-
var isNewPage=function(a,b){return b!==a};// Mirrors the event shape of the public mParticle.logPageView(), but carries the
|
|
609
|
-
// path and query params captured when the navigation was accepted rather than the
|
|
610
|
-
// live location.
|
|
611
|
-
var buildPageViewEvent=function(a){var b=a.params,c=a.hostname,d=a.title,e=a.path,f=a.isAutoPageView;return {messageType:MessageType$1.PageView,name:"PageView",// Params spread first, then the core fields by name, so a core field always
|
|
612
|
-
// wins. No allowlist entry collides with hostname/title/path today; naming
|
|
613
|
-
// them here is what keeps a later addition from silently overwriting one.
|
|
614
|
-
data:__assign(__assign(__assign({},b),{hostname:c,title:d,path:e}),autoPageViewAttribute(f)),eventType:EventType.Unknown}};// ---------------------------------------------------------------------------
|
|
615
|
-
// Window-scoped APV state. Every read and write goes through these helpers, so
|
|
616
|
-
// neither the tracker nor mp-instance touches `window` directly and
|
|
617
|
-
// `typeof window` is checked in exactly one place.
|
|
618
|
-
// ---------------------------------------------------------------------------
|
|
619
|
-
var apvWindow=function(){return "undefined"==typeof window?null:window},freshState=function(){return {initialPageViewFired:!1}},readState=function(){var a=apvWindow();return a?a[WIN_APV_KEY]:void 0},writeState=function(){var a=apvWindow();return a?(a[WIN_APV_KEY]||(a[WIN_APV_KEY]=freshState()),a[WIN_APV_KEY]):null};// Reads tolerate absent state, so a read never mutates `window`. Only the
|
|
620
|
-
// writers below create it.
|
|
621
|
-
var getActiveTracker=function(){var a=readState();return a?a.tracker:void 0};var hasInitialPageViewFired=function(){var a=readState();return !!(a&&a.initialPageViewFired)};var markInitialPageViewFired=function(){var a=writeState();a&&(a.initialPageViewFired=!0);};// Returns the page to its pre-APV state: stops the active tracker (restoring the
|
|
622
|
-
// history methods it patched), then swaps in fresh state. The state object is the
|
|
623
|
-
// authoritative handle, so this reaches trackers whose owning module is gone.
|
|
624
|
-
var resetPageViewTracking=function(){var a=apvWindow();if(a){var b=getActiveTracker();b&&b.teardown(),a[WIN_APV_KEY]=freshState();}};var setActiveTracker=function(a){var b=writeState();b&&(b.tracker=a);},clearActiveTracker=function(a){var b=readState();b&&b.tracker===a&&(b.tracker=void 0);},currentPage=function(){return {path:window.location.pathname,params:allowedQueryParams(getHref())}},describePage=function(a){if(!a)return "";var b=capturedNames(a.params);return b.length?"".concat(a.path," (params: ").concat(b.join(),")"):a.path},PageViewTracker=/** @class */function(){function a(a,b){this.lastPage=null,this.active=!1,this.pendingNavigations=[],this.undoHistoryPatch=null,this.mpInstance=a,this.isAutoPageView=!!(b&&b.isAutoPageView);}return Object.defineProperty(a.prototype,"isActive",{// True while this tracker owns the history patch and is listening for
|
|
625
|
-
// navigations. Flips to false on teardown, including the teardown a
|
|
626
|
-
// successor tracker performs during a handoff. Read-only, and the one thing
|
|
627
|
-
// worth checking on `window.__mpApv__.tracker` from a console.
|
|
628
|
-
get:function get(){return this.active},enumerable:!1,configurable:!0}),a.prototype.init=function(){var a=this;if(this.log("[init] PageViewTracker Init"),!supportsHistoryTracking(apvWindow()))return void this.log("[init] unsupported environment (no History API), not starting");// Take over from whichever tracker is currently active: one left behind by
|
|
629
|
-
// a previous module load, or this same tracker on a repeat
|
|
630
|
-
// mParticle.init(). Their pending navigations are transferred rather than
|
|
631
|
-
// dropped \u2014 a route change may have queued a deferred fire that has not
|
|
632
|
-
// flushed yet, and dropping it loses a page view entirely.
|
|
633
|
-
var b=getActiveTracker(),c=this.retire(b);this.active&&b!==this&&(c=c.concat(this.retire(this))),this.active=!0,this.lastPage=currentPage(),this.log("[init] seeded lastPage: ".concat(describePage(this.lastPage))),this.undoHistoryPatch=subscribeToRouteChange("pageView",function(b){return a.safeHandleNavigation(b)},function(b){return a.log(b)}),setActiveTracker(this),this.log("[init] patched pushState/replaceState + listening for popstate"),c.forEach(function(b){return a.scheduleFire(b)});},a.prototype.teardown=function(){this.takePendingNavigations(),this.undoHistoryPatch&&(this.undoHistoryPatch(),this.undoHistoryPatch=null),this.active=!1,clearActiveTracker(this);},a.prototype.retire=function(a){if(!a)return [];this.log(a===this?"[init] retiring this tracker for a repeat mParticle.init() \u2014 transferring pending navigations and tearing down":"[init] retiring a tracker from a previous module load \u2014 transferring pending navigations and tearing down");var b=a.takePendingNavigations();return a.teardown(),b},a.prototype.takePendingNavigations=function(){var a=this.pendingNavigations;return this.pendingNavigations=[],a.forEach(function(a){var b=a.timeoutId;return clearTimeout(b)}),a.map(function(a){var b=a.page;return b})},a.prototype.safeHandleNavigation=function(a){// An orphaned wrapper still calls in: teardown can only restore a history
|
|
634
|
-
// method that is still ours, so one a third party patched over stays
|
|
635
|
-
// installed and keeps firing at a dead tracker. Bail before touching
|
|
636
|
-
// lastPath or queueing a fire the flush would just abort. Guarding here
|
|
637
|
-
// rather than at each wrapper also covers the popstate path.
|
|
638
|
-
if(this.active)try{this.handleNavigation(a);}catch(b){this.log("[error] navigation handler threw (".concat(a,"), page view skipped: ").concat(b));}},a.prototype.handleNavigation=function(a){var b=currentPage(),c=this.lastPage?pageKey(this.lastPage):null;return this.log("[detect] navigation signal (source: ".concat(a,", candidate: ").concat(describePage(b),", last: ").concat(describePage(this.lastPage),")")),isNewPage(c,pageKey(b))?void(this.log("[accept] page changed, scheduling fire (source: ".concat(a,", from: ").concat(describePage(this.lastPage),", to: ").concat(describePage(b),")")),this.lastPage=b,this.scheduleFire(b)):void this.log("[dedupe] page unchanged, skipping (source: ".concat(a,", page: ").concat(describePage(b),")"))},a.prototype.scheduleFire=function(a){var b=this,c=setTimeout(function(){return b.pendingNavigations=b.pendingNavigations.filter(function(a){return a.timeoutId!==c}),b.active?void(b.mpInstance._SessionManager.resetSessionTimer(),b.firePageView(a)):void b.log("[defer] fire aborted, tracker inactive (torn down before flush)")},0);this.pendingNavigations.push({page:a,timeoutId:c});},a.prototype.firePageView=function(a){var b=window.document.title,c=buildPageViewEvent(__assign(__assign({},a),{hostname:window.location.hostname,title:b,isAutoPageView:this.isAutoPageView}));this.log("[fire] deferred flush -> _Events.logEvent(PageView) (page: ".concat(describePage(a),", title: ").concat(b,")")),this.mpInstance._Events.logEvent(c);},a.prototype.log=function(a){this.mpInstance.Logger.verbose("mParticle APV: ".concat(a));},a}();// Log-safe description of a page: the path, plus the NAMES of the captured
|
|
639
|
-
|
|
640
|
-
// `mParticle._cleanUrl`. `path` keeps scheme, host and path. `full` adds the
|
|
641
|
-
// query params an auto page view may capture, then the fragment.
|
|
642
|
-
var UrlMode={Path:"path",Full:"full"};// OAuth 2.0 / OIDC authorization-flow params. They stay off URLs even where the
|
|
643
|
-
// page view allowlist admits them, because a URL travels on every event.
|
|
644
|
-
var EXCLUDED_URL_QUERY_PARAMS=["client_id","redirect_uri","response_type","scope","state","code","nonce"];// An OAuth implicit or OIDC fragment response puts its tokens in `#k=v&...`.
|
|
645
|
-
var EXCLUDED_URL_FRAGMENT_PARAMS=EXCLUDED_URL_QUERY_PARAMS.concat(["access_token","id_token","refresh_token","provider_token","provider_refresh_token"]);// Allowlisted params whose value is itself a URL, so it can carry a query.
|
|
646
|
-
var URL_VALUED_QUERY_PARAMS=["ref","referrer"],USERINFO=/^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/]*@/i,decodeQueryComponent=function(a){return decodeURIComponent(a.replace(/\+/g," "))},cleanQueryPair=function(a){var b,c=a.indexOf("="),d=-1===c?a:a.slice(0,c);try{b=decodeQueryComponent(d);}catch(a){return null}var e=b.toLowerCase();if(!b||!isAllowedQueryParam(b)||-1!==EXCLUDED_URL_QUERY_PARAMS.indexOf(e))return null;if(-1===c||-1===URL_VALUED_QUERY_PARAMS.indexOf(e))return a;var f;try{f=decodeQueryComponent(a.slice(c+1));}catch(a){return null}var g=cleanUrl(f,UrlMode.Path);return g===f?a:"".concat(d,"=").concat(encodeURIComponent(g))},cleanQuery=function(a){return a.split("&").map(cleanQueryPair).filter(function(a){return null!==a}).join("&")},keepsFragmentPair=function(a){try{var b=decodeQueryComponent(a.split("=")[0]);return -1===EXCLUDED_URL_FRAGMENT_PARAMS.indexOf(b.toLowerCase())}catch(a){return !1}},cleanFragment=function(a){var b=a.indexOf("?"),c=-1===b?a:a.slice(0,b),d=/^#[/!]/.test(a)||-1!==b&&-1===c.indexOf("=");if(d&&-1!==b){var e=cleanQuery(a.slice(b+1));return c+(e?"?".concat(e):"")}if(-1===a.indexOf("="))return a;var f=a.slice(1).split("&").filter(keepsFragmentPair).join("&");return f?"#".concat(f):""};// A hash route (`#/...`, `#!...`, or a path with no `=` before its `?`) keeps
|
|
647
|
-
// its path; a query inside it gets the same allowlist as the URL's own query.
|
|
648
|
-
// A fragment of bare pairs loses the OAuth/OIDC ones.
|
|
649
|
-
// String-based rather than `new URL`, so kept pairs and the fragment go out
|
|
650
|
-
// exactly as the browser reported them and no environment can parse differently.
|
|
651
|
-
// An unknown mode is treated as `path`.
|
|
652
|
-
var cleanUrl=function(a,b){if("string"!=typeof a||!a)return "";var c=a.indexOf("#"),d=-1===c?"":a.slice(c),e=-1===c?a:a.slice(0,c),f=e.indexOf("?"),g=(-1===f?e:e.slice(0,f)).replace(USERINFO,"$1");if(b!==UrlMode.Full)return g;var h=-1===f?"":cleanQuery(e.slice(f+1));return g+(h?"?".concat(h):"")+cleanFragment(d)};// The current page as it may appear on an event.
|
|
653
|
-
var cleanPageHref=function(){return cleanUrl(getHref(),UrlMode.Full)};
|
|
654
|
-
|
|
655
|
-
// `Unavailable` covers storage being blocked/disabled (e.g. SecurityError),
|
|
656
|
-
// where retrying with a smaller payload cannot succeed.
|
|
657
|
-
var StorageResult;(function(a){a.Success="Success",a.QuotaExceeded="QuotaExceeded",a.Unavailable="Unavailable";})(StorageResult||(StorageResult={}));var isQuotaExceededError=function(a){return a instanceof DOMException&&(// Standard quota errors, plus Firefox's legacy name/code.
|
|
658
|
-
22===a.code||1014===a.code||"QuotaExceededError"===a.name||"NS_ERROR_DOM_QUOTA_REACHED"===a.name)},BaseVault=/** @class */function(){/**
|
|
659
|
-
*
|
|
660
|
-
* @param {string} storageKey the local storage key string
|
|
661
|
-
* @param {Storage} storageObject Web API Storage object that is being used
|
|
662
|
-
*/function a(a,b){this._storageKey=a,this.storageObject=b,this.contents=this.retrieve();}/**
|
|
663
|
-
* Stores a StorableItem to Storage
|
|
664
|
-
* @method store
|
|
665
|
-
* @param item {StorableItem}
|
|
666
|
-
*/return a.prototype.store=function(a){var b;try{return b=isNumber(a)||!isEmpty(a)?JSON.stringify(a):"",this.storageObject.setItem(this._storageKey,b),this.contents=a,StorageResult.Success}catch(a){return isQuotaExceededError(a)?StorageResult.QuotaExceeded:StorageResult.Unavailable}},a.prototype.retrieve=function(){// https://go.mparticle.com/work/SQDSDKS-5022
|
|
667
|
-
try{var a=this.storageObject.getItem(this._storageKey);this.contents=a?JSON.parse(a):null;}catch(a){this.contents=null;}return this.contents},a.prototype.purge=function(){this.contents=null;try{this.storageObject.removeItem(this._storageKey);}catch(a){// Storage persistence is best effort.
|
|
668
|
-
}},a}();var LocalStorageVault=/** @class */function(a){function b(b){return a.call(this,b,window.localStorage)||this}return __extends(b,a),b}(BaseVault);var SessionStorageVault=/** @class */function(a){function b(b){return a.call(this,b,window.sessionStorage)||this}return __extends(b,a),b}(BaseVault);var DisabledVault=/** @class */function(a){function b(b){var c=a.call(this,b,window.localStorage)||this;return c.contents=null,c.storageObject.removeItem(c._storageKey),c}return __extends(b,a),b.prototype.store=function(){return this.contents=null,StorageResult.Success},b.prototype.retrieve=function(){return this.contents},b.prototype.purge=function(){this.contents=null;},b}(BaseVault);
|
|
669
|
-
|
|
670
|
-
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body,a.method,a.headers)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b,c,d){return void 0===c&&(c="post"),void 0===d&&(d={}),__awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(){return e=new XMLHttpRequest,[2/*return*/,new Promise(function(f,g){for(var h in e.onreadystatechange=function(){4!==e.readyState||// Process the response
|
|
671
|
-
// We resolve all xhr responses whose ready state is 4 regardless of HTTP codes that may be errors (400+)
|
|
672
|
-
// because these are valid HTTP responses.
|
|
673
|
-
f(e);},e.onerror=function(){g(e);},e.open(c,a),d)d.hasOwnProperty(h)&&e.setRequestHeader(h,d[h]);e.send(b);})]})})},b}(AsyncUploader);
|
|
674
|
-
|
|
675
|
-
function hasMPIDAndUserLoginChanged(a,b){return !a||b.getMPID()!==a.getMPID()||a.isLoggedIn()!==b.isLoggedIn()}// https://go.mparticle.com/work/SQDSDKS-6504
|
|
676
|
-
function hasMPIDChanged(a,b){return !a||a.getMPID()&&b.mpid&&b.mpid!==a.getMPID()}// https://go.mparticle.com/work/SQDSDKS-7136
|
|
677
|
-
function appendUserInfo(a,b){if(b){if(!a)return b.MPID=null,b.ConsentState=null,b.UserAttributes=null,void(b.UserIdentities=null);if(!(b.MPID&&b.MPID===a.getMPID())){b.MPID=a.getMPID(),b.ConsentState=a.getConsentState(),b.UserAttributes=a.getAllUserAttributes();var c=a.getUserIdentities().userIdentities,d={};for(var e in c){var f=Types.IdentityType.getIdentityType(e);!1!==f&&(d[f]=c[e]);}var g=[];if(isObject(d)&&Object.keys(d).length)for(var h in d){var i={};i.Identity=d[h],i.Type=parseNumber(h),g.push(i);}b.UserIdentities=g;}}}
|
|
678
|
-
|
|
679
|
-
/**
|
|
680
|
-
* BatchUploader contains all the logic to store/retrieve events and batches
|
|
681
|
-
* to/from persistence, and upload batches to mParticle.
|
|
682
|
-
* It queues events as they come in, storing them in persistence, then at set
|
|
683
|
-
* intervals turns them into batches and transfers between event and batch
|
|
684
|
-
* persistence.
|
|
685
|
-
* It then attempts to upload them to mParticle, purging batch persistence if
|
|
686
|
-
* the upload is successful
|
|
687
|
-
*
|
|
688
|
-
* These uploads happen on an interval basis using window.fetch or XHR
|
|
689
|
-
* requests, depending on what is available in the browser.
|
|
690
|
-
*
|
|
691
|
-
* Uploads can also be triggered on browser visibility/focus changes via an
|
|
692
|
-
* event listener, which then uploads to mPartice via the browser's Beacon API.
|
|
693
|
-
*/var BatchUploader=/** @class */function(){/**
|
|
694
|
-
* Creates an instance of a BatchUploader
|
|
695
|
-
* @param {IMParticleWebSDKInstance} mpInstance - the mParticle SDK instance
|
|
696
|
-
* @param {number} uploadInterval - the desired upload interval in milliseconds
|
|
697
|
-
*/function a(b,c){var d,e,f;this.offlineStorageEnabled=!1,this.lastASTEventTime=0,this.AST_DEBOUNCE_MS=1e3,this.uploadIntervalTimerId=null,this.exitHandler=null,this.visibilityChangeHandler=null,this.destroyed=!1,this.batchOrder=new Map,this.nextBatchOrder=0,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable();// When noFunctional is true, prevent events/batches storage
|
|
698
|
-
var g=null===(e=b._CookieConsentManager)||void 0===e?void 0:e.getNoFunctional();this.offlineStorageEnabled&&!g&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events")),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches")),(d=this.eventsQueuedForProcessing).push.apply(d,null!==(f=this.eventVault.retrieve())&&void 0!==f?f:[]));var h=this.mpInstance._Store,i=h.SDKConfig,j=h.devToken,k=this.mpInstance._Helpers.createServiceUrl(i.v3SecureServiceUrl,j);this.uploadUrl="".concat(k,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}/**
|
|
699
|
-
* Cleans up timers and event listeners to prevent leaks when the SDK
|
|
700
|
-
* is re-initialized (e.g. between tests or on repeated init calls).
|
|
701
|
-
*/return a.prototype.destroy=function(){this.destroyed=!0,null!==this.uploadIntervalTimerId&&(clearTimeout(this.uploadIntervalTimerId),this.uploadIntervalTimerId=null),this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.exitHandler&&(window.removeEventListener("beforeunload",this.exitHandler),window.removeEventListener("pagehide",this.exitHandler)),this.exitHandler=null,this.visibilityChangeHandler=null;},a.prototype.isOfflineStorageAvailable=function(){var a=this.mpInstance,b=a._Helpers.getFeatureFlag,c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);// https://go.mparticle.com/work/SQDSDKS-6317
|
|
702
|
-
// TODO: Handle cases where Local Storage is unavailable
|
|
703
|
-
// Potentially shared between Vault and Persistence as well
|
|
704
|
-
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
705
|
-
return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a,b=Date.now(),c=this.mpInstance,d=c._Store,e=c.Identity,f=c._timeOnSiteTimer,g=c._Helpers,h=d.sessionId,i=d.deviceId,j=d.sessionStartDate,k=d.SDKConfig,l=g.generateUniqueId,m=g.getFeatureFlag,n=e.getCurrentUser,o={AppName:k.appName,AppVersion:k.appVersion,Package:k["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:b,SessionId:h,DeviceId:i,IsFirstRun:!1,SourceMessageId:l(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===j||void 0===j?void 0:j.getTime())||b,Debug:k.isDevelopmentMode,ActiveTimeOnSite:(null===f||void 0===f?void 0:f.getTimeInForeground())||0,TotalTimeOnSite:(null===(a=d.getTotalTimeOnSite)||void 0===a?void 0:a.call(d))||0,PageUrl:cleanPageHref()||null,IsBackgroundAST:!0},p=__assign({},o.CustomFlags),q=d.integrationAttributes;// https://go.mparticle.com/work/SQDSDKS-5053
|
|
706
|
-
if(isIntegrationCaptureEnabled(m)){this.mpInstance._IntegrationCapture.capture();var r=this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();p=__assign(__assign({},r),p);var s=this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();q=__assign(__assign({},s),q);}return o.CustomFlags=p,o.IntegrationAttributes=q,appendUserInfo(n(),o),o},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
|
|
707
|
-
var c=a.mpInstance._Helpers.getFeatureFlag,d=Constants.FeatureFlags.AstBackgroundEvents;if(c(d)){if(b.shouldDebounceAndUpdateLastASTTime())return;// Add application state transition event to queue
|
|
708
|
-
var e=b.createBackgroundASTEvent();b.queueEvent(e);}// Then trigger the upload with beacon
|
|
709
|
-
b.prepareAndUpload(!1,b.isBeaconAvailable());};this.exitHandler=c,this.visibilityChangeHandler=function(){"hidden"===document.visibilityState&&c();},document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.addEventListener("beforeunload",c),window.addEventListener("pagehide",c);},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),this.uploadIntervalTimerId=setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){if(!isEmpty(a)){if(this.eventsQueuedForProcessing.push(a),this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store(this.eventsQueuedForProcessing),this.mpInstance.Logger.isVerbose()){var b=obfuscateDevData(a,this.mpInstance._Store.SDKConfig.isDevelopmentMode);this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(b))),this.mpInstance.Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length));}this.shouldTriggerImmediateUpload(a.EventDataType)&&this.prepareAndUpload(!1,!1);}},a.prototype.shouldTriggerImmediateUpload=function(a){var b=[MessageType$1.Commerce,MessageType$1.UserIdentityChange];return !this.batchingEnabled||b.includes(a)},(a.createNewBatches=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
|
|
710
|
-
for(var d,e=[],f=new Map,g=0,h=a;g<h.length;g++){//on initial startup, there may be events logged without an mpid.
|
|
711
|
-
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){var d;return void 0===b&&(b=!1),void 0===c&&(c=!1),__awaiter(this,void 0,void 0,function(){var e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return e=this.mpInstance.Identity.getCurrentUser(),f=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),g=[],isEmpty(f)||(g=a.createNewBatches(f,e,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((k=this.batchesQueuedForProcessing).unshift.apply(k,null!==(d=this.batchVault.retrieve())&&void 0!==d?d:[]),this.batchVault.purge()),isEmpty(g)||(l=this.batchesQueuedForProcessing).push.apply(l,g),h=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],h.forEach(function(a){n.batchOrder.has(a.source_request_id)||n.batchOrder.set(a.source_request_id,n.nextBatchOrder++);}),[4/*yield*/,this.uploadBatches(h,c)];case 1:return i=o.sent(),j=(i||[]).map(function(a){return a.source_request_id}),h.forEach(function(a){-1===j.indexOf(a.source_request_id)&&n.batchOrder["delete"](a.source_request_id);}),isEmpty(i)||(m=this.batchesQueuedForProcessing).unshift.apply(m,i),!c&&this.offlineStorageEnabled&&this.batchVault&&this.storeBatchesQueuedForProcessing(),b&&!this.destroyed&&this.triggerUploadInterval(b,!1),[2/*return*/]}})})},a.prototype.storeBatchesQueuedForProcessing=function(){var a,b=this,c=function(a){var c;return null!==(c=b.batchOrder.get(a.source_request_id))&&void 0!==c?c:-1},d=__spreadArray(__spreadArray([],this.batchesQueuedForProcessing,!0),null!==(a=this.batchVault.retrieve())&&void 0!==a?a:[],!0).sort(function(d,a){var b,e;return c(d)-c(a)||(null!==(b=d.timestamp_unixtime_ms)&&void 0!==b?b:0)-(null!==(e=a.timestamp_unixtime_ms)&&void 0!==e?e:0)});// Another upload may have stored its failed batches while this one was
|
|
712
|
-
// in flight. Merge them in creation order, whichever upload finished
|
|
713
|
-
// first, so they are not overwritten and quota trimming drops the oldest.
|
|
714
|
-
// Nothing to persist: reset offline storage to an empty state.
|
|
715
|
-
if(isEmpty(d))return this.batchVault.store([]),void(this.batchesQueuedForProcessing=[]);// Drop oldest batches until storage accepts the payload. Only quota
|
|
716
|
-
// failures are recoverable by trimming; if storage is unavailable,
|
|
717
|
-
// dropping batches won't help, so retain them in memory.
|
|
718
|
-
for(var e,f=0;f<d.length;f++){if(e=this.batchVault.store(d.slice(f)),e===StorageResult.Success)return this.logDroppedOfflineBatches(f),void(this.batchesQueuedForProcessing=[]);if(e===StorageResult.Unavailable)return void this.mpInstance.Logger.warning("Offline batch storage is unavailable. Retaining batches in memory.")}// Every attempt stayed over quota, even down to the newest batch.
|
|
719
|
-
// Retain them in memory rather than dropping everything.
|
|
720
|
-
this.mpInstance.Logger.warning("Offline batch storage is over quota. Retaining batches in memory.");},a.prototype.logDroppedOfflineBatches=function(a){0<a&&this.mpInstance.Logger.warning("Offline batch storage is over quota. Dropped "+"".concat(a," oldest batch(es)."));},a.prototype.uploadBatches=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,j,k;return __generator(this,function(i){switch(i.label){case 0:if(d=b.filter(function(a){return !isEmpty(a.events)}),isEmpty(d))return [2/*return*/,null];this.mpInstance.Logger.isVerbose()&&(e=obfuscateDevData(d,this.mpInstance._Store.SDKConfig.isDevelopmentMode),this.mpInstance.Logger.verbose("Uploading batches: ".concat(JSON.stringify(e))),this.mpInstance.Logger.verbose("Batch count: ".concat(d.length))),f=0,i.label=1;case 1:return f<d.length?(g={method:"POST",headers:{Accept:a.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(d[f])},!(c&&this.isBeaconAvailable()))?[3/*break*/,2]:(h=new Blob([g.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,h),[3/*break*/,5]):[3/*break*/,6];case 2:return i.trys.push([2,4,,5]),[4/*yield*/,this.uploader.upload(g)];case 3:if(j=i.sent(),200<=j.status&&300>j.status)this.mpInstance.Logger.verbose("Upload success for request ID: ".concat(d[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later
|
|
721
|
-
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," received")),[2/*return*/,d.slice(f,d.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
722
|
-
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,d.slice(f,d.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}();
|
|
723
|
-
|
|
724
|
-
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"};
|
|
725
|
-
|
|
726
|
-
var Modify$4=Constants.IdentityMethods.Modify,Validators={// From ./utils
|
|
727
|
-
// Utility Functions for backwards compatability
|
|
728
|
-
isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,// Validator Functions
|
|
729
|
-
isValidAttributeValue:isValidAttributeValue,// Validator Functions
|
|
730
|
-
// Neither null nor undefined can be a valid Key
|
|
731
|
-
isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},removeFalsyIdentityValues:function removeFalsyIdentityValues(a,b){if(!a||!a.userIdentities)return a;var c={},d=__assign({},a.userIdentities);for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){var f=a.userIdentities[e];// Check if value is falsy (undefined, false, 0, '', etc.) but not null
|
|
732
|
-
null===f||f||(b.warning("Identity value for '".concat(e,"' is falsy (").concat(f,"). This value will be removed from the request.")),delete d[e]);}return c.userIdentities=d,c},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if(b===Modify$4&&(isObject(a.userIdentities)&&!Object.keys(a.userIdentities).length||!isObject(a.userIdentities)))return {valid:!1,error:Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent};for(var d in a)if(a.hasOwnProperty(d)){if(!c[d])return {valid:!1,error:Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey};if("onUserAlias"===d&&!Validators.isFunction(a[d]))return {valid:!1,error:Constants.Messages.ValidationMessages.OnUserAliasType}}if(0===Object.keys(a).length)return {valid:!0};// identityApiData.userIdentities can't be undefined
|
|
733
|
-
if(void 0===a.userIdentities)return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
|
|
734
|
-
if(null!==a.userIdentities&&!isObject(a.userIdentities))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};if(isObject(a.userIdentities)&&Object.keys(a.userIdentities).length)for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){if(!1===Types.IdentityType.getIdentityType(e))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey};if("string"!=typeof a.userIdentities[e]&&null!==a.userIdentities[e])return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues}}}return {valid:!0}}};
|
|
735
|
-
|
|
736
|
-
var HTTPCodes$4=Constants.HTTPCodes;/**
|
|
737
|
-
* Sends a POST to mParticle's IDSync Search endpoint and invokes `callback`
|
|
738
|
-
* with the HTTP status and parsed body.
|
|
739
|
-
*
|
|
740
|
-
* Defensive contract:
|
|
741
|
-
* - No identifier with a non-empty string value -> callback with
|
|
742
|
-
* `{ httpCode: noHttpCoverage }`, no network call.
|
|
743
|
-
* - Missing `apiKey` -> callback with `{ httpCode: noHttpCoverage }`,
|
|
744
|
-
* no network call.
|
|
745
|
-
* - Network/JSON-parse errors are caught and surfaced via the callback,
|
|
746
|
-
* never thrown. Network errors are also reported through the optional
|
|
747
|
-
* `errorReporter` so any registered IErrorReportingService can observe
|
|
748
|
-
* them (matches the pattern used by identifyRequest in identityApiClient).
|
|
749
|
-
*/var sendSearchRequest=function(a,b,c,d,e,f,g,h){return __awaiter(void 0,void 0,void 0,function(){var i,j,k,l,m,n,o,p,r,s,t,u;return __generator(this,function(v){switch(v.label){case 0:// Validate the callback up front. If it isn't a function we have nowhere
|
|
750
|
-
// to deliver a result to, so log and bail out without invoking anything.
|
|
751
|
-
if(!isFunction(e))return f.error("search called without a callback function; skipping request."),[2/*return*/];// No usable identifier -> deliver httpCode: noHttpCoverage so callers
|
|
752
|
-
// waiting on the callback (e.g. to clear a loading state) don't hang.
|
|
753
|
-
if(i=function(a){try{e(a);}catch(a){f.error("Error invoking search callback: "+getErrorMessage(a));}},j=Validators.removeFalsyIdentityValues({userIdentities:null!==a&&void 0!==a?a:{}},f).userIdentities,!Object.values(null!==j&&void 0!==j?j:{}).some(function(a){return "string"==typeof a&&0<a.length}))return f.verbose("Identity search called with empty identifiers; skipping request."),i({httpCode:HTTPCodes$4.noHttpCoverage}),[2/*return*/];// No API key -> same: deliver noHttpCoverage rather than hanging.
|
|
754
|
-
if(!b)return f.verbose("search called without a workspace API key; skipping request."),i({httpCode:HTTPCodes$4.noHttpCoverage}),[2/*return*/];v.label=1;case 1:return v.trys.push([1,9,,10]),k=c(),l=__assign(__assign({},k),{known_identities:__assign({},j)}),m={method:"post",headers:{Accept:"application/json","Content-Type":"application/json","x-mp-key":b},body:JSON.stringify(l)},n=g||(window.fetch?new FetchUploader(d):new XHRUploader(d)),f.verbose("Sending search request to "+d),[4/*yield*/,n.upload(m,d)];case 2:if(o=v.sent(),p=void 0,!isFunction(o.json))return [3/*break*/,7];v.label=3;case 3:return v.trys.push([3,5,,6]),[4/*yield*/,o.json()];case 4:return p=v.sent(),[3/*break*/,6];case 5:return v.sent(),f.verbose("search response had no parseable JSON body."),[3/*break*/,6];case 6:return [3/*break*/,8];case 7:if(r=o,null===r||void 0===r?void 0:r.responseText)try{p=JSON.parse(r.responseText);}catch(a){f.verbose("search XHR response was not valid JSON.");}v.label=8;case 8:return o.status===HTTP_OK?f.verbose("search received 200 OK."):o.status===HTTP_NOT_FOUND?f.verbose("search received 404 (no match)."):f.verbose("search received non-success status "+o.status),i({httpCode:o.status,body:p}),[3/*break*/,10];case 9:return s=v.sent(),t=getErrorMessage(s),u="Error sending search request: "+t,f.error(u),null===h||void 0===h?void 0:h.report({message:u,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),i({httpCode:HTTPCodes$4.noHttpCoverage}),[3/*break*/,10];case 10:return [2/*return*/]}})})};
|
|
755
|
-
|
|
756
|
-
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,HTTPCodes$3=Constants.HTTPCodes,Messages$9=Constants.Messages;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
757
|
-
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
758
|
-
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$3||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
|
|
759
|
-
// we sort the identities based on their enum.
|
|
760
|
-
// we create an array, set the user identity at the index of the user identity type
|
|
761
|
-
var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type
|
|
762
|
-
if(d){var f=[];// create an array where each index is equal to the user identity type
|
|
763
|
-
for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place
|
|
764
|
-
// before identify fires, so there may not be a cache. See what happens when
|
|
765
|
-
// the ? in idCache is removed to the following test
|
|
766
|
-
// "queued events contain login mpid instead of identify mpid when calling
|
|
767
|
-
// login immediately after mParticle initializes"
|
|
768
|
-
var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity
|
|
769
|
-
if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);if(!hasOwnProp(d,f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time.
|
|
770
|
-
// If the current time is greater than the expireTimestamp, it is not a valid
|
|
771
|
-
// cached identity.
|
|
772
|
-
var g=d[f].expireTimestamp;return !(g<new Date().getTime())};var getCachedIdentity=function(a,b,c){var d=concatenateIdentities(a,b),e=generateHash(d),f=c.retrieve(),g=f?f[e]:null;return {responseText:parseIdentityResponse(g.responseText),expireTimestamp:g.expireTimestamp,status:g.status}};// https://go.mparticle.com/work/SQDSDKS-6079
|
|
773
|
-
var createKnownIdentities=function(a,b){var c={};if(isObject(null===a||void 0===a?void 0:a.userIdentities))for(var d in a.userIdentities)c[d]=a.userIdentities[d];return c.device_application_stamp=b,c};var removeExpiredIdentityCacheDates=function(a){var b=a.retrieve()||{},c=new Date().getTime();// Iterate over the cache and remove any key/value pairs that are expired
|
|
774
|
-
for(var d in b)b[d].expireTimestamp<c&&delete b[d];a.store(b);};var tryCacheIdentity=function(a,b,c,d,e,f,g){// https://go.mparticle.com/work/SQDSDKS-6095
|
|
775
|
-
var h=hasValidCachedIdentity(g,a,b);// If Identity is cached, then immediately parse the identity response
|
|
776
|
-
if(h){var i=getCachedIdentity(g,a,b);return c(i,d,e,f,g,a,!0),!0}return !1};var getExpireTimestamp=function(a){return void 0===a&&(a=ONE_DAY_IN_SECONDS),new Date().getTime()+a*MILLIS_IN_ONE_SEC},parseIdentityResponse=function(a){return a?JSON.parse(a):{}},SHA256_IDENTITY_ALIASES={email_sha256:"other",mobile_sha256:"other2"};var normalizeUserIdentityKeys=function(a){var b=__assign({},a);return Object.keys(SHA256_IDENTITY_ALIASES).forEach(function(a){if(a in b){var c=b[a];delete b[a],b[SHA256_IDENTITY_ALIASES[a]]=c;}}),b};// Compare two identity objects by key and value, independent of
|
|
777
|
-
// object key insertion order. The two sides come from different sources
|
|
778
|
-
// (numeric IdentityType iteration vs. partner-provided / alias-normalized
|
|
779
|
-
// order)
|
|
780
|
-
var identitiesEqual=function(c,a){var b=Object.keys(null!==c&&void 0!==c?c:{}),d=Object.keys(null!==a&&void 0!==a?a:{});return !(b.length!==d.length)&&b.every(function(b){return c[b]===a[b]})};var hasIdentityRequestChanged=function(a,b){if(!a||!(null!==b&&void 0!==b)||!b.userIdentities)return !1;var c=a.getUserIdentities().userIdentities,d=normalizeUserIdentityKeys(b.userIdentities);return !identitiesEqual(c,d)};/**
|
|
781
|
-
* Checks if deviceId or other user identifiers (like email) were explicitly provided
|
|
782
|
-
* by the partner via config.deviceId or config.identifyRequest.userIdentities.
|
|
783
|
-
* When noFunctional is true, then cookies are blocked, so the partner must explicitly
|
|
784
|
-
* pass deviceId or other identifiers to prevent new users from being created on each page load.
|
|
785
|
-
*
|
|
786
|
-
* @param store - The SDK store (provides SDKConfig.deviceId and SDKConfig.identifyRequest.userIdentities)
|
|
787
|
-
* @returns true if deviceId or other identifiers were explicitly provided in config, false otherwise
|
|
788
|
-
*/var hasExplicitIdentifier=function(a){var b,c,d,e=null===(c=null===(b=null===a||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.identifyRequest)||void 0===c?void 0:c.userIdentities;return !!(e&&isObject(e)&&!isEmpty(e)&&Object.values(e).some(Boolean))||!(!(null!==(d=null===a||void 0===a?void 0:a.SDKConfig)&&void 0!==d)||!d.deviceId)};/**
|
|
789
|
-
* Builds the /v1/identify-style envelope (client_sdk, environment,
|
|
790
|
-
* request_id, request_timestamp_ms) used to correlate IDSync requests
|
|
791
|
-
* across endpoints. `known_identities` is omitted so the caller can
|
|
792
|
-
* fold in the search-specific identifiers alongside the envelope.
|
|
793
|
-
*/var buildIdentitySearchEnvelope=function(a){return {client_sdk:{platform:Constants.platform,sdk_vendor:Constants.sdkVendor,sdk_version:Constants.sdkVersion},environment:a,request_id:generateUniqueId(),request_timestamp_ms:Date.now()}};/**
|
|
794
|
-
* Wires the SDK instance into `sendSearchRequest`: gates on `canLog`,
|
|
795
|
-
* builds the `/v1/search` URL and request envelope, and dispatches.
|
|
796
|
-
* Lives here so the SDK glue (URL building, opt-out gate, dispatcher
|
|
797
|
-
* plumbing) is type-checked instead of being expressed in plain JS.
|
|
798
|
-
*/var executeSearchRequest=function(a,b,c,d){var e=a._Helpers,f=a._Store,g=a.Logger,h=a._ErrorReportingDispatcher,i=f.SDKConfig,j=i.identityUrl,k=i.isDevelopmentMode;if(!e.canLog()){if(g.verbose(Messages$9.InformationMessages.AbandonLogEvent),isFunction(d))try{d({httpCode:HTTPCodes$3.loggingDisabledOrMissingAPIKey});}catch(a){g.error("Error invoking search callback: "+getErrorMessage(a));}return}// The Search endpoint is colocated with /v1/identify under
|
|
799
|
-
// identityUrl, so we reuse the same service URL builder. We do
|
|
800
|
-
// NOT append the apiKey to the URL \u2014 auth is done via x-mp-key.
|
|
801
|
-
var l=e.createServiceUrl(j),m=k?"development":"production";sendSearchRequest(c,b,function(){return buildIdentitySearchEnvelope(m)},l+"search?cb=1",d,g,void 0,h);};
|
|
802
|
-
|
|
803
|
-
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){// https://go.mparticle.com/work/SQDSDKS-6317
|
|
804
|
-
var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
805
|
-
this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(a,b){b.forEach(function(b){b.MPID||appendUserInfo(a,b);});};// When noFunctional is set and there are no identities passed, the SDK will not fully initialize.
|
|
806
|
-
// In this case, there will be no MPID, but we still want kits to initialize and forward the event to kits.
|
|
807
|
-
// The original event is queued for the MP server upload path so it can be sent once an MPID is returned.
|
|
808
|
-
// Returns true if the event was handled by this path (caller should return early).
|
|
809
|
-
var d=function(c,d){var e,f=(null===(e=a._CookieConsentManager)||void 0===e?void 0:e.getNoFunctional())&&!hasExplicitIdentifier(a._Store);if(!f||d||!a._Store.configurationLoaded||a._Store.requireDelay)return !1;var g=c;return (null===b||void 0===b?void 0:b.kitBlockingEnabled)&&(g=b.createBlockedEvent(c)),g&&(a._Forwarders.sendEventToForwarders(g),c.AlreadySentToForwarders=!0),a.Logger.verbose("noFunctional event forwarded to kits and queued for MP server upload when MPID is available."),a._Store.eventQueue.push(c),!0};this.sendEventToServer=function(c,e){var f=extend({shouldUploadEvent:!0},e);if(a._Store.webviewBridgeEnabled)return void a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent,JSON.stringify(c));var g,h=a.Identity.getCurrentUser();if(h&&(g=h.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),!d(c,g)){// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that
|
|
810
|
-
// require this to stall because integration attributes need to be set, or if we are still
|
|
811
|
-
// fetching the config (self hosted only), and so require delaying events
|
|
812
|
-
if(!g||a._Store.requireDelay||!a._Store.configurationLoaded)return a.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void a._Store.eventQueue.push(c);this.processQueuedEvents(),isEmpty(c)||(f.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition+""&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&!c.AlreadySentToForwarders&&a._Forwarders.sendEventToForwarders(c)));}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
813
|
-
},this.sendBatchForwardingStatsToServer=function(b,c){var d,e;try{d=a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken),e={uuid:a._Helpers.generateUniqueId(),data:b},c&&(c.open("post",d+"/Forwarding"),c.send(JSON.stringify(e)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.initializeForwarderStatsUploader=function(){var b=a._Store.SDKConfig.v1SecureServiceUrl,c=a._Store.devToken,d="https://".concat(b).concat(c,"/Forwarding"),e=window.fetch?new FetchUploader(d):new XHRUploader(d);return e},this.prepareForwardingStats=function(b,c){var d,e=a._Forwarders.getForwarderStatsQueue();if(b&&b.isVisible){d={mid:b.id,esid:b.eventSubscriptionId,n:c.EventName,attrs:c.EventAttributes,sdk:c.SDKVersion,dt:c.EventDataType,et:c.EventCategory,dbg:c.Debug,ct:c.Timestamp,eec:c.ExpandedEventCount,dp:c.DataPlan};var f=a._Forwarders,g=f.sendSingleForwardingStatsToServer,h=f.setForwarderStatsQueue;a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(e.push(d),h(e)):g(d);}};}
|
|
814
|
-
|
|
815
|
-
var KitFilterHelper=/** @class */function(){function a(){}a.hashEventType=function(a){return generateHash(a)},a.hashEventName=function(a,b){return generateHash(b+a)},a.hashEventAttributeKey=function(a,b,c){return generateHash(a+b+c)},a.hashUserAttribute=function(a){return generateHash(a)},a.hashUserIdentity=function(a){return a},a.hashConsentPurpose=function(a,b){return generateHash(a+b)},a.hashAttributeConditionalForwarding=function(a){return generateHash(a).toString()},a.hashConsentPurposeConditionalForwarding=function(a,b){return this.hashConsentPurpose(a,b).toString()};var b;return b=a,a.filterUserAttributes=function(a,c){return filterDictionaryWithHash(a,c,function(a){return b.hashUserAttribute(a)})},a.filterUserIdentities=function(a,c){return filterDictionaryWithHash(a,c,function(a){return b.hashUserIdentity(IdentityType.getIdentityType(a))})},a.isFilteredUserAttribute=function(a,c){var d=b.hashUserAttribute(a);return c&&inArray(c,d)},a}();
|
|
816
|
-
|
|
817
|
-
var StorageNames$1=Constants.StorageNames;function appendFilteredUserIdentity(a,b,c){c===Types.IdentityType.CustomerId?a.unshift(b):a.push(b);}function buildFilteredUserIdentities$1(a,b,c){var d=[];if(!a||!Object.keys(a).length)return d;for(var e in a)if(a.hasOwnProperty(e)){// Must be `=== false`: IdentityType.Other is 0, so a falsy check would
|
|
818
|
-
// drop a valid type.
|
|
819
|
-
var f=Types.IdentityType.getIdentityType(e),g=!1===f;g||c(b,f)||appendFilteredUserIdentity(d,{Type:f,Identity:a[e]},f);}return d}function Helpers(a){var b=this;// TODO: Refactor SDK to directly use these methods
|
|
820
|
-
// https://go.mparticle.com/work/SQDSDKS-5239
|
|
821
|
-
// Utility Functions
|
|
822
|
-
// Imported Validators
|
|
823
|
-
this.canLog=function(){return !!(a._Store.isEnabled&&(a._Store.devToken||a._Store.webviewBridgeEnabled))},this.getFeatureFlag=function(b){return a._Store.SDKConfig.flags.hasOwnProperty(b)?a._Store.SDKConfig.flags[b]:null},this.invokeCallback=function(c,d,e,f,g){c||a.Logger.warning("There is no callback provided");try{b.Validators.isFunction(c)&&c({httpCode:d,body:e,getUser:function getUser(){return f?f:a.Identity.getCurrentUser()},getPreviousUser:function getPreviousUser(){if(!g){var b=a.Identity.getUsers(),c=b.shift(),d=f||a.Identity.getCurrentUser();return c&&d&&c.getMPID()===d.getMPID()&&(c=b.shift()),c||null}var d=f||a.Identity.getCurrentUser(),e=(null===d||void 0===d?void 0:d.getMPID())===g;return e?null:a.Identity.getUser(g)}});}catch(b){a.Logger.error("There was an error with your callback: "+b);}},this.invokeAliasCallback=function(c,d,e){c||a.Logger.warning("There is no callback provided");try{if(b.Validators.isFunction(c)){var f={httpCode:d};e&&(f.message=e),c(f);}}catch(b){a.Logger.error("There was an error with your callback: "+b);}},this.extend=extend,this.createServiceUrl=function(b,c){var d,e=window.mParticle&&a._Store.SDKConfig.forceHttps?"https://":window.location.protocol+"//";return d=a._Store.SDKConfig.forceHttps?"https://"+b:e+b,c&&(d+=c),d},this.createXHR=function(b){var c;try{c=new window.XMLHttpRequest;}catch(b){a.Logger.error("Error creating XMLHttpRequest object.");}if(c&&b&&"withCredentials"in c)c.onreadystatechange=b;else if("undefined"!=typeof window.XDomainRequest){a.Logger.verbose("Creating XDomainRequest object");try{c=new window.XDomainRequest,c.onload=b;}catch(b){a.Logger.error("Error creating XDomainRequest object");}}return c},this.filterUserIdentities=function(a,c){return buildFilteredUserIdentities$1(a,c,b.inArray)},this.filterUserIdentitiesForForwarders=KitFilterHelper.filterUserIdentities,this.filterUserAttributes=KitFilterHelper.filterUserAttributes,this.isEventType=function(a){for(var b in Types.EventType)if(Types.EventType.hasOwnProperty(b)&&Types.EventType[b]===a)return !0;return !1},this.sanitizeAttributes=function(c,d){if(!c||!b.isObject(c))return null;var e={};for(var f in c)// Make sure that attribute values are not objects or arrays, which are not valid
|
|
824
|
-
c.hasOwnProperty(f)&&b.Validators.isValidAttributeValue(c[f])?e[f]=c[f]:a.Logger.warning("For '"+d+"', the corresponding attribute value of '"+f+"' must be a string, number, boolean, or null.");return e},this.isDelayedByIntegration=function(b,c,d){if(d-c>a._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$1.currentStorageName+"_"+a:StorageNames$1.currentStorageName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.parseStringOrNumber=parseStringOrNumber,this.generateHash=generateHash,this.generateUniqueId=generateUniqueId,this.Validators=Validators;}
|
|
825
|
-
|
|
826
|
-
var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function getAndroidBridge(a){return Object.prototype.hasOwnProperty.call(window,a)?window[a]:void 0}function getInstanceNamedValue(a,b){return a[b]}function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){var b,c;if(!a)return !1;var d=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge
|
|
827
|
-
return !(!(null!==(c=null===(b=window.webkit)||void 0===b?void 0:b.messageHandlers)&&void 0!==c)||!c.hasOwnProperty(d))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===d)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge
|
|
828
|
-
// TODO: what to do about people setting things on mParticle itself?
|
|
829
|
-
// android
|
|
830
|
-
},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName
|
|
831
|
-
},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||getAndroidBridge(androidBridgeNameBase)||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){var e=getAndroidBridge(androidBridgeNameBase);e&&e.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),e[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){var f,g;if(e){var h,i,j=getAndroidBridge(androidBridgeNameBase+"_"+e+"_v2"),k=iosBridgeNameBase+"_"+e+"_v2";return (null===(g=null===(f=window.webkit)||void 0===f?void 0:f.messageHandlers)||void 0===g?void 0:g[k])&&(h=window.webkit.messageHandlers[k]),a.uiwebviewBridgeName===k&&(i=getInstanceNamedValue(a,k)),j&&j.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void j[c](d)):void(h?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),h.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):i&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};}
|
|
832
|
-
|
|
833
|
-
var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations
|
|
834
|
-
var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public
|
|
835
|
-
// Private
|
|
836
|
-
this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync
|
|
837
|
-
// dates. Skip cookie sync to avoid running it on every page load.
|
|
838
|
-
{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h;try{// set requiresConsent to false to start each additional pixel configuration
|
|
839
|
-
// set to true only if filteringConsenRuleValues.values.length exists
|
|
840
|
-
var j=!1,k=e.filteringConsentRuleValues,l=e.pixelUrl,m=e.redirectUrl,n=e.moduleId,o=e.settings,// Tells you how often we should do a cookie sync (in days)
|
|
841
|
-
p=e.frequencyCap,q=(k||{}).values;// Filtering rules as defined in UI
|
|
842
|
-
if(isEmpty(l))return;// If MPID is new to cookies, we should not try to perform the cookie sync
|
|
843
|
-
// because a cookie sync can only occur once a user either consents or doesn't.
|
|
844
|
-
// we should not check if it's enabled if the user has a blank consent
|
|
845
|
-
if(isEmpty(q)||(j=!0),j&&d)return;// For Rokt, block cookie sync when noTargeting privacy flag is true
|
|
846
|
-
if(n===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting())return;var r=a._Consent.isEnabledForUserConsent;if(!r(k,a.Identity.getCurrentUser()))return;var s=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},t=s[n]||null;if(!isLastSyncDateExpired(p,t))return;// The Trade Desk requires a URL parameter for GDPR enabled users.
|
|
847
|
-
// It is optional but to simplify the code, we add it for all Trade
|
|
848
|
-
// // Desk cookie syncs.
|
|
849
|
-
var u=n===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,v="true"===(null===(h=null===o||void 0===o?void 0:o.enableHmTag)||void 0===h?void 0:h.toLowerCase()),w=n===PARTNER_MODULE_IDS.DoubleclickDFP,x=w&&v,y=x?toWebSafeBase64(c):void 0;// Google Marketing Platform accepts a web-safe base64-encoded MPID via the
|
|
850
|
-
// `google_hm` query parameter, but only for accounts provisioned for Google
|
|
851
|
-
// Hosted Matching \u2014 Google returns errors otherwise. It is therefore gated
|
|
852
|
-
// behind the opt-in `enableHmTag` setting (off by default), which the server
|
|
853
|
-
// delivers as the string 'True' when the UI toggle is enabled.
|
|
854
|
-
x&&!y&&a.Logger.warning("Unable to base64 encode the current MPID; omitting the google_hm parameter from this cookie sync");var z=createCookieSyncUrl(c,l,m,u,y);b.performCookieSync(z,n.toString(),c,s);}catch(b){a.Logger.error("Error performing cookie sync: "+b);}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie
|
|
855
|
-
return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again
|
|
856
|
-
};
|
|
857
|
-
|
|
858
|
-
function logDeprecatedMethodUsage(a,b,c){b.warning(a.warningMessage),null===c||void 0===c?void 0:c.report({message:a.methodName,code:ErrorCodes.MP_DEPRECATED_METHOD_USAGE,severity:WSDKErrorSeverity.WARNING});}
|
|
859
|
-
|
|
860
|
-
var Messages$6=Constants.Messages;function SessionManager(a){/**
|
|
861
|
-
* Checks if the session has expired based on the last event timestamp
|
|
862
|
-
* @param lastEventTimestamp - Unix timestamp in milliseconds of the last event
|
|
863
|
-
* @param sessionTimeout - Session timeout in minutes
|
|
864
|
-
* @returns true if the session has expired, false otherwise
|
|
865
|
-
*/function b(a,b){if(!a||!b||0>=b)return !1;var c=Date.now()-a;return c>=6e4*b}/**
|
|
866
|
-
* Performs session end operations:
|
|
867
|
-
* - Logs a SessionEnd event
|
|
868
|
-
* - Nullifies the session ID and related data
|
|
869
|
-
* - Resets the time-on-site timer
|
|
870
|
-
*/function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045
|
|
871
|
-
// https://go.mparticle.com/work/SQDSDKS-6323
|
|
872
|
-
var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return logDeprecatedMethodUsage({methodName:"SessionManager.getSession()",warningMessage:generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")},a.Logger,a._ErrorReportingDispatcher),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
|
|
873
|
-
if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};}
|
|
874
|
-
|
|
875
|
-
var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801
|
|
876
|
-
// When the caller does not supply a transaction-level total via
|
|
877
|
-
// transactionAttributes.Revenue, derive it from the product list
|
|
878
|
-
// (quantity * price) plus shipping and tax. A total that the caller provided
|
|
879
|
-
// (including 0) is never overwritten.
|
|
880
|
-
// https://go.mparticle.com/work/SQDSDKS-4801
|
|
881
|
-
// https://go.mparticle.com/work/SQDSDKS-4801
|
|
882
|
-
// https://go.mparticle.com/work/SQDSDKS-4801
|
|
883
|
-
// https://go.mparticle.com/work/SQDSDKS-4801
|
|
884
|
-
// sanitizes any non number, non string value to 0
|
|
885
|
-
this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.calculateProductActionTotalAmount=function(a){if(!a||null!=a.TotalAmount)return a;var b=0;return Array.isArray(a.ProductList)&&a.ProductList.forEach(function(a){b+=parseNumber(a.Quantity)*parseNumber(a.Price);}),b+=parseNumber(a.ShippingAmount)+parseNumber(a.TaxAmount),a.TotalAmount=b,a},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.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(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:b===Types.ProductActionType.ViewCart||b===Types.ProductActionType.AddShippingInfo||b===Types.ProductActionType.AddPaymentInfo||b===Types.ProductActionType.PaymentMethodSelected||b===Types.ProductActionType.PaymentAttempted||b===Types.ProductActionType.PaymentSucceeded||b===Types.ProductActionType.PaymentFailed||b===Types.ProductActionType.RefundInitiated?Types.EventType.Unknown:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801
|
|
886
|
-
return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0
|
|
887
|
-
return a._Helpers.parseNumber(b)};}
|
|
888
|
-
|
|
889
|
-
var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window
|
|
890
|
-
document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}();
|
|
891
|
-
|
|
892
|
-
function normalizeRoktLauncherOptions(a){var b=a?__assign({},a):{},c=!0===b.noDeviceId||!0===b.noDeviceID;return c&&(b.noDeviceId=!0,b.noFunctional=!0,b.noTargeting=!0),b}
|
|
893
|
-
|
|
894
|
-
function createSDKConfig(a){// TODO: Refactor to create a default config object
|
|
895
|
-
var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access
|
|
896
|
-
return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
|
|
897
|
-
function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model
|
|
898
|
-
persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(isObject(d.persistenceData[a])?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state
|
|
899
|
-
(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315
|
|
900
|
-
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.getTimeOnSite=function(){var a;return null===(a=b._timeOnSiteTimer)||void 0===a?void 0:a.getTimeInForeground()},this.getTotalTimeOnSite=function(){return d.sessionStartDate?Date.now()-d.sessionStartDate.getTime():void 0},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g=a.workspaceToken,h=a.requiredWebviewBridgeName;// We should reprocess the flags and baseUrls in case they have changed when we request an updated config
|
|
901
|
-
// such as if the SDK is being self-hosted and the flags are different on the server config
|
|
902
|
-
// https://go.mparticle.com/work/SQDSDKS-6317
|
|
903
|
-
// Only update flags if the config actually has flags (don't overwrite with empty object)
|
|
904
|
-
a.flags&&(d.SDKConfig.flags=processFlags(a));var i=processBaseUrls(a,d.SDKConfig.flags,c);for(var j in i)d.SDKConfig[j]=i[j];if(g){d.SDKConfig.workspaceToken=g;var k=normalizeRoktLauncherOptions(null===a||void 0===a?void 0:a.launcherOptions).noFunctional;b._timeOnSiteTimer=new ForegroundTimeTracker(g,k);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned
|
|
905
|
-
d.storageName=e(g),d.SDKConfig.requiredWebviewBridgeName=h||g,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317
|
|
906
|
-
function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents,m=c.AutoLogPageView,n=c.AutoButtonTracking;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b[m]="True"===a.flags[m],b[n]="True"===a.flags[n],b):{};// https://go.mparticle.com/work/SQDSDKS-6317
|
|
907
|
-
// Passed in config flags take priority over defaults
|
|
908
|
-
}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
|
|
909
|
-
if(!c)return {};// Set default baseUrls
|
|
910
|
-
// A CNAME (config.domain, e.g. set by the snippet v2.6+) takes precedence
|
|
911
|
-
// over direct URL routing so that customer-configured first-party domains
|
|
912
|
-
// and the snippet's fallback domain are always honored.
|
|
913
|
-
return isEmpty(a.domain)?b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a):processCustomBaseUrls(a);// When direct URL routing is false, update baseUrls based custom urls
|
|
914
|
-
// passed to the config
|
|
915
|
-
}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c=Constants.CNAMEUrlPaths,d={};// newBaseUrls are default if the customer is not using a CNAME
|
|
916
|
-
// If a customer passes either config.domain or config.v3SecureServiceUrl,
|
|
917
|
-
// config.identityUrl, etc, the customer is using a CNAME.
|
|
918
|
-
// config.domain will take priority if a customer passes both.
|
|
919
|
-
// If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain.
|
|
920
|
-
// This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty
|
|
921
|
-
// if a customer is using a snippet prior to 2.6.
|
|
922
|
-
if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);return d}for(var f in b)d[f]=a[f]||b[f];return d}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that
|
|
923
|
-
// include the silo in the urls. mParticle API keys are prefixed with the
|
|
924
|
-
// silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo,
|
|
925
|
-
// and before other silos existed, there were no prefixes and all apiKeys
|
|
926
|
-
// were us1. As such, if we split on a '-' and the resulting array length
|
|
927
|
-
// is 1, then it is an older APIkey that should route to us1.
|
|
928
|
-
// When splitKey.length is greater than 1, then splitKey[0] will be
|
|
929
|
-
// us1, us2, eu1, au1, or st1, etc as new silos are added
|
|
930
|
-
for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct
|
|
931
|
-
// mapping to the silo. The most common use case is a customer provided CNAME.
|
|
932
|
-
if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d}
|
|
933
|
-
|
|
934
|
-
var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.isVerbose=function(){return this.logLevel===LogLevelType.Verbose},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}();
|
|
935
|
-
|
|
936
|
-
var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function getMParticleManager(){return window.mParticle}function _Persistence(a){function b(b,c){return b||c?void(a._Store.isFirstRun=!1):(a._Store.isFirstRun=!0,void(a._Store.mpid=0))}function c(a,b){return a&&b?extend(!1,a,b):a||b}// For migrating from localStorage to cookies -- If an instance switches from
|
|
937
|
-
// localStorage to cookies, then no mParticle cookie exists yet and there is
|
|
938
|
-
// localStorage. Get the localStorage, set them to cookies, then delete the
|
|
939
|
-
// localStorage item.
|
|
940
|
-
function d(b,d,e){var f;return d?(f=c(d,e),b.removeItem(a._Store.storageName)):e&&(f=e),D.storeDataInMemory(f),f}// For migrating from cookie to localStorage -- If an instance is newly
|
|
941
|
-
// switching from cookies to localStorage, then no mParticle localStorage
|
|
942
|
-
// exists yet and there are cookies. Get the cookies, set them to
|
|
943
|
-
// localStorage, then delete the cookies.
|
|
944
|
-
function e(b,c){if(!c)return void D.storeDataInMemory(b);var d=b||c;return D.storeDataInMemory(d),D.expireCookies(a._Store.storageName),d}function f(b,c){return a._Store.isLocalStorageAvailable?a._Store.SDKConfig.useCookieStorage?d(window.localStorage,b,c):e(b,c):void D.storeDataInMemory(c)}function g(b){for(var c in b)b.hasOwnProperty(c)&&!SDKv2NonMPIDCookieKeys[c]&&(a._Store.nonCurrentUserMPIDs[c]=b[c]);}function h(b){return D.useLocalStorage()&&a._Store.isLocalStorageAvailable?void(b||localStorage.removeItem(a._Store.storageName)):void D.expireCookies(a._Store.storageName)}function i(){a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId();}function j(b,c){// For most persistence values, we prioritize localstorage/cookie values over
|
|
945
|
-
// Store. However, we allow device ID to be overriden via a config value and
|
|
946
|
-
// thus the priority of the deviceId value is
|
|
947
|
-
// 1. value passed via config.deviceId
|
|
948
|
-
// 2. previous value in persistence
|
|
949
|
-
// 3. generate new guid
|
|
950
|
-
a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu];}// https://go.mparticle.com/work/SQDSDKS-6045
|
|
951
|
-
function k(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function l(b){var c=D.decodePersistence(b);if(!c)return null;var d=JSON.parse(c);return a._Helpers.isObject(d)&&Object.keys(d).length?d:null}/* This function determines if a cookie is greater than the configured maxCookieSize.
|
|
952
|
-
- If it is, we remove an MPID and its associated UI/UA/CSD from the cookie.
|
|
953
|
-
- Once removed, check size, and repeat.
|
|
954
|
-
- Never remove the currentUser's MPID from the cookie.
|
|
955
|
-
|
|
956
|
-
MPID removal priority:
|
|
957
|
-
1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie.
|
|
958
|
-
2. If there are currentSessionMPIDs:
|
|
959
|
-
a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs
|
|
960
|
-
b. Then remove MPIDs based on order in currentSessionMPIDs array, which
|
|
961
|
-
stores MPIDs based on earliest login.
|
|
962
|
-
*/function m(a,b){return a.length>b}function n(a,b,c,d){var e;for(var f in a)a.hasOwnProperty(f)&&(e=t(a,b,c),!!m(e,d))&&(SDKv2NonMPIDCookieKeys[f]||f===a.cu||delete a[f]);return e}function o(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(SDKv2NonMPIDCookieKeys[c]||c===a.cu||(b[c]=1));return b}function p(a,b,c,d,e,f){var g;for(var h in b)(g=t(a,d,e),!!m(g,f))&&b.hasOwnProperty(h)&&-1===c.indexOf(h)&&delete a[h];return g}function q(b,c,d){return b[c]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+d+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[c],null,2)),void delete b[c]):void a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+d+". We recommend using a maxCookieSize of 1500.")}function r(a,b,c,d,e){for(var f,g=0;g<b.length&&(f=t(a,c,d),!!m(f,e));g++)q(a,b[g],e);return f}function s(a){var b="https:"===window.location.protocol;window.document.cookie=b?a+";Secure":a;}function t(a,b,c){return D.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}function u(b){return Array.isArray(b)?0<b.length:!!a._Helpers.isObject(b)&&0<Object.keys(b).length}function v(a,b){return a[b]&&u(a[b])?void(a[b]=Base64.encode(JSON.stringify(a[b]))):void delete a[b]}function w(a){for(var b in a)if(a.hasOwnProperty(b)){if(Base64CookieKeys[b]){v(a,b);continue}if("ie"==b){a[b]=a[b]?1:0;continue}a[b]||delete a[b];}}function x(b,c){var d=b[c];return a._Helpers.isObject(d)&&Object.keys(d).length?void(b[c]=Base64.encode(JSON.stringify(d))):void delete b[c]}function y(a){for(var b in a)a.hasOwnProperty(b)&&Base64CookieKeys[b]&&x(a,b);}function z(a){for(var b in a)a.hasOwnProperty(b)&&(SDKv2NonMPIDCookieKeys[b]||y(a[b]));}function A(a){for(var b in a)if(a.hasOwnProperty(b)){if(Base64CookieKeys[b]){a[b]=JSON.parse(Base64.decode(a[b])),"csm"!==b||Array.isArray(a[b])||delete a[b];continue}"ie"==b&&(a[b]=!!a[b]);}}function B(a){for(var b in a)a.hasOwnProperty(b)&&Base64CookieKeys[b]&&a[b].length&&(a[b]=JSON.parse(Base64.decode(a[b])));}function C(b){for(var c in b)if(b.hasOwnProperty(c)){if(!SDKv2NonMPIDCookieKeys[c]){if(!a._Helpers.isObject(b[c])){delete b[c];continue}B(b[c]);continue}"l"==c&&(b[c]=!!b[c]);}}// TODO: This should actually be decodePersistenceString or
|
|
963
|
-
// we should refactor this to take a string and return an object
|
|
964
|
-
var D=this;// https://go.mparticle.com/work/SQDSDKS-5022
|
|
965
|
-
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
966
|
-
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
967
|
-
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
968
|
-
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
969
|
-
// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible.
|
|
970
|
-
// For example subdomain.domain.co.uk would try the following combinations:
|
|
971
|
-
// "co.uk" -> fail
|
|
972
|
-
// "domain.co.uk" -> success, return
|
|
973
|
-
// "subdomain.domain.co.uk" -> skipped, because already found
|
|
974
|
-
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
975
|
-
/**
|
|
976
|
-
* set the "first seen" time for a user. the time will only be set once for a given
|
|
977
|
-
* mpid after which subsequent calls will be ignored
|
|
978
|
-
*/ /**
|
|
979
|
-
* returns the "last seen" time for a user. If the mpid represents the current user, the
|
|
980
|
-
* return value will always be the current time, otherwise it will be to stored "last seen"
|
|
981
|
-
* time
|
|
982
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-6045
|
|
983
|
-
// Forwarder Batching Code
|
|
984
|
-
this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){var c=null;try{var d=D.getLocalStorage();c=D.getCookie(),b(d,c),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0);// https://go.mparticle.com/work/SQDSDKS-6046
|
|
985
|
-
var e=f(d,c);g(e),D.update();}catch(b){// If cookies or local storage is corrupt, we want to remove it
|
|
986
|
-
// so that in the future, initializeStorage will work
|
|
987
|
-
h(!!c),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&D.setCookie(),D.setLocalStorage());},this.storeDataInMemory=function(b,c){try{if(!b)return void i();j(b,c);}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b=getMParticleManager();if(null===b||void 0===b?void 0:b._forceNoLocalStorage)return !1;try{a.setItem("mparticle","test");var c="test"===a.getItem("mparticle");return a.removeItem("mparticle"),!!(c&&a)}catch(a){return !1}},this.setLocalStorage=function(){var b;if(a._Store.isLocalStorageAvailable&&(null===(b=a._CookieConsentManager)||void 0===b||!b.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true
|
|
988
|
-
{var c=a._Store.storageName,d=D.getLocalStorage()||{},e=a.Identity.getCurrentUser(),f=e?e.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){d.gs=d.gs||{},d.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(d.gs.csm=a._Store.currentSessionMPIDs),d.gs.ie=a._Store.isEnabled,f&&(d.cu=f),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(d=extend({},d,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),d=k(d);try{window.localStorage.setItem(encodeURIComponent(c),D.encodePersistence(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){return a._Store.isLocalStorageAvailable?l(window.localStorage.getItem(a._Store.storageName)):null},this.expireCookies=function(a){var b,c,d,e=new Date;d=D.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),s(a+"="+b+"; path=/"+c);},this.getCookie=function(){var b,c,d,e,f,g,h=a._Store.storageName;a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;c<d;c++){try{e=b[c].split("="),f=e.shift(),g=e.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+f+". Skipping.");}if(h&&h===f){var j=l(a._Helpers.converted(g));if(j)return a.Logger.verbose(Messages$4.InformationMessages.CookieFound),j}}return null},this.setCookie=function(){var b;// Block mprtcl-v4 cookies when noFunctional is true
|
|
989
|
-
if(!(null!==(b=a._CookieConsentManager)&&void 0!==b)||!b.getNoFunctional()){var c,d=a.Identity.getCurrentUser();d&&(c=d.getMPID());var e,f,g,h=new Date,i=a._Store.storageName,j=D.getCookie()||{},l=new Date(h.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toUTCString();e=D.getCookieDomain(),f=""===e?"":";domain="+e,j.gs=j.gs||{},a._Store.sessionId&&(j.gs.csm=a._Store.currentSessionMPIDs),c&&(j.cu=c),j.l=a._Store.isLoggedIn?1:0,j=k(j),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(j=extend({},j,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),g=D.reduceAndEncodePersistence(j,l,f,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),s(encodeURIComponent(i)+"="+g);}},this.reduceAndEncodePersistence=function(a,b,c,d){var e=a.gs.csm?a.gs.csm:[];if(!e.length)return n(a,b,c,d);var f=o(a);return Object.keys(f).length&&p(a,f,e,b,c,d),r(a,e,b,c,d)},this.encodePersistence=function(a){var b=JSON.parse(a);return w(b.gs),z(b),createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(!b)return;var c=JSON.parse(revertCookieString(b));return a._Helpers.isObject(c)&&Object.keys(c).length&&(A(c.gs),C(c)),JSON.stringify(c)}catch(b){a.Logger.error("Problem with decoding cookie");}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=D.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1<a.cookie.indexOf("mptest=cookie"))return a.cookie="mptest=;domain=."+d+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",d;return ""},this.saveUserCookieSyncDatesToPersistence=function(b,c){if(c){var d=D.getPersistence();d&&(a._Helpers.isObject(d[b])?d[b].csd=c:d[b]={csd:c}),D.savePersistence(d);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=D.getPersistence();d&&(d.cu=b,d.gs.csm=c,D.savePersistence(d));}},this.savePersistence=function(b){var c;// Block mprtcl-v4 persistence when noFunctional is true
|
|
990
|
-
if(null===(c=a._CookieConsentManager)||void 0===c||!c.getNoFunctional()){var d,e=D.encodePersistence(JSON.stringify(b)),f=new Date,g=a._Store.storageName,h=new Date(f.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toUTCString(),i=D.getCookieDomain();if(d=""===i?"":";domain="+i,a._Store.SDKConfig.useCookieStorage){var j=D.reduceAndEncodePersistence(b,h,d,a._Store.SDKConfig.maxCookieSize);s(encodeURIComponent(g)+"="+j);}else if(a._Store.isLocalStorageAvailable)try{localStorage.setItem(a._Store.storageName,e);}catch(b){a.Logger.error("Error saving persistence to localStorage.");}}},this.getPersistence=function(){var a=this.useLocalStorage()?this.getLocalStorage():this.getCookie();return a},this.getFirstSeenTime=function(a){if(!a)return null;var b=D.getPersistence();return b&&b[a]&&b[a].fst?b[a].fst:null},this.setFirstSeenTime=function(b,c){if(b){c||(c=new Date().getTime());var d=D.getPersistence();d&&(!a._Helpers.isObject(d[b])&&(d[b]={}),!d[b].fst&&(d[b].fst=c,D.savePersistence(d)));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
991
|
-
},this.getLastSeenTime=function(b){if(!b)return null;if(b===a.Identity.getCurrentUser().getMPID())//if the mpid is the current user, its last seen time is the current time
|
|
992
|
-
return new Date().getTime();var c=D.getPersistence();return c&&c[b]&&c[b].lst?c[b].lst:null},this.setLastSeenTime=function(b,c){if(b){c||(c=new Date().getTime());var d=D.getPersistence();d&&a._Helpers.isObject(d[b])&&(d[b].lst=c,D.savePersistence(d));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
993
|
-
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,D.update();},this.resetPersistence=function(){localStorage.clear(),D.expireCookies(StorageNames.cookieName),D.expireCookies(StorageNames.cookieNameV2),D.expireCookies(StorageNames.cookieNameV3),D.expireCookies(StorageNames.cookieNameV4),D.expireCookies(a._Store.storageName);var b=getMParticleManager();if(null===b||void 0===b?void 0:b._isTestEnv){localStorage.removeItem(a._Helpers.createMainStorageName("abcdef")),D.expireCookies(a._Helpers.createMainStorageName("abcdef"));}},this.forwardingStatsBatches={uploadsTable:{},forwardingStatsEventQueue:[]};}
|
|
994
|
-
|
|
995
|
-
var Messages$3=Constants.Messages;function Events(a){var b=this;// The auto page view for the landing page. The SPA navigations that follow it
|
|
996
|
-
// come from PageViewTracker instead, so both emitters attach the same
|
|
997
|
-
// allowlisted query params \u2014 and this is the one that matters for campaign
|
|
998
|
-
// attribution, since utm_*/gclid live on the entry URL.
|
|
999
|
-
this.logEvent=function(b,c){if(a.Logger.verbose(Messages$3.InformationMessages.StartingLogEvent+": "+b.name),a._Helpers.canLog()){var d=a._ServerModel.createEventObject(b);a._APIClient.sendEventToServer(d,c);}else a.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent);},this.startTracking=function(b){function c(b,c){if(b)try{c?b(c):b();}catch(b){a.Logger.error("Error invoking the callback passed to startTrackingLocation."),a.Logger.error(b);}}if(!a._Store.isTracking)"geolocation"in navigator&&(a._Store.watchPositionId=navigator.geolocation.watchPosition(function e(d){// prevents callback from being fired multiple times
|
|
1000
|
-
a._Store.currentPosition={lat:d.coords.latitude,lng:d.coords.longitude},c(b,d),b=null,a._Store.isTracking=!0;},function d(){// prevents callback from being fired multiple times
|
|
1001
|
-
c(b),b=null,a._Store.isTracking=!1;}));else {var d={coords:{latitude:a._Store.currentPosition.lat,longitude:a._Store.currentPosition.lng}};c(b,d);}},this.stopTracking=function(){a._Store.isTracking&&(navigator.geolocation.clearWatch(a._Store.watchPositionId),a._Store.currentPosition=null,a._Store.isTracking=!1);},this.logOptOut=function(){a.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut);var b=a._ServerModel.createEventObject({messageType:Types.MessageType.OptOut,eventType:Types.EventType.Other});a._APIClient.sendEventToServer(b);},this.logAST=function(){b.logEvent({messageType:Types.MessageType.AppStateTransition});},this.logPageView=function(a){b.logEvent({messageType:Types.MessageType.PageView,name:"PageView",data:__assign(__assign(__assign({},allowedQueryParams(getHref())),{hostname:window.location.hostname,title:window.document.title}),autoPageViewAttribute(a&&a.isAutoPageView)),eventType:Types.EventType.Unknown});},this.logProductActionEvent=function(c,d,e,f,g,h){var i=a._Ecommerce.createCommerceEventObject(f,h),j=Array.isArray(d)?d:[d];j.forEach(function(b){b.TotalAmount&&(b.TotalAmount=a._Ecommerce.sanitizeAmount(b.TotalAmount,"TotalAmount")),b.Position&&(b.Position=a._Ecommerce.sanitizeAmount(b.Position,"Position")),b.Price&&(b.Price=a._Ecommerce.sanitizeAmount(b.Price,"Price")),b.Quantity&&(b.Quantity=a._Ecommerce.sanitizeAmount(b.Quantity,"Quantity"));}),i&&(i.EventCategory=a._Ecommerce.convertProductActionToEventType(c),i.EventName+=a._Ecommerce.getProductActionEventName(c),i.ProductAction={ProductActionType:c,ProductList:j},Types.ProductActionType.isRoktCommerceType(c)&&(i.CustomFlags=i.CustomFlags||{},i.CustomFlags["Rokt.CommerceEventType"]=Types.ProductActionType.getExpansionName(c)),a._Helpers.isObject(g)&&a._Ecommerce.convertTransactionAttributesToProductAction(g,i.ProductAction),b.logCommerceEvent(i,e,h));},this.logPurchaseEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase),g.EventCategory=Types.CommerceEventType.ProductPurchase,g.ProductAction={ProductActionType:Types.ProductActionType.Purchase,ProductList:Array.isArray(d)?d:[d]},a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logPromotionEvent=function(c,d,e,f,g){var h=a._Ecommerce.createCommerceEventObject(f);h&&(h.EventName+=a._Ecommerce.getPromotionActionEventName(c),h.EventCategory=a._Ecommerce.convertPromotionActionToEventType(c),h.PromotionAction={PromotionActionType:c,PromotionList:Array.isArray(d)?d:[d]},b.logCommerceEvent(h,e,g));},this.logImpressionEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(e);g&&(g.EventName+="Impression",g.EventCategory=Types.CommerceEventType.ProductImpression,!Array.isArray(c)&&(c=[c]),g.ProductImpressions=[],c.forEach(function(a){g.ProductImpressions.push({ProductImpressionList:a.Name,ProductList:Array.isArray(a.Product)?a.Product:[a.Product]});}),b.logCommerceEvent(g,d,f));},this.logCommerceEvent=function(b,c,d){// If a developer typos the ProductActionType, the event category will be
|
|
1002
|
-
// null, resulting in kit forwarding errors on the server.
|
|
1003
|
-
// The check for `ProductAction` is required to denote that these are
|
|
1004
|
-
// ProductAction events, and not impression or promotions
|
|
1005
|
-
if(a.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent),b.ProductAction&&null===b.EventCategory)return void a.Logger.error("Commerce event not sent. The mParticle.ProductActionType you passed was invalid. Re-check your code.");var e=a._Helpers.sanitizeAttributes(c,b.EventName);a._Helpers.canLog()?(e&&(b.EventAttributes=e),b.ProductAction&&a._Ecommerce.calculateProductActionTotalAmount(b.ProductAction),a._APIClient.sendEventToServer(b,d),a._Persistence.update()):a.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent);},this.addEventHandler=function(c,d,f,g,h){var j,e=[],k=function handler(c,d){var e=function timeoutHandler(){d.href?window.location.href=d.href:d.submit&&d.submit();};a.Logger.verbose("DOM event triggered, handling event"),b.logEvent({messageType:Types.MessageType.PageEvent,name:"function"==typeof f?f(d):f,data:"function"==typeof g?g(d):g,eventType:h||Types.EventType.Other}),(d.href&&"_blank"!==d.target||d.submit)&&(c.preventDefault?c.preventDefault():c.returnValue=!1,setTimeout(e,a._Store.SDKConfig.timeout));};if(!d)return void a.Logger.error("Can't bind event, selector is required");// Handle a css selector string or a dom element
|
|
1006
|
-
if("string"==typeof d?e=document.querySelectorAll(d):d.nodeType&&(e=[d]),e.length){a.Logger.verbose("Found "+e.length+" element"+(1<e.length?"s":"")+", attaching event handlers");var l=function _loop_1(){var a=e[j],b=function elementHandler(b){k(b,a);};a.addEventListener?a.addEventListener(c,b,!1):a.attachEvent?a.attachEvent("on"+c,b):a["on"+c]=b;};for(j=0;j<e.length;j++)l();}else a.Logger.verbose("No elements found");};}
|
|
1007
|
-
|
|
1008
|
-
function isAttributeKeyAllowed(a,b){return !(null!==a&&void 0!==a)||!a.isAttributeKeyBlocked(b)}function isIdentityAllowed(a,b){return !(null!==a&&void 0!==a)||!a.isIdentityBlocked(b)}function copyUserAttributeValue(a){return Array.isArray(a)?a.slice():a}function buildUserAttributesCopy(a,b){var c={};if(!a)return c;for(var d in a)hasOwnProp(a,d)&&!isReservedStoredPropertyName(d)&&isAttributeKeyAllowed(b,d)&&(c[d]=copyUserAttributeValue(a[d]));return c}function buildUserAttributeLists(a,b){var c={};for(var d in a)hasOwnProp(a,d)&&!isReservedStoredPropertyName(d)&&Array.isArray(a[d])&&isAttributeKeyAllowed(b,d)&&(c[d]=a[d].slice());return c}function buildFilteredUserIdentities(a,b){var c={},d=a;for(var e in d)if(hasOwnProp(d,e)){var f=getIdentityTypeFromStoredKey(e);// Must be `=== null`: IdentityType.Other is 0, so a falsy check would
|
|
1009
|
-
// drop a valid stored Other identity.
|
|
1010
|
-
if(null!==f){var g=Types.IdentityType.getIdentityName(f);isIdentityAllowed(b,g)&&(c[g]=d[e]);}}return c}function filteredMparticleUser(a,b,c,d){function e(){var e=buildUserAttributesCopy(c._Store.getUserAttributes(a),d);return c._Helpers.filterUserAttributes(e,b.userAttributeFilters)}return {getUserIdentities:function getUserIdentities(){var e=buildFilteredUserIdentities(c._Store.getUserIdentities(a),d);return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b=buildUserAttributeLists(e(),d);return c._Helpers.filterUserAttributes(b,a.userAttributeFilters)},getAllUserAttributes:e}}
|
|
1011
|
-
|
|
1012
|
-
var FORWARDING_RULE_MESSAGE_TYPES=[Types.MessageType.PageEvent,Types.MessageType.PageView,Types.MessageType.Commerce];function inFilteredList(a,b){return !!(a&&a.length)&&inArray(a,b)}function isBlockedByForwardingRule(a,b,c){if(!FORWARDING_RULE_MESSAGE_TYPES.includes(a)||!c.filteringEventAttributeValue||!c.filteringEventAttributeValue.eventAttributeName||!c.filteringEventAttributeValue.eventAttributeValue)return !1;var d=null;if(b)for(var e in b)if(b.hasOwnProperty(e)){var f=KitFilterHelper.hashAttributeConditionalForwarding(e);if(f===c.filteringEventAttributeValue.eventAttributeName){d={name:f,value:KitFilterHelper.hashAttributeConditionalForwarding(b[e])};break}}var g=null!==d&&d.value===c.filteringEventAttributeValue.eventAttributeValue,h=!0===c.filteringEventAttributeValue.includeOnMatch?g:!g;return !h}function isBlockedByEventFilter(a,b,c,d){if(a===Types.MessageType.PageEvent&&(inFilteredList(d.eventNameFilters,b)||inFilteredList(d.eventTypeFilters,c)))return !0;return !!(a===Types.MessageType.Commerce&&inFilteredList(d.eventTypeFilters,c))||!!(a===Types.MessageType.PageView&&inFilteredList(d.screenNameFilters,b))}function filterEventAttributes(a,b,c,d,e){if(!d)return d;var f;if(a===Types.MessageType.PageEvent?f=e.attributeFilters:a===Types.MessageType.PageView&&(f=e.screenAttributeFilters),!f)return d;var g={};for(var h in d)if(d.hasOwnProperty(h)){var i=KitFilterHelper.hashEventAttributeKey(b,c,h);inArray(f,i)||(g[h]=d[h]);}return g}function filterUserIdentities(a,b){return a&&a.length?a.filter(function(a){return !inArray(b,KitFilterHelper.hashUserIdentity(a.Type))}):a||[]}
|
|
1013
|
-
|
|
1014
|
-
var _a;var _b=Constants.IdentityMethods,Modify$2=_b.Modify,Identify$1=_b.Identify,Login$1=_b.Login,Logout$1=_b.Logout,identityCompleteKitMethods=(_a={},_a[Identify$1]="onIdentifyComplete",_a[Login$1]="onLoginComplete",_a[Logout$1]="onLogoutComplete",_a[Modify$2]="onModifyComplete",_a);// Maps an identity method to the kit callback that reports its completion.
|
|
1015
|
-
function removeBlockedUserIdentities(a,b){var c=a,d={};for(var e in c)c.hasOwnProperty(e)&&isIdentityAllowed(b,e)&&(d[e]=c[e]);return d}function userAttributesMatchFilter(a,b){for(var c in a)if(hasOwnProp(a,c)){var d=KitFilterHelper.hashAttributeConditionalForwarding(c),e=KitFilterHelper.hashAttributeConditionalForwarding(a[c]);if(d===b.userAttributeName&&e===b.userAttributeValue)return !0}return !1}function Forwarders(a,b){var c=this,d=this;this.forwarderStatsUploader=new APIClient(a,b).initializeForwarderStatsUploader();var e={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// TODO: https://go.mparticle.com/work/SQDSDKS-6036
|
|
1016
|
-
// Processing forwarders is a 2 step process:
|
|
1017
|
-
// 1. Configure the kit
|
|
1018
|
-
// 2. Initialize the kit
|
|
1019
|
-
// There are 2 types of kits:
|
|
1020
|
-
// 1. UI-enabled kits
|
|
1021
|
-
// 2. Sideloaded kits.
|
|
1022
|
-
// These are kits that are enabled via the mParticle UI.
|
|
1023
|
-
// A kit that is UI-enabled will have a kit configuration that returns from
|
|
1024
|
-
// the server, or in rare cases, is passed in by the developer.
|
|
1025
|
-
// The kit configuration will be compared with the kit constructors to determine
|
|
1026
|
-
// if there is a match before being initialized.
|
|
1027
|
-
// Only kits that are configured properly can be active and used for kit forwarding.
|
|
1028
|
-
// Unlike UI enabled kits, sideloaded kits are always added to active forwarders.
|
|
1029
|
-
// TODO: Sideloading kits currently require the use of a register method
|
|
1030
|
-
// which requires an object on which to be registered.
|
|
1031
|
-
// In the future, when all kits are moved to the mpConfig rather than
|
|
1032
|
-
// there being a separate process for MP configured kits and
|
|
1033
|
-
// sideloaded kits, this will need to be refactored.
|
|
1034
|
-
// kits can be included via mParticle UI, or via sideloaded kit config API
|
|
1035
|
-
this.initForwarders=function(c,e){var f=a.Identity.getCurrentUser();if(!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders){var g=removeBlockedUserIdentities(c,b);// Some js libraries require that they be loaded first, or last, etc
|
|
1036
|
-
a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(c){if(!a._Consent.isEnabledForUserConsent(c.filteringConsentRuleValues,f))return !1;if(!d.isEnabledForUserAttributes(c.filteringUserAttributeValue,f))return !1;if(!d.isEnabledForUnknownUser(c.excludeAnonymousUser,f))return !1;var h=a._Helpers.filterUserIdentities(g,c.userIdentityFilters),i=f?filteredMparticleUser(f.getMPID(),c,a,b).getAllUserAttributes():{};return c.initialized||(c.logger=a.Logger,c.init(c.settings,e,!1,null,i,h,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),c.initialized=!0),!0});}},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;if(!c)return !1;var d=c.getAllUserAttributes();try{var e=d&&a._Helpers.isObject(d)&&0<Object.keys(d).length,f=!!e&&userAttributesMatchFilter(d,b);return b.includeOnMatch===f}catch(a){// in any error scenario, err on side of returning true and forwarding event
|
|
1037
|
-
return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){if(!a._Store.webviewBridgeEnabled&&a._Store.activeForwarders){// Not for...of: the downleveled loop is miscompiled in cjs/esm builds.
|
|
1038
|
-
var c=KitFilterHelper.hashEventName(b.EventName,b.EventCategory),d=KitFilterHelper.hashEventType(b.EventCategory),e=function(e){if(!isBlockedByForwardingRule(b.EventDataType,b.EventAttributes,e)){// Clone the event object, as we could be sending different attributes to each forwarder
|
|
1039
|
-
var f=extend(!0,{},b);if(!isBlockedByEventFilter(b.EventDataType,c,d,e)&&(f.EventAttributes=filterEventAttributes(b.EventDataType,b.EventCategory,b.EventName,f.EventAttributes,e),f.UserIdentities=filterUserIdentities(f.UserIdentities,e.userIdentityFilters),f.UserAttributes=KitFilterHelper.filterUserAttributes(f.UserAttributes,e.userAttributeFilters),!!e.process)){a.Logger.verbose("Sending message to forwarder: "+e.name);var g=e.process(f);g&&a.Logger.verbose(g);}}};a._Store.activeForwarders.forEach(function(a){e(a);});}},this.handleForwarderUserAttributes=function(c,d,f){b&&b.isAttributeKeyBlocked(d)||!a._Store.activeForwarders.length||a._Store.activeForwarders.forEach(function(b){var g=b[c];if(g&&!KitFilterHelper.isFilteredUserAttribute(d,b.userAttributeFilters))try{var h;c===e.setUserAttribute?h=b.setUserAttribute(d,f):c===e.removeUserAttribute&&(h=b.removeUserAttribute(d)),h&&a.Logger.verbose(h);}catch(b){a.Logger.error(b);}});},this.setForwarderUserIdentities=function(c){var d=removeBlockedUserIdentities(c,b);a._Store.activeForwarders.forEach(function(b){var c=a._Helpers.filterUserIdentities(d,b.userIdentityFilters);b.setUserIdentity&&c.forEach(function(c){var d=b.setUserIdentity(c.Identity,c.Type);d&&a.Logger.verbose(d);});});},this.setForwarderOnUserIdentified=function(c){a._Store.activeForwarders.forEach(function(d){var e=filteredMparticleUser(c.getMPID(),d,a,b);if(d.onUserIdentified){var f=d.onUserIdentified(e);f&&a.Logger.verbose(f);}});},this.setForwarderOnIdentityComplete=function(c,d){var e=identityCompleteKitMethods[d];e&&a._Store.activeForwarders.forEach(function(d){var f=d[e];if(f){var g=filteredMparticleUser(c.getMPID(),d,a,b),h=f.call(d,g,g.getUserIdentities());h&&a.Logger.verbose(h);}});},this.getForwarderStatsQueue=function(){return a._Persistence.forwardingStatsBatches.forwardingStatsEventQueue},this.setForwarderStatsQueue=function(b){a._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=b;},this.processForwarders=function(b,c){b?(this.processUIEnabledKits(b),this.processSideloadedKits(b),d.initForwarders(a._Store.SDKConfig.identifyRequest.userIdentities,c)):a.Logger.warning("No config was passed. Cannot process forwarders");},this.processUIEnabledKits=function(b){var c=this.returnKitConstructors();try{Array.isArray(b.kitConfigs)&&b.kitConfigs.length&&b.kitConfigs.forEach(function(a){d.configureUIEnabledKit(a,c);});}catch(b){a.Logger.error("MP Kits not configured propertly. Kits may not be initialized. "+b);}},this.returnKitConstructors=function(){var b={};// If there are kits inside of mpInstance._Store.SDKConfig.kits, then mParticle is self hosted
|
|
1040
|
-
return isEmpty(a._Store.SDKConfig.kits)?!isEmpty(a._preInit.forwarderConstructors)&&a._preInit.forwarderConstructors.forEach(function(a){// A suffix is added to a kitConstructor and kit config if there are multiple different
|
|
1041
|
-
// versions of a client kit. This matches the suffix in the DB. As an example
|
|
1042
|
-
// the GA4 kit has a client kit and a server side kit which has a client side
|
|
1043
|
-
// component. They share the same name/module ID in the DB, so we include a
|
|
1044
|
-
// suffix to distinguish them in the kits object.
|
|
1045
|
-
// If a customer wanted simultaneous GA4 client and server connections,
|
|
1046
|
-
// a suffix allows the SDK to distinguish the two.
|
|
1047
|
-
if(a.suffix){var c="".concat(a.name,"-").concat(a.suffix);b[c]=a;}else b[a.name]=a;}):b=a._Store.SDKConfig.kits,b},this.configureUIEnabledKit=function(b,c){var d=null,e=b;for(var f in c){// Configs are returned with suffixes also. We need to consider the
|
|
1048
|
-
// config suffix here to match the constructor suffix
|
|
1049
|
-
var g=void 0;if(e.suffix&&(g="".concat(e.name,"-").concat(e.suffix)),(f===g||f===e.name)&&(e.isDebug===a._Store.SDKConfig.isDevelopmentMode||e.isSandbox===a._Store.SDKConfig.isDevelopmentMode)){d=this.returnConfiguredKit(c[f],e),a._Store.configuredForwarders.push(d);break}}},this.processSideloadedKits=function(b){try{if(Array.isArray(b.sideloadedKits)){var c={kits:{}},e=b.sideloadedKits;// Then configure each registered kit
|
|
1050
|
-
for(var f in e.forEach(function(a){try{a.kitInstance.register(c);var b=a.kitInstance.name;// Then add the kit filters to each registered kit.
|
|
1051
|
-
c.kits[b].filters=a.filterDictionary;}catch(b){console.error("Error registering sideloaded kit "+a.kitInstance.name);}}),c.kits){var g=c.kits[f];d.configureSideloadedKit(g);}// If Sideloaded Kits are successfully registered,
|
|
1052
|
-
// record this in the Store.
|
|
1053
|
-
if(!isEmpty(c.kits)){var h=Object.keys(c.kits);a._Store.sideloadedKitsCount=h.length;}}}catch(b){a.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. "+b);}},this.configureSideloadedKit=function(b){a._Store.configuredForwarders.push(this.returnConfiguredKit(b,b.filters));},this.returnConfiguredKit=function(a,b){void 0===b&&(b={});var c=new a.constructor;return c.id=b.moduleId,c.isSandbox=b.isDebug||b.isSandbox,c.hasSandbox="true"===b.hasDebugString,c.isVisible=b.isVisible||!0,c.settings=b.settings||{},c.eventNameFilters=b.eventNameFilters||[],c.eventTypeFilters=b.eventTypeFilters||[],c.attributeFilters=b.attributeFilters||[],c.screenNameFilters=b.screenNameFilters||[],c.screenAttributeFilters=b.screenAttributeFilters||[],c.userIdentityFilters=b.userIdentityFilters||[],c.userAttributeFilters=b.userAttributeFilters||[],c.filteringEventAttributeValue=b.filteringEventAttributeValue||{},c.filteringUserAttributeValue=b.filteringUserAttributeValue||{},c.eventSubscriptionId=b.eventSubscriptionId||null,c.filteringConsentRuleValues=b.filteringConsentRuleValues||{},c.excludeAnonymousUser=b.excludeAnonymousUser||!1,c},this.configurePixel=function(b){(b.isDebug===a._Store.SDKConfig.isDevelopmentMode||b.isProduction!==a._Store.SDKConfig.isDevelopmentMode)&&a._Store.pixelConfigurations.push(b);},this.processPixelConfigs=function(b){try{isEmpty(b.pixelConfigs)||b.pixelConfigs.forEach(function(a){d.configurePixel(a);});}catch(b){a.Logger.error("Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. "+b);}},this.sendSingleForwardingStatsToServer=function(b){return __awaiter(c,void 0,void 0,function(){var c,d,e,f;return __generator(this,function(g){switch(g.label){case 0:return c={method:"post",body:JSON.stringify(b),headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"}},[4/*yield*/,this.forwarderStatsUploader.upload(c)];case 1:return d=g.sent(),e=202===d.status?"Successfully sent forwarding stats to mParticle Servers":"Issue with forwarding stats to mParticle Servers, received HTTP Code of "+d.statusText,null===(f=null===a||void 0===a?void 0:a.Logger)||void 0===f?void 0:f.verbose(e),[2/*return*/]}})})};}
|
|
1054
|
-
|
|
1055
|
-
// TODO: This file is no longer the server model because the web SDK payload
|
|
1056
|
-
var MessageType=Types.MessageType,ApplicationTransitionType=Types.ApplicationTransitionType;// TODO: Make this a pure function that returns a new object
|
|
1057
|
-
function convertCustomFlags(a,b){var c=[];for(var d in b.flags={},a.CustomFlags)c=[],a.CustomFlags.hasOwnProperty(d)&&(Array.isArray(a.CustomFlags[d])?a.CustomFlags[d].forEach(function(a){isValidCustomFlagProperty(a)&&c.push(a.toString());}):isValidCustomFlagProperty(a.CustomFlags[d])&&c.push(a.CustomFlags[d].toString()),c.length&&(b.flags[d]=c));}function convertProductToV2DTO(a){return {id:parseStringOrNumber(a.Sku),nm:parseStringOrNumber(a.Name),pr:parseNumber(a.Price),qt:parseNumber(a.Quantity),br:parseStringOrNumber(a.Brand),va:parseStringOrNumber(a.Variant),ca:parseStringOrNumber(a.Category),ps:parseNumber(a.Position),cc:parseStringOrNumber(a.CouponCode),tpa:parseNumber(a.TotalAmount),attrs:a.Attributes}}function convertProductListToV2DTO(a){return a?a.map(function(a){return convertProductToV2DTO(a)}):[]}function ServerModel(a){var b=this;this.convertToConsentStateV2DTO=function(a){if(!a)return null;var b={},c=a.getGDPRConsentState();if(c){var d={};for(var e in b.gdpr=d,c)if(c.hasOwnProperty(e)){var f=c[e];b.gdpr[e]={},"boolean"==typeof f.Consented&&(d[e].c=f.Consented),"number"==typeof f.Timestamp&&(d[e].ts=f.Timestamp),"string"==typeof f.ConsentDocument&&(d[e].d=f.ConsentDocument),"string"==typeof f.Location&&(d[e].l=f.Location),"string"==typeof f.HardwareId&&(d[e].h=f.HardwareId);}}var g=a.getCCPAConsentState();return g&&(b.ccpa={data_sale_opt_out:{c:g.Consented,ts:g.Timestamp,d:g.ConsentDocument,l:g.Location,h:g.HardwareId}}),b},this.createEventObject=function(b,c){var d,e,f,g={},h={},i=b.messageType===Types.MessageType.OptOut?!a._Store.isEnabled:null;// The `optOut` variable is passed later in this method to the `uploadObject`
|
|
1058
|
-
// so that it can be used to denote whether or not a user has "opted out" of being
|
|
1059
|
-
// tracked. If this is an `optOut` Event, we set `optOut` to the inverse of the SDK's
|
|
1060
|
-
// `isEnabled` boolean which is controlled via `MPInstanceManager.setOptOut`.
|
|
1061
|
-
// TODO: Why is Webview Bridge Enabled or Opt Out necessary here?
|
|
1062
|
-
if(a._Store.sessionId||b.messageType===Types.MessageType.OptOut||a._Store.webviewBridgeEnabled){var j=__assign({},b.customFlags),k=a._Store.integrationAttributes,l=a._Helpers.getFeatureFlag;// https://go.mparticle.com/work/SQDSDKS-5053
|
|
1063
|
-
// https://go.mparticle.com/work/SQDSDKS-7639
|
|
1064
|
-
if(isIntegrationCaptureEnabled(l)){a._IntegrationCapture.capture();var m=a._IntegrationCapture.getClickIdsAsCustomFlags();j=__assign(__assign({},m),j);var n=a._IntegrationCapture.getClickIdsAsIntegrationAttributes();k=__assign(__assign({},n),k);}h=b.hasOwnProperty("toEventAPIObject")?b.toEventAPIObject():{// This is an artifact from v2 events where SessionStart/End and AST event
|
|
1065
|
-
// names are numbers (1, 2, or 10), but going forward with v3, these lifecycle
|
|
1066
|
-
// events do not have names, but are denoted by their `event_type`
|
|
1067
|
-
EventName:b.name||b.messageType+"",EventCategory:b.eventType,EventAttributes:a._Helpers.sanitizeAttributes(b.data,b.name),ActiveTimeOnSite:null===(d=a._timeOnSiteTimer)||void 0===d?void 0:d.getTimeInForeground(),TotalTimeOnSite:null===(f=(e=a._Store).getTotalTimeOnSite)||void 0===f?void 0:f.call(e),PageUrl:cleanPageHref()||null,SourceMessageId:b.sourceMessageId||a._Helpers.generateUniqueId(),EventDataType:b.messageType,CustomFlags:j,UserAttributeChanges:b.userAttributeChanges,UserIdentityChanges:b.userIdentityChanges},b.messageType!==Types.MessageType.SessionEnd&&(a._Store.dateLastEventSent=new Date),g={// FIXME: Deprecate when we get rid of V2
|
|
1068
|
-
Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store.sessionId,SessionStartDate:a._Store.sessionStartDate?a._Store.sessionStartDate.getTime():0,Debug:a._Store.SDKConfig.isDevelopmentMode,Location:a._Store.currentPosition,OptOut:i,ExpandedEventCount:0,AppVersion:a.getAppVersion(),AppName:a.getAppName(),Package:a._Store.SDKConfig["package"],ClientGeneratedId:a._Store.clientId,DeviceId:a._Store.deviceId,IntegrationAttributes:k,CurrencyCode:a._Store.currencyCode,DataPlan:a._Store.SDKConfig.dataPlan?a._Store.SDKConfig.dataPlan:{}},h.EventDataType===MessageType.AppStateTransition&&(h.IsFirstRun=a._Store.isFirstRun,h.LaunchReferral=cleanPageHref()||null),h.CurrencyCode=a._Store.currencyCode;var o=c||a.Identity.getCurrentUser();return appendUserInfo(o,h),b.messageType===Types.MessageType.SessionEnd&&(h.SessionLength=a._Store.dateLastEventSent.getTime()-a._Store.sessionStartDate.getTime(),h.currentSessionMPIDs=a._Store.currentSessionMPIDs,h.EventAttributes=a._Store.sessionAttributes,a._Store.currentSessionMPIDs=[],a._Store.sessionStartDate=null),g.Timestamp=a._Store.dateLastEventSent.getTime(),extend({},h,g)}return null},this.convertEventToV2DTO=function(c){var d={n:c.EventName,et:c.EventCategory,ua:c.UserAttributes,ui:c.UserIdentities,ia:c.IntegrationAttributes,str:c.Store,attrs:c.EventAttributes,sdk:c.SDKVersion,sid:c.SessionId,sl:c.SessionLength,ssd:c.SessionStartDate,dt:c.EventDataType,dbg:c.Debug,ct:c.Timestamp,lc:c.Location,o:c.OptOut,eec:c.ExpandedEventCount,av:c.AppVersion,cgid:c.ClientGeneratedId,das:c.DeviceId,mpid:c.MPID,smpids:c.currentSessionMPIDs};c.DataPlan&&c.DataPlan.PlanId&&(d.dp_id=c.DataPlan.PlanId,c.DataPlan.PlanVersion&&(d.dp_v=c.DataPlan.PlanVersion));var e=b.convertToConsentStateV2DTO(c.ConsentState);return e&&(d.con=e),c.EventDataType===MessageType.AppStateTransition&&(d.fr=c.IsFirstRun,d.iu=!1,d.at=ApplicationTransitionType.AppInit,d.lr=c.LaunchReferral,d.attrs=null),c.CustomFlags&&convertCustomFlags(c,d),c.EventDataType===MessageType.Commerce?(d.cu=c.CurrencyCode,c.ProductAction?d.pd={an:c.ProductAction.ProductActionType,cs:a._Helpers.parseNumber(c.ProductAction.CheckoutStep),co:c.ProductAction.CheckoutOptions,pl:convertProductListToV2DTO(c.ProductAction.ProductList),ti:c.ProductAction.TransactionId,ta:c.ProductAction.Affiliation,tcc:c.ProductAction.CouponCode,tr:a._Helpers.parseNumber(c.ProductAction.TotalAmount),ts:a._Helpers.parseNumber(c.ProductAction.ShippingAmount),tt:a._Helpers.parseNumber(c.ProductAction.TaxAmount)}:c.PromotionAction?d.pm={an:c.PromotionAction.PromotionActionType,pl:c.PromotionAction.PromotionList.map(function(a){return {id:a.Id,nm:a.Name,cr:a.Creative,ps:a.Position?a.Position:0}})}:c.ProductImpressions&&(d.pi=c.ProductImpressions.map(function(a){return {pil:a.ProductImpressionList,pl:convertProductListToV2DTO(a.ProductList)}}))):c.EventDataType===MessageType.Profile&&(d.pet=c.ProfileMessageType),d};}
|
|
1069
|
-
|
|
1070
|
-
function forwardingStatsUploader(a){function b(){var b=a._Forwarders.getForwarderStatsQueue(),c=a._Persistence.forwardingStatsBatches.uploadsTable,d=Date.now();for(var e in b.length&&(c[d]={uploading:!1,data:b},a._Forwarders.setForwarderStatsQueue([])),c)(function(b){if(c.hasOwnProperty(b)&&!1===c[b].uploading){var d=function(){4===e.readyState&&(200===e.status||202===e.status?(a.Logger.verbose("Successfully sent "+e.statusText+" from server"),delete c[b]):"4"===e.status.toString()[0]?429!==e.status&&delete c[b]:c[b].uploading=!1);},e=a._Helpers.createXHR(d),f=c[b].data;c[b].uploading=!0,a._APIClient.sendBatchForwardingStatsToServer(f,e);}})(e);}this.startForwardingStatsTimer=function(){window.mParticle._forwardingStatsTimer=setInterval(function(){b();},a._Store.SDKConfig.forwarderStatsTimeout);};}
|
|
1071
|
-
|
|
1072
|
-
var AudienceManager=/** @class */function(){function a(a,b,c){this.url="",this.logger=c,this.url="https://".concat(a).concat(b,"/audience"),this.userAudienceAPI=window.fetch?new FetchUploader(this.url):new XHRUploader(this.url);}return a.prototype.sendGetUserAudienceRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c,d,e,f,g,h;return __generator(this,function(i){switch(i.label){case 0:this.logger.verbose("Fetching user audiences from server"),c={method:"GET",headers:{Accept:"*/*"}},d="".concat(this.url,"?mpid=").concat(a),i.label=1;case 1:return i.trys.push([1,6,,7]),[4/*yield*/,this.userAudienceAPI.upload(c,d)];case 2:return (e=i.sent(),!(200<=e.status&&300>e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate.
|
|
1073
|
-
throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}();
|
|
1074
|
-
|
|
1075
|
-
var processReadyQueue=function(a,b){if(isEmpty(a))return [];// Without draining first, sync re-entry (cache-hit identify \u2192
|
|
1076
|
-
// parseIdentityResponse \u2192 processReadyQueue) re-iterates the same array:
|
|
1077
|
-
// callers only replace `_preInit.readyQueue` with [] after we return, so the
|
|
1078
|
-
// nested call still sees every entry. That duplicates Identity/event calls
|
|
1079
|
-
// and can nest "Unable to compute proper mParticle function" wraps.
|
|
1080
|
-
// Splice the queue empty up front so a nested call observes [].
|
|
1081
|
-
var c=a.splice(0,a.length);// Isolate each item so one throw cannot abort the rest of this pass.
|
|
1082
|
-
// Drain-first already removed siblings from the shared queue; without a
|
|
1083
|
-
// per-item catch they would be lost forever when forEach aborts.
|
|
1084
|
-
return c.forEach(function(a){try{isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}catch(a){b.error("Error processing ready queue item: "+getErrorMessage(a));}}),[]};var processPreloadedItem=function(a){// Operate on a copy so processPreloadedItem never mutates the caller's
|
|
1085
|
-
// queued item array (defensive; the queue itself is drained above).
|
|
1086
|
-
var b=a.slice(),c=b.splice(0,1)[0];// Skip malformed queue entries (empty array or non-string method) instead of
|
|
1087
|
-
// throwing an uncaught TypeError from method.split() below.
|
|
1088
|
-
if("string"==typeof c&&0!==c.length)// if the first argument is a method on the base mParticle object, run it
|
|
1089
|
-
if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(window.mParticle,b);else {var d=c.split(".");try{// Track both the function and its context
|
|
1090
|
-
for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;h<i.length;h++)// Keep track of the parent object
|
|
1091
|
-
e=i[h],g=f,f=f[e];// Apply the function with its proper context
|
|
1092
|
-
f.apply(g,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}};
|
|
1093
|
-
|
|
1094
|
-
var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,FeatureFlags$1=Constants.FeatureFlags,IdentityMethods$1=Constants.IdentityMethods,ErrorMessages=Messages$2.ErrorMessages,CacheIdentity=FeatureFlags$1.CacheIdentity,Identify=IdentityMethods$1.Identify,Modify$1=IdentityMethods$1.Modify,Login=IdentityMethods$1.Login,Logout=IdentityMethods$1.Logout;function Identity(a){var b=a._Helpers,c=b.getFeatureFlag,d=b.extend,e=this;// https://go.mparticle.com/work/SQDSDKS-6353
|
|
1095
|
-
/**
|
|
1096
|
-
* Invoke these methods on the mParticle.Identity object.
|
|
1097
|
-
* Example: mParticle.Identity.getCurrentUser().
|
|
1098
|
-
* @class mParticle.Identity
|
|
1099
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-6354
|
|
1100
|
-
/**
|
|
1101
|
-
* Invoke these methods on the mParticle.Identity.getCurrentUser() object.
|
|
1102
|
-
* Example: mParticle.Identity.getCurrentUser().getAllUserAttributes()
|
|
1103
|
-
* @class mParticle.Identity.getCurrentUser()
|
|
1104
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-6355
|
|
1105
|
-
// send a user identity change request on identify, login, logout, modify when any values change.
|
|
1106
|
-
// compare what identities exist vs what is previously was for the specific user if they were in memory before.
|
|
1107
|
-
// if it's the first time the user is logging in, send a user identity change request with
|
|
1108
|
-
this.idCache=null,this.audienceManager=null,this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(b,c,d){a.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent+": "+d);// First, remove any falsy identity values and warn about them
|
|
1109
|
-
var e=a._Helpers.Validators.removeFalsyIdentityValues(b,a.Logger),f=(null===e||void 0===e?void 0:e.userIdentities)?__assign(__assign({},e),{userIdentities:normalizeUserIdentityKeys(e.userIdentities)}):e,g=a._Helpers.Validators.validateIdentities(f,d);// Normalize convenience aliases (email_sha256 \u2192 other, mobile_sha256 \u2192 other2)
|
|
1110
|
-
if(!g.valid)return a.Logger.error("ERROR: "+g.error),{valid:!1,error:g.error};if(c&&!a._Helpers.Validators.isFunction(c)){var h="The optional callback must be a function. You tried entering a(n) "+_typeof(c);return a.Logger.error(h),{valid:!1,error:h}}return {valid:!0,cleanedIdentities:f}},createIdentityRequest:function createIdentityRequest(b,c,d,e,f,g,h){var i={client_sdk:{platform:c,sdk_vendor:d,sdk_version:e},context:g,environment:a._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:a._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),previous_mpid:h||null,known_identities:createKnownIdentities(b,f)};return i},createModifyIdentityRequest:function createModifyIdentityRequest(b,c,d,e,f,g){return {client_sdk:{platform:d,sdk_vendor:e,sdk_version:f},context:g,environment:a._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:a._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),identity_changes:this.createIdentityChanges(b,c)}},createIdentityChanges:function createIdentityChanges(a,b){var c=[];if(b&&isObject(b)&&a&&isObject(a))for(var d in b)c.push({old_value:a[d]||null,new_value:b[d],identity_type:d});return c},// takes 2 UI objects keyed by name, combines them, returns them keyed by type
|
|
1111
|
-
combineUserIdentities:function combineUserIdentities(a,b){var c={},e=d({},a,b);for(var f in e){var g=Types.IdentityType.getIdentityType(f);// this check removes anything that is not whitelisted as an identity type
|
|
1112
|
-
!1!==g&&0<=g&&(c[Types.IdentityType.getIdentityType(f)]=e[f]);}return c},createAliasNetworkRequest:function createAliasNetworkRequest(b){return {request_id:a._Helpers.generateUniqueId(),request_type:"alias",environment:a._Store.SDKConfig.isDevelopmentMode?"development":"production",api_key:a._Store.devToken,data:{destination_mpid:b.destinationMpid,source_mpid:b.sourceMpid,start_unixtime_ms:b.startTime,end_unixtime_ms:b.endTime,scope:b.scope,device_application_stamp:a._Store.deviceId}}},convertAliasToNative:function convertAliasToNative(a){return {DestinationMpid:a.destinationMpid,SourceMpid:a.sourceMpid,StartUnixtimeMs:a.startTime,EndUnixtimeMs:a.endTime,Scope:a.scope}},convertToNative:function convertToNative(a){var b=[];if(null===a||void 0===a?void 0:a.userIdentities){for(var c in a.userIdentities)a.userIdentities.hasOwnProperty(c)&&b.push({Type:Types.IdentityType.getIdentityType(c),Identity:a.userIdentities[c]});return {UserIdentities:b}}}},this.IdentityAPI={HTTPCodes:HTTPCodes$2,/**
|
|
1113
|
-
* Initiate a logout request to the mParticle server
|
|
1114
|
-
* @method identify
|
|
1115
|
-
* @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)
|
|
1116
|
-
* @param {Function} [callback] A callback function that is called when the identify request completes
|
|
1117
|
-
*/identify:function identify(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1118
|
-
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Identify);if(f&&(d=f.getMPID()),g.valid){var h=a._Identity.IdentityRequest.createIdentityRequest(g.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.deviceId,a._Store.context,d);if(a._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var i=tryCacheIdentity(h.known_identities,e.idCache,e.parseIdentityResponse,d,c,b,Identify);if(i)return}a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Identify request sent to native sdk")):a._IdentityAPIClient.sendIdentityRequest(h,Identify,c,b,e.parseIdentityResponse,d,h.known_identities):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1119
|
-
* Initiate a logout request to the mParticle server
|
|
1120
|
-
* @method logout
|
|
1121
|
-
* @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)
|
|
1122
|
-
* @param {Function} [callback] A callback function that is called when the logout request completes
|
|
1123
|
-
*/logout:function logout(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1124
|
-
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Logout);if(f&&(d=f.getMPID()),g.valid){var h,i=a._Identity.IdentityRequest.createIdentityRequest(g.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.deviceId,a._Store.context,d);a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Logout request sent to native sdk")):(a._IdentityAPIClient.sendIdentityRequest(i,Logout,c,b,e.parseIdentityResponse,d),h=a._ServerModel.createEventObject({messageType:Types.MessageType.Profile}),h.ProfileMessageType=Types.ProfileMessageType.Logout,a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(a){var b=a;b.logOut&&b.logOut(h);})):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1125
|
-
* Initiate a login request to the mParticle server
|
|
1126
|
-
* @method login
|
|
1127
|
-
* @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)
|
|
1128
|
-
* @param {Function} [callback] A callback function that is called when the login request completes
|
|
1129
|
-
*/login:function login(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1130
|
-
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Login);if(f&&(d=f.getMPID()),g.valid){var h=a._Identity.IdentityRequest.createIdentityRequest(g.cleanedIdentities,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.deviceId,a._Store.context,d);if(a._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var i=tryCacheIdentity(h.known_identities,e.idCache,e.parseIdentityResponse,d,c,b,Login);if(i)return}a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Login request sent to native sdk")):a._IdentityAPIClient.sendIdentityRequest(h,Login,c,b,e.parseIdentityResponse,d,h.known_identities):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1131
|
-
* Initiate a modify request to the mParticle server
|
|
1132
|
-
* @method modify
|
|
1133
|
-
* @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)
|
|
1134
|
-
* @param {Function} [callback] A callback function that is called when the modify request completes
|
|
1135
|
-
*/modify:function modify(b,c){// https://go.mparticle.com/work/SQDSDKS-6337
|
|
1136
|
-
var d,f=a.Identity.getCurrentUser(),g=a._Identity.IdentityRequest.preProcessIdentityRequest(b,c,Modify$1);if(f&&(d=f.getMPID()),g.valid){var h=(null===b||void 0===b?void 0:b.userIdentities)?g.cleanedIdentities.userIdentities:{},i=a._Identity.IdentityRequest.createModifyIdentityRequest(f?f.getUserIdentities().userIdentities:{},h,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,a._Store.context);a._Helpers.canLog()?a._Store.webviewBridgeEnabled?(a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify,JSON.stringify(a._Identity.IdentityRequest.convertToNative(b))),a._Helpers.invokeCallback(c,HTTPCodes$2.nativeIdentityRequest,"Modify request sent to native sdk")):a._IdentityAPIClient.sendIdentityRequest(i,Modify$1,c,b,e.parseIdentityResponse,d):(a._Helpers.invokeCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),a.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else a._Helpers.invokeCallback(c,HTTPCodes$2.validationIssue,g.error),a.Logger.verbose(g);},/**
|
|
1137
|
-
* Returns a user object with methods to interact with the current user
|
|
1138
|
-
* @method getCurrentUser
|
|
1139
|
-
* @return {Object} the current user object
|
|
1140
|
-
*/getCurrentUser:function getCurrentUser(){var b;return a._Store?(b=a._Store.mpid,b?(b=a._Store.mpid.slice(),e.mParticleUser(b,a._Store.isLoggedIn)):a._Store.webviewBridgeEnabled?e.mParticleUser():null):null},/**
|
|
1141
|
-
* Returns a the user object associated with the mpid parameter or 'null' if no such
|
|
1142
|
-
* user exists
|
|
1143
|
-
* @method getUser
|
|
1144
|
-
* @param {String} mpid of the desired user
|
|
1145
|
-
* @return {Object} the user for mpid
|
|
1146
|
-
*/getUser:function getUser(b){var c=a._Persistence.getPersistence();return c?c[b]&&!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(b)?e.mParticleUser(b):null:null},/**
|
|
1147
|
-
* Returns all users, including the current user and all previous users that are stored on the device.
|
|
1148
|
-
* @method getUsers
|
|
1149
|
-
* @return {Array} array of users
|
|
1150
|
-
*/getUsers:function getUsers(){var b=a._Persistence.getPersistence(),c=[];if(b)for(var d in b)Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(d)||c.push(e.mParticleUser(d));return c.sort(function(c,a){var b=c.getLastSeenTime()||0,d=a.getLastSeenTime()||0;return b>d?-1:1}),c},/**
|
|
1151
|
-
* Initiate an alias request to the mParticle server
|
|
1152
|
-
* @method aliasUsers
|
|
1153
|
-
* @param {Object} aliasRequest object representing an AliasRequest
|
|
1154
|
-
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
|
|
1155
|
-
*/aliasUsers:function aliasUsers(b,c){var d;if(b.destinationMpid&&b.sourceMpid||(d=Messages$2.ValidationMessages.AliasMissingMpid),b.destinationMpid===b.sourceMpid&&(d=Messages$2.ValidationMessages.AliasNonUniqueMpid),b.startTime&&b.endTime||(d=Messages$2.ValidationMessages.AliasMissingTime),b.startTime>b.endTime&&(d=Messages$2.ValidationMessages.AliasStartBeforeEndTime),d)return a.Logger.warning(d),void a._Helpers.invokeAliasCallback(c,HTTPCodes$2.validationIssue,d);if(!a._Helpers.canLog())a._Helpers.invokeAliasCallback(c,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),a.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(a._Identity.IdentityRequest.convertAliasToNative(b))),a._Helpers.invokeAliasCallback(c,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {a.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+b.sourceMpid+" -> "+b.destinationMpid);var e=a._Identity.IdentityRequest.createAliasNetworkRequest(b);a._IdentityAPIClient.sendAliasRequest(e,c);}},/**
|
|
1156
|
-
* Search the IDSync Workspace endpoint for a known identity.
|
|
1157
|
-
*
|
|
1158
|
-
* POSTs to mParticle's `/v1/search` endpoint and invokes `callback`
|
|
1159
|
-
* with `{ httpCode, body? }`.
|
|
1160
|
-
*
|
|
1161
|
-
* The `workspaceApiKey` is a workspace-specific API key supplied by
|
|
1162
|
-
* the caller (passed in from a kit's settings). It is intentionally
|
|
1163
|
-
* NOT read from the SDK's own workspace token, so that workspace
|
|
1164
|
-
* searches can be authorised independently of the host SDK's
|
|
1165
|
-
* workspace.
|
|
1166
|
-
*
|
|
1167
|
-
* @method search
|
|
1168
|
-
* @param {String} workspaceApiKey Workspace API key (sent as x-mp-key).
|
|
1169
|
-
* @param {Object} knownIdentities A `UserIdentities` map.
|
|
1170
|
-
* @param {Function} callback Invoked with the `IIdentitySearchResult`.
|
|
1171
|
-
*/search:function search(b,c,d){executeSearchRequest(a,b,c,d);},/**
|
|
1172
|
-
Create a default AliasRequest for 2 MParticleUsers. This will construct the request
|
|
1173
|
-
using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
|
|
1174
|
-
|
|
1175
|
-
In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only
|
|
1176
|
-
be the case if they have not been the current user since this functionality was added, the
|
|
1177
|
-
startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly,
|
|
1178
|
-
if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time
|
|
1179
|
-
|
|
1180
|
-
There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days.
|
|
1181
|
-
If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime.
|
|
1182
|
-
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
|
|
1183
|
-
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
|
|
1184
|
-
validation that the startTime must be less than the endTime
|
|
1185
|
-
*/createAliasRequest:function createAliasRequest(b,c,d){try{if(!c||!b)return a.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var e=b.getFirstSeenTime();e||a.Identity.getUsers().forEach(function(a){a.getFirstSeenTime()&&(!e||a.getFirstSeenTime()<e)&&(e=a.getFirstSeenTime());});var f=new Date().getTime()-1e3*(60*(60*(24*a._Store.SDKConfig.aliasMaxWindow))),g=b.getLastSeenTime()||new Date().getTime();//if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed
|
|
1186
|
-
return e<f&&(e=f,g<e&&a.Logger.warning("Source User has not been seen in the last "+a._Store.SDKConfig.maxAliasWindow+" days, Alias Request will likely fail")),{destinationMpid:c.getMPID(),sourceMpid:b.getMPID(),startTime:e,endTime:g,scope:d||"device"}}catch(b){return a.Logger.error("There was a problem with creating an alias request: "+b),null}}},this.mParticleUser=function(b,c){return {/**
|
|
1187
|
-
* Get user identities for current user
|
|
1188
|
-
* @method getUserIdentities
|
|
1189
|
-
* @return {Object} an object with userIdentities as its key
|
|
1190
|
-
*/getUserIdentities:function getUserIdentities(){var c={},d=a._Store.getUserIdentities(b);for(var e in d)if(hasOwnProp(d,e)){var f=getIdentityTypeFromStoredKey(e);// Must be `=== null`: IdentityType.Other is 0, so a falsy
|
|
1191
|
-
// check would drop a valid stored Other identity.
|
|
1192
|
-
null!==f&&(c[Types.IdentityType.getIdentityName(f)]=d[e]);}return {userIdentities:c}},/**
|
|
1193
|
-
* Get the MPID of the current user
|
|
1194
|
-
* @method getMPID
|
|
1195
|
-
* @return {String} the current user MPID as a string
|
|
1196
|
-
*/getMPID:function getMPID(){return b},/**
|
|
1197
|
-
* Sets a user tag
|
|
1198
|
-
* @method setUserTag
|
|
1199
|
-
* @param {String} tagName
|
|
1200
|
-
*/setUserTag:function setUserTag(b){return a._Helpers.Validators.isValidKeyValue(b)?void this.setUserAttribute(b,null):void a.Logger.error(Messages$2.ErrorMessages.BadKey)},/**
|
|
1201
|
-
* Removes a user tag
|
|
1202
|
-
* @method removeUserTag
|
|
1203
|
-
* @param {String} tagName
|
|
1204
|
-
*/removeUserTag:function removeUserTag(b){return a._Helpers.Validators.isValidKeyValue(b)?void this.removeUserAttribute(b):void a.Logger.error(Messages$2.ErrorMessages.BadKey)},/**
|
|
1205
|
-
* Sets a user attribute
|
|
1206
|
-
* @method setUserAttribute
|
|
1207
|
-
* @param {String} key
|
|
1208
|
-
* @param {String} value
|
|
1209
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-4576
|
|
1210
|
-
// https://go.mparticle.com/work/SQDSDKS-6373
|
|
1211
|
-
setUserAttribute:function setUserAttribute(c,d){if(a._SessionManager.resetSessionTimer(),a._Helpers.canLog()){if(!a._Helpers.Validators.isValidAttributeValue(d))return void a.Logger.error(Messages$2.ErrorMessages.BadAttribute);if(!a._Helpers.Validators.isValidKeyValue(c))return void a.Logger.error(Messages$2.ErrorMessages.BadKey);if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:c,value:d}));else {var f=this.getAllUserAttributes(),g=void 0,h=void 0,i=a._Helpers.findKeyInObject(f,c);i?(h=!1,g=f[i],delete f[i]):h=!0,f[c]=d,a._Store.setUserAttributes(b,f),e.sendUserAttributeChangeEvent(c,d,g,h,!1,this),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats),a._Forwarders.handleForwarderUserAttributes("setUserAttribute",c,d);}}},/**
|
|
1212
|
-
* Set multiple user attributes
|
|
1213
|
-
* @method setUserAttributes
|
|
1214
|
-
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
|
|
1215
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-6373
|
|
1216
|
-
setUserAttributes:function setUserAttributes(b){if(a._SessionManager.resetSessionTimer(),!isObject(b))a.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof(b));else if(a._Helpers.canLog())for(var c in b)b.hasOwnProperty(c)&&this.setUserAttribute(c,b[c]);},/**
|
|
1217
|
-
* Removes a specific user attribute
|
|
1218
|
-
* @method removeUserAttribute
|
|
1219
|
-
* @param {String} key
|
|
1220
|
-
*/removeUserAttribute:function removeUserAttribute(c){var d,f;if(a._SessionManager.resetSessionTimer(),!a._Helpers.Validators.isValidKeyValue(c))return void a.Logger.error(Messages$2.ErrorMessages.BadKey);if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:c,value:null}));else {d=a._Persistence.getPersistence(),f=this.getAllUserAttributes();var g=a._Helpers.findKeyInObject(f,c);g&&(c=g);var h=f[c]?f[c].toString():null;delete f[c],d&&isObject(d[b])&&(d[b].ua=f,a._Persistence.savePersistence(d)),e.sendUserAttributeChangeEvent(c,null,h,!1,!0,this),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats),a._Forwarders.handleForwarderUserAttributes("removeUserAttribute",c,null);}},/**
|
|
1221
|
-
* Sets a list of user attributes
|
|
1222
|
-
* @method setUserAttributeList
|
|
1223
|
-
* @param {String} key
|
|
1224
|
-
* @param {Array} value an array of values
|
|
1225
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-6373
|
|
1226
|
-
setUserAttributeList:function setUserAttributeList(c,d){if(a._SessionManager.resetSessionTimer(),!a._Helpers.Validators.isValidKeyValue(c))return void a.Logger.error(Messages$2.ErrorMessages.BadKey);if(!Array.isArray(d))return void a.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a "+_typeof(d));var f=d.slice();if(a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList,JSON.stringify({key:c,value:f}));else {var g=this.getAllUserAttributes(),h=void 0,j=void 0,k=void 0,l=a._Helpers.findKeyInObject(g,c);// If the new attributeList length is different than the previous, then there is a change event.
|
|
1227
|
-
// Loop through new attributes list, see if they are all in the same index as previous user attributes list
|
|
1228
|
-
// If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value
|
|
1229
|
-
if(l?(j=!1,h=g[l],delete g[l]):j=!0,g[c]=f,a._Store.setUserAttributes(b,g),!h||!Array.isArray(h))k=!0;else if(d.length!==h.length)k=!0;else for(var m=0;m<d.length;m++)if(h[m]!==d[m]){k=!0;break}k&&e.sendUserAttributeChangeEvent(c,d,h,j,!1,this),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats),a._Forwarders.handleForwarderUserAttributes("setUserAttribute",c,f);}},/**
|
|
1230
|
-
* Removes all user attributes
|
|
1231
|
-
* @method removeAllUserAttributes
|
|
1232
|
-
*/removeAllUserAttributes:function removeAllUserAttributes(){var b;if(a._SessionManager.resetSessionTimer(),a._Store.webviewBridgeEnabled)a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(b=this.getAllUserAttributes(),a._Forwarders.initForwarders(e.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats),b)for(var c in b)hasOwnProp(b,c)&&a._Forwarders.handleForwarderUserAttributes("removeUserAttribute",c,null),this.removeUserAttribute(c);},/**
|
|
1233
|
-
* Returns all user attribute keys that have values that are arrays
|
|
1234
|
-
* @method getUserAttributesLists
|
|
1235
|
-
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
|
|
1236
|
-
*/getUserAttributesLists:function getUserAttributesLists(){var a,b={};for(var c in a=this.getAllUserAttributes(),a)hasOwnProp(a,c)&&!isReservedStoredPropertyName(c)&&Array.isArray(a[c])&&(b[c]=a[c].slice());return b},/**
|
|
1237
|
-
* Returns all user attributes
|
|
1238
|
-
* @method getAllUserAttributes
|
|
1239
|
-
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
|
|
1240
|
-
*/getAllUserAttributes:function getAllUserAttributes(){var c=a._Store.getUserAttributes,d={},e=c(b);if(e)for(var f in e)if(hasOwnProp(e,f)&&!isReservedStoredPropertyName(f)){var g=e[f];d[f]=Array.isArray(g)?g.slice():g;}return d},/**
|
|
1241
|
-
* Returns the Consent State stored locally for this user.
|
|
1242
|
-
* @method getConsentState
|
|
1243
|
-
* @return a ConsentState object
|
|
1244
|
-
*/getConsentState:function getConsentState(){return a._Store.getConsentState(b)},/**
|
|
1245
|
-
* Sets the Consent State stored locally for this user.
|
|
1246
|
-
* @method setConsentState
|
|
1247
|
-
* @param {Object} consent state
|
|
1248
|
-
*/setConsentState:function setConsentState(c){a._Store.setConsentState(b,c),a._Forwarders.initForwarders(this.getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats),a._CookieSyncManager.attemptCookieSync(this.getMPID());},isLoggedIn:function isLoggedIn(){return c},getLastSeenTime:function getLastSeenTime(){return a._Persistence.getLastSeenTime(b)},getFirstSeenTime:function getFirstSeenTime(){return a._Persistence.getFirstSeenTime(b)},/**
|
|
1249
|
-
* Get user audiences
|
|
1250
|
-
* @method getuserAudiences
|
|
1251
|
-
* @param {Function} [callback] A callback function that is invoked when the user audience request completes
|
|
1252
|
-
*/ // https://go.mparticle.com/work/SQDSDKS-6436
|
|
1253
|
-
getUserAudiences:function getUserAudiences(c){// user audience API is feature flagged
|
|
1254
|
-
return a._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===e.audienceManager&&(e.audienceManager=new AudienceManager(a._Store.SDKConfig.userAudienceUrl,a._Store.devToken,a.Logger)),e.audienceManager.sendGetUserAudienceRequest(b,c)):void a.Logger.error(ErrorMessages.AudienceAPINotEnabled)}}},this.parseIdentityResponse=function(b,d,f,g,h,i,j){var k,l,m,n,o,p,q=a.Identity.getUser(d),r=q?q.getMPID():null,s=q?q.getUserIdentities().userIdentities:{},t={};a._Store.identityCallInFlight=!1;try{if(a.Logger.verbose("Parsing \""+h+"\" identity response from server"),o=null!==(k=b.responseText)&&void 0!==k?k:null,a._Store.isLoggedIn=(null===o||void 0===o?void 0:o.is_logged_in)||!1,hasMPIDChanged(q,o)&&(a._Store.mpid=o.mpid,q&&a._Persistence.setLastSeenTime(d),n=!a._Persistence.getFirstSeenTime(o.mpid),a._Persistence.setFirstSeenTime(o.mpid)),b.status===HTTP_OK){c(CacheIdentity)&&cacheOrClearIdCache(h,i,e.idCache,b,j);var u=e.IdentityAPI.getUser(o.mpid),v=u?u.getUserIdentities().userIdentities:{};h===Modify$1?(t=a._Identity.IdentityRequest.combineUserIdentities(s,g.userIdentities),a._Store.setUserIdentities(d,t)):(h===Identify&&q&&o.mpid===r&&a._Persistence.setFirstSeenTime(o.mpid),a._Store.addMpidToSessionHistory(o.mpid,d),a._CookieSyncManager.attemptCookieSync(o.mpid,n),a._Persistence.swapCurrentUser(d,o.mpid,a._Store.currentSessionMPIDs),g&&!isEmpty(g.userIdentities)&&(t=e.IdentityRequest.combineUserIdentities(v,g.userIdentities)),a._Store.setUserIdentities(o.mpid,t),a._Persistence.update(),a._Store.syncPersistenceData(),a._Store.context=o.context||a._Store.context),p=a.Identity.getCurrentUser(),tryOnUserAlias(q,p,g,a.Logger,a._ErrorReportingDispatcher);var w=a._Persistence.getPersistence();p&&(a._Persistence.storeDataInMemory(w,p.getMPID()),e.reinitForwardersOnUserChange(q,p),e.setForwarderCallbacks(p,h));var x=IdentityType.getNewIdentitiesByName(t),y=h===Modify$1?s:v;// Sync $NoTargeting before sendUserIdentityChangeEvent
|
|
1255
|
-
// because UIC events call sendEventToServer which triggers
|
|
1256
|
-
// processQueuedEvents, draining the event queue. The
|
|
1257
|
-
// attribute must be in the store before that happens so
|
|
1258
|
-
// appendUserInfo picks it up.
|
|
1259
|
-
null===(l=a._CookieConsentManager)||void 0===l?void 0:l.syncNoTargetingAttribute(p),e.sendUserIdentityChangeEvent(x,h,o.mpid,y);}if(f){var z=0===b.status?HTTPCodes$2.noHttpCoverage:b.status;a._Helpers.invokeCallback(f,z,o||null,p,d);}else o&&!isEmpty(o.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
|
|
1260
|
-
a.Logger.error("Received HTTP response code of "+b.status+" - "+o.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(m=a._APIClient)||void 0===m?void 0:m.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,o||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.onIdentityComplete(),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue,a.Logger);},this.sendUserIdentityChangeEvent=function(b,c,d,f){var g;if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1261
|
-
{// https://go.mparticle.com/work/SQDSDKS-6354
|
|
1262
|
-
var h=this.IdentityAPI.getUser(d);for(var i in b)// Verifies a change actually happened
|
|
1263
|
-
if(f[i]!==b[i]){// If a new identity type was introduced when the identity changes
|
|
1264
|
-
// we need to notify the server so that the user profile is updated in
|
|
1265
|
-
// the mParticle UI.
|
|
1266
|
-
var j=!f[i],k=e.createUserIdentityChange(i,b[i],f[i],j,h);null===(g=a._APIClient)||void 0===g?void 0:g.sendEventToServer(k);}}},this.createUserIdentityChange=function(b,c,d,e,f){var g;// https://go.mparticle.com/work/SQDSDKS-6439
|
|
1267
|
-
return g=a._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:b,Identity:c,CreatedThisBatch:e},Old:{IdentityType:b,Identity:d,CreatedThisBatch:!1}},userInMemory:f}),g},this.sendUserAttributeChangeEvent=function(b,c,d,f,g,h){var i,j=e.createUserAttributeChange(b,c,d,f,g,h);j&&(null===(i=a._APIClient)||void 0===i?void 0:i.sendEventToServer(j));},this.createUserAttributeChange=function(b,c,d,e,f,g){"undefined"==typeof d&&(d=null);var h;return c!==d&&(h=a._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:b,New:c,Old:d,Deleted:f,IsNewAttribute:e}},g)),h},this.reinitForwardersOnUserChange=function(b,c){var d;hasMPIDAndUserLoginChanged(b,c)&&(null===(d=a._Forwarders)||void 0===d?void 0:d.initForwarders(c.getUserIdentities().userIdentities,a._APIClient.prepareForwardingStats));},this.setForwarderCallbacks=function(b,c){var d,e,f;// https://go.mparticle.com/work/SQDSDKS-6036
|
|
1268
|
-
null===(d=a._Forwarders)||void 0===d?void 0:d.setForwarderUserIdentities(b.getUserIdentities().userIdentities),null===(e=a._Forwarders)||void 0===e?void 0:e.setForwarderOnIdentityComplete(b,c),null===(f=a._Forwarders)||void 0===f?void 0:f.setForwarderOnUserIdentified(b);};}// https://go.mparticle.com/work/SQDSDKS-6359
|
|
1269
|
-
function tryOnUserAlias(a,b,c,d,e){if(c&&c.onUserAlias&&isFunction(c.onUserAlias))try{logDeprecatedMethodUsage({methodName:"onUserAlias",warningMessage:generateDeprecationMessage("onUserAlias")},d,e),c.onUserAlias(a,b);}catch(a){d.error("There was an error with your onUserAlias function - "+a);}}
|
|
1270
|
-
|
|
1271
|
-
var CCPAPurpose=Constants.CCPAPurpose;function Consent(a){function b(a){return isObject(a)?c.createPrivacyConsent(a.c,a.ts,a.d,a.l,a.h):null}// TODO: Refactor this method into a constructor
|
|
1272
|
-
var c=this;// this function is called when consent is required to
|
|
1273
|
-
// determine if a cookie sync should happen, or a
|
|
1274
|
-
// forwarder should be initialized
|
|
1275
|
-
this.isEnabledForUserConsent=function(a,b){if(!a||!a.values||!a.values.length)return !0;if(!b)return !1;var c,d={},e=b.getConsentState();if(e){// the server hashes consent purposes in the following way:
|
|
1276
|
-
// GDPR - '1' + purpose name
|
|
1277
|
-
// CCPA - '2data_sale_opt_out' (there is only 1 purpose of data_sale_opt_out for CCPA)
|
|
1278
|
-
var f=e.getGDPRConsentState();if(f)for(var g in f)f.hasOwnProperty(g)&&(c=KitFilterHelper.hashConsentPurposeConditionalForwarding("1",g),d[c]=f[g].Consented);var h=e.getCCPAConsentState();h&&(c=KitFilterHelper.hashConsentPurposeConditionalForwarding("2",CCPAPurpose),d[c]=h.Consented);}var i=a.values.some(function(a){var b=a.consentPurpose,c=a.hasConsented;return !!d.hasOwnProperty(b)&&d[b]===c});return a.includeOnMatch===i},this.createPrivacyConsent=function(b,c,d,e,f){if("boolean"!=typeof b)return a.Logger.error("Consented boolean is required when constructing a Consent object."),null;var g=c instanceof Date;return g&&(c=c.getTime()),(c||g)&&("number"!=typeof c&&"string"!=typeof c||isNaN(c))?(a.Logger.error("Timestamp must be a valid number when constructing a Consent object."),null):d&&"string"!=typeof d?(a.Logger.error("Document must be a valid string when constructing a Consent object."),null):e&&"string"!=typeof e?(a.Logger.error("Location must be a valid string when constructing a Consent object."),null):f&&"string"!=typeof f?(a.Logger.error("Hardware ID must be a valid string when constructing a Consent object."),null):{Consented:b,Timestamp:c||Date.now(),ConsentDocument:d,Location:e,HardwareId:f}},this.ConsentSerialization={toMinifiedJsonObject:function toMinifiedJsonObject(a){var b,c={};if(a){var d=a.getGDPRConsentState();if(d)for(var e in c.gdpr={},d)if(d.hasOwnProperty(e)){var f=d[e];c.gdpr[e]={},"boolean"==typeof f.Consented&&(c.gdpr[e].c=f.Consented),"number"==typeof f.Timestamp&&(c.gdpr[e].ts=f.Timestamp),"string"==typeof f.ConsentDocument&&(c.gdpr[e].d=f.ConsentDocument),"string"==typeof f.Location&&(c.gdpr[e].l=f.Location),"string"==typeof f.HardwareId&&(c.gdpr[e].h=f.HardwareId);}var g=a.getCCPAConsentState();g&&(c.ccpa=(b={},b[CCPAPurpose]={},b),"boolean"==typeof g.Consented&&(c.ccpa[CCPAPurpose].c=g.Consented),"number"==typeof g.Timestamp&&(c.ccpa[CCPAPurpose].ts=g.Timestamp),"string"==typeof g.ConsentDocument&&(c.ccpa[CCPAPurpose].d=g.ConsentDocument),"string"==typeof g.Location&&(c.ccpa[CCPAPurpose].l=g.Location),"string"==typeof g.HardwareId&&(c.ccpa[CCPAPurpose].h=g.HardwareId));}return c},fromMinifiedJsonObject:function fromMinifiedJsonObject(a){var d=c.createConsentState();if(!isObject(a))return d;if(isObject(a.gdpr))for(var e in a.gdpr)hasOwnProp(a.gdpr,e)&&d.addGDPRConsentState(e,b(a.gdpr[e]));return isObject(a.ccpa)&&hasOwnProp(a.ccpa,CCPAPurpose)&&d.setCCPAConsentState(b(a.ccpa[CCPAPurpose])),d}},this.createConsentState=function(b){function d(a){if("string"!=typeof a)return null;var b=a.trim();return b.length?b.toLowerCase():null}/**
|
|
1279
|
-
* Invoke these methods on a consent state object.
|
|
1280
|
-
* <p>
|
|
1281
|
-
* Usage: const consent = mParticle.Consent.createConsentState()
|
|
1282
|
-
* <br>
|
|
1283
|
-
* consent.setGDPRCoonsentState()
|
|
1284
|
-
*
|
|
1285
|
-
* @class Consent
|
|
1286
|
-
*/ /**
|
|
1287
|
-
* Add a GDPR Consent State to the consent state object
|
|
1288
|
-
*
|
|
1289
|
-
* @method addGDPRConsentState
|
|
1290
|
-
* @param purpose [String] Data processing purpose that describes the type of processing done on the data subject\u2019s data
|
|
1291
|
-
* @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...)
|
|
1292
|
-
*/function e(b,e){var f=d(b);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=c.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/**
|
|
1293
|
-
* Remove a GDPR Consent State to the consent state object
|
|
1294
|
-
*
|
|
1295
|
-
* @method removeGDPRConsentState
|
|
1296
|
-
* @param purpose [String] Data processing purpose that describes the type of processing done on the data subject\u2019s data
|
|
1297
|
-
*/function g(a){var b=d(a);return b?(delete k[b],this):this}/**
|
|
1298
|
-
* Gets the GDPR Consent State
|
|
1299
|
-
*
|
|
1300
|
-
* @method getGDPRConsentState
|
|
1301
|
-
* @return {Object} A GDPR Consent State
|
|
1302
|
-
*/function h(){return Object.assign({},k)}/**
|
|
1303
|
-
* Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out')
|
|
1304
|
-
*
|
|
1305
|
-
* @method setCCPAConsentState
|
|
1306
|
-
* @param {Object} ccpaConsent CCPA Consent State
|
|
1307
|
-
*/function i(b){if(!isObject(b))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=c.createPrivacyConsent(b.Consented,b.Timestamp,b.ConsentDocument,b.Location,b.HardwareId);return d&&(l[CCPAPurpose]=d),this}/**
|
|
1308
|
-
* Gets the CCPA Consent State
|
|
1309
|
-
*
|
|
1310
|
-
* @method getCCPAConsentStatensent
|
|
1311
|
-
* @return {Object} A CCPA Consent State
|
|
1312
|
-
*/ /**
|
|
1313
|
-
* Removes CCPA from the consent state object
|
|
1314
|
-
*
|
|
1315
|
-
* @method removeCCPAConsentState
|
|
1316
|
-
*/function j(){return delete l[CCPAPurpose],this}var k={},l={};if(b){var m=c.createConsentState();return m.setGDPRConsentState(b.getGDPRConsentState()),m.setCCPAConsentState(b.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAConsentState:j}};}
|
|
1317
|
-
|
|
1318
|
-
/*
|
|
1319
|
-
TODO: Including this as a workaround because attempting to import it from
|
|
1320
|
-
@mparticle/data-planning-models directly creates a build error.
|
|
1321
|
-
*/var DataPlanMatchType={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},withNoChange=function(a){return a},withoutUserAttributes=function(a){return __assign(__assign({},a),{UserAttributes:{}})},withoutUserIdentities=function(a){return __assign(__assign({},a),{UserIdentities:[]})},KitBlocker=/** @class */function(){function a(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r=this;// if data plan is not requested, the data plan is {document: null}
|
|
1322
|
-
if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,a&&!a.document)return void(this.kitBlockingEnabled=!1);this.kitBlockingEnabled=!0,this.mpInstance=b,this.blockEvents=null===(e=null===(d=null===(c=null===a||void 0===a?void 0:a.document)||void 0===c?void 0:c.dtpn)||void 0===d?void 0:d.blok)||void 0===e?void 0:e.ev,this.blockEventAttributes=null===(h=null===(g=null===(f=null===a||void 0===a?void 0:a.document)||void 0===f?void 0:f.dtpn)||void 0===g?void 0:g.blok)||void 0===h?void 0:h.ea,this.blockUserAttributes=null===(k=null===(j=null===(i=null===a||void 0===a?void 0:a.document)||void 0===i?void 0:i.dtpn)||void 0===j?void 0:j.blok)||void 0===k?void 0:k.ua,this.blockUserIdentities=null===(n=null===(m=null===(l=null===a||void 0===a?void 0:a.document)||void 0===l?void 0:l.dtpn)||void 0===m?void 0:m.blok)||void 0===n?void 0:n.id;var s=null===(q=null===(p=null===(o=null===a||void 0===a?void 0:a.document)||void 0===o?void 0:o.dtpn)||void 0===p?void 0:p.vers)||void 0===q?void 0:q.version_document,t=null===s||void 0===s?void 0:s.data_points;if(s)try{0<(null===t||void 0===t?void 0:t.length)&&t.forEach(function(a){return r.addToMatchLookups(a)});}catch(a){this.mpInstance.Logger.error("There was an issue with the data plan: "+a);}}return a.prototype.addToMatchLookups=function(a){var b,c,d;if(!a.match||!a.validator)return void this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(a));// match keys for non product custom attribute related data points
|
|
1323
|
-
var e=this.generateMatchKey(a.match),f=this.getPlannedProperties(a.match.type,a.validator);this.dataPlanMatchLookups[e]=f,((null===(b=null===a||void 0===a?void 0:a.match)||void 0===b?void 0:b.type)===DataPlanMatchType.ProductImpression||(null===(c=null===a||void 0===a?void 0:a.match)||void 0===c?void 0:c.type)===DataPlanMatchType.ProductAction||(null===(d=null===a||void 0===a?void 0:a.match)||void 0===d?void 0:d.type)===DataPlanMatchType.PromotionAction)&&(e=this.generateProductAttributeMatchKey(a.match),f=this.getProductProperties(a.match.type,a.validator),this.dataPlanMatchLookups[e]=f);},a.prototype.generateMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.CustomEvent:var c=b;return [DataPlanMatchType.CustomEvent,c.custom_event_type,c.event_name].join(":");case DataPlanMatchType.ScreenView:return [DataPlanMatchType.ScreenView,"",b.screen_name].join(":");case DataPlanMatchType.ProductAction:return [a.type,b.action].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action].join(":");case DataPlanMatchType.ProductImpression:return [a.type,b.action].join(":");case DataPlanMatchType.UserIdentities:case DataPlanMatchType.UserAttributes:return [a.type].join(":");default:return null}},a.prototype.generateProductAttributeMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.ProductAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.ProductImpression:return [a.type,"ProductAttributes"].join(":");default:return null}},a.prototype.getPlannedProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l;switch(a){case DataPlanMatchType.CustomEvent:case DataPlanMatchType.ScreenView:case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction:case DataPlanMatchType.ProductImpression:if(k=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.custom_attributes,k){if(!0===k.additionalProperties||void 0===k.additionalProperties)return !0;for(var m,n={},o=0,p=Object.keys(k.properties);o<p.length;o++)m=p[o],n[m]=!0;return n}return !1!==(null===(i=null===(h=null===(g=null===b||void 0===b?void 0:b.definition)||void 0===g?void 0:g.properties)||void 0===h?void 0:h.data)||void 0===i?void 0:i.additionalProperties)||{};case DataPlanMatchType.UserAttributes:case DataPlanMatchType.UserIdentities:if(l=null===(j=null===b||void 0===b?void 0:b.definition)||void 0===j?void 0:j.additionalProperties,!0===l||void 0===l)return !0;for(var m,n={},q=b.definition.properties,r=0,s=Object.keys(q);r<s.length;r++)m=s[r],n[m]=!0;return n;default:return null}},a.prototype.getProductProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;switch(a){case DataPlanMatchType.ProductImpression://product item attributes
|
|
1324
|
-
if(v=null===(l=null===(k=null===(j=null===(i=null===(h=null===(g=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.product_impressions)||void 0===g?void 0:g.items)||void 0===h?void 0:h.properties)||void 0===i?void 0:i.products)||void 0===j?void 0:j.items)||void 0===k?void 0:k.properties)||void 0===l?void 0:l.custom_attributes,!1===(null===v||void 0===v?void 0:v.additionalProperties)){for(var w,x={},y=0,z=Object.keys(null===v||void 0===v?void 0:v.properties);y<z.length;y++)w=z[y],x[w]=!0;return x}return !0;case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction://product item attributes
|
|
1325
|
-
if(v=null===(u=null===(t=null===(s=null===(r=null===(q=null===(p=null===(o=null===(n=null===(m=null===b||void 0===b?void 0:b.definition)||void 0===m?void 0:m.properties)||void 0===n?void 0:n.data)||void 0===o?void 0:o.properties)||void 0===p?void 0:p.product_action)||void 0===q?void 0:q.properties)||void 0===r?void 0:r.products)||void 0===s?void 0:s.items)||void 0===t?void 0:t.properties)||void 0===u?void 0:u.custom_attributes,v&&!1===v.additionalProperties){for(var w,x={},A=0,B=Object.keys(null===v||void 0===v?void 0:v.properties);A<B.length;A++)w=B[A],x[w]=!0;return x}return !0;default:return null}},a.prototype.getMatchKey=function(a){switch(a.event_type){case dist.EventTypeEnum.screenView:var b=a;return b.data?["screen_view","",b.data.screen_name].join(":"):null;case dist.EventTypeEnum.commerceEvent:var c=a,d=[];if(c&&c.data){var e=c.data,f=e.product_action,g=e.product_impressions,h=e.promotion_action;f?(d.push(DataPlanMatchType.ProductAction),d.push(f.action)):h?(d.push(DataPlanMatchType.PromotionAction),d.push(h.action)):g&&d.push(DataPlanMatchType.ProductImpression);}return d.join(":");case dist.EventTypeEnum.customEvent:var i=a;return i.data?["custom_event",i.data.custom_event_type,i.data.event_name].join(":"):null;default:return null}},a.prototype.getProductAttributeMatchKey=function(a){switch(a.event_type){case dist.EventTypeEnum.commerceEvent:var b=[],c=a.data,d=c.product_action,e=c.product_impressions,f=c.promotion_action;return d?(b.push(DataPlanMatchType.ProductAction),b.push(d.action),b.push("ProductAttributes")):f?(b.push(DataPlanMatchType.PromotionAction),b.push(f.action),b.push("ProductAttributes")):e&&(b.push(DataPlanMatchType.ProductImpression),b.push("ProductAttributes")),b.join(":");default:return null}},a.prototype.createBlockedEvent=function(a){return a&&(a=this.applyBlockingStep("the event and its attributes",this.transformEventAndEventAttributes,a,withNoChange)),a&&a.EventDataType===Types.MessageType.Commerce&&(a=this.applyBlockingStep("product attributes",this.transformProductAttributes,a,withNoChange)),a&&(a=this.applyBlockingStep("user attributes",this.transformUserAttributes,a,withoutUserAttributes),a=this.applyBlockingStep("user identities",this.transformUserIdentities,a,withoutUserIdentities)),a},a.prototype.applyBlockingStep=function(a,b,c,d){try{return b.call(this,c)}catch(b){var e=d(c);return this.reportFailedStep(a,b),e}},a.prototype.reportFailedStep=function(a,b){try{this.mpInstance.Logger.error("Kit blocking could not filter "+a+": "+b);}catch(a){// Best-effort: a logger or error value that throws must not stop the remaining steps.
|
|
1326
|
-
}},a.prototype.transformEventAndEventAttributes=function(a){var b=__assign({},a),c=convertEvent(b);if(!c)return b;var d=this.getMatchKey(c),e=this.dataPlanMatchLookups[d];if(this.blockEvents&&!e)/*
|
|
1327
|
-
If the event is not planned, it doesn't exist in dataPlanMatchLookups
|
|
1328
|
-
and should be blocked (return null to not send anything to forwarders)
|
|
1329
|
-
*/return null;if(this.blockEventAttributes){/*
|
|
1330
|
-
matchedEvent is set to `true` if additionalProperties is `true`
|
|
1331
|
-
otherwise, delete attributes that exist on event.EventAttributes
|
|
1332
|
-
that aren't on
|
|
1333
|
-
*/if(!0===e)return b;if(e){if(b.EventAttributes){for(var f,g={},h=0,i=Object.keys(b.EventAttributes);h<i.length;h++)f=i[h],!0===e[f]&&(g[f]=b.EventAttributes[f]);b.EventAttributes=g;}return b}return b}return b},a.prototype.transformProductAttributes=function(a){function b(a,b){return null===b||void 0===b?void 0:b.map(function(b){if(!b.Attributes)return b;for(var c,d={},e=0,f=Object.keys(b.Attributes);e<f.length;e++)c=f[e],!0===a[c]&&(d[c]=b.Attributes[c]);return __assign(__assign({},b),{Attributes:d})})}var c=__assign({},a),d=convertEvent(c),e=this.getProductAttributeMatchKey(d),f=this.dataPlanMatchLookups[e];return this.blockEvents&&!f?null:this.blockEventAttributes?!0===f?c:f?(c.ProductAction?c.ProductAction=__assign(__assign({},c.ProductAction),{ProductList:b(f,c.ProductAction.ProductList)}):c.ProductImpressions?c.ProductImpressions=c.ProductImpressions.map(function(a){return __assign(__assign({},a),{ProductList:b(f,a.ProductList)})}):this.mpInstance.Logger.warning("Product Not Supported "),c):c:c},a.prototype.transformUserAttributes=function(a){var b=__assign({},a);if(this.blockUserAttributes){var c=this.dataPlanMatchLookups.user_attributes;if(this.mpInstance._Helpers.isObject(c)&&b.UserAttributes){for(var d,e={},f=0,g=Object.keys(b.UserAttributes);f<g.length;f++)d=g[f],!0===c[d]&&(e[d]=b.UserAttributes[d]);b.UserAttributes=e;}}return b},a.prototype.isAttributeKeyBlocked=function(a){/* used when an attribute is added to the user */if(!this.blockUserAttributes)return !1;var b=this.dataPlanMatchLookups.user_attributes;// When additionalProperties is set to true, matchedAttributes
|
|
1334
|
-
// will be a boolean, otherwise it will return an object
|
|
1335
|
-
return !("boolean"==typeof b&&b)&&"object"===_typeof(b)&&!0!==b[a];// When "Block unplanned user attributes" is enabled and "Allow unplanned user
|
|
1336
|
-
// attributes" is also enabled in the UI, allowing unplanned user attributes will be prioritized
|
|
1337
|
-
},a.prototype.isIdentityBlocked=function(a){/* used when an attribute is added to the user */if(!this.blockUserIdentities)return !1;if(this.blockUserIdentities){var b=this.dataPlanMatchLookups.user_identities;// The lookup is absent, not empty, when the plan carries no
|
|
1338
|
-
// user_identities data point, and indexing it would throw.
|
|
1339
|
-
if(!0===b||!b)return !1;if(!b[a])return !0}else return !1;return !1},a.prototype.transformUserIdentities=function(a){var b,c=this,d=__assign({},a);if(this.blockUserIdentities){var e=this.dataPlanMatchLookups.user_identities;this.mpInstance._Helpers.isObject(e)&&(null===(b=null===d||void 0===d?void 0:d.UserIdentities)||void 0===b?void 0:b.length)&&(d.UserIdentities=d.UserIdentities.filter(function(a){var b=Types.IdentityType.getIdentityName(c.mpInstance._Helpers.parseNumber(a.Type));return e[b]}));}return d},a}();
|
|
1340
|
-
|
|
1341
|
-
var buildUrl=function(a,b,c,d){var e=d?"1":"0",f=["env=".concat(e)],g=c||{},h=g.planId,i=g.planVersion;return h&&f.push("plan_id=".concat(h)),i&&f.push("plan_version=".concat(i)),"".concat(a+b+"/config","?").concat(f.join("&"))};function ConfigAPIClient(a,b,c){var d=this,e="https://"+c._Store.SDKConfig.configUrl,f=b.isDevelopmentMode,g=b.dataPlan,h=buildUrl(e,a,g,f),i=window.fetch?new FetchUploader(h):new XHRUploader(h);this.getSDKConfiguration=function(){return __awaiter(d,void 0,void 0,function(){var a,d,e,f,h,j,k;return __generator(this,function(l){switch(l.label){case 0:d={method:"get",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"},body:null},l.label=1;case 1:return l.trys.push([1,6,,7]),[4/*yield*/,i.upload(d)];case 2:return (e=l.sent(),200!==e.status)?[3/*break*/,5]:(null===(h=null===c||void 0===c?void 0:c.Logger)||void 0===h?void 0:h.verbose("Successfully received configuration from server"),e.json?[4/*yield*/,e.json()]:[3/*break*/,4]);case 3:return a=l.sent(),[2/*return*/,a];case 4:return f=e,a=JSON.parse(f.responseText),[2/*return*/,a];case 5:return null===(j=null===c||void 0===c?void 0:c.Logger)||void 0===j?void 0:j.verbose("Issue with receiving configuration from server, received HTTP Code of "+e.statusText),[3/*break*/,7];case 6:return l.sent(),null===(k=null===c||void 0===c?void 0:c.Logger)||void 0===k?void 0:k.error("Error getting forwarder configuration from mParticle servers."),[3/*break*/,7];case 7:// Returns the original config object if we cannot retrieve the remote config
|
|
1342
|
-
return [2/*return*/,b]}})})};}
|
|
1343
|
-
|
|
1344
|
-
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=getErrorMessage(s),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,A,m,E,m,A,F;return __generator(this,function(G){switch(G.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,p=a._ErrorReportingDispatcher,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];q=g||null,r=this.getUploadUrl(c,g),s=window.fetch?new FetchUploader(r):new XHRUploader(r),t={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,G.label=1;case 1:return G.trys.push([1,9,,10]),[4/*yield*/,s.upload(t)];case 2:return u=G.sent(),v=void 0,w=void 0,x=u.status,x===HTTP_ACCEPTED?[3/*break*/,3]:x===HTTP_OK?[3/*break*/,3]:x===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return u.json?[4/*yield*/,u.json()]:[3/*break*/,5];case 4:return y=G.sent(),v=this.getIdentityResponseFromFetch(u,y),[3/*break*/,6];case 5:v=this.getIdentityResponseFromXHR(u),G.label=6;case 6:return v.status===HTTP_BAD_REQUEST?(z=v.responseText,w="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+v.status,(null===z||void 0===z?void 0:z.Errors)&&(A=z.Errors.map(function(a){return a.message}).join(", "),w+=" - "+A)):o.isVerbose()&&(B=v.responseText,C=a._Store.SDKConfig.isDevelopmentMode,D=B,!C&&(null===B||void 0===B?void 0:B.matched_identities)&&(D=__assign(__assign({},B),{matched_identities:obfuscateData(B.matched_identities)})),w="Received Identity Response from server: "+JSON.stringify(D)),[3/*break*/,8];case 7:{if(u.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,o.error("Error sending identity request to servers - "+A),n(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,w&&o.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return E=G.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),A=getErrorMessage(E),F="Error sending identity request to servers - "+A,o.error(F),null===p||void 0===p?void 0:p.report({message:F,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
|
|
1345
|
-
|
|
1346
|
-
var PASSBACK_CONVERSION_TRACKING_ID="passbackconversiontrackingid",CHECKOUT_INTENT_BUFFER_LIMIT=4,CHECKOUT_INTENT_MAX_AGE_MS=3e4,ON_SHOPPABLE_ADS_READY_METHOD="onShoppableAdsReady",RoktManager=/** @class */function(){// Keys this manager's route subscription, so a re-executed bundle's manager replaces
|
|
1347
|
-
// it while a second named instance keeps its own.
|
|
1348
|
-
function a(a){this.instanceName=a,this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1,this.isShoppableAdsLoaded=!1,this.stopRouteChangeWatch=null,this.pendingCheckoutIntents=[];}/**
|
|
1349
|
-
* Sets a callback to be invoked when RoktManager becomes ready
|
|
1350
|
-
*/return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g,h,i,j,k){var l,m,n=a||{},o=n.userAttributeFilters,p=n.settings,q=p||{},r=q.placementAttributesMapping,s=q.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(l=null===s||void 0===s?void 0:s.toLowerCase())&&void 0!==l?l:null,this.identityService=c,this.store=d,this.logger=e,this.errorReporter=h,this.loggingService=i,this.captureTiming=g,this.integrationCapture=j,this.createFilteredUser=k,null===(m=this.captureTiming)||void 0===m?void 0:m.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:o,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(r);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
|
|
1351
|
-
// It is set here and passed in to the createLauncher method in the Rokt Kit
|
|
1352
|
-
// This is not to be confused for the `sandbox` flag in the selectPlacements attributes
|
|
1353
|
-
// as that is independent of this setting, though they share the same name.
|
|
1354
|
-
var t=(null===f||void 0===f?void 0:f.sandbox)||!1,u=normalizeRoktLauncherOptions(null===f||void 0===f?void 0:f.launcherOptions);// Launcher options are set here for the kit to pick up and pass through
|
|
1355
|
-
// to the Rokt Launcher.
|
|
1356
|
-
this.launcherOptions=__assign({sandbox:t},u),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,this.watchRouteChanges(),this.flushCheckoutIntents(),(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.watchRouteChanges=function(){var a,b,c,d=this;return isFunction(null===(a=this.kit)||void 0===a?void 0:a.onRouteChange)?void(// A full navigation or a re-init lands on the trigger route without a route change
|
|
1357
|
-
// of its own.
|
|
1358
|
-
this.isAutoLogPageViewEnabled()?(null===(c=this.stopRouteChangeWatch)||void 0===c?void 0:c.call(this),this.stopRouteChangeWatch=null):!this.stopRouteChangeWatch&&(this.stopRouteChangeWatch=subscribeToRouteChange("rokt:".concat(this.instanceName),function(){return d.notifyRouteChange()})),this.notifyRouteChange()):(null===(b=this.stopRouteChangeWatch)||void 0===b?void 0:b.call(this),void(this.stopRouteChangeWatch=null))},a.prototype.notifyRouteChange=function(){var a,b,c;try{null===(b=null===(a=this.kit)||void 0===a?void 0:a.onRouteChange)||void 0===b?void 0:b.call(a);}catch(a){null===(c=this.logger)||void 0===c?void 0:c.error("RoktManager: Error in onRouteChange: ".concat(getErrorMessage(a)));}},a.prototype.isCheckoutIntentSuppressed=function(){var a,b,c=null===(b=null===(a=this.store)||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.flags;if(!c||!0!==c[Constants.FeatureFlags.AutoButtonTracking]||!this.store.isEnabled)return !0;var d=this.launcherOptions||{};if(d.noFunctional||d.noTargeting||d.doNotShareOrSell)return !0;var e="undefined"==typeof navigator?void 0:navigator;return !!e&&!0===e.globalPrivacyControl},a.prototype.isCheckoutIntentLive=function(){return !this.isCheckoutIntentSuppressed()&&"undefined"!=typeof Event&&isFunction(Event.prototype.composedPath)},a.prototype.notifyCheckoutIntent=function(a,b){var c;if(void 0===b&&(b=window.location.pathname),!this.isCheckoutIntentSuppressed()){var d=this.kit;if(!d)return void(this.pendingCheckoutIntents=this.pendingCheckoutIntents.filter(function(b){return b.signal.kind!==a.kind}).concat({signal:a,pathname:b}).slice(-CHECKOUT_INTENT_BUFFER_LIMIT));try{isFunction(d.onCheckoutIntent)&&d.onCheckoutIntent(a);}catch(a){null===(c=this.logger)||void 0===c?void 0:c.error("RoktManager: Error in onCheckoutIntent: ".concat(getErrorMessage(a)));}}},a.prototype.discardCheckoutIntents=function(){this.pendingCheckoutIntents=[];},a.prototype.flushCheckoutIntents=function(){var a=this,b=this.pendingCheckoutIntents;this.pendingCheckoutIntents=[];var c=Date.now(),d=window.location.pathname;b.filter(function(a){var b=a.signal,e=a.pathname;return c-b.t<CHECKOUT_INTENT_MAX_AGE_MS&&e===d}).sort(function(c,a){return c.signal.t-a.signal.t}).forEach(function(b){var c=b.signal;return a.notifyCheckoutIntent(c)});},a.prototype.isAutoLogPageViewEnabled=function(){var a,b,c;return !0===(null===(c=null===(b=null===(a=this.store)||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.flags)||void 0===c?void 0:c[Constants.FeatureFlags.AutoLogPageView])},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return __awaiter(this,void 0,void 0,function(){var s,t,u,v,w,x,y,z,A,B,C,D,E,F,F,G,H,I,J,K,L,M,N,O,P,Q=this;return __generator(this,function(){// Queue if kit isn't ready OR if identity is in flight
|
|
1359
|
-
if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];try{if(s=a.attributes,t=(null===s||void 0===s?void 0:s.sandbox)||null,u=this.mapPlacementAttributes(s,this.placementAttributesMapping),(null===(d=this.logger)||void 0===d?void 0:d.isVerbose())&&(v=obfuscateDevData(s,null===(f=null===(e=this.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode),this.logger.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(v,null,2)))),this.currentUser=this.identityService.getCurrentUser(),w=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},x=w.email,y=u.email,z=void 0,A=void 0,B=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),B&&(z=w[this.mappedEmailShaIdentityType],A=u.emailsha256||u[this.mappedEmailShaIdentityType]||void 0),C=this.hasIdentityChanged(x,y),D=this.hasIdentityChanged(z,A),E={},C&&(E.email=y,y&&(F="Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.",this.logger.warning(F),null===(i=this.errorReporter)||void 0===i?void 0:i.report({message:F,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING}))),D&&(E[this.mappedEmailShaIdentityType]=A,F="emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.",this.logger.warning(F),null===(j=this.errorReporter)||void 0===j?void 0:j.report({message:F,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING})),G=this.toUserAttributes(u),isEmpty(E))this.setUserAttributes(this.currentUser,G);else// Fire-and-forget identify \u2014 best-effort, does not block selectPlacements
|
|
1360
|
-
try{this.identityService.identify({userIdentities:__assign(__assign({},w),E)},function(a){var b,c=+(null===a||void 0===a?void 0:a.httpCode);c&&(400<=c||0>c)&&Q.logger.error("Background identify failed with HTTP "+c),Q.setUserAttributes(null===(b=null===a||void 0===a?void 0:a.getUser)||void 0===b?void 0:b.call(a),G,E),Q.processMessageQueue();});}catch(a){this.logger.error("Background identify threw an error: "+getErrorMessage(a)),this.setUserAttributes(this.identityService.getCurrentUser(),G,E);}return H=this.currentUser&&this.createFilteredUser?this.createFilteredUser(this.currentUser.getMPID()):null,I=(null===(k=null===H||void 0===H?void 0:H.getUserIdentities())||void 0===k?void 0:k.userIdentities)||{},J=null===(m=null===(l=this.store)||void 0===l?void 0:l.getTimeOnSite)||void 0===m?void 0:m.call(l),K=null===(o=null===(n=this.store)||void 0===n?void 0:n.getTotalTimeOnSite)||void 0===o?void 0:o.call(n),L=__assign(__assign(__assign(__assign({},u),null===t?{}:{sandbox:t}),J?{active_time_on_site_ms:J}:{}),K?{total_time_on_site_ms:K}:{}),L.email||(I.email?L.email=I.email:w.email&&this.logFilteredIdentity("email")),!B||L.emailsha256||L[this.mappedEmailShaIdentityType]||(M=I[this.mappedEmailShaIdentityType],M?L.emailsha256=M:w[this.mappedEmailShaIdentityType]&&this.logFilteredIdentity(this.mappedEmailShaIdentityType)),L[PASSBACK_CONVERSION_TRACKING_ID]||(null===(p=this.integrationCapture)||void 0===p?void 0:p.capture(),N=null===(q=this.integrationCapture)||void 0===q?void 0:q.getClickIdsAsIntegrationAttributes(),O=null===(r=null===N||void 0===N?void 0:N[PARTNER_MODULE_IDS.Rokt])||void 0===r?void 0:r[PASSBACK_CONVERSION_TRACKING_ID],O&&(L[PASSBACK_CONVERSION_TRACKING_ID]=O)),this.filters.filteredUser=H||this.filters.filteredUser||null,P=__assign(__assign({},a),{attributes:L}),[2/*return*/,this.kit.selectPlacements(P)]}catch(a){return [2/*return*/,Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))]}return [2/*return*/]})})},a.prototype.logFilteredIdentity=function(a){var b;null===(b=this.logger)||void 0===b?void 0:b.verbose("mParticle.Rokt selectPlacements did not add the ".concat(a," user identity to the attributes because the Rokt connection does not allow it"));},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m=this;return __generator(this,function(n){switch(n.label){case 0:return (n.trys.push([0,2,,3]),!a||"object"!==_typeof(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(m,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=n.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=n.sent(),this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(getErrorMessage(l))),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){throw new Error("Error setting extension data: "+getErrorMessage(a))}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.terminate=function(){var a,b,c;return __awaiter(this,void 0,void 0,function(){var d;return __generator(this,function(e){switch(e.label){case 0:if(!this.isReady())return null===(a=this.logger)||void 0===a?void 0:a.verbose("mParticle.Rokt.terminate called before the Rokt kit was ready. Nothing to terminate."),[2/*return*/];if(!isFunction(this.kit.terminate))return null===(b=this.logger)||void 0===b?void 0:b.error("mParticle.Rokt.terminate is not supported by the attached Rokt Kit version."),[2/*return*/];e.label=1;case 1:return e.trys.push([1,3,,4]),[4/*yield*/,this.kit.terminate()];case 2:return e.sent(),[3/*break*/,4];case 3:return d=e.sent(),null===(c=this.logger)||void 0===c?void 0:c.error("Failed to terminate the Rokt launcher: ".concat(getErrorMessage(d))),[3/*break*/,4];case 4:return [2/*return*/]}})})},a.prototype.onShoppableAdsReady=function(a){if(!this.kit||!this.isShoppableAdsLoaded)return void this.deferredCall("onShoppableAdsReady",a);try{this.kit.onShoppableAdsReady(a);}catch(a){this.logger.error("Failed to register onShoppableAdsReady callback: ".concat(getErrorMessage(a)));}},a.prototype.flushOnShoppableAdsReadyMessageQueue=function(a){var b=this;this.kit=a,this.messageQueue.forEach(function(c,d){var f;if(c.methodName===ON_SHOPPABLE_ADS_READY_METHOD){try{a.onShoppableAdsReady(c.payload);}catch(a){null===(f=b.logger)||void 0===f?void 0:f.error("RoktManager: Error flushing onShoppableAdsReady: "+a);}b.messageQueue["delete"](d);}}),this.isShoppableAdsLoaded=!0;},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c;return __generator(this,function(d){switch(d.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];d.label=1;case 1:return d.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,d.sent()];case 3:return c=d.sent(),this.logger.error("Failed to hashSha256, returning undefined: ".concat(getErrorMessage(c))),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
|
|
1361
|
-
return !!(this.kit&&this.kit.launcher)},a.prototype.toUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}return c},a.prototype.setUserAttributes=function(a,b,c){if(void 0===c&&(c={}),!a)return void this.logger.warning("selectPlacements attributes were not set because there is no user to set them on.");try{if(this.hasContradictingIdentity(a,c))return void this.logger.warning("selectPlacements attributes were not set because identify did not resolve to a user with the passed email or hashed email.");a.setUserAttributes(b);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.hasContradictingIdentity=function(a,b){return Object.keys(b).some(function(c){var d,e,f=null===(e=null===(d=a.getUserIdentities())||void 0===d?void 0:d.userIdentities)||void 0===e?void 0:e[c];return !!f&&f!==b[c]})},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
|
|
1362
|
-
this.messageQueue.clear(),c.forEach(function(a){var c,d,e,f;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));if(null===(d=b.logger)||void 0===d?void 0:d.isVerbose()){var g=obfuscateDevData(a.payload,null===(f=null===(e=b.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode);b.logger.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(g)));}// Capture resolve/reject functions before async processing
|
|
1363
|
-
var h=a.resolve,i=a.reject,j=function(c){var d;null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(getErrorMessage(c))),i&&i(c);};try{var k=b[a.methodName](a.payload);// Handle both sync and async methods
|
|
1364
|
-
Promise.resolve(k).then(function(a){h&&h(a);})["catch"](j);}catch(a){j(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
|
|
1365
|
-
},a}();// The purpose of this class is to create a link between the Core mParticle SDK and the
|
|
1366
|
-
|
|
1367
|
-
/**
|
|
1368
|
-
* CookieConsentManager handles storage and access of consent flags (noFunctional, noTargeting)
|
|
1369
|
-
* that are passed via launcherOptions during SDK initialization.
|
|
1370
|
-
*
|
|
1371
|
-
* These flags allow Rokt integration to respect user privacy choices.
|
|
1372
|
-
*
|
|
1373
|
-
* Default behavior: Both flags default to false, meaning all features are allowed
|
|
1374
|
-
* unless explicitly opted out by the user.
|
|
1375
|
-
*/var CookieConsentManager=/** @class */function(){function a(a){this.flags=a,this.flags={noFunctional:!0===a.noFunctional,noTargeting:!0===a.noTargeting};}/**
|
|
1376
|
-
* Returns true if third-party targeting is disabled.
|
|
1377
|
-
* Targeting is allowed when noTargeting is false (default).
|
|
1378
|
-
*/return a.prototype.getNoTargeting=function(){return this.flags.noTargeting},a.prototype.getNoFunctional=function(){return this.flags.noFunctional},a.prototype.syncNoTargetingAttribute=function(a){a&&(this.flags.noTargeting?a.setUserAttribute(NO_TARGETING_ATTRIBUTE,!0):hasOwnProp(a.getAllUserAttributes(),NO_TARGETING_ATTRIBUTE)&&a.removeUserAttribute(NO_TARGETING_ATTRIBUTE));},a}();
|
|
1379
|
-
|
|
1380
|
-
var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.report=function(a){var b=this;this.services.forEach(function(c){var d;try{c.report(a);}catch(a){null===(d=b.logger)||void 0===d?void 0:d.error("Error in ErrorReportingService: "+a);}});},a}();
|
|
1381
|
-
|
|
1382
|
-
var LoggingDispatcher=/** @class */function(){function a(){this.services=[];}return a.prototype.register=function(a){this.services.push(a);},a.prototype.log=function(a){var b=this;this.services.forEach(function(c){var d;try{c.log(a);}catch(a){null===(d=b.logger)||void 0===d?void 0:d.error("Error in LoggingService: "+a);}});},a}();
|
|
1383
|
-
|
|
1384
|
-
var AUTO_BUTTON_ATTRIBUTE="is_auto_button_click";// Specific enough not to merge with a customer's own 'Button Click' event.
|
|
1385
|
-
var BUTTON_CLICK_EVENT_NAME="Auto Button Click";// One custom event per click, logged like logLink() with the auto marker and the
|
|
1386
|
-
// page fields that auto page views carry. No intent: classifying clicks is left
|
|
1387
|
-
// to whoever reads the data.
|
|
1388
|
-
var buildButtonClickEvent=function(a,b){// Optional fields are left out when the button has no safe value for them.
|
|
1389
|
-
for(var c,d,e=(c={label_source:a.labelSource,element:a.element,type:a.type,path:b,hostname:window.location.hostname},c[AUTO_BUTTON_ATTRIBUTE]=!0,c),f={label:a.label,aria_label:a.ariaLabel,icon:a.icon,element_id:a.elementId,element_name:a.elementName,test_id:a.testId,controls:a.controls,form:a.form,link_type:a.linkType,link_domain:a.linkDomain,file_extension:a.fileExtension},g=0,h=Object.keys(f);g<h.length;g++)d=h[g],f[d]&&(e[d]=f[d]);return void 0!==a.checked&&(e.checked=a.checked),{messageType:MessageType$1.PageEvent,name:BUTTON_CLICK_EVENT_NAME,data:e,eventType:EventType.Other}};
|
|
1390
|
-
|
|
1391
|
-
// descriptions. Rokt's own elements, disabled controls and anything under
|
|
1392
|
-
// data-mp-no-track are never returned.
|
|
1393
|
-
var CONTROL_SELECTOR="button, input[type=\"submit\"], input[type=\"button\"], input[type=\"image\"], [role=\"button\"]";// closest() over the composed tree: slots, parents, then shadow hosts.
|
|
1394
|
-
function hasComposedAncestor(a,b){for(var c=a;c;){if(c.matches(b))return !0;var d=isFunction(c.getRootNode)?c.getRootNode():null;c=c.assignedSlot||c.parentElement||d&&d.host||null;}return !1}var ROKT_SELECTOR="[data-core-type], #rokt-controller-frame";// A Rokt frame or script is served from a /wsdk/ path.
|
|
1395
|
-
function hasRoktSrc(a){var b=a.getAttribute("src");if(!b)return !1;try{return -1!==new URL(b,"https://example.test").pathname.indexOf("/wsdk/")}catch(a){// An unparseable src is not a Rokt element.
|
|
1396
|
-
return !1}}// Rokt's own placements and frames never count as partner checkout controls.
|
|
1397
|
-
function isRoktElement(a){return hasComposedAncestor(a,ROKT_SELECTOR)||hasRoktSrc(a)}// Wallet and quick-pay buttons as their vendors render them: official custom
|
|
1398
|
-
// elements and documented classes, ids and attributes.
|
|
1399
|
-
var CARD_FORM_BUTTON="paypal-basic-card-button",VENDOR_BUTTON="apple-pay-button, .apple-pay-button, .gpay-button, .gpay-card-info-container, #gpay-button-online-api-id, paypal-button, venmo-button, paypal-pay-later-button, paypal-credit-button, shop-pay-button, shop-pay-wallet-button, shopify-accelerated-checkout, shopify-accelerated-checkout-cart, shopify-apple-pay-button, shopify-google-pay-button, shopify-paypal-button, shopify-amazon-pay-button, .amazonpay-button-focusable, #AmazonPayButton, [data-amazon-pay-button], [data-afterpay-entry-point], "+CARD_FORM_BUTTON,NOT_A_PAYMENT=["set-up","add-money","reload","top-up"].map(function(a){return "apple-pay-button[type=\""+a+"\"]"}).join(", ");// PayPal's card button opens a card form, so it is a step rather than a wallet.
|
|
1400
|
-
// Apple's set-up and top-up buttons manage a wallet rather than pay with it.
|
|
1401
|
-
// What a vendor's own button markup says about a control. Only the control or
|
|
1402
|
-
// the shadow host that owns it counts, so a merchant wrapper reusing a vendor
|
|
1403
|
-
// class never turns its children into wallet buttons.
|
|
1404
|
-
function vendorButtonKind(a){var b=a.matches(VENDOR_BUTTON)?a:null;if(!b){var c=isFunction(a.getRootNode)?a.getRootNode():null;b=c&&c.host&&c.host.matches(VENDOR_BUTTON)?c.host:null;}return b?b.matches(NOT_A_PAYMENT)?"none":b.matches(CARD_FORM_BUTTON)?"checkout_step":"wallet":void 0}function isWalletElement(a){return "wallet"===vendorButtonKind(a)}// Pickers and toggles choose a payment method or open a panel; they never pay.
|
|
1405
|
-
var PICKER="input[type=\"radio\"], input[type=\"checkbox\"], label, [role=\"radio\"], [role=\"tab\"], [role=\"option\"], [role=\"checkbox\"], [role=\"switch\"], [role=\"menuitemradio\"], [role=\"menuitemcheckbox\"], [aria-checked], [aria-selected]",PICKER_GROUP="[role=\"radiogroup\"], [role=\"tablist\"], [role=\"listbox\"]",MESSAGING="klarna-placement, afterpay-placement, square-placement, .affirm-as-low-as, .affirm-site-modal, .affirm-product-modal, [data-pp-message]";// Pay-later and financing messages link to details rather than pay.
|
|
1406
|
-
// A control that is still logged as a click but never counts as checkout intent.
|
|
1407
|
-
function isQuietIntentControl(a,b){return !!a.matches(PICKER)||!!hasComposedAncestor(a,PICKER_GROUP)||!!(!b&&(a.hasAttribute("aria-expanded")||a.hasAttribute("aria-pressed")))||hasComposedAncestor(a,MESSAGING)}// A checkbox or radio is a control of its own only when no button or link
|
|
1408
|
-
// around it takes the click, so a tappable row keeps its own name.
|
|
1409
|
-
var OPTION_INPUT="input[type=\"checkbox\"], input[type=\"radio\"]";// Walks at most 12 entries of an event's composed path for the nearest control.
|
|
1410
|
-
// One composed walk from the target rules out Rokt elements and anything under
|
|
1411
|
-
// data-mp-no-track; disabled controls are skipped.
|
|
1412
|
-
function findControl(a){for(var b,c,d=a.slice(0,12),e=0,f=d;e<f.length;e++)if(c=f[e],c instanceof Element){b=c;break}if(b&&!hasComposedAncestor(b,"[data-core-type], #rokt-controller-frame, [data-mp-no-track]")){for(var g,h,c,i=0;i<(void 0).length;i++)if(c=(void 0)[i],!!(c instanceof Element)){if(hasRoktSrc(c))return;!g&&c.matches("button, input[type=\"submit\"], input[type=\"button\"], input[type=\"image\"], [role=\"button\"], a[href], "+VENDOR_BUTTON)?g=c:!g&&!h&&c.matches(OPTION_INPUT)&&(h=c);}return g=g||h,!g||g.matches(":disabled, [aria-disabled=\"true\"]")?void 0:g}}// fields, editable regions, and anything under data-mp-no-track.
|
|
1413
|
-
function isUnsafeTextSource(a){return a.matches("input, select, textarea, option, optgroup, datalist, [contenteditable]:not([contenteditable=\"false\"])")||!!a.querySelector("input, select, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")||hasComposedAncestor(a,"select, datalist, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")}// A label around a checkbox or radio holds no typed text, so only the other
|
|
1414
|
-
// fields rule its text out.
|
|
1415
|
-
function isUnsafeLabelSource(a){return !!a.querySelector("input:not([type=\"checkbox\"]):not([type=\"radio\"]), select, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")||hasComposedAncestor(a,"select, datalist, textarea, [data-mp-no-track], [contenteditable]:not([contenteditable=\"false\"])")}
|
|
1416
|
-
|
|
1417
|
-
// Masks a button label before it is logged. Button text can carry personal data,
|
|
1418
|
-
// so this is the privacy boundary for every label and aria-label.
|
|
1419
|
-
// Masking needs \p{Nd} to see every script's digits. Browsers without Unicode
|
|
1420
|
-
// property escapes send no labels at all.
|
|
1421
|
-
function createDigitPatterns(){try{return {run:/\p{Nd}{6,}/u,number:/\p{Nd}+(?:[.,\u060C\u066B\u066C]\p{Nd}+)*/gu}}catch(a){}}var digitPatterns=createDigitPatterns();// The label as logged: lower case, at most 64 characters, digits and amounts
|
|
1422
|
-
// masked. Dropped when it looks like an email, phone or card number.
|
|
1423
|
-
function maskLabel(a){if(a&&!(128<a.length)&&digitPatterns){var b=a.replace(/\s+/g," ").trim().toLowerCase();if(b&&-1===b.indexOf("@")&&!digitPatterns.run.test(b.replace(/[\s()\-\u2010-\u2015]/g,""))){var c=b.replace(digitPatterns.number,"#").slice(0,64).trim();return c||void 0}}}
|
|
1424
|
-
|
|
1425
|
-
var DOWNLOAD_EXTENSIONS=/\.(pdf|zip|csv|txt|ics|docx?|xlsx?|pptx?|dmg|exe|apk|mp3|mp4)$/i;function elementKind(a){if(isWalletElement(a))return "wallet";var b=a.tagName.toLowerCase();return "button"===b||"input"===b?b:a.matches("a[href]:not([role=\"button\"])")?"link":"role"}function textOf(a){return a&&!isUnsafeTextSource(a)&&a.textContent?a.textContent.trim():""}function nonBlank(a){return a&&a.trim()?a:void 0}// The button's name as a screen reader would read it, simplified: the first of
|
|
1426
|
-
// aria-labelledby, aria-label, own text (or an inner image's alt), title, for
|
|
1427
|
-
// inputs their value, and for checkboxes and radios their label's text. The text
|
|
1428
|
-
// sources are skipped for controls that hold form fields or more than four
|
|
1429
|
-
// children, so a typed value is never read.
|
|
1430
|
-
function accessibleName(a){var b=a.getAttribute("aria-labelledby");if(b){var c=isFunction(a.getRootNode)?a.getRootNode():document,d=b.split(/\s+/).map(function(a){return textOf(c.getElementById?c.getElementById(a):null)}).filter(function(a){return !!a}).join(" ");if(d)return {raw:d,source:"labelledby"}}var e=nonBlank(a.getAttribute("aria-label"));if(e)return {raw:e,source:"aria"};var f=4>=a.children.length&&!isUnsafeTextSource(a);if(a instanceof HTMLInputElement){// The browser's normalised type: an unknown value reads as 'text'.
|
|
1431
|
-
var g=a.type;if("image"===g){var h=nonBlank(a.getAttribute("alt"));if(h)return {raw:h,source:"alt"}}else if("submit"===g||"button"===g||"reset"===g){var i=nonBlank(a.value);if(i)return {raw:i,source:"value"};if("button"!==g)// What the browser shows on an input without a value.
|
|
1432
|
-
return {raw:g,source:"value"}}else if("checkbox"===g||"radio"===g){// The label the browser ties to the box, never the box's value.
|
|
1433
|
-
var j=a.labels?a.labels[0]:void 0,d=j&&!isUnsafeLabelSource(j)&&j.textContent?j.textContent.trim():"";if(d)return {raw:d,source:"label"}}}else if(f){var d=textOf(a);if(d)return {raw:d,source:"text"};var k=a.querySelector("img[alt]"),h=k?nonBlank(k.getAttribute("alt")):void 0;if(h)return {raw:h,source:"alt"}}var l=nonBlank(a.getAttribute("title"));return l?{raw:l,source:"title"}:{source:"none"}}var ICON_CLASS=/^(?:fa|fas|far|fal|icon|bi|glyphicon|ti|mdi|ri|la|lucide|ion|feather|ph)-([a-z][a-z-]{1,31})$/,ICON_MODIFIER=/^(?:solid|regular|light|thin|duotone|brands|sharp|fw|lg|xs|sm|xl|spin|pulse|border|inverse|stack|flip(?:-[a-z]+)?|rotate(?:-[a-z]+)?|pull-[a-z]+)$/;// Size, style and animation classes that share the icon prefixes.
|
|
1434
|
-
function iconToken(a){if(a){var b=a.toLowerCase().replace(/^icon-/,"");return /^[a-z][a-z-]{1,31}$/.test(b)?b:void 0}}// An icon name from an SVG sprite reference or an icon-font class, for buttons
|
|
1435
|
-
// whose only content is an icon. Letters and hyphens only.
|
|
1436
|
-
function iconHint(a){var b=function(a){return !hasComposedAncestor(a,"[data-mp-no-track]")},c=Array.from(a.querySelectorAll("use")).filter(b)[0];if(c){var d=c.getAttribute("href")||c.getAttribute("xlink:href")||"",e=d.indexOf("#"),f=iconToken(-1===e?null:d.slice(e+1));if(f)return f}for(var g=[a].concat(Array.from(a.querySelectorAll("i, span, svg"))).filter(b).slice(0,5),h=0,i=g;h<i.length;h++)for(var j=i[h],k=(j.getAttribute("class")||"").split(/\s+/),l=0,m=k;l<m.length;l++){var n=m[l],o=ICON_CLASS.exec(n.toLowerCase());if(o&&!ICON_MODIFIER.test(o[1]))return o[1]}}// Words of letters, each optionally ending in up to three digits, joined by
|
|
1437
|
-
// hyphens or underscores: `add-to-cart`, `btnCheckout`, `step_2`. Generated ids
|
|
1438
|
-
// (`ember1234`, `a8f3e2c1`, `radix-:r1:`) and long numbers don't match.
|
|
1439
|
-
var HAND_WRITTEN_ID=/^[A-Za-z]+[0-9]{0,3}(?:[-_](?:[A-Za-z]+[0-9]{0,3}|[0-9]{1,3}))*$/;// A developer-written identifier, or nothing.
|
|
1440
|
-
function stableIdentifier(a){if(a){// At most three digits in all, so numbers split into groups don't pass.
|
|
1441
|
-
var b=a.trim(),c=b.replace(/[^0-9]/g,"").length;return 64>=b.length&&3>=c&&HAND_WRITTEN_ID.test(b)?b:void 0}}var TEST_ID_ATTRIBUTES=["data-testid","data-test-id","data-test","data-qa","data-cy"];// The first of these attributes that holds a developer-written identifier.
|
|
1442
|
-
function firstIdentifier(a,b){for(var c=0,d=b;c<d.length;c++){var e=d[c],f=stableIdentifier(a.getAttribute(e));if(f)return f}}// What the button opens or acts on: a menu, drawer or dialog. aria-controls can
|
|
1443
|
-
// list several ids, so only the first is used.
|
|
1444
|
-
function controlsIdentifier(a){var b=a.getAttribute("aria-controls");return stableIdentifier(b?b.trim().split(/\s+/)[0]:null)||firstIdentifier(a,["popovertarget","commandfor"])}// The id of the form a button or input actually submits, which the browser
|
|
1445
|
-
// resolves from its form attribute or its owning form. getAttribute, because a
|
|
1446
|
-
// field named "id" shadows form.id.
|
|
1447
|
-
function formIdentifier(a){var b=a instanceof HTMLButtonElement||a instanceof HTMLInputElement?a.form:null;return b?stableIdentifier(b.getAttribute("id")):void 0}// The browser's normalised type: a button defaults to 'submit' and an unknown
|
|
1448
|
-
// input type reads as 'text'. Wallet and role buttons are just 'button'.
|
|
1449
|
-
function controlType(a,b){return "button"===b||"input"===b?a.type:"button"}// Reads the link's own resolved URL parts, never its full href: only the hostname of
|
|
1450
|
-
// a link that leaves the site and the extension of a file it downloads travel. Navigation
|
|
1451
|
-
// within the site is left to page views, and mailto:, tel: and other schemes are skipped.
|
|
1452
|
-
function describeLink(a){var b=(a.getAttribute("href")||"").trim();if(!b||"#"===b.charAt(0))return {type:"same_page"};if(a instanceof HTMLAnchorElement){var c=a.protocol.toLowerCase();if("javascript:"===c)return {type:"same_page"};if("http:"===c||"https:"===c){var d=a.hostname===window.location.hostname?void 0:a.hostname.toLowerCase(),e=DOWNLOAD_EXTENSIONS.exec(a.pathname);return a.hasAttribute("download")||e?{type:"download",domain:d,fileExtension:e?e[1].toLowerCase():void 0}:d?{type:"outbound",domain:d}:a.pathname===window.location.pathname&&a.search===window.location.search?{type:"same_page"}:void 0}}}// Describes a clicked control for auto button tracking. A link counts only when page
|
|
1453
|
-
// views can't see the click, and carries its link type.
|
|
1454
|
-
function describeButtonClick(a){var b;if(!(a.matches("a[href]:not([role=\"button\"])")&&(b=describeLink(a),!b))){var c=elementKind(a),d=accessibleName(a),e=maskLabel(d.raw);return {label:e,labelSource:e?d.source:"none",// Kept on its own as well: it often says more than the visible text,
|
|
1455
|
-
// such as which item a remove button removes.
|
|
1456
|
-
ariaLabel:maskLabel(a.getAttribute("aria-label")),icon:iconHint(a),elementId:stableIdentifier(a.getAttribute("id")),elementName:stableIdentifier(a.getAttribute("name")),testId:firstIdentifier(a,TEST_ID_ATTRIBUTES),controls:controlsIdentifier(a),form:formIdentifier(a),element:c,type:controlType(a,c),linkType:b?b.type:void 0,linkDomain:b?b.domain:void 0,fileExtension:b?b.fileExtension:void 0,// The box as the click left it: the browser toggles it before the click
|
|
1457
|
-
// reaches listeners, and puts it back if the click is cancelled.
|
|
1458
|
-
checked:a instanceof HTMLInputElement&&("checkbox"===a.type||"radio"===a.type)?a.checked:void 0}}}
|
|
1459
|
-
|
|
1460
|
-
var checkoutPath=/(?:^|\/)(?:checkouts?|payment|order|kasse|paiement|commander?|pago)(?:\/|$)/i,englishExclusions=/\b(?:coupon|promo(?: code)?|newsletter|sign in|sign up|log in|login|add to (?:cart|bag|basket)|gift card balance|(?:add|apply|redeem|check|enter|use) (?:a |an |your )?gift card|pay later|interest free|as low as|learn more|prequalify|apply (?:now|for)|payment plan|available|accepted|we accept|set up|add money|reload|top up|add to (?:apple|google) wallet|connect|link your|unlink|remove|delete|edit|change|manage|use a different|switch)\b|^pay in$|\bpay in (?:installments|instalments)\b/,otherExclusions=new RegExp("gutschein|anmelden|warenkorb|bon cadeau|connexion|panier|cup\xF3n|iniciar sesi\xF3n|carrito|carrello|codice sconto|accedi|buono regalo|winkelwagen|kortingscode|inloggen|cadeaubon|achteraf betalen|\u30AB\u30FC\u30C8|\u30AF\u30FC\u30DD\u30F3|\u30ED\u30B0\u30A4\u30F3|\u4F1A\u54E1\u767B\u9332|\u30AE\u30D5\u30C8|\u5F8C\u6255\u3044|\u30E1\u30EB\u30DE\u30AC"),englishCommits="(?:(?:agree|accept|review) and )?(?:place|submit|complete|confirm|finali[sz]e)(?!(?: [^ ]+){0,2} (?:another|new|next)(?: |$))(?! (?:[^ ]+ )?gift card)(?: [^ ]+){0,2} (?:order|purchase|booking|reservation|payment|checkout|transaction)(?: now| securely| and pay| (?:with|using) [^ ]+(?: [^ ]+)?)?(?: (?:total|subtotal|items?|tickets?))?|pay(?: securely)?(?: now)?|(?:confirm|agree|accept|submit|order|book) and pay|pay and place (?:my |your )?order|order with obligation to pay",otherCommits="(?:jetzt )?(?:zahlungs|kosten)pflichtig (?:bestellen|buchen)|(?:jetzt )?bezahlen|kauf abschlie\xDFen|bestellung abschlie\xDFen|commander et payer|payer(?: maintenant)?|(?:confirmer|finaliser) (?:ma |la )?commande|valider et payer|confirmer et payer|commande avec obligation de paiement|finaliser l'achat|(?:realizar|confirmar|completar) (?:el |mi |la )?(?:pedido|compra|reserva)|finalizar (?:el |mi )?pedido|pagar(?: ahora)?|pedido con obligaci\xF3n de pago|(?:effettua|conferma|concludi|completa) (?:l'|il )?(?:ordine|acquisto)|ordine con obbligo di pagamento|paga(?: ora| adesso)?|ordina e paga|(?:nu )?betalen|bestellen en betalen|bestelling plaatsen|plaats bestelling|bestelling afronden|bestelling met betalingsverplichting|(?:\u3053\u306E\u5185\u5BB9\u3067|\u4E0A\u8A18\u306E?\u5185\u5BB9\u3067)?\u3054?(?:\u6CE8\u6587|\u8CFC\u5165|\u4E88\u7D04|\u6C7A\u6E08|\u304A?\u652F\u6255\u3044?)\u3092?(?:\u78BA\u5B9A|\u5B8C\u4E86)(?:\u3059\u308B)?|(?:\u3053\u306E\u5185\u5BB9\u3067|\u4E0A\u8A18\u306E?\u5185\u5BB9\u3067)\u3054?(?:\u6CE8\u6587|\u8CFC\u5165|\u4E88\u7D04)\u3059\u308B|\u3054?\u6CE8\u6587\u3059\u308B|\u6C7A\u6E08\u3059\u308B|(?:\u4ECA\u3059\u3050|\u3092)?\u652F\u6255\u3046",commits=new RegExp("^(?:"+englishCommits+"|"+otherCommits+")$"),linkCommits=new RegExp("^(?:(?:place|submit|complete)(?!(?: [^ ]+){0,2} (?:another|new|next)(?: |$))(?: [^ ]+){0,2} (?:order|purchase)|"+otherCommits+")$"),routeGatedCommits=/^(?:buy now|purchase|jetzt kaufen|kaufen|commander|(?:passer|valider) (?:la |ma )?commande|finalizar (?:la |mi )?compra|comprar ahora|acquista ora|nu kopen|\u4ECA\u3059\u3050\u8CFC\u5165|\u8CFC\u5165\u3059\u308B|\u3053\u306E\u5185\u5BB9\u3067\u7533\u3057\u8FBC\u3080)$/,steps=new RegExp("^(?:"+"(?:let's |lets |go to |proceed to |secure )?(?:check ?out|checkout)(?: now| securely| as guest)?|(?:continue|proceed) to (?:payment|review|billing|shipping|delivery|order review)|review (?:my |your )?order|guest checkout|(?:pay|continue|check ?out) (?:with|by) (?:card|credit card|debit card|credit or debit card)|zur kasse|zur kasse gehen|auschecken|weiter zur zahlung|passer \xE0 la caisse|continuer vers le paiement|proc\xE9der au paiement|ir a caja|continuar al pago|tramitar pedido|procedi al checkout|procedi all'acquisto|procedi al pagamento|vai alla cassa|afrekenen|verder naar betalen|doorgaan naar betalen|\u30EC\u30B8\u306B\u9032\u3080|\u3054?(?:\u8CFC\u5165|\u6CE8\u6587)\u624B\u7D9A\u304D(?:\u3078|\u306B)(?:\u9032\u3080)?|\u304A?\u652F\u6255\u3044(?:\u3078|\u306B)\u9032\u3080|(?:\u3054\u6CE8\u6587\u5185\u5BB9\u306E)?\u78BA\u8A8D\u753B\u9762\u3078(?:\u9032\u3080)?"+")$"),WALLET_NAMES="apple pay|google pay|paypal|venmo|amazon pay|shop pay|klarna|afterpay|clearpay|cash app(?: pay)?|affirm|sezzle|samsung pay",WALLET_VERBS="pay|buy|purchase|order|book|donate|subscribe|check ?out|checkout|express checkout|continue|proceed|complete purchase|place (?:my |your )?order",walletPhrases=new RegExp("^(?:(?:"+WALLET_VERBS+")(?: now| securely)? (?:with|using|via|through|by) (?:"+WALLET_NAMES+")(?: express(?: checkout)?| checkout)?|(?:continue|proceed|go) (?:to|with) (?:"+WALLET_NAMES+"))$"),walletBrands=new RegExp("^(?:"+WALLET_NAMES+")(?: (?:checkout|check out|express(?: checkout)?|express pay|buy now|pay now|pay|now)| (?:logo|icon|mark|button)(?: (?:logo|icon|mark|button))*)?$"),walletFrameHosts=new Set(["pay.google.com","applepay.cdn-apple.com","payments.amazon.com","pay.shopify.com"]),paypalFrameHosts=new Set(["www.paypal.com","www.sandbox.paypal.com"]),PAYPAL_BUTTON_FRAME=/^\/smart\/(?:buttons|menu)(?:\/|$)/,STRIPE_WALLET_FRAME=/\/elements-inner-(?:payment-request|express-checkout)-/,CARD_FRAME_DOMAINS=["adyen.com","braintreegateway.com","cybersource.com","squarecdn.com","checkout.com"],TYPOGRAPHIC_APOSTROPHES=/[\u2019\u2018]/g,CURRENCY_AND_NUMBER_CHARS=/[0-9\uFF10-\uFF19$\u20AC\u00A3\u00A5\uFFE5\u20B9\u5186.,\uFF0C]/g,BRACKETED=/\([^()]*\)|\[[^[\]]*\]|\uFF08[^\uFF08\uFF09]*\uFF09|\uFF3B[^\uFF3B\uFF3D]*\uFF3D|\u3010[^\u3010\u3011]*\u3011/g,EDGE="[\\s!-/:-@\\[-`{-~\\u00A1-\\u00BF\\u00D7\\u00F7\\u2000-\\u206F\\u20A0-\\u20CF\\u2190-\\u2BFF\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u30FB\\uD800-\\uDFFF\\uFE00-\\uFE0F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65]+",EDGE_SYMBOLS=new RegExp("^"+EDGE+"|"+EDGE+"$","g");// English look-alikes are whole words; the other languages stay substring
|
|
1461
|
-
// matches, since several of them do not separate words with spaces.
|
|
1462
|
-
// A plain link is navigation, so in English only an order or purchase it
|
|
1463
|
-
// places, submits or completes counts as the confirm click.
|
|
1464
|
-
// "Pay with Klarna", "Buy with GPay", "Continue to PayPal".
|
|
1465
|
-
// A wallet's own name on a button: "PayPal", "Klarna checkout", "Apple Pay logo".
|
|
1466
|
-
// Exact HTTPS hosts of hosted wallet button frames.
|
|
1467
|
-
// PayPal serves its buttons and its card fields and pay-later messages from
|
|
1468
|
-
// the same hosts; only the button frames are wallet taps.
|
|
1469
|
-
// Stripe's quick-pay button frames; its other frames are card and form fields.
|
|
1470
|
-
// Hosted card-entry and fingerprint frames: focus there is typing card details.
|
|
1471
|
-
// Keep these classes ASCII-only in source bytes to avoid mojibake parse failures
|
|
1472
|
-
// when a host page forces non-UTF-8 decoding before JavaScript parse.
|
|
1473
|
-
// Spaces, punctuation, separators, arrows and symbols, CJK and full-width forms
|
|
1474
|
-
// included, plus emoji halves and variation selectors.
|
|
1475
|
-
function getIntentRouteClass(a){return checkoutPath.test(a)?"checkout_path":"other"}var SEPARATORS=/[-_|\u00B7\u2022]/g,CURRENCY_CODES=/(?:^| )(?:usd|aud|cad|nzd|gbp|eur|chf|sgd|hkd|jpy|inr|mxn)(?= |$)|\b(?:a|au|ca|c|us|nz|hk|s)\$/g,WALLET_ALIASES=[[/\bapplepay\b/g,"apple pay"],[/\bg ?pay\b/g,"google pay"],[/\bamazonpay\b/g,"amazon pay"],[/\bshoppay\b/g,"shop pay"],[/\bcashapp\b/g,"cash app"]],MAX_LABEL_WORDS=8;// Labels longer than this are sentences: they neither match nor veto intent.
|
|
1476
|
-
function normalize(a){if(a&&!(128<a.length)){var b=a.toLowerCase().replace(TYPOGRAPHIC_APOSTROPHES,"'").replace(/[&+]/g," and ").replace(SEPARATORS," ").replace(CURRENCY_CODES," ").replace(CURRENCY_AND_NUMBER_CHARS,"").replace(/\s+/g," ").trim();return WALLET_ALIASES.forEach(function(a){var c=a[0],d=a[1];b=b.replace(c,d);}),b.split(" ").length>MAX_LABEL_WORDS?void 0:b}}// The label without bracketed asides or the separators and symbols left at its
|
|
1477
|
-
// edges, so "place order -" and "place order ( items)" both read "place order".
|
|
1478
|
-
function coreLabel(a){var b=a.replace(BRACKETED," ").replace(/\s+/g," ").replace(EDGE_SYMBOLS,"");return b||a.replace(EDGE_SYMBOLS,"")}// Labels come from aria-label then visible text. Only submit and button inputs
|
|
1479
|
-
// have their value read, so a typed field value is never touched. A control
|
|
1480
|
-
// holding form fields or more than four children gives only its aria-label.
|
|
1481
|
-
function labelSources(a){if(a instanceof HTMLInputElement){var b=a.type,c=null;return "submit"===b||"button"===b?c=a.value:"image"===b&&(c=a.getAttribute("alt")),[a.getAttribute("aria-label"),c]}return 4<a.children.length||isUnsafeTextSource(a)?[a.getAttribute("aria-label")]:[a.getAttribute("aria-label"),a.textContent]}function labels(a){return labelSources(a).map(normalize).filter(function(a){return !!a})}// "Buy now" and "Purchase" count only on a checkout route, and never on a plain
|
|
1482
|
-
// link, which is navigation.
|
|
1483
|
-
function isCommitLabel(a,b,c){return b?linkCommits.test(a):commits.test(a)||routeGatedCommits.test(a)&&"checkout_path"===getIntentRouteClass(c)}// Classifies a clicked or submitting control found by findControl, in order:
|
|
1484
|
-
// pickers, toggles and pay-later messages never count; a vendor's own wallet
|
|
1485
|
-
// button counts before any label rule; a confirm label on any source counts
|
|
1486
|
-
// before the look-alike exclusions veto; then wallet phrases and steps.
|
|
1487
|
-
function classifyIntent(a,b){var c=vendorButtonKind(a);if(!(isQuietIntentControl(a,"wallet"===c)||"none"===c)){if(c)return {kind:c,source:"vendor"};var d=labels(a),e=d.map(coreLabel),f=a.matches("a[href]:not([role=\"button\"])");if(e.some(function(a){return isCommitLabel(a,f,b)}))return {kind:"commit",source:"label"};if(!d.concat(e).some(function(a){return englishExclusions.test(a)||otherExclusions.test(a)}))for(var g,h=!f&&a.matches(CONTROL_SELECTOR),i=0;i<(void 0).length;i++){if(g=(void 0)[i],h&&walletPhrases.test(g))return {kind:"wallet",source:"label"};if(h&&walletBrands.test(g))return {kind:"wallet",source:"brand"};if(steps.test(g))return {kind:"checkout_step",source:"label"}}}}function isOnDomain(a,b){return a===b||a.length>b.length&&a.slice(a.length-b.length-1)==="."+b}// Focus moving into a visible hosted wallet button counts as a wallet click;
|
|
1488
|
-
// focus into hosted card fields or messages is only a frame.
|
|
1489
|
-
function classifyIntentFrame(a,b){if("visible"===b.document.visibilityState&&a instanceof HTMLIFrameElement&&!(isRoktElement(a)||hasComposedAncestor(a,"[data-mp-no-track]")))try{var c=new URL(a.src),d="https:"===c.protocol?c.hostname:"";if(paypalFrameHosts.has(d))return PAYPAL_BUTTON_FRAME.test(c.pathname)?"wallet":"frame";if(walletFrameHosts.has(d))return "wallet";if("js.stripe.com"===d)return STRIPE_WALLET_FRAME.test(c.pathname)?"wallet":"frame";if(CARD_FRAME_DOMAINS.some(function(a){return isOnDomain(d,a)}))return "frame"}catch(a){// An unparseable frame src is not a wallet frame.
|
|
1490
|
-
}}
|
|
1491
|
-
|
|
1492
|
-
// listeners. Inspect `window.__mpBtn__` in a console to see if one is live.
|
|
1493
|
-
var WIN_BTN_KEY="__mpBtn__";var THROTTLE_MS=2e3,SUBMIT_AFTER_COMMIT_CLICK_MS=1e3,PATH_LIMIT=12,PAGE_EVENT_LIMIT=100,UPLOAD_DEBOUNCE_MS=100,btnWindow=function(){return "undefined"==typeof window?null:window};// A ceiling, not a dedupe: a held Enter key or browser automation fires a
|
|
1494
|
-
// trusted click per repeat, and each one is forwarded to every kit.
|
|
1495
|
-
// A click uploads at once. Taps that follow it this quickly are held and share
|
|
1496
|
-
// one upload once they stop.
|
|
1497
|
-
var getActiveButtonTracker=function(){var a=btnWindow(),b=a?a[WIN_BTN_KEY]:void 0;return b?b.tracker:void 0};// Stops whichever tracker is active, including one from an earlier bundle load.
|
|
1498
|
-
var resetButtonTracking=function(){var a=btnWindow();if(a){var b=getActiveButtonTracker();b&&b.teardown(),a[WIN_BTN_KEY]={};}};// Runs once the browser has painted the page's response to the interaction, so
|
|
1499
|
-
// describing and logging a click never delays that paint.
|
|
1500
|
-
var afterNextPaint=function(a){isFunction(window.requestAnimationFrame)&&"hidden"!==document.visibilityState?requestAnimationFrame(function(){setTimeout(a,0);}):setTimeout(a,0);},CAPTURE_PASSIVE={capture:!0,passive:!0},PASSIVE={passive:!0},ButtonTracker=/** @class */function(){function a(a){var b=this;this.active=!1,this.hasRoktKit=!1,this.generation=0,this.lastCommitClick=-Infinity,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.pending=[],this.uploadTimerId=null,this.uploadHeld=!1,this.leaving=!1,this.drain=function(){var a=b.pending;b.pending=[],a.forEach(function(a){return a()});},this.onHide=function(a){if("beforeunload"===a.type||"pagehide"===a.type||"hidden"===document.visibilityState){b.leaving=!0;try{b.drain();}finally{b.leaving=!1;}// The SDK's exit upload sends the queue, held taps included.
|
|
1501
|
-
b.cancelUpload();}},this.onPageShow=function(a){a.persisted&&b.reset();},this.onEvent=function(a){try{b.observe(a);}catch(a){b.log("[error] event handler threw: "+a);}},this.mpInstance=a;}return Object.defineProperty(a.prototype,"isActive",{get:function get(){return this.active},enumerable:!1,configurable:!0}),a.prototype.init=function(a){var b=btnWindow();if(b){var c=getActiveButtonTracker();return c&&c.teardown(),this.active&&this.teardown(),this.hasRoktKit=a.hasRoktKit,!this.eventsEnabled()&&this.isKitSuppressed()?void this.log("opted out, not starting"):void(b.document.addEventListener("click",this.onEvent,CAPTURE_PASSIVE),b.document.addEventListener("submit",this.onEvent,CAPTURE_PASSIVE),b.addEventListener("blur",this.onEvent,PASSIVE),b.addEventListener("pageshow",this.onPageShow,PASSIVE),b.addEventListener("beforeunload",this.onHide,CAPTURE_PASSIVE),b.addEventListener("pagehide",this.onHide,CAPTURE_PASSIVE),b.document.addEventListener("visibilitychange",this.onHide,CAPTURE_PASSIVE),this.active=!0,!b[WIN_BTN_KEY]&&(b[WIN_BTN_KEY]={}),b[WIN_BTN_KEY].tracker=this,this.log("listening"))}},a.prototype.teardown=function(){var a=btnWindow();if(a){a.document.removeEventListener("click",this.onEvent,!0),a.document.removeEventListener("submit",this.onEvent,!0),a.removeEventListener("blur",this.onEvent),a.removeEventListener("pageshow",this.onPageShow),a.removeEventListener("beforeunload",this.onHide,!0),a.removeEventListener("pagehide",this.onHide,!0),a.document.removeEventListener("visibilitychange",this.onHide,!0);var b=a[WIN_BTN_KEY];b&&b.tracker===this&&(b.tracker=void 0);}this.active=!1,this.clearPending();},a.prototype.clearPending=function(){this.reset();var a=this.mpInstance._RoktManager;a&&a.discardCheckoutIntents();},a.prototype.reset=function(){this.generation++,this.pending=[],this.lastCommitClick=-Infinity,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.cancelUpload();},a.prototype.enqueue=function(a){this.pending.push(a),1===this.pending.length&&afterNextPaint(this.drain);},a.prototype.observe=function(a){var b=this;if(this.active&&a.isTrusted){// The button is read now, while the click is still being dispatched:
|
|
1502
|
-
// this capture listener runs before the page's own handlers, so a
|
|
1503
|
-
// button that disables or relabels itself is seen as it was clicked.
|
|
1504
|
-
// Logging and the kit hand-off wait for the next paint.
|
|
1505
|
-
var c=a.type,d="click"===c&&this.eventsEnabled(),e=!this.isKitSuppressed();if(d||e){var f,g,h,i,j=Date.now(),k=window.location.pathname,l=!1;if("click"===c){// The composed path is only populated during dispatch.
|
|
1506
|
-
var m=findControl(isFunction(a.composedPath)?a.composedPath().slice(0,PATH_LIMIT):[]);if(m){f=d?describeButtonClick(m):void 0,f&&void 0!==f.checked&&(g=m);// Checkout intent is only worked out when the kit can use it.
|
|
1507
|
-
var n=e?classifyIntent(m,k):void 0;h=n?n.kind:void 0,i=n?n.source:void 0;}}else if("submit"===c){var o=a.submitter,m=o?findControl([o]):void 0;// A form submitted without a submitter only counts right after a
|
|
1508
|
-
// commit click, which is known once that click is delivered.
|
|
1509
|
-
if(!o)h="commit",i="submit";else if(m){var n=classifyIntent(m,k);h=n?n.kind:void 0,i=n?n.source:void 0;}l=!o;}var p=this.generation;this.enqueue(function(){if(p===b.generation)try{"blur"===c?(h=classifyIntentFrame(document.activeElement,window),i="frame"):l&&j-b.lastCommitClick>SUBMIT_AFTER_COMMIT_CLICK_MS&&(h=void 0),f&&d&&(g&&a.defaultPrevented&&(f.checked="checkbox"===g.type?!f.checked:g.checked),b.logClick(f,k)),h&&b.emit(h,i,c,j,k);}catch(a){b.log("[error] delivery threw: "+a);}});}}},a.prototype.logClick=function(a,b){if(this.eventsEnabled()&&(b!==this.pagePath&&(this.pagePath=b,this.pageEvents=0),!(this.pageEvents>=PAGE_EVENT_LIMIT))){this.pageEvents++,this.mpInstance._SessionManager.resetSessionTimer();var c=this.queuedForUpload();this.mpInstance._Events.logEvent(buildButtonClickEvent(a,b)),!this.leaving&&void 0===a.checked&&this.queuedForUpload()>c&&this.uploadNow();}},a.prototype.queuedForUpload=function(){var a=this.mpInstance._APIClient.uploader;return a?a.eventsQueuedForProcessing.length:0},a.prototype.uploadNow=function(){var a=this;null===this.uploadTimerId?this.mpInstance.upload():(clearTimeout(this.uploadTimerId),this.uploadHeld=!0),this.uploadTimerId=setTimeout(function(){a.uploadTimerId=null,a.uploadHeld&&(a.uploadHeld=!1,a.mpInstance.upload());},UPLOAD_DEBOUNCE_MS);},a.prototype.cancelUpload=function(){null!==this.uploadTimerId&&(clearTimeout(this.uploadTimerId),this.uploadTimerId=null),this.uploadHeld=!1;},a.prototype.emit=function(a,b,c,d,e){if(!this.isKitSuppressed()){"commit"===a&&"click"===c&&(this.lastCommitClick=d);var f=this.lastSent[a];f&&f.pathname===e&&d-f.t<THROTTLE_MS||(this.lastSent[a]={t:d,pathname:e},this.mpInstance._RoktManager.notifyCheckoutIntent(Object.freeze({kind:a,t:d,source:b,pathname:e}),e));}},a.prototype.eventsEnabled=function(){var a=this.mpInstance._Store;return !!a&&a.isEnabled},a.prototype.isKitSuppressed=function(){var a=this.mpInstance._RoktManager;return !this.hasRoktKit||!a||a.isCheckoutIntentSuppressed()},a.prototype.log=function(a){this.mpInstance.Logger.verbose("mParticle button tracking: "+a);},a}();// Logs every button click as an mParticle event, and hands checkout intent to the
|
|
1510
|
-
|
|
1511
|
-
var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,CaptureIntegrationSpecificIdsV2Modes=Constants.CaptureIntegrationSpecificIdsV2Modes,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,CaptureIntegrationSpecificIdsV2=FeatureFlags.CaptureIntegrationSpecificIdsV2,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
|
|
1512
|
-
* <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
|
|
1513
|
-
* <p>In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.</p>
|
|
1514
|
-
* <p>This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().</p>
|
|
1515
|
-
* <p>If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:</p>
|
|
1516
|
-
* <code>
|
|
1517
|
-
* mParticle.init('apiKey', config, 'another_instance');
|
|
1518
|
-
* mParticle.getInstance('another_instance').logPageView();
|
|
1519
|
-
* </code>
|
|
1520
|
-
*
|
|
1521
|
-
* @class mParticle & mParticleInstance
|
|
1522
|
-
*/function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption
|
|
1523
|
-
this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._ErrorReportingDispatcher=new ErrorReportingDispatcher,this._LoggingDispatcher=new LoggingDispatcher,this._RoktManager=new RoktManager(a),this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue,b.Logger));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue,b.Logger));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.RoktEvents=RoktEvents,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
|
|
1524
|
-
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
|
|
1525
|
-
// to it for it to be run after fetched
|
|
1526
|
-
if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{// The Rokt manager keeps its own store reference, so stop button
|
|
1527
|
-
// tracking here rather than relying on the deleted store.
|
|
1528
|
-
a._Persistence.resetPersistence(),resetButtonTracking(),a._ButtonTracker=void 0,a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._ErrorReportingDispatcher.logger=c.Logger,c._LoggingDispatcher.logger=c.Logger,c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),resetPageViewTracking(),c._PageViewTracker=void 0,resetButtonTracking(),c._ButtonTracker=void 0,b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval
|
|
1529
|
-
b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/**
|
|
1530
|
-
* Creates a CCPA Opt Out Consent State.
|
|
1531
|
-
*
|
|
1532
|
-
* @method createCCPAConsent
|
|
1533
|
-
* @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
|
|
1534
|
-
* @param {Number} timestamp Unix time (likely to be Date.now())
|
|
1535
|
-
* @param {String} consentDocument document version or experience that the user may have consented to
|
|
1536
|
-
* @param {String} location location where the user gave consent
|
|
1537
|
-
* @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
|
|
1538
|
-
* @return {Object} CCPA Consent State
|
|
1539
|
-
*/createCCPAConsent:b._Consent.createPrivacyConsent,/**
|
|
1540
|
-
* Creates a GDPR Consent State.
|
|
1541
|
-
*
|
|
1542
|
-
* @method createGDPRConsent
|
|
1543
|
-
* @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
|
|
1544
|
-
* @param {Number} timestamp Unix time (likely to be Date.now())
|
|
1545
|
-
* @param {String} consentDocument document version or experience that the user may have consented to
|
|
1546
|
-
* @param {String} location location where the user gave consent
|
|
1547
|
-
* @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
|
|
1548
|
-
* @return {Object} GDPR Consent State
|
|
1549
|
-
*/createGDPRConsent:b._Consent.createPrivacyConsent,/**
|
|
1550
|
-
* Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states.
|
|
1551
|
-
*
|
|
1552
|
-
* @method createConsentState
|
|
1553
|
-
* @return {Object} ConsentState object
|
|
1554
|
-
*/createConsentState:b._Consent.createConsentState},this.eCommerce={/**
|
|
1555
|
-
* Sets the currency code
|
|
1556
|
-
* @for mParticle.eCommerce
|
|
1557
|
-
* @method setCurrencyCode
|
|
1558
|
-
* @param {String} code The currency code
|
|
1559
|
-
*/setCurrencyCode:function setCurrencyCode(a){var c=queueIfNotInitialized(function(){b.eCommerce.setCurrencyCode(a);},b);return c?void 0:"string"==typeof a?void(b._SessionManager.resetSessionTimer(),b._Store.currencyCode=a):void b.Logger.error("Code must be a string")},/**
|
|
1560
|
-
* Creates a product
|
|
1561
|
-
* @for mParticle.eCommerce
|
|
1562
|
-
* @method createProduct
|
|
1563
|
-
* @param {String} name product name
|
|
1564
|
-
* @param {String} sku product sku
|
|
1565
|
-
* @param {Number} price product price
|
|
1566
|
-
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
|
|
1567
|
-
* @param {String} [variant] product variant
|
|
1568
|
-
* @param {String} [category] product category
|
|
1569
|
-
* @param {String} [brand] product brand
|
|
1570
|
-
* @param {Number} [position] product position
|
|
1571
|
-
* @param {String} [coupon] product coupon
|
|
1572
|
-
* @param {Object} [attributes] product attributes
|
|
1573
|
-
*/createProduct:function createProduct(a,c,d,e,f,g,h,i,j,k){return b._Ecommerce.createProduct(a,c,d,e,f,g,h,i,j,k)},/**
|
|
1574
|
-
* Creates a promotion
|
|
1575
|
-
* @for mParticle.eCommerce
|
|
1576
|
-
* @method createPromotion
|
|
1577
|
-
* @param {String} id a unique promotion id
|
|
1578
|
-
* @param {String} [creative] promotion creative
|
|
1579
|
-
* @param {String} [name] promotion name
|
|
1580
|
-
* @param {Number} [position] promotion position
|
|
1581
|
-
*/createPromotion:function createPromotion(a,c,d,e){return b._Ecommerce.createPromotion(a,c,d,e)},/**
|
|
1582
|
-
* Creates a product impression
|
|
1583
|
-
* @for mParticle.eCommerce
|
|
1584
|
-
* @method createImpression
|
|
1585
|
-
* @param {String} name impression name
|
|
1586
|
-
* @param {Object} product the product for which an impression is being created
|
|
1587
|
-
*/createImpression:function createImpression(a,c){return b._Ecommerce.createImpression(a,c)},/**
|
|
1588
|
-
* Creates a transaction attributes object to be used with a checkout
|
|
1589
|
-
* @for mParticle.eCommerce
|
|
1590
|
-
* @method createTransactionAttributes
|
|
1591
|
-
* @param {String or Number} id a unique transaction id
|
|
1592
|
-
* @param {String} [affiliation] affilliation
|
|
1593
|
-
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
|
|
1594
|
-
* @param {Number} [revenue] total revenue for the product being purchased
|
|
1595
|
-
* @param {String} [shipping] the shipping method
|
|
1596
|
-
* @param {Number} [tax] the tax amount
|
|
1597
|
-
*/createTransactionAttributes:function createTransactionAttributes(a,c,d,e,f,g){return b._Ecommerce.createTransactionAttributes(a,c,d,e,f,g)},/**
|
|
1598
|
-
* Logs a product action
|
|
1599
|
-
* @for mParticle.eCommerce
|
|
1600
|
-
* @method logProductAction
|
|
1601
|
-
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
|
|
1602
|
-
* @param {Object} product the product for which you are creating the product action
|
|
1603
|
-
* @param {Object} [attrs] attributes related to the product action
|
|
1604
|
-
* @param {Object} [customFlags] Custom flags for the event
|
|
1605
|
-
* @param {Object} [transactionAttributes] Transaction Attributes for the event
|
|
1606
|
-
* @param {Object} [eventOptions] For Event-level Configuration Options
|
|
1607
|
-
*/logProductAction:function logProductAction(a,c,d,e,f,g){var h=queueIfNotInitialized(function(){b.eCommerce.logProductAction(a,c,d,e,f,g);},b);h||(b._SessionManager.resetSessionTimer(),b._Events.logProductActionEvent(a,c,d,e,f,g));},/**
|
|
1608
|
-
* Logs a product purchase
|
|
1609
|
-
* @for mParticle.eCommerce
|
|
1610
|
-
* @method logPurchase
|
|
1611
|
-
* @param {Object} transactionAttributes transactionAttributes object
|
|
1612
|
-
* @param {Object} product the product being purchased
|
|
1613
|
-
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
|
|
1614
|
-
* @param {Object} [attrs] other attributes related to the product purchase
|
|
1615
|
-
* @param {Object} [customFlags] Custom flags for the event
|
|
1616
|
-
* @deprecated Use `logProductAction` with `ProductActionType.Purchase` instead.
|
|
1617
|
-
*/logPurchase:function logPurchase(a,c,d,e,f){return logDeprecatedMethodUsage({methodName:"mParticle.logPurchase",warningMessage:"mParticle.logPurchase is deprecated, please use mParticle.logProductAction with ProductActionType.Purchase instead"},b.Logger,b._ErrorReportingDispatcher),b._Store.isInitialized?a&&c?void(b._SessionManager.resetSessionTimer(),b._Events.logPurchaseEvent(a,c,e,f)):void b.Logger.error(Messages.ErrorMessages.BadLogPurchase):void b.ready(function(){b.eCommerce.logPurchase(a,c,d,e,f);})},/**
|
|
1618
|
-
* Logs a product promotion
|
|
1619
|
-
* @for mParticle.eCommerce
|
|
1620
|
-
* @method logPromotion
|
|
1621
|
-
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
|
|
1622
|
-
* @param {Object} promotion promotion object
|
|
1623
|
-
* @param {Object} [attrs] boolean to clear the cart after logging or not
|
|
1624
|
-
* @param {Object} [customFlags] Custom flags for the event
|
|
1625
|
-
* @param {Object} [eventOptions] For Event-level Configuration Options
|
|
1626
|
-
*/logPromotion:function logPromotion(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.eCommerce.logPromotion(a,c,d,e,f);},b);g||(b._SessionManager.resetSessionTimer(),b._Events.logPromotionEvent(a,c,d,e,f));},/**
|
|
1627
|
-
* Logs a product impression
|
|
1628
|
-
* @for mParticle.eCommerce
|
|
1629
|
-
* @method logImpression
|
|
1630
|
-
* @param {Object} impression product impression object
|
|
1631
|
-
* @param {Object} attrs attributes related to the impression log
|
|
1632
|
-
* @param {Object} [customFlags] Custom flags for the event
|
|
1633
|
-
* @param {Object} [eventOptions] For Event-level Configuration Options
|
|
1634
|
-
*/logImpression:function logImpression(a,c,d,e){var f=queueIfNotInitialized(function(){b.eCommerce.logImpression(a,c,d,e);},b);f||(b._SessionManager.resetSessionTimer(),b._Events.logImpressionEvent(a,c,d,e));},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie
|
|
1635
|
-
// And logs to in-memory object
|
|
1636
|
-
// Example: mParticle.setSessionAttribute('location', '33431');
|
|
1637
|
-
if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,a&&(b._ButtonTracker&&b._ButtonTracker.clearPending(),b._RoktManager.discardCheckoutIntents()),b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed
|
|
1638
|
-
if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any
|
|
1639
|
-
// other integration delays set to true. It not, process the queued events/.
|
|
1640
|
-
var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this._registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this._registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment
|
|
1641
|
-
function completeSDKInitialization(a,b,c){var d,e,f,g,h=createKitBlocker(b,c),i=c._Helpers.getFeatureFlag,j=Constants.FeatureFlags,k=j.AutoLogPageView,l=j.AutoButtonTracking;// Destroy previous batch uploader to prevent leaked timers and event listeners
|
|
1642
|
-
// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's
|
|
1643
|
-
// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not
|
|
1644
|
-
// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
|
|
1645
|
-
// persistence or Identity directly.
|
|
1646
|
-
if((null===(d=c._APIClient)||void 0===d?void 0:d.uploader)&&c._APIClient.uploader.destroy(),c._APIClient=new APIClient(c,h),c._Forwarders=new Forwarders(c,h),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a),resetButtonTracking();else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
|
|
1647
|
-
var m=c.Identity.getCurrentUser(),n=m?m.getMPID():null,o=m?m.getUserIdentities().userIdentities:{};// https://go.mparticle.com/work/SQDSDKS-7639
|
|
1648
|
-
if(c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:o}:c._Store.SDKConfig.identifyRequest,i(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),isIntegrationCaptureEnabled(i)){var p=i(CaptureIntegrationSpecificIds),q=i(CaptureIntegrationSpecificIdsV2),r=void 0;p||q===CaptureIntegrationSpecificIdsV2Modes.All?r="all":q===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(r="roktonly"),c._IntegrationCapture=new IntegrationCapture(r),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
|
|
1649
|
-
var s=parseConfig(b,"Rokt",181);if(s){var t=null===(e=s.settings)||void 0===e?void 0:e.accountId;c._Store.setRoktAccountId(t);var u=function(a){return filteredMparticleUser(a,s,c,h)},v={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};c._RoktManager.init(s,u(n),c.Identity,c._Store,c.Logger,v,c.captureTiming,c._ErrorReportingDispatcher,c._LoggingDispatcher,c._IntegrationCapture,u);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),i(k)?(!c._PageViewTracker&&(c.Logger.verbose("mParticle APV: [sdk-init] creating new PageViewTracker for this instance"),c._PageViewTracker=new PageViewTracker(c,{isAutoPageView:!0})),hasInitialPageViewFired()?c.Logger.verbose("mParticle APV: [sdk-init] initial page view already logged this page load, skipping"):(markInitialPageViewFired(),c._Events.logPageView({isAutoPageView:!0})),c._PageViewTracker.init()):c._PageViewTracker&&c._PageViewTracker.teardown(),i(l)?(!c._ButtonTracker&&(c._ButtonTracker=new ButtonTracker(c)),c._ButtonTracker.init({hasRoktKit:!!s})):resetButtonTracking(),processIdentityCallback(c,m,n,o);}// We will continue to clear out the ready queue as part of the initial init flow
|
|
1650
|
-
// if an identify request is unnecessary, such as if there is an existing session
|
|
1651
|
-
(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,null===(f=c._CookieConsentManager)||void 0===f?void 0:f.syncNoTargetingAttribute(c.Identity.getCurrentUser()),c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue,c.Logger)),null===(g=c.processQueueOnNoFunctional)||void 0===g?void 0:g.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
|
|
1652
|
-
function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
|
|
1653
|
-
1. Manually via config.dataPlanOptions (this takes priority)
|
|
1654
|
-
If not passed in manually, we user the server provided via either
|
|
1655
|
-
2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
|
|
1656
|
-
3. Self hosting via /config endpoint (config.dataPlanResult)
|
|
1657
|
-
*/return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault
|
|
1658
|
-
// ensures no identity response data is written to localStorage when noFunctional is true
|
|
1659
|
-
return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache")):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"))}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._ErrorReportingDispatcher.logger=a.Logger,a._LoggingDispatcher.logger=a.Logger,a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,resetButtonTracking(),a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions
|
|
1660
|
-
var d=normalizeRoktLauncherOptions(null===c||void 0===c?void 0:c.launcherOptions),e=d.noFunctional,f=d.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:e,noTargeting:f});// Check to see if localStorage is available before main configuration runs
|
|
1661
|
-
// since we will need this for the current implementation of user persistence
|
|
1662
|
-
// TODO: Refactor this when we refactor User Identity Persistence
|
|
1663
|
-
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never
|
|
1664
|
-
// receive an MPID. Let these calls through so events can still reach forwarders immediately.
|
|
1665
|
-
// sendEventToServer handles queuing for the MP server upload path separately.
|
|
1666
|
-
return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)}
|
|
1667
|
-
|
|
1668
|
-
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1669
|
-
var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
|
|
1670
|
-
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:mockFunction},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction},getTotalTimeOnSite:mockFunction},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}();
|
|
1671
|
-
|
|
1672
|
-
var MPSideloadedKit=/** @class */function(){function a(a){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],// The below filtering members are optional, but we instantiate them
|
|
1673
|
-
// to simplify public method assignment
|
|
1674
|
-
filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=a;}return a.prototype.addEventTypeFilter=function(a){var b=KitFilterHelper.hashEventType(a);this.filterDictionary.eventTypeFilters.push(b);},a.prototype.addEventNameFilter=function(a,b){var c=KitFilterHelper.hashEventName(b,a);this.filterDictionary.eventNameFilters.push(c);},a.prototype.addEventAttributeFilter=function(a,b,c){var d=KitFilterHelper.hashEventAttributeKey(a,b,c);this.filterDictionary.attributeFilters.push(d);},a.prototype.addScreenNameFilter=function(a){var b=KitFilterHelper.hashEventName(a,EventType.Unknown);this.filterDictionary.screenNameFilters.push(b);},a.prototype.addScreenAttributeFilter=function(a,b){var c=KitFilterHelper.hashEventAttributeKey(EventType.Unknown,a,b);this.filterDictionary.screenAttributeFilters.push(c);},a.prototype.addUserIdentityFilter=function(a){var b=KitFilterHelper.hashUserIdentity(a);this.filterDictionary.userIdentityFilters.push(b);},a.prototype.addUserAttributeFilter=function(a){var b=KitFilterHelper.hashUserAttribute(a);this.filterDictionary.userAttributeFilters.push(b);},a}();
|
|
1675
|
-
|
|
1676
|
-
Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticleInstanceManager(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing
|
|
1677
|
-
/**
|
|
1678
|
-
* Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used.
|
|
1679
|
-
* <p>
|
|
1680
|
-
* If you'd like to initiate multiple mParticle instances, first review our <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">doc site</a>, and ensure you pass a unique instance name as the third argument as shown below.
|
|
1681
|
-
* @method init
|
|
1682
|
-
* @param {String} apiKey your mParticle assigned API key
|
|
1683
|
-
* @param {Object} [config] an options object for additional configuration
|
|
1684
|
-
* @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples.
|
|
1685
|
-
*/ // Kits clean every URL they send with the same rule as core events.
|
|
1686
|
-
this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.RoktEvents=RoktEvents,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);},search:function search(b,c,d){a.getInstance().Identity.search(b,c,d);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSessionId()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this._cleanUrl=cleanUrl,this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this._registerErrorReportingService=function(b){a.getInstance()._registerErrorReportingService(b);},this._registerLoggingService=function(b){a.getInstance()._registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator);
|
|
1687
|
-
|
|
1688
|
-
export { mParticleManager as default };
|
|
1
|
+
"undefined"!=typeof globalThis&&(globalThis.regeneratorRuntime=void 0);var e={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(e)))}catch(e){console.error("Error encoding cookie values into Base64:"+e)}return this._encode(e)},_encode:function(n){var r,i,o,s,a,u,c,d="",l=0;for(n=t.encode(n);l<n.length;)s=(r=n.charCodeAt(l++))>>2,a=(3&r)<<4|(i=n.charCodeAt(l++))>>4,u=(15&i)<<2|(o=n.charCodeAt(l++))>>6,c=63&o,isNaN(i)?u=c=64:isNaN(o)&&(c=64),d=d+e._keyStr.charAt(s)+e._keyStr.charAt(a)+e._keyStr.charAt(u)+e._keyStr.charAt(c);return d},decode:function(t){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(t)))}catch(e){}return e._decode(t)},_decode:function(n){var r,i,o,s,a,u,c="",d=0;for(n=n.replace(/[^A-Za-z0-9\+\/\=]/g,"");d<n.length;)r=e._keyStr.indexOf(n.charAt(d++))<<2|(s=e._keyStr.indexOf(n.charAt(d++)))>>4,i=(15&s)<<4|(a=e._keyStr.indexOf(n.charAt(d++)))>>2,o=(3&a)<<6|(u=e._keyStr.indexOf(n.charAt(d++))),c+=String.fromCharCode(r),64!==a&&(c+=String.fromCharCode(i)),64!==u&&(c+=String.fromCharCode(o));return c=t.decode(c)}},t={encode:function(e){for(var t="",n=0;n<e.length;n++){var r=e.charCodeAt(n);r<128?t+=String.fromCharCode(r):r>127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(63&r|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(63&r|128))}return t},decode:function(e){for(var t="",n=0,r=0,i=0,o=0;n<e.length;)(r=e.charCodeAt(n))<128?(t+=String.fromCharCode(r),n++):r>191&&r<224?(i=e.charCodeAt(n+1),t+=String.fromCharCode((31&r)<<6|63&i),n+=2):(i=e.charCodeAt(n+1),o=e.charCodeAt(n+2),t+=String.fromCharCode((15&r)<<12|(63&i)<<6|63&o),n+=3);return t}},n={forEach:function(e,t){var n,r;if(null==this)throw new TypeError(" this is null or not defined");var i=Object(this),o=i.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(n=t),r=0;r<o;){var s=void 0;r in i&&(s=i[r],e.call(n,s,r,i)),r++}},map:function(e,t){var n,r,i;if(null===this)throw new TypeError(" this is null or not defined");var o=Object(this),s=o.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(n=t),r=new Array(s),i=0;i<s;){var a=void 0,u=void 0;i in o&&(a=o[i],u=e.call(n,a,i,o),r[i]=u),i++}return r},filter:function(e){if(null==this)throw new TypeError;var t=Object(this),n=t.length>>>0;if("function"!=typeof e)throw new TypeError;for(var r=[],i=arguments.length>=2?arguments[1]:void 0,o=0;o<n;o++)if(o in t){var s=t[o];e.call(i,s,o,t)&&r.push(s)}return r},isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},Base64:e},r={sdkVersion:"3.24.0",sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",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",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0},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/"},CNAMEUrlPaths:{v1SecureServiceUrl:"/webevents/v1/JS/",v2SecureServiceUrl:"/webevents/v2/JS/",v3SecureServiceUrl:"/webevents/v3/JS/",configUrl:"/tags/JS/v2/",identityUrl:"/identity/v1/",aliasUrl:"/webevents/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,lsa:1,ua:1,ui:1,csd:1,ia:1,con:1},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",CaptureIntegrationSpecificIdsV2:"captureIntegrationSpecificIds.V2",AstBackgroundEvents:"astBackgroundEvents",AutoLogPageView:"autoLogPageView",AutoButtonTracking:"autoButtonTracking"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"},Environment:{Development:"development",Production:"production"},CaptureIntegrationSpecificIdsV2Modes:{All:"all",None:"none",RoktOnly:"roktonly"},Rokt:{LauncherInstanceGuidKey:"__rokt_li_guid__"}},i="$NoTargeting",o=200,s=202,a=400,u=500;function c(e){return c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},c(e)}var d=function(e,t){return d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},d(e,t)};function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}d(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var p=function(){return p=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},p.apply(this,arguments)};function g(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}function v(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(u){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function h(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var f=r.Messages,m=function(e){return T(D(e))},y=function(e){return E(k(e))},b=function(e,t){if(!e)return!1;var n=0;if(Array.prototype.indexOf)return e.indexOf(t,0)>=0;for(var r=e.length;n<r;n++)if(n in e&&e[n]===t)return!0;return!1},S=function(e,t){if(t&&e)for(var n in e)if(W(e,n)&&n.toLowerCase()===t.toLowerCase())return n;return null},I=function(e,t,n,r){var i=[e];return t?i.push(f.DeprecationMessages.MethodHasBeenDeprecated):i.push(f.DeprecationMessages.MethodMarkedForDeprecationPostfix),n&&(i.push(f.DeprecationMessages.AlternativeMethodPrefix),i.push(n+".")),r&&i.push("See - "+r),i.join(" ")};function _(e){var t=0;if(null==e)return 0;if(e=e.toString().toLowerCase(),Array.prototype.reduce)return e.split("").reduce((function(e,t){return(e=(e<<5)-e+t.charCodeAt(0))&e}),0);if(0===e.length)return t;for(var n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t&=t;return t}var w=function(e){return void 0===e&&(e=""),e?function(e){var t,n;return window.crypto&&window.crypto.getRandomValues&&(t=window.crypto.getRandomValues(new Uint8Array(1))),t?(n^t[0]%16>>NaN).toString(16):(n^16*Math.random()>>NaN).toString(16)}():"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,w)},P=function(e){var t=Object.prototype.toString.call(e);return"[object Object]"===t||"[object Error]"===t},C=function(e){if(isNaN(e)||!isFinite(e))return 0;var t=parseFloat(e);return isNaN(t)?0:t},A=function(e){return j(e)?e:null},T=function(e){return e.replace(/,/g,"|")},E=function(e){return e.replace(/\|/g,",")},k=function(e){return e.replace(/\'/g,'"')},D=function(e){return e.replace(/\"/g,"'")},M=function(e,t){return e.replace("%%mpid%%",t)},O=function(e){return e.replace(/&/g,"&")},F=function(e,t,n,r,i){var o=O(t),s=n?O(n):null,a=M(o,e),u=s?M(s,e):"",c=a+encodeURIComponent(u);if(r){var d=c.includes("?")?"&":"?";c+="".concat(d,"domain=").concat(r)}if(i){d=c.includes("?")?"&":"?";c+="".concat(d,"google_hm=").concat(i)}return c},L={"+":"-","/":"_","=":""},U=function(e){return function(e){return!/[^\u0000-\u00ff]/.test(e)}(e)?btoa(e).replace(/[+/=]/g,(function(e){return L[e]})):void 0},N=function(e){return"false"!==e&&"0"!==e&&Boolean(e)},R=function(e){return decodeURIComponent(e.replace(/\+/g," "))},V=function(e){return 0===e.indexOf('"')&&(e=e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")),e},x=function(e){return"string"==typeof e},H=function(e){return"number"==typeof e},K=function(e){return"function"==typeof e},q=function(e){return H(e)||x(e)||function(e){return"boolean"==typeof e}(e)},B=function(e){return e===(j(t=e)?t.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):"");var t},j=function(e){return x(e)||H(e)},z=function(e){return null==e||!(Object.keys(e)||e).length},Q=function(e,t){return e.slice(0,t).concat(e.slice(t+1),e[t])},W=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},J=function(e){return"__proto__"===e||"constructor"===e},G=function(e){return J(e)||"prototype"===e},$=function(e,t){var n;void 0===t&&(t=[]);var r={},i={};if(!e)return r;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var o=new URL(e);n=new URLSearchParams(o.search)}else n=Y(e);return n.forEach((function(e,t){i[t.toLowerCase()]=e})),z(t)?i:(t.forEach((function(e){var t=e.toLowerCase();W(i,t)&&i[t]&&(r[e]=i[t])})),r)},Y=function(e){var t={};return(e.split("#")[0].split("?")[1]||"").split("&").forEach((function(e){var n=e.split("="),r=n[0],i=n.slice(1).join("=");if(r&&void 0!==i)try{t[r]=decodeURIComponent(i||"")}catch(e){console.error("Failed to decode value for key ".concat(r,": ").concat(e))}})),{get:function(e){return t[e]},forEach:function(e){for(var n in t)W(t,n)&&e(t[n],n)}}},X=function(){return"undefined"!=typeof window&&window.location?window.location.href:""},Z=function(e,t,n){var r,i={};if(!z(e))for(var o in e)if(W(e,o)&&(!J(r=o)&&"hasOwnProperty"!==r)){var s=n(o);b(t,s)||(i[o]=e[o])}return i},ee=function(e,t,n){var r;return(null===(r=e.kitConfigs)||void 0===r?void 0:r.find((function(e){return e.name===t&&e.moduleId===n})))||null},te=function(e){if(null==e)return e;if(Array.isArray(e))return e.map((function(e){return te(e)}));if(P(e)){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=te(e[n]));return t}return c(e)},ne=function(e,t){return t?e:te(e)};function re(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n,r,i,o,s,a,u={hasOwn:Object.prototype.hasOwnProperty,class2type:{},type:function(e){return null==e?String(e):u.class2type[Object.prototype.toString.call(e)]||"object"},isPlainObject:function(e){if(!e||"object"!==u.type(e)||e.nodeType||u.isWindow(e))return!1;try{if(e.constructor&&!u.hasOwn.call(e,"constructor")&&!u.hasOwn.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(e){return!1}var t;for(t in e);return void 0===t||u.hasOwn.call(e,t)},isArray:Array.isArray||function(e){return"array"===u.type(e)},isFunction:function(e){return"function"===u.type(e)},isWindow:function(e){return null!=e&&e==e.window}},d=e[0]||{},l=1,p=!1,g=e.length;for("boolean"==typeof d&&(p=d,d=e[1]||{},l=2),"object"===c(d)||u.isFunction(d)||(d={}),g===l&&(d={},--l);l<g;l++)if(null!=(n=e[l]))for(r in n)G(r)||Object.prototype.hasOwnProperty.call(n,r)&&(i=d[r],d!==(o=n[r])&&(p&&o&&(u.isPlainObject(o)||(s=u.isArray(o)))?(s?(s=!1,a=i&&u.isArray(i)?i:[]):a=i&&u.isPlainObject(i)?i:{},d[r]=re(p,a,o)):void 0!==o&&(d[r]=o)));return d}var ie=function(e,t){return void 0===t&&(t="unknown error"),e instanceof Error?e.message:"string"==typeof e?e:e&&"object"===c(e)&&"string"==typeof e.message?e.message:t},oe={SessionStart:1,SessionEnd:2,PageView:3,PageEvent:4,CrashReport:5,OptOut:6,AppStateTransition:10,Profile:14,Commerce:16,Media:20,UserAttributeChange:17,UserIdentityChange:18},se={Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8,Media:9,getName:function(e){switch(e){case se.Unknown:return"Unknown";case se.Navigation:return"Navigation";case se.Location:return"Location";case se.Search:return"Search";case se.Transaction:return"Transaction";case se.UserContent:return"User Content";case se.UserPreference:return"User Preference";case se.Social:return"Social";case ae.ProductAddToCart:return"Product Added to Cart";case ae.ProductAddToWishlist:return"Product Added to Wishlist";case ae.ProductCheckout:return"Product Checkout";case ae.ProductCheckoutOption:return"Product Checkout Options";case ae.ProductClick:return"Product Click";case ae.ProductImpression:return"Product Impression";case ae.ProductPurchase:return"Product Purchased";case ae.ProductRefund:return"Product Refunded";case ae.ProductRemoveFromCart:return"Product Removed From Cart";case ae.ProductRemoveFromWishlist:return"Product Removed from Wishlist";case ae.ProductViewDetail:return"Product View Details";case ae.PromotionClick:return"Promotion Click";case ae.PromotionView:return"Promotion View";default:return"Other"}}},ae={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},ue={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(e){if("number"==typeof e)for(var t in ue)if(ue.hasOwnProperty(t)&&ue[t]===e)return!0;return!1},getName:function(e){switch(e){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(e){switch(e){case"other":case"email_sha256":return ue.Other;case"customerid":return ue.CustomerId;case"facebook":return ue.Facebook;case"twitter":return ue.Twitter;case"google":return ue.Google;case"microsoft":return ue.Microsoft;case"yahoo":return ue.Yahoo;case"email":return ue.Email;case"facebookcustomaudienceid":return ue.FacebookCustomAudienceId;case"other2":case"mobile_sha256":return ue.Other2;case"other3":return ue.Other3;case"other4":return ue.Other4;case"other5":return ue.Other5;case"other6":return ue.Other6;case"other7":return ue.Other7;case"other8":return ue.Other8;case"other9":return ue.Other9;case"other10":return ue.Other10;case"mobile_number":return ue.MobileNumber;case"phone_number_2":return ue.PhoneNumber2;case"phone_number_3":return ue.PhoneNumber3;default:return!1}},getIdentityName:function(e){switch(e){case ue.Other:return"other";case ue.CustomerId:return"customerid";case ue.Facebook:return"facebook";case ue.Twitter:return"twitter";case ue.Google:return"google";case ue.Microsoft:return"microsoft";case ue.Yahoo:return"yahoo";case ue.Email:return"email";case ue.FacebookCustomAudienceId:return"facebookcustomaudienceid";case ue.Other2:return"other2";case ue.Other3:return"other3";case ue.Other4:return"other4";case ue.Other5:return"other5";case ue.Other6:return"other6";case ue.Other7:return"other7";case ue.Other8:return"other8";case ue.Other9:return"other9";case ue.Other10:return"other10";case ue.MobileNumber:return"mobile_number";case ue.PhoneNumber2:return"phone_number_2";case ue.PhoneNumber3:return"phone_number_3";default:return null}},getValuesAsStrings:function(){return Object.values(ue).map((function(e){return H(e)?e.toString():void 0})).filter((function(e){return void 0!==e}))},getNewIdentitiesByName:function(e){var t={},n=ue.getValuesAsStrings();for(var r in e){if(n.includes(r))t[ue.getIdentityName(C(r))]=e[r]}return t}},ce={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10,ViewCart:11,AddShippingInfo:12,AddPaymentInfo:13,PaymentMethodSelected:14,PaymentAttempted:15,PaymentSucceeded:16,PaymentFailed:17,RefundInitiated:18,isRoktCommerceType:function(e){return e>=ce.ViewCart&&e<=ce.RefundInitiated},getName:function(e){switch(e){case ce.AddToCart:return"Add to Cart";case ce.RemoveFromCart:return"Remove from Cart";case ce.Checkout:return"Checkout";case ce.CheckoutOption:return"Checkout Option";case ce.Click:return"Click";case ce.ViewDetail:return"View Detail";case ce.Purchase:return"Purchase";case ce.Refund:return"Refund";case ce.AddToWishlist:return"Add to Wishlist";case ce.RemoveFromWishlist:return"Remove from Wishlist";case ce.ViewCart:return"View Cart";case ce.AddShippingInfo:return"Add Shipping Info";case ce.AddPaymentInfo:return"Add Payment Info";case ce.PaymentMethodSelected:return"Payment Method Selected";case ce.PaymentAttempted:return"Payment Attempted";case ce.PaymentSucceeded:return"Payment Succeeded";case ce.PaymentFailed:return"Payment Failed";case ce.RefundInitiated:return"Refund Initiated";default:return"Unknown"}},getExpansionName:function(e){switch(e){case ce.AddToCart:return"add_to_cart";case ce.RemoveFromCart:return"remove_from_cart";case ce.Checkout:return"checkout";case ce.CheckoutOption:return"checkout_option";case ce.Click:return"click";case ce.ViewDetail:return"view_detail";case ce.Purchase:return"purchase";case ce.Refund:return"refund";case ce.AddToWishlist:return"add_to_wishlist";case ce.RemoveFromWishlist:return"remove_from_wishlist";case ce.ViewCart:return"view_cart";case ce.AddShippingInfo:return"add_shipping_info";case ce.AddPaymentInfo:return"add_payment_info";case ce.PaymentMethodSelected:return"payment_method_selected";case ce.PaymentAttempted:return"payment_attempted";case ce.PaymentSucceeded:return"payment_succeeded";case ce.PaymentFailed:return"payment_failed";case ce.RefundInitiated:return"refund_initiated";default:return"unknown"}}},de={SignUp:"sign_up",Subscribe:"subscribe",StartTrial:"start_trial",GenerateLead:"generate_lead",Search:"search",Upsell:"upsell",EarnVirtualCurrency:"earn_virtual_currency",DwellTime:"dwell_time",Hover:"hover",Scroll:"scroll",ClickToExpand:"click_to_expand"},le={Unknown:0,PromotionView:1,PromotionClick:2,getName:function(e){switch(e){case le.PromotionView:return"view";case le.PromotionClick:return"click";default:return"unknown"}},getExpansionName:function(e){switch(e){case le.PromotionView:return"view";case le.PromotionClick:return"click";default:return"unknown"}}},pe="mp:sdkStart",ge="mp:jointSdkSelectPlacements",ve="mp:jointSdkRoktKitInit";function he(e){var t=C(e);return String(t)===e&&ue.isValid(t)?t:null}var fe,me={MessageType:oe,EventType:se,CommerceEventType:ae,IdentityType:ue,ProfileMessageType:{Logout:3},ApplicationTransitionType:{AppInit:1},ProductActionType:ce,PromotionActionType:le,RoktEvents:de,Environment:r.Environment};!function(e){e[e.Unknown=0]="Unknown",e[e.AddToCart=1]="AddToCart",e[e.RemoveFromCart=2]="RemoveFromCart",e[e.Checkout=3]="Checkout",e[e.CheckoutOption=4]="CheckoutOption",e[e.Click=5]="Click",e[e.ViewDetail=6]="ViewDetail",e[e.Purchase=7]="Purchase",e[e.Refund=8]="Refund",e[e.AddToWishlist=9]="AddToWishlist",e[e.RemoveFromWishlist=10]="RemoveFromWishlist",e[e.ViewCart=11]="ViewCart",e[e.AddShippingInfo=12]="AddShippingInfo",e[e.AddPaymentInfo=13]="AddPaymentInfo",e[e.PaymentMethodSelected=14]="PaymentMethodSelected",e[e.PaymentAttempted=15]="PaymentAttempted",e[e.PaymentSucceeded=16]="PaymentSucceeded",e[e.PaymentFailed=17]="PaymentFailed",e[e.RefundInitiated=18]="RefundInitiated"}(fe||(fe={}));var ye,be,Se,Ie,_e,we,Pe,Ce,Ae,Te,Ee,ke,De,Me,Oe,Fe,Le,Ue,Ne,Re="none",Ve="verbose",xe="warning",He={};ye=He,Object.defineProperty(ye,"__esModule",{value:!0}),(be=ye.ApplicationInformationOsEnum||(ye.ApplicationInformationOsEnum={})).unknown="Unknown",be.iOS="IOS",be.android="Android",be.windowsPhone="WindowsPhone",be.mobileWeb="MobileWeb",be.unityIOS="UnityIOS",be.unityAndroid="UnityAndroid",be.desktop="Desktop",be.tvOS="TVOS",be.roku="Roku",be.outOfBand="OutOfBand",be.alexa="Alexa",be.smartTV="SmartTV",be.fireTV="FireTV",be.xbox="Xbox",(ye.ApplicationStateTransitionEventEventTypeEnum||(ye.ApplicationStateTransitionEventEventTypeEnum={})).applicationStateTransition="application_state_transition",(Se=ye.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum||(ye.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum={})).applicationInitialized="application_initialized",Se.applicationExit="application_exit",Se.applicationBackground="application_background",Se.applicationForeground="application_foreground",(Ie=ye.BatchEnvironmentEnum||(ye.BatchEnvironmentEnum={})).unknown="unknown",Ie.development="development",Ie.production="production",(ye.BreadcrumbEventEventTypeEnum||(ye.BreadcrumbEventEventTypeEnum={})).breadcrumb="breadcrumb",(ye.CommerceEventEventTypeEnum||(ye.CommerceEventEventTypeEnum={})).commerceEvent="commerce_event",(_e=ye.CommerceEventDataCustomEventTypeEnum||(ye.CommerceEventDataCustomEventTypeEnum={})).addToCart="add_to_cart",_e.removeFromCart="remove_from_cart",_e.checkout="checkout",_e.checkoutOption="checkout_option",_e.click="click",_e.viewDetail="view_detail",_e.purchase="purchase",_e.refund="refund",_e.promotionView="promotion_view",_e.promotionClick="promotion_click",_e.addToWishlist="add_to_wishlist",_e.removeFromWishlist="remove_from_wishlist",_e.impression="impression",(ye.CrashReportEventEventTypeEnum||(ye.CrashReportEventEventTypeEnum={})).crashReport="crash_report",(ye.CustomEventEventTypeEnum||(ye.CustomEventEventTypeEnum={})).customEvent="custom_event",(we=ye.CustomEventDataCustomEventTypeEnum||(ye.CustomEventDataCustomEventTypeEnum={})).navigation="navigation",we.location="location",we.search="search",we.transaction="transaction",we.userContent="user_content",we.userPreference="user_preference",we.social="social",we.media="media",we.other="other",we.unknown="unknown",(Pe=ye.DeviceCurrentStateDeviceOrientationEnum||(ye.DeviceCurrentStateDeviceOrientationEnum={})).portrait="portrait",Pe.portraitUpsideDown="portrait_upside_down",Pe.landscape="landscape",Pe.landscapeLeft="LandscapeLeft",Pe.landscapeRight="LandscapeRight",Pe.faceUp="FaceUp",Pe.faceDown="FaceDown",Pe.square="Square",(Ce=ye.DeviceCurrentStateStatusBarOrientationEnum||(ye.DeviceCurrentStateStatusBarOrientationEnum={})).portrait="portrait",Ce.portraitUpsideDown="portrait_upside_down",Ce.landscape="landscape",Ce.landscapeLeft="LandscapeLeft",Ce.landscapeRight="LandscapeRight",Ce.faceUp="FaceUp",Ce.faceDown="FaceDown",Ce.square="Square",(Ae=ye.DeviceInformationPlatformEnum||(ye.DeviceInformationPlatformEnum={})).iOS="iOS",Ae.android="Android",Ae.web="web",Ae.desktop="desktop",Ae.tvOS="tvOS",Ae.roku="roku",Ae.outOfBand="out_of_band",Ae.smartTV="smart_tv",Ae.xbox="xbox",(Te=ye.EventTypeEnum||(ye.EventTypeEnum={})).unknown="unknown",Te.sessionStart="session_start",Te.sessionEnd="session_end",Te.screenView="screen_view",Te.customEvent="custom_event",Te.crashReport="crash_report",Te.optOut="opt_out",Te.firstRun="first_run",Te.preAttribution="pre_attribution",Te.pushRegistration="push_registration",Te.applicationStateTransition="application_state_transition",Te.pushMessage="push_message",Te.networkPerformance="network_performance",Te.breadcrumb="breadcrumb",Te.profile="profile",Te.pushReaction="push_reaction",Te.commerceEvent="commerce_event",Te.userAttributeChange="user_attribute_change",Te.userIdentityChange="user_identity_change",Te.uninstall="uninstall",Te.validationResult="validation_result",(Ee=ye.IdentityTypeEnum||(ye.IdentityTypeEnum={})).other="other",Ee.customerId="customer_id",Ee.facebook="facebook",Ee.twitter="twitter",Ee.google="google",Ee.microsoft="microsoft",Ee.yahoo="yahoo",Ee.email="email",Ee.alias="alias",Ee.facebookCustomAudienceId="facebook_custom_audience_id",Ee.otherId2="other_id_2",Ee.otherId3="other_id_3",Ee.otherId4="other_id_4",Ee.otherId5="other_id_5",Ee.otherId6="other_id_6",Ee.otherId7="other_id_7",Ee.otherId8="other_id_8",Ee.otherId9="other_id_9",Ee.otherId10="other_id_10",Ee.mobileNumber="mobile_number",Ee.phoneNumber2="phone_number_2",Ee.phoneNumber3="phone_number_3",(ye.NetworkPerformanceEventEventTypeEnum||(ye.NetworkPerformanceEventEventTypeEnum={})).networkPerformance="network_performance",(ye.OptOutEventEnum||(ye.OptOutEventEnum={})).optOut="opt_out",(ke=ye.ProductActionActionEnum||(ye.ProductActionActionEnum={})).unknown="unknown",ke.addToCart="add_to_cart",ke.removeFromCart="remove_from_cart",ke.checkout="checkout",ke.checkoutOption="checkout_option",ke.click="click",ke.viewDetail="view_detail",ke.purchase="purchase",ke.refund="refund",ke.addToWishlist="add_to_wishlist",ke.removeFromWishlist="remove_from_wish_list",(ye.ProfileEventEventTypeEnum||(ye.ProfileEventEventTypeEnum={})).profile="profile",(De=ye.ProfileEventDataProfileEventTypeEnum||(ye.ProfileEventDataProfileEventTypeEnum={})).signup="signup",De.login="login",De.logout="logout",De.update="update",De.delete="delete",(Me=ye.PromotionActionActionEnum||(ye.PromotionActionActionEnum={})).view="view",Me.click="click",(ye.PushMessageEventEventTypeEnum||(ye.PushMessageEventEventTypeEnum={})).pushMessage="push_message",(Oe=ye.PushMessageEventDataPushMessageTypeEnum||(ye.PushMessageEventDataPushMessageTypeEnum={})).sent="sent",Oe.received="received",Oe.action="action",(Fe=ye.PushMessageEventDataApplicationStateEnum||(ye.PushMessageEventDataApplicationStateEnum={})).notRunning="not_running",Fe.background="background",Fe.foreground="foreground",(Le=ye.PushMessageEventDataPushMessageBehaviorEnum||(ye.PushMessageEventDataPushMessageBehaviorEnum={})).received="Received",Le.directOpen="DirectOpen",Le.read="Read",Le.influencedOpen="InfluencedOpen",Le.displayed="Displayed",(ye.PushRegistrationEventEventTypeEnum||(ye.PushRegistrationEventEventTypeEnum={})).pushRegistration="push_registration",(ye.SessionEndEventEventTypeEnum||(ye.SessionEndEventEventTypeEnum={})).sessionEnd="session_end",(ye.SessionStartEventEventTypeEnum||(ye.SessionStartEventEventTypeEnum={})).sessionStart="session_start",(Ue=ye.SourceInformationChannelEnum||(ye.SourceInformationChannelEnum={})).native="native",Ue.javascript="javascript",Ue.pixel="pixel",Ue.desktop="desktop",Ue.partner="partner",Ue.serverToServer="server_to_server",(ye.UserAttributeChangeEventEventTypeEnum||(ye.UserAttributeChangeEventEventTypeEnum={})).userAttributeChange="user_attribute_change",(ye.UserIdentityChangeEventEventTypeEnum||(ye.UserIdentityChangeEventEventTypeEnum={})).userIdentityChange="user_identity_change",function(e){e.other="other",e.customerId="customerid",e.facebook="facebook",e.twitter="twitter",e.google="google",e.microsoft="microsoft",e.yahoo="yahoo",e.email="email",e.alias="alias",e.facebookCustomAudienceId="facebookcustomaudienceid",e.otherId2="other2",e.otherId3="other3",e.otherId4="other4",e.otherId5="other5",e.otherId6="other6",e.otherId7="other7",e.otherId8="other8",e.otherId9="other9",e.otherId10="other10",e.mobileNumber="mobile_number",e.phoneNumber2="phone_number_2",e.phoneNumber3="phone_number_3"}(Ne||(Ne={}));var Ke="custom_flags",qe="partner_identities",Be="integration_attributes",je={fbclid:{mappedKey:"Facebook.ClickId",processor:function(e,t,n){if(!e||!t)return"";var r=null==t?void 0:t.split("//");if(!r)return"";var i=1;r[1].split("/")[0].split(".").length>=3&&(i=2);var o=n||Date.now();return"fb.".concat(i,".").concat(o,".").concat(e)},output:Ke},_fbp:{mappedKey:"Facebook.BrowserId",output:Ke},_fbc:{mappedKey:"Facebook.ClickId",output:Ke},gclid:{mappedKey:"GoogleEnhancedConversions.Gclid",output:Ke},gbraid:{mappedKey:"GoogleEnhancedConversions.Gbraid",output:Ke},wbraid:{mappedKey:"GoogleEnhancedConversions.Wbraid",output:Ke},ttclid:{mappedKey:"TikTok.Callback",output:Ke},_ttp:{mappedKey:"tiktok_cookie_id",output:qe},ScCid:{mappedKey:"SnapchatConversions.ClickId",output:Ke},epik:{mappedKey:"Pinterest.click_id",output:Ke},_epik:{mappedKey:"Pinterest.click_id",output:Ke},_scid:{mappedKey:"SnapchatConversions.Cookie1",output:Ke}},ze={rtid:{mappedKey:"passbackconversiontrackingid",output:Be,moduleId:1277},rclid:{mappedKey:"passbackconversiontrackingid",output:Be,moduleId:1277},RoktTransactionId:{mappedKey:"passbackconversiontrackingid",output:Be,moduleId:1277}};function Qe(e){if(!e)return!1;var t=e(r.FeatureFlags.CaptureIntegrationSpecificIds),n=e(r.FeatureFlags.CaptureIntegrationSpecificIdsV2);return!!n&&n!==r.CaptureIntegrationSpecificIdsV2Modes.None||!0===t}var We=function(){function e(e){this.initialTimestamp=Date.now(),this.captureMode=e,this.filteredPartnerIdentityMappings=this.filterMappings(qe),this.filteredCustomFlagMappings=this.filterMappings(Ke),this.filteredIntegrationAttributeMappings=this.filterMappings(Be)}return e.prototype.capture=function(){var e=this.captureQueryParams()||{},t=this.captureCookies()||{},n=this.captureLocalStorage()||{};this.normalizePinterestClickId(e),this.normalizePinterestClickId(n),this.normalizePinterestClickId(t),this.applySourcePrecedence([e,n,t,this.clickIds||{}]),this.clickIds=p(p(p(p({},this.clickIds),t),n),e)},e.prototype.captureCookies=function(){var e,t=this.getAllowedKeysForMode(),n=(e=t,function(e,t){for(var n={},r=0,i=e;r<i.length;r++){var o=i[r].split("="),s=o[0],a=o[1];t&&!t.includes(s)||(n[s]=a)}return n}(function(){try{return"undefined"==typeof window?[]:window.document.cookie.split(";").map((function(e){return e.trim()}))}catch(e){return console.error("Unable to parse cookies",e),[]}}(),e));return this.applyProcessors(n,X(),this.initialTimestamp)},e.prototype.captureQueryParams=function(){var e=this.getQueryParams();return this.applyProcessors(e,X(),this.initialTimestamp)},e.prototype.captureLocalStorage=function(){for(var e={},t=0,n=this.getAllowedKeysForMode();t<n.length;t++){var r=n[t],i=localStorage.getItem(r);i&&(e[r]=i)}return this.applyProcessors(e,X(),this.initialTimestamp)},e.prototype.getQueryParams=function(){var e=this.getAllowedKeysForMode();return $(X(),e)},e.prototype.getClickIdsAsCustomFlags=function(){return this.getClickIds(this.clickIds,this.filteredCustomFlagMappings)},e.prototype.getClickIdsAsPartnerIdentities=function(){return this.getClickIds(this.clickIds,this.filteredPartnerIdentityMappings)},e.prototype.getClickIdsAsIntegrationAttributes=function(){var e,t,n,r={};for(var i in this.clickIds)if(this.clickIds.hasOwnProperty(i)){var o=this.clickIds[i],s=null===(t=this.filteredIntegrationAttributeMappings[i])||void 0===t?void 0:t.mappedKey;if(!z(s)){var a=null===(n=this.filteredIntegrationAttributeMappings[i])||void 0===n?void 0:n.moduleId;a&&!r[a]&&(r[a]=((e={})[s]=o,e))}}return r},e.prototype.getClickIds=function(e,t){var n,r={};if(!e)return r;for(var i in e)if(e.hasOwnProperty(i)){var o=e[i],s=null===(n=t[i])||void 0===n?void 0:n.mappedKey;z(s)||(r[s]=o)}return r},e.prototype.normalizePinterestClickId=function(e){z(null==e?void 0:e._epik)||z(null==e?void 0:e.epik)||delete e.epik},e.prototype.applySourcePrecedence=function(e){for(var t=this.getActiveIntegrationMapping(),n=function(e){var n;return(null===(n=t[e])||void 0===n?void 0:n.mappedKey)||e},r=[],i=0,o=e;i<o.length;i++){var s=o[i],a=[];for(var u in s){var c=n(u);-1!==r.indexOf(c)?delete s[u]:z(s[u])||a.push(c)}r.push.apply(r,a)}},e.prototype.applyProcessors=function(e,t,n){var r,i={},o=this.getActiveIntegrationMapping();for(var s in e)if(e.hasOwnProperty(s)){var a=e[s],u=null===(r=o[s])||void 0===r?void 0:r.processor;i[s]=u?u(a,t,n):a}return i},e.prototype.filterMappings=function(e){var t={},n=this.getActiveIntegrationMapping();for(var r in n)n[r].output===e&&(t[r]=n[r]);return t},e.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},e.prototype.getActiveIntegrationMapping=function(){return this.captureMode===r.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?ze:this.captureMode===r.CaptureIntegrationSpecificIdsV2Modes.All?p(p({},je),ze):{}},e}();function Je(e,t,n){if(!e)return null;if(!t||t.length<1)return null;for(var r=n._IntegrationCapture,i=n._Helpers.getFeatureFlag,o=n.Identity.getCurrentUser(),s=[],a=null,u=0,c=t;u<c.length;u++){var d=c[u];if(d){a=d;var l=Ze(d);l&&s.push(l)}}if(!a)return null;var p=null;z(a.ConsentState)?z(o)||(p=o.getConsentState()):p=a.ConsentState;var g={source_request_id:n._Helpers.generateUniqueId(),mpid:e,timestamp_unixtime_ms:(new Date).getTime(),environment:a.Debug?He.BatchEnvironmentEnum.development:He.BatchEnvironmentEnum.production,events:s,mp_deviceid:a.DeviceId,sdk_version:a.SDKVersion,application_info:{application_version:a.AppVersion,application_name:a.AppName,package:a.Package,sideloaded_kits_count:n._Store.sideloadedKitsCount},device_info:{platform:He.DeviceInformationPlatformEnum.web,screen_width:"undefined"!=typeof window&&void 0!==window.screen?window.screen.width:0,screen_height:"undefined"!=typeof window&&void 0!==window.screen?window.screen.height:0},user_attributes:a.UserAttributes,user_identities:Xe(a.UserIdentities),consent_state:Ge(p),integration_attributes:a.IntegrationAttributes};if(a.DataPlan&&a.DataPlan.PlanId&&(g.context={data_plan:{plan_id:a.DataPlan.PlanId,plan_version:a.DataPlan.PlanVersion||void 0}}),Qe(i)){null==r||r.capture();var v=null==r?void 0:r.getClickIdsAsPartnerIdentities();z(v)||(g.partner_identities=v)}return g}function Ge(e){return z(e)?null:{gdpr:$e(e.getGDPRConsentState()),ccpa:Ye(e.getCCPAConsentState())}}function $e(e){if(!e)return null;var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]={consented:e[n].Consented,hardware_id:e[n].HardwareId,document:e[n].ConsentDocument,timestamp_unixtime_ms:e[n].Timestamp,location:e[n].Location});return t}function Ye(e){return e?{data_sale_opt_out:{consented:e.Consented,hardware_id:e.HardwareId,document:e.ConsentDocument,timestamp_unixtime_ms:e.Timestamp,location:e.Location}}:null}function Xe(e){if(!e||!e.length)return null;for(var t={},n=0,r=e;n<r.length;n++){var i=r[n];switch(i.Type){case me.IdentityType.CustomerId:t.customer_id=i.Identity;break;case me.IdentityType.Email:t.email=i.Identity;break;case me.IdentityType.Facebook:t.facebook=i.Identity;break;case me.IdentityType.FacebookCustomAudienceId:t.facebook_custom_audience_id=i.Identity;break;case me.IdentityType.Google:t.google=i.Identity;break;case me.IdentityType.Microsoft:t.microsoft=i.Identity;break;case me.IdentityType.Other:t.other=i.Identity;break;case me.IdentityType.Other2:t.other_id_2=i.Identity;break;case me.IdentityType.Other3:t.other_id_3=i.Identity;break;case me.IdentityType.Other4:t.other_id_4=i.Identity;break;case me.IdentityType.Other5:t.other_id_5=i.Identity;break;case me.IdentityType.Other6:t.other_id_6=i.Identity;break;case me.IdentityType.Other7:t.other_id_7=i.Identity;break;case me.IdentityType.Other8:t.other_id_8=i.Identity;break;case me.IdentityType.Other9:t.other_id_9=i.Identity;break;case me.IdentityType.Other10:t.other_id_10=i.Identity;break;case me.IdentityType.MobileNumber:t.mobile_number=i.Identity;break;case me.IdentityType.PhoneNumber2:t.phone_number_2=i.Identity;break;case me.IdentityType.PhoneNumber3:t.phone_number_3=i.Identity}}return t}function Ze(e){if(!e)return null;switch(e.EventDataType){case me.MessageType.AppStateTransition:return function(e){var t=at(e),n=He.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum,r=n.applicationBackground,i=n.applicationInitialized,o=e.IsBackgroundAST?r:i,s={application_transition_type:o,is_first_run:e.IsFirstRun,is_upgrade:!1,launch_referral:e.LaunchReferral};return s=Object.assign(s,t),{event_type:He.EventTypeEnum.applicationStateTransition,data:s}}(e);case me.MessageType.Commerce:return function(e){var t=at(e),n={custom_flags:e.CustomFlags,product_action:tt(e),promotion_action:rt(e),product_impressions:ot(e),currency_code:e.CurrencyCode};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.commerceEvent,data:n}}(e);case me.MessageType.CrashReport:return function(e){var t=at(e),n={message:e.EventName};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.crashReport,data:n}}(e);case me.MessageType.OptOut:return function(e){var t=at(e),n={is_opted_out:e.OptOut};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.optOut,data:n}}(e);case me.MessageType.PageEvent:return function(e){var t=at(e),n={custom_event_type:st(e.EventCategory),custom_flags:e.CustomFlags,event_name:e.EventName};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.customEvent,data:n}}(e);case me.MessageType.PageView:return function(e){var t=at(e),n={custom_flags:e.CustomFlags,screen_name:e.EventName};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.screenView,data:n}}(e);case me.MessageType.Profile:return null;case me.MessageType.SessionEnd:return function(e){var t=at(e),n={session_duration_ms:e.SessionLength};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.sessionEnd,data:n}}(e);case me.MessageType.SessionStart:return function(e){var t=at(e),n={};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.sessionStart,data:n}}(e);case me.MessageType.UserAttributeChange:return function(e){var t=at(e),n={user_attribute_name:e.UserAttributeChanges.UserAttributeName,new:e.UserAttributeChanges.New,old:e.UserAttributeChanges.Old,deleted:e.UserAttributeChanges.Deleted,is_new_attribute:e.UserAttributeChanges.IsNewAttribute};return n=p(p({},n),t),{event_type:He.EventTypeEnum.userAttributeChange,data:n}}(e);case me.MessageType.UserIdentityChange:return function(e){var t=at(e),n={new:{identity_type:ct(e.UserIdentityChanges.New.IdentityType),identity:e.UserIdentityChanges.New.Identity||null,timestamp_unixtime_ms:e.Timestamp,created_this_batch:e.UserIdentityChanges.New.CreatedThisBatch},old:{identity_type:ct(e.UserIdentityChanges.Old.IdentityType),identity:e.UserIdentityChanges.Old.Identity||null,timestamp_unixtime_ms:e.Timestamp,created_this_batch:e.UserIdentityChanges.Old.CreatedThisBatch}};return n=Object.assign(n,t),{event_type:He.EventTypeEnum.userIdentityChange,data:n}}(e)}return null}function et(e){if(!e)return He.ProductActionActionEnum.unknown;switch(e){case fe.AddToCart:return He.ProductActionActionEnum.addToCart;case fe.AddToWishlist:return He.ProductActionActionEnum.addToWishlist;case fe.Checkout:return He.ProductActionActionEnum.checkout;case fe.CheckoutOption:return He.ProductActionActionEnum.checkoutOption;case fe.Click:return He.ProductActionActionEnum.click;case fe.Purchase:return He.ProductActionActionEnum.purchase;case fe.Refund:return He.ProductActionActionEnum.refund;case fe.RemoveFromCart:return He.ProductActionActionEnum.removeFromCart;case fe.RemoveFromWishlist:return He.ProductActionActionEnum.removeFromWishlist;case fe.ViewDetail:return He.ProductActionActionEnum.viewDetail;default:return He.ProductActionActionEnum.unknown}}function tt(e){return e.ProductAction?{action:et(e.ProductAction.ProductActionType),checkout_step:e.ProductAction.CheckoutStep,checkout_options:e.ProductAction.CheckoutOptions,transaction_id:e.ProductAction.TransactionId,affiliation:e.ProductAction.Affiliation,total_amount:e.ProductAction.TotalAmount,tax_amount:e.ProductAction.TaxAmount,shipping_amount:e.ProductAction.ShippingAmount,coupon_code:e.ProductAction.CouponCode,products:nt(e.ProductAction.ProductList)}:null}function nt(e){if(!e||!e.length)return null;for(var t=[],n=0,r=e;n<r.length;n++){var i=r[n],o={id:i.Sku,name:i.Name,brand:i.Brand,category:i.Category,variant:i.Variant,total_product_amount:i.TotalAmount,position:i.Position,price:i.Price,quantity:i.Quantity,coupon_code:i.CouponCode,custom_attributes:i.Attributes};t.push(o)}return t}function rt(e){return e.PromotionAction?{action:e.PromotionAction.PromotionActionType,promotions:it(e.PromotionAction.PromotionList)}:null}function it(e){if(!e||!e.length)return null;for(var t=[],n=0,r=e;n<r.length;n++){var i=r[n],o={id:i.Id,name:i.Name,creative:i.Creative,position:i.Position};t.push(o)}return t}function ot(e){if(!e.ProductImpressions)return null;for(var t=[],n=0,r=e.ProductImpressions;n<r.length;n++){var i=r[n],o={product_impression_list:i.ProductImpressionList,products:nt(i.ProductList)};t.push(o)}return t}function st(e){switch(e){case me.EventType.Other:return He.CustomEventDataCustomEventTypeEnum.other;case me.EventType.Location:return He.CustomEventDataCustomEventTypeEnum.location;case me.EventType.Navigation:return He.CustomEventDataCustomEventTypeEnum.navigation;case me.EventType.Search:return He.CustomEventDataCustomEventTypeEnum.search;case me.EventType.Social:return He.CustomEventDataCustomEventTypeEnum.social;case me.EventType.Transaction:return He.CustomEventDataCustomEventTypeEnum.transaction;case me.EventType.UserContent:return He.CustomEventDataCustomEventTypeEnum.userContent;case me.EventType.UserPreference:return He.CustomEventDataCustomEventTypeEnum.userPreference;case me.EventType.Media:return He.CustomEventDataCustomEventTypeEnum.media;case me.CommerceEventType.ProductAddToCart:return He.CommerceEventDataCustomEventTypeEnum.addToCart;case me.CommerceEventType.ProductAddToWishlist:return He.CommerceEventDataCustomEventTypeEnum.addToWishlist;case me.CommerceEventType.ProductCheckout:return He.CommerceEventDataCustomEventTypeEnum.checkout;case me.CommerceEventType.ProductCheckoutOption:return He.CommerceEventDataCustomEventTypeEnum.checkoutOption;case me.CommerceEventType.ProductClick:return He.CommerceEventDataCustomEventTypeEnum.click;case me.CommerceEventType.ProductImpression:return He.CommerceEventDataCustomEventTypeEnum.impression;case me.CommerceEventType.ProductPurchase:return He.CommerceEventDataCustomEventTypeEnum.purchase;case me.CommerceEventType.ProductRefund:return He.CommerceEventDataCustomEventTypeEnum.refund;case me.CommerceEventType.ProductRemoveFromCart:return He.CommerceEventDataCustomEventTypeEnum.removeFromCart;case me.CommerceEventType.ProductRemoveFromWishlist:return He.CommerceEventDataCustomEventTypeEnum.removeFromWishlist;case me.CommerceEventType.ProductViewDetail:return He.CommerceEventDataCustomEventTypeEnum.viewDetail;case me.CommerceEventType.PromotionClick:return He.CommerceEventDataCustomEventTypeEnum.promotionClick;case me.CommerceEventType.PromotionView:return He.CommerceEventDataCustomEventTypeEnum.promotionView;default:return He.CustomEventDataCustomEventTypeEnum.unknown}}function at(e){return{timestamp_unixtime_ms:e.Timestamp,session_uuid:e.SessionId,session_start_unixtime_ms:e.SessionStartDate,custom_attributes:e.EventAttributes,location:ut(e.Location),source_message_id:e.SourceMessageId,active_time_on_site_ms:e.ActiveTimeOnSite,total_time_on_site_ms:e.TotalTimeOnSite,page_url:e.PageUrl}}function ut(e){return e&&Object.keys(e).length?{latitude:e.lat,longitude:e.lng}:null}function ct(e){switch(e){case Ne.other:return He.IdentityTypeEnum.other;case Ne.customerId:return He.IdentityTypeEnum.customerId;case Ne.facebook:return He.IdentityTypeEnum.facebook;case Ne.twitter:return He.IdentityTypeEnum.twitter;case Ne.google:return He.IdentityTypeEnum.google;case Ne.microsoft:return He.IdentityTypeEnum.microsoft;case Ne.yahoo:return He.IdentityTypeEnum.yahoo;case Ne.email:return He.IdentityTypeEnum.email;case Ne.alias:return He.IdentityTypeEnum.alias;case Ne.facebookCustomAudienceId:return He.IdentityTypeEnum.facebookCustomAudienceId;case Ne.otherId2:return He.IdentityTypeEnum.otherId2;case Ne.otherId3:return He.IdentityTypeEnum.otherId3;case Ne.otherId4:return He.IdentityTypeEnum.otherId4;case Ne.otherId5:return He.IdentityTypeEnum.otherId5;case Ne.otherId6:return He.IdentityTypeEnum.otherId6;case Ne.otherId7:return He.IdentityTypeEnum.otherId7;case Ne.otherId8:return He.IdentityTypeEnum.otherId8;case Ne.otherId9:return He.IdentityTypeEnum.otherId9;case Ne.otherId10:return He.IdentityTypeEnum.otherId10;case Ne.mobileNumber:return He.IdentityTypeEnum.mobileNumber;case Ne.phoneNumber2:return He.IdentityTypeEnum.phoneNumber2;case Ne.phoneNumber3:return He.IdentityTypeEnum.phoneNumber3}}var dt,lt=["pushState","replaceState"],pt="__mpApvWrapped__",gt=function(e){return!!e&&void 0!==e.history&&"function"==typeof e.history.pushState&&"function"==typeof e.addEventListener},vt="__mpRouteMonitor__",ht=function(){var e=window;return e[vt]||(e[vt]={listeners:{},undoHistoryPatch:null,popStateListener:null}),e[vt]},ft=function(e){Object.values(ht().listeners).forEach((function(t){try{t(e)}catch(e){}}))},mt=function(e,t){e.undoHistoryPatch||e.popStateListener||(e.undoHistoryPatch=function(e,t){if(window.history.pushState[pt])return t("[patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DETECTED"),null;var n={},r={};lt.forEach((function(t){var i=window.history[t];n[t]=i;var o=function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var o=i.apply(this,n);return e(t),o};Object.defineProperty(o,pt,{value:!0,enumerable:!1}),r[t]=o}));var i=function(){return lt.forEach((function(e){window.history[e]===r[e]?(window.history[e]=n[e],t("[teardown] restored original ".concat(e))):t("[teardown] ".concat(e," no longer ours; leaving in place, gating callback to no-op"))}))};try{lt.forEach((function(e){window.history[e]=r[e]}))}catch(e){t("[error] failed to patch history methods (frozen/sealed), rolling back: ".concat(e));try{i()}catch(e){t("[error] failed to restore history methods after patch failure: ".concat(e))}return null}return i}(ft,t),e.popStateListener=function(){return ft("popstate")},window.addEventListener("popstate",e.popStateListener))},yt=function(e,t,n){if(void 0===n&&(n=function(){}),!gt("undefined"==typeof window?null:window))return function(){};var r=ht();return r.listeners[e]=t,mt(r,n),function(){r.listeners[e]===t&&(delete r.listeners[e],0===Object.keys(r.listeners).length&&function(e){e.popStateListener&&(window.removeEventListener("popstate",e.popStateListener),e.popStateListener=null),e.undoHistoryPatch&&(e.undoHistoryPatch(),e.undoHistoryPatch=null)}(r))}},bt="__mpApv__",St=["page","limit","offset","cursor","per_page","q","s","oq","search","query","keyword","keywords","term","text","searchTerm","searchText","search_query","search_text","Ntt","pid","productId","sku","skuId","variant","color","colour","size","category","ref","referrer"],It="is_auto_page_view",_t=["hostname","title","path",It].concat(["constructor","__proto__","prototype"],["true","false"]),wt=St.map((function(e){return e.toLowerCase()})),Pt=function(e){return-1!==wt.indexOf(e.toLowerCase())},Ct=/^[a-z0-9_][a-z0-9_.-]{0,63}$/,At=["dwvar_"],Tt=function(e){return At.some((function(t){return 0===e.indexOf(t)}))},Et=function(e){var t=[],n=[],r=0;return e?((Array.isArray(e)?e:String(e).split(",")).forEach((function(e,i){var o=i+1,s=String(e).trim().toLowerCase();s&&(Ct.test(s)&&-1===_t.indexOf(s)?Pt(s)||-1!==t.indexOf(s)||(t.length>=25?r++:t.push(s)):n.push(o))})),{allowed:t,rejectedPositions:n,overLimit:r}):{allowed:t,rejectedPositions:n,overLimit:r}},kt=function(e,t){return e<t?-1:e>t?1:0},Dt=function(e,t){void 0===t&&(t=[]);var n=function(e){return void 0===e&&(e=[]),St.concat(e.filter((function(e){return!Pt(e)})).sort(kt))}(t),r=$(e,n);return n.filter((function(e){return W(r,e)})).filter((function(e){return function(e,t){return Pt(e)||t.length<=512}(e,r[e])})).map((function(e){return{name:e,value:r[e]}})).concat(function(e,t){var n=$(e);return Object.keys(n).filter((function(e){return Tt(e)&&n[e]&&-1===t.indexOf(e)})).sort(kt).map((function(e){return{name:e,value:n[e]}}))}(e,n))},Mt=function(e){var t={};return e.forEach((function(e){var n=e.name,r=e.value;t[n]=r})),t},Ot=function(e){var t;return e?((t={})[It]=!0,t):{}},Ft=function(e){var t=e.params.map((function(e){var t=e.name,n=e.value;return"".concat(t,"=").concat(encodeURIComponent(n))})).join("&");return t?"".concat(e.path,"?").concat(t):e.path},Lt=function(){return"undefined"==typeof window?null:window},Ut=function(){var e=Lt();return e?e[bt]:void 0},Nt=function(){var e=Lt();return e?(e[bt]||(e[bt]={initialPageViewFired:!1}),e[bt]):null},Rt=function(){var e=Ut();return e?e.tracker:void 0},Vt=function(){var e=Ut();return!(!e||!e.initialPageViewFired)},xt=function(){var e=Nt();e&&(e.initialPageViewFired=!0)},Ht=function(){var e=Lt();if(e){var t=Rt();t&&t.teardown(),e[bt]={initialPageViewFired:!1}}},Kt=function(e){return{path:window.location.pathname,params:Dt(X(),e)}},qt=function(e){if(!e)return"";var t=e.params.map((function(e){return e.name}));return t.length?"".concat(e.path," (params: ").concat(t.join(),")"):e.path},Bt=function(){function e(e,t){this.lastPage=null,this.active=!1,this.customQueryParams=[],this.pendingNavigations=[],this.undoHistoryPatch=null,this.mpInstance=e,this.isAutoPageView=!(!t||!t.isAutoPageView)}return Object.defineProperty(e.prototype,"isActive",{get:function(){return this.active},enumerable:!1,configurable:!0}),e.prototype.init=function(){var e=this;if(this.log("[init] PageViewTracker Init"),gt(Lt())){var t,n,r=Rt(),i=this.retire(r);this.active&&r!==this&&(i=i.concat(this.retire(this))),this.active=!0,this.customQueryParams=this.readCustomQueryParams(),this.lastPage=Kt(this.customQueryParams),this.log("[init] seeded lastPage: ".concat(qt(this.lastPage))),this.undoHistoryPatch=yt("pageView",(function(t){return e.safeHandleNavigation(t)}),(function(t){return e.log(t)})),t=this,(n=Nt())&&(n.tracker=t),this.log("[init] patched pushState/replaceState + listening for popstate"),i.forEach((function(t){return e.scheduleFire(t)}))}else this.log("[init] unsupported environment (no History API), not starting")},e.prototype.teardown=function(){var e,t;this.takePendingNavigations(),this.undoHistoryPatch&&(this.undoHistoryPatch(),this.undoHistoryPatch=null),this.active=!1,e=this,(t=Ut())&&t.tracker===e&&(t.tracker=void 0)},e.prototype.readCustomQueryParams=function(){var e=this.mpInstance._Store.SDKConfig.autoLogPageViewQueryParams||{},t=e.allowed,n=void 0===t?[]:t,r=e.rejectedPositions,i=void 0===r?[]:r,o=e.overLimit,s=void 0===o?0:o;return i.length&&this.mpInstance.Logger.warning("mParticle APV: ignoring invalid additional page view query "+"parameters at positions ".concat(i.join(", "))),s&&this.mpInstance.Logger.warning("mParticle APV: ignoring ".concat(s," additional page view ")+"query parameters beyond the limit of "+"".concat(25)),n.length&&this.log("[init] additional query params: ".concat(n.join())),n},e.prototype.retire=function(e){if(!e)return[];this.log(e===this?"[init] retiring this tracker for a repeat mParticle.init() \u2014 transferring pending navigations and tearing down":"[init] retiring a tracker from a previous module load \u2014 transferring pending navigations and tearing down");var t=e.takePendingNavigations();return e.teardown(),t},e.prototype.takePendingNavigations=function(){var e=this.pendingNavigations;return this.pendingNavigations=[],e.forEach((function(e){var t=e.timeoutId;return clearTimeout(t)})),e.map((function(e){return e.page}))},e.prototype.safeHandleNavigation=function(e){if(this.active)try{this.handleNavigation(e)}catch(t){this.log("[error] navigation handler threw (".concat(e,"), page view skipped: ").concat(t))}},e.prototype.handleNavigation=function(e){var t=Kt(this.customQueryParams),n=this.lastPage?Ft(this.lastPage):null;this.log("[detect] navigation signal (source: ".concat(e,", candidate: ").concat(qt(t),", last: ").concat(qt(this.lastPage),")")),function(e,t){return t!==e}(n,Ft(t))?(this.log("[accept] page changed, scheduling fire (source: ".concat(e,", from: ").concat(qt(this.lastPage),", to: ").concat(qt(t),")")),this.lastPage=t,this.scheduleFire(t)):this.log("[dedupe] page unchanged, skipping (source: ".concat(e,", page: ").concat(qt(t),")"))},e.prototype.scheduleFire=function(e){var t=this,n=setTimeout((function(){t.pendingNavigations=t.pendingNavigations.filter((function(e){return e.timeoutId!==n})),t.active?(t.mpInstance._SessionManager.resetSessionTimer(),t.firePageView(e)):t.log("[defer] fire aborted, tracker inactive (torn down before flush)")}),0);this.pendingNavigations.push({page:e,timeoutId:n})},e.prototype.firePageView=function(e){var t=window.document.title,n=function(e){var t=e.params,n=e.hostname,r=e.title,i=e.path,o=e.isAutoPageView;return{messageType:oe.PageView,name:"PageView",data:p(p(p({},Mt(t)),{hostname:n,title:r,path:i}),Ot(o)),eventType:se.Unknown}}(p(p({},e),{hostname:window.location.hostname,title:t,isAutoPageView:this.isAutoPageView}));this.log("[fire] deferred flush -> _Events.logEvent(PageView) (page: ".concat(qt(e),", title: ").concat(t,")")),this.mpInstance._Events.logEvent(n)},e.prototype.log=function(e){this.mpInstance.Logger.verbose("mParticle APV: ".concat(e))},e}(),jt="path",zt="full",Qt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","utm_source_platform","utm_creative_format","utm_marketing_tactic","gad_source","gad_campaignid","mc_cid","gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","dclid","srsltid","epik","ScCid","irclickid","rtid","rclid"].map((function(e){return e.toLowerCase()})),Wt=function(e){return function(e){return Pt(e)||Tt(e.toLowerCase())}(e)||-1!==Qt.indexOf(e.toLowerCase())},Jt=["client_id","redirect_uri","response_type","scope","state","code","nonce"],Gt=Jt.concat(["access_token","id_token","refresh_token","provider_token","provider_refresh_token"]),$t=["ref","referrer"],Yt=/^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/]*@/i,Xt=function(e){return decodeURIComponent(e.replace(/\+/g," "))},Zt=function(e){var t,n=e.indexOf("="),r=-1===n?e:e.slice(0,n);try{t=Xt(r)}catch(e){return null}var i,o=t.toLowerCase();if(!t||!Wt(t)||-1!==Jt.indexOf(o))return null;if(-1===n||-1===$t.indexOf(o))return e;try{i=Xt(e.slice(n+1))}catch(e){return null}var s=nn(i,jt);return s===i?e:"".concat(r,"=").concat(encodeURIComponent(s))},en=function(e){return e.split("&").map(Zt).filter((function(e){return null!==e})).join("&")},tn=function(e){try{var t=Xt(e.split("=")[0]);return-1===Gt.indexOf(t.toLowerCase())}catch(e){return!1}},nn=function(e,t){if("string"!=typeof e||!e)return"";var n=e.indexOf("#"),r=-1===n?"":e.slice(n),i=-1===n?e:e.slice(0,n),o=i.indexOf("?"),s=(-1===o?i:i.slice(0,o)).replace(Yt,"$1");if(t!==zt)return s;var a=-1===o?"":en(i.slice(o+1));return s+(a?"?".concat(a):"")+function(e){var t=e.indexOf("?"),n=-1===t?e:e.slice(0,t);if((/^#[/!]/.test(e)||-1!==t&&-1===n.indexOf("="))&&-1!==t){var r=en(e.slice(t+1));return n+(r?"?".concat(r):"")}if(-1===e.indexOf("="))return e;var i=e.slice(1).split("&").filter(tn).join("&");return i?"#".concat(i):""}(r)},rn=function(){return nn(X(),zt)};!function(e){e.Success="Success",e.QuotaExceeded="QuotaExceeded",e.Unavailable="Unavailable"}(dt||(dt={}));var on=function(){function e(e,t){this._storageKey=e,this.storageObject=t,this.contents=this.retrieve()}return e.prototype.store=function(e){var t;try{return t=H(e)||!z(e)?JSON.stringify(e):"",this.storageObject.setItem(this._storageKey,t),this.contents=e,dt.Success}catch(e){return function(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)}(e)?dt.QuotaExceeded:dt.Unavailable}},e.prototype.retrieve=function(){try{var e=this.storageObject.getItem(this._storageKey);this.contents=e?JSON.parse(e):null}catch(e){this.contents=null}return this.contents},e.prototype.purge=function(){this.contents=null;try{this.storageObject.removeItem(this._storageKey)}catch(e){}},e}(),sn=function(e){function t(t){return e.call(this,t,window.localStorage)||this}return l(t,e),t}(on),an=function(e){function t(t){return e.call(this,t,window.sessionStorage)||this}return l(t,e),t}(on),un=function(e){function t(t){var n=e.call(this,t,window.localStorage)||this;return n.contents=null,n.storageObject.removeItem(n._storageKey),n}return l(t,e),t.prototype.store=function(e){return this.contents=null,dt.Success},t.prototype.retrieve=function(){return this.contents},t.prototype.purge=function(){this.contents=null},t}(on),cn=function(e){this.url=e},dn=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.upload=function(e,t){return g(this,void 0,void 0,(function(){var n;return v(this,(function(r){switch(r.label){case 0:return n=t||this.url,[4,fetch(n,e)];case 1:return[2,r.sent()]}}))}))},t}(cn),ln=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.upload=function(e){return g(this,void 0,void 0,(function(){return v(this,(function(t){switch(t.label){case 0:return[4,this.makeRequest(this.url,e.body,e.method,e.headers)];case 1:return[2,t.sent()]}}))}))},t.prototype.makeRequest=function(e,t,n,r){return void 0===n&&(n="post"),void 0===r&&(r={}),g(this,void 0,void 0,(function(){var i;return v(this,(function(o){return i=new XMLHttpRequest,[2,new Promise((function(o,s){for(var a in i.onreadystatechange=function(){4===i.readyState&&o(i)},i.onerror=function(){s(i)},i.open(n,e),r)r.hasOwnProperty(a)&&i.setRequestHeader(a,r[a]);i.send(t)}))]}))}))},t}(cn);function pn(e,t){if(t){if(!e)return t.MPID=null,t.ConsentState=null,t.UserAttributes=null,void(t.UserIdentities=null);if(!t.MPID||t.MPID!==e.getMPID()){t.MPID=e.getMPID(),t.ConsentState=e.getConsentState(),t.UserAttributes=e.getAllUserAttributes();var n=e.getUserIdentities().userIdentities,r={};for(var i in n){var o=me.IdentityType.getIdentityType(i);!1!==o&&(r[o]=n[i])}var s=[];if(P(r)&&Object.keys(r).length)for(var a in r){var u={};u.Identity=r[a],u.Type=C(a),s.push(u)}t.UserIdentities=s}}}var gn=function(){function e(t,n){var r,i,o;this.offlineStorageEnabled=!1,this.lastASTEventTime=0,this.AST_DEBOUNCE_MS=1e3,this.uploadIntervalTimerId=null,this.exitHandler=null,this.visibilityChangeHandler=null,this.destroyed=!1,this.batchOrder=new Map,this.nextBatchOrder=0,this.mpInstance=t,this.uploadIntervalMillis=n,this.batchingEnabled=n>=e.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<e.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=e.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable();var s=null===(i=t._CookieConsentManager)||void 0===i?void 0:i.getNoFunctional();this.offlineStorageEnabled&&!s&&(this.eventVault=new an("".concat(t._Store.storageName,"-events")),this.batchVault=new sn("".concat(t._Store.storageName,"-batches")),(r=this.eventsQueuedForProcessing).push.apply(r,null!==(o=this.eventVault.retrieve())&&void 0!==o?o:[]));var a=this.mpInstance._Store,u=a.SDKConfig,c=a.devToken,d=this.mpInstance._Helpers.createServiceUrl(u.v3SecureServiceUrl,c);this.uploadUrl="".concat(d,"/events"),this.uploader=window.fetch?new dn(this.uploadUrl):new ln(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners()}return e.prototype.destroy=function(){this.destroyed=!0,null!==this.uploadIntervalTimerId&&(clearTimeout(this.uploadIntervalTimerId),this.uploadIntervalTimerId=null),this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.exitHandler&&(window.removeEventListener("beforeunload",this.exitHandler),window.removeEventListener("pagehide",this.exitHandler)),this.exitHandler=null,this.visibilityChangeHandler=null},e.prototype.isOfflineStorageAvailable=function(){var e=this.mpInstance,t=e._Helpers.getFeatureFlag,n=e._Store.deviceId,i=t(r.FeatureFlags.OfflineStorage);return parseInt(i,10)>=function(e){if(!e)return 100;var t=_(e);return Math.abs(t%100)+1}(n)},e.prototype.shouldDebounceAndUpdateLastASTTime=function(){var e=Date.now();return e-this.lastASTEventTime<this.AST_DEBOUNCE_MS||(this.lastASTEventTime=e,!1)},e.prototype.createBackgroundASTEvent=function(){var e,t=Date.now(),n=this.mpInstance,i=n._Store,o=n.Identity,s=n._timeOnSiteTimer,a=n._Helpers,u=i.sessionId,c=i.deviceId,d=i.sessionStartDate,l=i.SDKConfig,g=a.generateUniqueId,v=a.getFeatureFlag,h=o.getCurrentUser,f={AppName:l.appName,AppVersion:l.appVersion,Package:l.package,EventDataType:oe.AppStateTransition,Timestamp:t,SessionId:u,DeviceId:c,IsFirstRun:!1,SourceMessageId:g(),SDKVersion:r.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null==d?void 0:d.getTime())||t,Debug:l.isDevelopmentMode,ActiveTimeOnSite:(null==s?void 0:s.getTimeInForeground())||0,TotalTimeOnSite:(null===(e=i.getTotalTimeOnSite)||void 0===e?void 0:e.call(i))||0,PageUrl:rn()||null,IsBackgroundAST:!0},m=p({},f.CustomFlags),y=i.integrationAttributes;if(Qe(v)){this.mpInstance._IntegrationCapture.capture();var b=this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();m=p(p({},b),m);var S=this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();y=p(p({},S),y)}return f.CustomFlags=m,f.IntegrationAttributes=y,pn(h(),f),f},e.prototype.addEventListeners=function(){var e=this,t=this,n=function(){if((0,e.mpInstance._Helpers.getFeatureFlag)(r.FeatureFlags.AstBackgroundEvents)){if(t.shouldDebounceAndUpdateLastASTTime())return;var n=t.createBackgroundASTEvent();t.queueEvent(n)}t.prepareAndUpload(!1,t.isBeaconAvailable())};this.exitHandler=n,this.visibilityChangeHandler=function(){"hidden"===document.visibilityState&&n()},document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.addEventListener("beforeunload",n),window.addEventListener("pagehide",n)},e.prototype.isBeaconAvailable=function(){return!!navigator.sendBeacon},e.prototype.triggerUploadInterval=function(e,t){var n=this;void 0===e&&(e=!1),void 0===t&&(t=!1),this.uploadIntervalTimerId=setTimeout((function(){n.prepareAndUpload(e,t)}),this.uploadIntervalMillis)},e.prototype.queueEvent=function(e){if(!z(e)){if(this.eventsQueuedForProcessing.push(e),this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store(this.eventsQueuedForProcessing),this.mpInstance.Logger.isVerbose()){var t=ne(e,this.mpInstance._Store.SDKConfig.isDevelopmentMode);this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(t))),this.mpInstance.Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length))}this.shouldTriggerImmediateUpload(e.EventDataType)&&this.prepareAndUpload(!1,!1)}},e.prototype.shouldTriggerImmediateUpload=function(e){var t=[oe.Commerce,oe.UserIdentityChange];return!this.batchingEnabled||t.includes(e)},e.createNewBatches=function(e,t,n){if(!t||!e||!e.length)return null;for(var r=[],i=new Map,o=0,s=e;o<s.length;o++){if(!(f=s[o]).MPID){var a=t.getMPID();f.MPID=a}(h=i.get(f.MPID))||(h=[]),h.push(f),i.set(f.MPID,h)}for(var u=0,c=Array.from(i.entries());u<c.length;u++){for(var d=c[u],l=(a=d[0],d[1]),p=new Map,g=0,v=l;g<v.length;g++){var h,f=v[g];(h=p.get(f.SessionId))||(h=[]),h.push(f),p.set(f.SessionId,h)}for(var m=0,y=Array.from(p.entries());m<y.length;m++){var b=Je(a,y[m][1],n),S=n._Store.SDKConfig.onCreateBatch;S&&((b=S(b))?b.modified=!0:n.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),b&&r.push(b)}}return r},e.prototype.prepareAndUpload=function(t,n){var r;return void 0===t&&(t=!1),void 0===n&&(n=!1),g(this,void 0,void 0,(function(){var i,o,s,a,u,c,d,l,p,g=this;return v(this,(function(v){switch(v.label){case 0:return i=this.mpInstance.Identity.getCurrentUser(),o=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),s=[],z(o)||(s=e.createNewBatches(o,i,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((d=this.batchesQueuedForProcessing).unshift.apply(d,null!==(r=this.batchVault.retrieve())&&void 0!==r?r:[]),this.batchVault.purge()),z(s)||(l=this.batchesQueuedForProcessing).push.apply(l,s),a=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],a.forEach((function(e){g.batchOrder.has(e.source_request_id)||g.batchOrder.set(e.source_request_id,g.nextBatchOrder++)})),[4,this.uploadBatches(a,n)];case 1:return u=v.sent(),c=(u||[]).map((function(e){return e.source_request_id})),a.forEach((function(e){-1===c.indexOf(e.source_request_id)&&g.batchOrder.delete(e.source_request_id)})),z(u)||(p=this.batchesQueuedForProcessing).unshift.apply(p,u),!n&&this.offlineStorageEnabled&&this.batchVault&&this.storeBatchesQueuedForProcessing(),t&&!this.destroyed&&this.triggerUploadInterval(t,!1),[2]}}))}))},e.prototype.storeBatchesQueuedForProcessing=function(){var e,t=this,n=function(e){var n;return null!==(n=t.batchOrder.get(e.source_request_id))&&void 0!==n?n:-1},r=h(h([],this.batchesQueuedForProcessing,!0),null!==(e=this.batchVault.retrieve())&&void 0!==e?e:[],!0).sort((function(e,t){var r,i;return n(e)-n(t)||(null!==(r=e.timestamp_unixtime_ms)&&void 0!==r?r:0)-(null!==(i=t.timestamp_unixtime_ms)&&void 0!==i?i:0)}));if(z(r))return this.batchVault.store([]),void(this.batchesQueuedForProcessing=[]);for(var i=0;i<r.length;i++){var o=this.batchVault.store(r.slice(i));if(o===dt.Success)return this.logDroppedOfflineBatches(i),void(this.batchesQueuedForProcessing=[]);if(o===dt.Unavailable)return void this.mpInstance.Logger.warning("Offline batch storage is unavailable. Retaining batches in memory.")}this.mpInstance.Logger.warning("Offline batch storage is over quota. Retaining batches in memory.")},e.prototype.logDroppedOfflineBatches=function(e){e>0&&this.mpInstance.Logger.warning("Offline batch storage is over quota. Dropped "+"".concat(e," oldest batch(es)."))},e.prototype.uploadBatches=function(t,n){return g(this,void 0,void 0,(function(){var r,i,o,s,a,u,c;return v(this,(function(d){switch(d.label){case 0:if(r=t.filter((function(e){return!z(e.events)})),z(r))return[2,null];this.mpInstance.Logger.isVerbose()&&(i=ne(r,this.mpInstance._Store.SDKConfig.isDevelopmentMode),this.mpInstance.Logger.verbose("Uploading batches: ".concat(JSON.stringify(i))),this.mpInstance.Logger.verbose("Batch count: ".concat(r.length))),o=0,d.label=1;case 1:return o<r.length?(s={method:"POST",headers:{Accept:e.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(r[o])},n&&this.isBeaconAvailable()?(a=new Blob([s.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,a),[3,5]):[3,2]):[3,6];case 2:return d.trys.push([2,4,,5]),[4,this.uploader.upload(s)];case 3:if(!((u=d.sent()).status>=200&&u.status<300)){if(u.status>=500||429===u.status)return this.mpInstance.Logger.error("HTTP error status ".concat(u.status," received")),[2,r.slice(o,r.length)];if(u.status>=401)return this.mpInstance.Logger.error("HTTP error status ".concat(u.status," while uploading - please verify your API key.")),[2,null];throw console.error("HTTP error status ".concat(u.status," while uploading events."),u),new Error("Uncaught HTTP Error ".concat(u.status,". Batch upload will be re-attempted."))}return this.mpInstance.Logger.verbose("Upload success for request ID: ".concat(r[o].source_request_id)),[3,5];case 4:return c=d.sent(),this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(c)),[2,r.slice(o,r.length)];case 5:return o++,[3,1];case 6:return[2,null]}}))}))},e.CONTENT_TYPE="text/plain;charset=UTF-8",e.MINIMUM_INTERVAL_MILLIS=500,e}(),vn={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",IDENTITY_MISMATCH:"IDENTITY_MISMATCH",MP_DEPRECATED_METHOD_USAGE:"MP_DEPRECATED_METHOD_USAGE"},hn={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},fn=r.IdentityMethods.Modify,mn={isNumber:H,isFunction:K,isStringOrNumber:j,isValidAttributeValue:function(e){return void 0!==e&&!P(e)&&!Array.isArray(e)},isValidKeyValue:function(e){return Boolean(e&&!P(e)&&!Array.isArray(e)&&!this.isFunction(e))},removeFalsyIdentityValues:function(e,t){if(!e||!e.userIdentities)return e;var n={},r=p({},e.userIdentities);for(var i in e.userIdentities)if(e.userIdentities.hasOwnProperty(i)){var o=e.userIdentities[i];null===o||o||(t.warning("Identity value for '".concat(i,"' is falsy (").concat(o,"). This value will be removed from the request.")),delete r[i])}return n.userIdentities=r,n},validateIdentities:function(e,t){var n={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(e){if(t===fn&&(P(e.userIdentities)&&!Object.keys(e.userIdentities).length||!P(e.userIdentities)))return{valid:!1,error:r.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent};for(var i in e)if(e.hasOwnProperty(i)){if(!n[i])return{valid:!1,error:r.Messages.ValidationMessages.IdentityRequesetInvalidKey};if("onUserAlias"===i&&!mn.isFunction(e[i]))return{valid:!1,error:r.Messages.ValidationMessages.OnUserAliasType}}if(0===Object.keys(e).length)return{valid:!0};if(void 0===e.userIdentities)return{valid:!1,error:r.Messages.ValidationMessages.UserIdentities};if(null!==e.userIdentities&&!P(e.userIdentities))return{valid:!1,error:r.Messages.ValidationMessages.UserIdentities};if(P(e.userIdentities)&&Object.keys(e.userIdentities).length)for(var o in e.userIdentities)if(e.userIdentities.hasOwnProperty(o)){if(!1===me.IdentityType.getIdentityType(o))return{valid:!1,error:r.Messages.ValidationMessages.UserIdentitiesInvalidKey};if("string"!=typeof e.userIdentities[o]&&null!==e.userIdentities[o])return{valid:!1,error:r.Messages.ValidationMessages.UserIdentitiesInvalidValues}}}return{valid:!0}}},yn=r.HTTPCodes,bn=r.IdentityMethods,Sn=bn.Identify,In=bn.Modify,_n=bn.Login,wn=bn.Logout,Pn=r.HTTPCodes,Cn=r.Messages,An="x-mp-max-age",Tn=function(e,t,n,r,i){if(!i){var o=Ln(null==r?void 0:r.cacheMaxAge);switch(e){case _n:case Sn:En(e,t,o,n,r);break;case In:case wn:n.purge()}}},En=function(e,t,n,r,i){var o=i.responseText,s=i.status,a=r.retrieve()||{},u=_(kn(e,t)),c={mpid:o.mpid,is_logged_in:o.is_logged_in};a[u]={responseText:JSON.stringify(c),status:s,expireTimestamp:n},r.store(a)},kn=function(e,t){var n="device_application_stamp",r="".concat(e,":").concat(n,"=").concat(t.device_application_stamp,";"),i="";if(Object.keys(t).length){var o=new Array;for(var s in t)s!==n&&(o[me.IdentityType.getIdentityType(s)]=t[s]);i=o.reduce((function(e,t,n){var r=me.IdentityType.getIdentityName(n);return"".concat(e).concat(r,"=").concat(t,";")}),r)}return i},Dn=function(e,t,n){var r=_(kn(e,t)),i=n.retrieve(),o=i?i[r]:null;return{responseText:Un(o.responseText),expireTimestamp:o.expireTimestamp,status:o.status}},Mn=function(e,t){var n={};if(P(null==e?void 0:e.userIdentities))for(var r in e.userIdentities)n[r]=e.userIdentities[r];return n.device_application_stamp=t,n},On=function(e){var t=e.retrieve()||{},n=(new Date).getTime();for(var r in t)t[r].expireTimestamp<n&&delete t[r];e.store(t)},Fn=function(e,t,n,r,i,o,s){var a=function(e,t,n){var r=null==n?void 0:n.retrieve();if(!r)return!1;var i=_(kn(e,t));return!(!W(r,i)||r[i].expireTimestamp<(new Date).getTime())}(s,e,t);return!!a&&(n(Dn(s,e,t),r,i,o,s,e,!0),!0)},Ln=function(e){return void 0===e&&(e=86400),(new Date).getTime()+1e3*e},Un=function(e){return e?JSON.parse(e):{}},Nn={email_sha256:"other",mobile_sha256:"other2"},Rn=function(e){var t=p({},e);return Object.keys(Nn).forEach((function(e){if(e in t){var n=t[e];delete t[e],t[Nn[e]]=n}})),t},Vn=function(e,t){if(!e||!(null==t?void 0:t.userIdentities))return!1;var n,r,i,o,s=e.getUserIdentities().userIdentities,a=Rn(t.userIdentities);return n=s,r=a,i=Object.keys(null!=n?n:{}),o=Object.keys(null!=r?r:{}),!(i.length===o.length&&i.every((function(e){return n[e]===r[e]})))},xn=function(e){var t,n,r,i=null===(n=null===(t=null==e?void 0:e.SDKConfig)||void 0===t?void 0:t.identifyRequest)||void 0===n?void 0:n.userIdentities;return!(!i||!P(i)||z(i)||!Object.values(i).some(Boolean))||!!(null===(r=null==e?void 0:e.SDKConfig)||void 0===r?void 0:r.deviceId)},Hn=function(e,t,n,i){var s=e._Helpers,a=e._Store,u=e.Logger,c=e._ErrorReportingDispatcher,d=a.SDKConfig,l=d.identityUrl,h=d.isDevelopmentMode;if(s.canLog()){var f=s.createServiceUrl(l),m=h?"development":"production";!function(e,t,n,r,i,s,a,u){g(void 0,void 0,void 0,(function(){var c,d,l,g,h,f,m,y,b,S,I,_;return v(this,(function(v){switch(v.label){case 0:if(!K(i))return s.error("search called without a callback function; skipping request."),[2];if(c=function(e){try{i(e)}catch(e){s.error("Error invoking search callback: "+ie(e))}},d=mn.removeFalsyIdentityValues({userIdentities:null!=e?e:{}},s).userIdentities,!Object.values(null!=d?d:{}).some((function(e){return"string"==typeof e&&e.length>0})))return s.verbose("Identity search called with empty identifiers; skipping request."),c({httpCode:yn.noHttpCoverage}),[2];if(!t)return s.verbose("search called without a workspace API key; skipping request."),c({httpCode:yn.noHttpCoverage}),[2];v.label=1;case 1:return v.trys.push([1,9,,10]),l=n(),g=p(p({},l),{known_identities:p({},d)}),h={method:"post",headers:{Accept:"application/json","Content-Type":"application/json","x-mp-key":t},body:JSON.stringify(g)},f=a||(window.fetch?new dn(r):new ln(r)),s.verbose("Sending search request to "+r),[4,f.upload(h,r)];case 2:if(m=v.sent(),y=void 0,!K(m.json))return[3,7];v.label=3;case 3:return v.trys.push([3,5,,6]),[4,m.json()];case 4:return y=v.sent(),[3,6];case 5:return v.sent(),s.verbose("search response had no parseable JSON body."),[3,6];case 6:return[3,8];case 7:if(null==(b=m)?void 0:b.responseText)try{y=JSON.parse(b.responseText)}catch(e){s.verbose("search XHR response was not valid JSON.")}v.label=8;case 8:return m.status===o?s.verbose("search received 200 OK."):404===m.status?s.verbose("search received 404 (no match)."):s.verbose("search received non-success status "+m.status),c({httpCode:m.status,body:y}),[3,10];case 9:return S=v.sent(),I=ie(S),_="Error sending search request: "+I,s.error(_),null==u||u.report({message:_,code:vn.IDENTITY_REQUEST,severity:hn.ERROR}),c({httpCode:yn.noHttpCoverage}),[3,10];case 10:return[2]}}))}))}(n,t,(function(){return function(e){return{client_sdk:{platform:r.platform,sdk_vendor:r.sdkVendor,sdk_version:r.sdkVersion},environment:e,request_id:w(),request_timestamp_ms:Date.now()}}(m)}),f+"search?cb=1",i,u,void 0,c)}else if(u.verbose(Cn.InformationMessages.AbandonLogEvent),K(i))try{i({httpCode:Pn.loggingDisabledOrMissingAPIKey})}catch(e){u.error("Error invoking search callback: "+ie(e))}};function Kn(e,t){this.uploader=null;var n=this;this.queueEventForBatchUpload=function(t){if(!this.uploader){var n=C(e._Helpers.getFeatureFlag(r.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new gn(e,n)}this.uploader.queueEvent(t),e._Persistence.update()},this.processQueuedEvents=function(){var t,r=e.Identity.getCurrentUser();if(r&&(t=r.getMPID()),e._Store.eventQueue.length&&t){var i=e._Store.eventQueue;e._Store.eventQueue=[],this.appendUserInfoToEvents(r,i),i.forEach((function(e){n.sendEventToServer(e)}))}},this.appendUserInfoToEvents=function(e,t){t.forEach((function(t){t.MPID||pn(e,t)}))};this.sendEventToServer=function(n,i){var o=re({shouldUploadEvent:!0},i);if(e._Store.webviewBridgeEnabled)e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.LogEvent,JSON.stringify(n));else{var s,a=e.Identity.getCurrentUser();if(a&&(s=a.getMPID()),e._Store.requireDelay=e._Helpers.isDelayedByIntegration(e._preInit.integrationDelays,e._Store.integrationDelayTimeoutStart,Date.now()),!function(n,r){var i;if(!(null===(i=e._CookieConsentManager)||void 0===i?void 0:i.getNoFunctional())||xn(e._Store)||r||!e._Store.configurationLoaded||e._Store.requireDelay)return!1;var o=n;return(null==t?void 0:t.kitBlockingEnabled)&&(o=t.createBlockedEvent(n)),o&&(e._Forwarders.sendEventToForwarders(o),n.AlreadySentToForwarders=!0),e.Logger.verbose("noFunctional event forwarded to kits and queued for MP server upload when MPID is available."),e._Store.eventQueue.push(n),!0}(n,s)){if(!s||e._Store.requireDelay||!e._Store.configurationLoaded)return e.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void e._Store.eventQueue.push(n);this.processQueuedEvents(),z(n)||(o.shouldUploadEvent&&this.queueEventForBatchUpload(n),n.EventName!==String(me.MessageType.AppStateTransition)&&(t&&t.kitBlockingEnabled&&(n=t.createBlockedEvent(n)),n&&!n.AlreadySentToForwarders&&e._Forwarders.sendEventToForwarders(n)))}}},this.sendBatchForwardingStatsToServer=function(t,n){var r,i;try{r=e._Helpers.createServiceUrl(e._Store.SDKConfig.v2SecureServiceUrl,e._Store.devToken),i={uuid:e._Helpers.generateUniqueId(),data:t},n&&(n.open("post",r+"/Forwarding"),n.send(JSON.stringify(i)))}catch(t){e.Logger.error("Error sending forwarding stats to mParticle servers.")}},this.initializeForwarderStatsUploader=function(){var t=e._Store.SDKConfig.v1SecureServiceUrl,n=e._Store.devToken,r="https://".concat(t).concat(n,"/Forwarding");return window.fetch?new dn(r):new ln(r)},this.prepareForwardingStats=function(t,n){var i,o=e._Forwarders.getForwarderStatsQueue();if(t&&t.isVisible){i={mid:t.id,esid:t.eventSubscriptionId,n:n.EventName,attrs:n.EventAttributes,sdk:n.SDKVersion,dt:n.EventDataType,et:n.EventCategory,dbg:n.Debug,ct:n.Timestamp,eec:n.ExpandedEventCount,dp:n.DataPlan};var s=e._Forwarders,a=s.sendSingleForwardingStatsToServer,u=s.setForwarderStatsQueue;e._Helpers.getFeatureFlag(r.FeatureFlags.ReportBatching)?(o.push(i),u(o)):a(i)}}}var qn=function(){function e(){}var t;return e.hashEventType=function(e){return _(e)},e.hashEventName=function(e,t){return _(t+e)},e.hashEventAttributeKey=function(e,t,n){return _(e+t+n)},e.hashUserAttribute=function(e){return _(e)},e.hashUserIdentity=function(e){return e},e.hashConsentPurpose=function(e,t){return _(e+t)},e.hashAttributeConditionalForwarding=function(e){return _(e).toString()},e.hashConsentPurposeConditionalForwarding=function(e,t){return this.hashConsentPurpose(e,t).toString()},t=e,e.filterUserAttributes=function(e,n){return Z(e,n,(function(e){return t.hashUserAttribute(e)}))},e.filterUserIdentities=function(e,n){return Z(e,n,(function(e){return t.hashUserIdentity(ue.getIdentityType(e))}))},e.isFilteredUserAttribute=function(e,n){var r=t.hashUserAttribute(e);return n&&b(n,r)},e}(),Bn=r.StorageNames;function jn(e,t,n){n===me.IdentityType.CustomerId?e.unshift(t):e.push(t)}function zn(e){var t=this;this.canLog=function(){return!(!e._Store.isEnabled||!e._Store.devToken&&!e._Store.webviewBridgeEnabled)},this.getFeatureFlag=function(t){return e._Store.SDKConfig.flags.hasOwnProperty(t)?e._Store.SDKConfig.flags[t]:null},this.invokeCallback=function(n,r,i,o,s){n||e.Logger.warning("There is no callback provided");try{t.Validators.isFunction(n)&&n({httpCode:r,body:i,getUser:function(){return o||e.Identity.getCurrentUser()},getPreviousUser:function(){if(s)return(null==(r=o||e.Identity.getCurrentUser())?void 0:r.getMPID())===s?null:e.Identity.getUser(s);var t=e.Identity.getUsers(),n=t.shift(),r=o||e.Identity.getCurrentUser();return n&&r&&n.getMPID()===r.getMPID()&&(n=t.shift()),n||null}})}catch(t){e.Logger.error("There was an error with your callback: "+t)}},this.invokeAliasCallback=function(n,r,i){n||e.Logger.warning("There is no callback provided");try{if(t.Validators.isFunction(n)){var o={httpCode:r};i&&(o.message=i),n(o)}}catch(t){e.Logger.error("There was an error with your callback: "+t)}},this.extend=re,this.createServiceUrl=function(t,n){var r,i=window.mParticle&&e._Store.SDKConfig.forceHttps?"https://":window.location.protocol+"//";return r=e._Store.SDKConfig.forceHttps?"https://"+t:i+t,n&&(r+=n),r},this.createXHR=function(t){var n;try{n=new window.XMLHttpRequest}catch(t){e.Logger.error("Error creating XMLHttpRequest object.")}if(n&&t&&"withCredentials"in n)n.onreadystatechange=t;else if(void 0!==window.XDomainRequest){e.Logger.verbose("Creating XDomainRequest object");try{(n=new window.XDomainRequest).onload=t}catch(t){e.Logger.error("Error creating XDomainRequest object")}}return n},this.filterUserIdentities=function(e,n){return function(e,t,n){var r=[];if(!e||!Object.keys(e).length)return r;for(var i in e)if(e.hasOwnProperty(i)){var o=me.IdentityType.getIdentityType(i);!1===o||n(t,o)||jn(r,{Type:o,Identity:e[i]},o)}return r}(e,n,t.inArray)},this.filterUserIdentitiesForForwarders=qn.filterUserIdentities,this.filterUserAttributes=qn.filterUserAttributes,this.isEventType=function(e){for(var t in me.EventType)if(me.EventType.hasOwnProperty(t)&&me.EventType[t]===e)return!0;return!1},this.sanitizeAttributes=function(n,r){if(!n||!t.isObject(n))return null;var i={};for(var o in n)n.hasOwnProperty(o)&&t.Validators.isValidAttributeValue(n[o])?i[o]=n[o]:e.Logger.warning("For '"+r+"', the corresponding attribute value of '"+o+"' must be a string, number, boolean, or null.");return i},this.isDelayedByIntegration=function(t,n,r){if(r-n>e._Store.SDKConfig.integrationDelayTimeout)return!1;for(var i in t)if(!0===t[i])return!0;return!1},this.createMainStorageName=function(e){return e?Bn.currentStorageName+"_"+e:Bn.currentStorageName},this.converted=V,this.findKeyInObject=S,this.parseNumber=C,this.inArray=b,this.isObject=P,this.decoded=R,this.parseStringOrNumber=A,this.generateHash=_,this.generateUniqueId=w,this.Validators=mn}var Qn=r.Messages,Wn="mParticleAndroid",Jn="mParticle";function Gn(e){if(Object.prototype.hasOwnProperty.call(window,e))return window[e]}function $n(e){var t=this;this.initializeSessionAttributes=function(e){var n=r.NativeSdkPaths.SetSessionAttribute,i=JSON.stringify({key:"$src_env",value:"webview"}),o=JSON.stringify({key:"$src_key",value:e});t.sendToNative(n,i),e&&t.sendToNative(n,o)},this.isBridgeV2Available=function(e){var t,n;if(!e)return!1;var r=Wn+"_"+e+"_v2",i=Jn+"_"+e+"_v2";return!!(null===(n=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===n?void 0:n.hasOwnProperty(i))||(!(!window.mParticle||!window.mParticle.uiwebviewBridgeName||window.mParticle.uiwebviewBridgeName!==i)||!!window.hasOwnProperty(r))},this.isWebviewEnabled=function(n,r){return e._Store.bridgeV2Available=t.isBridgeV2Available(n),e._Store.bridgeV1Available=t.isBridgeV1Available(),2===r?e._Store.bridgeV2Available:(!window.mParticle||!window.mParticle.uiwebviewBridgeName||window.mParticle.uiwebviewBridgeName===Jn+"_"+n+"_v2")&&(r<2&&(e._Store.bridgeV2Available||e._Store.bridgeV1Available))},this.isBridgeV1Available=function(){return!!(e._Store.SDKConfig.useNativeSdk||Gn(Wn)||e._Store.SDKConfig.isIOS)},this.sendToNative=function(n,r){e._Store.bridgeV2Available&&2===e._Store.SDKConfig.minWebviewBridgeVersion||e._Store.bridgeV2Available&&e._Store.SDKConfig.minWebviewBridgeVersion<2?t.sendViaBridgeV2(n,r,e._Store.SDKConfig.requiredWebviewBridgeName):e._Store.bridgeV1Available&&e._Store.SDKConfig.minWebviewBridgeVersion<2&&t.sendViaBridgeV1(n,r)},this.sendViaBridgeV1=function(n,r){var i=Gn(Wn);i&&i.hasOwnProperty(n)?(e.Logger.verbose(Qn.InformationMessages.SendAndroid+n),i[n](r)):e._Store.SDKConfig.isIOS&&(e.Logger.verbose(Qn.InformationMessages.SendIOS+n),t.sendViaIframeToIOS(n,r))},this.sendViaIframeToIOS=function(e,t){var n=document.createElement("IFRAME");n.setAttribute("src","mp-sdk://"+e+"/"+encodeURIComponent(t)),document.documentElement.appendChild(n),n.parentNode.removeChild(n)},this.sendViaBridgeV2=function(n,r,i){var o,s;if(i){var a,u,c=Gn(Wn+"_"+i+"_v2"),d=Jn+"_"+i+"_v2";if((null===(s=null===(o=window.webkit)||void 0===o?void 0:o.messageHandlers)||void 0===s?void 0:s[d])&&(a=window.webkit.messageHandlers[d]),e.uiwebviewBridgeName===d&&(u=e[d]),c&&c.hasOwnProperty(n))return e.Logger.verbose(Qn.InformationMessages.SendAndroid+n),void c[n](r);a?(e.Logger.verbose(Qn.InformationMessages.SendIOS+n),a.postMessage(JSON.stringify({path:n,value:r?JSON.parse(r):null}))):u&&(e.Logger.verbose(Qn.InformationMessages.SendIOS+n),t.sendViaIframeToIOS(n,r))}}}var Yn=r.Messages.InformationMessages,Xn={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function Zn(e){var t=this;this.attemptCookieSync=function(n,r){var i,o=e._Store,s=o.pixelConfigurations,a=o.webviewBridgeEnabled;if(n&&!a&&!(null===(i=e._CookieConsentManager)||void 0===i?void 0:i.getNoFunctional())){var u=e._Persistence.getPersistence();z(u)||s.forEach((function(i){var o,s,a;try{var c=!1,d=i.filteringConsentRuleValues,l=i.pixelUrl,p=i.redirectUrl,g=i.moduleId,v=i.settings,h=i.frequencyCap,f=(d||{}).values;if(z(l))return;if(z(f)||(c=!0),c&&r)return;if(g===Xn.Rokt&&e._CookieConsentManager.getNoTargeting())return;if(!(0,e._Consent.isEnabledForUserConsent)(d,e.Identity.getCurrentUser()))return;var m=null!==(s=null===(o=u[n])||void 0===o?void 0:o.csd)&&void 0!==s?s:{},y=m[g]||null;if(!er(h,y))return;var b=g===Xn.TradeDesk?window.location.hostname:void 0,S="true"===(null===(a=null==v?void 0:v.enableHmTag)||void 0===a?void 0:a.toLowerCase()),I=g===Xn.DoubleclickDFP&&S,_=I?U(n):void 0;I&&!_&&e.Logger.warning("Unable to base64 encode the current MPID; omitting the google_hm parameter from this cookie sync");var w=F(n,l,p,b,_);t.performCookieSync(w,g.toString(),n,m)}catch(t){e.Logger.error("Error performing cookie sync: "+t)}}))}},this.performCookieSync=function(t,n,r,i){var o=document.createElement("img");e.Logger.verbose(Yn.CookieSync),o.onload=function(){i[n]=(new Date).getTime(),e._Persistence.saveUserCookieSyncDatesToPersistence(r,i)},o.src=t}}var er=function(e,t){return!t||(new Date).getTime()>new Date(t).getTime()+864e5*e};function tr(e,t,n){t.warning(e.warningMessage),null==n||n.report({message:e.methodName,code:vn.MP_DEPRECATED_METHOD_USAGE,severity:hn.WARNING})}var nr=r.Messages;function rr(e){var t=this;function n(e,t){if(!e||!t||t<=0)return!1;var n=6e4*t;return Date.now()-e>=n}function r(){var t;e._Events.logEvent({messageType:me.MessageType.SessionEnd}),e._Store.nullifySession(),null===(t=e._timeOnSiteTimer)||void 0===t||t.resetTimer()}this.initialize=function(){var r;if(e._Store.sessionId){var i=e._Store,o=i.dateLastEventSent,s=i.SDKConfig,a=s.sessionTimeout;if(n(null==o?void 0:o.getTime(),a))t.endSession(),t.startNewSession();else{var u=e.Identity.getCurrentUser(),c=s.identifyRequest;!((null===(r=e._CookieConsentManager)||void 0===r?void 0:r.getNoFunctional())&&!xn(e._Store))&&Vn(u,c)&&(e.Identity.identify(c,s.identityCallback),e._Store.identifyCalled=!0,e._Store.SDKConfig.identityCallback=null)}}else t.startNewSession()},this.getSession=function(){return tr({methodName:"SessionManager.getSession()",warningMessage:I("SessionManager.getSession()",!1,"SessionManager.getSessionId()")},e.Logger,e._ErrorReportingDispatcher),this.getSessionId()},this.getSessionId=function(){return e._Store.sessionId},this.startNewSession=function(){var n;if(e.Logger.verbose(nr.InformationMessages.StartingNewSession),e._Helpers.canLog()){e._Store.sessionId=e._Helpers.generateUniqueId().toUpperCase();var r=e.Identity.getCurrentUser(),i=r?r.getMPID():null;if(i&&(e._Store.currentSessionMPIDs=[i]),!e._Store.sessionStartDate){var o=new Date;e._Store.sessionStartDate=o,e._Store.dateLastEventSent=o}t.setSessionTimer();var s=(null===(n=e._CookieConsentManager)||void 0===n?void 0:n.getNoFunctional())&&!xn(e._Store);e._Store.identifyCalled||s||(e.Identity.identify(e._Store.SDKConfig.identifyRequest,e._Store.SDKConfig.identityCallback),e._Store.identifyCalled=!0,e._Store.SDKConfig.identityCallback=null),e._Events.logEvent({messageType:me.MessageType.SessionStart})}else e.Logger.verbose(nr.InformationMessages.AbandonStartSession)},this.endSession=function(i){var o,s,a,u;if(e.Logger.verbose(nr.InformationMessages.StartingEndSession),i)r();else{if(!e._Helpers.canLog())return e.Logger.verbose(nr.InformationMessages.AbandonEndSession),void(null===(o=e._timeOnSiteTimer)||void 0===o||o.resetTimer());var c=e._Persistence.getPersistence();if(!c||c.gs&&!c.gs.sid)return e.Logger.verbose(nr.InformationMessages.NoSessionToEnd),void(null===(s=e._timeOnSiteTimer)||void 0===s||s.resetTimer());if(c.gs.sid&&e._Store.sessionId!==c.gs.sid&&(e._Store.sessionId=c.gs.sid),null===(a=null==c?void 0:c.gs)||void 0===a?void 0:a.les){var d=e._Store.SDKConfig.sessionTimeout;n(c.gs.les,d)?r():(t.setSessionTimer(),null===(u=e._timeOnSiteTimer)||void 0===u||u.resetTimer())}}},this.setSessionTimer=function(){var n=6e4*e._Store.SDKConfig.sessionTimeout;e._Store.globalTimer=window.setTimeout((function(){t.endSession()}),n)},this.resetSessionTimer=function(){e._Store.webviewBridgeEnabled||(e._Store.sessionId||t.startNewSession(),t.clearSessionTimeout(),t.setSessionTimer()),t.startNewSessionIfNeeded()},this.clearSessionTimeout=function(){clearTimeout(e._Store.globalTimer)},this.startNewSessionIfNeeded=function(){if(!e._Store.webviewBridgeEnabled){var n=e._Persistence.getPersistence();!e._Store.sessionId&&n&&(n.sid?e._Store.sessionId=n.sid:t.startNewSession())}}}var ir=r.Messages;function or(e){var t=this;this.convertTransactionAttributesToProductAction=function(e,t){e.hasOwnProperty("Id")&&(t.TransactionId=e.Id),e.hasOwnProperty("Affiliation")&&(t.Affiliation=e.Affiliation),e.hasOwnProperty("CouponCode")&&(t.CouponCode=e.CouponCode),e.hasOwnProperty("Revenue")&&(t.TotalAmount=this.sanitizeAmount(e.Revenue,"Revenue")),e.hasOwnProperty("Shipping")&&(t.ShippingAmount=this.sanitizeAmount(e.Shipping,"Shipping")),e.hasOwnProperty("Tax")&&(t.TaxAmount=this.sanitizeAmount(e.Tax,"Tax")),e.hasOwnProperty("Step")&&(t.CheckoutStep=e.Step),e.hasOwnProperty("Option")&&(t.CheckoutOptions=e.Option)},this.calculateProductActionTotalAmount=function(e){if(!e||null!=e.TotalAmount)return e;var t=0;return Array.isArray(e.ProductList)&&e.ProductList.forEach((function(e){t+=C(e.Quantity)*C(e.Price)})),t+=C(e.ShippingAmount)+C(e.TaxAmount),e.TotalAmount=t,e},this.getProductActionEventName=function(e){switch(e){case me.ProductActionType.AddToCart:return"AddToCart";case me.ProductActionType.AddToWishlist:return"AddToWishlist";case me.ProductActionType.Checkout:return"Checkout";case me.ProductActionType.CheckoutOption:return"CheckoutOption";case me.ProductActionType.Click:return"Click";case me.ProductActionType.Purchase:return"Purchase";case me.ProductActionType.Refund:return"Refund";case me.ProductActionType.RemoveFromCart:return"RemoveFromCart";case me.ProductActionType.RemoveFromWishlist:return"RemoveFromWishlist";case me.ProductActionType.ViewDetail:return"ViewDetail";case me.ProductActionType.ViewCart:return"ViewCart";case me.ProductActionType.AddShippingInfo:return"AddShippingInfo";case me.ProductActionType.AddPaymentInfo:return"AddPaymentInfo";case me.ProductActionType.PaymentMethodSelected:return"PaymentMethodSelected";case me.ProductActionType.PaymentAttempted:return"PaymentAttempted";case me.ProductActionType.PaymentSucceeded:return"PaymentSucceeded";case me.ProductActionType.PaymentFailed:return"PaymentFailed";case me.ProductActionType.RefundInitiated:return"RefundInitiated";case me.ProductActionType.Unknown:default:return"Unknown"}},this.getPromotionActionEventName=function(e){switch(e){case me.PromotionActionType.PromotionClick:return"PromotionClick";case me.PromotionActionType.PromotionView:return"PromotionView";default:return"Unknown"}},this.convertProductActionToEventType=function(t){switch(t){case me.ProductActionType.AddToCart:return me.CommerceEventType.ProductAddToCart;case me.ProductActionType.AddToWishlist:return me.CommerceEventType.ProductAddToWishlist;case me.ProductActionType.Checkout:return me.CommerceEventType.ProductCheckout;case me.ProductActionType.CheckoutOption:return me.CommerceEventType.ProductCheckoutOption;case me.ProductActionType.Click:return me.CommerceEventType.ProductClick;case me.ProductActionType.Purchase:return me.CommerceEventType.ProductPurchase;case me.ProductActionType.Refund:return me.CommerceEventType.ProductRefund;case me.ProductActionType.RemoveFromCart:return me.CommerceEventType.ProductRemoveFromCart;case me.ProductActionType.RemoveFromWishlist:return me.CommerceEventType.ProductRemoveFromWishlist;case me.ProductActionType.Unknown:return me.EventType.Unknown;case me.ProductActionType.ViewDetail:return me.CommerceEventType.ProductViewDetail;case me.ProductActionType.ViewCart:case me.ProductActionType.AddShippingInfo:case me.ProductActionType.AddPaymentInfo:case me.ProductActionType.PaymentMethodSelected:case me.ProductActionType.PaymentAttempted:case me.ProductActionType.PaymentSucceeded:case me.ProductActionType.PaymentFailed:case me.ProductActionType.RefundInitiated:return me.EventType.Unknown;default:return e.Logger.error("Could not convert product action type "+t+" to event type"),null}},this.convertPromotionActionToEventType=function(t){switch(t){case me.PromotionActionType.PromotionClick:return me.CommerceEventType.PromotionClick;case me.PromotionActionType.PromotionView:return me.CommerceEventType.PromotionView;default:return e.Logger.error("Could not convert promotion action type "+t+" to event type"),null}},this.generateExpandedEcommerceName=function(e,t){return"eCommerce - "+e+" - "+(t?"Total":"Item")},this.extractProductAttributes=function(e,t){t.CouponCode&&(e["Coupon Code"]=t.CouponCode),t.Brand&&(e.Brand=t.Brand),t.Category&&(e.Category=t.Category),t.Name&&(e.Name=t.Name),t.Sku&&(e.Id=t.Sku),t.Price&&(e["Item Price"]=t.Price),t.Quantity&&(e.Quantity=t.Quantity),t.Position&&(e.Position=t.Position),t.Variant&&(e.Variant=t.Variant),e["Total Product Amount"]=t.TotalAmount||0},this.extractTransactionId=function(e,t){t.TransactionId&&(e["Transaction Id"]=t.TransactionId)},this.extractActionAttributes=function(e,n){t.extractTransactionId(e,n),n.Affiliation&&(e.Affiliation=n.Affiliation),n.CouponCode&&(e["Coupon Code"]=n.CouponCode),n.TotalAmount&&(e["Total Amount"]=n.TotalAmount),n.ShippingAmount&&(e["Shipping Amount"]=n.ShippingAmount),n.TaxAmount&&(e["Tax Amount"]=n.TaxAmount),n.CheckoutOptions&&(e["Checkout Options"]=n.CheckoutOptions),n.CheckoutStep&&(e["Checkout Step"]=n.CheckoutStep)},this.extractPromotionAttributes=function(e,t){t.Id&&(e.Id=t.Id),t.Creative&&(e.Creative=t.Creative),t.Name&&(e.Name=t.Name),t.Position&&(e.Position=t.Position)},this.createProduct=function(t,n,r,i,o,s,a,u,c,d){return d=e._Helpers.sanitizeAttributes(d,t),"string"!=typeof t?(e.Logger.error("Name is required when creating a product"),null):e._Helpers.Validators.isStringOrNumber(n)?e._Helpers.Validators.isStringOrNumber(r)?(r=e._Helpers.parseNumber(r),u&&!e._Helpers.Validators.isNumber(u)&&(e.Logger.error("Position must be a number, it will be set to null."),u=null),{Name:t,Sku:n,Price:r,Quantity:i=e._Helpers.Validators.isStringOrNumber(i)?e._Helpers.parseNumber(i):1,Brand:a,Variant:o,Category:s,Position:u,CouponCode:c,TotalAmount:i*r,Attributes:d}):(e.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(e.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(t,n,r,i){return e._Helpers.Validators.isStringOrNumber(t)?{Id:t,Creative:n,Name:r,Position:i}:(e.Logger.error(ir.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(t,n){return"string"!=typeof t?(e.Logger.error("Name is required when creating an impression."),null):n?{Name:t,Product:n}:(e.Logger.error("Product is required when creating an impression."),null)},this.createTransactionAttributes=function(t,n,r,i,o,s){return e._Helpers.Validators.isStringOrNumber(t)?{Id:t,Affiliation:n,CouponCode:r,Revenue:i,Shipping:o,Tax:s}:(e.Logger.error(ir.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(n){var r=[];return n.ProductImpressions?(n.ProductImpressions.forEach((function(i){i.ProductList&&i.ProductList.forEach((function(o){var s=re(!1,{},n.EventAttributes);if(o.Attributes)for(var a in o.Attributes)s[a]=o.Attributes[a];t.extractProductAttributes(s,o),i.ProductImpressionList&&(s["Product Impression List"]=i.ProductImpressionList);var u=e._ServerModel.createEventObject({messageType:me.MessageType.PageEvent,name:t.generateExpandedEcommerceName("Impression"),data:s,eventType:me.EventType.Transaction});r.push(u)}))})),r):r},this.expandCommerceEvent=function(e){return e?t.expandProductAction(e).concat(t.expandPromotionAction(e)).concat(t.expandProductImpression(e)):null},this.expandPromotionAction=function(n){var r=[];return n.PromotionAction?(n.PromotionAction.PromotionList.forEach((function(i){var o=re(!1,{},n.EventAttributes);t.extractPromotionAttributes(o,i);var s=e._ServerModel.createEventObject({messageType:me.MessageType.PageEvent,name:t.generateExpandedEcommerceName(me.PromotionActionType.getExpansionName(n.PromotionAction.PromotionActionType)),data:o,eventType:me.EventType.Transaction});r.push(s)})),r):r},this.expandProductAction=function(n){var r=[];if(!n.ProductAction)return r;var i=!1;if(n.ProductAction.ProductActionType===me.ProductActionType.Purchase||n.ProductAction.ProductActionType===me.ProductActionType.Refund){var o=re(!1,{},n.EventAttributes);o["Product Count"]=n.ProductAction.ProductList?n.ProductAction.ProductList.length:0,t.extractActionAttributes(o,n.ProductAction),n.CurrencyCode&&(o["Currency Code"]=n.CurrencyCode);var s=e._ServerModel.createEventObject({messageType:me.MessageType.PageEvent,name:t.generateExpandedEcommerceName(me.ProductActionType.getExpansionName(n.ProductAction.ProductActionType),!0),data:o,eventType:me.EventType.Transaction});r.push(s)}else i=!0;var a=n.ProductAction.ProductList;return a?(a.forEach((function(o){var s=re(!1,n.EventAttributes,o.Attributes);i?t.extractActionAttributes(s,n.ProductAction):t.extractTransactionId(s,n.ProductAction),t.extractProductAttributes(s,o);var a=e._ServerModel.createEventObject({messageType:me.MessageType.PageEvent,name:t.generateExpandedEcommerceName(me.ProductActionType.getExpansionName(n.ProductAction.ProductActionType)),data:s,eventType:me.EventType.Transaction});r.push(a)})),r):r},this.createCommerceEventObject=function(t,n){var r,i=e._Helpers.extend;return e.Logger.verbose(ir.InformationMessages.StartingLogCommerceEvent),e._Helpers.canLog()?((r=e._ServerModel.createEventObject({messageType:me.MessageType.Commerce,sourceMessageId:null==n?void 0:n.sourceMessageId})).EventName="eCommerce - ",r.CurrencyCode=e._Store.currencyCode,r.CustomFlags=i(r.CustomFlags,t),r):(e.Logger.verbose(ir.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(t,n){if(!e._Helpers.Validators.isStringOrNumber(t)){var r=[n,"must be of type number. A",c(t),"was passed. Converting to 0"].join(" ");return e.Logger.warning(r),0}return e._Helpers.parseNumber(t)}}var sr=function(){function e(e,t){void 0===t&&(t=!1),this.noFunctional=t,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(e),this.timerVault=new sn(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking()}return e.prototype.addHandlers=function(){var e=this;document.addEventListener("visibilitychange",(function(){return e.handleVisibilityChange()})),window.addEventListener("blur",(function(){return e.handleWindowBlur()})),window.addEventListener("focus",(function(){return e.handleWindowFocus()})),window.addEventListener("storage",(function(t){return e.syncAcrossTabs(t)})),window.addEventListener("beforeunload",(function(){return e.updateTimeInPersistence()}))},e.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking()},e.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking()},e.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking()},e.prototype.syncAcrossTabs=function(e){if(e.key===this.localStorageName&&null!==e.newValue){var t=parseFloat(e.newValue)||0;this.totalTime=t}},e.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime))},e.prototype.loadTimeFromStorage=function(){var e=this.timerVault.retrieve();H(e)&&null!==e&&(this.totalTime=e)},e.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0)},e.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1)},e.prototype.setTotalTime=function(){if(this.isTrackerActive){var e=Math.floor(performance.now());this.totalTime+=e-this.startTime,this.startTime=e}},e.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},e.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence()},e}();function ar(e){var t=e?p({},e):{};return(!0===t.noDeviceId||!0===t.noDeviceID)&&(t.noDeviceId=!0,t.noFunctional=!0,t.noTargeting=!0),t}function ur(e,t,n){var i=this,o=t._Helpers.createMainStorageName,s=t._NativeSdkHelpers.isWebviewEnabled,a={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,persistenceData:{gs:{}}};for(var u in a)this[u]=a[u];if(this.devToken=n||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=function(e){var t={};for(var n in r.DefaultConfig)r.DefaultConfig.hasOwnProperty(n)&&(t[n]=r.DefaultConfig[n]);if(e)for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);for(var n in r.DefaultBaseUrls)t[n]=r.DefaultBaseUrls[n];return t.flags=t.flags||{},t}(e),e){e.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=cr(e),this.SDKConfig.autoLogPageViewQueryParams=Et(e.autoLogPageViewQueryParams),e.deviceId&&(this.deviceId=e.deviceId),e.hasOwnProperty("isDevelopmentMode")?this.SDKConfig.isDevelopmentMode=N(e.isDevelopmentMode):this.SDKConfig.isDevelopmentMode=!1;var d=dr(e,this.SDKConfig.flags,n);for(var l in d)this.SDKConfig[l]=d[l];if(this.SDKConfig.useNativeSdk=!!e.useNativeSdk,this.SDKConfig.kits=e.kits||{},this.SDKConfig.sideloadedKits=e.sideloadedKits||[],e.hasOwnProperty("isIOS")?this.SDKConfig.isIOS=e.isIOS:this.SDKConfig.isIOS=!(!window.mParticle||!window.mParticle.isIOS)&&window.mParticle.isIOS,e.hasOwnProperty("useCookieStorage")?this.SDKConfig.useCookieStorage=e.useCookieStorage:this.SDKConfig.useCookieStorage=!1,e.hasOwnProperty("maxCookieSize")?this.SDKConfig.maxCookieSize=e.maxCookieSize:this.SDKConfig.maxCookieSize=r.DefaultConfig.maxCookieSize,e.hasOwnProperty("appName")&&(this.SDKConfig.appName=e.appName),e.hasOwnProperty("package")&&(this.SDKConfig.package=e.package),e.hasOwnProperty("integrationDelayTimeout")?this.SDKConfig.integrationDelayTimeout=e.integrationDelayTimeout:this.SDKConfig.integrationDelayTimeout=r.DefaultConfig.integrationDelayTimeout,e.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=e.identifyRequest),e.hasOwnProperty("identityCallback")){var g=e.identityCallback;t._Helpers.Validators.isFunction(g)?this.SDKConfig.identityCallback=e.identityCallback:t.Logger.warning("The optional callback must be a function. You tried entering a(n) "+c(g)+" . Callback not set. Please set your callback again.")}if(e.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=e.appVersion),e.hasOwnProperty("appName")&&(this.SDKConfig.appName=e.appName),e.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=e.sessionTimeout),e.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var v=e.dataPlan;v.planId&&(B(v.planId)?this.SDKConfig.dataPlan.PlanId=v.planId:t.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),v.planVersion&&(H(v.planVersion)?this.SDKConfig.dataPlan.PlanVersion=v.planVersion:t.Logger.error("Your data plan version must be a number"))}else this.SDKConfig.dataPlan={};if(e.hasOwnProperty("forceHttps")?this.SDKConfig.forceHttps=e.forceHttps:this.SDKConfig.forceHttps=!0,this.SDKConfig.customFlags=e.customFlags||{},e.hasOwnProperty("minWebviewBridgeVersion")?this.SDKConfig.minWebviewBridgeVersion=e.minWebviewBridgeVersion:this.SDKConfig.minWebviewBridgeVersion=1,e.hasOwnProperty("aliasMaxWindow")?this.SDKConfig.aliasMaxWindow=e.aliasMaxWindow:this.SDKConfig.aliasMaxWindow=r.DefaultConfig.aliasMaxWindow,e.hasOwnProperty("dataPlanOptions")){var h=e.dataPlanOptions;h.hasOwnProperty("dataPlanVersion")&&h.hasOwnProperty("blockUserAttributes")&&h.hasOwnProperty("blockEventAttributes")&&h.hasOwnProperty("blockEvents")&&h.hasOwnProperty("blockUserIdentities")||t.Logger.error('Ensure your config.dataPlanOptions object has the following keys: a "dataPlanVersion" object, and "blockUserAttributes", "blockEventAttributes", "blockEvents", "blockUserIdentities" booleans')}e.hasOwnProperty("onCreateBatch")&&("function"==typeof e.onCreateBatch?this.SDKConfig.onCreateBatch=e.onCreateBatch:(t.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0))}this._getFromPersistence=function(e,t){return e?(i.syncPersistenceData(),i.persistenceData&&i.persistenceData[e]&&i.persistenceData[e][t]?i.persistenceData[e][t]:null):null},this._setPersistence=function(e,n,r){var o;e&&(i.syncPersistenceData(),i.persistenceData&&(P(i.persistenceData[e])?i.persistenceData[e][n]=r:i.persistenceData[e]=((o={})[n]=r,o),P(i.persistenceData[e][n])&&z(i.persistenceData[e][n])&&delete i.persistenceData[e][n],t._Persistence.savePersistence(i.persistenceData)))},this.hasInvalidIdentifyRequest=function(){var e=i.SDKConfig.identifyRequest;return P(e)&&P(e.userIdentities)&&z(e.userIdentities)||!e},this.getConsentState=function(e){var n=t._Consent.ConsentSerialization.fromMinifiedJsonObject,r=i._getFromPersistence(e,"con");return z(r)?null:n(r)},this.setConsentState=function(e,n){var r=t._Consent.ConsentSerialization.toMinifiedJsonObject;(n||null===n)&&i._setPersistence(e,"con",r(n))},this.getDeviceId=function(){return i.deviceId},this.setDeviceId=function(e){i.deviceId=e,i.persistenceData.gs.das=e,t._Persistence.update()},this.getFirstSeenTime=function(e){return i._getFromPersistence(e,"fst")},this.setFirstSeenTime=function(e,t){if(e){var n=t||(new Date).getTime();i._setPersistence(e,"fst",n)}},this.getLastSeenTime=function(e){if(!e)return null;var n=t.Identity.getCurrentUser();return e===(null==n?void 0:n.getMPID())?(new Date).getTime():i._getFromPersistence(e,"lst")},this.setLastSeenTime=function(e,t){if(e){var n=t||(new Date).getTime();i._setPersistence(e,"lst",n)}},this.getLocalSessionAttributes=function(){return i.localSessionAttributes||{}},this.setLocalSessionAttribute=function(e,n){var r;i.localSessionAttributes[e]=n,i.persistenceData.gs.lsa=p(p({},i.persistenceData.gs.lsa||{}),((r={})[e]=n,r)),t._Persistence.savePersistence(i.persistenceData)},this.syncPersistenceData=function(){var e=t._Persistence.getPersistence();i.persistenceData=re({},i.persistenceData,e)},this.getUserAttributes=function(e){return i._getFromPersistence(e,"ua")||{}},this.setUserAttributes=function(e,t){return i._setPersistence(e,"ua",t)},this.getUserIdentities=function(e){return i._getFromPersistence(e,"ui")||{}},this.setUserIdentities=function(e,t){i._setPersistence(e,"ui",t)},this.getRoktAccountId=function(){return i.roktAccountId},this.setRoktAccountId=function(e){i.roktAccountId=e},this.getIntegrationName=function(){return i.integrationName},this.setIntegrationName=function(e){i.integrationName=e},this.getTimeOnSite=function(){var e;return null===(e=t._timeOnSiteTimer)||void 0===e?void 0:e.getTimeInForeground()},this.getTotalTimeOnSite=function(){return i.sessionStartDate?Date.now()-i.sessionStartDate.getTime():void 0},this.addMpidToSessionHistory=function(e,t){var n=i.currentSessionMPIDs.indexOf(e);e&&t!==e&&n<0?i.currentSessionMPIDs.push(e):n>=0&&(i.currentSessionMPIDs=Q(i.currentSessionMPIDs,n))},this.nullifySession=function(){i.sessionId=null,i.dateLastEventSent=null,i.sessionStartDate=null,i.sessionAttributes={},i.localSessionAttributes={},t._Persistence.update()},this.processConfig=function(e){var r=e.workspaceToken,a=e.requiredWebviewBridgeName;e.flags&&(i.SDKConfig.flags=cr(e)),i.SDKConfig.autoLogPageViewQueryParams=Et(e.autoLogPageViewQueryParams);var u=dr(e,i.SDKConfig.flags,n);for(var c in u)i.SDKConfig[c]=u[c];if(r){i.SDKConfig.workspaceToken=r;var d=ar(null==e?void 0:e.launcherOptions).noFunctional;t._timeOnSiteTimer=new sr(r,d)}else t.Logger.warning("You should have a workspaceToken on your config object for security purposes.");i.storageName=o(r),i.SDKConfig.requiredWebviewBridgeName=a||r,i.webviewBridgeEnabled=s(i.SDKConfig.requiredWebviewBridgeName,i.SDKConfig.minWebviewBridgeVersion),i.configurationLoaded=!0}}function cr(e){var t={},n=r.FeatureFlags,i=n.ReportBatching,o=n.EventBatchingIntervalMillis,s=n.OfflineStorage,a=n.DirectUrlRouting,u=n.CacheIdentity,c=n.AudienceAPI,d=n.CaptureIntegrationSpecificIds,l=n.CaptureIntegrationSpecificIdsV2,p=n.AstBackgroundEvents,g=n.AutoLogPageView,v=n.AutoButtonTracking;return e.flags?(t[i]=e.flags[i]||!1,t[o]=C(e.flags[o])||r.DefaultConfig.uploadInterval,t[s]=e.flags[s]||"0",t[a]="True"===e.flags[a],t[u]="True"===e.flags[u],t[c]="True"===e.flags[c],t[d]="True"===e.flags[d],t[l]=e.flags[l]||"none",t[p]="True"===e.flags[p],t[g]="True"===e.flags[g],t[v]="True"===e.flags[v],t):{}}function dr(e,t,n){return n?z(e.domain)&&t.directURLRouting?function(e,t){var n=r.DefaultBaseUrls,i={},o="us1",s=t.split("-"),a=s.length<=1?o:s[0];for(var u in n)if("configUrl"!==u)if(e.hasOwnProperty(u))i[u]=e[u];else{var c=n[u].split(".");i[u]=h([c[0],a],c.slice(1),!0).join(".")}else i[u]=e[u]||n[u];return i}(e,n):lr(e):{}}function lr(e){var t=r.DefaultBaseUrls,n=r.CNAMEUrlPaths,i={};if(!z(e.domain)){for(var o in n)i[o]="".concat(e.domain).concat(n[o]);return i}for(var s in t)i[s]=e[s]||t[s];return i}var pr=function(){function e(e){var t,n;this.logLevel=null!==(t=e.logLevel)&&void 0!==t?t:xe,this.logger=null!==(n=e.logger)&&void 0!==n?n:new gr}return e.prototype.verbose=function(e){this.logLevel!==Re&&this.logger.verbose&&this.logLevel===Ve&&this.logger.verbose(e)},e.prototype.warning=function(e){this.logLevel!==Re&&(!this.logger.warning||this.logLevel!==Ve&&this.logLevel!==xe||this.logger.warning(e))},e.prototype.error=function(e){this.logLevel!==Re&&this.logger.error&&this.logger.error(e)},e.prototype.isVerbose=function(){return this.logLevel===Ve},e.prototype.setLogLevel=function(e){this.logLevel=e},e}(),gr=function(){function e(){}return e.prototype.verbose=function(e){console&&console.info&&console.info(e)},e.prototype.error=function(e){console&&console.error&&console.error(e)},e.prototype.warning=function(e){console&&console.warn&&console.warn(e)},e}(),vr=n.Base64,hr=r.Messages,fr=r.Base64CookieKeys,mr=r.SDKv2NonMPIDCookieKeys,yr=r.StorageNames;function br(){return window.mParticle}function Sr(e){var t=this;function n(n,r,i){var o;return r?(o=function(e,t){return e&&t?re(!1,e,t):e||t}(r,i),n.removeItem(e._Store.storageName)):i&&(o=i),t.storeDataInMemory(o),o}function r(r,i){if(e._Store.isLocalStorageAvailable)return e._Store.SDKConfig.useCookieStorage?n(window.localStorage,r,i):function(n,r){if(r){var i=n||r;return t.storeDataInMemory(i),t.expireCookies(e._Store.storageName),i}t.storeDataInMemory(n)}(r,i);t.storeDataInMemory(i)}function i(t){var n=e._Store;return t.gs.sid=n.sessionId,t.gs.ie=n.isEnabled,t.gs.sa=n.sessionAttributes,t.gs.lsa=n.localSessionAttributes,t.gs.ss=n.serverSettings,t.gs.dt=n.devToken,t.gs.les=n.dateLastEventSent?n.dateLastEventSent.getTime():null,t.gs.av=n.SDKConfig.appVersion,t.gs.cgid=n.clientId,t.gs.das=n.deviceId,t.gs.c=n.context,t.gs.ssd=n.sessionStartDate?n.sessionStartDate.getTime():0,t.gs.ia=n.integrationAttributes,t}function o(n){var r=t.decodePersistence(n);if(!r)return null;var i=JSON.parse(r);return e._Helpers.isObject(i)&&Object.keys(i).length?i:null}function s(e,t){return e.length>t}function a(t,n,r){if(t[n])return e.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+r+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(t[n],null,2)),void delete t[n];e.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+r+". We recommend using a maxCookieSize of 1500.")}function u(e){var t="https:"===window.location.protocol;window.document.cookie=t?e+";Secure":e}function c(e,n,r){return t.encodePersistence(JSON.stringify(e))+";expires="+n+";path=/"+r}function d(t,n){var r;t[n]&&(r=t[n],Array.isArray(r)?r.length>0:e._Helpers.isObject(r)&&Object.keys(r).length>0)?t[n]=vr.encode(JSON.stringify(t[n])):delete t[n]}function l(t,n){var r=t[n];e._Helpers.isObject(r)&&Object.keys(r).length?t[n]=vr.encode(JSON.stringify(r)):delete t[n]}function p(e){for(var t in e)e.hasOwnProperty(t)&&fr[t]&&l(e,t)}function g(e){for(var t in e)e.hasOwnProperty(t)&&fr[t]&&e[t].length&&(e[t]=JSON.parse(vr.decode(e[t])))}this.useLocalStorage=function(){return!e._Store.SDKConfig.useCookieStorage&&e._Store.isLocalStorageAvailable},this.initializeStorage=function(){var n,i=null;try{var o=t.getLocalStorage();(function(t,n){if(!t&&!n)return e._Store.isFirstRun=!0,void(e._Store.mpid=0);e._Store.isFirstRun=!1})(o,i=t.getCookie()),e._Store.isLocalStorageAvailable||(e._Store.SDKConfig.useCookieStorage=!0),!function(t){for(var n in t)t.hasOwnProperty(n)&&!mr[n]&&(e._Store.nonCurrentUserMPIDs[n]=t[n])}(r(o,i)),t.update()}catch(r){n=Boolean(i),t.useLocalStorage()&&e._Store.isLocalStorageAvailable?n||localStorage.removeItem(e._Store.storageName):t.expireCookies(e._Store.storageName),e.Logger.error("Error initializing storage: "+r)}},this.update=function(){e._Store.webviewBridgeEnabled||(e._Store.SDKConfig.useCookieStorage&&t.setCookie(),t.setLocalStorage())},this.storeDataInMemory=function(t,n){try{if(!t)return e.Logger.verbose(hr.InformationMessages.CookieNotFound),e._Store.clientId=e._Store.clientId||e._Helpers.generateUniqueId(),void(e._Store.deviceId=e._Store.deviceId||e._Helpers.generateUniqueId());!function(t,n){e._Store.mpid=n||t.cu||0,t.gs=t.gs||{},e._Store.sessionId=t.gs.sid||e._Store.sessionId,e._Store.isEnabled=void 0!==t.gs.ie?t.gs.ie:e._Store.isEnabled,e._Store.sessionAttributes=t.gs.sa||e._Store.sessionAttributes,e._Store.localSessionAttributes=t.gs.lsa||e._Store.localSessionAttributes,e._Store.serverSettings=t.gs.ss||e._Store.serverSettings,e._Store.devToken=e._Store.devToken||t.gs.dt,e._Store.SDKConfig.appVersion=e._Store.SDKConfig.appVersion||t.gs.av,e._Store.clientId=t.gs.cgid||e._Store.clientId||e._Helpers.generateUniqueId(),e._Store.deviceId=e._Store.deviceId||t.gs.das||e._Helpers.generateUniqueId(),e._Store.integrationAttributes=t.gs.ia||{},e._Store.context=t.gs.c||e._Store.context,e._Store.currentSessionMPIDs=t.gs.csm||e._Store.currentSessionMPIDs,e._Store.isLoggedIn=!0===t.l,t.gs.les&&(e._Store.dateLastEventSent=new Date(t.gs.les)),e._Store.sessionStartDate=t.gs.ssd?new Date(t.gs.ssd):new Date,t=n?t[n]:t[t.cu]}(t,n)}catch(t){e.Logger.error(hr.ErrorMessages.CookieParseError)}},this.determineLocalStorageAvailability=function(e){var t=br();if(null==t?void 0:t._forceNoLocalStorage)return!1;try{e.setItem("mparticle","test");var n="test"===e.getItem("mparticle");return e.removeItem("mparticle"),Boolean(n&&e)}catch(e){return!1}},this.setLocalStorage=function(){var n;if(e._Store.isLocalStorageAvailable&&!(null===(n=e._CookieConsentManager)||void 0===n?void 0:n.getNoFunctional())){var r=e._Store.storageName,o=t.getLocalStorage()||{},s=e.Identity.getCurrentUser(),a=s?s.getMPID():null;if(!e._Store.SDKConfig.useCookieStorage){o.gs=o.gs||{},o.l=e._Store.isLoggedIn?1:0,e._Store.sessionId&&(o.gs.csm=e._Store.currentSessionMPIDs),o.gs.ie=e._Store.isEnabled,a&&(o.cu=a),Object.keys(e._Store.nonCurrentUserMPIDs).length&&(o=re({},o,e._Store.nonCurrentUserMPIDs),e._Store.nonCurrentUserMPIDs={}),o=i(o);try{window.localStorage.setItem(encodeURIComponent(r),t.encodePersistence(JSON.stringify(o)))}catch(t){e.Logger.error("Error with setting localStorage item.")}}}},this.getLocalStorage=function(){return e._Store.isLocalStorageAvailable?o(window.localStorage.getItem(e._Store.storageName)):null},this.expireCookies=function(e){var n,r,i=new Date;n=""===(r=t.getCookieDomain())?"":";domain="+r,i.setTime(i.getTime()-864e5),u(e+"="+("; expires="+i.toUTCString())+"; path=/"+n)},this.getCookie=function(){var t,n,r,i,s,a,u=e._Store.storageName;e.Logger.verbose(hr.InformationMessages.CookieSearch);try{t=window.document.cookie.split("; ")}catch(t){return e.Logger.verbose("Unable to parse undefined cookie"),null}for(n=0,r=t.length;n<r;n++){try{s=(i=t[n].split("=")).shift(),a=i.join("=")}catch(t){e.Logger.verbose("Unable to parse cookie: "+s+". Skipping.")}if(u&&u===s){var c=o(e._Helpers.converted(a));if(c)return e.Logger.verbose(hr.InformationMessages.CookieFound),c}}return null},this.setCookie=function(){var n;if(!(null===(n=e._CookieConsentManager)||void 0===n?void 0:n.getNoFunctional())){var r,o=e.Identity.getCurrentUser();o&&(r=o.getMPID());var s,a,c,d=new Date,l=e._Store.storageName,p=t.getCookie()||{},g=new Date(d.getTime()+24*e._Store.SDKConfig.cookieExpiration*60*60*1e3).toUTCString();a=""===(s=t.getCookieDomain())?"":";domain="+s,p.gs=p.gs||{},e._Store.sessionId&&(p.gs.csm=e._Store.currentSessionMPIDs),r&&(p.cu=r),p.l=e._Store.isLoggedIn?1:0,p=i(p),Object.keys(e._Store.nonCurrentUserMPIDs).length&&(p=re({},p,e._Store.nonCurrentUserMPIDs),e._Store.nonCurrentUserMPIDs={}),c=t.reduceAndEncodePersistence(p,g,a,e._Store.SDKConfig.maxCookieSize),e.Logger.verbose(hr.InformationMessages.CookieSet),u(encodeURIComponent(l)+"="+c)}},this.reduceAndEncodePersistence=function(e,t,n,r){var i=e.gs.csm?e.gs.csm:[];if(!i.length)return function(e,t,n,r){var i;for(var o in e)e.hasOwnProperty(o)&&s(i=c(e,t,n),r)&&(mr[o]||o===e.cu||delete e[o]);return i}(e,t,n,r);var o=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(mr[n]||n===e.cu||(t[n]=1));return t}(e);return Object.keys(o).length&&function(e,t,n,r,i,o){var a;for(var u in t)s(a=c(e,r,i),o)&&t.hasOwnProperty(u)&&-1===n.indexOf(u)&&delete e[u]}(e,o,i,t,n,r),function(e,t,n,r,i){for(var o,u=0;u<t.length&&s(o=c(e,n,r),i);u++)a(e,t[u],i);return o}(e,i,t,n,r)},this.encodePersistence=function(e){var t=JSON.parse(e);return function(e){for(var t in e)e.hasOwnProperty(t)&&(fr[t]?d(e,t):"ie"!==t?e[t]||delete e[t]:e[t]=e[t]?1:0)}(t.gs),function(e){for(var t in e)e.hasOwnProperty(t)&&(mr[t]||p(e[t]))}(t),m(JSON.stringify(t))},this.decodePersistence=function(t){try{if(!t)return;var n=JSON.parse(y(t));return e._Helpers.isObject(n)&&Object.keys(n).length&&(function(e){for(var t in e)e.hasOwnProperty(t)&&(fr[t]?(e[t]=JSON.parse(vr.decode(e[t])),"csm"!==t||Array.isArray(e[t])||delete e[t]):"ie"===t&&(e[t]=Boolean(e[t])))}(n.gs),function(t){for(var n in t)if(t.hasOwnProperty(n))if(mr[n])"l"===n&&(t[n]=Boolean(t[n]));else{if(!e._Helpers.isObject(t[n])){delete t[n];continue}g(t[n])}}(n)),JSON.stringify(n)}catch(t){e.Logger.error("Problem with decoding cookie")}},this.getCookieDomain=function(){if(e._Store.SDKConfig.cookieDomain)return e._Store.SDKConfig.cookieDomain;var n=t.getDomain(document,location.hostname);return""===n?"":"."+n},this.getDomain=function(e,t){var n,r,i="mptest=cookie",o=t.split(".");for(n=o.length-1;n>=0;n--)if(r=o.slice(n).join("."),e.cookie=i+";domain=."+r+";",e.cookie.indexOf(i)>-1)return e.cookie=i.split("=")[0]+"=;domain=."+r+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",r;return""},this.saveUserCookieSyncDatesToPersistence=function(n,r){if(r){var i=t.getPersistence();i&&(e._Helpers.isObject(i[n])?i[n].csd=r:i[n]={csd:r}),t.savePersistence(i)}},this.swapCurrentUser=function(e,n,r){if(e&&n&&e!==n){var i=t.getPersistence();i&&(i.cu=n,i.gs.csm=r,t.savePersistence(i))}},this.savePersistence=function(n){var r;if(!(null===(r=e._CookieConsentManager)||void 0===r?void 0:r.getNoFunctional())){var i,o=t.encodePersistence(JSON.stringify(n)),s=new Date,a=e._Store.storageName,c=new Date(s.getTime()+24*e._Store.SDKConfig.cookieExpiration*60*60*1e3).toUTCString(),d=t.getCookieDomain();if(i=""===d?"":";domain="+d,e._Store.SDKConfig.useCookieStorage){var l=t.reduceAndEncodePersistence(n,c,i,e._Store.SDKConfig.maxCookieSize);u(encodeURIComponent(a)+"="+l)}else if(e._Store.isLocalStorageAvailable)try{localStorage.setItem(e._Store.storageName,o)}catch(t){e.Logger.error("Error saving persistence to localStorage.")}}},this.getPersistence=function(){return this.useLocalStorage()?this.getLocalStorage():this.getCookie()},this.getFirstSeenTime=function(e){if(!e)return null;var n=t.getPersistence();return n&&n[e]&&n[e].fst?n[e].fst:null},this.setFirstSeenTime=function(n,r){if(n){r||(r=(new Date).getTime());var i=t.getPersistence();i&&(e._Helpers.isObject(i[n])||(i[n]={}),i[n].fst||(i[n].fst=r,t.savePersistence(i)))}},this.getLastSeenTime=function(n){if(!n)return null;if(n===e.Identity.getCurrentUser().getMPID())return(new Date).getTime();var r=t.getPersistence();return r&&r[n]&&r[n].lst?r[n].lst:null},this.setLastSeenTime=function(n,r){if(n){r||(r=(new Date).getTime());var i=t.getPersistence();i&&e._Helpers.isObject(i[n])&&(i[n].lst=r,t.savePersistence(i))}},this.getDeviceId=function(){return e._Store.deviceId},this.setDeviceId=function(n){e._Store.deviceId=n,t.update()},this.resetPersistence=function(){localStorage.clear(),t.expireCookies(yr.cookieName),t.expireCookies(yr.cookieNameV2),t.expireCookies(yr.cookieNameV3),t.expireCookies(yr.cookieNameV4),t.expireCookies(e._Store.storageName);var n=br();if(null==n?void 0:n._isTestEnv){var r="abcdef";localStorage.removeItem(e._Helpers.createMainStorageName(r)),t.expireCookies(e._Helpers.createMainStorageName(r))}},this.forwardingStatsBatches={uploadsTable:{},forwardingStatsEventQueue:[]}}var Ir=r.Messages;function _r(e){var t=this;this.logEvent=function(t,n){if(e.Logger.verbose(Ir.InformationMessages.StartingLogEvent+": "+t.name),e._Helpers.canLog()){var r=e._ServerModel.createEventObject(t);e._APIClient.sendEventToServer(r,n)}else e.Logger.verbose(Ir.InformationMessages.AbandonLogEvent)},this.startTracking=function(t){if(e._Store.isTracking){var n={coords:{latitude:e._Store.currentPosition.lat,longitude:e._Store.currentPosition.lng}};r(t,n)}else"geolocation"in navigator&&(e._Store.watchPositionId=navigator.geolocation.watchPosition((function(n){e._Store.currentPosition={lat:n.coords.latitude,lng:n.coords.longitude},r(t,n),t=null,e._Store.isTracking=!0}),(function(){r(t),t=null,e._Store.isTracking=!1})));function r(t,n){if(t)try{n?t(n):t()}catch(t){e.Logger.error("Error invoking the callback passed to startTrackingLocation."),e.Logger.error(t)}}},this.stopTracking=function(){e._Store.isTracking&&(navigator.geolocation.clearWatch(e._Store.watchPositionId),e._Store.currentPosition=null,e._Store.isTracking=!1)},this.logOptOut=function(){e.Logger.verbose(Ir.InformationMessages.StartingLogOptOut);var t=e._ServerModel.createEventObject({messageType:me.MessageType.OptOut,eventType:me.EventType.Other});e._APIClient.sendEventToServer(t)},this.logAST=function(){t.logEvent({messageType:me.MessageType.AppStateTransition})},this.logPageView=function(n){var r;t.logEvent({messageType:me.MessageType.PageView,name:"PageView",data:p(p(p({},Mt(Dt(X(),null===(r=e._Store.SDKConfig.autoLogPageViewQueryParams)||void 0===r?void 0:r.allowed))),{hostname:window.location.hostname,title:window.document.title}),Ot(n&&n.isAutoPageView)),eventType:me.EventType.Unknown})},this.logProductActionEvent=function(n,r,i,o,s,a){var u=e._Ecommerce.createCommerceEventObject(o,a),c=Array.isArray(r)?r:[r];c.forEach((function(t){t.TotalAmount&&(t.TotalAmount=e._Ecommerce.sanitizeAmount(t.TotalAmount,"TotalAmount")),t.Position&&(t.Position=e._Ecommerce.sanitizeAmount(t.Position,"Position")),t.Price&&(t.Price=e._Ecommerce.sanitizeAmount(t.Price,"Price")),t.Quantity&&(t.Quantity=e._Ecommerce.sanitizeAmount(t.Quantity,"Quantity"))})),u&&(u.EventCategory=e._Ecommerce.convertProductActionToEventType(n),u.EventName+=e._Ecommerce.getProductActionEventName(n),u.ProductAction={ProductActionType:n,ProductList:c},me.ProductActionType.isRoktCommerceType(n)&&(u.CustomFlags=u.CustomFlags||{},u.CustomFlags["Rokt.CommerceEventType"]=me.ProductActionType.getExpansionName(n)),e._Helpers.isObject(s)&&e._Ecommerce.convertTransactionAttributesToProductAction(s,u.ProductAction),t.logCommerceEvent(u,i,a))},this.logPurchaseEvent=function(n,r,i,o){var s=e._Ecommerce.createCommerceEventObject(o);s&&(s.EventName+=e._Ecommerce.getProductActionEventName(me.ProductActionType.Purchase),s.EventCategory=me.CommerceEventType.ProductPurchase,s.ProductAction={ProductActionType:me.ProductActionType.Purchase,ProductList:Array.isArray(r)?r:[r]},e._Ecommerce.convertTransactionAttributesToProductAction(n,s.ProductAction),t.logCommerceEvent(s,i))},this.logPromotionEvent=function(n,r,i,o,s){var a=e._Ecommerce.createCommerceEventObject(o);a&&(a.EventName+=e._Ecommerce.getPromotionActionEventName(n),a.EventCategory=e._Ecommerce.convertPromotionActionToEventType(n),a.PromotionAction={PromotionActionType:n,PromotionList:Array.isArray(r)?r:[r]},t.logCommerceEvent(a,i,s))},this.logImpressionEvent=function(n,r,i,o){var s=e._Ecommerce.createCommerceEventObject(i);s&&(s.EventName+="Impression",s.EventCategory=me.CommerceEventType.ProductImpression,Array.isArray(n)||(n=[n]),s.ProductImpressions=[],n.forEach((function(e){s.ProductImpressions.push({ProductImpressionList:e.Name,ProductList:Array.isArray(e.Product)?e.Product:[e.Product]})})),t.logCommerceEvent(s,r,o))},this.logCommerceEvent=function(t,n,r){if(e.Logger.verbose(Ir.InformationMessages.StartingLogCommerceEvent),t.ProductAction&&null===t.EventCategory)e.Logger.error("Commerce event not sent. The mParticle.ProductActionType you passed was invalid. Re-check your code.");else{var i=e._Helpers.sanitizeAttributes(n,t.EventName);e._Helpers.canLog()?(i&&(t.EventAttributes=i),t.ProductAction&&e._Ecommerce.calculateProductActionTotalAmount(t.ProductAction),e._APIClient.sendEventToServer(t,r),e._Persistence.update()):e.Logger.verbose(Ir.InformationMessages.AbandonLogEvent)}},this.addEventHandler=function(n,r,i,o,s){var a,u=[];if(r)if("string"==typeof r?u=document.querySelectorAll(r):r.nodeType&&(u=[r]),u.length){e.Logger.verbose("Found "+u.length+" element"+(u.length>1?"s":"")+", attaching event handlers");var c=function(){var r=u[a],c=function(n){!function(n,r){e.Logger.verbose("DOM event triggered, handling event"),t.logEvent({messageType:me.MessageType.PageEvent,name:"function"==typeof i?i(r):i,data:"function"==typeof o?o(r):o,eventType:s||me.EventType.Other}),(r.href&&"_blank"!==r.target||r.submit)&&(n.preventDefault?n.preventDefault():n.returnValue=!1,setTimeout((function(){r.href?window.location.href=r.href:r.submit&&r.submit()}),e._Store.SDKConfig.timeout))}(n,r)};r.addEventListener?r.addEventListener(n,c,!1):r.attachEvent?r.attachEvent("on"+n,c):r["on"+n]=c};for(a=0;a<u.length;a++)c()}else e.Logger.verbose("No elements found");else e.Logger.error("Can't bind event, selector is required")}}function wr(e,t){return!(null==e?void 0:e.isAttributeKeyBlocked(t))}function Pr(e,t){return!(null==e?void 0:e.isIdentityBlocked(t))}function Cr(e,t,n,r){function i(){var i=function(e,t){var n,r={};if(!e)return r;for(var i in e)W(e,i)&&!J(i)&&wr(t,i)&&(r[i]=(n=e[i],Array.isArray(n)?n.slice():n));return r}(n._Store.getUserAttributes(e),r);return n._Helpers.filterUserAttributes(i,t.userAttributeFilters)}return{getUserIdentities:function(){var i=function(e,t){var n={},r=e;for(var i in r)if(W(r,i)){var o=he(i);if(null!==o){var s=me.IdentityType.getIdentityName(o);Pr(t,s)&&(n[s]=r[i])}}return n}(n._Store.getUserIdentities(e),r);return{userIdentities:i=n._Helpers.filterUserIdentitiesForForwarders(i,t.userIdentityFilters)}},getMPID:function(){return e},getUserAttributesLists:function(e){var t=function(e,t){var n={};for(var r in e)W(e,r)&&!J(r)&&Array.isArray(e[r])&&wr(t,r)&&(n[r]=e[r].slice());return n}(i(),r);return n._Helpers.filterUserAttributes(t,e.userAttributeFilters)},getAllUserAttributes:i}}var Ar,Tr=[me.MessageType.PageEvent,me.MessageType.PageView,me.MessageType.Commerce];function Er(e,t){return!(!e||!e.length)&&b(e,t)}function kr(e,t,n){var r=n&&n.kitBlockingEnabled?n.createBlockedEvent(e):e;if(!r)return!1;if(function(e,t,n){if(!(Tr.includes(e)&&n.filteringEventAttributeValue&&n.filteringEventAttributeValue.eventAttributeName&&n.filteringEventAttributeValue.eventAttributeValue))return!1;var r=null;if(t)for(var i in t)if(t.hasOwnProperty(i)){var o=qn.hashAttributeConditionalForwarding(i);if(o===n.filteringEventAttributeValue.eventAttributeName){r={name:o,value:qn.hashAttributeConditionalForwarding(t[i])};break}}var s=null!==r&&r.value===n.filteringEventAttributeValue.eventAttributeValue;return!(!0===n.filteringEventAttributeValue.includeOnMatch?s:!s)}(r.EventDataType,r.EventAttributes,t))return!1;var i=r.EventCategory;return!function(e,t,n,r){return!(e!==me.MessageType.PageEvent||!Er(r.eventNameFilters,t)&&!Er(r.eventTypeFilters,n))||!(e!==me.MessageType.Commerce||!Er(r.eventTypeFilters,n))||!(e!==me.MessageType.PageView||!Er(r.screenNameFilters,t))}(r.EventDataType,qn.hashEventName(r.EventName,i),qn.hashEventType(i),t)}var Dr=r.IdentityMethods,Mr=Dr.Modify,Or=Dr.Identify,Fr=Dr.Login,Lr=Dr.Logout,Ur=((Ar={})[Or]="onIdentifyComplete",Ar[Fr]="onLoginComplete",Ar[Lr]="onLogoutComplete",Ar[Mr]="onModifyComplete",Ar);function Nr(e,t){var n=e,r={};for(var i in n)n.hasOwnProperty(i)&&Pr(t,i)&&(r[i]=n[i]);return r}function Rr(e,t){var n=this,r=this;this.forwarderStatsUploader=new Kn(e,t).initializeForwarderStatsUploader();var i="setUserAttribute",o="removeUserAttribute";this.initForwarders=function(n,i){var o=e.Identity.getCurrentUser();if(!e._Store.webviewBridgeEnabled&&e._Store.configuredForwarders){var s=Nr(n,t);e._Store.configuredForwarders.sort((function(e,t){return e.settings.PriorityValue=e.settings.PriorityValue||0,t.settings.PriorityValue=t.settings.PriorityValue||0,-1*(e.settings.PriorityValue-t.settings.PriorityValue)})),e._Store.activeForwarders=e._Store.configuredForwarders.filter((function(n){if(!e._Consent.isEnabledForUserConsent(n.filteringConsentRuleValues,o))return!1;if(!r.isEnabledForUserAttributes(n.filteringUserAttributeValue,o))return!1;if(!r.isEnabledForUnknownUser(n.excludeAnonymousUser,o))return!1;var a=e._Helpers.filterUserIdentities(s,n.userIdentityFilters),u=o?Cr(o.getMPID(),n,e,t).getAllUserAttributes():{};return n.initialized||(n.logger=e.Logger,n.init(n.settings,i,!1,null,u,a,e._Store.SDKConfig.appVersion,e._Store.SDKConfig.appName,e._Store.SDKConfig.customFlags,e._Store.clientId),n.initialized=!0),!0}))}},this.isEnabledForUserAttributes=function(t,n){if(!t||!e._Helpers.isObject(t)||!Object.keys(t).length)return!0;if(!n)return!1;var r=n.getAllUserAttributes();try{var i=!!(r&&e._Helpers.isObject(r)&&Object.keys(r).length>0)&&function(e,t){for(var n in e)if(W(e,n)){var r=qn.hashAttributeConditionalForwarding(n),i=qn.hashAttributeConditionalForwarding(e[n]);if(r===t.userAttributeName&&i===t.userAttributeValue)return!0}return!1}(r,t);return t.includeOnMatch===i}catch(e){return!0}},this.isEnabledForUnknownUser=function(e,t){return!!(t&&t.isLoggedIn()||!e)},this.applyToForwarders=function(t,n){e._Store.activeForwarders.length&&e._Store.activeForwarders.forEach((function(r){if(r[t])try{var i=r[t](n);i&&e.Logger.verbose(i)}catch(t){e.Logger.verbose(t)}}))},this.sendEventToForwarders=function(t){if(!e._Store.webviewBridgeEnabled&&e._Store.activeForwarders){var n=function(n){if(kr(t,n)){var r,i,o=re(!0,{},t);if(o.EventAttributes=function(e,t,n,r,i){if(!r)return r;var o;if(e===me.MessageType.PageEvent?o=i.attributeFilters:e===me.MessageType.PageView&&(o=i.screenAttributeFilters),!o)return r;var s={};for(var a in r)if(r.hasOwnProperty(a)){var u=qn.hashEventAttributeKey(t,n,a);b(o,u)||(s[a]=r[a])}return s}(t.EventDataType,t.EventCategory,t.EventName,o.EventAttributes,n),o.UserIdentities=(r=o.UserIdentities,i=n.userIdentityFilters,r&&r.length?r.filter((function(e){return!b(i,qn.hashUserIdentity(e.Type))})):r||[]),o.UserAttributes=qn.filterUserAttributes(o.UserAttributes,n.userAttributeFilters),n.process){e.Logger.verbose("Sending message to forwarder: "+n.name);var s=n.process(o);s&&e.Logger.verbose(s)}}};e._Store.activeForwarders.forEach((function(e){n(e)}))}},this.handleForwarderUserAttributes=function(n,r,s){t&&t.isAttributeKeyBlocked(r)||!e._Store.activeForwarders.length||e._Store.activeForwarders.forEach((function(t){if(t[n]&&!qn.isFilteredUserAttribute(r,t.userAttributeFilters))try{var a=void 0;n===i?a=t.setUserAttribute(r,s):n===o&&(a=t.removeUserAttribute(r)),a&&e.Logger.verbose(a)}catch(t){e.Logger.error(t)}}))},this.setForwarderUserIdentities=function(n){var r=Nr(n,t);e._Store.activeForwarders.forEach((function(t){var n=e._Helpers.filterUserIdentities(r,t.userIdentityFilters);t.setUserIdentity&&n.forEach((function(n){var r=t.setUserIdentity(n.Identity,n.Type);r&&e.Logger.verbose(r)}))}))},this.setForwarderOnUserIdentified=function(n){e._Store.activeForwarders.forEach((function(r){var i=Cr(n.getMPID(),r,e,t);if(r.onUserIdentified){var o=r.onUserIdentified(i);o&&e.Logger.verbose(o)}}))},this.setForwarderOnIdentityComplete=function(n,r){var i=Ur[r];i&&e._Store.activeForwarders.forEach((function(r){var o=r[i];if(o){var s=Cr(n.getMPID(),r,e,t),a=o.call(r,s,s.getUserIdentities());a&&e.Logger.verbose(a)}}))},this.getForwarderStatsQueue=function(){return e._Persistence.forwardingStatsBatches.forwardingStatsEventQueue},this.setForwarderStatsQueue=function(t){e._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=t},this.processForwarders=function(t,n){t?(this.processUIEnabledKits(t),this.processSideloadedKits(t),r.initForwarders(e._Store.SDKConfig.identifyRequest.userIdentities,n)):e.Logger.warning("No config was passed. Cannot process forwarders")},this.processUIEnabledKits=function(t){var n=this.returnKitConstructors();try{Array.isArray(t.kitConfigs)&&t.kitConfigs.length&&t.kitConfigs.forEach((function(e){r.configureUIEnabledKit(e,n)}))}catch(t){e.Logger.error("MP Kits not configured propertly. Kits may not be initialized. "+t)}},this.returnKitConstructors=function(){var t={};return z(e._Store.SDKConfig.kits)?z(e._preInit.forwarderConstructors)||e._preInit.forwarderConstructors.forEach((function(e){if(e.suffix){var n="".concat(e.name,"-").concat(e.suffix);t[n]=e}else t[e.name]=e})):t=e._Store.SDKConfig.kits,t},this.configureUIEnabledKit=function(t,n){var r=null,i=t;for(var o in n){var s=void 0;if(i.suffix&&(s="".concat(i.name,"-").concat(i.suffix)),!(o!==s&&o!==i.name||i.isDebug!==e._Store.SDKConfig.isDevelopmentMode&&i.isSandbox!==e._Store.SDKConfig.isDevelopmentMode)){r=this.returnConfiguredKit(n[o],i),e._Store.configuredForwarders.push(r);break}}},this.processSideloadedKits=function(t){try{if(Array.isArray(t.sideloadedKits)){var n={kits:{}},i=t.sideloadedKits;for(var o in i.forEach((function(e){try{e.kitInstance.register(n);var t=e.kitInstance.name;n.kits[t].filters=e.filterDictionary}catch(t){console.error("Error registering sideloaded kit "+e.kitInstance.name)}})),n.kits){var s=n.kits[o];r.configureSideloadedKit(s)}if(!z(n.kits)){var a=Object.keys(n.kits);e._Store.sideloadedKitsCount=a.length}}}catch(t){e.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. "+t)}},this.configureSideloadedKit=function(t){e._Store.configuredForwarders.push(this.returnConfiguredKit(t,t.filters))},this.returnConfiguredKit=function(e,t){void 0===t&&(t={});var n=new e.constructor;return n.id=t.moduleId,n.isSandbox=t.isDebug||t.isSandbox,n.hasSandbox="true"===t.hasDebugString,n.isVisible=t.isVisible||!0,n.settings=t.settings||{},n.eventNameFilters=t.eventNameFilters||[],n.eventTypeFilters=t.eventTypeFilters||[],n.attributeFilters=t.attributeFilters||[],n.screenNameFilters=t.screenNameFilters||[],n.screenAttributeFilters=t.screenAttributeFilters||[],n.userIdentityFilters=t.userIdentityFilters||[],n.userAttributeFilters=t.userAttributeFilters||[],n.filteringEventAttributeValue=t.filteringEventAttributeValue||{},n.filteringUserAttributeValue=t.filteringUserAttributeValue||{},n.eventSubscriptionId=t.eventSubscriptionId||null,n.filteringConsentRuleValues=t.filteringConsentRuleValues||{},n.excludeAnonymousUser=t.excludeAnonymousUser||!1,n},this.configurePixel=function(t){t.isDebug!==e._Store.SDKConfig.isDevelopmentMode&&t.isProduction===e._Store.SDKConfig.isDevelopmentMode||e._Store.pixelConfigurations.push(t)},this.processPixelConfigs=function(t){try{z(t.pixelConfigs)||t.pixelConfigs.forEach((function(e){r.configurePixel(e)}))}catch(t){e.Logger.error("Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. "+t)}},this.sendSingleForwardingStatsToServer=function(t){return g(n,void 0,void 0,(function(){var n,r,i,o;return v(this,(function(s){switch(s.label){case 0:return n={method:"post",body:JSON.stringify(t),headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"}},[4,this.forwarderStatsUploader.upload(n)];case 1:return r=s.sent(),i=202===r.status?"Successfully sent forwarding stats to mParticle Servers":"Issue with forwarding stats to mParticle Servers, received HTTP Code of "+r.statusText,null===(o=null==e?void 0:e.Logger)||void 0===o||o.verbose(i),[2]}}))}))}}var Vr=me.MessageType,xr=me.ApplicationTransitionType;function Hr(e){return e?e.map((function(e){return function(e){return{id:A(e.Sku),nm:A(e.Name),pr:C(e.Price),qt:C(e.Quantity),br:A(e.Brand),va:A(e.Variant),ca:A(e.Category),ps:C(e.Position),cc:A(e.CouponCode),tpa:C(e.TotalAmount),attrs:e.Attributes}}(e)})):[]}function Kr(e){var t=this;this.convertToConsentStateV2DTO=function(e){if(!e)return null;var t={},n=e.getGDPRConsentState();if(n){var r={};for(var i in t.gdpr=r,n)if(n.hasOwnProperty(i)){var o=n[i];t.gdpr[i]={},"boolean"==typeof o.Consented&&(r[i].c=o.Consented),"number"==typeof o.Timestamp&&(r[i].ts=o.Timestamp),"string"==typeof o.ConsentDocument&&(r[i].d=o.ConsentDocument),"string"==typeof o.Location&&(r[i].l=o.Location),"string"==typeof o.HardwareId&&(r[i].h=o.HardwareId)}}var s=e.getCCPAConsentState();return s&&(t.ccpa={data_sale_opt_out:{c:s.Consented,ts:s.Timestamp,d:s.ConsentDocument,l:s.Location,h:s.HardwareId}}),t},this.createEventObject=function(t,n){var i,o,s,a={},u={},c=t.messageType===me.MessageType.OptOut?!e._Store.isEnabled:null;if(e._Store.sessionId||t.messageType===me.MessageType.OptOut||e._Store.webviewBridgeEnabled){var d=p({},t.customFlags),l=e._Store.integrationAttributes;if(Qe(e._Helpers.getFeatureFlag)){e._IntegrationCapture.capture();var g=e._IntegrationCapture.getClickIdsAsCustomFlags();d=p(p({},g),d);var v=e._IntegrationCapture.getClickIdsAsIntegrationAttributes();l=p(p({},v),l)}return u=t.hasOwnProperty("toEventAPIObject")?t.toEventAPIObject():{EventName:t.name||String(t.messageType),EventCategory:t.eventType,EventAttributes:e._Helpers.sanitizeAttributes(t.data,t.name),ActiveTimeOnSite:null===(i=e._timeOnSiteTimer)||void 0===i?void 0:i.getTimeInForeground(),TotalTimeOnSite:null===(s=(o=e._Store).getTotalTimeOnSite)||void 0===s?void 0:s.call(o),PageUrl:rn()||null,SourceMessageId:t.sourceMessageId||e._Helpers.generateUniqueId(),EventDataType:t.messageType,CustomFlags:d,UserAttributeChanges:t.userAttributeChanges,UserIdentityChanges:t.userIdentityChanges},t.messageType!==me.MessageType.SessionEnd&&(e._Store.dateLastEventSent=new Date),a={Store:e._Store.serverSettings,SDKVersion:r.sdkVersion,SessionId:e._Store.sessionId,SessionStartDate:e._Store.sessionStartDate?e._Store.sessionStartDate.getTime():0,Debug:e._Store.SDKConfig.isDevelopmentMode,Location:e._Store.currentPosition,OptOut:c,ExpandedEventCount:0,AppVersion:e.getAppVersion(),AppName:e.getAppName(),Package:e._Store.SDKConfig.package,ClientGeneratedId:e._Store.clientId,DeviceId:e._Store.deviceId,IntegrationAttributes:l,CurrencyCode:e._Store.currencyCode,DataPlan:e._Store.SDKConfig.dataPlan?e._Store.SDKConfig.dataPlan:{}},u.EventDataType===Vr.AppStateTransition&&(u.IsFirstRun=e._Store.isFirstRun,u.LaunchReferral=rn()||null),u.CurrencyCode=e._Store.currencyCode,pn(n||e.Identity.getCurrentUser(),u),t.messageType===me.MessageType.SessionEnd&&(u.SessionLength=e._Store.dateLastEventSent.getTime()-e._Store.sessionStartDate.getTime(),u.currentSessionMPIDs=e._Store.currentSessionMPIDs,u.EventAttributes=e._Store.sessionAttributes,e._Store.currentSessionMPIDs=[],e._Store.sessionStartDate=null),a.Timestamp=e._Store.dateLastEventSent.getTime(),re({},u,a)}return null},this.convertEventToV2DTO=function(n){var r={n:n.EventName,et:n.EventCategory,ua:n.UserAttributes,ui:n.UserIdentities,ia:n.IntegrationAttributes,str:n.Store,attrs:n.EventAttributes,sdk:n.SDKVersion,sid:n.SessionId,sl:n.SessionLength,ssd:n.SessionStartDate,dt:n.EventDataType,dbg:n.Debug,ct:n.Timestamp,lc:n.Location,o:n.OptOut,eec:n.ExpandedEventCount,av:n.AppVersion,cgid:n.ClientGeneratedId,das:n.DeviceId,mpid:n.MPID,smpids:n.currentSessionMPIDs};n.DataPlan&&n.DataPlan.PlanId&&(r.dp_id=n.DataPlan.PlanId,n.DataPlan.PlanVersion&&(r.dp_v=n.DataPlan.PlanVersion));var i=t.convertToConsentStateV2DTO(n.ConsentState);return i&&(r.con=i),n.EventDataType===Vr.AppStateTransition&&(r.fr=n.IsFirstRun,r.iu=!1,r.at=xr.AppInit,r.lr=n.LaunchReferral,r.attrs=null),n.CustomFlags&&function(e,t){var n=[];for(var r in t.flags={},e.CustomFlags)n=[],e.CustomFlags.hasOwnProperty(r)&&(Array.isArray(e.CustomFlags[r])?e.CustomFlags[r].forEach((function(e){q(e)&&n.push(e.toString())})):q(e.CustomFlags[r])&&n.push(e.CustomFlags[r].toString()),n.length&&(t.flags[r]=n))}(n,r),n.EventDataType===Vr.Commerce?(r.cu=n.CurrencyCode,n.ProductAction?r.pd={an:n.ProductAction.ProductActionType,cs:e._Helpers.parseNumber(n.ProductAction.CheckoutStep),co:n.ProductAction.CheckoutOptions,pl:Hr(n.ProductAction.ProductList),ti:n.ProductAction.TransactionId,ta:n.ProductAction.Affiliation,tcc:n.ProductAction.CouponCode,tr:e._Helpers.parseNumber(n.ProductAction.TotalAmount),ts:e._Helpers.parseNumber(n.ProductAction.ShippingAmount),tt:e._Helpers.parseNumber(n.ProductAction.TaxAmount)}:n.PromotionAction?r.pm={an:n.PromotionAction.PromotionActionType,pl:n.PromotionAction.PromotionList.map((function(e){return{id:e.Id,nm:e.Name,cr:e.Creative,ps:e.Position?e.Position:0}}))}:n.ProductImpressions&&(r.pi=n.ProductImpressions.map((function(e){return{pil:e.ProductImpressionList,pl:Hr(e.ProductList)}})))):n.EventDataType===Vr.Profile&&(r.pet=n.ProfileMessageType),r}}function qr(e){this.startForwardingStatsTimer=function(){window.mParticle._forwardingStatsTimer=setInterval((function(){!function(){var t=e._Forwarders.getForwarderStatsQueue(),n=e._Persistence.forwardingStatsBatches.uploadsTable,r=Date.now();t.length&&(n[r]={uploading:!1,data:t},e._Forwarders.setForwarderStatsQueue([]));for(var i in n)!function(t){if(n.hasOwnProperty(t)&&!1===n[t].uploading){var r=function(){4===i.readyState&&(200===i.status||202===i.status?(e.Logger.verbose("Successfully sent "+i.statusText+" from server"),delete n[t]):"4"===i.status.toString()[0]?429!==i.status&&delete n[t]:n[t].uploading=!1)},i=e._Helpers.createXHR(r),o=n[t].data;n[t].uploading=!0,e._APIClient.sendBatchForwardingStatsToServer(o,i)}}(i)}()}),e._Store.SDKConfig.forwarderStatsTimeout)}}var Br=function(){function e(e,t,n){this.url="",this.logger=n,this.url="https://".concat(e).concat(t,"/audience"),this.userAudienceAPI=window.fetch?new dn(this.url):new ln(this.url)}return e.prototype.sendGetUserAudienceRequest=function(e,t){return g(this,void 0,void 0,(function(){var n,r,i,o,s,a;return v(this,(function(u){switch(u.label){case 0:this.logger.verbose("Fetching user audiences from server"),n={method:"GET",headers:{Accept:"*/*"}},r="".concat(this.url,"?mpid=").concat(e),u.label=1;case 1:return u.trys.push([1,6,,7]),[4,this.userAudienceAPI.upload(n,r)];case 2:return(i=u.sent()).status>=200&&i.status<300?(this.logger.verbose("User Audiences successfully received"),[4,i.json()]):[3,4];case 3:o=u.sent(),s={currentAudienceMemberships:null==o?void 0:o.audience_memberships};try{t(s)}catch(e){throw new Error("Error invoking callback on user audience response.")}return[3,5];case 4:throw 401===i.status?new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`"):403===i.status?new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`"):new Error("Uncaught HTTP Error ".concat(i.status,"."));case 5:return[3,7];case 6:return a=u.sent(),this.logger.error("Error retrieving audiences. ".concat(a)),[3,7];case 7:return[2]}}))}))},e}(),jr=function(e,t){return z(e)||e.splice(0,e.length).forEach((function(e){try{K(e)?e():Array.isArray(e)&&zr(e)}catch(e){t.error("Error processing ready queue item: "+ie(e))}})),[]},zr=function(e){var t=e.slice(),n=t.splice(0,1)[0];if("string"==typeof n&&0!==n.length)if("undefined"!=typeof window&&window.mParticle&&window.mParticle[t[0]])window.mParticle[n].apply(window.mParticle,t);else{var r=n.split(".");try{for(var i=window.mParticle,o=window.mParticle,s=0,a=r;s<a.length;s++){var u=a[s];o=i,i=i[u]}i.apply(o,t)}catch(e){throw new Error("Unable to compute proper mParticle function "+e)}}},Qr=r.Messages,Wr=r.HTTPCodes,Jr=r.FeatureFlags,Gr=r.IdentityMethods,$r=Qr.ErrorMessages,Yr=Jr.CacheIdentity,Xr=Gr.Identify,Zr=Gr.Modify,ei=Gr.Login,ti=Gr.Logout;function ni(e){var t=e._Helpers,n=t.getFeatureFlag,i=t.extend,s=this;this.idCache=null,this.audienceManager=null,this.IdentityRequest={preProcessIdentityRequest:function(t,n,r){e.Logger.verbose(Qr.InformationMessages.StartingLogEvent+": "+r);var i=e._Helpers.Validators.removeFalsyIdentityValues(t,e.Logger),o=(null==i?void 0:i.userIdentities)?p(p({},i),{userIdentities:Rn(i.userIdentities)}):i,s=e._Helpers.Validators.validateIdentities(o,r);if(!s.valid)return e.Logger.error("ERROR: "+s.error),{valid:!1,error:s.error};if(n&&!e._Helpers.Validators.isFunction(n)){var a="The optional callback must be a function. You tried entering a(n) "+c(n);return e.Logger.error(a),{valid:!1,error:a}}return{valid:!0,cleanedIdentities:o}},createIdentityRequest:function(t,n,r,i,o,s,a){return{client_sdk:{platform:n,sdk_vendor:r,sdk_version:i},context:s,environment:e._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:e._Helpers.generateUniqueId(),request_timestamp_ms:(new Date).getTime(),previous_mpid:a||null,known_identities:Mn(t,o)}},createModifyIdentityRequest:function(t,n,r,i,o,s){return{client_sdk:{platform:r,sdk_vendor:i,sdk_version:o},context:s,environment:e._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:e._Helpers.generateUniqueId(),request_timestamp_ms:(new Date).getTime(),identity_changes:this.createIdentityChanges(t,n)}},createIdentityChanges:function(e,t){var n=[];if(t&&P(t)&&e&&P(e))for(var r in t)n.push({old_value:e[r]||null,new_value:t[r],identity_type:r});return n},combineUserIdentities:function(e,t){var n={},r=i({},e,t);for(var o in r){var s=me.IdentityType.getIdentityType(o);!1!==s&&s>=0&&(n[me.IdentityType.getIdentityType(o)]=r[o])}return n},createAliasNetworkRequest:function(t){return{request_id:e._Helpers.generateUniqueId(),request_type:"alias",environment:e._Store.SDKConfig.isDevelopmentMode?"development":"production",api_key:e._Store.devToken,data:{destination_mpid:t.destinationMpid,source_mpid:t.sourceMpid,start_unixtime_ms:t.startTime,end_unixtime_ms:t.endTime,scope:t.scope,device_application_stamp:e._Store.deviceId}}},convertAliasToNative:function(e){return{DestinationMpid:e.destinationMpid,SourceMpid:e.sourceMpid,StartUnixtimeMs:e.startTime,EndUnixtimeMs:e.endTime,Scope:e.scope}},convertToNative:function(e){var t=[];if(null==e?void 0:e.userIdentities){for(var n in e.userIdentities)e.userIdentities.hasOwnProperty(n)&&t.push({Type:me.IdentityType.getIdentityType(n),Identity:e.userIdentities[n]});return{UserIdentities:t}}}},this.IdentityAPI={HTTPCodes:Wr,identify:function(t,n){var i,o=e.Identity.getCurrentUser(),a=e._Identity.IdentityRequest.preProcessIdentityRequest(t,n,Xr);if(o&&(i=o.getMPID()),a.valid){var u=e._Identity.IdentityRequest.createIdentityRequest(a.cleanedIdentities,r.platform,r.sdkVendor,r.sdkVersion,e._Store.deviceId,e._Store.context,i);if(e._Helpers.getFeatureFlag(r.FeatureFlags.CacheIdentity))if(Fn(u.known_identities,s.idCache,s.parseIdentityResponse,i,n,t,Xr))return;e._Helpers.canLog()?e._Store.webviewBridgeEnabled?(e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.Identify,JSON.stringify(e._Identity.IdentityRequest.convertToNative(t))),e._Helpers.invokeCallback(n,Wr.nativeIdentityRequest,"Identify request sent to native sdk")):e._IdentityAPIClient.sendIdentityRequest(u,Xr,n,t,s.parseIdentityResponse,i,u.known_identities):(e._Helpers.invokeCallback(n,Wr.loggingDisabledOrMissingAPIKey,Qr.InformationMessages.AbandonLogEvent),e.Logger.verbose(Qr.InformationMessages.AbandonLogEvent))}else e._Helpers.invokeCallback(n,Wr.validationIssue,a.error),e.Logger.verbose(a)},logout:function(t,n){var i,o=e.Identity.getCurrentUser(),a=e._Identity.IdentityRequest.preProcessIdentityRequest(t,n,ti);if(o&&(i=o.getMPID()),a.valid){var u,c=e._Identity.IdentityRequest.createIdentityRequest(a.cleanedIdentities,r.platform,r.sdkVendor,r.sdkVersion,e._Store.deviceId,e._Store.context,i);e._Helpers.canLog()?e._Store.webviewBridgeEnabled?(e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.Logout,JSON.stringify(e._Identity.IdentityRequest.convertToNative(t))),e._Helpers.invokeCallback(n,Wr.nativeIdentityRequest,"Logout request sent to native sdk")):(e._IdentityAPIClient.sendIdentityRequest(c,ti,n,t,s.parseIdentityResponse,i),(u=e._ServerModel.createEventObject({messageType:me.MessageType.Profile})).ProfileMessageType=me.ProfileMessageType.Logout,e._Store.activeForwarders.length&&e._Store.activeForwarders.forEach((function(e){var t=e;t.logOut&&t.logOut(u)}))):(e._Helpers.invokeCallback(n,Wr.loggingDisabledOrMissingAPIKey,Qr.InformationMessages.AbandonLogEvent),e.Logger.verbose(Qr.InformationMessages.AbandonLogEvent))}else e._Helpers.invokeCallback(n,Wr.validationIssue,a.error),e.Logger.verbose(a)},login:function(t,n){var i,o=e.Identity.getCurrentUser(),a=e._Identity.IdentityRequest.preProcessIdentityRequest(t,n,ei);if(o&&(i=o.getMPID()),a.valid){var u=e._Identity.IdentityRequest.createIdentityRequest(a.cleanedIdentities,r.platform,r.sdkVendor,r.sdkVersion,e._Store.deviceId,e._Store.context,i);if(e._Helpers.getFeatureFlag(r.FeatureFlags.CacheIdentity))if(Fn(u.known_identities,s.idCache,s.parseIdentityResponse,i,n,t,ei))return;e._Helpers.canLog()?e._Store.webviewBridgeEnabled?(e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.Login,JSON.stringify(e._Identity.IdentityRequest.convertToNative(t))),e._Helpers.invokeCallback(n,Wr.nativeIdentityRequest,"Login request sent to native sdk")):e._IdentityAPIClient.sendIdentityRequest(u,ei,n,t,s.parseIdentityResponse,i,u.known_identities):(e._Helpers.invokeCallback(n,Wr.loggingDisabledOrMissingAPIKey,Qr.InformationMessages.AbandonLogEvent),e.Logger.verbose(Qr.InformationMessages.AbandonLogEvent))}else e._Helpers.invokeCallback(n,Wr.validationIssue,a.error),e.Logger.verbose(a)},modify:function(t,n){var i,o=e.Identity.getCurrentUser(),a=e._Identity.IdentityRequest.preProcessIdentityRequest(t,n,Zr);if(o&&(i=o.getMPID()),a.valid){var u=(null==t?void 0:t.userIdentities)?a.cleanedIdentities.userIdentities:{},c=e._Identity.IdentityRequest.createModifyIdentityRequest(o?o.getUserIdentities().userIdentities:{},u,r.platform,r.sdkVendor,r.sdkVersion,e._Store.context);e._Helpers.canLog()?e._Store.webviewBridgeEnabled?(e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.Modify,JSON.stringify(e._Identity.IdentityRequest.convertToNative(t))),e._Helpers.invokeCallback(n,Wr.nativeIdentityRequest,"Modify request sent to native sdk")):e._IdentityAPIClient.sendIdentityRequest(c,Zr,n,t,s.parseIdentityResponse,i):(e._Helpers.invokeCallback(n,Wr.loggingDisabledOrMissingAPIKey,Qr.InformationMessages.AbandonLogEvent),e.Logger.verbose(Qr.InformationMessages.AbandonLogEvent))}else e._Helpers.invokeCallback(n,Wr.validationIssue,a.error),e.Logger.verbose(a)},getCurrentUser:function(){var t;return e._Store?(t=e._Store.mpid)?(t=e._Store.mpid.slice(),s.mParticleUser(t,e._Store.isLoggedIn)):e._Store.webviewBridgeEnabled?s.mParticleUser():null:null},getUser:function(t){var n=e._Persistence.getPersistence();return n&&n[t]&&!r.SDKv2NonMPIDCookieKeys.hasOwnProperty(t)?s.mParticleUser(t):null},getUsers:function(){var t=e._Persistence.getPersistence(),n=[];if(t)for(var i in t)r.SDKv2NonMPIDCookieKeys.hasOwnProperty(i)||n.push(s.mParticleUser(i));return n.sort((function(e,t){return(e.getLastSeenTime()||0)>(t.getLastSeenTime()||0)?-1:1})),n},aliasUsers:function(t,n){var i;if(t.destinationMpid&&t.sourceMpid||(i=Qr.ValidationMessages.AliasMissingMpid),t.destinationMpid===t.sourceMpid&&(i=Qr.ValidationMessages.AliasNonUniqueMpid),t.startTime&&t.endTime||(i=Qr.ValidationMessages.AliasMissingTime),t.startTime>t.endTime&&(i=Qr.ValidationMessages.AliasStartBeforeEndTime),i)return e.Logger.warning(i),void e._Helpers.invokeAliasCallback(n,Wr.validationIssue,i);if(e._Helpers.canLog())if(e._Store.webviewBridgeEnabled)e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.Alias,JSON.stringify(e._Identity.IdentityRequest.convertAliasToNative(t))),e._Helpers.invokeAliasCallback(n,Wr.nativeIdentityRequest,"Alias request sent to native sdk");else{e.Logger.verbose(Qr.InformationMessages.StartingAliasRequest+": "+t.sourceMpid+" -> "+t.destinationMpid);var o=e._Identity.IdentityRequest.createAliasNetworkRequest(t);e._IdentityAPIClient.sendAliasRequest(o,n)}else e._Helpers.invokeAliasCallback(n,Wr.loggingDisabledOrMissingAPIKey,Qr.InformationMessages.AbandonAliasUsers),e.Logger.verbose(Qr.InformationMessages.AbandonAliasUsers)},search:function(t,n,r){Hn(e,t,n,r)},createAliasRequest:function(t,n,r){try{if(!n||!t)return e.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var i=t.getFirstSeenTime();i||e.Identity.getUsers().forEach((function(e){e.getFirstSeenTime()&&(!i||e.getFirstSeenTime()<i)&&(i=e.getFirstSeenTime())}));var o=(new Date).getTime()-24*e._Store.SDKConfig.aliasMaxWindow*60*60*1e3,s=t.getLastSeenTime()||(new Date).getTime();return i<o&&s<(i=o)&&e.Logger.warning("Source User has not been seen in the last "+e._Store.SDKConfig.maxAliasWindow+" days, Alias Request will likely fail"),{destinationMpid:n.getMPID(),sourceMpid:t.getMPID(),startTime:i,endTime:s,scope:r||"device"}}catch(t){return e.Logger.error("There was a problem with creating an alias request: "+t),null}}},this.mParticleUser=function(t,n){return{getUserIdentities:function(){var n={},r=e._Store.getUserIdentities(t);for(var i in r)if(W(r,i)){var o=he(i);null!==o&&(n[me.IdentityType.getIdentityName(o)]=r[i])}return{userIdentities:n}},getMPID:function(){return t},setUserTag:function(t){e._Helpers.Validators.isValidKeyValue(t)?this.setUserAttribute(t,null):e.Logger.error(Qr.ErrorMessages.BadKey)},removeUserTag:function(t){e._Helpers.Validators.isValidKeyValue(t)?this.removeUserAttribute(t):e.Logger.error(Qr.ErrorMessages.BadKey)},setUserAttribute:function(n,i){if(e._SessionManager.resetSessionTimer(),e._Helpers.canLog()){if(!e._Helpers.Validators.isValidAttributeValue(i))return void e.Logger.error(Qr.ErrorMessages.BadAttribute);if(!e._Helpers.Validators.isValidKeyValue(n))return void e.Logger.error(Qr.ErrorMessages.BadKey);if(e._Store.webviewBridgeEnabled)e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:n,value:i}));else{var o=this.getAllUserAttributes(),a=void 0,u=void 0,c=e._Helpers.findKeyInObject(o,n);c?(u=!1,a=o[c],delete o[c]):u=!0,o[n]=i,e._Store.setUserAttributes(t,o),s.sendUserAttributeChangeEvent(n,i,a,u,!1,this),e._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,e._APIClient.prepareForwardingStats),e._Forwarders.handleForwarderUserAttributes("setUserAttribute",n,i)}}},setUserAttributes:function(t){if(e._SessionManager.resetSessionTimer(),P(t)){if(e._Helpers.canLog())for(var n in t)t.hasOwnProperty(n)&&this.setUserAttribute(n,t[n])}else e.Logger.error("Must pass an object into setUserAttributes. You passed a "+c(t))},removeUserAttribute:function(n){var i,o;if(e._SessionManager.resetSessionTimer(),e._Helpers.Validators.isValidKeyValue(n))if(e._Store.webviewBridgeEnabled)e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:n,value:null}));else{i=e._Persistence.getPersistence(),o=this.getAllUserAttributes();var a=e._Helpers.findKeyInObject(o,n);a&&(n=a);var u=o[n]?o[n].toString():null;delete o[n],i&&P(i[t])&&(i[t].ua=o,e._Persistence.savePersistence(i)),s.sendUserAttributeChangeEvent(n,null,u,!1,!0,this),e._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,e._APIClient.prepareForwardingStats),e._Forwarders.handleForwarderUserAttributes("removeUserAttribute",n,null)}else e.Logger.error(Qr.ErrorMessages.BadKey)},setUserAttributeList:function(n,i){if(e._SessionManager.resetSessionTimer(),e._Helpers.Validators.isValidKeyValue(n))if(Array.isArray(i)){var o=i.slice();if(e._Store.webviewBridgeEnabled)e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.SetUserAttributeList,JSON.stringify({key:n,value:o}));else{var a=this.getAllUserAttributes(),u=void 0,d=void 0,l=void 0,p=e._Helpers.findKeyInObject(a,n);if(p?(d=!1,u=a[p],delete a[p]):d=!0,a[n]=o,e._Store.setUserAttributes(t,a),u&&Array.isArray(u)){if(i.length!==u.length)l=!0;else for(var g=0;g<i.length;g++)if(u[g]!==i[g]){l=!0;break}}else l=!0;l&&s.sendUserAttributeChangeEvent(n,i,u,d,!1,this),e._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,e._APIClient.prepareForwardingStats),e._Forwarders.handleForwarderUserAttributes("setUserAttribute",n,o)}}else e.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a "+c(i));else e.Logger.error(Qr.ErrorMessages.BadKey)},removeAllUserAttributes:function(){var t;if(e._SessionManager.resetSessionTimer(),e._Store.webviewBridgeEnabled)e._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.RemoveAllUserAttributes);else if(t=this.getAllUserAttributes(),e._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities().userIdentities,e._APIClient.prepareForwardingStats),t)for(var n in t)W(t,n)&&e._Forwarders.handleForwarderUserAttributes("removeUserAttribute",n,null),this.removeUserAttribute(n)},getUserAttributesLists:function(){var e,t={};for(var n in e=this.getAllUserAttributes())W(e,n)&&!J(n)&&Array.isArray(e[n])&&(t[n]=e[n].slice());return t},getAllUserAttributes:function(){var n={},r=(0,e._Store.getUserAttributes)(t);if(r)for(var i in r)if(W(r,i)&&!J(i)){var o=r[i];Array.isArray(o)?n[i]=o.slice():n[i]=o}return n},getConsentState:function(){return e._Store.getConsentState(t)},setConsentState:function(n){e._Store.setConsentState(t,n),e._Forwarders.initForwarders(this.getUserIdentities().userIdentities,e._APIClient.prepareForwardingStats),e._CookieSyncManager.attemptCookieSync(this.getMPID())},isLoggedIn:function(){return n},getLastSeenTime:function(){return e._Persistence.getLastSeenTime(t)},getFirstSeenTime:function(){return e._Persistence.getFirstSeenTime(t)},getUserAudiences:function(n){e._Helpers.getFeatureFlag(Jr.AudienceAPI)?(null===s.audienceManager&&(s.audienceManager=new Br(e._Store.SDKConfig.userAudienceUrl,e._Store.devToken,e.Logger)),s.audienceManager.sendGetUserAudienceRequest(t,n)):e.Logger.error($r.AudienceAPINotEnabled)}}},this.parseIdentityResponse=function(t,r,i,a,u,c,d){var l,p,g,v,h,f,m=e.Identity.getUser(r),y=m?m.getMPID():null,b=m?m.getUserIdentities().userIdentities:{},S={};e._Store.identityCallInFlight=!1;try{if(e.Logger.verbose('Parsing "'+u+'" identity response from server'),h=null!==(l=t.responseText)&&void 0!==l?l:null,e._Store.isLoggedIn=(null==h?void 0:h.is_logged_in)||!1,function(e,t){return!e||e.getMPID()&&t.mpid&&t.mpid!==e.getMPID()}(m,h)&&(e._Store.mpid=h.mpid,m&&e._Persistence.setLastSeenTime(r),v=!e._Persistence.getFirstSeenTime(h.mpid),e._Persistence.setFirstSeenTime(h.mpid)),t.status===o){n(Yr)&&Tn(u,c,s.idCache,t,d);var _=s.IdentityAPI.getUser(h.mpid),w=_?_.getUserIdentities().userIdentities:{};u===Zr?(S=e._Identity.IdentityRequest.combineUserIdentities(b,a.userIdentities),e._Store.setUserIdentities(r,S)):(u===Xr&&m&&h.mpid===y&&e._Persistence.setFirstSeenTime(h.mpid),e._Store.addMpidToSessionHistory(h.mpid,r),e._CookieSyncManager.attemptCookieSync(h.mpid,v),e._Persistence.swapCurrentUser(r,h.mpid,e._Store.currentSessionMPIDs),a&&!z(a.userIdentities)&&(S=s.IdentityRequest.combineUserIdentities(w,a.userIdentities)),e._Store.setUserIdentities(h.mpid,S),e._Persistence.update(),e._Store.syncPersistenceData(),e._Store.context=h.context||e._Store.context),function(e,t,n,r,i){if(n&&n.onUserAlias&&K(n.onUserAlias))try{tr({methodName:"onUserAlias",warningMessage:I("onUserAlias")},r,i),n.onUserAlias(e,t)}catch(e){r.error("There was an error with your onUserAlias function - "+e)}}(m,f=e.Identity.getCurrentUser(),a,e.Logger,e._ErrorReportingDispatcher);var P=e._Persistence.getPersistence();f&&(e._Persistence.storeDataInMemory(P,f.getMPID()),s.reinitForwardersOnUserChange(m,f),s.setForwarderCallbacks(f,u));var C=ue.getNewIdentitiesByName(S),A=u===Zr?b:w;null===(p=e._CookieConsentManager)||void 0===p||p.syncNoTargetingAttribute(f),s.sendUserIdentityChangeEvent(C,u,h.mpid,A)}if(i){var T=0===t.status?Wr.noHttpCoverage:t.status;e._Helpers.invokeCallback(i,T,h||null,f,r)}else h&&!z(h.errors)&&e.Logger.error("Received HTTP response code of "+t.status+" - "+h.errors[0].message);e.Logger.verbose("Successfully parsed Identity Response"),null===(g=e._APIClient)||void 0===g||g.processQueuedEvents()}catch(n){i&&e._Helpers.invokeCallback(i,t.status,h||null),e.Logger.error("Error parsing JSON response from Identity server: "+n)}e._Store.isInitialized=!0,e._RoktManager.onIdentityComplete(),e._preInit.readyQueue=jr(e._preInit.readyQueue,e.Logger)},this.sendUserIdentityChangeEvent=function(t,n,r,i){var o;if(r||n===Zr){var a=this.IdentityAPI.getUser(r);for(var u in t)if(i[u]!==t[u]){var c=!i[u],d=s.createUserIdentityChange(u,t[u],i[u],c,a);null===(o=e._APIClient)||void 0===o||o.sendEventToServer(d)}}},this.createUserIdentityChange=function(t,n,r,i,o){return e._ServerModel.createEventObject({messageType:me.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:t,Identity:n,CreatedThisBatch:i},Old:{IdentityType:t,Identity:r,CreatedThisBatch:!1}},userInMemory:o})},this.sendUserAttributeChangeEvent=function(t,n,r,i,o,a){var u,c=s.createUserAttributeChange(t,n,r,i,o,a);c&&(null===(u=e._APIClient)||void 0===u||u.sendEventToServer(c))},this.createUserAttributeChange=function(t,n,r,i,o,s){var a;return void 0===r&&(r=null),n!==r&&(a=e._ServerModel.createEventObject({messageType:me.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:t,New:n,Old:r,Deleted:o,IsNewAttribute:i}},s)),a},this.reinitForwardersOnUserChange=function(t,n){var r;(function(e,t){return!e||t.getMPID()!==e.getMPID()||e.isLoggedIn()!==t.isLoggedIn()})(t,n)&&(null===(r=e._Forwarders)||void 0===r||r.initForwarders(n.getUserIdentities().userIdentities,e._APIClient.prepareForwardingStats))},this.setForwarderCallbacks=function(t,n){var r,i,o;null===(r=e._Forwarders)||void 0===r||r.setForwarderUserIdentities(t.getUserIdentities().userIdentities),null===(i=e._Forwarders)||void 0===i||i.setForwarderOnIdentityComplete(t,n),null===(o=e._Forwarders)||void 0===o||o.setForwarderOnUserIdentified(t)}}var ri=r.CCPAPurpose;function ii(e){var t=this;function n(e){return P(e)?t.createPrivacyConsent(e.c,e.ts,e.d,e.l,e.h):null}this.isEnabledForUserConsent=function(e,t){if(!e||!e.values||!e.values.length)return!0;if(!t)return!1;var n,r={},i=t.getConsentState();if(i){var o=i.getGDPRConsentState();if(o)for(var s in o)o.hasOwnProperty(s)&&(n=qn.hashConsentPurposeConditionalForwarding("1",s),r[n]=o[s].Consented);var a=i.getCCPAConsentState();a&&(n=qn.hashConsentPurposeConditionalForwarding("2",ri),r[n]=a.Consented)}var u=e.values.some((function(e){var t=e.consentPurpose,n=e.hasConsented;return!!r.hasOwnProperty(t)&&r[t]===n}));return e.includeOnMatch===u},this.createPrivacyConsent=function(t,n,r,i,o){if("boolean"!=typeof t)return e.Logger.error("Consented boolean is required when constructing a Consent object."),null;var s=n instanceof Date;return s&&(n=n.getTime()),(n||s)&&("number"!=typeof n&&"string"!=typeof n||isNaN(n))?(e.Logger.error("Timestamp must be a valid number when constructing a Consent object."),null):r&&"string"!=typeof r?(e.Logger.error("Document must be a valid string when constructing a Consent object."),null):i&&"string"!=typeof i?(e.Logger.error("Location must be a valid string when constructing a Consent object."),null):o&&"string"!=typeof o?(e.Logger.error("Hardware ID must be a valid string when constructing a Consent object."),null):{Consented:t,Timestamp:n||Date.now(),ConsentDocument:r,Location:i,HardwareId:o}},this.ConsentSerialization={toMinifiedJsonObject:function(e){var t,n={};if(e){var r=e.getGDPRConsentState();if(r)for(var i in n.gdpr={},r)if(r.hasOwnProperty(i)){var o=r[i];n.gdpr[i]={},"boolean"==typeof o.Consented&&(n.gdpr[i].c=o.Consented),"number"==typeof o.Timestamp&&(n.gdpr[i].ts=o.Timestamp),"string"==typeof o.ConsentDocument&&(n.gdpr[i].d=o.ConsentDocument),"string"==typeof o.Location&&(n.gdpr[i].l=o.Location),"string"==typeof o.HardwareId&&(n.gdpr[i].h=o.HardwareId)}var s=e.getCCPAConsentState();s&&(n.ccpa=((t={})[ri]={},t),"boolean"==typeof s.Consented&&(n.ccpa[ri].c=s.Consented),"number"==typeof s.Timestamp&&(n.ccpa[ri].ts=s.Timestamp),"string"==typeof s.ConsentDocument&&(n.ccpa[ri].d=s.ConsentDocument),"string"==typeof s.Location&&(n.ccpa[ri].l=s.Location),"string"==typeof s.HardwareId&&(n.ccpa[ri].h=s.HardwareId))}return n},fromMinifiedJsonObject:function(e){var r=t.createConsentState();if(!P(e))return r;if(P(e.gdpr))for(var i in e.gdpr)W(e.gdpr,i)&&r.addGDPRConsentState(i,n(e.gdpr[i]));return P(e.ccpa)&&W(e.ccpa,ri)&&r.setCCPAConsentState(n(e.ccpa[ri])),r}},this.createConsentState=function(n){var r={},i={};if(n){var o=t.createConsentState();return o.setGDPRConsentState(n.getGDPRConsentState()),o.setCCPAConsentState(n.getCCPAConsentState()),o}function s(e){if("string"!=typeof e)return null;var t=e.trim();return t.length?t.toLowerCase():null}return{setGDPRConsentState:function(e){if(e){if(P(e))for(var t in r={},e)e.hasOwnProperty(t)&&this.addGDPRConsentState(t,e[t])}else r={};return this},addGDPRConsentState:function(n,i){var o=s(n);if(!o)return e.Logger.error("Purpose must be a string."),this;if(!P(i))return e.Logger.error("Invoked with a bad or empty consent object."),this;var a=t.createPrivacyConsent(i.Consented,i.Timestamp,i.ConsentDocument,i.Location,i.HardwareId);return a&&(r[o]=a),this},setCCPAConsentState:function(n){if(!P(n))return e.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var r=t.createPrivacyConsent(n.Consented,n.Timestamp,n.ConsentDocument,n.Location,n.HardwareId);return r&&(i[ri]=r),this},getCCPAConsentState:function(){return i[ri]},getGDPRConsentState:function(){return Object.assign({},r)},removeGDPRConsentState:function(e){var t=s(e);return t?(delete r[t],this):this},removeCCPAConsentState:function(){return delete i[ri],this}}}}var oi={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},si=function(e){return e},ai=function(e){return p(p({},e),{UserAttributes:{}})},ui=function(e){return p(p({},e),{UserIdentities:[]})},ci=function(){function e(e,t){var n,r,i,o,s,a,u,c,d,l,p,g,v,h,f,m=this;if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,!e||e.document){this.kitBlockingEnabled=!0,this.mpInstance=t,this.blockEvents=null===(i=null===(r=null===(n=null==e?void 0:e.document)||void 0===n?void 0:n.dtpn)||void 0===r?void 0:r.blok)||void 0===i?void 0:i.ev,this.blockEventAttributes=null===(a=null===(s=null===(o=null==e?void 0:e.document)||void 0===o?void 0:o.dtpn)||void 0===s?void 0:s.blok)||void 0===a?void 0:a.ea,this.blockUserAttributes=null===(d=null===(c=null===(u=null==e?void 0:e.document)||void 0===u?void 0:u.dtpn)||void 0===c?void 0:c.blok)||void 0===d?void 0:d.ua,this.blockUserIdentities=null===(g=null===(p=null===(l=null==e?void 0:e.document)||void 0===l?void 0:l.dtpn)||void 0===p?void 0:p.blok)||void 0===g?void 0:g.id;var y=null===(f=null===(h=null===(v=null==e?void 0:e.document)||void 0===v?void 0:v.dtpn)||void 0===h?void 0:h.vers)||void 0===f?void 0:f.version_document,b=null==y?void 0:y.data_points;if(y)try{(null==b?void 0:b.length)>0&&b.forEach((function(e){return m.addToMatchLookups(e)}))}catch(e){this.mpInstance.Logger.error("There was an issue with the data plan: "+e)}}else this.kitBlockingEnabled=!1}return e.prototype.addToMatchLookups=function(e){var t,n,r;if(e.match&&e.validator){var i=this.generateMatchKey(e.match),o=this.getPlannedProperties(e.match.type,e.validator);this.dataPlanMatchLookups[i]=o,(null===(t=null==e?void 0:e.match)||void 0===t?void 0:t.type)!==oi.ProductImpression&&(null===(n=null==e?void 0:e.match)||void 0===n?void 0:n.type)!==oi.ProductAction&&(null===(r=null==e?void 0:e.match)||void 0===r?void 0:r.type)!==oi.PromotionAction||(i=this.generateProductAttributeMatchKey(e.match),o=this.getProductProperties(e.match.type,e.validator),this.dataPlanMatchLookups[i]=o)}else this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(e))},e.prototype.generateMatchKey=function(e){var t=e.criteria||"";switch(e.type){case oi.CustomEvent:var n=t;return[oi.CustomEvent,n.custom_event_type,n.event_name].join(":");case oi.ScreenView:var r=t;return[oi.ScreenView,"",r.screen_name].join(":");case oi.ProductAction:var i=t;return[e.type,i.action].join(":");case oi.PromotionAction:var o=t;return[e.type,o.action].join(":");case oi.ProductImpression:var s=t;return[e.type,s.action].join(":");case oi.UserIdentities:case oi.UserAttributes:return[e.type].join(":");default:return null}},e.prototype.generateProductAttributeMatchKey=function(e){var t=e.criteria||"";switch(e.type){case oi.ProductAction:var n=t;return[e.type,n.action,"ProductAttributes"].join(":");case oi.PromotionAction:var r=t;return[e.type,r.action,"ProductAttributes"].join(":");case oi.ProductImpression:return[e.type,"ProductAttributes"].join(":");default:return null}},e.prototype.getPlannedProperties=function(e,t){var n,r,i,o,s,a,u,c,d,l;switch(e){case oi.CustomEvent:case oi.ScreenView:case oi.ProductAction:case oi.PromotionAction:case oi.ProductImpression:if(d=null===(o=null===(i=null===(r=null===(n=null==t?void 0:t.definition)||void 0===n?void 0:n.properties)||void 0===r?void 0:r.data)||void 0===i?void 0:i.properties)||void 0===o?void 0:o.custom_attributes){if(!0===d.additionalProperties||void 0===d.additionalProperties)return!0;for(var p={},g=0,v=Object.keys(d.properties);g<v.length;g++){p[v[g]]=!0}return p}return!1!==(null===(u=null===(a=null===(s=null==t?void 0:t.definition)||void 0===s?void 0:s.properties)||void 0===a?void 0:a.data)||void 0===u?void 0:u.additionalProperties)||{};case oi.UserAttributes:case oi.UserIdentities:if(!0===(l=null===(c=null==t?void 0:t.definition)||void 0===c?void 0:c.additionalProperties)||void 0===l)return!0;p={};for(var h=t.definition.properties,f=0,m=Object.keys(h);f<m.length;f++){p[m[f]]=!0}return p;default:return null}},e.prototype.getProductProperties=function(e,t){var n,r,i,o,s,a,u,c,d,l,p,g,v,h,f,m,y,b,S,I;switch(e){case oi.ProductImpression:if(!1===(null==(I=null===(l=null===(d=null===(c=null===(u=null===(a=null===(s=null===(o=null===(i=null===(r=null===(n=null==t?void 0:t.definition)||void 0===n?void 0:n.properties)||void 0===r?void 0:r.data)||void 0===i?void 0:i.properties)||void 0===o?void 0:o.product_impressions)||void 0===s?void 0:s.items)||void 0===a?void 0:a.properties)||void 0===u?void 0:u.products)||void 0===c?void 0:c.items)||void 0===d?void 0:d.properties)||void 0===l?void 0:l.custom_attributes)?void 0:I.additionalProperties)){for(var _={},w=0,P=Object.keys(null==I?void 0:I.properties);w<P.length;w++){_[P[w]]=!0}return _}return!0;case oi.ProductAction:case oi.PromotionAction:if((I=null===(S=null===(b=null===(y=null===(m=null===(f=null===(h=null===(v=null===(g=null===(p=null==t?void 0:t.definition)||void 0===p?void 0:p.properties)||void 0===g?void 0:g.data)||void 0===v?void 0:v.properties)||void 0===h?void 0:h.product_action)||void 0===f?void 0:f.properties)||void 0===m?void 0:m.products)||void 0===y?void 0:y.items)||void 0===b?void 0:b.properties)||void 0===S?void 0:S.custom_attributes)&&!1===I.additionalProperties){_={};for(var C=0,A=Object.keys(null==I?void 0:I.properties);C<A.length;C++){_[A[C]]=!0}return _}return!0;default:return null}},e.prototype.getMatchKey=function(e){switch(e.event_type){case He.EventTypeEnum.screenView:var t=e;return t.data?["screen_view","",t.data.screen_name].join(":"):null;case He.EventTypeEnum.commerceEvent:var n=e,r=[];if(n&&n.data){var i=n.data,o=i.product_action,s=i.product_impressions,a=i.promotion_action;o?(r.push(oi.ProductAction),r.push(o.action)):a?(r.push(oi.PromotionAction),r.push(a.action)):s&&r.push(oi.ProductImpression)}return r.join(":");case He.EventTypeEnum.customEvent:var u=e;return u.data?["custom_event",u.data.custom_event_type,u.data.event_name].join(":"):null;default:return null}},e.prototype.getProductAttributeMatchKey=function(e){if(e.event_type===He.EventTypeEnum.commerceEvent){var t=[],n=e.data,r=n.product_action,i=n.product_impressions,o=n.promotion_action;return r?(t.push(oi.ProductAction),t.push(r.action),t.push("ProductAttributes")):o?(t.push(oi.PromotionAction),t.push(o.action),t.push("ProductAttributes")):i&&(t.push(oi.ProductImpression),t.push("ProductAttributes")),t.join(":")}return null},e.prototype.createBlockedEvent=function(e){return e&&(e=this.applyBlockingStep("the event and its attributes",this.transformEventAndEventAttributes,e,si)),e&&e.EventDataType===me.MessageType.Commerce&&(e=this.applyBlockingStep("product attributes",this.transformProductAttributes,e,si)),e&&(e=this.applyBlockingStep("user attributes",this.transformUserAttributes,e,ai),e=this.applyBlockingStep("user identities",this.transformUserIdentities,e,ui)),e},e.prototype.applyBlockingStep=function(e,t,n,r){try{return t.call(this,n)}catch(t){var i=r(n);return this.reportFailedStep(e,t),i}},e.prototype.reportFailedStep=function(e,t){try{this.mpInstance.Logger.error("Kit blocking could not filter "+e+": "+t)}catch(e){}},e.prototype.transformEventAndEventAttributes=function(e){var t=p({},e),n=Ze(t);if(!n)return t;var r=this.getMatchKey(n),i=this.dataPlanMatchLookups[r];if(this.blockEvents&&!i)return null;if(this.blockEventAttributes){if(!0===i)return t;if(i){if(t.EventAttributes){for(var o={},s=0,a=Object.keys(t.EventAttributes);s<a.length;s++){var u=a[s];!0===i[u]&&(o[u]=t.EventAttributes[u])}t.EventAttributes=o}return t}return t}return t},e.prototype.transformProductAttributes=function(e){var t=p({},e),n=Ze(t),r=this.getProductAttributeMatchKey(n),i=this.dataPlanMatchLookups[r];function o(e,t){return null==t?void 0:t.map((function(t){if(!t.Attributes)return t;for(var n={},r=0,i=Object.keys(t.Attributes);r<i.length;r++){var o=i[r];!0===e[o]&&(n[o]=t.Attributes[o])}return p(p({},t),{Attributes:n})}))}return this.blockEvents&&!i?null:this.blockEventAttributes?!0===i?t:i?(t.ProductAction?t.ProductAction=p(p({},t.ProductAction),{ProductList:o(i,t.ProductAction.ProductList)}):t.ProductImpressions?t.ProductImpressions=t.ProductImpressions.map((function(e){return p(p({},e),{ProductList:o(i,e.ProductList)})})):this.mpInstance.Logger.warning("Product Not Supported "),t):t:t},e.prototype.transformUserAttributes=function(e){var t=p({},e);if(this.blockUserAttributes){var n=this.dataPlanMatchLookups.user_attributes;if(this.mpInstance._Helpers.isObject(n)&&t.UserAttributes){for(var r={},i=0,o=Object.keys(t.UserAttributes);i<o.length;i++){var s=o[i];!0===n[s]&&(r[s]=t.UserAttributes[s])}t.UserAttributes=r}}return t},e.prototype.isAttributeKeyBlocked=function(e){if(!this.blockUserAttributes)return!1;var t=this.dataPlanMatchLookups.user_attributes;return("boolean"!=typeof t||!t)&&("object"===c(t)&&!0!==t[e])},e.prototype.isIdentityBlocked=function(e){if(!this.blockUserIdentities)return!1;if(!this.blockUserIdentities)return!1;var t=this.dataPlanMatchLookups.user_identities;return!(!0===t||!t)&&!t[e]},e.prototype.transformUserIdentities=function(e){var t,n=this,r=p({},e);if(this.blockUserIdentities){var i=this.dataPlanMatchLookups.user_identities;this.mpInstance._Helpers.isObject(i)&&(null===(t=null==r?void 0:r.UserIdentities)||void 0===t?void 0:t.length)&&(r.UserIdentities=r.UserIdentities.filter((function(e){var t=me.IdentityType.getIdentityName(n.mpInstance._Helpers.parseNumber(e.Type));return i[t]})))}return r},e}(),di=function(e,t,n,r){var i=e+t+"/config",o=["env=".concat(r?"1":"0")],s=n||{},a=s.planId,u=s.planVersion;return a&&o.push("plan_id=".concat(a)),u&&o.push("plan_version=".concat(u)),"".concat(i,"?").concat(o.join("&"))};function li(e,t,n){var r=this,i="https://"+n._Store.SDKConfig.configUrl,o=t.isDevelopmentMode,s=t.dataPlan,a=di(i,e,s,o),u=window.fetch?new dn(a):new ln(a);this.getSDKConfiguration=function(){return g(r,void 0,void 0,(function(){var e,r,i,o,s,a;return v(this,(function(c){switch(c.label){case 0:e={method:"get",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"},body:null},c.label=1;case 1:return c.trys.push([1,6,,7]),[4,u.upload(e)];case 2:return 200!==(r=c.sent()).status?[3,5]:(null===(o=null==n?void 0:n.Logger)||void 0===o||o.verbose("Successfully received configuration from server"),r.json?[4,r.json()]:[3,4]);case 3:return[2,c.sent()];case 4:return i=r,[2,JSON.parse(i.responseText)];case 5:return null===(s=null==n?void 0:n.Logger)||void 0===s||s.verbose("Issue with receiving configuration from server, received HTTP Code of "+r.statusText),[3,7];case 6:return c.sent(),null===(a=null==n?void 0:n.Logger)||void 0===a||a.error("Error getting forwarder configuration from mParticle servers."),[3,7];case 7:return[2,t]}}))}))}}var pi=r.HTTPCodes,gi=r.Messages,vi=r.IdentityMethods.Modify;function hi(e){this.sendAliasRequest=function(t,n){return g(this,void 0,void 0,(function(){var r,i,u,c,d,l,p,g,h,f,m,y,b,S;return v(this,(function(v){switch(v.label){case 0:r=e.Logger,i=e._Helpers.invokeAliasCallback,u=e._Store.SDKConfig.aliasUrl,c=e._Store.devToken,r.verbose(gi.InformationMessages.SendAliasHttp),d="https://".concat(u).concat(c,"/Alias"),l=window.fetch?new dn(d):new ln(d),p={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(t)},v.label=1;case 1:return v.trys.push([1,13,,14]),[4,l.upload(p)];case 2:switch(g=v.sent(),h=void 0,f=void 0,S=void 0,g.status){case s:case o:return[3,3];case a:return[3,4]}return[3,11];case 3:return f="Received Alias Response from server: "+JSON.stringify(g.status),[3,12];case 4:if(!g.json)return[3,9];v.label=5;case 5:return v.trys.push([5,7,,8]),[4,g.json()];case 6:return h=v.sent(),[3,8];case 7:return v.sent(),r.verbose("The request has no response body"),[3,8];case 8:return[3,10];case 9:h=(m=g).responseText?JSON.parse(m.responseText):"",v.label=10;case 10:return(null==(y=h)?void 0:y.message)&&(S=y.message),f="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+g.status,(null==y?void 0:y.code)&&(f+=" - "+y.code),[3,12];case 11:throw new Error("Received HTTP Code of "+g.status);case 12:return r.verbose(f),i(n,g.status,S),[3,14];case 13:return b=v.sent(),S=ie(b),r.error("Error sending alias request to mParticle servers. "+S),i(n,pi.noHttpCoverage,S),[3,14];case 14:return[2]}}))}))},this.sendIdentityRequest=function(t,n,r,i,c,d,l){var h,f,m,y;return g(this,void 0,void 0,(function(){var g,b,S,I,_,w,P,C,A,T,E,k,D,M,O,F,L,U,N;return v(this,(function(v){switch(v.label){case 0:if((null===(h=e._RoktManager)||void 0===h?void 0:h.isInitialized)&&(e._Store.identifyRequestCount=(e._Store.identifyRequestCount||0)+1,L=e._Store.identifyRequestCount,e.captureTiming("".concat(L,"-identityRequestStart"))),g=e._Helpers.invokeCallback,b=e.Logger,S=e._ErrorReportingDispatcher,b.verbose(gi.InformationMessages.SendIdentityBegin),!t)return b.error(gi.ErrorMessages.APIRequestEmpty),[2];if(b.verbose(gi.InformationMessages.SendIdentityHttp),e._Store.identityCallInFlight)return g(r,pi.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2];I=d||null,_=this.getUploadUrl(n,d),w=window.fetch?new dn(_):new ln(_),P={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":e._Store.devToken},body:JSON.stringify(t)},e._Store.identityCallInFlight=!0,v.label=1;case 1:return v.trys.push([1,9,,10]),[4,w.upload(P)];case 2:switch(C=v.sent(),A=void 0,T=void 0,C.status){case s:case o:case a:return[3,3]}return[3,7];case 3:return C.json?[4,C.json()]:[3,5];case 4:return E=v.sent(),A=this.getIdentityResponseFromFetch(C,E),[3,6];case 5:A=this.getIdentityResponseFromXHR(C),v.label=6;case 6:return A.status===a?(k=A.responseText,T="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+A.status,(null==k?void 0:k.Errors)&&(U=k.Errors.map((function(e){return e.message})).join(", "),T+=" - "+U)):b.isVerbose()&&(D=A.responseText,M=e._Store.SDKConfig.isDevelopmentMode,O=D,!M&&(null==D?void 0:D.matched_identities)&&(O=p(p({},D),{matched_identities:te(D.matched_identities)})),T="Received Identity Response from server: "+JSON.stringify(O)),[3,8];case 7:if(C.status>=u)throw new Error("Received HTTP Code of "+C.status);return e._Store.identityCallInFlight=!1,e._Store.identityCallFailed=!1,U="Received HTTP Code of "+C.status,b.error("Error sending identity request to servers - "+U),g(r,pi.noHttpCoverage,U),[2];case 8:return e._Store.identityCallInFlight=!1,e._Store.identityCallFailed=!1,T&&b.verbose(T),(null===(f=e._RoktManager)||void 0===f?void 0:f.isInitialized)&&(L=e._Store.identifyRequestCount,e.captureTiming("".concat(L,"-identityRequestEnd"))),c(A,I,r,i,n,l,!1),[3,10];case 9:return F=v.sent(),e._Store.identityCallInFlight=!1,e._Store.identityCallFailed=!0,(null===(m=e._RoktManager)||void 0===m?void 0:m.isInitialized)&&(L=e._Store.identifyRequestCount,e.captureTiming("".concat(L,"-identityRequestEnd"))),U=ie(F),N="Error sending identity request to servers - "+U,b.error(N),null==S||S.report({message:N,code:vn.IDENTITY_REQUEST,severity:hn.ERROR}),null===(y=e.processQueueOnIdentityFailure)||void 0===y||y.call(e),g(r,pi.noHttpCoverage,U),[3,10];case 10:return[2]}}))}))},this.getUploadUrl=function(t,n){var r=e._Helpers.createServiceUrl(e._Store.SDKConfig.identityUrl);return t===vi?r+n+"/"+t:r+t},this.getIdentityResponseFromFetch=function(e,t){return{status:e.status,responseText:t,cacheMaxAge:parseInt(e.headers.get(An))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(e){return{status:e.status,responseText:e.responseText?JSON.parse(e.responseText):{},cacheMaxAge:C(e.getResponseHeader(An)||""),expireTimestamp:0}}}var fi="passbackconversiontrackingid",mi=function(){function e(e){this.instanceName=e,this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1,this.isShoppableAdsLoaded=!1,this.stopRouteChangeWatch=null,this.pendingCheckoutIntents=[],this.autoButtonClicksForwarded=!1}return e.prototype.setOnReadyCallback=function(e){this.onReadyCallback=e},e.prototype.init=function(e,t,n,r,i,o,s,a,u,c,d){var l,g,v=e||{},h=v.userAttributeFilters,f=v.settings||{},m=f.placementAttributesMapping,y=f.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(l=null==y?void 0:y.toLowerCase())&&void 0!==l?l:null,this.identityService=n,this.store=r,this.logger=i,this.errorReporter=a,this.loggingService=u,this.captureTiming=s,this.integrationCapture=c,this.createFilteredUser=d,null===(g=this.captureTiming)||void 0===g||g.call(this,ve),this.filters={userAttributeFilters:h,filterUserAttributes:qn.filterUserAttributes,filteredUser:t};try{this.placementAttributesMapping=function(e){try{return e?JSON.parse(e.replace(/"/g,'"')):[]}catch(e){throw new Error("Settings string contains invalid JSON")}}(m)}catch(e){this.logger.error("Error parsing placement attributes mapping from config: "+e)}var b=(null==o?void 0:o.sandbox)||!1,S=ar(null==o?void 0:o.launcherOptions);this.launcherOptions=p({sandbox:b},S),(null==o?void 0:o.domain)&&(this.domain=o.domain),this.initialized=!0},Object.defineProperty(e.prototype,"isInitialized",{get:function(){return this.initialized},enumerable:!1,configurable:!0}),e.prototype.attachKit=function(e){var t,n,r,i;this.kit=e,this.watchRouteChanges(),this.flushCheckoutIntents(),(null===(t=e.settings)||void 0===t?void 0:t.accountId)&&this.store.setRoktAccountId(e.settings.accountId),e.integrationName&&(null===(n=this.store)||void 0===n||n.setIntegrationName(e.integrationName)),this.processMessageQueue();try{null===(r=this.onReadyCallback)||void 0===r||r.call(this)}catch(e){null===(i=this.logger)||void 0===i||i.error("RoktManager: Error in onReadyCallback: "+e)}},e.prototype.watchRouteChanges=function(){var e,t,n,r=this;if(!K(null===(e=this.kit)||void 0===e?void 0:e.onRouteChange))return null===(t=this.stopRouteChangeWatch)||void 0===t||t.call(this),void(this.stopRouteChangeWatch=null);this.isAutoLogPageViewEnabled()?(null===(n=this.stopRouteChangeWatch)||void 0===n||n.call(this),this.stopRouteChangeWatch=null):this.stopRouteChangeWatch||(this.stopRouteChangeWatch=yt("rokt:".concat(this.instanceName),(function(){return r.notifyRouteChange()}))),this.notifyRouteChange()},e.prototype.notifyRouteChange=function(){var e,t,n;try{null===(t=null===(e=this.kit)||void 0===e?void 0:e.onRouteChange)||void 0===t||t.call(e)}catch(e){null===(n=this.logger)||void 0===n||n.error("RoktManager: Error in onRouteChange: ".concat(ie(e)))}},e.prototype.setAutoButtonClicksForwarded=function(e){this.autoButtonClicksForwarded=e},e.prototype.isCheckoutIntentSuppressed=function(){var e,t,n=null===(t=null===(e=this.store)||void 0===e?void 0:e.SDKConfig)||void 0===t?void 0:t.flags;if(!n||!0!==n[r.FeatureFlags.AutoButtonTracking]||!this.store.isEnabled||!this.autoButtonClicksForwarded)return!0;var i=this.launcherOptions||{};if(i.noFunctional||i.noTargeting||i.doNotShareOrSell)return!0;var o="undefined"==typeof navigator?void 0:navigator;return!!o&&!0===o.globalPrivacyControl},e.prototype.isCheckoutIntentLive=function(){return!this.isCheckoutIntentSuppressed()&&("undefined"!=typeof Event&&K(Event.prototype.composedPath))},e.prototype.notifyCheckoutIntent=function(e,t){var n;if(void 0===t&&(t=window.location.pathname),!this.isCheckoutIntentSuppressed()){var r=this.kit;if(r)try{K(r.onCheckoutIntent)&&r.onCheckoutIntent(e)}catch(e){null===(n=this.logger)||void 0===n||n.error("RoktManager: Error in onCheckoutIntent: ".concat(ie(e)))}else this.pendingCheckoutIntents=this.pendingCheckoutIntents.filter((function(t){return t.signal.kind!==e.kind})).concat({signal:e,pathname:t}).slice(-5)}},e.prototype.discardCheckoutIntents=function(){this.pendingCheckoutIntents=[]},e.prototype.flushCheckoutIntents=function(){var e=this,t=this.pendingCheckoutIntents;this.pendingCheckoutIntents=[];var n=Date.now(),r=window.location.pathname;t.filter((function(e){var t=e.signal,i=e.pathname;return n-t.t<3e4&&i===r})).sort((function(e,t){return e.signal.t-t.signal.t})).forEach((function(t){var n=t.signal;return e.notifyCheckoutIntent(n)}))},e.prototype.isAutoLogPageViewEnabled=function(){var e,t,n;return!0===(null===(n=null===(t=null===(e=this.store)||void 0===e?void 0:e.SDKConfig)||void 0===t?void 0:t.flags)||void 0===n?void 0:n[r.FeatureFlags.AutoLogPageView])},e.prototype.selectPlacements=function(e){var t,n,r,i,o,s,a,u,c,d,l,h,f,m,y,b,S;return g(this,void 0,void 0,(function(){var g,I,_,w,P,C,A,T,E,k,D,M,O,F,L,U,N,R,V,x,H,K,q,B,j=this;return v(this,(function(v){if(null===(t=this.captureTiming)||void 0===t||t.call(this,ge),!this.isReady()||(null===(n=this.store)||void 0===n?void 0:n.identityCallInFlight))return[2,this.deferredCall("selectPlacements",e)];try{if(g=e.attributes,I=(null==g?void 0:g.sandbox)||null,_=this.mapPlacementAttributes(g,this.placementAttributesMapping),(null===(r=this.logger)||void 0===r?void 0:r.isVerbose())&&(w=ne(g,null===(o=null===(i=this.store)||void 0===i?void 0:i.SDKConfig)||void 0===o?void 0:o.isDevelopmentMode),this.logger.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(w,null,2)))),this.currentUser=this.identityService.getCurrentUser(),P=(null===(a=null===(s=this.currentUser)||void 0===s?void 0:s.getUserIdentities())||void 0===a?void 0:a.userIdentities)||{},C=P.email,A=_.email,T=void 0,E=void 0,(k=this.mappedEmailShaIdentityType&&!1!==ue.getIdentityType(this.mappedEmailShaIdentityType))&&(T=P[this.mappedEmailShaIdentityType],E=_.emailsha256||_[this.mappedEmailShaIdentityType]||void 0),D=this.hasIdentityChanged(C,A),M=this.hasIdentityChanged(T,E),O={},D&&(O.email=A,A&&(F="Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.",this.logger.warning(F),null===(u=this.errorReporter)||void 0===u||u.report({message:F,code:vn.IDENTITY_MISMATCH,severity:hn.WARNING}))),M&&(O[this.mappedEmailShaIdentityType]=E,F="emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.",this.logger.warning(F),null===(c=this.errorReporter)||void 0===c||c.report({message:F,code:vn.IDENTITY_MISMATCH,severity:hn.WARNING})),L=this.toUserAttributes(_),z(O))this.setUserAttributes(this.currentUser,L);else try{this.identityService.identify({userIdentities:p(p({},P),O)},(function(e){var t,n=Number(null==e?void 0:e.httpCode);n&&(n>=400||n<0)&&j.logger.error("Background identify failed with HTTP "+n),j.setUserAttributes(null===(t=null==e?void 0:e.getUser)||void 0===t?void 0:t.call(e),L,O),j.processMessageQueue()}))}catch(e){this.logger.error("Background identify threw an error: "+ie(e)),this.setUserAttributes(this.identityService.getCurrentUser(),L,O)}return U=this.currentUser&&this.createFilteredUser?this.createFilteredUser(this.currentUser.getMPID()):null,N=(null===(d=null==U?void 0:U.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},R=null===(h=null===(l=this.store)||void 0===l?void 0:l.getTimeOnSite)||void 0===h?void 0:h.call(l),V=null===(m=null===(f=this.store)||void 0===f?void 0:f.getTotalTimeOnSite)||void 0===m?void 0:m.call(f),(x=p(p(p(p({},_),null!==I?{sandbox:I}:{}),R?{active_time_on_site_ms:R}:{}),V?{total_time_on_site_ms:V}:{})).email||(N.email?x.email=N.email:P.email&&this.logFilteredIdentity("email")),!k||x.emailsha256||x[this.mappedEmailShaIdentityType]||((H=N[this.mappedEmailShaIdentityType])?x.emailsha256=H:P[this.mappedEmailShaIdentityType]&&this.logFilteredIdentity(this.mappedEmailShaIdentityType)),x[fi]||(null===(y=this.integrationCapture)||void 0===y||y.capture(),K=null===(b=this.integrationCapture)||void 0===b?void 0:b.getClickIdsAsIntegrationAttributes(),(q=null===(S=null==K?void 0:K[Xn.Rokt])||void 0===S?void 0:S[fi])&&(x[fi]=q)),this.filters.filteredUser=U||this.filters.filteredUser||null,B=p(p({},e),{attributes:x}),[2,this.kit.selectPlacements(B)]}catch(e){return[2,Promise.reject(e instanceof Error?e:new Error("Unknown error occurred"))]}return[2]}))}))},e.prototype.logFilteredIdentity=function(e){var t;null===(t=this.logger)||void 0===t||t.verbose("mParticle.Rokt selectPlacements did not add the ".concat(e," user identity to the attributes because the Rokt connection does not allow it"))},e.prototype.hashAttributes=function(e){return g(this,void 0,void 0,(function(){var t,n,r,i,o,s,a,u,d,l,p,h=this;return v(this,(function(f){switch(f.label){case 0:return f.trys.push([0,2,,3]),e&&"object"===c(e)?0===(t=Object.keys(e)).length?[2,{}]:(n=t.map((function(t){return g(h,void 0,void 0,(function(){var n,r;return v(this,(function(i){switch(i.label){case 0:return n=e[t],[4,this.hashSha256(n)];case 1:return r=i.sent(),[2,{key:t,attributeValue:n,hashedValue:r}]}}))}))})),[4,Promise.all(n)]):[2,{}];case 1:for(r=f.sent(),i={},o=0,s=r;o<s.length;o++)a=s[o],u=a.key,d=a.attributeValue,l=a.hashedValue,i[u]=d,l&&(i["".concat(u,"sha256")]=l);return[2,i];case 2:return p=f.sent(),this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(ie(p))),[2,{}];case 3:return[2]}}))}))},e.prototype.setExtensionData=function(e){if(this.isReady())try{this.kit.setExtensionData(e)}catch(e){throw new Error("Error setting extension data: "+ie(e))}else this.deferredCall("setExtensionData",e)},e.prototype.use=function(e){if(!this.isReady())return this.deferredCall("use",e);try{return this.kit.use(e)}catch(t){return Promise.reject(t instanceof Error?t:new Error("Error using extension: "+e))}},e.prototype.terminate=function(){var e,t,n;return g(this,void 0,void 0,(function(){var r;return v(this,(function(i){switch(i.label){case 0:if(!this.isReady())return null===(e=this.logger)||void 0===e||e.verbose("mParticle.Rokt.terminate called before the Rokt kit was ready. Nothing to terminate."),[2];if(!K(this.kit.terminate))return null===(t=this.logger)||void 0===t||t.error("mParticle.Rokt.terminate is not supported by the attached Rokt Kit version."),[2];i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.kit.terminate()];case 2:return i.sent(),[3,4];case 3:return r=i.sent(),null===(n=this.logger)||void 0===n||n.error("Failed to terminate the Rokt launcher: ".concat(ie(r))),[3,4];case 4:return[2]}}))}))},e.prototype.onShoppableAdsReady=function(e){if(this.kit&&this.isShoppableAdsLoaded)try{this.kit.onShoppableAdsReady(e)}catch(e){this.logger.error("Failed to register onShoppableAdsReady callback: ".concat(ie(e)))}else this.deferredCall("onShoppableAdsReady",e)},e.prototype.flushOnShoppableAdsReadyMessageQueue=function(e){var t=this;this.kit=e,this.messageQueue.forEach((function(n,r){var i;if("onShoppableAdsReady"===n.methodName){try{e.onShoppableAdsReady(n.payload)}catch(e){null===(i=t.logger)||void 0===i||i.error("RoktManager: Error flushing onShoppableAdsReady: "+e)}t.messageQueue.delete(r)}})),this.isShoppableAdsLoaded=!0},e.prototype.hashSha256=function(e){return g(this,void 0,void 0,(function(){var t,n;return v(this,(function(r){switch(r.label){case 0:if(null==e)return this.logger.warning("hashSha256 received null/undefined as input"),[2,e];r.label=1;case 1:return r.trys.push([1,3,,4]),t=String(e).trim().toLocaleLowerCase(),[4,this.sha256Hex(t)];case 2:return[2,r.sent()];case 3:return n=r.sent(),this.logger.error("Failed to hashSha256, returning undefined: ".concat(ie(n))),[2,void 0];case 4:return[2]}}))}))},e.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},e.prototype.setLocalSessionAttribute=function(e,t){this.store.setLocalSessionAttribute(e,t)},e.prototype.isReady=function(){return Boolean(this.kit&&this.kit.launcher)},e.prototype.toUserAttributes=function(e){var t=["sandbox"],n={};for(var r in e)if(e.hasOwnProperty(r)&&-1===t.indexOf(r)){var i=e[r];n[r]=Array.isArray(i)?JSON.stringify(i):i}return n},e.prototype.setUserAttributes=function(e,t,n){if(void 0===n&&(n={}),e)try{if(this.hasContradictingIdentity(e,n))return void this.logger.warning("selectPlacements attributes were not set because identify did not resolve to a user with the passed email or hashed email.");e.setUserAttributes(t)}catch(e){this.logger.error("Error setting user attributes: "+e)}else this.logger.warning("selectPlacements attributes were not set because there is no user to set them on.")},e.prototype.hasContradictingIdentity=function(e,t){return Object.keys(t).some((function(n){var r,i,o=null===(i=null===(r=e.getUserIdentities())||void 0===r?void 0:r.userIdentities)||void 0===i?void 0:i[n];return Boolean(o)&&o!==t[n]}))},e.prototype.mapPlacementAttributes=function(e,t){for(var n={},r=0,i=t;r<i.length;r++){var o=i[r];n[o.map]=o.value}var s={};for(var a in e){if(e.hasOwnProperty(a))s[n[a]||a]=e[a]}return s},e.prototype.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue())},e.prototype.processMessageQueue=function(){var e,t=this;if(this.isReady()&&0!==this.messageQueue.size){null===(e=this.logger)||void 0===e||e.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var n=Array.from(this.messageQueue.values());this.messageQueue.clear(),n.forEach((function(e){var n,r,i,o;if(e.methodName in t&&K(t[e.methodName])){if(null===(r=t.logger)||void 0===r?void 0:r.isVerbose()){var s=ne(e.payload,null===(o=null===(i=t.store)||void 0===i?void 0:i.SDKConfig)||void 0===o?void 0:o.isDevelopmentMode);t.logger.verbose("RoktManager: Processing queued message: ".concat(e.methodName," with payload: ").concat(JSON.stringify(s)))}var a=e.resolve,u=e.reject,c=function(n){var r;null===(r=t.logger)||void 0===r||r.error("RoktManager: Error processing message '".concat(e.methodName,"': ").concat(ie(n))),u&&u(n)};try{var d=t[e.methodName](e.payload);Promise.resolve(d).then((function(e){a&&a(e)})).catch(c)}catch(e){c(e)}}else null===(n=t.logger)||void 0===n||n.error("RoktManager: Method ".concat(e.methodName," not found"))}))}},e.prototype.queueMessage=function(e){this.messageQueue.set(e.messageId,e)},e.prototype.deferredCall=function(e,t){var n=this;return new Promise((function(r,i){var o="".concat(e,"_").concat(w());n.queueMessage({messageId:o,methodName:e,payload:t,resolve:r,reject:i})}))},e.prototype.sha256Hex=function(e){return g(this,void 0,void 0,(function(){var t,n,r;return v(this,(function(i){switch(i.label){case 0:return t=new TextEncoder,n=t.encode(e),[4,crypto.subtle.digest("SHA-256",n)];case 1:return r=i.sent(),[2,this.arrayBufferToHex(r)]}}))}))},e.prototype.arrayBufferToHex=function(e){for(var t=new Uint8Array(e),n="",r=0;r<t.length;r++){n+=t[r].toString(16).padStart(2,"0")}return n},e.prototype.hasIdentityChanged=function(e,t){return!!t&&(!e||e!==t)},e}(),yi=function(){function e(e){this.flags=e,this.flags={noFunctional:!0===e.noFunctional,noTargeting:!0===e.noTargeting}}return e.prototype.getNoTargeting=function(){return this.flags.noTargeting},e.prototype.getNoFunctional=function(){return this.flags.noFunctional},e.prototype.syncNoTargetingAttribute=function(e){e&&(this.flags.noTargeting?e.setUserAttribute(i,!0):W(e.getAllUserAttributes(),i)&&e.removeUserAttribute(i))},e}(),bi=function(){function e(){this.services=[]}return e.prototype.register=function(e){this.services.push(e)},e.prototype.report=function(e){var t=this;this.services.forEach((function(n){var r;try{n.report(e)}catch(e){null===(r=t.logger)||void 0===r||r.error("Error in ErrorReportingService: "+e)}}))},e}(),Si=function(){function e(){this.services=[]}return e.prototype.register=function(e){this.services.push(e)},e.prototype.log=function(e){var t=this;this.services.forEach((function(n){var r;try{n.log(e)}catch(e){null===(r=t.logger)||void 0===r||r.error("Error in LoggingService: "+e)}}))},e}(),Ii="is_auto_button_click",_i="Auto Button Click",wi=["label_source","element","type","path","label","aria_label","icon","element_id","element_name","test_id","controls","form","link_type","link_domain","file_extension","checked"],Pi=function(e,t){var n,r=e.filteringEventAttributeValue;if(r&&r.eventAttributeValue&&wi.some((function(e){return qn.hashAttributeConditionalForwarding(e)===r.eventAttributeName})))return"forwarding rule";var i={EventName:_i,EventCategory:se.Other,EventDataType:oe.PageEvent,EventAttributes:(n={},n[Ii]=!0,n.hostname=window.location.hostname,n)},o=[["data plan",{}],["forwarding rule",{filteringEventAttributeValue:r}],["event name filter",{eventNameFilters:e.eventNameFilters}],["event type filter",{eventTypeFilters:e.eventTypeFilters}]].find((function(e){var n=e[1];return!kr(i,n,t)}));return o?o[0]:void 0},Ci='button, input[type="submit"], input[type="button"], input[type="image"], [role="button"]',Ai='[contenteditable]:not([contenteditable="false"])';function Ti(e){var t=K(e.getRootNode)?e.getRootNode():null;return e.assignedSlot||e.parentElement||t&&t.host||null}function Ei(e,t,n){for(var r=e;r&&r!==n;){if(t(r))return!0;r=Ti(r)}return!1}function ki(e,t){return Ei(e,(function(e){return e.matches(t)}))}var Di="[data-core-type], #rokt-controller-frame";function Mi(e){var t=e.getAttribute("src");if(!t)return!1;try{return-1!==new URL(t,"https://example.test").pathname.indexOf("/wsdk/")}catch(e){return!1}}var Oi=["apple-pay-button",".apple-pay-button",".gpay-button",".gpay-card-info-container","#gpay-button-online-api-id","paypal-button","venmo-button","paypal-pay-later-button","paypal-credit-button","shop-pay-button","shop-pay-wallet-button","shopify-accelerated-checkout","shopify-accelerated-checkout-cart","shopify-apple-pay-button","shopify-google-pay-button","shopify-paypal-button","shopify-amazon-pay-button",".amazonpay-button-focusable","#AmazonPayButton","[data-amazon-pay-button]","[data-afterpay-entry-point]"].join(", "),Fi="paypal-basic-card-button",Li=Oi+", "+Fi,Ui=["set-up","add-money","reload","top-up"].map((function(e){return'apple-pay-button[type="'+e+'"]'})).join(", ");function Ni(e){var t=e.matches(Li)?e:null;if(!t){var n=K(e.getRootNode)?e.getRootNode():null;t=n&&n.host&&n.host.matches(Li)?n.host:null}if(t)return t.matches(Ui)?"none":t.matches(Fi)?"checkout_step":"wallet"}var Ri=/(?:^| )(?:apple ?pay|google ?pay|g ?pay|amazon ?pay|cash ?app|venmo|pay ?pal|shop ?pay|klarna|after ?pay|clear ?pay|sezzle|samsung ?pay)(?= |$)/,Vi=/(?:^| )affirm(?= |$)/,xi=/(?:^| )(?:pay|payment|checkout)(?= |$)/,Hi=/(?:^| )(?:btn|button)(?= |$)/,Ki=/(?:^| )(?:logo|icon|image|img|label|text|caption|message|messaging|info|tooltip|help|learn|terms|promo|banner|container|wrapper|wrap|placeholder|form|section|panel|modal|list|group|select|option|tab|toggle|radio|choice|method)(?= |$)/;function qi(e){return(e||"").slice(0,64).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9]+/g," ").trim().toLowerCase()}function Bi(e){return[e.getAttribute("id"),e.getAttribute("data-testid")].map(qi).some((function(e){return(Ri.test(e)||Vi.test(e)&&xi.test(e))&&Hi.test(e)&&!Ki.test(e)}))}var ji='input[type="radio"], input[type="checkbox"], label, [role="radio"], [role="tab"], [role="option"], [role="checkbox"], [role="switch"], [role="menuitemradio"], [role="menuitemcheckbox"], [aria-checked], [aria-selected]',zi='[role="radiogroup"], [role="tablist"], [role="listbox"]',Qi="klarna-placement, afterpay-placement, square-placement, .affirm-as-low-as, .affirm-site-modal, .affirm-product-modal, [data-pp-message]";function Wi(e,t,n){return void 0===n&&(n=!1),!!e.matches(ji)||(!!ki(e,zi)||(!(t||!(!n&&e.hasAttribute("aria-expanded")||e.hasAttribute("aria-pressed")))||ki(e,Qi)))}var Ji=ji+", "+zi+', input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="image"]), select, textarea, option, optgroup, datalist, [aria-expanded], [aria-pressed], '+Ai,Gi=ji+", "+Ci+", a[href], "+Li+", [aria-expanded], [aria-pressed], "+Ai;function $i(e){if(!Bi(e)||e.matches(Ji))return!1;for(var t=Ti(e);t;t=Ti(t))if(t.matches(Gi)||Bi(t))return!1;var n=e.shadowRoot;return!(e.querySelector(Ji)||n&&n.querySelector(Ji))}function Yi(e){for(var t,n=e.slice(0,12),r=0,i=n;r<i.length;r++){if((a=i[r])instanceof Element){t=a;break}}if(!t||ki(t,Di+", [data-mp-no-track]"))return!0;for(var o=0,s=n;o<s.length;o++){var a;if((a=s[o])instanceof Element&&Mi(a))return!0}return!1}function Xi(e,t){if(void 0===t&&(t=!1),t||!Yi(e)){for(var n,r,i=!1,o=0,s=e.slice(0,12);o<s.length;o++){var a=s[o];if(n)break;a instanceof Element&&(a.matches(Ci+", a[href], "+Li)||!i&&$i(a)?n=a:(!r&&a.matches('input[type="checkbox"], input[type="radio"]')&&(r=a),i=i||a.matches(Ji)))}if(!(!(n=n||r)||n.matches(':disabled, [aria-disabled="true"]')||n.classList.contains("disabled")&&Bi(n)))return n}}function Zi(e){return e.matches("input, select, textarea, option, optgroup, datalist, "+Ai)||!!e.querySelector("input, select, textarea, [data-mp-no-track], "+Ai)||ki(e,"select, datalist, textarea, [data-mp-no-track], "+Ai)}var eo=function(){try{return{run:new RegExp("\\p{Nd}{6,}","u"),number:new RegExp("\\p{Nd}+(?:[.,\u060c\u066b\u066c]\\p{Nd}+)*","gu")}}catch(e){return}}(),to=128;function no(e){if(e&&!(e.length>to)&&eo){var t=e.replace(/\s+/g," ").trim().toLowerCase();if(t&&-1===t.indexOf("@")&&!eo.run.test(t.replace(/[\s()\-\u2010-\u2015]/g,"")))return t.replace(eo.number,"#").slice(0,64).trim()||void 0}}var ro=/\.(pdf|zip|csv|txt|ics|docx?|xlsx?|pptx?|dmg|exe|apk|mp3|mp4)$/i;function io(e){if("wallet"===Ni(t=e)||$i(t))return"wallet";var t,n=e.tagName.toLowerCase();return"button"===n||"input"===n?n:e.matches('a[href]:not([role="button"])')?"link":"role"}var oo='script, style, template, [hidden], [aria-hidden="true"], [inert]',so=64;function ao(e){var t=e;return K(t.assignedNodes)?t.assignedNodes():[]}function uo(e){return!!(e.matches(oo)||(t=e,n=t.parentElement,n&&(n.shadowRoot?!t.assignedSlot:ao(n).length>0)))||!(e instanceof SVGTitleElement)&&"none"===window.getComputedStyle(e).display;var t,n}function co(e){var t=window.getComputedStyle(e).visibility;return"hidden"!==t&&"collapse"!==t}function lo(e,t){return!Ei(e,uo,t)}function po(e,t){var n=e.assignedSlot;return!!n&&lo(n,t)}function go(e){return!(/\S/.test(e.textContent||"")||e instanceof Element&&(e.matches("slot")||e.querySelector("slot")))}function vo(e){var t="",n=0,r=function(e){t=(t+e).replace(/\s+/g," ")},i=function(e){if(uo(e))return!0;for(var o=ao(e),s=o.length?o:e.childNodes,a=0;a<s.length;a++){var u=s[a],c=u.nodeType===Node.TEXT_NODE;if(c||u instanceof Element)if(go(u))r(u.textContent);else{if(++n>so)return!1;if(!e.shadowRoot||po(u,e)){if(c)co(u.assignedSlot||e)&&r(u.nodeValue);else if(o.length&&Zi(u)||!i(u))return!1;if(t.trim().length>to)return!1}}}return!0};return i(e)?t.trim():void 0}function ho(e){return e&&e.trim()?e:void 0}function fo(e){var t=e.getAttribute("aria-labelledby");if(t){var n=K(e.getRootNode)?e.getRootNode():document,r=t.split(/\s+/).map((function(e){return(t=n.getElementById?n.getElementById(e):null)&&!Zi(t)&&lo(t)?vo(t):"";var t}));if(-1!==r.indexOf(void 0))return{source:"none"};if(u=r.filter((function(e){return!!e})).join(" "))return{raw:u,source:"labelledby"}}var i=ho(e.getAttribute("aria-label"));if(i)return{raw:i,source:"aria"};var o=e.children.length<=4&&!Zi(e);if(e instanceof HTMLInputElement){var s=e.type;if("image"===s){if(c=ho(e.getAttribute("alt")))return{raw:c,source:"alt"}}else if("submit"===s||"button"===s||"reset"===s){var a=ho(e.value);if(a)return{raw:a,source:"value"};if("button"!==s)return{raw:s,source:"value"}}}else if(o&&lo(e)){var u;if(void 0===(u=vo(e)))return{source:"none"};if(u)return{raw:u,source:"text"};var c=function(e){for(var t=e.querySelectorAll("img[alt]"),n=0;n<t.length&&n<so;n++)if(lo(t[n],e)&&co(t[n]))return ho(t[n].getAttribute("alt"))}(e);if(c)return{raw:c,source:"alt"}}var d=ho(e.getAttribute("title"));return d?{raw:d,source:"title"}:{source:"none"}}var mo=/^(?:fa|fas|far|fal|icon|bi|glyphicon|ti|mdi|ri|la|lucide|ion|feather|ph)-([a-z][a-z-]{1,31})$/,yo=/^(?:solid|regular|light|thin|duotone|brands|sharp|fw|lg|xs|sm|xl|spin|pulse|border|inverse|stack|flip(?:-[a-z]+)?|rotate(?:-[a-z]+)?|pull-[a-z]+)$/;function bo(e){var t=function(e){return!ki(e,"[data-mp-no-track]")},n=Array.from(e.querySelectorAll("use")).filter(t)[0];if(n){var r=n.getAttribute("href")||n.getAttribute("xlink:href")||"",i=r.indexOf("#"),o=function(e){if(e){var t=e.toLowerCase().replace(/^icon-/,"");return/^[a-z][a-z-]{1,31}$/.test(t)?t:void 0}}(-1===i?null:r.slice(i+1));if(o)return o}for(var s=0,a=[e].concat(Array.from(e.querySelectorAll("i, span, svg"))).filter(t).slice(0,5);s<a.length;s++)for(var u=0,c=(a[s].getAttribute("class")||"").split(/\s+/);u<c.length;u++){var d=c[u],l=mo.exec(d.toLowerCase());if(l&&!yo.test(l[1]))return l[1]}}var So=/^[A-Za-z]+[0-9]{0,3}(?:[-_](?:[A-Za-z]+[0-9]{0,3}|[0-9]{1,3}))*$/;function Io(e){if(e){var t=e.trim(),n=t.replace(/[^0-9]/g,"").length;return t.length<=64&&n<=3&&So.test(t)?t:void 0}}var _o=["data-testid","data-test-id","data-test","data-qa","data-cy"];function wo(e,t){for(var n=0,r=t;n<r.length;n++){var i=r[n],o=Io(e.getAttribute(i));if(o)return o}}function Po(e){var t=e.getAttribute("aria-controls");return Io(t?t.trim().split(/\s+/)[0]:null)||wo(e,["popovertarget","commandfor"])}function Co(e){var t=e instanceof HTMLButtonElement||e instanceof HTMLInputElement?e.form:null;return t?Io(t.getAttribute("id")):void 0}function Ao(e){var t=e.tagName.toLowerCase();return"button"===t||"input"===t?e.type:"button"}var To='input[type="checkbox"], input[type="radio"], [role~="checkbox"], [role~="radio"], [role~="switch"], [role~="menuitemcheckbox"], [role~="menuitemradio"]';function Eo(e){var t=e instanceof HTMLLabelElement?e.control:e;return t&&t.matches(To)?t:null}function ko(e,t){var n;if(void 0===t&&(t=[]),!e.matches('a[href]:not([role="button"])')||(n=function(e){var t=(e.getAttribute("href")||"").trim();if(!t||"#"===t.charAt(0))return{type:"same_page"};if(e instanceof HTMLAnchorElement){var n=e.protocol.toLowerCase();if("javascript:"===n)return{type:"same_page"};if("http:"===n||"https:"===n){var r=e.hostname!==window.location.hostname?e.hostname.toLowerCase():void 0,i=ro.exec(e.pathname);return e.hasAttribute("download")||i?{type:"download",domain:r,fileExtension:i?i[1].toLowerCase():void 0}:r?{type:"outbound",domain:r}:e.pathname===window.location.pathname&&e.search===window.location.search?{type:"same_page"}:void 0}}}(e))){var r=io(e),i=e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?e:void 0,o=i||function(e,t){for(var n=0,r=t;n<r.length;n++){var i=r[n];if(i===e)break;var o=i instanceof Element?Eo(i):null;if(o)return o}return Eo(e)||e.querySelector(To)}(e,t),s=o instanceof HTMLInputElement?"radio"===o.type:!!o&&o.matches('[role~="radio"], [role~="menuitemradio"]'),a=s?o instanceof HTMLInputElement?o:null:e,u=o?void 0:fo(e),c=u?no(u.raw):void 0;return{label:c,labelSource:c?u.source:"none",ariaLabel:o?void 0:no(e.getAttribute("aria-label")),icon:o?void 0:bo(e),elementId:s?void 0:Io(e.getAttribute("id")),elementName:Io(a&&a.getAttribute("name")),testId:s?void 0:wo(e,_o),controls:s?void 0:Po(e),form:Co(e),element:r,type:Ao(e),linkType:n?n.type:void 0,linkDomain:n?n.domain:void 0,fileExtension:n?n.fileExtension:void 0,checked:i?i.checked:void 0}}}var Do=/(?:^|\/)(?:checkouts?|payment|order|kasse|paiement|commander?|pago)(?:\/|$)/i,Mo=new RegExp("\\b(?:coupon|promo(?: code)?|newsletter|sign in|sign up|log in|login|add to (?:cart|bag|basket)|gift card balance|(?:add|apply|redeem|check|enter|use) (?:a |an |your )?gift card|pay later|interest free|as low as|learn more|prequalify|apply (?:now|for)|payment plan|available|accepted|we accept|set up|add money|reload|top up|add to (?:apple|google) wallet|connect|link your|unlink|remove|delete|edit|change|manage|use a different|switch)\\b|^pay in$|\\bpay in (?:installments|instalments)\\b"),Oo=new RegExp(["gutschein|anmelden|warenkorb|bon cadeau|connexion|panier|cup\xf3n|iniciar sesi\xf3n|carrito","carrello|codice sconto|accedi|buono regalo|winkelwagen|kortingscode|inloggen|cadeaubon|achteraf betalen","\u30ab\u30fc\u30c8|\u30af\u30fc\u30dd\u30f3|\u30ed\u30b0\u30a4\u30f3|\u4f1a\u54e1\u767b\u9332|\u30ae\u30d5\u30c8|\u5f8c\u6255\u3044|\u30e1\u30eb\u30de\u30ac"].join("|")),Fo=["(?:jetzt )?(?:zahlungs|kosten)pflichtig (?:bestellen|buchen)|(?:jetzt )?bezahlen|kauf abschlie\xdfen|bestellung abschlie\xdfen","commander et payer|payer(?: maintenant)?|(?:confirmer|finaliser) (?:ma |la )?commande","valider et payer|confirmer et payer|commande avec obligation de paiement|finaliser l'achat","(?:realizar|confirmar|completar) (?:el |mi |la )?(?:pedido|compra|reserva)|finalizar (?:el |mi )?pedido|pagar(?: ahora)?","pedido con obligaci\xf3n de pago","(?:effettua|conferma|concludi|completa) (?:l'|il )?(?:ordine|acquisto)|ordine con obbligo di pagamento","paga(?: ora| adesso)?|ordina e paga","(?:nu )?betalen|bestellen en betalen|bestelling plaatsen|plaats bestelling|bestelling afronden","bestelling met betalingsverplichting","(?:\u3053\u306e\u5185\u5bb9\u3067|\u4e0a\u8a18\u306e?\u5185\u5bb9\u3067)?\u3054?(?:\u6ce8\u6587|\u8cfc\u5165|\u4e88\u7d04|\u6c7a\u6e08|\u304a?\u652f\u6255\u3044?)\u3092?(?:\u78ba\u5b9a|\u5b8c\u4e86)(?:\u3059\u308b)?","(?:\u3053\u306e\u5185\u5bb9\u3067|\u4e0a\u8a18\u306e?\u5185\u5bb9\u3067)\u3054?(?:\u6ce8\u6587|\u8cfc\u5165|\u4e88\u7d04)\u3059\u308b|\u3054?\u6ce8\u6587\u3059\u308b|\u6c7a\u6e08\u3059\u308b|(?:\u4eca\u3059\u3050|\u3092)?\u652f\u6255\u3046"].join("|"),Lo=new RegExp("^(?:(?:(?:agree|accept|review) and )?(?:place|submit|complete|confirm|finali[sz]e)(?!(?: [^ ]+){0,2} (?:another|new|next)(?: |$))(?! (?:[^ ]+ )?gift card)(?: [^ ]+){0,2} (?:order|purchase|booking|reservation|payment|checkout|transaction)(?: now| securely| and pay| (?:with|using) [^ ]+(?: [^ ]+)?)?(?: (?:total|subtotal|items?|tickets?))?|pay(?: securely)?(?: now)?|(?:confirm|agree|accept|submit|order|book) and pay|pay and place (?:my |your )?order|order with obligation to pay|"+Fo+")$"),Uo=new RegExp("^(?:(?:place|submit|complete)(?!(?: [^ ]+){0,2} (?:another|new|next)(?: |$))(?: [^ ]+){0,2} (?:order|purchase)|"+Fo+")$"),No=new RegExp("^(?:buy now|purchase|jetzt kaufen|kaufen|commander|(?:passer|valider) (?:la |ma )?commande|finalizar (?:la |mi )?compra|comprar ahora|acquista ora|nu kopen|\u4eca\u3059\u3050\u8cfc\u5165|\u8cfc\u5165\u3059\u308b|\u3053\u306e\u5185\u5bb9\u3067\u7533\u3057\u8fbc\u3080)$"),Ro=new RegExp("^(?:"+["(?:let's |lets |go to |proceed to |secure )?(?:check ?out|checkout)(?: now| securely| as guest)?","(?:continue|proceed) to (?:payment|review|billing|shipping|delivery|order review)|review (?:my |your )?order","guest checkout|(?:pay|continue|check ?out) (?:with|by) (?:card|credit card|debit card|credit or debit card)","zur kasse|zur kasse gehen|auschecken|weiter zur zahlung","passer \xe0 la caisse|continuer vers le paiement|proc\xe9der au paiement","ir a caja|continuar al pago|tramitar pedido","procedi al checkout|procedi all'acquisto|procedi al pagamento|vai alla cassa","afrekenen|verder naar betalen|doorgaan naar betalen","\u30ec\u30b8\u306b\u9032\u3080|\u3054?(?:\u8cfc\u5165|\u6ce8\u6587)\u624b\u7d9a\u304d(?:\u3078|\u306b)(?:\u9032\u3080)?|\u304a?\u652f\u6255\u3044(?:\u3078|\u306b)\u9032\u3080|(?:\u3054\u6ce8\u6587\u5185\u5bb9\u306e)?\u78ba\u8a8d\u753b\u9762\u3078(?:\u9032\u3080)?"].join("|")+")$"),Vo="(?:(?:my|your|the) )?(?:shopping )?(?:cart|bag|basket)",xo=new RegExp("^(?:add(?: [^ ]+){0,5} to "+Vo+"|(?:(?:view|open|go to) )?"+Vo+"(?: items?)?|items? in "+Vo+")$"),Ho="apple pay|google pay|paypal|venmo|amazon pay|shop pay|klarna|afterpay|clearpay|cash app(?: pay)?|affirm|sezzle|samsung pay",Ko=new RegExp("^(?:(?:pay|buy|purchase|order|book|donate|subscribe|check ?out|checkout|express checkout|continue|proceed|complete purchase|place (?:my |your )?order)(?: now| securely)? (?:with|using|via|through|by) (?:"+Ho+")(?: express(?: checkout)?| checkout)?|(?:continue|proceed|go) (?:to|with) (?:"+Ho+"))$"),qo=new RegExp("^(?:"+Ho+")(?: (?:checkout|check out|express(?: checkout)?|express pay|buy now|pay now|pay|now)| (?:logo|icon|mark|button)(?: (?:logo|icon|mark|button))*)?$"),Bo=new Set(["pay.google.com","applepay.cdn-apple.com","payments.amazon.com","pay.shopify.com"]),jo=new Set(["www.paypal.com","www.sandbox.paypal.com"]),zo=/^\/smart\/(?:buttons|menu)(?:\/|$)/,Qo=/\/elements-inner-(?:payment-request|express-checkout)-/,Wo=["adyen.com","braintreegateway.com","cybersource.com","squarecdn.com","checkout.com"],Jo=/[\u2019\u2018]/g,Go=/[0-9\uFF10-\uFF19$\u20AC\u00A3\u00A5\uFFE5\u20B9\u5186.,\uFF0C]/g,$o=/\([^()]*\)|\[[^[\]]*\]|\uFF08[^\uFF08\uFF09]*\uFF09|\uFF3B[^\uFF3B\uFF3D]*\uFF3D|\u3010[^\u3010\u3011]*\u3011/g,Yo="[\\s!-/:-@\\[-`{-~\\u00A1-\\u00BF\\u00D7\\u00F7\\u2000-\\u206F\\u20A0-\\u20CF\\u2190-\\u2BFF\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u30FB\\uD800-\\uDFFF\\uFE00-\\uFE0F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65]+",Xo=new RegExp("^"+Yo+"|"+Yo+"$","g");var Zo=/[-_|\xb7\u2022]/g,es=/(?:^| )(?:usd|aud|cad|nzd|gbp|eur|chf|sgd|hkd|jpy|inr|mxn)(?= |$)|\b(?:a|au|ca|c|us|nz|hk|s)\$/g,ts=[[/\bapplepay\b/g,"apple pay"],[/\bg ?pay\b/g,"google pay"],[/\bamazonpay\b/g,"amazon pay"],[/\bshoppay\b/g,"shop pay"],[/\bcashapp\b/g,"cash app"]],ns=8;function rs(e){if(e&&!(e.length>128)){var t=e.toLowerCase().replace(Jo,"'").replace(/[&+]/g," and ").replace(Zo," ").replace(es," ").replace(Go,"").replace(/\s+/g," ").trim();return ts.forEach((function(e){var n=e[0],r=e[1];t=t.replace(n,r)})),t.split(" ").length>ns?void 0:t}}function is(e){return e.replace($o," ").replace(/\s+/g," ").replace(Xo,"")||e.replace(Xo,"")}function os(e){return function(e){if(e instanceof HTMLInputElement){var t=e.type,n=null;return"submit"===t||"button"===t?n=e.value:"image"===t&&(n=e.getAttribute("alt")),[e.getAttribute("aria-label"),n]}return e.children.length>4||Zi(e)?[e.getAttribute("aria-label")]:[e.getAttribute("aria-label"),e.textContent]}(e).map(rs).filter((function(e){return!!e}))}function ss(e,t,n){return t?Uo.test(e):Lo.test(e)||No.test(e)&&"checkout_path"===function(e){return Do.test(e)?"checkout_path":"other"}(n)}function as(e,t){var n=Ni(e);if("none"!==n){if(n)return Wi(e,"wallet"===n)?void 0:{kind:n,source:"vendor"};var r=os(e),i=r.map(is),o=function(e,t){var n=t.length?void 0:rs(e.getAttribute("title"));return(n?[is(n)]:t).some((function(e){return xo.test(e)}))}(e,i)?{kind:"cart",source:"label"}:void 0;if(!Wi(e,!1,!!o)){if(o&&e.hasAttribute("aria-expanded"))return o;var s=e.matches('a[href]:not([role="button"])');if(i.some((function(e){return ss(e,s,t)})))return{kind:"commit",source:"label"};if(r.concat(i).some((function(e){return Mo.test(e)||Oo.test(e)})))return o;if($i(e))return{kind:"wallet",source:"name"};for(var a=!s&&e.matches(Ci),u=0,c=i;u<c.length;u++){var d=c[u];if(a&&Ko.test(d))return{kind:"wallet",source:"label"};if(a&&qo.test(d))return{kind:"wallet",source:"brand"};if(Ro.test(d))return{kind:"checkout_step",source:"label"}}return o}}}function us(e,t){var n;if("visible"===t.document.visibilityState&&e instanceof HTMLIFrameElement&&!(ki(n=e,Di)||Mi(n)||ki(e,"[data-mp-no-track]")))try{var r=new URL(e.src),i="https:"===r.protocol?r.hostname:"";if(jo.has(i))return zo.test(r.pathname)?"wallet":"frame";if(Bo.has(i))return"wallet";if("js.stripe.com"===i)return Qo.test(r.pathname)?"wallet":"frame";if(Wo.some((function(e){return function(e,t){return e===t||e.length>t.length&&e.slice(e.length-t.length-1)==="."+t}(i,e)})))return"frame"}catch(e){}}var cs="__mpBtn__",ds=function(){return"undefined"==typeof window?null:window},ls=function(){var e=ds(),t=e?e[cs]:void 0;return t?t.tracker:void 0},ps=function(){var e=ds();if(e){var t=ls();t&&t.teardown(),e[cs]={}}},gs="__mpApplePayHook__",vs=function(e){var t=e.ApplePaySession;return t&&t.prototype},hs={capture:!0,passive:!0},fs={passive:!0},ms=function(){function e(e){var t=this;this.active=!1,this.hasRoktKit=!1,this.generation=0,this.lastCommitClick=-1/0,this.lastClick=null,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.pending=[],this.uploadTimerId=null,this.uploadHeld=!1,this.leaving=!1,this.drain=function(){var e=t.pending;t.pending=[],e.forEach((function(e){return e()}))},this.onHide=function(e){if("beforeunload"===e.type||"pagehide"===e.type||"hidden"===document.visibilityState){t.leaving=!0;try{t.drain()}finally{t.leaving=!1}t.cancelUpload()}},this.onPageShow=function(e){e.persisted&&t.reset()},this.onEvent=function(e){try{t.observe(e)}catch(e){t.log("[error] event handler threw: "+e)}},this.mpInstance=e}return Object.defineProperty(e.prototype,"isActive",{get:function(){return this.active},enumerable:!1,configurable:!0}),e.prototype.init=function(e){var t=ds();if(t){var n=ls();n&&n.teardown(),this.active&&this.teardown(),this.hasRoktKit=e.hasRoktKit,this.eventsEnabled()||!this.isKitSuppressed()?(t.document.addEventListener("click",this.onEvent,hs),t.document.addEventListener("submit",this.onEvent,hs),t.addEventListener("blur",this.onEvent,fs),t.addEventListener("pageshow",this.onPageShow,fs),t.addEventListener("beforeunload",this.onHide,hs),t.addEventListener("pagehide",this.onHide,hs),t.document.addEventListener("visibilitychange",this.onHide,hs),this.active=!0,t[cs]||(t[cs]={}),t[cs].tracker=this,this.isKitSuppressed()||function(e){try{var t=vs(e),n=t&&t.begin;if(!K(n)||n[gs])return;var r=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=n.apply(this,e);try{var i=ls();i&&i.onApplePayBegin()}catch(e){}return r};Object.defineProperty(r,gs,{value:n}),t.begin=r}catch(e){}}(t),this.log("listening")):this.log("opted out, not starting")}},e.prototype.onApplePayBegin=function(){var e=this,t=Date.now(),n=this.lastClick;if(!(!this.active||!n||n.excluded||"commit"===n.kind||t-n.t>1e3||this.isKitSuppressed())){var r=window.location.pathname,i=this.generation;setTimeout((function(){if(i===e.generation)try{e.emit("wallet","wallet"===n.kind?n.source:"api","apple_pay",t,r)}catch(t){e.log("[error] Apple Pay delivery threw: "+t)}}),0)}},e.prototype.teardown=function(){var e=ds();if(e){e.document.removeEventListener("click",this.onEvent,!0),e.document.removeEventListener("submit",this.onEvent,!0),e.removeEventListener("blur",this.onEvent),e.removeEventListener("pageshow",this.onPageShow),e.removeEventListener("beforeunload",this.onHide,!0),e.removeEventListener("pagehide",this.onHide,!0),e.document.removeEventListener("visibilitychange",this.onHide,!0);var t=e[cs];t&&t.tracker===this&&(t.tracker=void 0,function(e){try{var t=vs(e),n=t&&t.begin;K(n)&&K(n[gs])&&(t.begin=n[gs])}catch(e){}}(e))}this.active=!1,this.clearPending()},e.prototype.clearPending=function(){this.reset();var e=this.mpInstance._RoktManager;e&&e.discardCheckoutIntents()},e.prototype.reset=function(){this.generation++,this.pending=[],this.lastCommitClick=-1/0,this.lastClick=null,this.lastSent={},this.pagePath=null,this.pageEvents=0,this.cancelUpload()},e.prototype.enqueue=function(e){var t;this.pending.push(e),1===this.pending.length&&(t=this.drain,K(window.requestAnimationFrame)&&"hidden"!==document.visibilityState?requestAnimationFrame((function(){setTimeout(t,0)})):setTimeout(t,0))},e.prototype.observe=function(e){var t=this;if(this.active&&e.isTrusted){var n=e.type,r="click"===n&&this.eventsEnabled(),i=!this.isKitSuppressed();if(r||i){var o,s,a,u,c=Date.now(),d=window.location.pathname,l=!1;if("click"===n){var p=K(e.composedPath)?e.composedPath().slice(0,12):[],g=Yi(p);if(f=g?void 0:Xi(p,!0)){(o=r?ko(f,p):void 0)&&void 0!==o.checked&&(s=f);var v=i?as(f,d):void 0;a=v?v.kind:void 0,u=v?v.source:void 0}this.lastClick={t:c,excluded:g,kind:a,source:u}}else if("submit"===n){var h=e.submitter,f=h?Xi([h]):void 0;if(h){if(f){v=as(f,d);a=v?v.kind:void 0,u=v?v.source:void 0}}else a="commit",u="submit";l=!h}var m=this.generation;this.enqueue((function(){if(m===t.generation)try{"blur"===n?(a=us(document.activeElement,window),u="frame"):l&&c-t.lastCommitClick>1e3&&(a=void 0),o&&r&&(s&&e.defaultPrevented&&(o.checked="checkbox"===s.type?!o.checked:s.checked),t.logClick(o,d)),a&&t.emit(a,u,n,c,d)}catch(e){t.log("[error] delivery threw: "+e)}}))}}},e.prototype.logClick=function(e,t){if(this.eventsEnabled()&&(t!==this.pagePath&&(this.pagePath=t,this.pageEvents=0),!(this.pageEvents>=100))){this.pageEvents++,this.mpInstance._SessionManager.resetSessionTimer();var n=this.queuedForUpload();this.mpInstance._Events.logEvent(function(e,t){for(var n,r=((n={label_source:e.labelSource,element:e.element,type:e.type,path:t,hostname:window.location.hostname})[Ii]=!0,n),i={label:e.label,aria_label:e.ariaLabel,icon:e.icon,element_id:e.elementId,element_name:e.elementName,test_id:e.testId,controls:e.controls,form:e.form,link_type:e.linkType,link_domain:e.linkDomain,file_extension:e.fileExtension},o=0,s=Object.keys(i);o<s.length;o++){var a=s[o];i[a]&&(r[a]=i[a])}return void 0!==e.checked&&(r.checked=e.checked),{messageType:oe.PageEvent,name:_i,data:r,eventType:se.Other}}(e,t)),!this.leaving&&void 0===e.checked&&this.queuedForUpload()>n&&this.uploadNow()}},e.prototype.queuedForUpload=function(){var e=this.mpInstance._APIClient.uploader;return e?e.eventsQueuedForProcessing.length:0},e.prototype.uploadNow=function(){var e=this;null===this.uploadTimerId?this.mpInstance.upload():(clearTimeout(this.uploadTimerId),this.uploadHeld=!0),this.uploadTimerId=setTimeout((function(){e.uploadTimerId=null,e.uploadHeld&&(e.uploadHeld=!1,e.mpInstance.upload())}),100)},e.prototype.cancelUpload=function(){null!==this.uploadTimerId&&(clearTimeout(this.uploadTimerId),this.uploadTimerId=null),this.uploadHeld=!1},e.prototype.emit=function(e,t,n,r,i){if(!this.isKitSuppressed()){"commit"===e&&"click"===n&&(this.lastCommitClick=r);var o=this.lastSent[e];o&&o.pathname===i&&r-o.t<2e3||(this.lastSent[e]={t:r,pathname:i},this.mpInstance._RoktManager.notifyCheckoutIntent(Object.freeze({kind:e,t:r,source:t,pathname:i}),i))}},e.prototype.eventsEnabled=function(){var e=this.mpInstance._Store;return!!e&&e.isEnabled},e.prototype.isKitSuppressed=function(){var e=this.mpInstance._RoktManager;return!this.hasRoktKit||!e||e.isCheckoutIntentSuppressed()},e.prototype.log=function(e){this.mpInstance.Logger.verbose("mParticle button tracking: "+e)},e}(),ys=r.Messages,bs=r.HTTPCodes,Ss=r.FeatureFlags,Is=r.CaptureIntegrationSpecificIdsV2Modes,_s=Ss.ReportBatching,ws=Ss.CaptureIntegrationSpecificIds,Ps=Ss.CaptureIntegrationSpecificIdsV2,Cs=ys.InformationMessages.StartingInitialization;function As(e){var t=this;this._instanceName=e,this._NativeSdkHelpers=new $n(this),this._SessionManager=new rr(this),this._Persistence=new Sr(this),this._Helpers=new zn(this),this._Events=new _r(this),this._CookieSyncManager=new Zn(this),this._ServerModel=new Kr(this),this._Ecommerce=new or(this),this._ForwardingStatsUploader=new qr(this),this._Consent=new ii(this),this._IdentityAPIClient=new hi(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._ErrorReportingDispatcher=new bi,this._LoggingDispatcher=new Si,this._RoktManager=new mi(e),this._RoktManager.setOnReadyCallback((function(){t.processQueueOnIdentityFailure()})),this.processQueueOnIdentityFailure=function(){var e,n,r;(null===(e=t._Store)||void 0===e?void 0:e.isInitialized)||(null===(n=t._Store)||void 0===n?void 0:n.identityCallFailed)&&(null===(r=t._RoktManager)||void 0===r?void 0:r.isReady())&&(t._RoktManager.processMessageQueue(),t._preInit.readyQueue=jr(t._preInit.readyQueue,t.Logger))},this.processQueueOnNoFunctional=function(){var e,n;(null===(e=t._Store)||void 0===e?void 0:e.isInitialized)||(null===(n=t._CookieConsentManager)||void 0===n?void 0:n.getNoFunctional())&&!xn(t._Store)&&(t._preInit.readyQueue=jr(t._preInit.readyQueue,t.Logger))},this.IdentityType=ue,this.EventType=se,this.CommerceEventType=ae,this.PromotionType=le,this.ProductActionType=ce,this.RoktEvents=de,this._Identity=new ni(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(e,t){var n=this;(t||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),function(e,t,n){e.Logger=new pr(n),e._ErrorReportingDispatcher.logger=e.Logger,e._LoggingDispatcher.logger=e.Logger,e._Store=new ur(n,e,t),window.mParticle.Store=e._Store,ps(),e.Logger.verbose(Cs);var r=ar(null==n?void 0:n.launcherOptions),i=r.noFunctional,o=r.noTargeting;e._CookieConsentManager=new yi({noFunctional:i,noTargeting:o});try{e._Store.isLocalStorageAvailable=e._Persistence.determineLocalStorageAvailability(window.localStorage)}catch(t){e.Logger.warning("localStorage is not available, using cookies if available"),e._Store.isLocalStorageAvailable=!1}}(this,e,t),t)?!t.hasOwnProperty("requestConfig")||t.requestConfig?new li(e,t,this).getSDKConfiguration().then((function(r){var i=re({},t,r);Ts(e,i,n)})):Ts(e,t,this):console.error("No config available on the window, please pass a config object to mParticle.init()")},this.setLogLevel=function(e){t.Logger.setLogLevel(e)},this.reset=function(e){try{e._Persistence.resetPersistence(),ps(),e._ButtonTracker=void 0,e._Store&&delete e._Store}catch(e){console.error("Cannot reset mParticle",e)}},this._resetForTests=function(e,t,n){n._Store&&delete n._Store,n._ErrorReportingDispatcher=new bi,n._LoggingDispatcher=new Si,n.Logger=new pr(e),n._ErrorReportingDispatcher.logger=n.Logger,n._LoggingDispatcher.logger=n.Logger,n._Store=new ur(e,n),n._Store.isLocalStorageAvailable=n._Persistence.determineLocalStorageAvailability(window.localStorage),n._Events.stopTracking(),Ht(),n._PageViewTracker=void 0,ps(),n._ButtonTracker=void 0,t||n._Persistence.resetPersistence(),n._Persistence.forwardingStatsBatches.uploadsTable={},n._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],n._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1}},this.ready=function(e){var n,r,i,o=(null===(n=t._CookieConsentManager)||void 0===n?void 0:n.getNoFunctional())&&!xn(t._Store);K(e)&&((null===(r=t._Store)||void 0===r?void 0:r.isInitialized)||(null===(i=t._Store)||void 0===i?void 0:i.identityCallFailed)&&t._RoktManager.isReady()||o)?e():t._preInit.readyQueue.push(e)},this.getEnvironment=function(){return t._Store.SDKConfig.isDevelopmentMode?r.Environment.Development:r.Environment.Production},this.getVersion=function(){return r.sdkVersion},this.setAppVersion=function(e){Es((function(){t.setAppVersion(e)}),t)||(t._Store.SDKConfig.appVersion=e,t._Persistence.update())},this.setDeviceId=function(e){Es((function(){t.setDeviceId(e)}),t)||this._Store.setDeviceId(e)},this.isInitialized=function(){return!!t._Store&&t._Store.isInitialized},this.getAppName=function(){return t._Store.SDKConfig.appName},this.setAppName=function(e){Es((function(){t.setAppName(e)}),t)||(t._Store.SDKConfig.appName=e)},this.getAppVersion=function(){return t._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){t._SessionManager.resetSessionTimer(),t._Events.stopTracking()},this.startTrackingLocation=function(e){K(e)||t.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),t._SessionManager.resetSessionTimer(),t._Events.startTracking(e)},this.setPosition=function(e,n){Es((function(){t.setPosition(e,n)}),t)||(t._SessionManager.resetSessionTimer(),"number"==typeof e&&"number"==typeof n?t._Store.currentPosition={lat:e,lng:n}:t.Logger.error("Position latitude and/or longitude must both be of type number"))},this.startNewSession=function(){t._SessionManager.startNewSession()},this.endSession=function(){t._SessionManager.endSession(!0)},this.logBaseEvent=function(e,n){Es((function(){t.logBaseEvent(e,n)}),t)||(t._SessionManager.resetSessionTimer(),"string"==typeof e.name?(e.eventType||(e.eventType=se.Unknown),t._Helpers.canLog()?t._Events.logEvent(e,n):t.Logger.error(ys.ErrorMessages.LoggingDisabled)):t.Logger.error(ys.ErrorMessages.EventNameInvalidType))},this.logEvent=function(e,n,r,i,o){Es((function(){t.logEvent(e,n,r,i,o)}),t)||(t._SessionManager.resetSessionTimer(),"string"==typeof e?(n||(n=se.Unknown),t._Helpers.isEventType(n)?t._Helpers.canLog()?t._Events.logEvent({messageType:oe.PageEvent,name:e,data:r,eventType:n,customFlags:i},o):t.Logger.error(ys.ErrorMessages.LoggingDisabled):t.Logger.error("Invalid event type: "+n+", must be one of: \n"+JSON.stringify(se))):t.Logger.error(ys.ErrorMessages.EventNameInvalidType))},this.logError=function(e,n){if(!Es((function(){t.logError(e,n)}),t)&&(t._SessionManager.resetSessionTimer(),e)){"string"==typeof e&&(e={message:e});var r={m:e.message?e.message:e,s:"Error",t:e.stack||null};if(n){var i=t._Helpers.sanitizeAttributes(n,r.m);for(var o in i)r[o]=i[o]}t._Events.logEvent({messageType:oe.CrashReport,name:e.name?e.name:"Error",eventType:se.Other,data:r})}},this.logLink=function(e,n,r,i){t._Events.addEventHandler("click",e,n,i,r)},this.logForm=function(e,n,r,i){t._Events.addEventHandler("submit",e,n,i,r)},this.logPageView=function(e,n,r,i){if(!Es((function(){t.logPageView(e,n,r,i)}),t)){if(t._SessionManager.resetSessionTimer(),t._Helpers.canLog()){if(t._Helpers.Validators.isStringOrNumber(e)||(e="PageView"),n){if(!t._Helpers.isObject(n))return void t.Logger.error("The attributes argument must be an object. A "+c(n)+" was entered. Please correct and retry.")}else n={hostname:window.location.hostname,title:window.document.title};if(r&&!t._Helpers.isObject(r))return void t.Logger.error("The customFlags argument must be an object. A "+c(r)+" was entered. Please correct and retry.")}t._Events.logEvent({messageType:oe.PageView,name:e,data:n,eventType:se.Unknown,customFlags:r},i)}},this.upload=function(){var e,n;t._Helpers.canLog()&&(t._Store.webviewBridgeEnabled?t._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.Upload):null===(n=null===(e=t._APIClient)||void 0===e?void 0:e.uploader)||void 0===n||n.prepareAndUpload(!1,!1))},this.Consent={createCCPAConsent:t._Consent.createPrivacyConsent,createGDPRConsent:t._Consent.createPrivacyConsent,createConsentState:t._Consent.createConsentState},this.eCommerce={setCurrencyCode:function(e){Es((function(){t.eCommerce.setCurrencyCode(e)}),t)||("string"==typeof e?(t._SessionManager.resetSessionTimer(),t._Store.currencyCode=e):t.Logger.error("Code must be a string"))},createProduct:function(e,n,r,i,o,s,a,u,c,d){return t._Ecommerce.createProduct(e,n,r,i,o,s,a,u,c,d)},createPromotion:function(e,n,r,i){return t._Ecommerce.createPromotion(e,n,r,i)},createImpression:function(e,n){return t._Ecommerce.createImpression(e,n)},createTransactionAttributes:function(e,n,r,i,o,s){return t._Ecommerce.createTransactionAttributes(e,n,r,i,o,s)},logProductAction:function(e,n,r,i,o,s){Es((function(){t.eCommerce.logProductAction(e,n,r,i,o,s)}),t)||(t._SessionManager.resetSessionTimer(),t._Events.logProductActionEvent(e,n,r,i,o,s))},logPurchase:function(e,n,r,i,o){tr({methodName:"mParticle.logPurchase",warningMessage:"mParticle.logPurchase is deprecated, please use mParticle.logProductAction with ProductActionType.Purchase instead"},t.Logger,t._ErrorReportingDispatcher),t._Store.isInitialized?e&&n?(t._SessionManager.resetSessionTimer(),t._Events.logPurchaseEvent(e,n,i,o)):t.Logger.error(ys.ErrorMessages.BadLogPurchase):t.ready((function(){t.eCommerce.logPurchase(e,n,r,i,o)}))},logPromotion:function(e,n,r,i,o){Es((function(){t.eCommerce.logPromotion(e,n,r,i,o)}),t)||(t._SessionManager.resetSessionTimer(),t._Events.logPromotionEvent(e,n,r,i,o))},logImpression:function(e,n,r,i){Es((function(){t.eCommerce.logImpression(e,n,r,i)}),t)||(t._SessionManager.resetSessionTimer(),t._Events.logImpressionEvent(e,n,r,i))},expandCommerceEvent:function(e){return t._Ecommerce.expandCommerceEvent(e)}},this.setSessionAttribute=function(e,n){var i;if(!((null===(i=t._CookieConsentManager)||void 0===i?void 0:i.getNoFunctional())&&!xn(t._Store))&&Es((function(){t.setSessionAttribute(e,n)}),t))return;if(t._Helpers.canLog()){if(!t._Helpers.Validators.isValidAttributeValue(n))return void t.Logger.error(ys.ErrorMessages.BadAttribute);if(!t._Helpers.Validators.isValidKeyValue(e))return void t.Logger.error(ys.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(r.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:e,value:n}));else{var o=t._Helpers.findKeyInObject(t._Store.sessionAttributes,e);o&&(e=o),t._Store.sessionAttributes[e]=n,t._Persistence.update(),t._Forwarders.applyToForwarders("setSessionAttribute",[e,n])}}},this.setOptOut=function(e){Es((function(){t.setOptOut(e)}),t)||(t._SessionManager.resetSessionTimer(),t._Store.isEnabled=!e,e&&(t._ButtonTracker&&t._ButtonTracker.clearPending(),t._RoktManager.discardCheckoutIntents()),t._Events.logOptOut(),t._Persistence.update(),t._Store.activeForwarders.length&&t._Store.activeForwarders.forEach((function(n){if(n.setOptOut){var r=n.setOptOut(e);r&&t.Logger.verbose(r)}})))},this.setIntegrationAttribute=function(e,n){if(!Es((function(){t.setIntegrationAttribute(e,n)}),t))if("number"==typeof e){if(null===n)t._Store.integrationAttributes[e]={};else{if(!t._Helpers.isObject(n))return void t.Logger.error("Attrs must be an object with keys and values. You entered a "+c(n));if(0===Object.keys(n).length)t._Store.integrationAttributes[e]={};else for(var r in n)"string"==typeof r?"string"==typeof n[r]?(t._Helpers.isObject(t._Store.integrationAttributes[e])||(t._Store.integrationAttributes[e]={}),t._Store.integrationAttributes[e][r]=n[r]):t.Logger.error("Values for integration attributes must be strings. You entered a "+c(n[r])):t.Logger.error("Keys must be strings, you entered a "+c(r))}t._Persistence.update()}else t.Logger.error("integrationId must be a number")},this.getIntegrationAttributes=function(e){return t._Store.integrationAttributes[e]?t._Store.integrationAttributes[e]:{}},this.addForwarder=function(e){t._preInit.forwarderConstructors.push(e)},this.configurePixel=function(e){t._Forwarders.configurePixel(e)},this._getActiveForwarders=function(){return t._Store.activeForwarders},this._getIntegrationDelays=function(){return t._preInit.integrationDelays},this._setIntegrationDelay=function(e,n){if(t._preInit.integrationDelays[e]=n,!0!==n){var r=Object.keys(t._preInit.integrationDelays);if(0!==r.length)r.some((function(e){return!0===t._preInit.integrationDelays[e]}))||t._APIClient.processQueuedEvents()}},this._setWrapperSDKInfo=function(e,n){Es((function(){t._setWrapperSDKInfo(e,n)}),t)||void 0!==t._Store.wrapperSDKInfo&&t._Store.wrapperSDKInfo.isInfoSet||(t._Store.wrapperSDKInfo={name:e,version:n,isInfoSet:!0})},this._registerErrorReportingService=function(e){t._ErrorReportingDispatcher.register(e)},this._registerLoggingService=function(e){t._LoggingDispatcher.register(e)};var n=r.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[n]&&"string"==typeof window[n]||(window[n]=t._Helpers.generateUniqueId())},this.getLauncherInstanceGuid=function(){return window[n]},this.captureTiming=function(e){var t;"undefined"!=typeof window&&(null===(t=window.performance)||void 0===t?void 0:t.mark)&&window.performance.mark(e)}}function Ts(e,t,n){var i,o,s,a,u=function(e,t){var n,r,i,o;e.dataPlanOptions&&(t.Logger.verbose("Customer provided data plan found"),r={document:{dtpn:{vers:(o=e.dataPlanOptions).dataPlanVersion,blok:{ev:o.blockEvents,ea:o.blockEventAttributes,ua:o.blockUserAttributes,id:o.blockUserIdentities}}}});r||(e.dataPlan&&e.dataPlan.document?e.dataPlan.document.error_message?i=e.dataPlan.document.error_message:(t.Logger.verbose("Data plan found from mParticle.js"),r=e.dataPlan):e.dataPlanResult&&(e.dataPlanResult.error_message?i=e.dataPlanResult.error_message:(t.Logger.verbose("Data plan found from /config"),r={document:e.dataPlanResult})));i&&t.Logger.error(i);r&&(n=new ci(r,t));return n}(t,n),c=n._Helpers.getFeatureFlag,d=r.FeatureFlags,l=d.AutoLogPageView,p=d.AutoButtonTracking;if((null===(i=n._APIClient)||void 0===i?void 0:i.uploader)&&n._APIClient.uploader.destroy(),n._APIClient=new Kn(n,u),n._Forwarders=new Rr(n,u),n._Store.processConfig(t),n._Identity.idCache=function(e){var t;if(null===(t=e._CookieConsentManager)||void 0===t?void 0:t.getNoFunctional())return new un("".concat(e._Store.storageName,"-id-cache"));return new sn("".concat(e._Store.storageName,"-id-cache"))}(n),On(n._Identity.idCache),n._Store.webviewBridgeEnabled)n._NativeSdkHelpers.initializeSessionAttributes(e),ps(),n._RoktManager.setAutoButtonClicksForwarded(!1);else{n._Persistence.initializeStorage(),n._Store.syncPersistenceData();var g=n.Identity.getCurrentUser(),v=g?g.getMPID():null,h=g?g.getUserIdentities().userIdentities:{};if(n._Store.SDKConfig.identifyRequest=n._Store.hasInvalidIdentifyRequest()?{userIdentities:h}:n._Store.SDKConfig.identifyRequest,c(_s)&&n._ForwardingStatsUploader.startForwardingStatsTimer(),Qe(c)){var f=c(ws),m=c(Ps),y=void 0;f||m===Is.All?y="all":m===Is.RoktOnly&&(y="roktonly"),n._IntegrationCapture=new We(y),n._IntegrationCapture.capture()}var b=ee(t,"Rokt",181);if(b){var S=null===(o=b.settings)||void 0===o?void 0:o.accountId;n._Store.setRoktAccountId(S);var I=function(e){return Cr(e,b,n,u)},_={sandbox:null==t?void 0:t.isDevelopmentMode,launcherOptions:null==t?void 0:t.launcherOptions,domain:null==t?void 0:t.domain};n._RoktManager.init(b,I(v),n.Identity,n._Store,n.Logger,_,n.captureTiming,n._ErrorReportingDispatcher,n._LoggingDispatcher,n._IntegrationCapture,I)}var w=b?Pi(b,u):void 0;w&&c(p)&&n.Logger.warning("Checkout intent is off: the ".concat(w," keeps some or all Auto Button Click events from the Rokt kit.")),n._RoktManager.setAutoButtonClicksForwarded(!!b&&!w),n._Forwarders.processForwarders(t,n._APIClient.prepareForwardingStats),n._Forwarders.processPixelConfigs(t),n._SessionManager.initialize(),n._Events.logAST(),c(l)?(n._PageViewTracker||(n.Logger.verbose("mParticle APV: [sdk-init] creating new PageViewTracker for this instance"),n._PageViewTracker=new Bt(n,{isAutoPageView:!0})),Vt()?n.Logger.verbose("mParticle APV: [sdk-init] initial page view already logged this page load, skipping"):(xt(),n._Events.logPageView({isAutoPageView:!0})),n._PageViewTracker.init()):n._PageViewTracker&&n._PageViewTracker.teardown(),c(p)?(n._ButtonTracker||(n._ButtonTracker=new ms(n)),n._ButtonTracker.init({hasRoktKit:!!b})):ps(),function(e,t,n,r){!e._Store.identifyCalled&&e._Store.SDKConfig.identityCallback&&t&&n&&e._Store.SDKConfig.identityCallback({httpCode:bs.activeSession,getUser:function(){return e._Identity.mParticleUser(n)},getPreviousUser:function(){var t=e.Identity.getUsers(),r=t.shift(),i=r.getMPID();return r&&i===n&&(r=t.shift()),r||null},body:{mpid:n,is_logged_in:e._Store.isLoggedIn,matched_identities:r,context:null,is_ephemeral:!1}})}(n,g,v,h)}(n._Store.mpid&&!n._Store.identifyCalled||n._Store.webviewBridgeEnabled)&&(n._Store.isInitialized=!0,null===(s=n._CookieConsentManager)||void 0===s||s.syncNoTargetingAttribute(n.Identity.getCurrentUser()),n._preInit.readyQueue=jr(n._preInit.readyQueue,n.Logger)),null===(a=n.processQueueOnNoFunctional)||void 0===a||a.call(n),n._Store.isFirstRun&&(n._Store.isFirstRun=!1)}function Es(e,t){var n,r,i=(null===(n=t._CookieConsentManager)||void 0===n?void 0:n.getNoFunctional())&&!xn(t._Store);return!(null===(r=t._Store)||void 0===r?void 0:r.isInitialized)&&!i&&(t._preInit.readyQueue.push((function(){var n;(null===(n=t._Store)||void 0===n?void 0:n.isInitialized)&&e()})),!0)}var ks=function(){return null},Ds=function(){function e(){}return e.prototype.getMPInstance=function(){return{_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function(){return"mockHash"},generateUniqueId:function(){return"mockId"},extend:re,createServiceUrl:ks,parseNumber:ks,isObject:ks,Validators:null},_resetForTests:ks,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:ks},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:ks},getTotalTimeOnSite:ks},config:null,eCommerce:null,Identity:{getCurrentUser:ks,IdentityAPI:{},identify:ks,login:ks,logout:ks,modify:ks},Logger:{verbose:ks,error:ks,warning:ks},ProductActionType:null,ServerModel:null,addForwarder:ks,generateHash:ks,getAppVersion:ks,getAppName:ks,getInstance:ks,getDeviceId:ks,init:ks,logBaseEvent:ks,logEvent:ks,logLevel:"none",setPosition:ks,upload:ks}},e.prototype.createSDKEventFunction=function(e){return new Kr(this.getMPInstance()).createEventObject(e)},e.prototype.returnBatch=function(e){var t=this,n=this.getMPInstance();return Je("0",Array.isArray(e)?e.map((function(e){return t.createSDKEventFunction(e)})):[this.createSDKEventFunction(e)],n)},e}(),Ms=function(){function e(e){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=e}return e.prototype.addEventTypeFilter=function(e){var t=qn.hashEventType(e);this.filterDictionary.eventTypeFilters.push(t)},e.prototype.addEventNameFilter=function(e,t){var n=qn.hashEventName(t,e);this.filterDictionary.eventNameFilters.push(n)},e.prototype.addEventAttributeFilter=function(e,t,n){var r=qn.hashEventAttributeKey(e,t,n);this.filterDictionary.attributeFilters.push(r)},e.prototype.addScreenNameFilter=function(e){var t=qn.hashEventName(e,se.Unknown);this.filterDictionary.screenNameFilters.push(t)},e.prototype.addScreenAttributeFilter=function(e,t){var n=qn.hashEventAttributeKey(se.Unknown,e,t);this.filterDictionary.screenAttributeFilters.push(n)},e.prototype.addUserIdentityFilter=function(e){var t=qn.hashUserIdentity(e);this.filterDictionary.userIdentityFilters.push(t)},e.prototype.addUserAttributeFilter=function(e){var t=qn.hashUserAttribute(e);this.filterDictionary.userAttributeFilters.push(t)},e}();Array.prototype.forEach||(Array.prototype.forEach=n.forEach),Array.prototype.map||(Array.prototype.map=n.map),Array.prototype.filter||(Array.prototype.filter=n.filter),Array.isArray||(Array.prototype.isArray=n.isArray);var Os=new function(){var e=this;this.Store={},this._instances={},this.IdentityType=ue,this.EventType=se,this.CommerceEventType=ae,this.PromotionType=le,this.ProductActionType=ce,this.RoktEvents=de,this.MPSideloadedKit=Ms,"undefined"!=typeof window&&(this.isIOS=!(!window.mParticle||!window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(t,n,i){!n&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),n=window.mParticle?window.mParticle.config:{}),i=(i&&0!==i.length?i:r.DefaultInstance).toLowerCase();var o=e._instances[i];void 0===o&&(o=new As(i),e._instances[i]=o),o.captureTiming(pe),o.setLauncherInstanceGuid(),o.init(t,n,i)},this.captureTiming=function(t){e.getInstance().captureTiming(t)},this.getInstance=function(t){var n;return t?(n=e._instances[t.toLowerCase()])||(console.log("You tried to initialize an instance named "+t+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null):(t=r.DefaultInstance,(n=e._instances[t])||(n=new As(t),e._instances[r.DefaultInstance]=n),n)},this.Rokt=e.getInstance()._RoktManager,this.getDeviceId=function(){return e.getInstance().getDeviceId()},this.setDeviceId=function(t){return e.getInstance().setDeviceId(t)},this.isInitialized=function(){return e.getInstance().isInitialized()},this.startNewSession=function(){e.getInstance().startNewSession()},this.endSession=function(){e.getInstance().endSession()},this.setLogLevel=function(t){e.getInstance().setLogLevel(t)},this.ready=function(t){e.getInstance().ready(t)},this.setAppVersion=function(t){e.getInstance().setAppVersion(t)},this.getAppName=function(){return e.getInstance().getAppName()},this.setAppName=function(t){e.getInstance().setAppName(t)},this.getAppVersion=function(){return e.getInstance().getAppVersion()},this.getEnvironment=function(){return e.getInstance().getEnvironment()},this.stopTrackingLocation=function(){e.getInstance().stopTrackingLocation()},this.startTrackingLocation=function(t){e.getInstance().startTrackingLocation(t)},this.setPosition=function(t,n){e.getInstance().setPosition(t,n)},this.logBaseEvent=function(t,n){e.getInstance().logBaseEvent(t,n)},this.logEvent=function(t,n,r,i,o){e.getInstance().logEvent(t,n,r,i,o)},this.logError=function(t,n){e.getInstance().logError(t,n)},this.logLink=function(t,n,r,i){e.getInstance().logLink(t,n,r,i)},this.logForm=function(t,n,r,i){e.getInstance().logForm(t,n,r,i)},this.logPageView=function(t,n,r,i){e.getInstance().logPageView(t,n,r,i)},this.upload=function(){e.getInstance().upload()},this.eCommerce={setCurrencyCode:function(t){e.getInstance().eCommerce.setCurrencyCode(t)},createProduct:function(t,n,r,i,o,s,a,u,c,d){return e.getInstance().eCommerce.createProduct(t,n,r,i,o,s,a,u,c,d)},createPromotion:function(t,n,r,i){return e.getInstance().eCommerce.createPromotion(t,n,r,i)},createImpression:function(t,n){return e.getInstance().eCommerce.createImpression(t,n)},createTransactionAttributes:function(t,n,r,i,o,s){return e.getInstance().eCommerce.createTransactionAttributes(t,n,r,i,o,s)},logProductAction:function(t,n,r,i,o,s){e.getInstance().eCommerce.logProductAction(t,n,r,i,o,s)},logPurchase:function(t,n,r,i,o){e.getInstance().eCommerce.logPurchase(t,n,r,i,o)},logPromotion:function(t,n,r,i,o){e.getInstance().eCommerce.logPromotion(t,n,r,i,o)},logImpression:function(t,n,r,i){e.getInstance().eCommerce.logImpression(t,n,r,i)},expandCommerceEvent:function(t){return e.getInstance().eCommerce.expandCommerceEvent(t)}},this.setSessionAttribute=function(t,n){e.getInstance().setSessionAttribute(t,n)},this.setOptOut=function(t){e.getInstance().setOptOut(t)},this.setIntegrationAttribute=function(t,n){e.getInstance().setIntegrationAttribute(t,n)},this.getIntegrationAttributes=function(t){return e.getInstance().getIntegrationAttributes(t)},this.Identity={HTTPCodes:r.HTTPCodes,aliasUsers:function(t,n){e.getInstance().Identity.aliasUsers(t,n)},createAliasRequest:function(t,n,r){return e.getInstance().Identity.createAliasRequest(t,n,r)},getCurrentUser:function(){return e.getInstance().Identity.getCurrentUser()},getUser:function(t){return e.getInstance().Identity.getUser(t)},getUsers:function(){return e.getInstance().Identity.getUsers()},identify:function(t,n){e.getInstance().Identity.identify(t,n)},login:function(t,n){e.getInstance().Identity.login(t,n)},logout:function(t,n){e.getInstance().Identity.logout(t,n)},modify:function(t,n){e.getInstance().Identity.modify(t,n)},search:function(t,n,r){e.getInstance().Identity.search(t,n,r)}},this.sessionManager={getSession:function(){return e.getInstance()._SessionManager.getSessionId()}},this.Consent={createConsentState:function(){return e.getInstance().Consent.createConsentState()},createGDPRConsent:function(t,n,r,i,o){return e.getInstance().Consent.createGDPRConsent(t,n,r,i,o)},createCCPAConsent:function(t,n,r,i,o){return e.getInstance().Consent.createGDPRConsent(t,n,r,i,o)}},this.reset=function(){e.getInstance().reset(e.getInstance())},this._resetForTests=function(t,n){"boolean"==typeof n?e.getInstance()._resetForTests(t,n,e.getInstance()):e.getInstance()._resetForTests(t,!1,e.getInstance())},this.configurePixel=function(t){e.getInstance().configurePixel(t)},this._setIntegrationDelay=function(t,n){e.getInstance()._setIntegrationDelay(t,n)},this._getIntegrationDelays=function(){return e.getInstance()._getIntegrationDelays()},this.getVersion=function(){return e.getInstance().getVersion()},this.generateHash=function(t){return e.getInstance().generateHash(t)},this._cleanUrl=nn,this.addForwarder=function(t){e.getInstance().addForwarder(t)},this._getActiveForwarders=function(){return e.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(t,n){e.getInstance()._setWrapperSDKInfo(t,n)},this._registerErrorReportingService=function(t){e.getInstance()._registerErrorReportingService(t)},this._registerLoggingService=function(t){e.getInstance()._registerLoggingService(t)}};"undefined"!=typeof window&&(window.mParticle=Os,window.mParticle._BatchValidator=new Ds);export{Os as default};
|