@mparticle/web-sdk 2.79.2 → 2.80.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/README.md +52 -0
- package/dist/mparticle.common.js +156 -56
- package/dist/mparticle.esm.js +156 -56
- package/dist/mparticle.js +941 -708
- package/dist/types/src/filteredMparticleUser.d.ts +15 -7
- package/dist/types/src/forwardingStatsUploader.d.ts +4 -4
- package/dist/types/src/mp-instance.d.ts +3 -2
- package/dist/types/src/nativeSdkHelpers.d.ts +3 -12
- package/dist/types/src/nativeSdkHelpers.interfaces.d.ts +15 -1
- package/dist/types/src/pageViewTracker.d.ts +35 -24
- package/dist/types/src/persistence.d.ts +3 -44
- package/dist/types/src/persistence.interfaces.d.ts +10 -10
- package/dist/types/src/sdkRuntimeModels.d.ts +5 -3
- package/dist/types/src/store.d.ts +3 -0
- package/package.json +1 -1
- package/src/events.ts +9 -1
- package/src/filteredMparticleUser.ts +160 -0
- package/src/{forwardingStatsUploader.js → forwardingStatsUploader.ts} +25 -12
- package/src/mp-instance.ts +27 -25
- package/src/nativeSdkHelpers.interfaces.ts +21 -1
- package/src/{nativeSdkHelpers.js → nativeSdkHelpers.ts} +59 -34
- package/src/pageViewTracker.ts +475 -281
- package/src/persistence.interfaces.ts +10 -10
- package/src/persistence.ts +1210 -0
- package/src/sdkRuntimeModels.ts +5 -3
- package/src/store.ts +3 -0
- package/src/filteredMparticleUser.js +0 -101
- package/src/persistence.js +0 -985
package/dist/mparticle.esm.js
CHANGED
|
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
|
|
|
15
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
16
|
isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
|
|
17
17
|
|
|
18
|
-
var version = "2.
|
|
18
|
+
var version = "2.80.0";
|
|
19
19
|
|
|
20
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",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
|
|
21
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
|
|
@@ -617,19 +617,19 @@ if(!g||a._Store.requireDelay||!a._Store.configurationLoaded)return a.Logger.verb
|
|
|
617
617
|
|
|
618
618
|
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}();
|
|
619
619
|
|
|
620
|
-
var StorageNames$1=Constants.StorageNames;function appendFilteredUserIdentity(a,b,c){c===Types.IdentityType.CustomerId?a.unshift(b):a.push(b);}function buildFilteredUserIdentities(a,b,c){var d=[];if(!a||!Object.keys(a).length)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=Types.IdentityType.getIdentityType(e);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
|
|
620
|
+
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)){var f=Types.IdentityType.getIdentityType(e);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
|
|
621
621
|
// https://go.mparticle.com/work/SQDSDKS-5239
|
|
622
622
|
// Utility Functions
|
|
623
623
|
// Imported Validators
|
|
624
|
-
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}return 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(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
|
|
624
|
+
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}return 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
|
|
625
625
|
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;}
|
|
626
626
|
|
|
627
|
-
var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var
|
|
628
|
-
return
|
|
627
|
+
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
|
|
628
|
+
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
|
|
629
629
|
// TODO: what to do about people setting things on mParticle itself?
|
|
630
630
|
// android
|
|
631
631
|
},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
|
|
632
|
-
},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var
|
|
632
|
+
},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){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)))}};}
|
|
633
633
|
|
|
634
634
|
var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations
|
|
635
635
|
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
|
|
@@ -734,13 +734,22 @@ if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];els
|
|
|
734
734
|
|
|
735
735
|
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}();
|
|
736
736
|
|
|
737
|
-
var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){
|
|
738
|
-
//
|
|
739
|
-
//
|
|
740
|
-
//
|
|
741
|
-
|
|
742
|
-
//
|
|
743
|
-
|
|
737
|
+
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
|
|
738
|
+
// localStorage to cookies, then no mParticle cookie exists yet and there is
|
|
739
|
+
// localStorage. Get the localStorage, set them to cookies, then delete the
|
|
740
|
+
// localStorage item.
|
|
741
|
+
function d(b,d,e){var f;return d?(f=c(d,e),b.removeItem(a._Store.storageName)):e&&(f=e),E.storeDataInMemory(f),f}// For migrating from cookie to localStorage -- If an instance is newly
|
|
742
|
+
// switching from cookies to localStorage, then no mParticle localStorage
|
|
743
|
+
// exists yet and there are cookies. Get the cookies, set them to
|
|
744
|
+
// localStorage, then delete the cookies.
|
|
745
|
+
function e(b,d){if(!d)return void E.storeDataInMemory(b);var e=c(b,d);return E.storeDataInMemory(e),E.expireCookies(a._Store.storageName),e}function f(b,c){return a._Store.isLocalStorageAvailable?a._Store.SDKConfig.useCookieStorage?d(window.localStorage,b,c):e(b,c):void E.storeDataInMemory(c)}function g(b){for(var c in b)b.hasOwnProperty(c)&&!SDKv2NonMPIDCookieKeys[c]&&(a._Store.nonCurrentUserMPIDs[c]=b[c]);}function h(){return E.useLocalStorage()&&a._Store.isLocalStorageAvailable?void localStorage.removeItem(a._Store.storageName):void E.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
|
|
746
|
+
// Store. However, we allow device ID to be overriden via a config value and
|
|
747
|
+
// thus the priority of the deviceId value is
|
|
748
|
+
// 1. value passed via config.deviceId
|
|
749
|
+
// 2. previous value in persistence
|
|
750
|
+
// 3. generate new guid
|
|
751
|
+
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
|
|
752
|
+
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}/* This function determines if a cookie is greater than the configured maxCookieSize.
|
|
744
753
|
- If it is, we remove an MPID and its associated UI/UA/CSD from the cookie.
|
|
745
754
|
- Once removed, check size, and repeat.
|
|
746
755
|
- Never remove the currentUser's MPID from the cookie.
|
|
@@ -751,8 +760,15 @@ var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Consta
|
|
|
751
760
|
a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs
|
|
752
761
|
b. Then remove MPIDs based on order in currentSessionMPIDs array, which
|
|
753
762
|
stores MPIDs based on earliest login.
|
|
754
|
-
*/
|
|
763
|
+
*/function l(a,b){return a.length>b}function m(a,b,c,d){var e;for(var f in a)a.hasOwnProperty(f)&&(e=r(a,b,c),!!l(e,d))&&(SDKv2NonMPIDCookieKeys[f]||f===a.cu||delete a[f]);return e}function n(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(SDKv2NonMPIDCookieKeys[c]||c===a.cu||(b[c]=1));return b}function o(a,b,c,d,e,f){var g;for(var h in b)(g=r(a,d,e),!!l(g,f))&&b.hasOwnProperty(h)&&-1===c.indexOf(h)&&delete a[h];return g}function p(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 q(a,b,c,d,e){for(var f,g=0;g<b.length&&(f=r(a,c,d),!!l(f,e));g++)p(a,b[g],e);return f}function r(a,b,c){return E.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}function s(a,b,c){for(var d in a)if(b===d&&c===a[d])return !0;return !1}function t(a,b,c){var d;for(var e in a)// any value in persistence that has an MPID key will be an MPID to search through
|
|
764
|
+
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
|
|
765
|
+
a[e].mpid&&s(a[e].ui,b,c)&&(d=e);return d}function u(a,b){var c;for(var d in b.userIdentities)if(a&&Object.keys(a).length){var e=t(a,d,b.userIdentities[d]);e&&(c=e);}return c}function v(b){return Array.isArray(b)?0<b.length:!!a._Helpers.isObject(b)&&0<Object.keys(b).length}function w(a,b){return a[b]&&v(a[b])?void(a[b]=Base64.encode(JSON.stringify(a[b]))):void delete a[b]}function x(a){for(var b in a)if(a.hasOwnProperty(b)){if(Base64CookieKeys[b]){w(a,b);continue}if("ie"==b){a[b]=a[b]?1:0;continue}a[b]||delete a[b];}}function y(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 z(a){for(var b in a)a.hasOwnProperty(b)&&Base64CookieKeys[b]&&y(a,b);}function A(a){for(var b in a)a.hasOwnProperty(b)&&(SDKv2NonMPIDCookieKeys[b]||z(a[b]));}function B(a){for(var b in a)if(a.hasOwnProperty(b)){if(Base64CookieKeys[b]){a[b]=JSON.parse(Base64.decode(a[b]));continue}"ie"==b&&(a[b]=!!a[b]);}}function C(a){for(var b in a)a.hasOwnProperty(b)&&Base64CookieKeys[b]&&a[b].length&&(a[b]=JSON.parse(Base64.decode(a[b])));}function D(a){for(var b in a)if(a.hasOwnProperty(b)){if(!SDKv2NonMPIDCookieKeys[b]){C(a[b]);continue}"l"==b&&(a[b]=!!a[b]);}}// TODO: This should actually be decodePersistenceString or
|
|
755
766
|
// we should refactor this to take a string and return an object
|
|
767
|
+
var E=this;// https://go.mparticle.com/work/SQDSDKS-5022
|
|
768
|
+
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
769
|
+
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
770
|
+
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
771
|
+
// https://go.mparticle.com/work/SQDSDKS-6021
|
|
756
772
|
// 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.
|
|
757
773
|
// For example subdomain.domain.co.uk would try the following combinations:
|
|
758
774
|
// "co.uk" -> fail
|
|
@@ -768,27 +784,130 @@ var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Consta
|
|
|
768
784
|
* time
|
|
769
785
|
*/ // https://go.mparticle.com/work/SQDSDKS-6045
|
|
770
786
|
// Forwarder Batching Code
|
|
771
|
-
this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var
|
|
772
|
-
|
|
773
|
-
//
|
|
774
|
-
//
|
|
775
|
-
|
|
776
|
-
{var
|
|
777
|
-
if(!(null!==(
|
|
778
|
-
if(
|
|
779
|
-
var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above
|
|
780
|
-
if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above
|
|
781
|
-
for(var n,o=0;o<h.length&&(g=d(b,c,e),g.length>f);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through
|
|
782
|
-
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
|
|
783
|
-
if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1<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(a,b){if(b){var c=f.getPersistence();c&&(c[a]?c[a].csd=b:c[a]={csd:b}),f.savePersistence(c);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=f.getPersistence();d&&(d.cu=b,d.gs.csm=c,f.savePersistence(d));}},this.savePersistence=function(b){var c;// Block mprtcl-v4 persistence when noFunctional is true
|
|
784
|
-
if(!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional())){var d,e=f.encodePersistence(JSON.stringify(b)),g=new Date,h=a._Store.storageName,i=new Date(g.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString(),j=f.getCookieDomain();if(d=""===j?"":";domain="+j,a._Store.SDKConfig.useCookieStorage){var k=f.reduceAndEncodePersistence(b,i,d,a._Store.SDKConfig.maxCookieSize);window.document.cookie=encodeURIComponent(h)+"="+k;}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=f.getPersistence();return b&&b[a]&&b[a].fst?b[a].fst:null},this.setFirstSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=f.getPersistence();c&&(!c[a]&&(c[a]={}),!c[a].fst&&(c[a].fst=b,f.savePersistence(c)));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
787
|
+
this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var c=E.getLocalStorage(),d=E.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045
|
|
788
|
+
b(c,d),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0);// https://go.mparticle.com/work/SQDSDKS-6046
|
|
789
|
+
var e=f(c,d);g(e),E.update();}catch(b){// If cookies or local storage is corrupt, we want to remove it
|
|
790
|
+
// so that in the future, initializeStorage will work
|
|
791
|
+
h(),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&E.setCookie(),E.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
|
|
792
|
+
{var c=a._Store.storageName,d=E.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),E.encodePersistence(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b=a._Store.storageName,c=E.decodePersistence(window.localStorage.getItem(b));if(!c)return null;var d=JSON.parse(c),e={};for(var f in d)d.hasOwnProperty(f)&&(e[f]=d[f]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=E.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,f,g,h=a._Store.storageName,j=h?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;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){j=a._Helpers.converted(g);break}h||(j[f]=a._Helpers.converted(g));}return j?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(E.decodePersistence(j))):null},this.setCookie=function(){var b;// Block mprtcl-v4 cookies when noFunctional is true
|
|
793
|
+
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=E.getCookie()||{},l=new Date(h.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toUTCString();e=E.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=E.reduceAndEncodePersistence(j,l,f,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(i)+"="+g;}},this.reduceAndEncodePersistence=function(a,b,c,d){var e=a.gs.csm?a.gs.csm:[];if(!e.length)return m(a,b,c,d);var f=n(a);return Object.keys(f).length&&o(a,f,e,b,c,d),q(a,e,b,c,d)},this.findPrevCookiesBasedOnUI=function(b){var c=a._Persistence.getPersistence();if(b){var d=u(c,b);d&&E.storeDataInMemory(c,d);}},this.encodePersistence=function(a){var b=JSON.parse(a);return x(b.gs),A(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&&(B(c.gs),D(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=E.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(a,b){if(b){var c=E.getPersistence();c&&(c[a]?c[a].csd=b:c[a]={csd:b}),E.savePersistence(c);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=E.getPersistence();d&&(d.cu=b,d.gs.csm=c,E.savePersistence(d));}},this.savePersistence=function(b){var c;// Block mprtcl-v4 persistence when noFunctional is true
|
|
794
|
+
if(null===(c=a._CookieConsentManager)||void 0===c||!c.getNoFunctional()){var d,e=E.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=E.getCookieDomain();if(d=""===i?"":";domain="+i,a._Store.SDKConfig.useCookieStorage){var j=E.reduceAndEncodePersistence(b,h,d,a._Store.SDKConfig.maxCookieSize);window.document.cookie=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=E.getPersistence();return b&&b[a]&&b[a].fst?b[a].fst:null},this.setFirstSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=E.getPersistence();c&&(!c[a]&&(c[a]={}),!c[a].fst&&(c[a].fst=b,E.savePersistence(c)));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
785
795
|
},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
|
|
786
|
-
return new Date().getTime();var c=
|
|
787
|
-
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,
|
|
788
|
-
|
|
789
|
-
var
|
|
796
|
+
return new Date().getTime();var c=E.getPersistence();return c&&c[b]&&c[b].lst?c[b].lst:null},this.setLastSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=E.getPersistence();c&&c[a]&&(c[a].lst=b,E.savePersistence(c));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
797
|
+
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,E.update();},this.resetPersistence=function(){localStorage.clear(),E.expireCookies(StorageNames.cookieName),E.expireCookies(StorageNames.cookieNameV2),E.expireCookies(StorageNames.cookieNameV3),E.expireCookies(StorageNames.cookieNameV4),E.expireCookies(a._Store.storageName);var b=getMParticleManager();if(null===b||void 0===b?void 0:b._isTestEnv){localStorage.removeItem(a._Helpers.createMainStorageName("abcdef")),E.expireCookies(a._Helpers.createMainStorageName("abcdef"));}},this.forwardingStatsBatches={uploadsTable:{},forwardingStatsEventQueue:[]};}
|
|
798
|
+
|
|
799
|
+
var HISTORY_METHODS=["pushState","replaceState"],WRAPPED_MARKER="__mpApvWrapped__";// All APV state hangs off one window key, and it is the public debugging
|
|
800
|
+
// contract: `window.__mpApv__` is what you inspect in a console to see whether
|
|
801
|
+
// tracking is live.
|
|
802
|
+
//
|
|
803
|
+
// It lives on `window` rather than in module scope because Next.js re-executes
|
|
804
|
+
// the SDK bundle on every SPA navigation: module-level state is reset each time,
|
|
805
|
+
// but `window` persists for the lifetime of the tab.
|
|
806
|
+
//
|
|
807
|
+
// One object rather than a key per flag, so resetting is a single reassignment.
|
|
808
|
+
// Nothing has to be deleted, and there is no ordering in which half the state
|
|
809
|
+
// survives the reset.
|
|
810
|
+
var WIN_APV_KEY="__mpApv__";// The query params an auto page view may carry. An allowlist, not a denylist:
|
|
811
|
+
// partner URLs routinely hold order ids, email addresses and session tokens, and
|
|
812
|
+
// none of those should reach the event stream because someone forgot to exclude
|
|
813
|
+
// them. Anything absent from this list is dropped.
|
|
814
|
+
//
|
|
815
|
+
// SECURITY: `code`, `state` and `nonce` are the OAuth 2.0 / OIDC authorization
|
|
816
|
+
// code and the CSRF/replay tokens. They are credentials until redeemed, and
|
|
817
|
+
// attaching them here persists them in the event store and forwards them to
|
|
818
|
+
// every configured kit. They are on the list by explicit product decision —
|
|
819
|
+
// deleting that line is the whole of the fix if that decision is revisited.
|
|
820
|
+
var ALLOWED_QUERY_PARAMS=[// Campaign attribution
|
|
821
|
+
"utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id",// Ad-network click ids
|
|
822
|
+
"gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","dclid",// OAuth / OIDC — see the SECURITY note above
|
|
823
|
+
"client_id","redirect_uri","response_type","scope","state","code","nonce",// Pagination and search
|
|
824
|
+
"page","limit","offset","cursor","per_page","q","search",// Referral
|
|
825
|
+
"ref","referrer"];// ---------------------------------------------------------------------------
|
|
826
|
+
// Pure helpers. No `this`, no globals, no side effects — callable and assertable
|
|
827
|
+
// on their own, which is where the interesting rules live.
|
|
828
|
+
// ---------------------------------------------------------------------------
|
|
829
|
+
// Pulls the allowlisted query params off a URL. Delegates to the SDK's own
|
|
830
|
+
// parser, which lowercases keys (so `?UTM_Source=` and `?utm_source=` land on one
|
|
831
|
+
// attribute), drops empty values, and carries the fallback for browsers without
|
|
832
|
+
// URLSearchParams. Tolerates an empty href, so SSR yields no params rather than
|
|
833
|
+
// throwing.
|
|
834
|
+
var allowedQueryParams=function(a){return queryStringParser(a,ALLOWED_QUERY_PARAMS)};// The captured params, in allowlist order. Ordering comes from the constant
|
|
835
|
+
// rather than a sort: it is deterministic without needing a comparator, and it
|
|
836
|
+
// does not depend on the object's insertion order, so reordering the query string
|
|
837
|
+
// cannot produce a different key.
|
|
838
|
+
var capturedNames=function(a){return ALLOWED_QUERY_PARAMS.filter(function(b){return b in a})};// The dedup key: pathname plus the allowlisted params in a fixed order, so that
|
|
839
|
+
// reordering the query string is not a new page. Params outside the allowlist
|
|
840
|
+
// never make it into `page.params` and so cannot key a view — nor can the hash.
|
|
841
|
+
//
|
|
842
|
+
// Values are re-encoded because queryStringParser hands them back DECODED. A
|
|
843
|
+
// value holding the pair delimiters would otherwise serialize exactly like two
|
|
844
|
+
// separate params — `{q: 'a&search=b'}` and `{q: 'a', search: 'b'}` both becoming
|
|
845
|
+
// `q=a&search=b` — and dedup would treat a real navigation between them as the
|
|
846
|
+
// same page and drop the view. `q`, `search` and `redirect_uri` carry `&` and `=`
|
|
847
|
+
// routinely, so this is reachable rather than theoretical.
|
|
848
|
+
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
|
|
849
|
+
// (`?page=2` is a distinct pagination view), while a hash-only change, or a
|
|
850
|
+
// change confined to params we do not capture, is the same page.
|
|
851
|
+
var isNewPage=function(a,b){return b!==a};var supportsHistoryTracking=function(a){return !!a&&a.history!==void 0&&"function"==typeof a.history.pushState&&"function"==typeof a.addEventListener};// Mirrors the event shape of the public mParticle.logPageView(), but carries the
|
|
852
|
+
// path and query params captured when the navigation was accepted rather than the
|
|
853
|
+
// live location.
|
|
854
|
+
var buildPageViewEvent=function(a){var b=a.params,c=a.hostname,d=a.title,e=a.path;return {messageType:MessageType$1.PageView,name:"PageView",// Params spread first, then the core fields by name, so a core field always
|
|
855
|
+
// wins. No allowlist entry collides with hostname/title/path today; naming
|
|
856
|
+
// them here is what keeps a later addition from silently overwriting one.
|
|
857
|
+
data:__assign(__assign({},b),{hostname:c,title:d,path:e}),eventType:EventType.Unknown}};// ---------------------------------------------------------------------------
|
|
858
|
+
// Window-scoped APV state. Every read and write goes through these helpers, so
|
|
859
|
+
// neither the tracker nor mp-instance touches `window` directly and
|
|
860
|
+
// `typeof window` is checked in exactly one place.
|
|
861
|
+
// ---------------------------------------------------------------------------
|
|
862
|
+
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
|
|
863
|
+
// writers below create it.
|
|
864
|
+
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
|
|
865
|
+
// history methods it patched), then swaps in fresh state. The state object is the
|
|
866
|
+
// authoritative handle, so this reaches trackers whose owning module is gone.
|
|
867
|
+
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};// Log-safe description of a page: the path, plus the NAMES of the captured
|
|
868
|
+
// params. Values are deliberately omitted — verbose logging goes to the console,
|
|
869
|
+
// and session-replay tooling ships console output off-domain, which is not a
|
|
870
|
+
// place for an OAuth code or a consumer's search terms.
|
|
871
|
+
// Only reachable before init() assigns lastPage, which is ahead of any navigation
|
|
872
|
+
// handler being able to run, so this returns nothing rather than a sentinel.
|
|
873
|
+
// ---------------------------------------------------------------------------
|
|
874
|
+
// History patching
|
|
875
|
+
// ---------------------------------------------------------------------------
|
|
876
|
+
// Wraps pushState/replaceState so `onNavigate` runs after the real method, and
|
|
877
|
+
// returns the single function that undoes it — or null when nothing was
|
|
878
|
+
// installed (history is already wrapped, or a frozen/sealed History rejected the
|
|
879
|
+
// assignment). Handing back one undo closure keeps the wrapper and original
|
|
880
|
+
// references out of the tracker entirely: there is no half-patched state for a
|
|
881
|
+
// caller to inspect, and no way to restore the wrong pair.
|
|
882
|
+
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
|
|
883
|
+
// ours after we installed. Clobbering theirs would break their tracking, so
|
|
884
|
+
// leave anything that is no longer ours in place.
|
|
885
|
+
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};// ---------------------------------------------------------------------------
|
|
886
|
+
// Tracker
|
|
887
|
+
// ---------------------------------------------------------------------------
|
|
888
|
+
var PageViewTracker=/** @class */function(){function a(a){this.lastPage=null,this.active=!1,this.pendingNavigations=[],this.undoHistoryPatch=null,this.popStateListener=null,this.mpInstance=a;}return Object.defineProperty(a.prototype,"isActive",{// True while this tracker owns the history patch and is listening for
|
|
889
|
+
// navigations. Flips to false on teardown, including the teardown a
|
|
890
|
+
// successor tracker performs during a handoff. Read-only, and the one thing
|
|
891
|
+
// worth checking on `window.__mpApv__.tracker` from a console.
|
|
892
|
+
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
|
|
893
|
+
// a previous module load, or this same tracker on a repeat
|
|
894
|
+
// mParticle.init(). Their pending navigations are transferred rather than
|
|
895
|
+
// dropped — a route change may have queued a deferred fire that has not
|
|
896
|
+
// flushed yet, and dropping it loses a page view entirely.
|
|
897
|
+
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=patchHistory(function(b){return a.safeHandleNavigation(b)},function(b){return a.log(b)}),this.popStateListener=function(){return a.safeHandleNavigation("popstate")},window.addEventListener("popstate",this.popStateListener),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.popStateListener&&(window.removeEventListener("popstate",this.popStateListener),this.popStateListener=null),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
|
|
898
|
+
// method that is still ours, so one a third party patched over stays
|
|
899
|
+
// installed and keeps firing at a dead tracker. Bail before touching
|
|
900
|
+
// lastPath or queueing a fire the flush would just abort. Guarding here
|
|
901
|
+
// rather than at each wrapper also covers the popstate path.
|
|
902
|
+
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}));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}();
|
|
903
|
+
|
|
904
|
+
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
|
|
905
|
+
// come from PageViewTracker instead, so both emitters attach the same
|
|
906
|
+
// allowlisted query params — and this is the one that matters for campaign
|
|
907
|
+
// attribution, since utm_*/gclid live on the entry URL.
|
|
908
|
+
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
|
|
790
909
|
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
|
|
791
|
-
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(){b.logEvent({messageType:Types.MessageType.PageView,name:"PageView",data:{hostname:window.location.hostname,title:window.document.title},eventType:Types.EventType.Unknown});},this.logCheckoutEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout),g.EventCategory=Types.CommerceEventType.ProductCheckout,g.ProductAction={ProductActionType:Types.ProductActionType.Checkout,CheckoutStep:c,CheckoutOptions:d,ProductList:[]},b.logCommerceEvent(g,e));},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},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,d),a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logRefundEvent=function(c,d,e,f){if(!c)return void a.Logger.error(Messages$3.ErrorMessages.TransactionRequired);var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund),g.EventCategory=Types.CommerceEventType.ProductRefund,g.ProductAction={ProductActionType:Types.ProductActionType.Refund},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,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
|
|
910
|
+
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(){b.logEvent({messageType:Types.MessageType.PageView,name:"PageView",data:__assign(__assign({},allowedQueryParams(getHref())),{hostname:window.location.hostname,title:window.document.title}),eventType:Types.EventType.Unknown});},this.logCheckoutEvent=function(c,d,e,f){var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout),g.EventCategory=Types.CommerceEventType.ProductCheckout,g.ProductAction={ProductActionType:Types.ProductActionType.Checkout,CheckoutStep:c,CheckoutOptions:d,ProductList:[]},b.logCommerceEvent(g,e));},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},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,d),a._Ecommerce.convertTransactionAttributesToProductAction(c,g.ProductAction),b.logCommerceEvent(g,e));},this.logRefundEvent=function(c,d,e,f){if(!c)return void a.Logger.error(Messages$3.ErrorMessages.TransactionRequired);var g=a._Ecommerce.createCommerceEventObject(f);g&&(g.EventName+=a._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund),g.EventCategory=Types.CommerceEventType.ProductRefund,g.ProductAction={ProductActionType:Types.ProductActionType.Refund},g.ProductAction.ProductList=a._Ecommerce.buildProductList(g,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
|
|
792
911
|
// null, resulting in kit forwarding errors on the server.
|
|
793
912
|
// The check for `ProductAction` is required to denote that these are
|
|
794
913
|
// ProductAction events, and not impression or promotions
|
|
@@ -1175,8 +1294,7 @@ try {
|
|
|
1175
1294
|
|
|
1176
1295
|
var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);
|
|
1177
1296
|
|
|
1178
|
-
function
|
|
1179
|
-
e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Store.getUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}}
|
|
1297
|
+
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)a.hasOwnProperty(d)&&isAttributeKeyAllowed(b,d)&&(c[d]=copyUserAttributeValue(a[d]));return c}function buildUserAttributeLists(a,b){var c={};for(var d in a)a.hasOwnProperty(d)&&Array.isArray(a[d])&&isAttributeKeyAllowed(b,d)&&(c[d]=a[d].slice());return c}function buildFilteredUserIdentities(a,b,c){var d={},e=a;for(var f in e)if(e.hasOwnProperty(f)){var g=Types.IdentityType.getIdentityName(c(f));isIdentityAllowed(b,g)&&(d[g]=e[f]);}return d}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,c._Helpers.parseNumber);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}}
|
|
1180
1298
|
|
|
1181
1299
|
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||[]}
|
|
1182
1300
|
|
|
@@ -1233,7 +1351,7 @@ if(o){a._IntegrationCapture.capture();var p=a._IntegrationCapture.getClickIdsAsC
|
|
|
1233
1351
|
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:getHref()||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
|
|
1234
1352
|
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=window.location.href||null),h.CurrencyCode=a._Store.currencyCode;var r=c||a.Identity.getCurrentUser();return appendUserInfo(r,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.ShoppingCart&&(d.sc={pl:convertProductListToV2DTO(c.ShoppingCart.ProductList)}),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};}
|
|
1235
1353
|
|
|
1236
|
-
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(){mParticle._forwardingStatsTimer=setInterval(function(){b();},a._Store.SDKConfig.forwarderStatsTimeout);};}
|
|
1354
|
+
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);};}
|
|
1237
1355
|
|
|
1238
1356
|
function _toPrimitive(input, hint) {
|
|
1239
1357
|
if (_typeof$1(input) !== "object" || input === null) return input;
|
|
@@ -1658,24 +1776,6 @@ var ErrorReportingDispatcher=/** @class */function(){function a(){this.services=
|
|
|
1658
1776
|
|
|
1659
1777
|
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}();
|
|
1660
1778
|
|
|
1661
|
-
var WRAPPED_MARKER="__mpApvWrapped__";// window key under which the single active tracker is stored.
|
|
1662
|
-
// Survives module re-evaluation (Next.js re-executes the bundle on every SPA
|
|
1663
|
-
// navigation, resetting all module-level state, but window persists for the
|
|
1664
|
-
// lifetime of the tab).
|
|
1665
|
-
var WIN_TRACKER_KEY="__mpApvTracker__";// Guards the initial page view so repeated mParticle.init() calls from SPA
|
|
1666
|
-
// re-renders don't fire duplicate logPageView() events for the same page.
|
|
1667
|
-
var WIN_INIT_PV_KEY="__mpApvInitPVLogged__";var PageViewTracker=/** @class */function(){function a(a){this.lastPath=null,this._isActive=!1,this.pendingNavigations=[],this.originalPushState=null,this.originalReplaceState=null,this.pushStateWrapper=null,this.replaceStateWrapper=null,this.popStateListener=null,this.mpInstance=a;}return a.hasInitialPageViewFired=function(){return !!window[WIN_INIT_PV_KEY]},a.markInitialPageViewFired=function(){window[WIN_INIT_PV_KEY]=!0;},a.resetWindowState=function(a){var b=getWindowTracker();b&&b!==a&&b.teardown(),"undefined"!=typeof window&&delete window[WIN_INIT_PV_KEY],setWindowTracker(void 0);},Object.defineProperty(a.prototype,"isActive",{get:function get(){return this._isActive},enumerable:!1,configurable:!0}),a.prototype.isSupportedEnvironment=function(){return "undefined"!=typeof window&&"undefined"!=typeof window.history&&"function"==typeof window.history.pushState&&"function"==typeof window.addEventListener},a.prototype.init=function(){var a=this;if(this.mpInstance.Logger.verbose("mParticle APV: [init] PageViewTracker Init"),!this.isSupportedEnvironment())return void this.mpInstance.Logger.verbose("mParticle APV: [init] unsupported environment (no History API), not starting");// Tear down any tracker left over from a previous module load.
|
|
1668
|
-
// window[WIN_TRACKER_KEY] outlives module re-evaluation; this is the
|
|
1669
|
-
// only way to reach a tracker instance in a dead module scope.
|
|
1670
|
-
// Transfer any pending navigations first so a route change that queued a
|
|
1671
|
-
// deferred fire before module re-evaluation occurs is not silently dropped.
|
|
1672
|
-
var b=getWindowTracker(),c=[];b&&b!==this&&(this.mpInstance.Logger.verbose("mParticle APV: [init] found stale tracker from previous module load \u2014 transferring pending navigations and tearing down"),c=b.takePendingNavigations(),b.teardown()),this._isActive&&(this.mpInstance.Logger.verbose("mParticle APV: [init] starting (teardown-first for idempotency)"),c=__spreadArray(__spreadArray([],c,!0),this.takePendingNavigations(),!0),this.teardown()),this._isActive=!0,this.lastPath=this.getCurrentKey(),this.mpInstance.Logger.verbose("mParticle APV: [init] seeded lastPath: ".concat(this.lastPath)),this.patchHistoryMethods(),this.addNavigationListeners(),setWindowTracker(this),this.mpInstance.Logger.verbose("mParticle APV: [init] patched pushState/replaceState + listening for popstate"),c.forEach(function(b){var c=setTimeout(function(){a.pendingNavigations=a.pendingNavigations.filter(function(a){return a.timeoutId!==c}),a._isActive&&(a.mpInstance._SessionManager.resetSessionTimer(),a.firePageView(b));},0);a.pendingNavigations.push({path:b,timeoutId:c});});},a.prototype.patchHistoryMethods=function(){var a=this,b=window.history.pushState;if(b[WRAPPED_MARKER])return void this.mpInstance.Logger.verbose("mParticle APV: [patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DETECTED");var c=window.history.pushState,d=window.history.replaceState;this.originalPushState=c,this.originalReplaceState=d;var e=function(){for(var b=[],d=0;d<arguments.length;d++)b[d]=arguments[d];var e=c.apply(this,b);return a._isActive&&a.safeHandleNavigation("pushState"),e},f=function(){for(var b=[],c=0;c<arguments.length;c++)b[c]=arguments[c];var e=d.apply(this,b);return a._isActive&&a.safeHandleNavigation("replaceState"),e};Object.defineProperty(e,WRAPPED_MARKER,{value:!0,enumerable:!1}),Object.defineProperty(f,WRAPPED_MARKER,{value:!0,enumerable:!1}),this.pushStateWrapper=e,this.replaceStateWrapper=f;try{window.history.pushState=e,window.history.replaceState=f;}catch(a){this.mpInstance.Logger.verbose("mParticle APV: [error] failed to patch history methods (frozen/sealed), rolling back: ".concat(a));try{window.history.pushState===e&&(window.history.pushState=c),window.history.replaceState===f&&(window.history.replaceState=d);}catch(a){this.mpInstance.Logger.verbose("mParticle APV: [error] failed to restore history methods after patch failure: ".concat(a));}this.pushStateWrapper=null,this.replaceStateWrapper=null,this.originalPushState=null,this.originalReplaceState=null;}},a.prototype.addNavigationListeners=function(){var a=this;this.popStateListener=function(){return a.safeHandleNavigation("popstate")},window.addEventListener("popstate",this.popStateListener);},a.prototype.safeHandleNavigation=function(a){try{this.handleNavigation(a);}catch(b){this.mpInstance.Logger.verbose("mParticle APV: [error] navigation handler threw (".concat(a,"), page view skipped: ").concat(b));}},a.prototype.getCurrentKey=function(){return window.location.pathname},a.prototype.handleNavigation=function(a){var b=this,c=this.getCurrentKey();if(this.mpInstance.Logger.verbose("mParticle APV: [detect] navigation signal (source: ".concat(a,", candidatePath: ").concat(c,", lastPath: ").concat(this.lastPath,")")),c===this.lastPath)return void this.mpInstance.Logger.verbose("mParticle APV: [dedupe] pathname unchanged, skipping (source: ".concat(a,", path: ").concat(c,")"));this.mpInstance.Logger.verbose("mParticle APV: [accept] pathname changed, scheduling fire (source: ".concat(a,", from: ").concat(this.lastPath,", to: ").concat(c,")")),this.lastPath=c;// Snapshot the path now: it is already settled at this point, and a
|
|
1673
|
-
// same-tick navigation would otherwise overwrite window.location
|
|
1674
|
-
// before the deferred flush reads it. The title is intentionally read
|
|
1675
|
-
// later (in the deferred flush) so the router's post-navigation render
|
|
1676
|
-
// commit has a chance to update document.title first.
|
|
1677
|
-
var d=c,e=setTimeout(function(){return b.pendingNavigations=b.pendingNavigations.filter(function(a){return a.timeoutId!==e}),b._isActive?void(b.mpInstance._SessionManager.resetSessionTimer(),b.firePageView(d)):void b.mpInstance.Logger.verbose("mParticle APV: [defer] fire aborted, tracker inactive (torn down before flush)")},0);this.pendingNavigations.push({path:d,timeoutId:e});},a.prototype.firePageView=function(a){var b=window.document.title;this.mpInstance.Logger.verbose("mParticle APV: [fire] deferred flush -> _Events.logEvent(PageView) (path: ".concat(a,", title: ").concat(b,")")),this.mpInstance._Events.logEvent({messageType:MessageType$1.PageView,name:"PageView",data:{hostname:window.location.hostname,title:b,path:a},eventType:EventType.Unknown});},a.prototype.takePendingNavigations=function(){var a=this.pendingNavigations.map(function(a){return a.path});return this.pendingNavigations.forEach(function(a){return clearTimeout(a.timeoutId)}),this.pendingNavigations=[],a},a.prototype.restoreHistoryMethod=function(a,b,c){if(b){var d=null!==c&&window.history[a]===c;d?(window.history[a]=b,this.mpInstance.Logger.verbose("mParticle APV: [teardown] restored original ".concat(a))):this.mpInstance.Logger.verbose("mParticle APV: [teardown] ".concat(a," no longer ours; leaving in place, gating callback to no-op"));}},a.prototype.teardown=function(){this.pendingNavigations.forEach(function(a){return clearTimeout(a.timeoutId)}),this.pendingNavigations=[],this.popStateListener&&(window.removeEventListener("popstate",this.popStateListener),this.popStateListener=null),this.restoreHistoryMethod("pushState",this.originalPushState,this.pushStateWrapper),this.originalPushState=null,this.pushStateWrapper=null,this.restoreHistoryMethod("replaceState",this.originalReplaceState,this.replaceStateWrapper),this.originalReplaceState=null,this.replaceStateWrapper=null,this._isActive=!1,getWindowTracker()===this&&setWindowTracker(void 0);},a}();function getWindowTracker(){return "undefined"==typeof window?void 0:window[WIN_TRACKER_KEY]}function setWindowTracker(a){if("undefined"!=typeof window){var b=window;a?b[WIN_TRACKER_KEY]=a:delete b[WIN_TRACKER_KEY];}}
|
|
1678
|
-
|
|
1679
1779
|
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;/**
|
|
1680
1780
|
* <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>
|
|
1681
1781
|
* <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>
|
|
@@ -1691,7 +1791,7 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Const
|
|
|
1691
1791
|
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,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
|
|
1692
1792
|
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
|
|
1693
1793
|
// to it for it to be run after fetched
|
|
1694
|
-
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{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._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()
|
|
1794
|
+
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{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._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,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
|
|
1695
1795
|
b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/**
|
|
1696
1796
|
* Creates a CCPA Opt Out Consent State.
|
|
1697
1797
|
*
|
|
@@ -1853,7 +1953,7 @@ if((null===(d=c._APIClient)||void 0===d?void 0:d.uploader)&&c._APIClient.uploade
|
|
|
1853
1953
|
var k=c.Identity.getCurrentUser(),l=k?k.getMPID():null,m=k?k.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:m}:c._Store.SDKConfig.identifyRequest,i(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639
|
|
1854
1954
|
var n=i(CaptureIntegrationSpecificIds),o=i(CaptureIntegrationSpecificIdsV2),p=o&&o!==CaptureIntegrationSpecificIdsV2Modes.None||!0===n;if(p){var q;n||o===CaptureIntegrationSpecificIdsV2Modes.All?q="all":o===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(q="roktonly"),c._IntegrationCapture=new IntegrationCapture(q),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
|
|
1855
1955
|
var r=parseConfig(b,"Rokt",181);if(r){var s=null===(e=r.settings)||void 0===e?void 0:e.accountId;c._Store.setRoktAccountId(s);var t=r.userAttributeFilters,u=filteredMparticleUser(l,{userAttributeFilters:t},c),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};// https://go.mparticle.com/work/SQDSDKS-7339
|
|
1856
|
-
c._RoktManager.init(r,u,c.Identity,c._Store,c.Logger,v,c.captureTiming,c._ErrorReportingDispatcher,c._LoggingDispatcher,c._IntegrationCapture);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),i(j)?(c._PageViewTracker
|
|
1956
|
+
c._RoktManager.init(r,u,c.Identity,c._Store,c.Logger,v,c.captureTiming,c._ErrorReportingDispatcher,c._LoggingDispatcher,c._IntegrationCapture);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),i(j)?(!c._PageViewTracker&&(c.Logger.verbose("mParticle APV: [sdk-init] creating new PageViewTracker for this instance"),c._PageViewTracker=new PageViewTracker(c)),hasInitialPageViewFired()?c.Logger.verbose("mParticle APV: [sdk-init] initial page view already logged this page load, skipping"):(markInitialPageViewFired(),c._Events.logPageView()),c._PageViewTracker.init()):c._PageViewTracker&&c._PageViewTracker.teardown(),processIdentityCallback(c,k,l,m);}// We will continue to clear out the ready queue as part of the initial init flow
|
|
1857
1957
|
// if an identify request is unnecessary, such as if there is an existing session
|
|
1858
1958
|
(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
|
|
1859
1959
|
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:
|