@mparticle/web-sdk 2.53.1 → 2.54.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.53.1";
18
+ var version = "2.54.1";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls
@@ -148,7 +148,7 @@ var CommerceEventType={ProductAddToCart:10,ProductRemoveFromCart:11,ProductCheck
148
148
  getValuesAsStrings:function getValuesAsStrings(){return Object.values(IdentityType).map(function(a){return isNumber(a)?a.toString():void 0}).filter(function(a){return a!==void 0})},getNewIdentitiesByName:function getNewIdentitiesByName(a){var b={},c=IdentityType.getValuesAsStrings();for(var d in a)// IdentityTypes are stored as numbers but are passed in as strings
149
149
  if(c.includes(d)){var e=IdentityType.getIdentityName(parseNumber(d));b[e]=a[d];}return b}};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10,getName:function getName(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"},// these are the action names used by server and mobile SDKs when expanding a CommerceEvent
150
150
  getExpansionName:function getExpansionName(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,getName:function getName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},// these are the names that the server and mobile SDKs use while expanding CommerceEvent
151
- getExpansionName:function getExpansionName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"}};var ProfileMessageType={Logout:3};var ApplicationTransitionType$1={AppInit:1};var PerformanceMarkType={SdkStart:"mp:sdkStart"};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,Environment:Constants.Environment};
151
+ getExpansionName:function getExpansionName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"}};var ProfileMessageType={Logout:3};var ApplicationTransitionType$1={AppInit:1};var PerformanceMarkType={SdkStart:"mp:sdkStart",JointSdkSelectPlacements:"mp:jointSdkSelectPlacements"};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,Environment:Constants.Environment};
152
152
 
153
153
  function _typeof$1(o) {
154
154
  "@babel/helpers - typeof";
@@ -1296,7 +1296,7 @@ return a._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===d.audie
1296
1296
  * @deprecated
1297
1297
  */getCartProducts:function getCartProducts(){return a.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")),[]}}},this.parseIdentityResponse=function(b,d,f,g,h,i,j){var k,l,m,n=a.Identity.getUser(d),o=n?n.getMPID():null,p=n?n.getUserIdentities().userIdentities:{},q={};a._Store.identityCallInFlight=!1;try{var r,s,t;if(a.Logger.verbose("Parsing \""+h+"\" identity response from server"),l=null!==(r=b.responseText)&&void 0!==r?r:null,a._Store.isLoggedIn=(null===(s=l)||void 0===s?void 0:s.is_logged_in)||!1,hasMPIDChanged(n,l)&&(a._Store.mpid=l.mpid,n&&a._Persistence.setLastSeenTime(d),k=!a._Persistence.getFirstSeenTime(l.mpid),a._Persistence.setFirstSeenTime(l.mpid)),b.status===HTTP_OK){c(CacheIdentity)&&cacheOrClearIdCache(h,i,e.idCache,b,j);var u=e.IdentityAPI.getUser(l.mpid),v=u?u.getUserIdentities().userIdentities:{};h===Modify$1?(q=a._Identity.IdentityRequest.combineUserIdentities(p,g.userIdentities),a._Store.setUserIdentities(d,q)):(h===Identify&&n&&l.mpid===o&&a._Persistence.setFirstSeenTime(l.mpid),a._Store.addMpidToSessionHistory(l.mpid,d),a._CookieSyncManager.attemptCookieSync(l.mpid,k),a._Persistence.swapCurrentUser(d,l.mpid,a._Store.currentSessionMPIDs),g&&!isEmpty(g.userIdentities)&&(q=e.IdentityRequest.combineUserIdentities(v,g.userIdentities)),a._Store.setUserIdentities(l.mpid,q),a._Persistence.update(),a._Store.syncPersistenceData(),a._Persistence.findPrevCookiesBasedOnUI(g),a._Store.context=l.context||a._Store.context),m=a.Identity.getCurrentUser(),tryOnUserAlias(n,m,g,a.Logger);var w=a._Persistence.getPersistence();m&&(a._Persistence.storeDataInMemory(w,m.getMPID()),e.reinitForwardersOnUserChange(n,m),e.setForwarderCallbacks(m,h));var x=IdentityType.getNewIdentitiesByName(q),y=h===Modify$1?p:v;// https://go.mparticle.com/work/SQDSDKS-6501
1298
1298
  e.sendUserIdentityChangeEvent(x,h,l.mpid,y);}if(f){var z=0===b.status?HTTPCodes$2.noHttpCoverage:b.status;a._Helpers.invokeCallback(f,z,l||null,m);}else l&&!isEmpty(l.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1299
- a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.isReady()&&(a._RoktManager.currentUser=a.Identity.getCurrentUser()),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1299
+ a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.onIdentityComplete(),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1300
1300
  {// https://go.mparticle.com/work/SQDSDKS-6354
1301
1301
  var g=this.IdentityAPI.getUser(d);for(var h in b)// Verifies a change actually happened
1302
1302
  if(f[h]!==b[h]){var i,j=!f[h],k=e.createUserIdentityChange(h,b[h],f[h],j,g);// If a new identity type was introduced when the identity changes
@@ -1458,17 +1458,21 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1458
1458
  * @param {SDKIdentityApi} identityService - The mParticle Identity instance
1459
1459
  * @param {SDKLoggerApi} logger - The mParticle Logger instance
1460
1460
  * @param {IRoktOptions} options - Options for the RoktManager
1461
+ * @param {Function} captureTiming - Function to capture performance timing marks
1461
1462
  *
1462
1463
  * @throws Logs error to console if placementAttributesMapping parsing fails
1463
- */return a.prototype.init=function(a,b,c,d,e,f){var g,h=a||{},i=h.userAttributeFilters,j=h.settings,k=j||{},l=k.placementAttributesMapping,m=k.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(g=null===m||void 0===m?void 0:m.toLowerCase())&&void 0!==g?g:null,this.identityService=c,this.store=d,this.logger=e,this.filters={userAttributeFilters:i,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(l);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
1464
+ */return a.prototype.init=function(a,b,c,d,e,f,g){var h,i=a||{},j=i.userAttributeFilters,k=i.settings,l=k||{},m=l.placementAttributesMapping,n=l.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(h=null===n||void 0===n?void 0:n.toLowerCase())&&void 0!==h?h:null,this.identityService=c,this.store=d,this.logger=e,this.captureTiming=g,this.filters={userAttributeFilters:j,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(m);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
1464
1465
  // It is set here and passed in to the createLauncher method in the Rokt Kit
1465
1466
  // This is not to be confused for the `sandbox` flag in the selectPlacements attributes
1466
1467
  // as that is independent of this setting, though they share the same name.
1467
- var n=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1468
+ var o=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1468
1469
  // to the Rokt Launcher.
1469
- this.launcherOptions=__assign({sandbox:n},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain);},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c;return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s=this;return __generator(this,function(t){switch(t.label){case 0:if(!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];t.label=1;case 1:if(t.trys.push([1,6,,7]),d=a.attributes,e=(null===d||void 0===d?void 0:d.sandbox)||null,f=this.mapPlacementAttributes(d,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),g=(null===(c=null===(b=this.currentUser)||void 0===b?void 0:b.getUserIdentities())||void 0===c?void 0:c.userIdentities)||{},h=g.email,i=f.email,j=void 0,k=void 0,this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType)&&(j=g[this.mappedEmailShaIdentityType],k=f.emailsha256||f[this.mappedEmailShaIdentityType]||void 0),l=this.hasIdentityChanged(h,i),m=this.hasIdentityChanged(j,k),n={},l&&(n.email=i,i&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),m&&(n[this.mappedEmailShaIdentityType]=k,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(n))return [3/*break*/,5];t.label=2;case 2:return t.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){s.identityService.identify({userIdentities:__assign(__assign({},g),n)},function(){a();});})];case 3:return t.sent(),[3/*break*/,5];case 4:return o=t.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(o)),[3/*break*/,5];case 5:return this.setUserAttributes(f),p=__assign(__assign({},f),null===e?{}:{sandbox:e}),q=__assign(__assign({},a),{attributes:p}),[2/*return*/,this.kit.selectPlacements(q)];case 6:return r=t.sent(),[2/*return*/,Promise.reject(r instanceof Error?r:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1470
- return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.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,b=this;this.isReady()&&0!==this.messageQueue.size&&(// Clear the queue after processing all messages
1471
- null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));try{var f=b[a.methodName](a.payload);b.completePendingPromise(a.messageId,f);}catch(c){var g=c instanceof Error?c.message:c+"";null===(e=b.logger)||void 0===e?void 0:e.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(g)),b.completePendingPromise(a.messageId,Promise.reject(c));}}),this.messageQueue.clear());},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.completePendingPromise=function(a,b){if(a&&this.messageQueue.has(a)){var c=this.messageQueue.get(a);c.resolve&&Promise.resolve(b).then(function(a){return c.resolve(a)})["catch"](function(a){return c.reject(a)}),this.messageQueue["delete"](a);}},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1470
+ this.launcherOptions=__assign({sandbox:o},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain);},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c,d,e,f;return __awaiter(this,void 0,void 0,function(){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=this;return __generator(this,function(z){switch(z.label){case 0:// Queue if kit isn't ready OR if identity is in flight
1471
+ if(this.captureTiming&&this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(b=this.store)||void 0===b?void 0:b.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];z.label=1;case 1:if(z.trys.push([1,6,,7]),g=a.attributes,h=(null===g||void 0===g?void 0:g.sandbox)||null,i=this.mapPlacementAttributes(g,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),j=(null===(d=null===(c=this.currentUser)||void 0===c?void 0:c.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},k=j.email,l=i.email,m=void 0,n=void 0,o=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),o&&(m=j[this.mappedEmailShaIdentityType],n=i.emailsha256||i[this.mappedEmailShaIdentityType]||void 0),p=this.hasIdentityChanged(k,l),q=this.hasIdentityChanged(m,n),r={},p&&(r.email=l,l&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),q&&(r[this.mappedEmailShaIdentityType]=n,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(r))return [3/*break*/,5];z.label=2;case 2:return z.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){y.identityService.identify({userIdentities:__assign(__assign({},j),r)},function(){a();});})];case 3:return z.sent(),[3/*break*/,5];case 4:return s=z.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(s)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),t=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},this.setUserAttributes(i),u=__assign(__assign({},i),null===h?{}:{sandbox:h}),t.email&&!u.email&&(u.email=t.email),o&&(v=t[this.mappedEmailShaIdentityType],v&&!u.emailsha256&&!u[this.mappedEmailShaIdentityType]&&(u.emailsha256=v)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,w=__assign(__assign({},a),{attributes:u}),[2/*return*/,this.kit.selectPlacements(w)];case 6:return x=z.sent(),[2/*return*/,Promise.reject(x instanceof Error?x:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1472
+ return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.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.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
1473
+ this.messageQueue.clear(),c.forEach(function(a){var c,d;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));// Capture resolve/reject functions before async processing
1474
+ var e=a.resolve,f=a.reject,g=function(c){var d,e=c instanceof Error?c.message:c+"";null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(e)),f&&f(c);};try{var h=b[a.methodName](a.payload);// Handle both sync and async methods
1475
+ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1472
1476
  },a}();
1473
1477
 
1474
1478
  /**
@@ -1660,7 +1664,7 @@ if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.pr
1660
1664
  var f=c.Identity.getCurrentUser(),g=f?f.getMPID():null,h=f?f.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:h}:c._Store.SDKConfig.identifyRequest,e(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639
1661
1665
  var i=e(CaptureIntegrationSpecificIds),j=e(CaptureIntegrationSpecificIdsV2),k=j&&j!==CaptureIntegrationSpecificIdsV2Modes.None||!0===i;if(k){var l;i||j===CaptureIntegrationSpecificIdsV2Modes.All?l="all":j===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(l="roktonly"),c._IntegrationCapture=new IntegrationCapture(l),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
1662
1666
  var m=parseConfig(b,"Rokt",181);if(m){var n=m.userAttributeFilters,o=filteredMparticleUser(g,{userAttributeFilters:n},c),p={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339
1663
- c._RoktManager.init(m,o,c.Identity,c._Store,c.Logger,p);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,f,g,h);}// We will continue to clear out the ready queue as part of the initial init flow
1667
+ c._RoktManager.init(m,o,c.Identity,c._Store,c.Logger,p,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,f,g,h);}// We will continue to clear out the ready queue as part of the initial init flow
1664
1668
  // if an identify request is unnecessary, such as if there is an existing session
1665
1669
  (c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
1666
1670
  function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
@@ -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.53.1";
18
+ var version = "2.54.1";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls
@@ -148,7 +148,7 @@ var CommerceEventType={ProductAddToCart:10,ProductRemoveFromCart:11,ProductCheck
148
148
  getValuesAsStrings:function getValuesAsStrings(){return Object.values(IdentityType).map(function(a){return isNumber(a)?a.toString():void 0}).filter(function(a){return a!==void 0})},getNewIdentitiesByName:function getNewIdentitiesByName(a){var b={},c=IdentityType.getValuesAsStrings();for(var d in a)// IdentityTypes are stored as numbers but are passed in as strings
149
149
  if(c.includes(d)){var e=IdentityType.getIdentityName(parseNumber(d));b[e]=a[d];}return b}};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10,getName:function getName(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"},// these are the action names used by server and mobile SDKs when expanding a CommerceEvent
150
150
  getExpansionName:function getExpansionName(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,getName:function getName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},// these are the names that the server and mobile SDKs use while expanding CommerceEvent
151
- getExpansionName:function getExpansionName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"}};var ProfileMessageType={Logout:3};var ApplicationTransitionType$1={AppInit:1};var PerformanceMarkType={SdkStart:"mp:sdkStart"};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,Environment:Constants.Environment};
151
+ getExpansionName:function getExpansionName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"}};var ProfileMessageType={Logout:3};var ApplicationTransitionType$1={AppInit:1};var PerformanceMarkType={SdkStart:"mp:sdkStart",JointSdkSelectPlacements:"mp:jointSdkSelectPlacements"};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,Environment:Constants.Environment};
152
152
 
153
153
  function _typeof$1(o) {
154
154
  "@babel/helpers - typeof";
@@ -1296,7 +1296,7 @@ return a._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===d.audie
1296
1296
  * @deprecated
1297
1297
  */getCartProducts:function getCartProducts(){return a.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")),[]}}},this.parseIdentityResponse=function(b,d,f,g,h,i,j){var k,l,m,n=a.Identity.getUser(d),o=n?n.getMPID():null,p=n?n.getUserIdentities().userIdentities:{},q={};a._Store.identityCallInFlight=!1;try{var r,s,t;if(a.Logger.verbose("Parsing \""+h+"\" identity response from server"),l=null!==(r=b.responseText)&&void 0!==r?r:null,a._Store.isLoggedIn=(null===(s=l)||void 0===s?void 0:s.is_logged_in)||!1,hasMPIDChanged(n,l)&&(a._Store.mpid=l.mpid,n&&a._Persistence.setLastSeenTime(d),k=!a._Persistence.getFirstSeenTime(l.mpid),a._Persistence.setFirstSeenTime(l.mpid)),b.status===HTTP_OK){c(CacheIdentity)&&cacheOrClearIdCache(h,i,e.idCache,b,j);var u=e.IdentityAPI.getUser(l.mpid),v=u?u.getUserIdentities().userIdentities:{};h===Modify$1?(q=a._Identity.IdentityRequest.combineUserIdentities(p,g.userIdentities),a._Store.setUserIdentities(d,q)):(h===Identify&&n&&l.mpid===o&&a._Persistence.setFirstSeenTime(l.mpid),a._Store.addMpidToSessionHistory(l.mpid,d),a._CookieSyncManager.attemptCookieSync(l.mpid,k),a._Persistence.swapCurrentUser(d,l.mpid,a._Store.currentSessionMPIDs),g&&!isEmpty(g.userIdentities)&&(q=e.IdentityRequest.combineUserIdentities(v,g.userIdentities)),a._Store.setUserIdentities(l.mpid,q),a._Persistence.update(),a._Store.syncPersistenceData(),a._Persistence.findPrevCookiesBasedOnUI(g),a._Store.context=l.context||a._Store.context),m=a.Identity.getCurrentUser(),tryOnUserAlias(n,m,g,a.Logger);var w=a._Persistence.getPersistence();m&&(a._Persistence.storeDataInMemory(w,m.getMPID()),e.reinitForwardersOnUserChange(n,m),e.setForwarderCallbacks(m,h));var x=IdentityType.getNewIdentitiesByName(q),y=h===Modify$1?p:v;// https://go.mparticle.com/work/SQDSDKS-6501
1298
1298
  e.sendUserIdentityChangeEvent(x,h,l.mpid,y);}if(f){var z=0===b.status?HTTPCodes$2.noHttpCoverage:b.status;a._Helpers.invokeCallback(f,z,l||null,m);}else l&&!isEmpty(l.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1299
- a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.isReady()&&(a._RoktManager.currentUser=a.Identity.getCurrentUser()),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1299
+ a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.onIdentityComplete(),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1300
1300
  {// https://go.mparticle.com/work/SQDSDKS-6354
1301
1301
  var g=this.IdentityAPI.getUser(d);for(var h in b)// Verifies a change actually happened
1302
1302
  if(f[h]!==b[h]){var i,j=!f[h],k=e.createUserIdentityChange(h,b[h],f[h],j,g);// If a new identity type was introduced when the identity changes
@@ -1458,17 +1458,21 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1458
1458
  * @param {SDKIdentityApi} identityService - The mParticle Identity instance
1459
1459
  * @param {SDKLoggerApi} logger - The mParticle Logger instance
1460
1460
  * @param {IRoktOptions} options - Options for the RoktManager
1461
+ * @param {Function} captureTiming - Function to capture performance timing marks
1461
1462
  *
1462
1463
  * @throws Logs error to console if placementAttributesMapping parsing fails
1463
- */return a.prototype.init=function(a,b,c,d,e,f){var g,h=a||{},i=h.userAttributeFilters,j=h.settings,k=j||{},l=k.placementAttributesMapping,m=k.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(g=null===m||void 0===m?void 0:m.toLowerCase())&&void 0!==g?g:null,this.identityService=c,this.store=d,this.logger=e,this.filters={userAttributeFilters:i,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(l);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
1464
+ */return a.prototype.init=function(a,b,c,d,e,f,g){var h,i=a||{},j=i.userAttributeFilters,k=i.settings,l=k||{},m=l.placementAttributesMapping,n=l.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(h=null===n||void 0===n?void 0:n.toLowerCase())&&void 0!==h?h:null,this.identityService=c,this.store=d,this.logger=e,this.captureTiming=g,this.filters={userAttributeFilters:j,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(m);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
1464
1465
  // It is set here and passed in to the createLauncher method in the Rokt Kit
1465
1466
  // This is not to be confused for the `sandbox` flag in the selectPlacements attributes
1466
1467
  // as that is independent of this setting, though they share the same name.
1467
- var n=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1468
+ var o=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1468
1469
  // to the Rokt Launcher.
1469
- this.launcherOptions=__assign({sandbox:n},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain);},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c;return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s=this;return __generator(this,function(t){switch(t.label){case 0:if(!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];t.label=1;case 1:if(t.trys.push([1,6,,7]),d=a.attributes,e=(null===d||void 0===d?void 0:d.sandbox)||null,f=this.mapPlacementAttributes(d,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),g=(null===(c=null===(b=this.currentUser)||void 0===b?void 0:b.getUserIdentities())||void 0===c?void 0:c.userIdentities)||{},h=g.email,i=f.email,j=void 0,k=void 0,this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType)&&(j=g[this.mappedEmailShaIdentityType],k=f.emailsha256||f[this.mappedEmailShaIdentityType]||void 0),l=this.hasIdentityChanged(h,i),m=this.hasIdentityChanged(j,k),n={},l&&(n.email=i,i&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),m&&(n[this.mappedEmailShaIdentityType]=k,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(n))return [3/*break*/,5];t.label=2;case 2:return t.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){s.identityService.identify({userIdentities:__assign(__assign({},g),n)},function(){a();});})];case 3:return t.sent(),[3/*break*/,5];case 4:return o=t.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(o)),[3/*break*/,5];case 5:return this.setUserAttributes(f),p=__assign(__assign({},f),null===e?{}:{sandbox:e}),q=__assign(__assign({},a),{attributes:p}),[2/*return*/,this.kit.selectPlacements(q)];case 6:return r=t.sent(),[2/*return*/,Promise.reject(r instanceof Error?r:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1470
- return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.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,b=this;this.isReady()&&0!==this.messageQueue.size&&(// Clear the queue after processing all messages
1471
- null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));try{var f=b[a.methodName](a.payload);b.completePendingPromise(a.messageId,f);}catch(c){var g=c instanceof Error?c.message:c+"";null===(e=b.logger)||void 0===e?void 0:e.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(g)),b.completePendingPromise(a.messageId,Promise.reject(c));}}),this.messageQueue.clear());},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.completePendingPromise=function(a,b){if(a&&this.messageQueue.has(a)){var c=this.messageQueue.get(a);c.resolve&&Promise.resolve(b).then(function(a){return c.resolve(a)})["catch"](function(a){return c.reject(a)}),this.messageQueue["delete"](a);}},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1470
+ this.launcherOptions=__assign({sandbox:o},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain);},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c,d,e,f;return __awaiter(this,void 0,void 0,function(){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=this;return __generator(this,function(z){switch(z.label){case 0:// Queue if kit isn't ready OR if identity is in flight
1471
+ if(this.captureTiming&&this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(b=this.store)||void 0===b?void 0:b.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];z.label=1;case 1:if(z.trys.push([1,6,,7]),g=a.attributes,h=(null===g||void 0===g?void 0:g.sandbox)||null,i=this.mapPlacementAttributes(g,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),j=(null===(d=null===(c=this.currentUser)||void 0===c?void 0:c.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},k=j.email,l=i.email,m=void 0,n=void 0,o=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),o&&(m=j[this.mappedEmailShaIdentityType],n=i.emailsha256||i[this.mappedEmailShaIdentityType]||void 0),p=this.hasIdentityChanged(k,l),q=this.hasIdentityChanged(m,n),r={},p&&(r.email=l,l&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),q&&(r[this.mappedEmailShaIdentityType]=n,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(r))return [3/*break*/,5];z.label=2;case 2:return z.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){y.identityService.identify({userIdentities:__assign(__assign({},j),r)},function(){a();});})];case 3:return z.sent(),[3/*break*/,5];case 4:return s=z.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(s)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),t=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},this.setUserAttributes(i),u=__assign(__assign({},i),null===h?{}:{sandbox:h}),t.email&&!u.email&&(u.email=t.email),o&&(v=t[this.mappedEmailShaIdentityType],v&&!u.emailsha256&&!u[this.mappedEmailShaIdentityType]&&(u.emailsha256=v)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,w=__assign(__assign({},a),{attributes:u}),[2/*return*/,this.kit.selectPlacements(w)];case 6:return x=z.sent(),[2/*return*/,Promise.reject(x instanceof Error?x:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1472
+ return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.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.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
1473
+ this.messageQueue.clear(),c.forEach(function(a){var c,d;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));// Capture resolve/reject functions before async processing
1474
+ var e=a.resolve,f=a.reject,g=function(c){var d,e=c instanceof Error?c.message:c+"";null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(e)),f&&f(c);};try{var h=b[a.methodName](a.payload);// Handle both sync and async methods
1475
+ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1472
1476
  },a}();
1473
1477
 
1474
1478
  /**
@@ -1660,7 +1664,7 @@ if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.pr
1660
1664
  var f=c.Identity.getCurrentUser(),g=f?f.getMPID():null,h=f?f.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:h}:c._Store.SDKConfig.identifyRequest,e(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639
1661
1665
  var i=e(CaptureIntegrationSpecificIds),j=e(CaptureIntegrationSpecificIdsV2),k=j&&j!==CaptureIntegrationSpecificIdsV2Modes.None||!0===i;if(k){var l;i||j===CaptureIntegrationSpecificIdsV2Modes.All?l="all":j===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(l="roktonly"),c._IntegrationCapture=new IntegrationCapture(l),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
1662
1666
  var m=parseConfig(b,"Rokt",181);if(m){var n=m.userAttributeFilters,o=filteredMparticleUser(g,{userAttributeFilters:n},c),p={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339
1663
- c._RoktManager.init(m,o,c.Identity,c._Store,c.Logger,p);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,f,g,h);}// We will continue to clear out the ready queue as part of the initial init flow
1667
+ c._RoktManager.init(m,o,c.Identity,c._Store,c.Logger,p,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,f,g,h);}// We will continue to clear out the ready queue as part of the initial init flow
1664
1668
  // if an identify request is unnecessary, such as if there is an existing session
1665
1669
  (c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
1666
1670
  function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
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.53.1";
206
+ var version = "2.54.1";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -1213,7 +1213,8 @@ var mParticle = (function () {
1213
1213
  AppInit: 1
1214
1214
  };
1215
1215
  var PerformanceMarkType = {
1216
- SdkStart: 'mp:sdkStart'
1216
+ SdkStart: 'mp:sdkStart',
1217
+ JointSdkSelectPlacements: 'mp:jointSdkSelectPlacements'
1217
1218
  };
1218
1219
  var Types = {
1219
1220
  MessageType: MessageType$1,
@@ -8223,9 +8224,7 @@ var mParticle = (function () {
8223
8224
  mpInstance.Logger.error('Error parsing JSON response from Identity server: ' + e);
8224
8225
  }
8225
8226
  mpInstance._Store.isInitialized = true;
8226
- if (mpInstance._RoktManager.isReady()) {
8227
- mpInstance._RoktManager.currentUser = mpInstance.Identity.getCurrentUser();
8228
- }
8227
+ mpInstance._RoktManager.onIdentityComplete();
8229
8228
  mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue);
8230
8229
  };
8231
8230
 
@@ -9703,10 +9702,11 @@ var mParticle = (function () {
9703
9702
  * @param {SDKIdentityApi} identityService - The mParticle Identity instance
9704
9703
  * @param {SDKLoggerApi} logger - The mParticle Logger instance
9705
9704
  * @param {IRoktOptions} options - Options for the RoktManager
9705
+ * @param {Function} captureTiming - Function to capture performance timing marks
9706
9706
  *
9707
9707
  * @throws Logs error to console if placementAttributesMapping parsing fails
9708
9708
  */
9709
- RoktManager.prototype.init = function (roktConfig, filteredUser, identityService, store, logger, options) {
9709
+ RoktManager.prototype.init = function (roktConfig, filteredUser, identityService, store, logger, options, captureTiming) {
9710
9710
  var _a;
9711
9711
  var _b = roktConfig || {},
9712
9712
  userAttributeFilters = _b.userAttributeFilters,
@@ -9718,6 +9718,7 @@ var mParticle = (function () {
9718
9718
  this.identityService = identityService;
9719
9719
  this.store = store;
9720
9720
  this.logger = logger;
9721
+ this.captureTiming = captureTiming;
9721
9722
  this.filters = {
9722
9723
  userAttributeFilters: userAttributeFilters,
9723
9724
  filterUserAttributes: KitFilterHelper.filterUserAttributes,
@@ -9762,31 +9763,34 @@ var mParticle = (function () {
9762
9763
  * });
9763
9764
  */
9764
9765
  RoktManager.prototype.selectPlacements = function (options) {
9765
- var _a, _b;
9766
+ var _a, _b, _c, _d, _e;
9766
9767
  return __awaiter(this, void 0, void 0, function () {
9767
- var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail, currentHashedEmail, newHashedEmail, emailChanged, hashedEmailChanged, newIdentities_1, error_1, enrichedAttributes, enrichedOptions, error_2;
9768
+ var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail, currentHashedEmail, newHashedEmail, isValidHashedEmailIdentityType, emailChanged, hashedEmailChanged, newIdentities_1, error_1, finalUserIdentities, enrichedAttributes, hashedEmail, enrichedOptions, error_2;
9768
9769
  var _this = this;
9769
- return __generator(this, function (_c) {
9770
- switch (_c.label) {
9770
+ return __generator(this, function (_f) {
9771
+ switch (_f.label) {
9771
9772
  case 0:
9772
- if (!this.isReady()) {
9773
+ if (this.captureTiming) {
9774
+ this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements);
9775
+ }
9776
+ // Queue if kit isn't ready OR if identity is in flight
9777
+ if (!this.isReady() || ((_a = this.store) === null || _a === void 0 ? void 0 : _a.identityCallInFlight)) {
9773
9778
  return [2 /*return*/, this.deferredCall('selectPlacements', options)];
9774
9779
  }
9775
- _c.label = 1;
9780
+ _f.label = 1;
9776
9781
  case 1:
9777
- _c.trys.push([1, 6,, 7]);
9782
+ _f.trys.push([1, 6,, 7]);
9778
9783
  attributes = options.attributes;
9779
9784
  sandboxValue = (attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) || null;
9780
9785
  mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9781
- // Get current user identities
9782
9786
  this.currentUser = this.identityService.getCurrentUser();
9783
- currentUserIdentities_1 = ((_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.getUserIdentities()) === null || _b === void 0 ? void 0 : _b.userIdentities) || {};
9787
+ currentUserIdentities_1 = ((_c = (_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.getUserIdentities()) === null || _c === void 0 ? void 0 : _c.userIdentities) || {};
9784
9788
  currentEmail = currentUserIdentities_1.email;
9785
9789
  newEmail = mappedAttributes.email;
9786
9790
  currentHashedEmail = void 0;
9787
9791
  newHashedEmail = void 0;
9788
- // Hashed email identity is valid if it is set to Other-Other10
9789
- if (this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false) {
9792
+ isValidHashedEmailIdentityType = this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false;
9793
+ if (isValidHashedEmailIdentityType) {
9790
9794
  currentHashedEmail = currentUserIdentities_1[this.mappedEmailShaIdentityType];
9791
9795
  newHashedEmail = mappedAttributes['emailsha256'] || mappedAttributes[this.mappedEmailShaIdentityType] || undefined;
9792
9796
  }
@@ -9804,9 +9808,9 @@ var mParticle = (function () {
9804
9808
  this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.");
9805
9809
  }
9806
9810
  if (!!isEmpty(newIdentities_1)) return [3 /*break*/, 5];
9807
- _c.label = 2;
9811
+ _f.label = 2;
9808
9812
  case 2:
9809
- _c.trys.push([2, 4,, 5]);
9813
+ _f.trys.push([2, 4,, 5]);
9810
9814
  return [4 /*yield*/, new Promise(function (resolve, reject) {
9811
9815
  _this.identityService.identify({
9812
9816
  userIdentities: __assign(__assign({}, currentUserIdentities_1), newIdentities_1)
@@ -9815,23 +9819,38 @@ var mParticle = (function () {
9815
9819
  });
9816
9820
  })];
9817
9821
  case 3:
9818
- _c.sent();
9822
+ _f.sent();
9819
9823
  return [3 /*break*/, 5];
9820
9824
  case 4:
9821
- error_1 = _c.sent();
9825
+ error_1 = _f.sent();
9822
9826
  this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error_1));
9823
9827
  return [3 /*break*/, 5];
9824
9828
  case 5:
9829
+ // Refresh current user identities to ensure we have the latest values before building enrichedAttributes
9830
+ this.currentUser = this.identityService.getCurrentUser();
9831
+ finalUserIdentities = ((_e = (_d = this.currentUser) === null || _d === void 0 ? void 0 : _d.getUserIdentities()) === null || _e === void 0 ? void 0 : _e.userIdentities) || {};
9825
9832
  this.setUserAttributes(mappedAttributes);
9826
9833
  enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9827
9834
  sandbox: sandboxValue
9828
9835
  } : {});
9836
+ // Propagate email from current user identities if not already in attributes
9837
+ if (finalUserIdentities.email && !enrichedAttributes.email) {
9838
+ enrichedAttributes.email = finalUserIdentities.email;
9839
+ }
9840
+ // Propagate emailsha256 from current user identities if not already in attributes
9841
+ if (isValidHashedEmailIdentityType) {
9842
+ hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType];
9843
+ if (hashedEmail && !enrichedAttributes.emailsha256 && !enrichedAttributes[this.mappedEmailShaIdentityType]) {
9844
+ enrichedAttributes.emailsha256 = hashedEmail;
9845
+ }
9846
+ }
9847
+ this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null;
9829
9848
  enrichedOptions = __assign(__assign({}, options), {
9830
9849
  attributes: enrichedAttributes
9831
9850
  });
9832
9851
  return [2 /*return*/, this.kit.selectPlacements(enrichedOptions)];
9833
9852
  case 6:
9834
- error_2 = _c.sent();
9853
+ error_2 = _f.sent();
9835
9854
  return [2 /*return*/, Promise.reject(error_2 instanceof Error ? error_2 : new Error('Unknown error occurred'))];
9836
9855
  case 7:
9837
9856
  return [2 /*return*/];
@@ -10004,6 +10023,13 @@ var mParticle = (function () {
10004
10023
  }
10005
10024
  return mappedAttributes;
10006
10025
  };
10026
+ RoktManager.prototype.onIdentityComplete = function () {
10027
+ if (this.isReady()) {
10028
+ this.currentUser = this.identityService.getCurrentUser();
10029
+ // Process any queued selectPlacements calls that were waiting for identity
10030
+ this.processMessageQueue();
10031
+ }
10032
+ };
10007
10033
  RoktManager.prototype.processMessageQueue = function () {
10008
10034
  var _this = this;
10009
10035
  var _a;
@@ -10011,24 +10037,39 @@ var mParticle = (function () {
10011
10037
  return;
10012
10038
  }
10013
10039
  (_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages"));
10014
- this.messageQueue.forEach(function (message) {
10015
- var _a, _b, _c;
10040
+ var messagesToProcess = Array.from(this.messageQueue.values());
10041
+ // Clear the queue immediately to prevent re-processing
10042
+ this.messageQueue.clear();
10043
+ messagesToProcess.forEach(function (message) {
10044
+ var _a, _b;
10016
10045
  if (!(message.methodName in _this) || !isFunction(_this[message.methodName])) {
10017
10046
  (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Method ".concat(message.methodName, " not found"));
10018
10047
  return;
10019
10048
  }
10020
10049
  (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.verbose("RoktManager: Processing queued message: ".concat(message.methodName, " with payload: ").concat(JSON.stringify(message.payload)));
10050
+ // Capture resolve/reject functions before async processing
10051
+ var resolve = message.resolve;
10052
+ var reject = message.reject;
10053
+ var handleError = function handleError(error) {
10054
+ var _a;
10055
+ var errorMessage = error instanceof Error ? error.message : String(error);
10056
+ (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage));
10057
+ if (reject) {
10058
+ reject(error);
10059
+ }
10060
+ };
10021
10061
  try {
10022
10062
  var result = _this[message.methodName](message.payload);
10023
- _this.completePendingPromise(message.messageId, result);
10063
+ // Handle both sync and async methods
10064
+ Promise.resolve(result).then(function (resolvedResult) {
10065
+ if (resolve) {
10066
+ resolve(resolvedResult);
10067
+ }
10068
+ })["catch"](handleError);
10024
10069
  } catch (error) {
10025
- var errorMessage = error instanceof Error ? error.message : String(error);
10026
- (_c = _this.logger) === null || _c === void 0 ? void 0 : _c.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage));
10027
- _this.completePendingPromise(message.messageId, Promise.reject(error));
10070
+ handleError(error);
10028
10071
  }
10029
10072
  });
10030
- // Clear the queue after processing all messages
10031
- this.messageQueue.clear();
10032
10073
  };
10033
10074
  RoktManager.prototype.queueMessage = function (message) {
10034
10075
  this.messageQueue.set(message.messageId, message);
@@ -10046,20 +10087,6 @@ var mParticle = (function () {
10046
10087
  });
10047
10088
  });
10048
10089
  };
10049
- RoktManager.prototype.completePendingPromise = function (messageId, resultOrError) {
10050
- if (!messageId || !this.messageQueue.has(messageId)) {
10051
- return;
10052
- }
10053
- var message = this.messageQueue.get(messageId);
10054
- if (message.resolve) {
10055
- Promise.resolve(resultOrError).then(function (result) {
10056
- return message.resolve(result);
10057
- })["catch"](function (error) {
10058
- return message.reject(error);
10059
- });
10060
- }
10061
- this.messageQueue["delete"](messageId);
10062
- };
10063
10090
  /**
10064
10091
  * Hashes a string input using SHA-256 and returns the hex digest
10065
10092
  * Uses the Web Crypto API for secure hashing
@@ -11149,7 +11176,7 @@ var mParticle = (function () {
11149
11176
  domain: config === null || config === void 0 ? void 0 : config.domain
11150
11177
  };
11151
11178
  // https://go.mparticle.com/work/SQDSDKS-7339
11152
- mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance._Store, mpInstance.Logger, roktOptions);
11179
+ mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance._Store, mpInstance.Logger, roktOptions, mpInstance.captureTiming);
11153
11180
  }
11154
11181
  mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats);
11155
11182
  mpInstance._Forwarders.processPixelConfigs(config);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.53.1",
3
+ "version": "2.54.1",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/identity.js CHANGED
@@ -1372,7 +1372,6 @@ export default function Identity(mpInstance) {
1372
1372
  : {};
1373
1373
  let mpidIsNotInCookies;
1374
1374
  let identityApiResult;
1375
-
1376
1375
  let newUser;
1377
1376
  let newIdentitiesByType = {};
1378
1377
 
@@ -1577,9 +1576,7 @@ export default function Identity(mpInstance) {
1577
1576
  }
1578
1577
  mpInstance._Store.isInitialized = true;
1579
1578
 
1580
- if (mpInstance._RoktManager.isReady()) {
1581
- mpInstance._RoktManager.currentUser = mpInstance.Identity.getCurrentUser();
1582
- }
1579
+ mpInstance._RoktManager.onIdentityComplete();
1583
1580
 
1584
1581
  mpInstance._preInit.readyQueue = processReadyQueue(
1585
1582
  mpInstance._preInit.readyQueue
@@ -1438,7 +1438,8 @@ function completeSDKInitialization(apiKey, config, mpInstance) {
1438
1438
  mpInstance.Identity,
1439
1439
  mpInstance._Store,
1440
1440
  mpInstance.Logger,
1441
- roktOptions
1441
+ roktOptions,
1442
+ mpInstance.captureTiming
1442
1443
  );
1443
1444
  }
1444
1445
 
@@ -14,7 +14,7 @@ import { SDKIdentityApi } from "./identity.interfaces";
14
14
  import { SDKLoggerApi } from "./sdkRuntimeModels";
15
15
  import { IStore, LocalSessionAttributes } from "./store";
16
16
  import { UserIdentities } from "@mparticle/web-sdk";
17
- import { IdentityType } from "./types";
17
+ import { IdentityType, PerformanceMarkType } from "./types";
18
18
 
19
19
  // https://docs.rokt.com/developers/integration-guides/web/library/attributes
20
20
  export type RoktAttributeValueArray = Array<string | number | boolean>;
@@ -101,6 +101,7 @@ export default class RoktManager {
101
101
  private logger: SDKLoggerApi;
102
102
  private domain?: string;
103
103
  private mappedEmailShaIdentityType?: string | null;
104
+ private captureTiming?: (metricsName: string) => void;
104
105
  /**
105
106
  * Initializes the RoktManager with configuration settings and user data.
106
107
  *
@@ -109,6 +110,7 @@ export default class RoktManager {
109
110
  * @param {SDKIdentityApi} identityService - The mParticle Identity instance
110
111
  * @param {SDKLoggerApi} logger - The mParticle Logger instance
111
112
  * @param {IRoktOptions} options - Options for the RoktManager
113
+ * @param {Function} captureTiming - Function to capture performance timing marks
112
114
  *
113
115
  * @throws Logs error to console if placementAttributesMapping parsing fails
114
116
  */
@@ -118,7 +120,8 @@ export default class RoktManager {
118
120
  identityService: SDKIdentityApi,
119
121
  store: IStore,
120
122
  logger?: SDKLoggerApi,
121
- options?: IRoktOptions
123
+ options?: IRoktOptions,
124
+ captureTiming?: (metricsName: string) => void
122
125
  ): void {
123
126
  const { userAttributeFilters, settings } = roktConfig || {};
124
127
  const { placementAttributesMapping, hashedEmailUserIdentityType } = settings || {};
@@ -127,6 +130,7 @@ export default class RoktManager {
127
130
  this.identityService = identityService;
128
131
  this.store = store;
129
132
  this.logger = logger;
133
+ this.captureTiming = captureTiming;
130
134
 
131
135
  this.filters = {
132
136
  userAttributeFilters,
@@ -176,7 +180,12 @@ export default class RoktManager {
176
180
  * });
177
181
  */
178
182
  public async selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
179
- if (!this.isReady()) {
183
+ if (this.captureTiming) {
184
+ this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements);
185
+ }
186
+
187
+ // Queue if kit isn't ready OR if identity is in flight
188
+ if (!this.isReady() || this.store?.identityCallInFlight) {
180
189
  return this.deferredCall<IRoktSelection>('selectPlacements', options);
181
190
  }
182
191
 
@@ -184,8 +193,7 @@ export default class RoktManager {
184
193
  const { attributes } = options;
185
194
  const sandboxValue = attributes?.sandbox || null;
186
195
  const mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
187
-
188
- // Get current user identities
196
+
189
197
  this.currentUser = this.identityService.getCurrentUser();
190
198
  const currentUserIdentities = this.currentUser?.getUserIdentities()?.userIdentities || {};
191
199
 
@@ -196,9 +204,16 @@ export default class RoktManager {
196
204
  let newHashedEmail: string | undefined;
197
205
 
198
206
  // Hashed email identity is valid if it is set to Other-Other10
199
- if(this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false) {
207
+ const isValidHashedEmailIdentityType =
208
+ this.mappedEmailShaIdentityType &&
209
+ IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false;
210
+
211
+ if (isValidHashedEmailIdentityType) {
200
212
  currentHashedEmail = currentUserIdentities[this.mappedEmailShaIdentityType];
201
- newHashedEmail = mappedAttributes['emailsha256'] as string || mappedAttributes[this.mappedEmailShaIdentityType] as string || undefined;
213
+ newHashedEmail =
214
+ (mappedAttributes['emailsha256'] as string) ||
215
+ (mappedAttributes[this.mappedEmailShaIdentityType] as string) ||
216
+ undefined;
202
217
  }
203
218
 
204
219
  const emailChanged = this.hasIdentityChanged(currentEmail, newEmail);
@@ -234,14 +249,37 @@ export default class RoktManager {
234
249
  this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error));
235
250
  }
236
251
  }
252
+
253
+ // Refresh current user identities to ensure we have the latest values before building enrichedAttributes
254
+ this.currentUser = this.identityService.getCurrentUser();
255
+ const finalUserIdentities = this.currentUser?.getUserIdentities()?.userIdentities || {};
237
256
 
238
257
  this.setUserAttributes(mappedAttributes);
239
258
 
240
- const enrichedAttributes = {
259
+ const enrichedAttributes: RoktAttributes = {
241
260
  ...mappedAttributes,
242
261
  ...(sandboxValue !== null ? { sandbox: sandboxValue } : {}),
243
262
  };
244
263
 
264
+ // Propagate email from current user identities if not already in attributes
265
+ if (finalUserIdentities.email && !enrichedAttributes.email) {
266
+ enrichedAttributes.email = finalUserIdentities.email;
267
+ }
268
+
269
+ // Propagate emailsha256 from current user identities if not already in attributes
270
+ if (isValidHashedEmailIdentityType) {
271
+ const hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType];
272
+ if (
273
+ hashedEmail &&
274
+ !enrichedAttributes.emailsha256 &&
275
+ !enrichedAttributes[this.mappedEmailShaIdentityType]
276
+ ) {
277
+ enrichedAttributes.emailsha256 = hashedEmail;
278
+ }
279
+ }
280
+
281
+ this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null;
282
+
245
283
  const enrichedOptions = {
246
284
  ...options,
247
285
  attributes: enrichedAttributes,
@@ -397,6 +435,14 @@ export default class RoktManager {
397
435
  return mappedAttributes;
398
436
  }
399
437
 
438
+ public onIdentityComplete(): void {
439
+ if (this.isReady()) {
440
+ this.currentUser = this.identityService.getCurrentUser();
441
+ // Process any queued selectPlacements calls that were waiting for identity
442
+ this.processMessageQueue();
443
+ }
444
+ }
445
+
400
446
  private processMessageQueue(): void {
401
447
  if (!this.isReady() || this.messageQueue.size === 0) {
402
448
  return;
@@ -404,7 +450,12 @@ export default class RoktManager {
404
450
 
405
451
  this.logger?.verbose(`RoktManager: Processing ${this.messageQueue.size} queued messages`);
406
452
 
407
- this.messageQueue.forEach((message) => {
453
+ const messagesToProcess = Array.from(this.messageQueue.values());
454
+
455
+ // Clear the queue immediately to prevent re-processing
456
+ this.messageQueue.clear();
457
+
458
+ messagesToProcess.forEach((message) => {
408
459
  if(!(message.methodName in this) || !isFunction(this[message.methodName])) {
409
460
  this.logger?.error(`RoktManager: Method ${message.methodName} not found`);
410
461
 
@@ -413,18 +464,32 @@ export default class RoktManager {
413
464
 
414
465
  this.logger?.verbose(`RoktManager: Processing queued message: ${message.methodName} with payload: ${JSON.stringify(message.payload)}`);
415
466
 
467
+ // Capture resolve/reject functions before async processing
468
+ const resolve = message.resolve;
469
+ const reject = message.reject;
470
+
471
+ const handleError = (error: unknown) => {
472
+ const errorMessage = error instanceof Error ? error.message : String(error);
473
+ this.logger?.error(`RoktManager: Error processing message '${message.methodName}': ${errorMessage}`);
474
+ if (reject) {
475
+ reject(error);
476
+ }
477
+ };
478
+
416
479
  try {
417
480
  const result = (this[message.methodName] as Function)(message.payload);
418
- this.completePendingPromise(message.messageId, result);
481
+ // Handle both sync and async methods
482
+ Promise.resolve(result)
483
+ .then((resolvedResult) => {
484
+ if (resolve) {
485
+ resolve(resolvedResult);
486
+ }
487
+ })
488
+ .catch(handleError);
419
489
  } catch (error) {
420
- const errorMessage = error instanceof Error ? error.message : String(error);
421
- this.logger?.error(`RoktManager: Error processing message '${message.methodName}': ${errorMessage}`);
422
- this.completePendingPromise(message.messageId, Promise.reject(error));
490
+ handleError(error);
423
491
  }
424
492
  });
425
-
426
- // Clear the queue after processing all messages
427
- this.messageQueue.clear();
428
493
  }
429
494
 
430
495
  private queueMessage(message: IRoktMessage): void {
@@ -445,22 +510,6 @@ export default class RoktManager {
445
510
  });
446
511
  }
447
512
 
448
- private completePendingPromise(messageId: string | undefined, resultOrError: any): void {
449
- if (!messageId || !this.messageQueue.has(messageId)) {
450
- return;
451
- }
452
-
453
- const message = this.messageQueue.get(messageId)!;
454
-
455
- if (message.resolve) {
456
- Promise.resolve(resultOrError)
457
- .then((result) => message.resolve!(result))
458
- .catch((error) => message.reject!(error));
459
- }
460
-
461
- this.messageQueue.delete(messageId);
462
- }
463
-
464
513
  /**
465
514
  * Hashes a string input using SHA-256 and returns the hex digest
466
515
  * Uses the Web Crypto API for secure hashing
@@ -514,4 +563,4 @@ export default class RoktManager {
514
563
 
515
564
  return false; // Values are the same
516
565
  }
517
- }
566
+ }
package/src/types.ts CHANGED
@@ -393,6 +393,7 @@ export const ApplicationTransitionType = {
393
393
 
394
394
  export const PerformanceMarkType = {
395
395
  SdkStart: 'mp:sdkStart' as const,
396
+ JointSdkSelectPlacements: 'mp:jointSdkSelectPlacements' as const,
396
397
  }
397
398
 
398
399
  export default {