@mparticle/web-sdk 2.23.1 → 2.23.3

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.
@@ -15,14 +15,14 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- function _typeof(obj) {
18
+ function _typeof(o) {
19
19
  "@babel/helpers - typeof";
20
20
 
21
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
22
- return typeof obj;
23
- } : function (obj) {
24
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
25
- }, _typeof(obj);
21
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
22
+ return typeof o;
23
+ } : function (o) {
24
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
25
+ }, _typeof(o);
26
26
  }
27
27
 
28
28
  function _toPrimitive(input, hint) {
@@ -61,9 +61,9 @@ 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.23.1";
64
+ var version = "2.23.3";
65
65
 
66
- var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{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
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
67
67
  },DefaultUrls:{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},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"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out"};
68
68
 
69
69
  /******************************************************************************
@@ -460,7 +460,7 @@ slugify$1.exports;
460
460
  var slugifyExports = slugify$1.exports;
461
461
  var slugify = /*@__PURE__*/getDefaultExportFromCjs(slugifyExports);
462
462
 
463
- var createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null};function generateHash(a){var b,c=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(var d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c}var generateRandomValue=function(){var b,c;return window.crypto&&window.crypto.getRandomValues&&(b=window.crypto.getRandomValues(new Uint8Array(1))),b?(c^b[0]%16>>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
463
+ var Messages$9=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},generateDeprecationMessage=function(a,b){var c=[a,Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix];return b&&(c.push(b),c.push(Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix)),c.join(" ")};function generateHash(a){var b,c=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(var d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c}var generateRandomValue=function(){var b,c;return window.crypto&&window.crypto.getRandomValues&&(b=window.crypto.getRandomValues(new Uint8Array(1))),b?(c^b[0]%16>>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
464
464
  ?generateRandomValue()// if the placeholder was passed, return
465
465
  :// [1e7] -> // 10000000 +
466
466
  // -1e3 -> // -1000 +
@@ -512,7 +512,7 @@ var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.p
512
512
  * Creates an instance of a BatchUploader
513
513
  * @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
514
514
  * @param {number} uploadInterval - the desired upload interval in milliseconds
515
- */function a(b,c){var d,e;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 f=(e=this.mpInstance._Store,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,b=(a=this.mpInstance,a._Helpers.getFeatureFlag),c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);// TODO: Handle cases where Local Storage is unavailable
515
+ */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);// TODO: Handle cases where Local Storage is unavailable
516
516
  // Potentially shared between Vault and Persistence as well
517
517
  // https://go.mparticle.com/work/SQDSDKS-5022
518
518
  return e>=f},a.prototype.addEventListeners=function(){var a=this;// visibility change is a document property, not window
@@ -593,8 +593,9 @@ if(!(h&&g)&&a._Consent.isEnabledForUserConsent(f,a.Identity.getCurrentUser()))//
593
593
  // function polls the user object and consent multiple times.
594
594
  {var i=document.createElement("img");a.Logger.verbose(Messages$7.InformationMessages.CookieSync),i.onload=function(){e[c.toString()]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},i.src=b;}};}
595
595
 
596
- var Messages$6=Constants.Messages;function SessionManager(a){var b=this;this.initialize=function(){if(a._Store.sessionId){var c=6e4*a._Store.SDKConfig.sessionTimeout;if(new Date>new Date(a._Store.dateLastEventSent.getTime()+c))b.endSession(),b.startNewSession();else {var d=a._Persistence.getPersistence();d&&!d.cu&&(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else b.startNewSession();},this.getSession=function(){return a._Store.sessionId},this.startNewSession=function(){if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),d=c?c.getMPID():null;if(d&&(a._Store.currentSessionMPIDs=[d]),!a._Store.sessionStartDate){var e=new Date;a._Store.sessionStartDate=e,a._Store.dateLastEventSent=e;}b.setSessionTimer(),a._Store.identifyCalled||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(c){if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),c)a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionAttributes={},a._Persistence.update();else if(a._Helpers.canLog()){var d,e,f;if(e=a._Persistence.getPersistence(),!e)return;if(e.gs&&!e.gs.sid)return void a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
597
- if(e.gs.sid&&a._Store.sessionId!==e.gs.sid&&(a._Store.sessionId=e.gs.sid),e.gs&&e.gs.les){d=6e4*a._Store.SDKConfig.sessionTimeout;var g=new Date().getTime();f=g-e.gs.les,f<d?b.setSessionTimer():(a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionStartDate=null,a._Store.sessionAttributes={},a._Persistence.update());}}else a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);},this.setSessionTimer=function(){var c=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){b.endSession();},c);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&b.startNewSession(),b.clearSessionTimeout(),b.setSessionTimer()),b.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var c=a._Persistence.getPersistence();!a._Store.sessionId&&c&&(c.sid?a._Store.sessionId=c.sid:b.startNewSession());}};}
596
+ var Messages$6=Constants.Messages;function SessionManager(a){function b(){a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionAttributes={},a._Persistence.update();}var c=this;this.initialize=function(){if(a._Store.sessionId){var b=6e4*a._Store.SDKConfig.sessionTimeout;if(new Date>new Date(a._Store.dateLastEventSent.getTime()+b))c.endSession(),c.startNewSession();else {var d=a._Persistence.getPersistence();d&&!d.cu&&(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else c.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()","SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var b=a.Identity.getCurrentUser(),d=b?b.getMPID():null;if(d&&(a._Store.currentSessionMPIDs=[d]),!a._Store.sessionStartDate){var e=new Date;a._Store.sessionStartDate=e,a._Store.dateLastEventSent=e;}c.setSessionTimer(),a._Store.identifyCalled||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(d){var e;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),d)return a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),void b();if(!a._Helpers.canLog())return void a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);var f,g,h=a._Persistence.getPersistence();// TODO: https://go.mparticle.com/work/SQDSDKS-5684
597
+ if(h){if(h.gs&&!h.gs.sid)return void a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
598
+ if(h.gs.sid&&a._Store.sessionId!==h.gs.sid&&(a._Store.sessionId=h.gs.sid),null===(e=null===h||void 0===h?void 0:h.gs)||void 0===e?void 0:e.les){f=6e4*a._Store.SDKConfig.sessionTimeout;var i=new Date().getTime();g=i-h.gs.les,g<f?c.setSessionTimer():(a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionStartDate=null,b());}}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){c.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&c.startNewSession(),c.clearSessionTimeout(),c.setSessionTimer()),c.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:c.startNewSession());}};}
598
599
 
599
600
  var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// sanitizes any non number, non string value to 0
600
601
  this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b){var c;return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(c=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce}),c.EventName="eCommerce - ",c.CurrencyCode=a._Store.currencyCode,c.ShoppingCart=[],c.CustomFlags=b,c):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0
@@ -1313,7 +1314,7 @@ if(mParticle[c[0]])mParticle[d].apply(this,c);else {var e=d.split(".");try{for(v
1313
1314
 
1314
1315
  // This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
1315
1316
  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
1316
- _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,returnConvertedBoolean:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,MPSideloadedKit:null,_Consent: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}();
1317
+ _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,returnConvertedBoolean: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}();
1317
1318
 
1318
1319
  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
1319
1320
  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={}));
@@ -15,14 +15,14 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- function _typeof(obj) {
18
+ function _typeof(o) {
19
19
  "@babel/helpers - typeof";
20
20
 
21
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
22
- return typeof obj;
23
- } : function (obj) {
24
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
25
- }, _typeof(obj);
21
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
22
+ return typeof o;
23
+ } : function (o) {
24
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
25
+ }, _typeof(o);
26
26
  }
27
27
 
28
28
  function _toPrimitive(input, hint) {
@@ -61,9 +61,9 @@ 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.23.1";
64
+ var version = "2.23.3";
65
65
 
66
- var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{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
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
67
67
  },DefaultUrls:{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},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"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out"};
68
68
 
69
69
  /******************************************************************************
@@ -460,7 +460,7 @@ slugify$1.exports;
460
460
  var slugifyExports = slugify$1.exports;
461
461
  var slugify = /*@__PURE__*/getDefaultExportFromCjs(slugifyExports);
462
462
 
463
- var createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null};function generateHash(a){var b,c=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(var d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c}var generateRandomValue=function(){var b,c;return window.crypto&&window.crypto.getRandomValues&&(b=window.crypto.getRandomValues(new Uint8Array(1))),b?(c^b[0]%16>>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
463
+ var Messages$9=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},generateDeprecationMessage=function(a,b){var c=[a,Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix];return b&&(c.push(b),c.push(Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix)),c.join(" ")};function generateHash(a){var b,c=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(var d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c}var generateRandomValue=function(){var b,c;return window.crypto&&window.crypto.getRandomValues&&(b=window.crypto.getRandomValues(new Uint8Array(1))),b?(c^b[0]%16>>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
464
464
  ?generateRandomValue()// if the placeholder was passed, return
465
465
  :// [1e7] -> // 10000000 +
466
466
  // -1e3 -> // -1000 +
@@ -512,7 +512,7 @@ var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.p
512
512
  * Creates an instance of a BatchUploader
513
513
  * @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
514
514
  * @param {number} uploadInterval - the desired upload interval in milliseconds
515
- */function a(b,c){var d,e;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 f=(e=this.mpInstance._Store,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,b=(a=this.mpInstance,a._Helpers.getFeatureFlag),c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);// TODO: Handle cases where Local Storage is unavailable
515
+ */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);// TODO: Handle cases where Local Storage is unavailable
516
516
  // Potentially shared between Vault and Persistence as well
517
517
  // https://go.mparticle.com/work/SQDSDKS-5022
518
518
  return e>=f},a.prototype.addEventListeners=function(){var a=this;// visibility change is a document property, not window
@@ -593,8 +593,9 @@ if(!(h&&g)&&a._Consent.isEnabledForUserConsent(f,a.Identity.getCurrentUser()))//
593
593
  // function polls the user object and consent multiple times.
594
594
  {var i=document.createElement("img");a.Logger.verbose(Messages$7.InformationMessages.CookieSync),i.onload=function(){e[c.toString()]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},i.src=b;}};}
595
595
 
596
- var Messages$6=Constants.Messages;function SessionManager(a){var b=this;this.initialize=function(){if(a._Store.sessionId){var c=6e4*a._Store.SDKConfig.sessionTimeout;if(new Date>new Date(a._Store.dateLastEventSent.getTime()+c))b.endSession(),b.startNewSession();else {var d=a._Persistence.getPersistence();d&&!d.cu&&(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else b.startNewSession();},this.getSession=function(){return a._Store.sessionId},this.startNewSession=function(){if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),d=c?c.getMPID():null;if(d&&(a._Store.currentSessionMPIDs=[d]),!a._Store.sessionStartDate){var e=new Date;a._Store.sessionStartDate=e,a._Store.dateLastEventSent=e;}b.setSessionTimer(),a._Store.identifyCalled||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(c){if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),c)a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionAttributes={},a._Persistence.update();else if(a._Helpers.canLog()){var d,e,f;if(e=a._Persistence.getPersistence(),!e)return;if(e.gs&&!e.gs.sid)return void a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
597
- if(e.gs.sid&&a._Store.sessionId!==e.gs.sid&&(a._Store.sessionId=e.gs.sid),e.gs&&e.gs.les){d=6e4*a._Store.SDKConfig.sessionTimeout;var g=new Date().getTime();f=g-e.gs.les,f<d?b.setSessionTimer():(a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionStartDate=null,a._Store.sessionAttributes={},a._Persistence.update());}}else a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);},this.setSessionTimer=function(){var c=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){b.endSession();},c);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&b.startNewSession(),b.clearSessionTimeout(),b.setSessionTimer()),b.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var c=a._Persistence.getPersistence();!a._Store.sessionId&&c&&(c.sid?a._Store.sessionId=c.sid:b.startNewSession());}};}
596
+ var Messages$6=Constants.Messages;function SessionManager(a){function b(){a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionAttributes={},a._Persistence.update();}var c=this;this.initialize=function(){if(a._Store.sessionId){var b=6e4*a._Store.SDKConfig.sessionTimeout;if(new Date>new Date(a._Store.dateLastEventSent.getTime()+b))c.endSession(),c.startNewSession();else {var d=a._Persistence.getPersistence();d&&!d.cu&&(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else c.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()","SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var b=a.Identity.getCurrentUser(),d=b?b.getMPID():null;if(d&&(a._Store.currentSessionMPIDs=[d]),!a._Store.sessionStartDate){var e=new Date;a._Store.sessionStartDate=e,a._Store.dateLastEventSent=e;}c.setSessionTimer(),a._Store.identifyCalled||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(d){var e;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),d)return a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),void b();if(!a._Helpers.canLog())return void a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);var f,g,h=a._Persistence.getPersistence();// TODO: https://go.mparticle.com/work/SQDSDKS-5684
597
+ if(h){if(h.gs&&!h.gs.sid)return void a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
598
+ if(h.gs.sid&&a._Store.sessionId!==h.gs.sid&&(a._Store.sessionId=h.gs.sid),null===(e=null===h||void 0===h?void 0:h.gs)||void 0===e?void 0:e.les){f=6e4*a._Store.SDKConfig.sessionTimeout;var i=new Date().getTime();g=i-h.gs.les,g<f?c.setSessionTimer():(a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionStartDate=null,b());}}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){c.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&c.startNewSession(),c.clearSessionTimeout(),c.setSessionTimer()),c.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:c.startNewSession());}};}
598
599
 
599
600
  var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// sanitizes any non number, non string value to 0
600
601
  this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b){var c;return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(c=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce}),c.EventName="eCommerce - ",c.CurrencyCode=a._Store.currencyCode,c.ShoppingCart=[],c.CustomFlags=b,c):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0
@@ -1313,7 +1314,7 @@ if(mParticle[c[0]])mParticle[d].apply(this,c);else {var e=d.split(".");try{for(v
1313
1314
 
1314
1315
  // This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
1315
1316
  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
1316
- _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,returnConvertedBoolean:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,MPSideloadedKit:null,_Consent: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}();
1317
+ _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,returnConvertedBoolean: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}();
1317
1318
 
1318
1319
  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
1319
1320
  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={}));
package/dist/mparticle.js CHANGED
@@ -203,14 +203,14 @@ var mParticle = (function () {
203
203
  Base64: Base64$1
204
204
  };
205
205
 
206
- function _typeof(obj) {
206
+ function _typeof(o) {
207
207
  "@babel/helpers - typeof";
208
208
 
209
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
210
- return typeof obj;
211
- } : function (obj) {
212
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
213
- }, _typeof(obj);
209
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
210
+ return typeof o;
211
+ } : function (o) {
212
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
213
+ }, _typeof(o);
214
214
  }
215
215
 
216
216
  function _toPrimitive(input, hint) {
@@ -608,13 +608,17 @@ var mParticle = (function () {
608
608
  Environment: Environment
609
609
  };
610
610
 
611
- var version = "2.23.1";
611
+ var version = "2.23.3";
612
612
 
613
613
  var Constants = {
614
614
  sdkVersion: version,
615
615
  sdkVendor: 'mparticle',
616
616
  platform: 'web',
617
617
  Messages: {
618
+ DeprecationMessages: {
619
+ MethodIsDeprecatedPostfix: 'is a deprecated method and will be removed in future releases',
620
+ AlternativeMethodPrefix: 'Please use the alternate method:'
621
+ },
618
622
  ErrorMessages: {
619
623
  NoToken: 'A token must be specified.',
620
624
  EventNameInvalidType: 'Event name must be a valid string value.',
@@ -1195,6 +1199,7 @@ var mParticle = (function () {
1195
1199
  var slugifyExports = slugify$1.exports;
1196
1200
  var slugify = /*@__PURE__*/getDefaultExportFromCjs(slugifyExports);
1197
1201
 
1202
+ var Messages$9 = Constants.Messages;
1198
1203
  var createCookieString = function createCookieString(value) {
1199
1204
  return replaceCommasWithPipes(replaceQuotesWithApostrophes(value));
1200
1205
  };
@@ -1224,6 +1229,14 @@ var mParticle = (function () {
1224
1229
  }
1225
1230
  return null;
1226
1231
  };
1232
+ var generateDeprecationMessage = function generateDeprecationMessage(methodName, alternateMethod) {
1233
+ var messageArray = [methodName, Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix];
1234
+ if (alternateMethod) {
1235
+ messageArray.push(alternateMethod);
1236
+ messageArray.push(Messages$9.DeprecationMessages.MethodIsDeprecatedPostfix);
1237
+ }
1238
+ return messageArray.join(' ');
1239
+ };
1227
1240
  function generateHash(name) {
1228
1241
  var hash = 0;
1229
1242
  var character;
@@ -2043,7 +2056,7 @@ var mParticle = (function () {
2043
2056
  * @param {number} uploadInterval - the desired upload interval in milliseconds
2044
2057
  */
2045
2058
  function BatchUploader(mpInstance, uploadInterval) {
2046
- var _a, _b;
2059
+ var _a;
2047
2060
  this.offlineStorageEnabled = false;
2048
2061
  this.mpInstance = mpInstance;
2049
2062
  this.uploadIntervalMillis = uploadInterval;
@@ -2070,7 +2083,8 @@ var mParticle = (function () {
2070
2083
  // Load Events from Session Storage in case we have any in storage
2071
2084
  (_a = this.eventsQueuedForProcessing).push.apply(_a, this.eventVault.retrieve());
2072
2085
  }
2073
- var SDKConfig = (_b = this.mpInstance._Store, _b.SDKConfig),
2086
+ var _b = this.mpInstance._Store,
2087
+ SDKConfig = _b.SDKConfig,
2074
2088
  devToken = _b.devToken;
2075
2089
  var baseUrl = this.mpInstance._Helpers.createServiceUrl(SDKConfig.v3SecureServiceUrl, devToken);
2076
2090
  this.uploadUrl = "".concat(baseUrl, "/events");
@@ -2079,8 +2093,8 @@ var mParticle = (function () {
2079
2093
  this.addEventListeners();
2080
2094
  }
2081
2095
  BatchUploader.prototype.isOfflineStorageAvailable = function () {
2082
- var _a;
2083
- var getFeatureFlag = (_a = this.mpInstance, _a._Helpers.getFeatureFlag),
2096
+ var _a = this.mpInstance,
2097
+ getFeatureFlag = _a._Helpers.getFeatureFlag,
2084
2098
  deviceId = _a._Store.deviceId;
2085
2099
  var offlineStorageFeatureFlagValue = getFeatureFlag(Constants.FeatureFlags.OfflineStorage);
2086
2100
  var offlineStoragePercentage = parseInt(offlineStorageFeatureFlagValue, 10);
@@ -3269,14 +3283,18 @@ var mParticle = (function () {
3269
3283
  }
3270
3284
  };
3271
3285
  this.getSession = function () {
3286
+ mpInstance.Logger.warning(generateDeprecationMessage('SessionManager.getSession()', 'SessionManager.getSessionId()'));
3287
+ return this.getSessionId();
3288
+ };
3289
+ this.getSessionId = function () {
3272
3290
  return mpInstance._Store.sessionId;
3273
3291
  };
3274
3292
  this.startNewSession = function () {
3275
3293
  mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingNewSession);
3276
3294
  if (mpInstance._Helpers.canLog()) {
3277
3295
  mpInstance._Store.sessionId = mpInstance._Helpers.generateUniqueId().toUpperCase();
3278
- var currentUser = mpInstance.Identity.getCurrentUser(),
3279
- mpid = currentUser ? currentUser.getMPID() : null;
3296
+ var currentUser = mpInstance.Identity.getCurrentUser();
3297
+ var mpid = currentUser ? currentUser.getMPID() : null;
3280
3298
  if (mpid) {
3281
3299
  mpInstance._Store.currentSessionMPIDs = [mpid];
3282
3300
  }
@@ -3299,49 +3317,51 @@ var mParticle = (function () {
3299
3317
  }
3300
3318
  };
3301
3319
  this.endSession = function (override) {
3320
+ var _a;
3302
3321
  mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingEndSession);
3303
3322
  if (override) {
3304
3323
  mpInstance._Events.logEvent({
3305
3324
  messageType: Types.MessageType.SessionEnd
3306
3325
  });
3307
- mpInstance._Store.sessionId = null;
3308
- mpInstance._Store.dateLastEventSent = null;
3309
- mpInstance._Store.sessionAttributes = {};
3310
- mpInstance._Persistence.update();
3311
- } else if (mpInstance._Helpers.canLog()) {
3312
- var sessionTimeoutInMilliseconds, cookies, timeSinceLastEventSent;
3313
- cookies = mpInstance._Persistence.getPersistence();
3314
- if (!cookies) {
3315
- return;
3316
- }
3317
- if (cookies.gs && !cookies.gs.sid) {
3318
- mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);
3319
- return;
3320
- }
3321
-
3322
- // sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
3323
- if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) {
3324
- mpInstance._Store.sessionId = cookies.gs.sid;
3325
- }
3326
- if (cookies.gs && cookies.gs.les) {
3327
- sessionTimeoutInMilliseconds = mpInstance._Store.SDKConfig.sessionTimeout * 60000;
3328
- var newDate = new Date().getTime();
3329
- timeSinceLastEventSent = newDate - cookies.gs.les;
3330
- if (timeSinceLastEventSent < sessionTimeoutInMilliseconds) {
3331
- self.setSessionTimer();
3332
- } else {
3333
- mpInstance._Events.logEvent({
3334
- messageType: Types.MessageType.SessionEnd
3335
- });
3336
- mpInstance._Store.sessionId = null;
3337
- mpInstance._Store.dateLastEventSent = null;
3338
- mpInstance._Store.sessionStartDate = null;
3339
- mpInstance._Store.sessionAttributes = {};
3340
- mpInstance._Persistence.update();
3341
- }
3342
- }
3343
- } else {
3326
+ nullifySession();
3327
+ return;
3328
+ }
3329
+ if (!mpInstance._Helpers.canLog()) {
3330
+ // At this moment, an AbandonedEndSession is defined when on of three things occurs:
3331
+ // - the SDK's store is not enabled because mParticle.setOptOut was called
3332
+ // - the devToken is undefined
3333
+ // - webviewBridgeEnabled is set to false
3344
3334
  mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);
3335
+ return;
3336
+ }
3337
+ var sessionTimeoutInMilliseconds;
3338
+ var timeSinceLastEventSent;
3339
+ var cookies = mpInstance._Persistence.getPersistence();
3340
+ // TODO: https://go.mparticle.com/work/SQDSDKS-5684
3341
+ if (!cookies) {
3342
+ return;
3343
+ }
3344
+ if (cookies.gs && !cookies.gs.sid) {
3345
+ mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);
3346
+ return;
3347
+ }
3348
+ // sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
3349
+ if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) {
3350
+ mpInstance._Store.sessionId = cookies.gs.sid;
3351
+ }
3352
+ if ((_a = cookies === null || cookies === void 0 ? void 0 : cookies.gs) === null || _a === void 0 ? void 0 : _a.les) {
3353
+ sessionTimeoutInMilliseconds = mpInstance._Store.SDKConfig.sessionTimeout * 60000;
3354
+ var newDate = new Date().getTime();
3355
+ timeSinceLastEventSent = newDate - cookies.gs.les;
3356
+ if (timeSinceLastEventSent < sessionTimeoutInMilliseconds) {
3357
+ self.setSessionTimer();
3358
+ } else {
3359
+ mpInstance._Events.logEvent({
3360
+ messageType: Types.MessageType.SessionEnd
3361
+ });
3362
+ mpInstance._Store.sessionStartDate = null;
3363
+ nullifySession();
3364
+ }
3345
3365
  }
3346
3366
  };
3347
3367
  this.setSessionTimer = function () {
@@ -3375,6 +3395,12 @@ var mParticle = (function () {
3375
3395
  }
3376
3396
  }
3377
3397
  };
3398
+ function nullifySession() {
3399
+ mpInstance._Store.sessionId = null;
3400
+ mpInstance._Store.dateLastEventSent = null;
3401
+ mpInstance._Store.sessionAttributes = {};
3402
+ mpInstance._Persistence.update();
3403
+ }
3378
3404
  }
3379
3405
 
3380
3406
  var Messages$5 = Constants.Messages;
@@ -9142,6 +9168,7 @@ var mParticle = (function () {
9142
9168
  _APIClient: null,
9143
9169
  MPSideloadedKit: null,
9144
9170
  _Consent: null,
9171
+ _Events: null,
9145
9172
  _Forwarders: null,
9146
9173
  _NativeSdkHelpers: null,
9147
9174
  _Persistence: null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.23.1",
3
+ "version": "2.23.3",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -84,9 +84,9 @@
84
84
  "@mparticle/data-planning-models": "^0.1.0",
85
85
  "@mparticle/event-models": "^1.1.8",
86
86
  "@rollup/plugin-babel": "6.0.3",
87
- "@rollup/plugin-commonjs": "25.0.2",
88
- "@rollup/plugin-json": "^4.1.0",
89
- "@rollup/plugin-node-resolve": "15.1.0",
87
+ "@rollup/plugin-commonjs": "25.0.4",
88
+ "@rollup/plugin-json": "^5.0.2",
89
+ "@rollup/plugin-node-resolve": "15.2.1",
90
90
  "@rollup/plugin-typescript": "^11.1.0",
91
91
  "@semantic-release/changelog": "^5.0.1",
92
92
  "@semantic-release/exec": "^5.0.0",
@@ -103,10 +103,10 @@
103
103
  "chai": "^4.2.0",
104
104
  "cross-env": "^7.0.3",
105
105
  "eslint": "^8.36.0",
106
- "eslint-config-prettier": "8.8.0",
106
+ "eslint-config-prettier": "9.0.0",
107
107
  "eslint-plugin-prettier": "3.4.1",
108
108
  "fetch-mock": "^7.5.1",
109
- "gts": "^3.1.0",
109
+ "gts": "^5.0.1",
110
110
  "jest": "^29.5.0",
111
111
  "jest-environment-jsdom": "^29.5.0",
112
112
  "karma": "^6.3.2",
package/src/constants.ts CHANGED
@@ -5,6 +5,11 @@ const Constants = {
5
5
  sdkVendor: 'mparticle',
6
6
  platform: 'web',
7
7
  Messages: {
8
+ DeprecationMessages: {
9
+ MethodIsDeprecatedPostfix:
10
+ 'is a deprecated method and will be removed in future releases',
11
+ AlternativeMethodPrefix: 'Please use the alternate method:',
12
+ },
8
13
  ErrorMessages: {
9
14
  NoToken: 'A token must be specified.',
10
15
  EventNameInvalidType: 'Event name must be a valid string value.',
@@ -163,7 +168,7 @@ const Constants = {
163
168
  OfflineStorage: 'offlineStorage',
164
169
  },
165
170
  DefaultInstance: 'default_instance',
166
- CCPAPurpose: 'data_sale_opt_out'
171
+ CCPAPurpose: 'data_sale_opt_out',
167
172
  } as const;
168
173
 
169
174
  export default Constants;
@@ -34,6 +34,7 @@ export default class _BatchValidator {
34
34
  _APIClient: null,
35
35
  MPSideloadedKit: null,
36
36
  _Consent: null,
37
+ _Events: null,
37
38
  _Forwarders: null,
38
39
  _NativeSdkHelpers: null,
39
40
  _Persistence: null,
@@ -9,6 +9,8 @@ import { IKitConfigs } from './configAPIClient';
9
9
  import { SDKConsentApi, SDKConsentState } from './consent';
10
10
  import { IPersistence } from './persistence.interfaces';
11
11
  import { IMPSideloadedKit } from './sideloadedKit';
12
+ import { ISessionManager } from './sessionManager';
13
+
12
14
  // TODO: Resolve this with version in @mparticle/web-sdk
13
15
  export type SDKEventCustomFlags = Dictionary<any>;
14
16
 
@@ -126,6 +128,11 @@ export interface SDKProduct {
126
128
  Attributes?: { [key: string]: string };
127
129
  }
128
130
 
131
+ // Temporary Interfaces for Events Module
132
+ interface IEvents {
133
+ logEvent?(event: BaseEvent): void;
134
+ }
135
+
129
136
  export interface MParticleWebSDK {
130
137
  addForwarder(mockForwarder: MPForwarder): void;
131
138
  Identity: SDKIdentityApi;
@@ -135,9 +142,10 @@ export interface MParticleWebSDK {
135
142
  _Store: IStore;
136
143
  _Forwarders: any;
137
144
  _Helpers: SDKHelpersApi;
145
+ _Events: IEvents;
138
146
  config: SDKInitConfig;
139
147
  _ServerModel: IServerModel;
140
- _SessionManager: any; // TODO: Set up Session Manager
148
+ _SessionManager: ISessionManager;
141
149
  _Consent: SDKConsentApi;
142
150
  Consent: SDKConsentApi;
143
151
  _NativeSdkHelpers: any; // TODO: Set up API
@@ -231,6 +239,7 @@ export interface SDKIdentityApi {
231
239
  }
232
240
 
233
241
  export interface SDKHelpersApi {
242
+ canLog?(): boolean;
234
243
  createServiceUrl(arg0: string, arg1: string): void;
235
244
  createXHR?(cb: () => void): XMLHttpRequest;
236
245
  extend?(...args: any[]);
@@ -306,7 +315,7 @@ export interface SDKUserAttributeChangeData {
306
315
 
307
316
  export interface BaseEvent {
308
317
  messageType: number;
309
- name: string;
318
+ name?: string;
310
319
  eventType?: number;
311
320
  data?: { [key: string]: string };
312
321
  customFlags?: { [key: string]: string };
@@ -0,0 +1,231 @@
1
+ import { MPID } from '@mparticle/web-sdk';
2
+ import Constants from './constants';
3
+ import { IPersistenceMinified } from './persistence.interfaces';
4
+ import { MParticleUser, MParticleWebSDK } from './sdkRuntimeModels';
5
+ import Types from './types';
6
+ import { generateDeprecationMessage } from './utils';
7
+
8
+ const { Messages } = Constants;
9
+
10
+ export interface ISessionManager {
11
+ initialize: () => void;
12
+ getSessionId: () => string;
13
+ startNewSession: () => void;
14
+ endSession: (override?: boolean) => void;
15
+ setSessionTimer: () => void;
16
+ resetSessionTimer: () => void;
17
+ clearSessionTimeout: () => void;
18
+ startNewSessionIfNeeded: () => void;
19
+
20
+ /**
21
+ * @deprecated
22
+ */
23
+ getSession: () => string;
24
+ }
25
+
26
+ export default function SessionManager(
27
+ this: ISessionManager,
28
+ mpInstance: MParticleWebSDK
29
+ ) {
30
+ const self = this;
31
+
32
+ this.initialize = function(): void {
33
+ if (mpInstance._Store.sessionId) {
34
+ const sessionTimeoutInMilliseconds: number =
35
+ mpInstance._Store.SDKConfig.sessionTimeout * 60000;
36
+
37
+ if (
38
+ new Date() >
39
+ new Date(
40
+ mpInstance._Store.dateLastEventSent.getTime() +
41
+ sessionTimeoutInMilliseconds
42
+ )
43
+ ) {
44
+ self.endSession();
45
+ self.startNewSession();
46
+ } else {
47
+ const persistence: IPersistenceMinified = mpInstance._Persistence.getPersistence();
48
+ if (persistence && !persistence.cu) {
49
+ mpInstance.Identity.identify(
50
+ mpInstance._Store.SDKConfig.identifyRequest,
51
+ mpInstance._Store.SDKConfig.identityCallback
52
+ );
53
+ mpInstance._Store.identifyCalled = true;
54
+ mpInstance._Store.SDKConfig.identityCallback = null;
55
+ }
56
+ }
57
+ } else {
58
+ self.startNewSession();
59
+ }
60
+ };
61
+
62
+ this.getSession = function(): string {
63
+ mpInstance.Logger.warning(
64
+ generateDeprecationMessage(
65
+ 'SessionManager.getSession()',
66
+
67
+ 'SessionManager.getSessionId()'
68
+ )
69
+ );
70
+ return this.getSessionId();
71
+ };
72
+
73
+ this.getSessionId = function(): string {
74
+ return mpInstance._Store.sessionId;
75
+ };
76
+
77
+ this.startNewSession = function(): void {
78
+ mpInstance.Logger.verbose(
79
+ Messages.InformationMessages.StartingNewSession
80
+ );
81
+
82
+ if (mpInstance._Helpers.canLog()) {
83
+ mpInstance._Store.sessionId = mpInstance._Helpers
84
+ .generateUniqueId()
85
+ .toUpperCase();
86
+
87
+ const currentUser: MParticleUser = mpInstance.Identity.getCurrentUser();
88
+ const mpid: MPID = currentUser ? currentUser.getMPID() : null;
89
+
90
+ if (mpid) {
91
+ mpInstance._Store.currentSessionMPIDs = [mpid];
92
+ }
93
+
94
+ if (!mpInstance._Store.sessionStartDate) {
95
+ const date: Date = new Date();
96
+ mpInstance._Store.sessionStartDate = date;
97
+ mpInstance._Store.dateLastEventSent = date;
98
+ }
99
+
100
+ self.setSessionTimer();
101
+
102
+ if (!mpInstance._Store.identifyCalled) {
103
+ mpInstance.Identity.identify(
104
+ mpInstance._Store.SDKConfig.identifyRequest,
105
+ mpInstance._Store.SDKConfig.identityCallback
106
+ );
107
+ mpInstance._Store.identifyCalled = true;
108
+ mpInstance._Store.SDKConfig.identityCallback = null;
109
+ }
110
+
111
+ mpInstance._Events.logEvent({
112
+ messageType: Types.MessageType.SessionStart,
113
+ });
114
+ } else {
115
+ mpInstance.Logger.verbose(
116
+ Messages.InformationMessages.AbandonStartSession
117
+ );
118
+ }
119
+ };
120
+
121
+ this.endSession = function(override: boolean): void {
122
+ mpInstance.Logger.verbose(
123
+ Messages.InformationMessages.StartingEndSession
124
+ );
125
+
126
+ if (override) {
127
+ mpInstance._Events.logEvent({
128
+ messageType: Types.MessageType.SessionEnd,
129
+ });
130
+
131
+ nullifySession();
132
+ return;
133
+ }
134
+
135
+ if (!mpInstance._Helpers.canLog()) {
136
+ // At this moment, an AbandonedEndSession is defined when on of three things occurs:
137
+ // - the SDK's store is not enabled because mParticle.setOptOut was called
138
+ // - the devToken is undefined
139
+ // - webviewBridgeEnabled is set to false
140
+ mpInstance.Logger.verbose(
141
+ Messages.InformationMessages.AbandonEndSession
142
+ );
143
+ return;
144
+ }
145
+
146
+ let sessionTimeoutInMilliseconds: number;
147
+ let timeSinceLastEventSent: number;
148
+
149
+ const cookies: IPersistenceMinified = mpInstance._Persistence.getPersistence();
150
+
151
+ // TODO: https://go.mparticle.com/work/SQDSDKS-5684
152
+ if (!cookies) {
153
+ return;
154
+ }
155
+
156
+ if (cookies.gs && !cookies.gs.sid) {
157
+ mpInstance.Logger.verbose(
158
+ Messages.InformationMessages.NoSessionToEnd
159
+ );
160
+ return;
161
+ }
162
+
163
+ // sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
164
+ if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) {
165
+ mpInstance._Store.sessionId = cookies.gs.sid;
166
+ }
167
+
168
+ if (cookies?.gs?.les) {
169
+ sessionTimeoutInMilliseconds =
170
+ mpInstance._Store.SDKConfig.sessionTimeout * 60000;
171
+ const newDate: number = new Date().getTime();
172
+ timeSinceLastEventSent = newDate - cookies.gs.les;
173
+
174
+ if (timeSinceLastEventSent < sessionTimeoutInMilliseconds) {
175
+ self.setSessionTimer();
176
+ } else {
177
+ mpInstance._Events.logEvent({
178
+ messageType: Types.MessageType.SessionEnd,
179
+ });
180
+
181
+ mpInstance._Store.sessionStartDate = null;
182
+ nullifySession();
183
+ }
184
+ }
185
+ };
186
+
187
+ this.setSessionTimer = function(): void {
188
+ const sessionTimeoutInMilliseconds: number =
189
+ mpInstance._Store.SDKConfig.sessionTimeout * 60000;
190
+
191
+ mpInstance._Store.globalTimer = window.setTimeout(function() {
192
+ self.endSession();
193
+ }, sessionTimeoutInMilliseconds);
194
+ };
195
+
196
+ this.resetSessionTimer = function(): void {
197
+ if (!mpInstance._Store.webviewBridgeEnabled) {
198
+ if (!mpInstance._Store.sessionId) {
199
+ self.startNewSession();
200
+ }
201
+ self.clearSessionTimeout();
202
+ self.setSessionTimer();
203
+ }
204
+ self.startNewSessionIfNeeded();
205
+ };
206
+
207
+ this.clearSessionTimeout = function(): void {
208
+ clearTimeout(mpInstance._Store.globalTimer);
209
+ };
210
+
211
+ this.startNewSessionIfNeeded = function(): void {
212
+ if (!mpInstance._Store.webviewBridgeEnabled) {
213
+ const persistence = mpInstance._Persistence.getPersistence();
214
+
215
+ if (!mpInstance._Store.sessionId && persistence) {
216
+ if (persistence.sid) {
217
+ mpInstance._Store.sessionId = persistence.sid;
218
+ } else {
219
+ self.startNewSession();
220
+ }
221
+ }
222
+ }
223
+ };
224
+
225
+ function nullifySession(): void {
226
+ mpInstance._Store.sessionId = null;
227
+ mpInstance._Store.dateLastEventSent = null;
228
+ mpInstance._Store.sessionAttributes = {};
229
+ mpInstance._Persistence.update();
230
+ }
231
+ }
package/src/utils.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import slugify from 'slugify';
2
+ import Constants from './constants';
3
+
4
+ const { Messages } = Constants;
2
5
 
3
6
  type valueof<T> = T[keyof T];
4
7
 
@@ -42,6 +45,25 @@ const findKeyInObject = (obj: any, key: string): string => {
42
45
  return null;
43
46
  };
44
47
 
48
+ const generateDeprecationMessage = (
49
+ methodName: string,
50
+ alternateMethod: string
51
+ ): string => {
52
+ const messageArray: string[] = [
53
+ methodName,
54
+ Messages.DeprecationMessages.MethodIsDeprecatedPostfix,
55
+ ];
56
+
57
+ if (alternateMethod) {
58
+ messageArray.push(alternateMethod);
59
+ messageArray.push(
60
+ Messages.DeprecationMessages.MethodIsDeprecatedPostfix
61
+ );
62
+ }
63
+
64
+ return messageArray.join(' ');
65
+ };
66
+
45
67
  function generateHash(name: string): number {
46
68
  let hash: number = 0;
47
69
  let character: number;
@@ -53,7 +75,7 @@ function generateHash(name: string): number {
53
75
  name = name.toString().toLowerCase();
54
76
 
55
77
  if (Array.prototype.reduce) {
56
- return name.split('').reduce(function (a: number, b: string) {
78
+ return name.split('').reduce(function(a: number, b: string) {
57
79
  a = (a << 5) - a + b.charCodeAt(0);
58
80
  return a & a;
59
81
  }, 0);
@@ -140,9 +162,11 @@ const parseStringOrNumber = (
140
162
  }
141
163
  };
142
164
 
143
- const replaceCommasWithPipes = (value: string): string => value.replace(/,/g, '|');
165
+ const replaceCommasWithPipes = (value: string): string =>
166
+ value.replace(/,/g, '|');
144
167
 
145
- const replacePipesWithCommas = (value: string): string => value.replace(/\|/g, ',');
168
+ const replacePipesWithCommas = (value: string): string =>
169
+ value.replace(/\|/g, ',');
146
170
 
147
171
  const replaceApostrophesWithQuotes = (value: string): string =>
148
172
  value.replace(/\'/g, '"');
@@ -167,7 +191,10 @@ const decoded = (s: string): string =>
167
191
 
168
192
  const converted = (s: string): string => {
169
193
  if (s.indexOf('"') === 0) {
170
- s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
194
+ s = s
195
+ .slice(1, -1)
196
+ .replace(/\\"/g, '"')
197
+ .replace(/\\\\/g, '\\');
171
198
  }
172
199
 
173
200
  return s;
@@ -194,6 +221,7 @@ export {
194
221
  converted,
195
222
  decoded,
196
223
  findKeyInObject,
224
+ generateDeprecationMessage,
197
225
  generateHash,
198
226
  generateUniqueId,
199
227
  getRampNumber,
@@ -1,188 +0,0 @@
1
- import Constants from './constants';
2
- import Types from './types';
3
-
4
- var Messages = Constants.Messages;
5
-
6
- function SessionManager(mpInstance) {
7
- var self = this;
8
- this.initialize = function() {
9
- if (mpInstance._Store.sessionId) {
10
- var sessionTimeoutInMilliseconds =
11
- mpInstance._Store.SDKConfig.sessionTimeout * 60000;
12
-
13
- if (
14
- new Date() >
15
- new Date(
16
- mpInstance._Store.dateLastEventSent.getTime() +
17
- sessionTimeoutInMilliseconds
18
- )
19
- ) {
20
- self.endSession();
21
- self.startNewSession();
22
- } else {
23
- var persistence = mpInstance._Persistence.getPersistence();
24
- if (persistence && !persistence.cu) {
25
- mpInstance.Identity.identify(
26
- mpInstance._Store.SDKConfig.identifyRequest,
27
- mpInstance._Store.SDKConfig.identityCallback
28
- );
29
- mpInstance._Store.identifyCalled = true;
30
- mpInstance._Store.SDKConfig.identityCallback = null;
31
- }
32
- }
33
- } else {
34
- self.startNewSession();
35
- }
36
- };
37
-
38
- this.getSession = function() {
39
- return mpInstance._Store.sessionId;
40
- };
41
-
42
- this.startNewSession = function() {
43
- mpInstance.Logger.verbose(
44
- Messages.InformationMessages.StartingNewSession
45
- );
46
-
47
- if (mpInstance._Helpers.canLog()) {
48
- mpInstance._Store.sessionId = mpInstance._Helpers
49
- .generateUniqueId()
50
- .toUpperCase();
51
- var currentUser = mpInstance.Identity.getCurrentUser(),
52
- mpid = currentUser ? currentUser.getMPID() : null;
53
- if (mpid) {
54
- mpInstance._Store.currentSessionMPIDs = [mpid];
55
- }
56
-
57
- if (!mpInstance._Store.sessionStartDate) {
58
- var date = new Date();
59
- mpInstance._Store.sessionStartDate = date;
60
- mpInstance._Store.dateLastEventSent = date;
61
- }
62
-
63
- self.setSessionTimer();
64
-
65
- if (!mpInstance._Store.identifyCalled) {
66
- mpInstance.Identity.identify(
67
- mpInstance._Store.SDKConfig.identifyRequest,
68
- mpInstance._Store.SDKConfig.identityCallback
69
- );
70
- mpInstance._Store.identifyCalled = true;
71
- mpInstance._Store.SDKConfig.identityCallback = null;
72
- }
73
-
74
- mpInstance._Events.logEvent({
75
- messageType: Types.MessageType.SessionStart,
76
- });
77
- } else {
78
- mpInstance.Logger.verbose(
79
- Messages.InformationMessages.AbandonStartSession
80
- );
81
- }
82
- };
83
-
84
- this.endSession = function(override) {
85
- mpInstance.Logger.verbose(
86
- Messages.InformationMessages.StartingEndSession
87
- );
88
-
89
- if (override) {
90
- mpInstance._Events.logEvent({
91
- messageType: Types.MessageType.SessionEnd,
92
- });
93
-
94
- mpInstance._Store.sessionId = null;
95
- mpInstance._Store.dateLastEventSent = null;
96
- mpInstance._Store.sessionAttributes = {};
97
- mpInstance._Persistence.update();
98
- } else if (mpInstance._Helpers.canLog()) {
99
- var sessionTimeoutInMilliseconds, cookies, timeSinceLastEventSent;
100
-
101
- cookies = mpInstance._Persistence.getPersistence();
102
-
103
- if (!cookies) {
104
- return;
105
- }
106
-
107
- if (cookies.gs && !cookies.gs.sid) {
108
- mpInstance.Logger.verbose(
109
- Messages.InformationMessages.NoSessionToEnd
110
- );
111
- return;
112
- }
113
-
114
- // sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
115
- if (
116
- cookies.gs.sid &&
117
- mpInstance._Store.sessionId !== cookies.gs.sid
118
- ) {
119
- mpInstance._Store.sessionId = cookies.gs.sid;
120
- }
121
-
122
- if (cookies.gs && cookies.gs.les) {
123
- sessionTimeoutInMilliseconds =
124
- mpInstance._Store.SDKConfig.sessionTimeout * 60000;
125
- var newDate = new Date().getTime();
126
- timeSinceLastEventSent = newDate - cookies.gs.les;
127
-
128
- if (timeSinceLastEventSent < sessionTimeoutInMilliseconds) {
129
- self.setSessionTimer();
130
- } else {
131
- mpInstance._Events.logEvent({
132
- messageType: Types.MessageType.SessionEnd,
133
- });
134
-
135
- mpInstance._Store.sessionId = null;
136
- mpInstance._Store.dateLastEventSent = null;
137
- mpInstance._Store.sessionStartDate = null;
138
- mpInstance._Store.sessionAttributes = {};
139
- mpInstance._Persistence.update();
140
- }
141
- }
142
- } else {
143
- mpInstance.Logger.verbose(
144
- Messages.InformationMessages.AbandonEndSession
145
- );
146
- }
147
- };
148
-
149
- this.setSessionTimer = function() {
150
- var sessionTimeoutInMilliseconds =
151
- mpInstance._Store.SDKConfig.sessionTimeout * 60000;
152
-
153
- mpInstance._Store.globalTimer = window.setTimeout(function() {
154
- self.endSession();
155
- }, sessionTimeoutInMilliseconds);
156
- };
157
-
158
- this.resetSessionTimer = function() {
159
- if (!mpInstance._Store.webviewBridgeEnabled) {
160
- if (!mpInstance._Store.sessionId) {
161
- self.startNewSession();
162
- }
163
- self.clearSessionTimeout();
164
- self.setSessionTimer();
165
- }
166
- self.startNewSessionIfNeeded();
167
- };
168
-
169
- this.clearSessionTimeout = function() {
170
- clearTimeout(mpInstance._Store.globalTimer);
171
- };
172
-
173
- this.startNewSessionIfNeeded = function() {
174
- if (!mpInstance._Store.webviewBridgeEnabled) {
175
- var persistence = mpInstance._Persistence.getPersistence();
176
-
177
- if (!mpInstance._Store.sessionId && persistence) {
178
- if (persistence.sid) {
179
- mpInstance._Store.sessionId = persistence.sid;
180
- } else {
181
- self.startNewSession();
182
- }
183
- }
184
- }
185
- };
186
- }
187
-
188
- export default SessionManager;