@mparticle/web-sdk 2.25.3 → 2.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mparticle.common.js +72 -48
- package/dist/mparticle.esm.js +72 -48
- package/dist/mparticle.js +360 -184
- package/package.json +1 -1
- package/src/apiClient.ts +2 -1
- package/src/audience.ts +9 -0
- package/src/audienceManager.ts +88 -0
- package/src/batchUploader.ts +11 -66
- package/src/constants.ts +4 -0
- package/src/helpers.js +0 -1
- package/src/identity.js +32 -2
- package/src/mockBatchCreator.ts +1 -2
- package/src/mp-instance.js +110 -173
- package/src/nativeSdkHelpers.js +18 -0
- package/src/sdkRuntimeModels.ts +18 -4
- package/src/sessionManager.ts +1 -0
- package/src/store.ts +152 -14
- package/src/uploaders.ts +59 -0
package/dist/mparticle.esm.js
CHANGED
|
@@ -61,11 +61,11 @@ var _TriggerUploadType,MessageType$2={SessionStart:1,SessionEnd:2,PageView:3,Pag
|
|
|
61
61
|
// Continuation of enum above, but in seperate object since we don't expose these to end user
|
|
62
62
|
IdentityType$1.isValid=function(a){if("number"==typeof a)for(var b in IdentityType$1)if(IdentityType$1.hasOwnProperty(b)&&IdentityType$1[b]===a)return !0;return !1},IdentityType$1.getName=function(a){return a===window.mParticle.IdentityType.CustomerId?"Customer ID":a===window.mParticle.IdentityType.Facebook?"Facebook ID":a===window.mParticle.IdentityType.Twitter?"Twitter ID":a===window.mParticle.IdentityType.Google?"Google ID":a===window.mParticle.IdentityType.Microsoft?"Microsoft ID":a===window.mParticle.IdentityType.Yahoo?"Yahoo ID":a===window.mParticle.IdentityType.Email?"Email":a===window.mParticle.IdentityType.FacebookCustomAudienceId?"Facebook App User ID":"Other ID"},IdentityType$1.getIdentityType=function(a){return "other"===a?IdentityType$1.Other:"customerid"===a?IdentityType$1.CustomerId:"facebook"===a?IdentityType$1.Facebook:"twitter"===a?IdentityType$1.Twitter:"google"===a?IdentityType$1.Google:"microsoft"===a?IdentityType$1.Microsoft:"yahoo"===a?IdentityType$1.Yahoo:"email"===a?IdentityType$1.Email:"facebookcustomaudienceid"===a?IdentityType$1.FacebookCustomAudienceId:"other2"===a?IdentityType$1.Other2:"other3"===a?IdentityType$1.Other3:"other4"===a?IdentityType$1.Other4:"other5"===a?IdentityType$1.Other5:"other6"===a?IdentityType$1.Other6:"other7"===a?IdentityType$1.Other7:"other8"===a?IdentityType$1.Other8:"other9"===a?IdentityType$1.Other9:"other10"===a?IdentityType$1.Other10:"mobile_number"===a?IdentityType$1.MobileNumber:"phone_number_2"===a?IdentityType$1.PhoneNumber2:!("phone_number_3"!=a)&&IdentityType$1.PhoneNumber3},IdentityType$1.getIdentityName=function(a){return a===IdentityType$1.Other?"other":a===IdentityType$1.CustomerId?"customerid":a===IdentityType$1.Facebook?"facebook":a===IdentityType$1.Twitter?"twitter":a===IdentityType$1.Google?"google":a===IdentityType$1.Microsoft?"microsoft":a===IdentityType$1.Yahoo?"yahoo":a===IdentityType$1.Email?"email":a===IdentityType$1.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType$1.Other2?"other2":a===IdentityType$1.Other3?"other3":a===IdentityType$1.Other4?"other4":a===IdentityType$1.Other5?"other5":a===IdentityType$1.Other6?"other6":a===IdentityType$1.Other7?"other7":a===IdentityType$1.Other8?"other8":a===IdentityType$1.Other9?"other9":a===IdentityType$1.Other10?"other10":a===IdentityType$1.MobileNumber?"mobile_number":a===IdentityType$1.PhoneNumber2?"phone_number_2":a===IdentityType$1.PhoneNumber3?"phone_number_3":void 0};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10};ProductActionType.getName=function(a){return a===ProductActionType.AddToCart?"Add to Cart":a===ProductActionType.RemoveFromCart?"Remove from Cart":a===ProductActionType.Checkout?"Checkout":a===ProductActionType.CheckoutOption?"Checkout Option":a===ProductActionType.Click?"Click":a===ProductActionType.ViewDetail?"View Detail":a===ProductActionType.Purchase?"Purchase":a===ProductActionType.Refund?"Refund":a===ProductActionType.AddToWishlist?"Add to Wishlist":a===ProductActionType.RemoveFromWishlist?"Remove from Wishlist":"Unknown"},ProductActionType.getExpansionName=function(a){return a===ProductActionType.AddToCart?"add_to_cart":a===ProductActionType.RemoveFromCart?"remove_from_cart":a===ProductActionType.Checkout?"checkout":a===ProductActionType.CheckoutOption?"checkout_option":a===ProductActionType.Click?"click":a===ProductActionType.ViewDetail?"view_detail":a===ProductActionType.Purchase?"purchase":a===ProductActionType.Refund?"refund":a===ProductActionType.AddToWishlist?"add_to_wishlist":a===ProductActionType.RemoveFromWishlist?"remove_from_wishlist":"unknown"};var PromotionActionType={Unknown:0,PromotionView:1,PromotionClick:2};PromotionActionType.getName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},PromotionActionType.getExpansionName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"};var ProfileMessageType={Logout:3},ApplicationTransitionType$1={AppInit:1},Environment={Production:"production",Development:"development"};var Types = {MessageType:MessageType$2,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType$1,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType,Environment:Environment};
|
|
63
63
|
|
|
64
|
-
var version = "2.
|
|
64
|
+
var version = "2.26.1";
|
|
65
65
|
|
|
66
|
-
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"},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
|
|
67
|
-
},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/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
|
|
68
|
-
SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};var ONE_DAY_IN_SECONDS=86400;var MILLIS_IN_ONE_SEC=1e3;
|
|
66
|
+
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout: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
|
|
67
|
+
},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
|
|
68
|
+
SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};var ONE_DAY_IN_SECONDS=86400;var MILLIS_IN_ONE_SEC=1e3;
|
|
69
69
|
|
|
70
70
|
/******************************************************************************
|
|
71
71
|
Copyright (c) Microsoft Corporation.
|
|
@@ -429,6 +429,8 @@ var BaseVault=/** @class */function(){/**
|
|
|
429
429
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
430
430
|
var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.parse(a):null,this.logger.verbose("Retrieving item from Storage: ".concat(a)),this.contents},a.prototype.purge=function(){this.logger.verbose("Purging Storage"),this.contents=null,this.storageObject.removeItem(this._storageKey);},a}();var LocalStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.localStorage,c)||this}return __extends(b,a),b}(BaseVault);var SessionStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.sessionStorage,c)||this}return __extends(b,a),b}(BaseVault);
|
|
431
431
|
|
|
432
|
+
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(){return c=new XMLHttpRequest,[2/*return*/,new Promise(function(d,e){c.onreadystatechange=function(){4!==c.readyState||(200<=c.status&&300>c.status?d(c):e(c));},c.open("post",a),c.send(b);})]})})},b}(AsyncUploader);
|
|
433
|
+
|
|
432
434
|
/**
|
|
433
435
|
* BatchUploader contains all the logic to store/retrieve events and batches
|
|
434
436
|
* to/from persistence, and upload batches to mParticle.
|
|
@@ -447,7 +449,8 @@ var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.p
|
|
|
447
449
|
* Creates an instance of a BatchUploader
|
|
448
450
|
* @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
|
|
449
451
|
* @param {number} uploadInterval - the desired upload interval in milliseconds
|
|
450
|
-
*/function a(b,c){var d;this.offlineStorageEnabled=!1,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable(),this.offlineStorageEnabled&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events"),{logger:b.Logger}),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches"),{logger:b.Logger}),(d=this.eventsQueuedForProcessing).push.apply(d,this.eventVault.retrieve()));var e=this.mpInstance._Store,f=e.SDKConfig,g=e.devToken,h=this.mpInstance._Helpers.createServiceUrl(f.v3SecureServiceUrl,g);this.uploadUrl="".concat(h,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}return a.prototype.isOfflineStorageAvailable=function(){var a=this.mpInstance,b=a._Helpers.getFeatureFlag,c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);//
|
|
452
|
+
*/function a(b,c){var d;this.offlineStorageEnabled=!1,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable(),this.offlineStorageEnabled&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events"),{logger:b.Logger}),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches"),{logger:b.Logger}),(d=this.eventsQueuedForProcessing).push.apply(d,this.eventVault.retrieve()));var e=this.mpInstance._Store,f=e.SDKConfig,g=e.devToken,h=this.mpInstance._Helpers.createServiceUrl(f.v3SecureServiceUrl,g);this.uploadUrl="".concat(h,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}return a.prototype.isOfflineStorageAvailable=function(){var a=this.mpInstance,b=a._Helpers.getFeatureFlag,c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);// https://go.mparticle.com/work/SQDSDKS-6317
|
|
453
|
+
// TODO: Handle cases where Local Storage is unavailable
|
|
451
454
|
// Potentially shared between Vault and Persistence as well
|
|
452
455
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
453
456
|
return e>=f},a.prototype.addEventListeners=function(){var a=this;// visibility change is a document property, not window
|
|
@@ -455,9 +458,10 @@ document.addEventListener("visibilitychange",function(){a.prepareAndUpload(!1,a.
|
|
|
455
458
|
for(var d,e=[],f=new Map,g=0,h=a;g<h.length;g++){//on initial startup, there may be events logged without an mpid.
|
|
456
459
|
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k;return __generator(this,function(l){switch(l.label){case 0:return d=this.mpInstance.Identity.getCurrentUser(),e=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),f=[],isEmpty(e)||(f=a.createNewBatches(e,d,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((i=this.batchesQueuedForProcessing).unshift.apply(i,this.batchVault.retrieve()),this.batchVault.purge()),isEmpty(f)||(j=this.batchesQueuedForProcessing).push.apply(j,f),g=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],[4/*yield*/,this.uploadBatches(this.mpInstance.Logger,g,c)];case 1:return h=l.sent(),isEmpty(h)||(k=this.batchesQueuedForProcessing).unshift.apply(k,h),!c&&this.offlineStorageEnabled&&this.batchVault&&(this.batchVault.store(this.batchesQueuedForProcessing),this.batchesQueuedForProcessing=[]),b&&this.triggerUploadInterval(b,!1),[2/*return*/]}})})},a.prototype.uploadBatches=function(b,c,d){return __awaiter(this,void 0,void 0,function(){var e,f,g,h,j,k;return __generator(this,function(i){switch(i.label){case 0:if(e=c.filter(function(a){return !isEmpty(a.events)}),isEmpty(e))return [2/*return*/,null];b.verbose("Uploading batches: ".concat(JSON.stringify(e))),b.verbose("Batch count: ".concat(e.length)),f=0,i.label=1;case 1:return f<e.length?(g={method:"POST",headers:{Accept:a.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(e[f])},!(d&&this.isBeaconAvailable()))?[3/*break*/,2]:(h=new Blob([g.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,h),[3/*break*/,5]):[3/*break*/,6];case 2:return i.trys.push([2,4,,5]),[4/*yield*/,this.uploader.upload(g)];case 3:if(j=i.sent(),200<=j.status&&300>j.status)b.verbose("Upload success for request ID: ".concat(e[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later
|
|
457
460
|
return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
458
|
-
return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a}();
|
|
461
|
+
return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a}();
|
|
459
462
|
|
|
460
|
-
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){
|
|
463
|
+
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){// https://go.mparticle.com/work/SQDSDKS-6317
|
|
464
|
+
var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
461
465
|
this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(b,c){c.forEach(function(c){c.MPID||a._ServerModel.appendUserInfo(b,c);});},this.sendEventToServer=function(c,d){var e=a._Helpers.extend({shouldUploadEvent:!0},d);if(a._Store.webviewBridgeEnabled)return void a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent,JSON.stringify(c));var f,g=a.Identity.getCurrentUser();// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
|
|
462
466
|
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
|
|
463
467
|
return (g&&(f=g.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),!f||a._Store.requireDelay||!a._Store.configurationLoaded)?(a.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void a._Store.eventQueue.push(c)):void(this.processQueuedEvents(),isEmpty(c)||(e.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&a._Forwarders.sendEventToForwarders(c))))},this.sendBatchForwardingStatsToServer=function(b,c){var d,e;try{d=a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken),e={uuid:a._Helpers.generateUniqueId(),data:b},c&&(c.open("post",d+"/Forwarding"),c.send(JSON.stringify(e)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.sendSingleForwardingStatsToServer=function(b){var c,d;try{var e=function(){4===f.readyState&&202===f.status&&a.Logger.verbose("Successfully sent "+f.statusText+" from server");},f=a._Helpers.createXHR(e);c=a._Helpers.createServiceUrl(a._Store.SDKConfig.v1SecureServiceUrl,a._Store.devToken),d=b,f&&(f.open("post",c+"/Forwarding"),f.send(JSON.stringify(d)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.prepareForwardingStats=function(b,d){var e,f=a._Forwarders.getForwarderStatsQueue();b&&b.isVisible&&(e={mid:b.id,esid:b.eventSubscriptionId,n:d.EventName,attrs:d.EventAttributes,sdk:d.SDKVersion,dt:d.EventDataType,et:d.EventCategory,dbg:d.Debug,ct:d.Timestamp,eec:d.ExpandedEventCount,dp:d.DataPlan},a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(f.push(e),a._Forwarders.setForwarderStatsQueue(f)):c.sendSingleForwardingStatsToServer(e));};}
|
|
@@ -489,9 +493,9 @@ for(c in a)// Prevent never-ending loop
|
|
|
489
493
|
(d=h[c],e=a[c],h!==e)&&(l&&e&&(m.isPlainObject(e)||(f=m.isArray(e)))?(f?(f=!1,g=d&&m.isArray(d)?d:[]):g=d&&m.isPlainObject(d)?d:{},h[c]=b.extend(l,g,e)):void 0!==e&&(h[c]=e));// Recurse if we're merging plain objects or arrays
|
|
490
494
|
// Return the modified object
|
|
491
495
|
return h},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){var d=[];if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=Types.IdentityType.getIdentityType(e);if(!b.inArray(c,f)){var g={Type:f,Identity:a[e]};f===Types.IdentityType.CustomerId?d.unshift(g):d.push(g);}}return d},this.filterUserIdentitiesForForwarders=function(a,c){var d={};if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=KitFilterHelper.hashUserIdentity(Types.IdentityType.getIdentityType(e));b.inArray(c,f)||(d[e]=a[e]);}return d},this.filterUserAttributes=function(a,c){var d={};if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=KitFilterHelper.hashUserAttribute(e);b.inArray(c,f)||(d[e]=a[e]);}return d},this.isFilteredUserAttribute=function(a,c){var d=KitFilterHelper.hashUserAttribute(a);return c&&b.inArray(c,d)},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
|
|
492
|
-
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.createProductStorageName=function(a){return a?StorageNames$1.currentStorageProductsName+"_"+a:StorageNames$1.currentStorageProductsName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.
|
|
496
|
+
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.createProductStorageName=function(a){return a?StorageNames$1.currentStorageProductsName+"_"+a:StorageNames$1.currentStorageProductsName},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;}
|
|
493
497
|
|
|
494
|
-
var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge
|
|
498
|
+
var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge
|
|
495
499
|
return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge
|
|
496
500
|
// TODO: what to do about people setting things on mParticle itself?
|
|
497
501
|
// android
|
|
@@ -540,8 +544,14 @@ return a._Helpers.parseNumber(b)};}
|
|
|
540
544
|
|
|
541
545
|
function createSDKConfig(a){// TODO: Refactor to create a default config object
|
|
542
546
|
var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];return b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
|
|
543
|
-
function Store(a,b,c){var d=this,e={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},// Placeholder for in-memory persistence model
|
|
544
|
-
persistenceData:{cu:null,gs:{sid:null,ie:null,sa:null,ss:null,dt:null,av:null,cgid:null,das:null,ia:null,c:null,csm:null,les:null,ssd:null},l:null}};for(var
|
|
547
|
+
function Store(a,b,c){var d=this,e=b._Helpers,f=e.createMainStorageName,g=e.createProductStorageName,h=b._NativeSdkHelpers.isWebviewEnabled,i={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},// Placeholder for in-memory persistence model
|
|
548
|
+
persistenceData:{cu:null,gs:{sid:null,ie:null,sa:null,ss:null,dt:null,av:null,cgid:null,das:null,ia:null,c:null,csm:null,les:null,ssd:null},l:null}};for(var j in i)this[j]=i[j];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var k=processBaseUrls(a,this.SDKConfig.flags,c);for(var l in k)this.SDKConfig[l]=k[l];if(a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var m=a.identityCallback;b._Helpers.Validators.isFunction(m)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(m)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var n=a.dataPlan;n.planId&&(isDataPlanSlug(n.planId)?this.SDKConfig.dataPlan.PlanId=n.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),n.planVersion&&(isNumber(n.planVersion)?this.SDKConfig.dataPlan.PlanVersion=n.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var o=a.dataPlanOptions;o.hasOwnProperty("dataPlanVersion")&&o.hasOwnProperty("blockUserAttributes")&&o.hasOwnProperty("blockEventAttributes")&&o.hasOwnProperty("blockEvents")&&o.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return a?d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a].fst?d.persistenceData[a].fst:null:null},this.setFirstSeenTime=function(a,c){if(a){var e=c||new Date().getTime();d.persistenceData&&(!d.persistenceData[a]&&(d.persistenceData[a]={}),!d.persistenceData[a].fst&&(d.persistenceData[a].fst=e,b._Persistence.savePersistence(d.persistenceData)));}},this.getLastSeenTime=function(a){if(!a)return null;// // https://go.mparticle.com/work/SQDSDKS-6315
|
|
549
|
+
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a].lst?d.persistenceData[a].lst:null},this.setLastSeenTime=function(a,c){if(a){var e=c||new Date().getTime();d.persistenceData&&(!d.persistenceData[a]&&(d.persistenceData[a]={}),!d.persistenceData[a].lst&&(d.persistenceData[a].lst=e,b._Persistence.savePersistence(d.persistenceData)));}},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var c=a.workspaceToken,e=a.requiredWebviewBridgeName;// We should reprocess the flags in case they have changed when we request an updated config
|
|
550
|
+
// such as if the SDK is being self-hosted and the flags are different on the server config
|
|
551
|
+
// https://go.mparticle.com/work/SQDSDKS-6317
|
|
552
|
+
d.SDKConfig.flags=processFlags(a),c?d.SDKConfig.workspaceToken=c:b.Logger.warning("You should have a workspaceToken on your config object for security purposes."),d.storageName=f(c),d.prodStorageName=g(c),d.SDKConfig.requiredWebviewBridgeName=e||c,d.webviewBridgeEnabled=h(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317
|
|
553
|
+
function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b):{};// https://go.mparticle.com/work/SQDSDKS-6317
|
|
554
|
+
// Passed in config flags take priority over defaults
|
|
545
555
|
}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
|
|
546
556
|
if(!c)return {};// Set default baseUrls
|
|
547
557
|
// When direct URL routing is false, update baseUrls based custom urls
|
|
@@ -710,7 +720,10 @@ for(var d in b)b[d].expireTimestamp<c&&delete b[d];a.store(b);};var tryCacheIden
|
|
|
710
720
|
var h=hasValidCachedIdentity(g,a,b);// If Identity is cached, then immediately parse the identity response
|
|
711
721
|
if(h){var i=getCachedIdentity(g,a,b);return c(i,d,e,f,g,a,!0),!0}return !1};
|
|
712
722
|
|
|
713
|
-
var
|
|
723
|
+
var AudienceManager=/** @class */function(){function a(a,b,c){this.url="",this.logger=c,this.url="https://".concat(a).concat(b,"/audience"),this.userAudienceAPI=window.fetch?new FetchUploader(this.url):new XHRUploader(this.url);}return a.prototype.sendGetUserAudienceRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c,d,e,f,g,h;return __generator(this,function(i){switch(i.label){case 0:this.logger.verbose("Fetching user audiences from server"),c={method:"GET",headers:{Accept:"*/*"}},d="".concat(this.url,"?mpid=").concat(a),i.label=1;case 1:return i.trys.push([1,6,,7]),[4/*yield*/,this.userAudienceAPI.upload(c,d)];case 2:return (e=i.sent(),!(200<=e.status&&300>e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate.
|
|
724
|
+
throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}();
|
|
725
|
+
|
|
726
|
+
var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,FeatureFlags$1=Constants.FeatureFlags,ErrorMessages=Messages$2.ErrorMessages,_Constants$IdentityMe=Constants.IdentityMethods,Identify=_Constants$IdentityMe.Identify,Modify$1=_Constants$IdentityMe.Modify,Login=_Constants$IdentityMe.Login,Logout=_Constants$IdentityMe.Logout;function Identity(t){var r=this;/**
|
|
714
727
|
* Invoke these methods on the mParticle.Identity object.
|
|
715
728
|
* Example: mParticle.Identity.getCurrentUser().
|
|
716
729
|
* @class mParticle.Identity
|
|
@@ -726,48 +739,48 @@ var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,_Constants$Ide
|
|
|
726
739
|
*/ // send a user identity change request on identify, login, logout, modify when any values change.
|
|
727
740
|
// compare what identities exist vs what is previously was for the specific user if they were in memory before.
|
|
728
741
|
// if it's the first time the user is logging in, send a user identity change request with
|
|
729
|
-
this.idCache=null,this.checkIdentitySwap=function(e,s
|
|
730
|
-
combineUserIdentities:function combineUserIdentities(e,
|
|
731
|
-
!1!==
|
|
742
|
+
this.idCache=null,this.audienceManager=null,this.checkIdentitySwap=function(e,r,s){if(e&&r&&e!==r){var i=t._Persistence.getPersistence();i&&(i.cu=r,i.gs.csm=s,t._Persistence.savePersistence(i));}},this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(e,r,s){t.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent+": "+s);var i=t._Helpers.Validators.validateIdentities(e,s);if(!i.valid)return t.Logger.error("ERROR: "+i.error),{valid:!1,error:i.error};if(r&&!t._Helpers.Validators.isFunction(r)){var n="The optional callback must be a function. You tried entering a(n) "+_typeof(r);return t.Logger.error(n),{valid:!1,error:n}}return {valid:!0}},createIdentityRequest:function createIdentityRequest(e,r,s,i,n,a,o){var d={client_sdk:{platform:r,sdk_vendor:s,sdk_version:i},context:a,environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:t._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),previous_mpid:o||null,known_identities:createKnownIdentities(e,n)};return d},createModifyIdentityRequest:function createModifyIdentityRequest(e,r,s,i,n,a){return {client_sdk:{platform:s,sdk_vendor:i,sdk_version:n},context:a,environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:t._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),identity_changes:this.createIdentityChanges(e,r)}},createIdentityChanges:function createIdentityChanges(e,r){var s,i=[];if(r&&t._Helpers.isObject(r)&&e&&t._Helpers.isObject(e))for(s in r)i.push({old_value:e[s]||null,new_value:r[s],identity_type:s});return i},// takes 2 UI objects keyed by name, combines them, returns them keyed by type
|
|
743
|
+
combineUserIdentities:function combineUserIdentities(e,r){var s={},i=t._Helpers.extend(e,r);for(var n in i){var a=Types.IdentityType.getIdentityType(n);// this check removes anything that is not whitelisted as an identity type
|
|
744
|
+
!1!==a&&0<=a&&(s[Types.IdentityType.getIdentityType(n)]=i[n]);}return s},createAliasNetworkRequest:function createAliasNetworkRequest(e){return {request_id:t._Helpers.generateUniqueId(),request_type:"alias",environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",api_key:t._Store.devToken,data:{destination_mpid:e.destinationMpid,source_mpid:e.sourceMpid,start_unixtime_ms:e.startTime,end_unixtime_ms:e.endTime,scope:e.scope,device_application_stamp:t._Store.deviceId}}},convertAliasToNative:function convertAliasToNative(e){return {DestinationMpid:e.destinationMpid,SourceMpid:e.sourceMpid,StartUnixtimeMs:e.startTime,EndUnixtimeMs:e.endTime}},convertToNative:function convertToNative(e){var t=[];if(e&&e.userIdentities){for(var r in e.userIdentities)e.userIdentities.hasOwnProperty(r)&&t.push({Type:Types.IdentityType.getIdentityType(r),Identity:e.userIdentities[r]});return {UserIdentities:t}}}},this.IdentityAPI={HTTPCodes:HTTPCodes$2,/**
|
|
732
745
|
* Initiate a logout request to the mParticle server
|
|
733
746
|
* @method identify
|
|
734
747
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
735
748
|
* @param {Function} [callback] A callback function that is called when the identify request completes
|
|
736
|
-
*/identify:function identify(e,
|
|
749
|
+
*/identify:function identify(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Identify);if(n&&(i=n.getMPID()),a.valid){var o=t._Identity.IdentityRequest.createIdentityRequest(e,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,i);if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var d=tryCacheIdentity(o.known_identities,r.idCache,r.parseIdentityResponse,i,s,e,Identify);if(d)return}t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Identify request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(o,Identify,s,e,r.parseIdentityResponse,i,o.known_identities):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
737
750
|
* Initiate a logout request to the mParticle server
|
|
738
751
|
* @method logout
|
|
739
752
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
740
753
|
* @param {Function} [callback] A callback function that is called when the logout request completes
|
|
741
|
-
*/logout:function logout(e,
|
|
754
|
+
*/logout:function logout(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Logout);if(n&&(i=n.getMPID()),a.valid){var o,d=t._Identity.IdentityRequest.createIdentityRequest(e,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,i);t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Logout request sent to native sdk")):(t._IdentityAPIClient.sendIdentityRequest(d,Logout,s,e,r.parseIdentityResponse,i),o=t._ServerModel.createEventObject({messageType:Types.MessageType.Profile}),o.ProfileMessageType=Types.ProfileMessageType.Logout,t._Store.activeForwarders.length&&t._Store.activeForwarders.forEach(function(e){e.logOut&&e.logOut(o);})):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
742
755
|
* Initiate a login request to the mParticle server
|
|
743
756
|
* @method login
|
|
744
757
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
745
758
|
* @param {Function} [callback] A callback function that is called when the login request completes
|
|
746
|
-
*/login:function login(e,
|
|
759
|
+
*/login:function login(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Login);if(n&&(i=n.getMPID()),a.valid){var o=t._Identity.IdentityRequest.createIdentityRequest(e,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,i);if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var d=tryCacheIdentity(o.known_identities,r.idCache,r.parseIdentityResponse,i,s,e,Login);if(d)return}t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Login request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(o,Login,s,e,r.parseIdentityResponse,i,o.known_identities):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
747
760
|
* Initiate a modify request to the mParticle server
|
|
748
761
|
* @method modify
|
|
749
762
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
750
763
|
* @param {Function} [callback] A callback function that is called when the modify request completes
|
|
751
|
-
*/modify:function modify(e,
|
|
764
|
+
*/modify:function modify(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Modify$1);n&&(i=n.getMPID());var o=e&&e.userIdentities?e.userIdentities:{};if(a.valid){var d=t._Identity.IdentityRequest.createModifyIdentityRequest(n?n.getUserIdentities().userIdentities:{},o,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.context);t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Modify request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(d,Modify$1,s,e,r.parseIdentityResponse,i,d.known_identities):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
752
765
|
* Returns a user object with methods to interact with the current user
|
|
753
766
|
* @method getCurrentUser
|
|
754
767
|
* @return {Object} the current user object
|
|
755
|
-
*/getCurrentUser:function getCurrentUser(){var e;return t._Store?(e=t._Store.mpid,e?(e=t._Store.mpid.slice(),
|
|
768
|
+
*/getCurrentUser:function getCurrentUser(){var e;return t._Store?(e=t._Store.mpid,e?(e=t._Store.mpid.slice(),r.mParticleUser(e,t._Store.isLoggedIn)):t._Store.webviewBridgeEnabled?r.mParticleUser():null):null},/**
|
|
756
769
|
* Returns a the user object associated with the mpid parameter or 'null' if no such
|
|
757
770
|
* user exists
|
|
758
771
|
* @method getUser
|
|
759
772
|
* @param {String} mpid of the desired user
|
|
760
773
|
* @return {Object} the user for mpid
|
|
761
|
-
*/getUser:function getUser(e){var
|
|
774
|
+
*/getUser:function getUser(e){var s=t._Persistence.getPersistence();return s?s[e]&&!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(e)?r.mParticleUser(e):null:null},/**
|
|
762
775
|
* Returns all users, including the current user and all previous users that are stored on the device.
|
|
763
776
|
* @method getUsers
|
|
764
777
|
* @return {Array} array of users
|
|
765
|
-
*/getUsers:function getUsers(){var e=t._Persistence.getPersistence(),
|
|
778
|
+
*/getUsers:function getUsers(){var e=t._Persistence.getPersistence(),s=[];if(e)for(var i in e)Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(i)||s.push(r.mParticleUser(i));return s.sort(function(e,t){var r=e.getLastSeenTime()||0,s=t.getLastSeenTime()||0;return r>s?-1:1}),s},/**
|
|
766
779
|
* Initiate an alias request to the mParticle server
|
|
767
780
|
* @method aliasUsers
|
|
768
781
|
* @param {Object} aliasRequest object representing an AliasRequest
|
|
769
782
|
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
|
|
770
|
-
*/aliasUsers:function aliasUsers(e,
|
|
783
|
+
*/aliasUsers:function aliasUsers(e,r){var s;if(e.destinationMpid&&e.sourceMpid||(s=Messages$2.ValidationMessages.AliasMissingMpid),e.destinationMpid===e.sourceMpid&&(s=Messages$2.ValidationMessages.AliasNonUniqueMpid),e.startTime&&e.endTime||(s=Messages$2.ValidationMessages.AliasMissingTime),e.startTime>e.endTime&&(s=Messages$2.ValidationMessages.AliasStartBeforeEndTime),s)return t.Logger.warning(s),void t._Helpers.invokeAliasCallback(r,HTTPCodes$2.validationIssue,s);if(!t._Helpers.canLog())t._Helpers.invokeAliasCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),t.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(t._Identity.IdentityRequest.convertAliasToNative(e))),t._Helpers.invokeAliasCallback(r,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {t.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+e.sourceMpid+" -> "+e.destinationMpid);var i=t._Identity.IdentityRequest.createAliasNetworkRequest(e);t._IdentityAPIClient.sendAliasRequest(i,r);}},/**
|
|
771
784
|
Create a default AliasRequest for 2 MParticleUsers. This will construct the request
|
|
772
785
|
using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
|
|
773
786
|
|
|
@@ -781,12 +794,12 @@ combineUserIdentities:function combineUserIdentities(e,s){var r={},i=t._Helpers.
|
|
|
781
794
|
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
|
|
782
795
|
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
|
|
783
796
|
validation that the startTime must be less than the endTime
|
|
784
|
-
*/createAliasRequest:function createAliasRequest(e,
|
|
785
|
-
return
|
|
797
|
+
*/createAliasRequest:function createAliasRequest(e,r){try{if(!r||!e)return t.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var s=e.getFirstSeenTime();s||t.Identity.getUsers().forEach(function(e){e.getFirstSeenTime()&&(!s||e.getFirstSeenTime()<s)&&(s=e.getFirstSeenTime());});var i=new Date().getTime()-1e3*(60*(60*(24*t._Store.SDKConfig.aliasMaxWindow))),n=e.getLastSeenTime()||new Date().getTime();//if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed
|
|
798
|
+
return s<i&&(s=i,n<s&&t.Logger.warning("Source User has not been seen in the last "+t._Store.SDKConfig.maxAliasWindow+" days, Alias Request will likely fail")),{destinationMpid:r.getMPID(),sourceMpid:e.getMPID(),startTime:s,endTime:n}}catch(r){return t.Logger.error("There was a problem with creating an alias request: "+r),null}}},this.mParticleUser=function(e,r){var s=this;return {/**
|
|
786
799
|
* Get user identities for current user
|
|
787
800
|
* @method getUserIdentities
|
|
788
801
|
* @return {Object} an object with userIdentities as its key
|
|
789
|
-
*/getUserIdentities:function getUserIdentities(){var
|
|
802
|
+
*/getUserIdentities:function getUserIdentities(){var r={},s=t._Persistence.getUserIdentities(e);for(var i in s)s.hasOwnProperty(i)&&(r[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(i))]=s[i]);return {userIdentities:r}},/**
|
|
790
803
|
* Get the MPID of the current user
|
|
791
804
|
* @method getMPID
|
|
792
805
|
* @return {String} the current user MPID as a string
|
|
@@ -803,38 +816,38 @@ return r<i&&(r=i,n<r&&t.Logger.warning("Source User has not been seen in the las
|
|
|
803
816
|
* @method setUserAttribute
|
|
804
817
|
* @param {String} key
|
|
805
818
|
* @param {String} value
|
|
806
|
-
*/setUserAttribute:function setUserAttribute(
|
|
819
|
+
*/setUserAttribute:function setUserAttribute(r,i){var n,a,o,d;if(t._SessionManager.resetSessionTimer(),t._Helpers.canLog()){if(!t._Helpers.Validators.isValidAttributeValue(i))return void t.Logger.error(Messages$2.ErrorMessages.BadAttribute);if(!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:r,value:i}));else {n=t._Persistence.getPersistence(),a=this.getAllUserAttributes();var g=t._Helpers.findKeyInObject(a,r);g?(d=!1,o=a[g],delete a[g]):d=!0,a[r]=i,n&&n[e]&&(n[e].ua=a,t._Persistence.savePersistence(n,e)),s.sendUserAttributeChangeEvent(r,i,o,d,!1,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",r,i);}}},/**
|
|
807
820
|
* Set multiple user attributes
|
|
808
821
|
* @method setUserAttributes
|
|
809
822
|
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
|
|
810
|
-
*/setUserAttributes:function setUserAttributes(e){if(t._SessionManager.resetSessionTimer(),!t._Helpers.isObject(e))t.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof(e));else if(t._Helpers.canLog())for(var
|
|
823
|
+
*/setUserAttributes:function setUserAttributes(e){if(t._SessionManager.resetSessionTimer(),!t._Helpers.isObject(e))t.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof(e));else if(t._Helpers.canLog())for(var r in e)e.hasOwnProperty(r)&&this.setUserAttribute(r,e[r]);},/**
|
|
811
824
|
* Removes a specific user attribute
|
|
812
825
|
* @method removeUserAttribute
|
|
813
826
|
* @param {String} key
|
|
814
|
-
*/removeUserAttribute:function removeUserAttribute(
|
|
827
|
+
*/removeUserAttribute:function removeUserAttribute(r){var i,n;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:r,value:null}));else {i=t._Persistence.getPersistence(),n=this.getAllUserAttributes();var a=t._Helpers.findKeyInObject(n,r);a&&(r=a);var o=n[r]?n[r].toString():null;delete n[r],i&&i[e]&&(i[e].ua=n,t._Persistence.savePersistence(i,e)),s.sendUserAttributeChangeEvent(r,null,o,!1,!0,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",r,null);}},/**
|
|
815
828
|
* Sets a list of user attributes
|
|
816
829
|
* @method setUserAttributeList
|
|
817
830
|
* @param {String} key
|
|
818
831
|
* @param {Array} value an array of values
|
|
819
|
-
*/setUserAttributeList:function setUserAttributeList(
|
|
832
|
+
*/setUserAttributeList:function setUserAttributeList(r,n){var a,o,d,g,l;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(!Array.isArray(n))return void t.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a "+("undefined"==typeof value?"undefined":_typeof(value)));var u=n.slice();if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList,JSON.stringify({key:r,value:u}));else {a=t._Persistence.getPersistence(),o=this.getAllUserAttributes();var c=t._Helpers.findKeyInObject(o,r);// If the new attributeList length is different previous, then there is a change event.
|
|
820
833
|
// Loop through new attributes list, see if they are all in the same index as previous user attributes list
|
|
821
834
|
// If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value
|
|
822
|
-
if(
|
|
835
|
+
if(c?(g=!1,d=o[c],delete o[c]):g=!0,o[r]=u,a&&a[e]&&(a[e].ua=o,t._Persistence.savePersistence(a,e)),!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var p=0;p<n.length;p++)if(d[p]!==n[p]){l=!0;break}l&&s.sendUserAttributeChangeEvent(r,n,d,g,!1,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",r,u);}},/**
|
|
823
836
|
* Removes all user attributes
|
|
824
837
|
* @method removeAllUserAttributes
|
|
825
|
-
*/removeAllUserAttributes:function removeAllUserAttributes(){var e;if(t._SessionManager.resetSessionTimer(),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(e=this.getAllUserAttributes(),t._Forwarders.initForwarders(
|
|
838
|
+
*/removeAllUserAttributes:function removeAllUserAttributes(){var e;if(t._SessionManager.resetSessionTimer(),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(e=this.getAllUserAttributes(),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),e)for(var r in e)e.hasOwnProperty(r)&&t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",r,null),this.removeUserAttribute(r);},/**
|
|
826
839
|
* Returns all user attribute keys that have values that are arrays
|
|
827
840
|
* @method getUserAttributesLists
|
|
828
841
|
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
|
|
829
|
-
*/getUserAttributesLists:function getUserAttributesLists(){var e,t={};for(var
|
|
842
|
+
*/getUserAttributesLists:function getUserAttributesLists(){var e,t={};for(var r in e=this.getAllUserAttributes(),e)e.hasOwnProperty(r)&&Array.isArray(e[r])&&(t[r]=e[r].slice());return t},/**
|
|
830
843
|
* Returns all user attributes
|
|
831
844
|
* @method getAllUserAttributes
|
|
832
845
|
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
|
|
833
|
-
*/getAllUserAttributes:function getAllUserAttributes(){var
|
|
846
|
+
*/getAllUserAttributes:function getAllUserAttributes(){var r={},s=t._Persistence.getAllUserAttributes(e);if(s)for(var i in s)s.hasOwnProperty(i)&&(r[i]=Array.isArray(s[i])?s[i].slice():s[i]);return r},/**
|
|
834
847
|
* Returns the cart object for the current user
|
|
835
848
|
* @method getCart
|
|
836
849
|
* @return a cart object
|
|
837
|
-
*/getCart:function getCart(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"),
|
|
850
|
+
*/getCart:function getCart(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"),s.mParticleUserCart(e)},/**
|
|
838
851
|
* Returns the Consent State stored locally for this user.
|
|
839
852
|
* @method getConsentState
|
|
840
853
|
* @return a ConsentState object
|
|
@@ -842,28 +855,33 @@ if(p?(g=!1,d=a[p],delete a[p]):g=!0,a[s]=u,o&&o[e]&&(o[e].ua=a,t._Persistence.sa
|
|
|
842
855
|
* Sets the Consent State stored locally for this user.
|
|
843
856
|
* @method setConsentState
|
|
844
857
|
* @param {Object} consent state
|
|
845
|
-
*/setConsentState:function setConsentState(
|
|
858
|
+
*/setConsentState:function setConsentState(r){t._Persistence.saveUserConsentStateToCookies(e,r),t._Forwarders.initForwarders(this.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._CookieSyncManager.attemptCookieSync(null,this.getMPID());},isLoggedIn:function isLoggedIn(){return r},getLastSeenTime:function getLastSeenTime(){return t._Persistence.getLastSeenTime(e)},getFirstSeenTime:function getFirstSeenTime(){return t._Persistence.getFirstSeenTime(e)},/**
|
|
859
|
+
* Get user audiences
|
|
860
|
+
* @method getuserAudiences
|
|
861
|
+
* @param {Function} [callback] A callback function that is invoked when the user audience request completes
|
|
862
|
+
*/getUserAudiences:function getUserAudiences(r){// user audience API is feature flagged
|
|
863
|
+
return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audienceManager&&(s.audienceManager=new AudienceManager(t._Store.SDKConfig.userAudienceUrl,t._Store.devToken,t.Logger,e)),s.audienceManager.sendGetUserAudienceRequest(e,r)):void t.Logger.error(ErrorMessages.AudienceAPINotEnabled)}}},this.mParticleUserCart=function(e){return {/**
|
|
846
864
|
* Adds a cart product to the user cart
|
|
847
865
|
* @method add
|
|
848
866
|
* @param {Object} product the product
|
|
849
867
|
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
|
|
850
868
|
* @deprecated
|
|
851
|
-
*/add:function add(s
|
|
869
|
+
*/add:function add(r,s){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().add() will be removed in future releases");var i,n,a;if(a=Array.isArray(r)?r.slice():[r],a.forEach(function(e){e.Attributes=t._Helpers.sanitizeAttributes(e.Attributes);}),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.AddToCart,JSON.stringify(a));else {t._SessionManager.resetSessionTimer(),n=t._Persistence.getUserProductsFromLS(e),n=n.concat(a),!0===s&&t._Events.logProductActionEvent(Types.ProductActionType.AddToCart,a);n.length>t._Store.SDKConfig.maxProducts&&(t.Logger.verbose("The cart contains "+n.length+" items. Only "+t._Store.SDKConfig.maxProducts+" can currently be saved in cookies."),n=n.slice(-t._Store.SDKConfig.maxProducts)),i=t._Persistence.getAllUserProductsFromLS(),i[e].cp=n,t._Persistence.setCartProducts(i);}},/**
|
|
852
870
|
* Removes a cart product from the current user cart
|
|
853
871
|
* @method remove
|
|
854
872
|
* @param {Object} product the product
|
|
855
873
|
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
|
|
856
874
|
* @deprecated
|
|
857
|
-
*/remove:function remove(s
|
|
875
|
+
*/remove:function remove(r,s){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().remove() will be removed in future releases");var i,n,a=-1,o=null;if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveFromCart,JSON.stringify(r));else {t._SessionManager.resetSessionTimer(),n=t._Persistence.getUserProductsFromLS(e),n&&(n.forEach(function(e,t){e.Sku===r.Sku&&(a=t,o=e);}),-1<a&&(n.splice(a,1),!0===s&&t._Events.logProductActionEvent(Types.ProductActionType.RemoveFromCart,o)));i=t._Persistence.getAllUserProductsFromLS(),i[e].cp=n,t._Persistence.setCartProducts(i);}},/**
|
|
858
876
|
* Clears the user's cart
|
|
859
877
|
* @method clear
|
|
860
878
|
* @deprecated
|
|
861
|
-
*/clear:function clear(){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().clear() will be removed in future releases");var
|
|
879
|
+
*/clear:function clear(){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().clear() will be removed in future releases");var r;t._Store.webviewBridgeEnabled?t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.ClearCart):(t._SessionManager.resetSessionTimer(),r=t._Persistence.getAllUserProductsFromLS(),r&&r[e]&&r[e].cp&&(r[e].cp=[],r[e].cp=[],t._Persistence.setCartProducts(r)));},/**
|
|
862
880
|
* Returns all cart products
|
|
863
881
|
* @method getCartProducts
|
|
864
882
|
* @return {Array} array of cart products
|
|
865
883
|
* @deprecated
|
|
866
|
-
*/getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(
|
|
884
|
+
*/getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(s,i,n,a,o,d,g){var l,u,c,p,_=t.Identity.getUser(i),I={},y=_?_.getUserIdentities().userIdentities:{},v=t._Helpers.extend({},y);t._Store.identityCallInFlight=!1;try{if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),s.responseText&&(c=JSON.parse(s.responseText),c.hasOwnProperty("is_logged_in")&&(t._Store.isLoggedIn=c.is_logged_in)),(!_||_.getMPID()&&c.mpid&&c.mpid!==_.getMPID())&&(t._Store.mpid=c.mpid,_&&t._Persistence.setLastSeenTime(i),!t._Persistence.getFirstSeenTime(c.mpid)&&(u=!0),t._Persistence.setFirstSeenTime(c.mpid)),200===s.status){if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)&&cacheOrClearIdCache(o,d,r.idCache,s,g),o===Modify$1)I=t._Identity.IdentityRequest.combineUserIdentities(y,a.userIdentities),t._Persistence.saveUserIdentitiesToPersistence(i,I);else {var m=r.IdentityAPI.getUser(c.mpid),S=m?m.getUserIdentities().userIdentities:{},P=t._Helpers.extend({},S);t.Logger.verbose("Successfully parsed Identity Response"),o===Identify&&_&&c.mpid===_.getMPID()&&t._Persistence.setFirstSeenTime(c.mpid),p=t._Store.currentSessionMPIDs.indexOf(c.mpid),t._Store.sessionId&&c.mpid&&i!==c.mpid&&0>p&&t._Store.currentSessionMPIDs.push(c.mpid),-1<p&&(t._Store.currentSessionMPIDs=t._Store.currentSessionMPIDs.slice(0,p).concat(t._Store.currentSessionMPIDs.slice(p+1,t._Store.currentSessionMPIDs.length)),t._Store.currentSessionMPIDs.push(c.mpid)),t._CookieSyncManager.attemptCookieSync(i,c.mpid,u),r.checkIdentitySwap(i,c.mpid,t._Store.currentSessionMPIDs),a&&a.userIdentities&&Object.keys(a.userIdentities).length&&(I=r.IdentityRequest.combineUserIdentities(S,a.userIdentities)),t._Persistence.saveUserIdentitiesToPersistence(c.mpid,I),t._Persistence.update(),t._Persistence.findPrevCookiesBasedOnUI(a),t._Store.context=c.context||t._Store.context;}if(l=t.Identity.getCurrentUser(),a&&a.onUserAlias&&t._Helpers.Validators.isFunction(a.onUserAlias))try{t.Logger.warning("Deprecated function onUserAlias will be removed in future releases"),a.onUserAlias(_,l);}catch(r){t.Logger.error("There was an error with your onUserAlias function - "+r);}var b=t._Persistence.getPersistence();l&&(t._Persistence.storeDataInMemory(b,l.getMPID()),(!_||l.getMPID()!==_.getMPID()||_.isLoggedIn()!==l.isLoggedIn())&&t._Forwarders.initForwarders(l.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._Forwarders.setForwarderUserIdentities(l.getUserIdentities().userIdentities),t._Forwarders.setForwarderOnIdentityComplete(l,o),t._Forwarders.setForwarderOnUserIdentified(l));var A={};for(var k in I)A[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(k))]=I[k];r.sendUserIdentityChangeEvent(A,o,c.mpid,o===Modify$1?v:P);}n?0===s.status?t._Helpers.invokeCallback(n,HTTPCodes$2.noHttpCoverage,c||null,l):t._Helpers.invokeCallback(n,s.status,c||null,l):c&&c.errors&&c.errors.length&&t.Logger.error("Received HTTP response code of "+s.status+" - "+c.errors[0].message),t._APIClient.processQueuedEvents();}catch(r){n&&t._Helpers.invokeCallback(n,s.status,c||null),t.Logger.error("Error parsing JSON response from Identity server: "+r);}},this.sendUserIdentityChangeEvent=function(e,s,i,n){var a,o;if(i||s===Modify$1)for(var d in a=this.IdentityAPI.getUser(i),e)if(n[d]!==e[d]){var g=!n[d];o=r.createUserIdentityChange(d,e[d],n[d],g,a),t._APIClient.sendEventToServer(o);}},this.createUserIdentityChange=function(e,r,s,i,n){var a;return a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:r,CreatedThisBatch:i},Old:{IdentityType:e,Identity:s,CreatedThisBatch:!1}},userInMemory:n}),a},this.sendUserAttributeChangeEvent=function(e,s,i,n,a,o){var d=r.createUserAttributeChange(e,s,i,n,a,o);d&&t._APIClient.sendEventToServer(d);},this.createUserAttributeChange=function(e,r,s,i,n,a){"undefined"==typeof s&&(s=null);var o;return r!==s&&(o=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:r,Old:s,Deleted:n,IsNewAttribute:i}},a)),o};}
|
|
867
885
|
|
|
868
886
|
var CCPAPurpose=Constants.CCPAPurpose;function Consent(a){var b=this;// this function is called when consent is required to
|
|
869
887
|
// determine if a cookie sync should happen, or a
|
|
@@ -956,7 +974,7 @@ function ConfigAPIClient(){this.getSDKConfiguration=function(a,b,c,d){var e;try{
|
|
|
956
974
|
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,Modify=Constants.IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){var d,e=function xhrCallback(){if(4===d.readyState){//only parse error messages from failing requests
|
|
957
975
|
if(a.Logger.verbose("Received "+d.statusText+" from server"),200!==d.status&&202!==d.status&&d.responseText){var b=JSON.parse(d.responseText);if(b.hasOwnProperty("message")){var e=b.message;return void a._Helpers.invokeAliasCallback(c,d.status,e)}}a._Helpers.invokeAliasCallback(c,d.status);}};if(a.Logger.verbose(Messages$1.InformationMessages.SendAliasHttp),d=a._Helpers.createXHR(e),d)try{d.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.aliasUrl,a._Store.devToken)+"/Alias"),d.send(JSON.stringify(b));}catch(b){a._Helpers.invokeAliasCallback(c,HTTPCodes$1.noHttpCoverage,b),a.Logger.error("Error sending alias request to mParticle servers. "+b);}},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k=function xhrCallback(){4===i.readyState&&(a.Logger.verbose("Received "+i.statusText+" from server"),f(i,j,d,e,c,h,!1));};if(a.Logger.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return void a.Logger.error(Messages$1.ErrorMessages.APIRequestEmpty);if(a.Logger.verbose(Messages$1.InformationMessages.SendIdentityHttp),i=a._Helpers.createXHR(k),i)try{a._Store.identityCallInFlight?a._Helpers.invokeCallback(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"):(j=g||null,c===Modify?i.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl)+g+"/"+c):i.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl)+c),i.setRequestHeader("Content-Type","application/json"),i.setRequestHeader("x-mp-key",a._Store.devToken),a._Store.identityCallInFlight=!0,i.send(JSON.stringify(b)));}catch(b){a._Store.identityCallInFlight=!1,a._Helpers.invokeCallback(d,HTTPCodes$1.noHttpCoverage,b),a.Logger.error("Error sending identity request to servers with status code "+i.status+" - "+b);}};}
|
|
958
976
|
|
|
959
|
-
var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes;/**
|
|
977
|
+
var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
|
|
960
978
|
* <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>
|
|
961
979
|
* <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>
|
|
962
980
|
* <p>This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().</p>
|
|
@@ -1133,7 +1151,7 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes;/**
|
|
|
1133
1151
|
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.IdentityType=Types.IdentityType,this.EventType=Types.EventType,this.CommerceEventType=Types.CommerceEventType,this.PromotionType=Types.PromotionActionType,this.ProductActionType=Types.ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
|
|
1134
1152
|
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
|
|
1135
1153
|
// to it for it to be run after fetched
|
|
1136
|
-
return b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),b?void(!b.hasOwnProperty("requestConfig")||b.requestConfig?new ConfigAPIClient().getSDKConfiguration(a,b,completeSDKInitialization,this):completeSDKInitialization(a,b,this)):void console.error("No config available on the window, please pass a config object to mParticle.init()")},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._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){b.isInitialized()&&"function"==typeof a?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Types.Environment.Development:Types.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){
|
|
1154
|
+
return b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),b?void(!b.hasOwnProperty("requestConfig")||b.requestConfig?new ConfigAPIClient().getSDKConfiguration(a,b,completeSDKInitialization,this):completeSDKInitialization(a,b,this)):void console.error("No config available on the window, please pass a config object to mParticle.init()")},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._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){b.isInitialized()&&"function"==typeof a?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Types.Environment.Development:Types.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
|
|
1137
1155
|
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=Types.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=Types.EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:Types.MessageType.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(Types.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:Types.MessageType.CrashReport,name:a.name?a.name:"Error",data:e,eventType:Types.EventType.Other});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:Types.MessageType.PageView,name:a,data:c,eventType:Types.EventType.Unknown,customFlags:d},e);}},this.upload=function(){b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):b._APIClient.uploader.prepareAndUpload(!1,!1));},this.Consent={/**
|
|
1138
1156
|
* Creates a CCPA Opt Out Consent State.
|
|
1139
1157
|
*
|
|
@@ -1286,21 +1304,27 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf
|
|
|
1286
1304
|
if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any
|
|
1287
1305
|
// other integration delays set to true. It not, process the queued events/.
|
|
1288
1306
|
var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment
|
|
1289
|
-
function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c)
|
|
1290
|
-
|
|
1307
|
+
function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's
|
|
1308
|
+
// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not
|
|
1309
|
+
// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
|
|
1310
|
+
// persistence or Identity directly.
|
|
1311
|
+
if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage();// Set up user identitiy variables for later use
|
|
1312
|
+
var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}c._Store.isInitialized=!0;// Call any functions that are waiting for the library to be initialized
|
|
1313
|
+
try{c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue);}catch(a){c.Logger.error(a);}// https://go.mparticle.com/work/SQDSDKS-6040
|
|
1314
|
+
c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}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:
|
|
1291
1315
|
1. Manually via config.dataPlanOptions (this takes priority)
|
|
1292
1316
|
If not passed in manually, we user the server provided via either
|
|
1293
1317
|
2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
|
|
1294
1318
|
3. Self hosting via /config endpoint (config.dataPlanResult)
|
|
1295
|
-
*/return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(
|
|
1319
|
+
*/return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){return new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Check to see if localStorage is available before main configuration runs
|
|
1296
1320
|
// since we will need this for the current implementation of user persistence
|
|
1297
1321
|
// TODO: Refactor this when we refactor User Identity Persistence
|
|
1298
|
-
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function
|
|
1299
|
-
if(mParticle[
|
|
1322
|
+
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function processPreloadedItem(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
|
|
1323
|
+
if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){if(!isEmpty(a))return a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
|
|
1300
1324
|
|
|
1301
1325
|
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1302
1326
|
var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
|
|
1303
|
-
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,
|
|
1327
|
+
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}();
|
|
1304
1328
|
|
|
1305
1329
|
var EventTypeEnum;(function(a){a[a.Unknown=0]="Unknown",a[a.Navigation=1]="Navigation",a[a.Location=2]="Location",a[a.Search=3]="Search",a[a.Transaction=4]="Transaction",a[a.UserContent=5]="UserContent",a[a.UserPreference=6]="UserPreference",a[a.Social=7]="Social",a[a.Other=8]="Other",a[a.Media=9]="Media";})(EventTypeEnum||(EventTypeEnum={}));// TODO: https://mparticle-eng.atlassian.net/browse/SQDSDKS-5403
|
|
1306
1330
|
var MessageType;(function(a){a[a.SessionStart=1]="SessionStart",a[a.SessionEnd=2]="SessionEnd",a[a.PageView=3]="PageView",a[a.PageEvent=4]="PageEvent",a[a.CrashReport=5]="CrashReport",a[a.OptOut=6]="OptOut",a[a.AppStateTransition=10]="AppStateTransition",a[a.Profile=14]="Profile",a[a.Commerce=16]="Commerce",a[a.UserAttributeChange=17]="UserAttributeChange",a[a.UserIdentityChange=18]="UserIdentityChange",a[a.Media=20]="Media";})(MessageType||(MessageType={}));var IdentityType;(function(a){a[a.Other=0]="Other",a[a.CustomerId=1]="CustomerId",a[a.Facebook=2]="Facebook",a[a.Twitter=3]="Twitter",a[a.Google=4]="Google",a[a.Microsoft=5]="Microsoft",a[a.Yahoo=6]="Yahoo",a[a.Email=7]="Email",a[a.FacebookCustomAudienceId=9]="FacebookCustomAudienceId",a[a.Other2=10]="Other2",a[a.Other3=11]="Other3",a[a.Other4=12]="Other4",a[a.Other5=13]="Other5",a[a.Other6=14]="Other6",a[a.Other7=15]="Other7",a[a.Other8=16]="Other8",a[a.Other9=17]="Other9",a[a.Other10=18]="Other10",a[a.MobileNumber=19]="MobileNumber",a[a.PhoneNumber2=20]="PhoneNumber2",a[a.PhoneNumber3=21]="PhoneNumber3";})(IdentityType||(IdentityType={}));
|