@mparticle/web-sdk 2.23.9 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,11 +61,11 @@ var _TriggerUploadType,MessageType$2={SessionStart:1,SessionEnd:2,PageView:3,Pag
61
61
  // Continuation of enum above, but in seperate object since we don't expose these to end user
62
62
  IdentityType$1.isValid=function(a){if("number"==typeof a)for(var b in IdentityType$1)if(IdentityType$1.hasOwnProperty(b)&&IdentityType$1[b]===a)return !0;return !1},IdentityType$1.getName=function(a){return a===window.mParticle.IdentityType.CustomerId?"Customer ID":a===window.mParticle.IdentityType.Facebook?"Facebook ID":a===window.mParticle.IdentityType.Twitter?"Twitter ID":a===window.mParticle.IdentityType.Google?"Google ID":a===window.mParticle.IdentityType.Microsoft?"Microsoft ID":a===window.mParticle.IdentityType.Yahoo?"Yahoo ID":a===window.mParticle.IdentityType.Email?"Email":a===window.mParticle.IdentityType.FacebookCustomAudienceId?"Facebook App User ID":"Other ID"},IdentityType$1.getIdentityType=function(a){return "other"===a?IdentityType$1.Other:"customerid"===a?IdentityType$1.CustomerId:"facebook"===a?IdentityType$1.Facebook:"twitter"===a?IdentityType$1.Twitter:"google"===a?IdentityType$1.Google:"microsoft"===a?IdentityType$1.Microsoft:"yahoo"===a?IdentityType$1.Yahoo:"email"===a?IdentityType$1.Email:"facebookcustomaudienceid"===a?IdentityType$1.FacebookCustomAudienceId:"other2"===a?IdentityType$1.Other2:"other3"===a?IdentityType$1.Other3:"other4"===a?IdentityType$1.Other4:"other5"===a?IdentityType$1.Other5:"other6"===a?IdentityType$1.Other6:"other7"===a?IdentityType$1.Other7:"other8"===a?IdentityType$1.Other8:"other9"===a?IdentityType$1.Other9:"other10"===a?IdentityType$1.Other10:"mobile_number"===a?IdentityType$1.MobileNumber:"phone_number_2"===a?IdentityType$1.PhoneNumber2:!("phone_number_3"!=a)&&IdentityType$1.PhoneNumber3},IdentityType$1.getIdentityName=function(a){return a===IdentityType$1.Other?"other":a===IdentityType$1.CustomerId?"customerid":a===IdentityType$1.Facebook?"facebook":a===IdentityType$1.Twitter?"twitter":a===IdentityType$1.Google?"google":a===IdentityType$1.Microsoft?"microsoft":a===IdentityType$1.Yahoo?"yahoo":a===IdentityType$1.Email?"email":a===IdentityType$1.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType$1.Other2?"other2":a===IdentityType$1.Other3?"other3":a===IdentityType$1.Other4?"other4":a===IdentityType$1.Other5?"other5":a===IdentityType$1.Other6?"other6":a===IdentityType$1.Other7?"other7":a===IdentityType$1.Other8?"other8":a===IdentityType$1.Other9?"other9":a===IdentityType$1.Other10?"other10":a===IdentityType$1.MobileNumber?"mobile_number":a===IdentityType$1.PhoneNumber2?"phone_number_2":a===IdentityType$1.PhoneNumber3?"phone_number_3":void 0};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10};ProductActionType.getName=function(a){return a===ProductActionType.AddToCart?"Add to Cart":a===ProductActionType.RemoveFromCart?"Remove from Cart":a===ProductActionType.Checkout?"Checkout":a===ProductActionType.CheckoutOption?"Checkout Option":a===ProductActionType.Click?"Click":a===ProductActionType.ViewDetail?"View Detail":a===ProductActionType.Purchase?"Purchase":a===ProductActionType.Refund?"Refund":a===ProductActionType.AddToWishlist?"Add to Wishlist":a===ProductActionType.RemoveFromWishlist?"Remove from Wishlist":"Unknown"},ProductActionType.getExpansionName=function(a){return a===ProductActionType.AddToCart?"add_to_cart":a===ProductActionType.RemoveFromCart?"remove_from_cart":a===ProductActionType.Checkout?"checkout":a===ProductActionType.CheckoutOption?"checkout_option":a===ProductActionType.Click?"click":a===ProductActionType.ViewDetail?"view_detail":a===ProductActionType.Purchase?"purchase":a===ProductActionType.Refund?"refund":a===ProductActionType.AddToWishlist?"add_to_wishlist":a===ProductActionType.RemoveFromWishlist?"remove_from_wishlist":"unknown"};var PromotionActionType={Unknown:0,PromotionView:1,PromotionClick:2};PromotionActionType.getName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},PromotionActionType.getExpansionName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"};var ProfileMessageType={Logout:3},ApplicationTransitionType$1={AppInit:1},Environment={Production:"production",Development:"development"};var Types = {MessageType:MessageType$2,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType$1,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType,Environment:Environment};
63
63
 
64
- var version = "2.23.9";
64
+ var version = "2.24.0";
65
65
 
66
- var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload
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},// https://go.mparticle.com/work/SQDSDKS-6039
68
- SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};
66
+ var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
67
+ },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
68
+ SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};
69
69
 
70
70
  /******************************************************************************
71
71
  Copyright (c) Microsoft Corporation.
@@ -147,6 +147,16 @@ function __generator(thisArg, body) {
147
147
  }
148
148
  }
149
149
 
150
+ function __spreadArray(to, from, pack) {
151
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
152
+ if (ar || !(i in from)) {
153
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
154
+ ar[i] = from[i];
155
+ }
156
+ }
157
+ return to.concat(ar || Array.prototype.slice.call(from));
158
+ }
159
+
150
160
  typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
151
161
  var e = new Error(message);
152
162
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
@@ -447,7 +457,7 @@ if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.p
447
457
  return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
448
458
  return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a}();var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}(),FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,fetch(this.url,a)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b}(AsyncUploader),XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(){return c=new XMLHttpRequest,[2/*return*/,new Promise(function(d,e){c.onreadystatechange=function(){4!==c.readyState||(200<=c.status&&300>c.status?d(c):e(c));},c.open("post",a),c.send(b);})]})})},b}(AsyncUploader);
449
459
 
450
- function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){var c=a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis);this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
460
+ function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
451
461
  this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(b,c){c.forEach(function(c){c.MPID||a._ServerModel.appendUserInfo(b,c);});},this.sendEventToServer=function(c,d){var e=a._Helpers.extend({shouldUploadEvent:!0},d);if(a._Store.webviewBridgeEnabled)return void a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent,JSON.stringify(c));var f,g=a.Identity.getCurrentUser();// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
452
462
  // need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
453
463
  return (g&&(f=g.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),!f||a._Store.requireDelay||!a._Store.configurationLoaded)?(a.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void a._Store.eventQueue.push(c)):void(this.processQueuedEvents(),isEmpty(c)||(e.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&a._Forwarders.sendEventToForwarders(c))))},this.sendBatchForwardingStatsToServer=function(b,c){var d,e;try{d=a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken),e={uuid:a._Helpers.generateUniqueId(),data:b},c&&(c.open("post",d+"/Forwarding"),c.send(JSON.stringify(e)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.sendSingleForwardingStatsToServer=function(b){var c,d;try{var e=function(){4===f.readyState&&202===f.status&&a.Logger.verbose("Successfully sent "+f.statusText+" from server");},f=a._Helpers.createXHR(e);c=a._Helpers.createServiceUrl(a._Store.SDKConfig.v1SecureServiceUrl,a._Store.devToken),d=b,f&&(f.open("post",c+"/Forwarding"),f.send(JSON.stringify(d)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.prepareForwardingStats=function(b,d){var e,f=a._Forwarders.getForwarderStatsQueue();b&&b.isVisible&&(e={mid:b.id,esid:b.eventSubscriptionId,n:d.EventName,attrs:d.EventAttributes,sdk:d.SDKVersion,dt:d.EventDataType,et:d.EventCategory,dbg:d.Debug,ct:d.Timestamp,eec:d.ExpandedEventCount,dp:d.DataPlan},a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(f.push(e),a._Forwarders.setForwarderStatsQueue(f)):c.sendSingleForwardingStatsToServer(e));};}
@@ -530,9 +540,24 @@ this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty(
530
540
  return a._Helpers.parseNumber(b)};}
531
541
 
532
542
  function createSDKConfig(a){// TODO: Refactor to create a default config object
533
- var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultUrls)b[c]=Constants.DefaultUrls[c];return b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
534
- function Store(a,b){var c={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1}};for(var d in c)this[d]=c[d];// Set configuration to default settings
535
- if(this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){if(a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode),a.hasOwnProperty("v1SecureServiceUrl")&&(this.SDKConfig.v1SecureServiceUrl=a.v1SecureServiceUrl),a.hasOwnProperty("v2SecureServiceUrl")&&(this.SDKConfig.v2SecureServiceUrl=a.v2SecureServiceUrl),a.hasOwnProperty("v3SecureServiceUrl")&&(this.SDKConfig.v3SecureServiceUrl=a.v3SecureServiceUrl),a.hasOwnProperty("identityUrl")&&(this.SDKConfig.identityUrl=a.identityUrl),a.hasOwnProperty("aliasUrl")&&(this.SDKConfig.aliasUrl=a.aliasUrl),a.hasOwnProperty("configUrl")&&(this.SDKConfig.configUrl=a.configUrl),a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var e=a.identityCallback;b._Helpers.Validators.isFunction(e)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(e)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var f=a.dataPlan;f.planId&&(isDataPlanSlug(f.planId)?this.SDKConfig.dataPlan.PlanId=f.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),f.planVersion&&(isNumber(f.planVersion)?this.SDKConfig.dataPlan.PlanVersion=f.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var g=a.dataPlanOptions;g.hasOwnProperty("dataPlanVersion")&&g.hasOwnProperty("blockUserAttributes")&&g.hasOwnProperty("blockEventAttributes")&&g.hasOwnProperty("blockEvents")&&g.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0)),a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)||(this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=Constants.DefaultConfig.uploadInterval),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)||(this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching]=!1),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.OfflineStorage)||(this.SDKConfig.flags[Constants.FeatureFlags.OfflineStorage]=0);}}
543
+ var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];return b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
544
+ function Store(a,b,c){var d={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1}};for(var e in d)this[e]=d[e];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a,this.SDKConfig),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode);var f=processBaseUrls(a,this.SDKConfig.flags,c);for(var g in f)this.SDKConfig[g]=f[g];if(a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var h=a.identityCallback;b._Helpers.Validators.isFunction(h)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(h)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var i=a.dataPlan;i.planId&&(isDataPlanSlug(i.planId)?this.SDKConfig.dataPlan.PlanId=i.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),i.planVersion&&(isNumber(i.planVersion)?this.SDKConfig.dataPlan.PlanVersion=i.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var j=a.dataPlanOptions;j.hasOwnProperty("dataPlanVersion")&&j.hasOwnProperty("blockUserAttributes")&&j.hasOwnProperty("blockEventAttributes")&&j.hasOwnProperty("blockEvents")&&j.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}}function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b):{};// Passed in config flags take priority over defaults
545
+ }function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
546
+ if(!c)return {};// Set default baseUrls
547
+ // When direct URL routing is false, update baseUrls based custom urls
548
+ // passed to the config
549
+ return b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a)}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c={};// If there is no custo base url, we use the default base url
550
+ for(var d in b)c[d]=a[d]||b[d];return c}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that
551
+ // include the silo in the urls. mParticle API keys are prefixed with the
552
+ // silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo,
553
+ // and before other silos existed, there were no prefixes and all apiKeys
554
+ // were us1. As such, if we split on a '-' and the resulting array length
555
+ // is 1, then it is an older APIkey that should route to us1.
556
+ // When splitKey.length is greater than 1, then splitKey[0] will be
557
+ // us1, us2, eu1, au1, or st1, etc as new silos are added
558
+ for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct
559
+ // mapping to the silo. The most common use case is a customer provided CNAME.
560
+ if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d}
536
561
 
537
562
  function Logger(a){var b=this,c=a.logLevel||"warning";this.logger=a.hasOwnProperty("logger")?a.logger:new ConsoleLogger,this.verbose=function(a){"none"!==c&&b.logger.verbose&&"verbose"===c&&b.logger.verbose(a);},this.warning=function(a){"none"!==c&&b.logger.warning&&("verbose"===c||"warning"===c)&&b.logger.warning(a);},this.error=function(a){"none"!==c&&b.logger.error&&b.logger.error(a);},this.setLogLevel=function(a){c=a;};}function ConsoleLogger(){this.verbose=function(a){console&&console.info&&console.info(a);},this.error=function(a){console&&console.error&&console.error(a);},this.warning=function(a){console&&console.warn&&console.warn(a);};}
538
563
 
@@ -1242,7 +1267,7 @@ if(c._Helpers.isObject(c._Store.SDKConfig.identifyRequest)&&c._Helpers.isObject(
1242
1267
  If not passed in manually, we user the server provided via either
1243
1268
  2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
1244
1269
  3. Self hosting via /config endpoint (config.dataPlanResult)
1245
- */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a),window.mParticle.Store=a._Store,a._Store.devToken=b||null,a.Logger.verbose(Messages.InformationMessages.StartingInitialization);// Check to see if localStorage is available before main configuration runs
1270
+ */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(Messages.InformationMessages.StartingInitialization);// Check to see if localStorage is available before main configuration runs
1246
1271
  // since we will need this for the current implementation of user persistence
1247
1272
  // TODO: Refactor this when we refactor User Identity Persistence
1248
1273
  try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processPreloadedItem(a,b){var c=a,d=c.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
@@ -61,11 +61,11 @@ var _TriggerUploadType,MessageType$2={SessionStart:1,SessionEnd:2,PageView:3,Pag
61
61
  // Continuation of enum above, but in seperate object since we don't expose these to end user
62
62
  IdentityType$1.isValid=function(a){if("number"==typeof a)for(var b in IdentityType$1)if(IdentityType$1.hasOwnProperty(b)&&IdentityType$1[b]===a)return !0;return !1},IdentityType$1.getName=function(a){return a===window.mParticle.IdentityType.CustomerId?"Customer ID":a===window.mParticle.IdentityType.Facebook?"Facebook ID":a===window.mParticle.IdentityType.Twitter?"Twitter ID":a===window.mParticle.IdentityType.Google?"Google ID":a===window.mParticle.IdentityType.Microsoft?"Microsoft ID":a===window.mParticle.IdentityType.Yahoo?"Yahoo ID":a===window.mParticle.IdentityType.Email?"Email":a===window.mParticle.IdentityType.FacebookCustomAudienceId?"Facebook App User ID":"Other ID"},IdentityType$1.getIdentityType=function(a){return "other"===a?IdentityType$1.Other:"customerid"===a?IdentityType$1.CustomerId:"facebook"===a?IdentityType$1.Facebook:"twitter"===a?IdentityType$1.Twitter:"google"===a?IdentityType$1.Google:"microsoft"===a?IdentityType$1.Microsoft:"yahoo"===a?IdentityType$1.Yahoo:"email"===a?IdentityType$1.Email:"facebookcustomaudienceid"===a?IdentityType$1.FacebookCustomAudienceId:"other2"===a?IdentityType$1.Other2:"other3"===a?IdentityType$1.Other3:"other4"===a?IdentityType$1.Other4:"other5"===a?IdentityType$1.Other5:"other6"===a?IdentityType$1.Other6:"other7"===a?IdentityType$1.Other7:"other8"===a?IdentityType$1.Other8:"other9"===a?IdentityType$1.Other9:"other10"===a?IdentityType$1.Other10:"mobile_number"===a?IdentityType$1.MobileNumber:"phone_number_2"===a?IdentityType$1.PhoneNumber2:!("phone_number_3"!=a)&&IdentityType$1.PhoneNumber3},IdentityType$1.getIdentityName=function(a){return a===IdentityType$1.Other?"other":a===IdentityType$1.CustomerId?"customerid":a===IdentityType$1.Facebook?"facebook":a===IdentityType$1.Twitter?"twitter":a===IdentityType$1.Google?"google":a===IdentityType$1.Microsoft?"microsoft":a===IdentityType$1.Yahoo?"yahoo":a===IdentityType$1.Email?"email":a===IdentityType$1.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType$1.Other2?"other2":a===IdentityType$1.Other3?"other3":a===IdentityType$1.Other4?"other4":a===IdentityType$1.Other5?"other5":a===IdentityType$1.Other6?"other6":a===IdentityType$1.Other7?"other7":a===IdentityType$1.Other8?"other8":a===IdentityType$1.Other9?"other9":a===IdentityType$1.Other10?"other10":a===IdentityType$1.MobileNumber?"mobile_number":a===IdentityType$1.PhoneNumber2?"phone_number_2":a===IdentityType$1.PhoneNumber3?"phone_number_3":void 0};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10};ProductActionType.getName=function(a){return a===ProductActionType.AddToCart?"Add to Cart":a===ProductActionType.RemoveFromCart?"Remove from Cart":a===ProductActionType.Checkout?"Checkout":a===ProductActionType.CheckoutOption?"Checkout Option":a===ProductActionType.Click?"Click":a===ProductActionType.ViewDetail?"View Detail":a===ProductActionType.Purchase?"Purchase":a===ProductActionType.Refund?"Refund":a===ProductActionType.AddToWishlist?"Add to Wishlist":a===ProductActionType.RemoveFromWishlist?"Remove from Wishlist":"Unknown"},ProductActionType.getExpansionName=function(a){return a===ProductActionType.AddToCart?"add_to_cart":a===ProductActionType.RemoveFromCart?"remove_from_cart":a===ProductActionType.Checkout?"checkout":a===ProductActionType.CheckoutOption?"checkout_option":a===ProductActionType.Click?"click":a===ProductActionType.ViewDetail?"view_detail":a===ProductActionType.Purchase?"purchase":a===ProductActionType.Refund?"refund":a===ProductActionType.AddToWishlist?"add_to_wishlist":a===ProductActionType.RemoveFromWishlist?"remove_from_wishlist":"unknown"};var PromotionActionType={Unknown:0,PromotionView:1,PromotionClick:2};PromotionActionType.getName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},PromotionActionType.getExpansionName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"};var ProfileMessageType={Logout:3},ApplicationTransitionType$1={AppInit:1},Environment={Production:"production",Development:"development"};var Types = {MessageType:MessageType$2,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType$1,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType,Environment:Environment};
63
63
 
64
- var version = "2.23.9";
64
+ var version = "2.24.0";
65
65
 
66
- var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload
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},// https://go.mparticle.com/work/SQDSDKS-6039
68
- SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};
66
+ var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
67
+ },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
68
+ SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};
69
69
 
70
70
  /******************************************************************************
71
71
  Copyright (c) Microsoft Corporation.
@@ -147,6 +147,16 @@ function __generator(thisArg, body) {
147
147
  }
148
148
  }
149
149
 
150
+ function __spreadArray(to, from, pack) {
151
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
152
+ if (ar || !(i in from)) {
153
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
154
+ ar[i] = from[i];
155
+ }
156
+ }
157
+ return to.concat(ar || Array.prototype.slice.call(from));
158
+ }
159
+
150
160
  typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
151
161
  var e = new Error(message);
152
162
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
@@ -447,7 +457,7 @@ if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.p
447
457
  return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
448
458
  return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a}();var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}(),FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,fetch(this.url,a)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b}(AsyncUploader),XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(){return c=new XMLHttpRequest,[2/*return*/,new Promise(function(d,e){c.onreadystatechange=function(){4!==c.readyState||(200<=c.status&&300>c.status?d(c):e(c));},c.open("post",a),c.send(b);})]})})},b}(AsyncUploader);
449
459
 
450
- function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){var c=a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis);this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
460
+ function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
451
461
  this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(b,c){c.forEach(function(c){c.MPID||a._ServerModel.appendUserInfo(b,c);});},this.sendEventToServer=function(c,d){var e=a._Helpers.extend({shouldUploadEvent:!0},d);if(a._Store.webviewBridgeEnabled)return void a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent,JSON.stringify(c));var f,g=a.Identity.getCurrentUser();// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
452
462
  // need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
453
463
  return (g&&(f=g.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),!f||a._Store.requireDelay||!a._Store.configurationLoaded)?(a.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void a._Store.eventQueue.push(c)):void(this.processQueuedEvents(),isEmpty(c)||(e.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&a._Forwarders.sendEventToForwarders(c))))},this.sendBatchForwardingStatsToServer=function(b,c){var d,e;try{d=a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken),e={uuid:a._Helpers.generateUniqueId(),data:b},c&&(c.open("post",d+"/Forwarding"),c.send(JSON.stringify(e)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.sendSingleForwardingStatsToServer=function(b){var c,d;try{var e=function(){4===f.readyState&&202===f.status&&a.Logger.verbose("Successfully sent "+f.statusText+" from server");},f=a._Helpers.createXHR(e);c=a._Helpers.createServiceUrl(a._Store.SDKConfig.v1SecureServiceUrl,a._Store.devToken),d=b,f&&(f.open("post",c+"/Forwarding"),f.send(JSON.stringify(d)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.prepareForwardingStats=function(b,d){var e,f=a._Forwarders.getForwarderStatsQueue();b&&b.isVisible&&(e={mid:b.id,esid:b.eventSubscriptionId,n:d.EventName,attrs:d.EventAttributes,sdk:d.SDKVersion,dt:d.EventDataType,et:d.EventCategory,dbg:d.Debug,ct:d.Timestamp,eec:d.ExpandedEventCount,dp:d.DataPlan},a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(f.push(e),a._Forwarders.setForwarderStatsQueue(f)):c.sendSingleForwardingStatsToServer(e));};}
@@ -530,9 +540,24 @@ this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty(
530
540
  return a._Helpers.parseNumber(b)};}
531
541
 
532
542
  function createSDKConfig(a){// TODO: Refactor to create a default config object
533
- var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultUrls)b[c]=Constants.DefaultUrls[c];return b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
534
- function Store(a,b){var c={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1}};for(var d in c)this[d]=c[d];// Set configuration to default settings
535
- if(this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){if(a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode),a.hasOwnProperty("v1SecureServiceUrl")&&(this.SDKConfig.v1SecureServiceUrl=a.v1SecureServiceUrl),a.hasOwnProperty("v2SecureServiceUrl")&&(this.SDKConfig.v2SecureServiceUrl=a.v2SecureServiceUrl),a.hasOwnProperty("v3SecureServiceUrl")&&(this.SDKConfig.v3SecureServiceUrl=a.v3SecureServiceUrl),a.hasOwnProperty("identityUrl")&&(this.SDKConfig.identityUrl=a.identityUrl),a.hasOwnProperty("aliasUrl")&&(this.SDKConfig.aliasUrl=a.aliasUrl),a.hasOwnProperty("configUrl")&&(this.SDKConfig.configUrl=a.configUrl),a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var e=a.identityCallback;b._Helpers.Validators.isFunction(e)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(e)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var f=a.dataPlan;f.planId&&(isDataPlanSlug(f.planId)?this.SDKConfig.dataPlan.PlanId=f.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),f.planVersion&&(isNumber(f.planVersion)?this.SDKConfig.dataPlan.PlanVersion=f.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var g=a.dataPlanOptions;g.hasOwnProperty("dataPlanVersion")&&g.hasOwnProperty("blockUserAttributes")&&g.hasOwnProperty("blockEventAttributes")&&g.hasOwnProperty("blockEvents")&&g.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0)),a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)||(this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=Constants.DefaultConfig.uploadInterval),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)||(this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching]=!1),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.OfflineStorage)||(this.SDKConfig.flags[Constants.FeatureFlags.OfflineStorage]=0);}}
543
+ var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];return b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
544
+ function Store(a,b,c){var d={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1}};for(var e in d)this[e]=d[e];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a,this.SDKConfig),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode);var f=processBaseUrls(a,this.SDKConfig.flags,c);for(var g in f)this.SDKConfig[g]=f[g];if(a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var h=a.identityCallback;b._Helpers.Validators.isFunction(h)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(h)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var i=a.dataPlan;i.planId&&(isDataPlanSlug(i.planId)?this.SDKConfig.dataPlan.PlanId=i.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),i.planVersion&&(isNumber(i.planVersion)?this.SDKConfig.dataPlan.PlanVersion=i.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var j=a.dataPlanOptions;j.hasOwnProperty("dataPlanVersion")&&j.hasOwnProperty("blockUserAttributes")&&j.hasOwnProperty("blockEventAttributes")&&j.hasOwnProperty("blockEvents")&&j.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}}function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b):{};// Passed in config flags take priority over defaults
545
+ }function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
546
+ if(!c)return {};// Set default baseUrls
547
+ // When direct URL routing is false, update baseUrls based custom urls
548
+ // passed to the config
549
+ return b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a)}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c={};// If there is no custo base url, we use the default base url
550
+ for(var d in b)c[d]=a[d]||b[d];return c}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that
551
+ // include the silo in the urls. mParticle API keys are prefixed with the
552
+ // silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo,
553
+ // and before other silos existed, there were no prefixes and all apiKeys
554
+ // were us1. As such, if we split on a '-' and the resulting array length
555
+ // is 1, then it is an older APIkey that should route to us1.
556
+ // When splitKey.length is greater than 1, then splitKey[0] will be
557
+ // us1, us2, eu1, au1, or st1, etc as new silos are added
558
+ for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct
559
+ // mapping to the silo. The most common use case is a customer provided CNAME.
560
+ if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d}
536
561
 
537
562
  function Logger(a){var b=this,c=a.logLevel||"warning";this.logger=a.hasOwnProperty("logger")?a.logger:new ConsoleLogger,this.verbose=function(a){"none"!==c&&b.logger.verbose&&"verbose"===c&&b.logger.verbose(a);},this.warning=function(a){"none"!==c&&b.logger.warning&&("verbose"===c||"warning"===c)&&b.logger.warning(a);},this.error=function(a){"none"!==c&&b.logger.error&&b.logger.error(a);},this.setLogLevel=function(a){c=a;};}function ConsoleLogger(){this.verbose=function(a){console&&console.info&&console.info(a);},this.error=function(a){console&&console.error&&console.error(a);},this.warning=function(a){console&&console.warn&&console.warn(a);};}
538
563
 
@@ -1242,7 +1267,7 @@ if(c._Helpers.isObject(c._Store.SDKConfig.identifyRequest)&&c._Helpers.isObject(
1242
1267
  If not passed in manually, we user the server provided via either
1243
1268
  2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
1244
1269
  3. Self hosting via /config endpoint (config.dataPlanResult)
1245
- */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a),window.mParticle.Store=a._Store,a._Store.devToken=b||null,a.Logger.verbose(Messages.InformationMessages.StartingInitialization);// Check to see if localStorage is available before main configuration runs
1270
+ */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(Messages.InformationMessages.StartingInitialization);// Check to see if localStorage is available before main configuration runs
1246
1271
  // since we will need this for the current implementation of user persistence
1247
1272
  // TODO: Refactor this when we refactor User Identity Persistence
1248
1273
  try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processPreloadedItem(a,b){var c=a,d=c.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
package/dist/mparticle.js CHANGED
@@ -608,7 +608,7 @@ var mParticle = (function () {
608
608
  Environment: Environment
609
609
  };
610
610
 
611
- var version = "2.23.9";
611
+ var version = "2.24.0";
612
612
 
613
613
  var Constants = {
614
614
  sdkVersion: version,
@@ -721,10 +721,10 @@ var mParticle = (function () {
721
721
  integrationDelayTimeout: 5000,
722
722
  maxCookieSize: 3000,
723
723
  aliasMaxWindow: 90,
724
- uploadInterval: 0 // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload
724
+ uploadInterval: 0 // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
725
725
  },
726
726
 
727
- DefaultUrls: {
727
+ DefaultBaseUrls: {
728
728
  v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/',
729
729
  v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/',
730
730
  v3SecureServiceUrl: 'jssdks.mparticle.com/v3/JS/',
@@ -762,7 +762,8 @@ var mParticle = (function () {
762
762
  FeatureFlags: {
763
763
  ReportBatching: 'reportBatching',
764
764
  EventBatchingIntervalMillis: 'eventBatchingIntervalMillis',
765
- OfflineStorage: 'offlineStorage'
765
+ OfflineStorage: 'offlineStorage',
766
+ DirectUrlRouting: 'directURLRouting'
766
767
  },
767
768
  DefaultInstance: 'default_instance',
768
769
  CCPAPurpose: 'data_sale_opt_out',
@@ -854,6 +855,16 @@ var mParticle = (function () {
854
855
  }
855
856
  }
856
857
 
858
+ function __spreadArray(to, from, pack) {
859
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
860
+ if (ar || !(i in from)) {
861
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
862
+ ar[i] = from[i];
863
+ }
864
+ }
865
+ return to.concat(ar || Array.prototype.slice.call(from));
866
+ }
867
+
857
868
  typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
858
869
  var e = new Error(message);
859
870
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
@@ -2373,7 +2384,7 @@ var mParticle = (function () {
2373
2384
  var self = this;
2374
2385
  this.queueEventForBatchUpload = function (event) {
2375
2386
  if (!this.uploader) {
2376
- var millis = mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis);
2387
+ var millis = parseNumber(mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));
2377
2388
  this.uploader = new BatchUploader(mpInstance, millis);
2378
2389
  }
2379
2390
  this.uploader.queueEvent(event);
@@ -3757,13 +3768,13 @@ var mParticle = (function () {
3757
3768
  }
3758
3769
  }
3759
3770
  }
3760
- for (var prop in Constants.DefaultUrls) {
3761
- sdkConfig[prop] = Constants.DefaultUrls[prop];
3771
+ for (var prop in Constants.DefaultBaseUrls) {
3772
+ sdkConfig[prop] = Constants.DefaultBaseUrls[prop];
3762
3773
  }
3763
3774
  return sdkConfig;
3764
3775
  }
3765
3776
  // TODO: Merge this with SDKStoreApi in sdkRuntimeModels
3766
- function Store(config, mpInstance) {
3777
+ function Store(config, mpInstance, apiKey) {
3767
3778
  var defaultStore = {
3768
3779
  isEnabled: true,
3769
3780
  sessionAttributes: {},
@@ -3811,10 +3822,15 @@ var mParticle = (function () {
3811
3822
  for (var key in defaultStore) {
3812
3823
  this[key] = defaultStore[key];
3813
3824
  }
3825
+ this.devToken = apiKey || null;
3814
3826
  this.integrationDelayTimeoutStart = Date.now();
3815
- this.SDKConfig = createSDKConfig(config);
3816
3827
  // Set configuration to default settings
3828
+ this.SDKConfig = createSDKConfig(config);
3817
3829
  if (config) {
3830
+ if (!config.hasOwnProperty('flags')) {
3831
+ this.SDKConfig.flags = {};
3832
+ }
3833
+ this.SDKConfig.flags = processFlags(config, this.SDKConfig);
3818
3834
  if (config.deviceId) {
3819
3835
  this.deviceId = config.deviceId;
3820
3836
  }
@@ -3823,23 +3839,9 @@ var mParticle = (function () {
3823
3839
  } else {
3824
3840
  this.SDKConfig.isDevelopmentMode = false;
3825
3841
  }
3826
- if (config.hasOwnProperty('v1SecureServiceUrl')) {
3827
- this.SDKConfig.v1SecureServiceUrl = config.v1SecureServiceUrl;
3828
- }
3829
- if (config.hasOwnProperty('v2SecureServiceUrl')) {
3830
- this.SDKConfig.v2SecureServiceUrl = config.v2SecureServiceUrl;
3831
- }
3832
- if (config.hasOwnProperty('v3SecureServiceUrl')) {
3833
- this.SDKConfig.v3SecureServiceUrl = config.v3SecureServiceUrl;
3834
- }
3835
- if (config.hasOwnProperty('identityUrl')) {
3836
- this.SDKConfig.identityUrl = config.identityUrl;
3837
- }
3838
- if (config.hasOwnProperty('aliasUrl')) {
3839
- this.SDKConfig.aliasUrl = config.aliasUrl;
3840
- }
3841
- if (config.hasOwnProperty('configUrl')) {
3842
- this.SDKConfig.configUrl = config.configUrl;
3842
+ var baseUrls = processBaseUrls(config, this.SDKConfig.flags, apiKey);
3843
+ for (var baseUrlKeys in baseUrls) {
3844
+ this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys];
3843
3845
  }
3844
3846
  if (config.hasOwnProperty('logLevel')) {
3845
3847
  this.SDKConfig.logLevel = config.logLevel;
@@ -3953,19 +3955,77 @@ var mParticle = (function () {
3953
3955
  this.SDKConfig.onCreateBatch = undefined;
3954
3956
  }
3955
3957
  }
3956
- if (!config.hasOwnProperty('flags')) {
3957
- this.SDKConfig.flags = {};
3958
- }
3959
- if (!this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)) {
3960
- this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis] = Constants.DefaultConfig.uploadInterval;
3961
- }
3962
- if (!this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)) {
3963
- this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching] = false;
3964
- }
3965
- if (!this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.OfflineStorage)) {
3966
- this.SDKConfig.flags[Constants.FeatureFlags.OfflineStorage] = 0;
3958
+ }
3959
+ }
3960
+ function processFlags(config, SDKConfig) {
3961
+ var flags = {};
3962
+ var _a = Constants.FeatureFlags,
3963
+ ReportBatching = _a.ReportBatching,
3964
+ EventBatchingIntervalMillis = _a.EventBatchingIntervalMillis,
3965
+ OfflineStorage = _a.OfflineStorage,
3966
+ DirectUrlRouting = _a.DirectUrlRouting;
3967
+ if (!config.flags) {
3968
+ return {};
3969
+ }
3970
+ // Passed in config flags take priority over defaults
3971
+ flags[ReportBatching] = config.flags[ReportBatching] || false;
3972
+ // The server returns stringified numbers, sowe need to parse
3973
+ flags[EventBatchingIntervalMillis] = parseNumber(config.flags[EventBatchingIntervalMillis]) || Constants.DefaultConfig.uploadInterval;
3974
+ flags[OfflineStorage] = config.flags[OfflineStorage] || '0';
3975
+ flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === 'True';
3976
+ return flags;
3977
+ }
3978
+ function processBaseUrls(config, flags, apiKey) {
3979
+ // an API key is not present in a webview only mode. In this case, no baseUrls are needed
3980
+ if (!apiKey) {
3981
+ return {};
3982
+ }
3983
+ // When direct URL routing is false, update baseUrls based custom urls
3984
+ // passed to the config
3985
+ if (flags.directURLRouting) {
3986
+ return processDirectBaseUrls(config, apiKey);
3987
+ } else {
3988
+ return processCustomBaseUrls(config);
3989
+ }
3990
+ }
3991
+ function processCustomBaseUrls(config) {
3992
+ var defaultBaseUrls = Constants.DefaultBaseUrls;
3993
+ var newBaseUrls = {};
3994
+ // If there is no custo base url, we use the default base url
3995
+ for (var baseUrlKey in defaultBaseUrls) {
3996
+ newBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey];
3997
+ }
3998
+ return newBaseUrls;
3999
+ }
4000
+ function processDirectBaseUrls(config, apiKey) {
4001
+ var defaultBaseUrls = Constants.DefaultBaseUrls;
4002
+ var directBaseUrls = {};
4003
+ // When Direct URL Routing is true, we create a new set of baseUrls that
4004
+ // include the silo in the urls. mParticle API keys are prefixed with the
4005
+ // silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo,
4006
+ // and before other silos existed, there were no prefixes and all apiKeys
4007
+ // were us1. As such, if we split on a '-' and the resulting array length
4008
+ // is 1, then it is an older APIkey that should route to us1.
4009
+ // When splitKey.length is greater than 1, then splitKey[0] will be
4010
+ // us1, us2, eu1, au1, or st1, etc as new silos are added
4011
+ var DEFAULT_SILO = 'us1';
4012
+ var splitKey = apiKey.split('-');
4013
+ var routingPrefix = splitKey.length <= 1 ? DEFAULT_SILO : splitKey[0];
4014
+ for (var baseUrlKey in defaultBaseUrls) {
4015
+ // Any custom endpoints passed to mpConfig will take priority over direct
4016
+ // mapping to the silo. The most common use case is a customer provided CNAME.
4017
+ if (baseUrlKey === 'configUrl') {
4018
+ directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey];
4019
+ continue;
4020
+ }
4021
+ if (config.hasOwnProperty(baseUrlKey)) {
4022
+ directBaseUrls[baseUrlKey] = config[baseUrlKey];
4023
+ } else {
4024
+ var urlparts = defaultBaseUrls[baseUrlKey].split('.');
4025
+ directBaseUrls[baseUrlKey] = __spreadArray([urlparts[0], routingPrefix], urlparts.slice(1), true).join('.');
3967
4026
  }
3968
4027
  }
4028
+ return directBaseUrls;
3969
4029
  }
3970
4030
 
3971
4031
  function Logger(config) {
@@ -9080,9 +9140,8 @@ var mParticle = (function () {
9080
9140
  }
9081
9141
  function runPreConfigFetchInitialization(mpInstance, apiKey, config) {
9082
9142
  mpInstance.Logger = new Logger(config);
9083
- mpInstance._Store = new Store(config, mpInstance);
9143
+ mpInstance._Store = new Store(config, mpInstance, apiKey);
9084
9144
  window.mParticle.Store = mpInstance._Store;
9085
- mpInstance._Store.devToken = apiKey || null;
9086
9145
  mpInstance.Logger.verbose(Messages.InformationMessages.StartingInitialization);
9087
9146
 
9088
9147
  // Check to see if localStorage is available before main configuration runs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.23.9",
3
+ "version": "2.24.0",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/apiClient.ts CHANGED
@@ -3,7 +3,7 @@ import Types from './types';
3
3
  import { BatchUploader } from './batchUploader';
4
4
  import { MParticleUser, MParticleWebSDK, SDKEvent } from './sdkRuntimeModels';
5
5
  import KitBlocker from './kitBlocking';
6
- import { Dictionary, isEmpty } from './utils';
6
+ import { Dictionary, getRampNumber, isEmpty, parseNumber } from './utils';
7
7
  import { IUploadObject } from './serverModel';
8
8
  import { MPForwarder } from './forwarders.interfaces';
9
9
 
@@ -38,9 +38,9 @@ export default function APIClient(
38
38
  const self = this;
39
39
  this.queueEventForBatchUpload = function(event: SDKEvent) {
40
40
  if (!this.uploader) {
41
- const millis = mpInstance._Helpers.getFeatureFlag(
41
+ const millis: number = parseNumber(mpInstance._Helpers.getFeatureFlag(
42
42
  Constants.FeatureFlags.EventBatchingIntervalMillis
43
- );
43
+ ));
44
44
  this.uploader = new BatchUploader(mpInstance, millis);
45
45
  }
46
46
  this.uploader.queueEvent(event);
package/src/constants.ts CHANGED
@@ -126,9 +126,9 @@ const Constants = {
126
126
  integrationDelayTimeout: 5000, // Milliseconds for forcing the integration delay to un-suspend event queueing due to integration partner errors
127
127
  maxCookieSize: 3000, // Number of bytes for cookie size to not exceed
128
128
  aliasMaxWindow: 90, // Max age of Alias request startTime, in days
129
- uploadInterval: 0, // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload
129
+ uploadInterval: 0, // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
130
130
  },
131
- DefaultUrls: {
131
+ DefaultBaseUrls: {
132
132
  v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/',
133
133
  v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/',
134
134
  v3SecureServiceUrl: 'jssdks.mparticle.com/v3/JS/',
@@ -168,6 +168,7 @@ const Constants = {
168
168
  ReportBatching: 'reportBatching',
169
169
  EventBatchingIntervalMillis: 'eventBatchingIntervalMillis',
170
170
  OfflineStorage: 'offlineStorage',
171
+ DirectUrlRouting: 'directURLRouting',
171
172
  },
172
173
  DefaultInstance: 'default_instance',
173
174
  CCPAPurpose: 'data_sale_opt_out',
@@ -1526,9 +1526,8 @@ function createKitBlocker(config, mpInstance) {
1526
1526
 
1527
1527
  function runPreConfigFetchInitialization(mpInstance, apiKey, config) {
1528
1528
  mpInstance.Logger = new Logger(config);
1529
- mpInstance._Store = new Store(config, mpInstance);
1529
+ mpInstance._Store = new Store(config, mpInstance, apiKey);
1530
1530
  window.mParticle.Store = mpInstance._Store;
1531
- mpInstance._Store.devToken = apiKey || null;
1532
1531
  mpInstance.Logger.verbose(
1533
1532
  Messages.InformationMessages.StartingInitialization
1534
1533
  );
package/src/store.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  SDKInitConfig,
21
21
  SDKProduct,
22
22
  } from './sdkRuntimeModels';
23
- import { isNumber, isDataPlanSlug, Dictionary } from './utils';
23
+ import { isNumber, isDataPlanSlug, Dictionary, parseNumber } from './utils';
24
24
  import { SDKConsentState } from './consent';
25
25
  import { Kit, MPForwarder } from './forwarders.interfaces';
26
26
 
@@ -43,7 +43,7 @@ export interface SDKConfig {
43
43
  appName?: string;
44
44
  appVersion?: string;
45
45
  package?: string;
46
- flags?: { [key: string]: string | number | boolean };
46
+ flags?: IFeatureFlags;
47
47
  kitConfigs: IKitConfigs[];
48
48
  kits: Dictionary<Kit>;
49
49
  logLevel?: LogLevelType;
@@ -89,8 +89,8 @@ function createSDKConfig(config: SDKInitConfig): SDKConfig {
89
89
  }
90
90
  }
91
91
 
92
- for (const prop in Constants.DefaultUrls) {
93
- sdkConfig[prop] = Constants.DefaultUrls[prop];
92
+ for (const prop in Constants.DefaultBaseUrls) {
93
+ sdkConfig[prop] = Constants.DefaultBaseUrls[prop];
94
94
  }
95
95
 
96
96
  return sdkConfig;
@@ -110,6 +110,14 @@ interface WrapperSDKInfo {
110
110
  isInfoSet: boolean;
111
111
  }
112
112
 
113
+ // https://go.mparticle.com/work/SQDSDKS-5954
114
+ export interface IFeatureFlags {
115
+ reportBatching?: string;
116
+ eventBatchingIntervalMillis?: number;
117
+ offlineStorage?: string;
118
+ directURLRouting?: boolean;
119
+ }
120
+
113
121
  // Temporary Interface until Store can be refactored as a class
114
122
  export interface IStore {
115
123
  isEnabled: boolean;
@@ -159,7 +167,8 @@ export interface IStore {
159
167
  export default function Store(
160
168
  this: IStore,
161
169
  config: SDKInitConfig,
162
- mpInstance: MParticleWebSDK
170
+ mpInstance: MParticleWebSDK,
171
+ apiKey?: string
163
172
  ) {
164
173
  const defaultStore: Partial<IStore> = {
165
174
  isEnabled: true,
@@ -209,12 +218,21 @@ export default function Store(
209
218
  for (var key in defaultStore) {
210
219
  this[key] = defaultStore[key];
211
220
  }
221
+ this.devToken = apiKey || null;
212
222
 
213
223
  this.integrationDelayTimeoutStart = Date.now();
214
224
 
215
- this.SDKConfig = createSDKConfig(config);
216
225
  // Set configuration to default settings
226
+ this.SDKConfig = createSDKConfig(config);
227
+
217
228
  if (config) {
229
+ if (!config.hasOwnProperty('flags')) {
230
+ this.SDKConfig.flags = {};
231
+ }
232
+
233
+ this.SDKConfig.flags = processFlags(config, this
234
+ .SDKConfig as SDKConfig);
235
+
218
236
  if (config.deviceId) {
219
237
  this.deviceId = config.deviceId;
220
238
  }
@@ -226,28 +244,14 @@ export default function Store(
226
244
  this.SDKConfig.isDevelopmentMode = false;
227
245
  }
228
246
 
229
- if (config.hasOwnProperty('v1SecureServiceUrl')) {
230
- this.SDKConfig.v1SecureServiceUrl = config.v1SecureServiceUrl;
231
- }
232
-
233
- if (config.hasOwnProperty('v2SecureServiceUrl')) {
234
- this.SDKConfig.v2SecureServiceUrl = config.v2SecureServiceUrl;
235
- }
247
+ const baseUrls: Dictionary<string> = processBaseUrls(
248
+ config,
249
+ this.SDKConfig.flags,
250
+ apiKey
251
+ );
236
252
 
237
- if (config.hasOwnProperty('v3SecureServiceUrl')) {
238
- this.SDKConfig.v3SecureServiceUrl = config.v3SecureServiceUrl;
239
- }
240
-
241
- if (config.hasOwnProperty('identityUrl')) {
242
- this.SDKConfig.identityUrl = config.identityUrl;
243
- }
244
-
245
- if (config.hasOwnProperty('aliasUrl')) {
246
- this.SDKConfig.aliasUrl = config.aliasUrl;
247
- }
248
-
249
- if (config.hasOwnProperty('configUrl')) {
250
- this.SDKConfig.configUrl = config.configUrl;
253
+ for (const baseUrlKeys in baseUrls) {
254
+ this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys];
251
255
  }
252
256
 
253
257
  if (config.hasOwnProperty('logLevel')) {
@@ -412,32 +416,112 @@ export default function Store(
412
416
  this.SDKConfig.onCreateBatch = undefined;
413
417
  }
414
418
  }
419
+ }
420
+ }
415
421
 
416
- if (!config.hasOwnProperty('flags')) {
417
- this.SDKConfig.flags = {};
418
- }
419
- if (
420
- !this.SDKConfig.flags.hasOwnProperty(
421
- Constants.FeatureFlags.EventBatchingIntervalMillis
422
- )
423
- ) {
424
- this.SDKConfig.flags[
425
- Constants.FeatureFlags.EventBatchingIntervalMillis
426
- ] = Constants.DefaultConfig.uploadInterval;
427
- }
428
- if (
429
- !this.SDKConfig.flags.hasOwnProperty(
430
- Constants.FeatureFlags.ReportBatching
431
- )
432
- ) {
433
- this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching] = false;
434
- }
435
- if (
436
- !this.SDKConfig.flags.hasOwnProperty(
437
- Constants.FeatureFlags.OfflineStorage
438
- )
439
- ) {
440
- this.SDKConfig.flags[Constants.FeatureFlags.OfflineStorage] = 0;
441
- }
422
+ export function processFlags(
423
+ config: SDKInitConfig,
424
+ SDKConfig: SDKConfig
425
+ ): IFeatureFlags {
426
+ const flags: IFeatureFlags = {};
427
+ const {
428
+ ReportBatching,
429
+ EventBatchingIntervalMillis,
430
+ OfflineStorage,
431
+ DirectUrlRouting,
432
+ } = Constants.FeatureFlags;
433
+
434
+ if (!config.flags) {
435
+ return {};
436
+ }
437
+
438
+ // Passed in config flags take priority over defaults
439
+ flags[ReportBatching] = config.flags[ReportBatching] || false;
440
+ // The server returns stringified numbers, sowe need to parse
441
+ flags[EventBatchingIntervalMillis] =
442
+ parseNumber(config.flags[EventBatchingIntervalMillis]) ||
443
+ Constants.DefaultConfig.uploadInterval;
444
+ flags[OfflineStorage] = config.flags[OfflineStorage] || '0';
445
+ flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === 'True';
446
+
447
+ return flags;
448
+ }
449
+
450
+ export function processBaseUrls(
451
+ config: SDKInitConfig,
452
+ flags: IFeatureFlags,
453
+ apiKey?: string
454
+ ): Dictionary<string> {
455
+ // an API key is not present in a webview only mode. In this case, no baseUrls are needed
456
+ if (!apiKey) {
457
+ return {};
458
+ }
459
+
460
+ // Set default baseUrls
461
+ let baseUrls: Dictionary<string>;
462
+
463
+ // When direct URL routing is false, update baseUrls based custom urls
464
+ // passed to the config
465
+ if (flags.directURLRouting) {
466
+ return processDirectBaseUrls(config, apiKey);
467
+ } else {
468
+ return processCustomBaseUrls(config);
442
469
  }
443
470
  }
471
+
472
+ function processCustomBaseUrls(config: SDKInitConfig): Dictionary<string> {
473
+ const defaultBaseUrls: Dictionary<string> = Constants.DefaultBaseUrls;
474
+ const newBaseUrls: Dictionary<string> = {};
475
+
476
+ // If there is no custo base url, we use the default base url
477
+ for (let baseUrlKey in defaultBaseUrls) {
478
+ newBaseUrls[baseUrlKey] =
479
+ config[baseUrlKey] || defaultBaseUrls[baseUrlKey];
480
+ }
481
+
482
+ return newBaseUrls;
483
+ }
484
+
485
+ function processDirectBaseUrls(
486
+ config: SDKInitConfig,
487
+ apiKey: string
488
+ ): Dictionary {
489
+ const defaultBaseUrls = Constants.DefaultBaseUrls;
490
+ const directBaseUrls: Dictionary<string> = {};
491
+ // When Direct URL Routing is true, we create a new set of baseUrls that
492
+ // include the silo in the urls. mParticle API keys are prefixed with the
493
+ // silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo,
494
+ // and before other silos existed, there were no prefixes and all apiKeys
495
+ // were us1. As such, if we split on a '-' and the resulting array length
496
+ // is 1, then it is an older APIkey that should route to us1.
497
+ // When splitKey.length is greater than 1, then splitKey[0] will be
498
+ // us1, us2, eu1, au1, or st1, etc as new silos are added
499
+ const DEFAULT_SILO = 'us1';
500
+ const splitKey: Array<string> = apiKey.split('-');
501
+ const routingPrefix: string =
502
+ splitKey.length <= 1 ? DEFAULT_SILO : splitKey[0];
503
+
504
+ for (let baseUrlKey in defaultBaseUrls) {
505
+ // Any custom endpoints passed to mpConfig will take priority over direct
506
+ // mapping to the silo. The most common use case is a customer provided CNAME.
507
+ if (baseUrlKey === 'configUrl') {
508
+ directBaseUrls[baseUrlKey] =
509
+ config[baseUrlKey] || defaultBaseUrls[baseUrlKey];
510
+ continue;
511
+ }
512
+
513
+ if (config.hasOwnProperty(baseUrlKey)) {
514
+ directBaseUrls[baseUrlKey] = config[baseUrlKey];
515
+ } else {
516
+ const urlparts = defaultBaseUrls[baseUrlKey].split('.');
517
+
518
+ directBaseUrls[baseUrlKey] = [
519
+ urlparts[0],
520
+ routingPrefix,
521
+ ...urlparts.slice(1),
522
+ ].join('.');
523
+ }
524
+ }
525
+
526
+ return directBaseUrls;
527
+ }