@mparticle/web-sdk 2.38.0 → 2.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- var version = "2.38.0";
18
+ var version = "2.38.1";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
@@ -128,7 +128,7 @@ var Messages$9=Constants.Messages,createCookieString=function(a){return replaceC
128
128
  generateUniqueId// random hex digits
129
129
  )},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/&quot;/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&amp;/g,"&")},createCookieSyncUrl=function(a,b,c){var d=replaceAmpWithAmpersand(b),e=c?replaceAmpWithAmpersand(c):null,f=replaceMPID(d,a),g=e?replaceMPID(e,a):"";return f+encodeURIComponent(g)},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers
130
130
  return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var e=new URL(a);c=new URLSearchParams(e.search);}else c=queryStringParserFallback(a);return isEmpty(b)?c.forEach(function(a,b){d[b]=a;}):b.forEach(function(a){var b=c.get(a);b&&(d[a]=b);}),d},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie
131
- var b=function parseCookies(){return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}();// Helper function to filter cookies by keys
131
+ var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys
132
132
  // Parse cookies from document.cookie
133
133
  // Filter cookies by keys if provided
134
134
  return function filterCookies(a,b){for(var c={},d=0,e=a;d<e.length;d++){var f=e[d],g=f.split("="),h=g[0],i=g[1];(!b||b.includes(h))&&(c[h]=i);}return c}(b,a)},getHref=function(){return "undefined"!=typeof window&&window.location?window.location.href:""},filterDictionaryWithHash=function(a,b,c){var d={};if(!isEmpty(a))for(var e in a)if(a.hasOwnProperty(e)){var f=c(e);inArray(b,f)||(d[e]=a[e]);}return d},parseConfig=function(a,b,c){var d;return (null===(d=a.kitConfigs)||void 0===d?void 0:d.find(function(a){return a.name===b&&a.moduleId===c}))||null};/**
@@ -596,7 +596,7 @@ try{if(a._Store.isLocalStorageAvailable){var g=localStorage.getItem(a._Store.pro
596
596
  // Stores all non-current user MPID information into the store
597
597
  for(var i in c)c.hasOwnProperty(i)&&(SDKv2NonMPIDCookieKeys[i]||(a._Store.nonCurrentUserMPIDs[i]=c[i]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeProductsInMemory=function(b,c){if(b)try{a._Store.cartProducts=b[c]&&b[c].cp?b[c].cp:[];}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.getUserProductsFromLS=function(b){if(!a._Store.isLocalStorageAvailable)return [];var c,d,e,f=localStorage.getItem(a._Store.prodStorageName);// if there is an MPID, we are retrieving the user's products, which is an array
598
598
  if(f&&(c=Base64.decode(f)),b)try{return c&&(e=JSON.parse(c)),d=c&&e[b]&&e[b].cp&&Array.isArray(e[b].cp)?e[b].cp:[],d}catch(a){return []}else return []},this.getAllUserProductsFromLS=function(){var b,c,d=localStorage.getItem(a._Store.prodStorageName);d&&(b=Base64.decode(d));// returns an object with keys of MPID and values of array of products
599
- try{c=JSON.parse(b);}catch(a){c={};}return c},this.setLocalStorage=function(){if(a._Store.isLocalStorageAvailable){var c=a._Store.storageName,d=f.getAllUserProductsFromLS(),e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null,i={cp:d[h]?d[h].cp:[]};if(h){d=d||{},d[h]=i;try{window.localStorage.setItem(encodeURIComponent(a._Store.prodStorageName),Base64.encode(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting products on localStorage.");}}if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(c),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,g,h,j=window.document.cookie.split("; "),k=a._Store.storageName,m=k?void 0:{};for(a.Logger.verbose(Messages$4.InformationMessages.CookieSearch),b=0,c=j.length;b<c;b++){try{d=j[b].split("="),g=d.shift(),h=d.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+g+". Skipping.");}if(k&&k===g){m=a._Helpers.converted(h);break}k||(m[g]=a._Helpers.converted(h));}return m?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(f.decodePersistence(m))):null},this.setCookie=function(){var c,d=a.Identity.getCurrentUser();d&&(c=d.getMPID());var e,g,h,i=new Date,j=a._Store.storageName,k=f.getCookie()||{},l=new Date(i.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString();e=f.getCookieDomain(),g=""===e?"":";domain="+e,k.gs=k.gs||{},a._Store.sessionId&&(k.gs.csm=a._Store.currentSessionMPIDs),c&&(k.cu=c),k.l=a._Store.isLoggedIn?1:0,k=b(k),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(k=a._Helpers.extend({},k,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),h=f.reduceAndEncodePersistence(k,l,g,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(j)+"="+h;},this.reduceAndEncodePersistence=function(b,c,e,f){var g,h=b.gs.csm?b.gs.csm:[];// Comment 1 above
599
+ try{c=JSON.parse(b);}catch(a){c={};}return c},this.setLocalStorage=function(){if(a._Store.isLocalStorageAvailable){var c=a._Store.storageName,d=f.getAllUserProductsFromLS(),e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null,i={cp:d[h]?d[h].cp:[]};if(h){d=d||{},d[h]=i;try{window.localStorage.setItem(encodeURIComponent(a._Store.prodStorageName),Base64.encode(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting products on localStorage.");}}if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(c),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;c<d;c++){try{e=b[c].split("="),g=e.shift(),h=e.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+g+". Skipping.");}if(j&&j===g){k=a._Helpers.converted(h);break}j||(k[g]=a._Helpers.converted(h));}return k?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(f.decodePersistence(k))):null},this.setCookie=function(){var c,d=a.Identity.getCurrentUser();d&&(c=d.getMPID());var e,g,h,i=new Date,j=a._Store.storageName,k=f.getCookie()||{},l=new Date(i.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString();e=f.getCookieDomain(),g=""===e?"":";domain="+e,k.gs=k.gs||{},a._Store.sessionId&&(k.gs.csm=a._Store.currentSessionMPIDs),c&&(k.cu=c),k.l=a._Store.isLoggedIn?1:0,k=b(k),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(k=a._Helpers.extend({},k,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),h=f.reduceAndEncodePersistence(k,l,g,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(j)+"="+h;},this.reduceAndEncodePersistence=function(b,c,e,f){var g,h=b.gs.csm?b.gs.csm:[];// Comment 1 above
600
600
  if(!h.length)for(var j in b)b.hasOwnProperty(j)&&(g=d(b,c,e),g.length>f&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie
601
601
  var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above
602
602
  if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above
@@ -1417,7 +1417,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1417
1417
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1418
1418
  //
1419
1419
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1420
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.userAttributeMapping=[];}/**
1420
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1421
1421
  * Initializes the RoktManager with configuration settings and user data.
1422
1422
  *
1423
1423
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1425,9 +1425,9 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1425
1425
  * @param {IMParticleUser} currentUser - Current mParticle user object
1426
1426
  * @param {IRoktManagerOptions} options - Options for the RoktManager
1427
1427
  *
1428
- * @throws Logs error to console if userAttributeMapping parsing fails
1429
- */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).userAttributeMapping;try{this.userAttributeMapping=parseSettingsString(h);}catch(a){console.error("Error parsing user attribute mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapUserAttributes(c,this.userAttributeMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
- return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.error("Error setting user attributes",a);}},a.prototype.mapUserAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1428
+ * @throws Logs error to console if placementAttributesMapping parsing fails
1429
+ */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(h);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapPlacementAttributes(c,this.placementAttributesMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
+ return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.error("Error setting user attributes",a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1431
1431
 
1432
1432
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
1433
1433
  * <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- var version = "2.38.0";
18
+ var version = "2.38.1";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
@@ -128,7 +128,7 @@ var Messages$9=Constants.Messages,createCookieString=function(a){return replaceC
128
128
  generateUniqueId// random hex digits
129
129
  )},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/&quot;/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&amp;/g,"&")},createCookieSyncUrl=function(a,b,c){var d=replaceAmpWithAmpersand(b),e=c?replaceAmpWithAmpersand(c):null,f=replaceMPID(d,a),g=e?replaceMPID(e,a):"";return f+encodeURIComponent(g)},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers
130
130
  return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var e=new URL(a);c=new URLSearchParams(e.search);}else c=queryStringParserFallback(a);return isEmpty(b)?c.forEach(function(a,b){d[b]=a;}):b.forEach(function(a){var b=c.get(a);b&&(d[a]=b);}),d},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie
131
- var b=function parseCookies(){return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}();// Helper function to filter cookies by keys
131
+ var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys
132
132
  // Parse cookies from document.cookie
133
133
  // Filter cookies by keys if provided
134
134
  return function filterCookies(a,b){for(var c={},d=0,e=a;d<e.length;d++){var f=e[d],g=f.split("="),h=g[0],i=g[1];(!b||b.includes(h))&&(c[h]=i);}return c}(b,a)},getHref=function(){return "undefined"!=typeof window&&window.location?window.location.href:""},filterDictionaryWithHash=function(a,b,c){var d={};if(!isEmpty(a))for(var e in a)if(a.hasOwnProperty(e)){var f=c(e);inArray(b,f)||(d[e]=a[e]);}return d},parseConfig=function(a,b,c){var d;return (null===(d=a.kitConfigs)||void 0===d?void 0:d.find(function(a){return a.name===b&&a.moduleId===c}))||null};/**
@@ -596,7 +596,7 @@ try{if(a._Store.isLocalStorageAvailable){var g=localStorage.getItem(a._Store.pro
596
596
  // Stores all non-current user MPID information into the store
597
597
  for(var i in c)c.hasOwnProperty(i)&&(SDKv2NonMPIDCookieKeys[i]||(a._Store.nonCurrentUserMPIDs[i]=c[i]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeProductsInMemory=function(b,c){if(b)try{a._Store.cartProducts=b[c]&&b[c].cp?b[c].cp:[];}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.getUserProductsFromLS=function(b){if(!a._Store.isLocalStorageAvailable)return [];var c,d,e,f=localStorage.getItem(a._Store.prodStorageName);// if there is an MPID, we are retrieving the user's products, which is an array
598
598
  if(f&&(c=Base64.decode(f)),b)try{return c&&(e=JSON.parse(c)),d=c&&e[b]&&e[b].cp&&Array.isArray(e[b].cp)?e[b].cp:[],d}catch(a){return []}else return []},this.getAllUserProductsFromLS=function(){var b,c,d=localStorage.getItem(a._Store.prodStorageName);d&&(b=Base64.decode(d));// returns an object with keys of MPID and values of array of products
599
- try{c=JSON.parse(b);}catch(a){c={};}return c},this.setLocalStorage=function(){if(a._Store.isLocalStorageAvailable){var c=a._Store.storageName,d=f.getAllUserProductsFromLS(),e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null,i={cp:d[h]?d[h].cp:[]};if(h){d=d||{},d[h]=i;try{window.localStorage.setItem(encodeURIComponent(a._Store.prodStorageName),Base64.encode(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting products on localStorage.");}}if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(c),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,g,h,j=window.document.cookie.split("; "),k=a._Store.storageName,m=k?void 0:{};for(a.Logger.verbose(Messages$4.InformationMessages.CookieSearch),b=0,c=j.length;b<c;b++){try{d=j[b].split("="),g=d.shift(),h=d.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+g+". Skipping.");}if(k&&k===g){m=a._Helpers.converted(h);break}k||(m[g]=a._Helpers.converted(h));}return m?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(f.decodePersistence(m))):null},this.setCookie=function(){var c,d=a.Identity.getCurrentUser();d&&(c=d.getMPID());var e,g,h,i=new Date,j=a._Store.storageName,k=f.getCookie()||{},l=new Date(i.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString();e=f.getCookieDomain(),g=""===e?"":";domain="+e,k.gs=k.gs||{},a._Store.sessionId&&(k.gs.csm=a._Store.currentSessionMPIDs),c&&(k.cu=c),k.l=a._Store.isLoggedIn?1:0,k=b(k),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(k=a._Helpers.extend({},k,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),h=f.reduceAndEncodePersistence(k,l,g,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(j)+"="+h;},this.reduceAndEncodePersistence=function(b,c,e,f){var g,h=b.gs.csm?b.gs.csm:[];// Comment 1 above
599
+ try{c=JSON.parse(b);}catch(a){c={};}return c},this.setLocalStorage=function(){if(a._Store.isLocalStorageAvailable){var c=a._Store.storageName,d=f.getAllUserProductsFromLS(),e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null,i={cp:d[h]?d[h].cp:[]};if(h){d=d||{},d[h]=i;try{window.localStorage.setItem(encodeURIComponent(a._Store.prodStorageName),Base64.encode(JSON.stringify(d)));}catch(b){a.Logger.error("Error with setting products on localStorage.");}}if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(c),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;c<d;c++){try{e=b[c].split("="),g=e.shift(),h=e.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+g+". Skipping.");}if(j&&j===g){k=a._Helpers.converted(h);break}j||(k[g]=a._Helpers.converted(h));}return k?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(f.decodePersistence(k))):null},this.setCookie=function(){var c,d=a.Identity.getCurrentUser();d&&(c=d.getMPID());var e,g,h,i=new Date,j=a._Store.storageName,k=f.getCookie()||{},l=new Date(i.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString();e=f.getCookieDomain(),g=""===e?"":";domain="+e,k.gs=k.gs||{},a._Store.sessionId&&(k.gs.csm=a._Store.currentSessionMPIDs),c&&(k.cu=c),k.l=a._Store.isLoggedIn?1:0,k=b(k),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(k=a._Helpers.extend({},k,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),h=f.reduceAndEncodePersistence(k,l,g,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(j)+"="+h;},this.reduceAndEncodePersistence=function(b,c,e,f){var g,h=b.gs.csm?b.gs.csm:[];// Comment 1 above
600
600
  if(!h.length)for(var j in b)b.hasOwnProperty(j)&&(g=d(b,c,e),g.length>f&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie
601
601
  var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above
602
602
  if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above
@@ -1417,7 +1417,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1417
1417
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1418
1418
  //
1419
1419
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1420
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.userAttributeMapping=[];}/**
1420
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1421
1421
  * Initializes the RoktManager with configuration settings and user data.
1422
1422
  *
1423
1423
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1425,9 +1425,9 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1425
1425
  * @param {IMParticleUser} currentUser - Current mParticle user object
1426
1426
  * @param {IRoktManagerOptions} options - Options for the RoktManager
1427
1427
  *
1428
- * @throws Logs error to console if userAttributeMapping parsing fails
1429
- */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).userAttributeMapping;try{this.userAttributeMapping=parseSettingsString(h);}catch(a){console.error("Error parsing user attribute mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapUserAttributes(c,this.userAttributeMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
- return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.error("Error setting user attributes",a);}},a.prototype.mapUserAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1428
+ * @throws Logs error to console if placementAttributesMapping parsing fails
1429
+ */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(h);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapPlacementAttributes(c,this.placementAttributesMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
+ return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.error("Error setting user attributes",a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1431
1431
 
1432
1432
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
1433
1433
  * <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
package/dist/mparticle.js CHANGED
@@ -203,7 +203,7 @@ var mParticle = (function () {
203
203
  Base64: Base64$1
204
204
  };
205
205
 
206
- var version = "2.38.0";
206
+ var version = "2.38.1";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -751,12 +751,17 @@ var mParticle = (function () {
751
751
  var getCookies = function getCookies(keys) {
752
752
  // Helper function to parse cookies from document.cookie
753
753
  var parseCookies = function parseCookies() {
754
- if (typeof window === 'undefined') {
754
+ try {
755
+ if (typeof window === 'undefined') {
756
+ return [];
757
+ }
758
+ return window.document.cookie.split(';').map(function (cookie) {
759
+ return cookie.trim();
760
+ });
761
+ } catch (e) {
762
+ console.error('Unable to parse cookies', e);
755
763
  return [];
756
764
  }
757
- return window.document.cookie.split(';').map(function (cookie) {
758
- return cookie.trim();
759
- });
760
765
  };
761
766
  // Helper function to filter cookies by keys
762
767
  var filterCookies = function filterCookies(cookies, keys) {
@@ -4949,7 +4954,7 @@ var mParticle = (function () {
4949
4954
  document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain;
4950
4955
  };
4951
4956
  this.getCookie = function () {
4952
- var cookies = window.document.cookie.split('; '),
4957
+ var cookies,
4953
4958
  key = mpInstance._Store.storageName,
4954
4959
  i,
4955
4960
  l,
@@ -4958,6 +4963,12 @@ var mParticle = (function () {
4958
4963
  cookie,
4959
4964
  result = key ? undefined : {};
4960
4965
  mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSearch);
4966
+ try {
4967
+ cookies = window.document.cookie.split('; ');
4968
+ } catch (e) {
4969
+ mpInstance.Logger.verbose('Unable to parse undefined cookie');
4970
+ return null;
4971
+ }
4961
4972
  for (i = 0, l = cookies.length; i < l; i++) {
4962
4973
  try {
4963
4974
  parts = cookies[i].split('=');
@@ -9654,7 +9665,7 @@ var mParticle = (function () {
9654
9665
  this.filteredUser = null;
9655
9666
  this.messageQueue = [];
9656
9667
  this.sandbox = null;
9657
- this.userAttributeMapping = [];
9668
+ this.placementAttributesMapping = [];
9658
9669
  }
9659
9670
  /**
9660
9671
  * Initializes the RoktManager with configuration settings and user data.
@@ -9664,17 +9675,17 @@ var mParticle = (function () {
9664
9675
  * @param {IMParticleUser} currentUser - Current mParticle user object
9665
9676
  * @param {IRoktManagerOptions} options - Options for the RoktManager
9666
9677
  *
9667
- * @throws Logs error to console if userAttributeMapping parsing fails
9678
+ * @throws Logs error to console if placementAttributesMapping parsing fails
9668
9679
  */
9669
9680
  RoktManager.prototype.init = function (roktConfig, filteredUser, currentUser, options) {
9670
9681
  var _a = roktConfig || {},
9671
9682
  userAttributeFilters = _a.userAttributeFilters,
9672
9683
  settings = _a.settings;
9673
- var userAttributeMapping = (settings || {}).userAttributeMapping;
9684
+ var placementAttributesMapping = (settings || {}).placementAttributesMapping;
9674
9685
  try {
9675
- this.userAttributeMapping = parseSettingsString(userAttributeMapping);
9686
+ this.placementAttributesMapping = parseSettingsString(placementAttributesMapping);
9676
9687
  } catch (error) {
9677
- console.error('Error parsing user attribute mapping from config', error);
9688
+ console.error('Error parsing placement attributes mapping from config', error);
9678
9689
  }
9679
9690
  this.currentUser = currentUser;
9680
9691
  this.filters = {
@@ -9700,7 +9711,7 @@ var mParticle = (function () {
9700
9711
  try {
9701
9712
  var attributes = options.attributes;
9702
9713
  var sandboxValue = (_a = attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) !== null && _a !== void 0 ? _a : this.sandbox;
9703
- var mappedAttributes = this.mapUserAttributes(attributes, this.userAttributeMapping);
9714
+ var mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9704
9715
  this.setUserAttributes(mappedAttributes);
9705
9716
  var enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9706
9717
  sandbox: sandboxValue
@@ -9745,10 +9756,10 @@ var mParticle = (function () {
9745
9756
  console.error('Error setting user attributes', error);
9746
9757
  }
9747
9758
  };
9748
- RoktManager.prototype.mapUserAttributes = function (attributes, userAttributeMapping) {
9759
+ RoktManager.prototype.mapPlacementAttributes = function (attributes, placementAttributesMapping) {
9749
9760
  var mappingLookup = {};
9750
- for (var _i = 0, userAttributeMapping_1 = userAttributeMapping; _i < userAttributeMapping_1.length; _i++) {
9751
- var mapping = userAttributeMapping_1[_i];
9761
+ for (var _i = 0, placementAttributesMapping_1 = placementAttributesMapping; _i < placementAttributesMapping_1.length; _i++) {
9762
+ var mapping = placementAttributesMapping_1[_i];
9752
9763
  mappingLookup[mapping.map] = mapping.value;
9753
9764
  }
9754
9765
  var mappedAttributes = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.38.0",
3
+ "version": "2.38.1",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -467,7 +467,7 @@ export default function _Persistence(mpInstance) {
467
467
  };
468
468
 
469
469
  this.getCookie = function() {
470
- var cookies = window.document.cookie.split('; '),
470
+ var cookies,
471
471
  key = mpInstance._Store.storageName,
472
472
  i,
473
473
  l,
@@ -478,6 +478,13 @@ export default function _Persistence(mpInstance) {
478
478
 
479
479
  mpInstance.Logger.verbose(Messages.InformationMessages.CookieSearch);
480
480
 
481
+ try {
482
+ cookies = window.document.cookie.split('; ');
483
+ } catch (e) {
484
+ mpInstance.Logger.verbose('Unable to parse undefined cookie');
485
+ return null;
486
+ }
487
+
481
488
  for (i = 0, l = cookies.length; i < l; i++) {
482
489
  try {
483
490
  parts = cookies[i].split('=');
@@ -68,7 +68,7 @@ export default class RoktManager {
68
68
  private filteredUser: IMParticleUser | null = null;
69
69
  private messageQueue: IRoktMessage[] = [];
70
70
  private sandbox: boolean | null = null;
71
- private userAttributeMapping: Dictionary<string>[] = [];
71
+ private placementAttributesMapping: Dictionary<string>[] = [];
72
72
 
73
73
  /**
74
74
  * Initializes the RoktManager with configuration settings and user data.
@@ -78,16 +78,16 @@ export default class RoktManager {
78
78
  * @param {IMParticleUser} currentUser - Current mParticle user object
79
79
  * @param {IRoktManagerOptions} options - Options for the RoktManager
80
80
  *
81
- * @throws Logs error to console if userAttributeMapping parsing fails
81
+ * @throws Logs error to console if placementAttributesMapping parsing fails
82
82
  */
83
83
  public init(roktConfig: IKitConfigs, filteredUser: IMParticleUser, currentUser: IMParticleUser, options?: IRoktManagerOptions): void {
84
84
  const { userAttributeFilters, settings } = roktConfig || {};
85
- const { userAttributeMapping } = settings || {};
85
+ const { placementAttributesMapping } = settings || {};
86
86
 
87
87
  try {
88
- this.userAttributeMapping = parseSettingsString(userAttributeMapping);
88
+ this.placementAttributesMapping = parseSettingsString(placementAttributesMapping);
89
89
  } catch (error) {
90
- console.error('Error parsing user attribute mapping from config', error);
90
+ console.error('Error parsing placement attributes mapping from config', error);
91
91
  }
92
92
 
93
93
  this.currentUser = currentUser;
@@ -118,7 +118,7 @@ export default class RoktManager {
118
118
  try {
119
119
  const { attributes } = options;
120
120
  const sandboxValue = attributes?.sandbox ?? this.sandbox;
121
- const mappedAttributes = this.mapUserAttributes(attributes, this.userAttributeMapping);
121
+ const mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
122
122
 
123
123
  this.setUserAttributes(mappedAttributes);
124
124
 
@@ -176,9 +176,9 @@ export default class RoktManager {
176
176
  }
177
177
  }
178
178
 
179
- private mapUserAttributes(attributes: IRoktPartnerAttributes, userAttributeMapping: Dictionary<string>[]): IRoktPartnerAttributes {
179
+ private mapPlacementAttributes(attributes: IRoktPartnerAttributes, placementAttributesMapping: Dictionary<string>[]): IRoktPartnerAttributes {
180
180
  const mappingLookup: { [key: string]: string } = {};
181
- for (const mapping of userAttributeMapping) {
181
+ for (const mapping of placementAttributesMapping) {
182
182
  mappingLookup[mapping.map] = mapping.value;
183
183
  }
184
184
 
package/src/utils.ts CHANGED
@@ -340,10 +340,15 @@ const queryStringParserFallback = (url: string): URLSearchParamsFallback => {
340
340
  const getCookies = (keys?: string[]): Dictionary<string> => {
341
341
  // Helper function to parse cookies from document.cookie
342
342
  const parseCookies = (): string[] => {
343
- if (typeof window === 'undefined') {
343
+ try {
344
+ if (typeof window === 'undefined') {
345
+ return [];
346
+ }
347
+ return window.document.cookie.split(';').map(cookie => cookie.trim());
348
+ } catch (e) {
349
+ console.error('Unable to parse cookies', e);
344
350
  return [];
345
351
  }
346
- return window.document.cookie.split(';').map(cookie => cookie.trim());
347
352
  };
348
353
 
349
354
  // Helper function to filter cookies by keys