@mparticle/web-sdk 2.39.1 → 2.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.39.1";
18
+ var version = "2.40.0";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
@@ -1417,16 +1417,17 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1417
1417
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1418
1418
  //
1419
1419
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1420
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1420
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1421
1421
  * Initializes the RoktManager with configuration settings and user data.
1422
1422
  *
1423
1423
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
1424
1424
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
1425
- * @param {IMParticleUser} currentUser - Current mParticle user object
1425
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
1426
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
1426
1427
  * @param {IRoktManagerOptions} options - Options for the RoktManager
1427
1428
  *
1428
1429
  * @throws Logs error to console if placementAttributesMapping parsing fails
1429
- */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(h);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapPlacementAttributes(c,this.placementAttributesMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
+ */return a.prototype.init=function(a,b,c,d,e){var f=a||{},g=f.userAttributeFilters,h=f.settings,i=(h||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(i);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.identityService=c,this.logger=d,this.filters={userAttributeFilters:g,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===e||void 0===e?void 0:e.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c,d;return __awaiter(this,void 0,void 0,function(){var e,f,g,h,i,j,k,l,m,n,o=this;return __generator(this,function(p){switch(p.label){case 0:if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),[2/*return*/,Promise.resolve({})];p.label=1;case 1:if(p.trys.push([1,6,,7]),e=a.attributes,f=null!==(b=null===e||void 0===e?void 0:e.sandbox)&&void 0!==b?b:this.sandbox,g=this.mapPlacementAttributes(e,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),h=(null===(d=null===(c=this.currentUser)||void 0===c?void 0:c.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},i=h.email,j=g.email,!j||i&&i===j)return [3/*break*/,5];i&&i!==j&&this.logger.warning("Email mismatch detected. Current email, ".concat(i," differs from email passed to selectPlacements call, ").concat(j,". Proceeding to call identify with ").concat(j,". Please verify your implementation.")),p.label=2;case 2:return p.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){o.identityService.identify({userIdentities:__assign(__assign({},h),{email:j})},function(){a();});})];case 3:return p.sent(),[3/*break*/,5];case 4:return k=p.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(k)),[3/*break*/,5];case 5:return this.setUserAttributes(g),l=__assign(__assign({},g),null===f?{}:{sandbox:f}),m=__assign(__assign({},a),{attributes:l}),[2/*return*/,this.kit.selectPlacements(m)];case 6:return n=p.sent(),[2/*return*/,Promise.reject(n instanceof Error?n:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
1431
  return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.error("Error setting user attributes",a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1431
1432
 
1432
1433
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
@@ -1764,8 +1765,9 @@ function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web Vie
1764
1765
  // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
1765
1766
  // persistence or Identity directly.
1766
1767
  if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
1767
- var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)&&c._IntegrationCapture.capture();// Configure Rokt Manager with user and filtered user
1768
- var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={sandbox:b.isDevelopmentMode};c._RoktManager.init(h,j,e,k);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1768
+ var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)&&c._IntegrationCapture.capture(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST();// Configure Rokt Manager with user and filtered user
1769
+ var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={sandbox:b.isDevelopmentMode};// https://go.mparticle.com/work/SQDSDKS-7339
1770
+ c._RoktManager.init(h,j,c.Identity,c.Logger,k);}processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1769
1771
  // if an identify request is unnecessary, such as if there is an existing session
1770
1772
  (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
1771
1773
  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.39.1";
18
+ var version = "2.40.0";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
@@ -1417,16 +1417,17 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1417
1417
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1418
1418
  //
1419
1419
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1420
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1420
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1421
1421
  * Initializes the RoktManager with configuration settings and user data.
1422
1422
  *
1423
1423
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
1424
1424
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
1425
- * @param {IMParticleUser} currentUser - Current mParticle user object
1425
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
1426
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
1426
1427
  * @param {IRoktManagerOptions} options - Options for the RoktManager
1427
1428
  *
1428
1429
  * @throws Logs error to console if placementAttributesMapping parsing fails
1429
- */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(h);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapPlacementAttributes(c,this.placementAttributesMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
+ */return a.prototype.init=function(a,b,c,d,e){var f=a||{},g=f.userAttributeFilters,h=f.settings,i=(h||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(i);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.identityService=c,this.logger=d,this.filters={userAttributeFilters:g,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===e||void 0===e?void 0:e.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c,d;return __awaiter(this,void 0,void 0,function(){var e,f,g,h,i,j,k,l,m,n,o=this;return __generator(this,function(p){switch(p.label){case 0:if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),[2/*return*/,Promise.resolve({})];p.label=1;case 1:if(p.trys.push([1,6,,7]),e=a.attributes,f=null!==(b=null===e||void 0===e?void 0:e.sandbox)&&void 0!==b?b:this.sandbox,g=this.mapPlacementAttributes(e,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),h=(null===(d=null===(c=this.currentUser)||void 0===c?void 0:c.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},i=h.email,j=g.email,!j||i&&i===j)return [3/*break*/,5];i&&i!==j&&this.logger.warning("Email mismatch detected. Current email, ".concat(i," differs from email passed to selectPlacements call, ").concat(j,". Proceeding to call identify with ").concat(j,". Please verify your implementation.")),p.label=2;case 2:return p.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){o.identityService.identify({userIdentities:__assign(__assign({},h),{email:j})},function(){a();});})];case 3:return p.sent(),[3/*break*/,5];case 4:return k=p.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(k)),[3/*break*/,5];case 5:return this.setUserAttributes(g),l=__assign(__assign({},g),null===f?{}:{sandbox:f}),m=__assign(__assign({},a),{attributes:l}),[2/*return*/,this.kit.selectPlacements(m)];case 6:return n=p.sent(),[2/*return*/,Promise.reject(n instanceof Error?n:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
1431
  return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.error("Error setting user attributes",a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1431
1432
 
1432
1433
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
@@ -1764,8 +1765,9 @@ function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web Vie
1764
1765
  // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
1765
1766
  // persistence or Identity directly.
1766
1767
  if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
1767
- var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)&&c._IntegrationCapture.capture();// Configure Rokt Manager with user and filtered user
1768
- var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={sandbox:b.isDevelopmentMode};c._RoktManager.init(h,j,e,k);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1768
+ var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)&&c._IntegrationCapture.capture(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST();// Configure Rokt Manager with user and filtered user
1769
+ var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={sandbox:b.isDevelopmentMode};// https://go.mparticle.com/work/SQDSDKS-7339
1770
+ c._RoktManager.init(h,j,c.Identity,c.Logger,k);}processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1769
1771
  // if an identify request is unnecessary, such as if there is an existing session
1770
1772
  (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
1771
1773
  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.39.1";
206
+ var version = "2.40.0";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -9664,7 +9664,6 @@ var mParticle = (function () {
9664
9664
  this.kit = null;
9665
9665
  this.filters = {};
9666
9666
  this.currentUser = null;
9667
- this.filteredUser = null;
9668
9667
  this.messageQueue = [];
9669
9668
  this.sandbox = null;
9670
9669
  this.placementAttributesMapping = [];
@@ -9674,12 +9673,13 @@ var mParticle = (function () {
9674
9673
  *
9675
9674
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
9676
9675
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
9677
- * @param {IMParticleUser} currentUser - Current mParticle user object
9676
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
9677
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
9678
9678
  * @param {IRoktManagerOptions} options - Options for the RoktManager
9679
9679
  *
9680
9680
  * @throws Logs error to console if placementAttributesMapping parsing fails
9681
9681
  */
9682
- RoktManager.prototype.init = function (roktConfig, filteredUser, currentUser, options) {
9682
+ RoktManager.prototype.init = function (roktConfig, filteredUser, identityService, logger, options) {
9683
9683
  var _a = roktConfig || {},
9684
9684
  userAttributeFilters = _a.userAttributeFilters,
9685
9685
  settings = _a.settings;
@@ -9689,7 +9689,8 @@ var mParticle = (function () {
9689
9689
  } catch (error) {
9690
9690
  console.error('Error parsing placement attributes mapping from config', error);
9691
9691
  }
9692
- this.currentUser = currentUser;
9692
+ this.identityService = identityService;
9693
+ this.logger = logger;
9693
9694
  this.filters = {
9694
9695
  userAttributeFilters: userAttributeFilters,
9695
9696
  filterUserAttributes: KitFilterHelper.filterUserAttributes,
@@ -9701,31 +9702,89 @@ var mParticle = (function () {
9701
9702
  this.kit = kit;
9702
9703
  this.processMessageQueue();
9703
9704
  };
9705
+ /**
9706
+ * Renders ads based on the options provided
9707
+ *
9708
+ * @param {IRoktSelectPlacementsOptions} options - The options for selecting placements, including attributes and optional identifier
9709
+ * @returns {Promise<IRoktSelection>} A promise that resolves to the selection
9710
+ *
9711
+ * @example
9712
+ * // Correct usage with await
9713
+ * await window.mParticle.Rokt.selectPlacements({
9714
+ * attributes: {
9715
+ * email: 'user@example.com',
9716
+ * customAttr: 'value'
9717
+ * }
9718
+ * });
9719
+ */
9704
9720
  RoktManager.prototype.selectPlacements = function (options) {
9705
- var _a;
9706
- if (!this.isReady()) {
9707
- this.queueMessage({
9708
- methodName: 'selectPlacements',
9709
- payload: options
9710
- });
9711
- return Promise.resolve({});
9712
- }
9713
- try {
9714
- var attributes = options.attributes;
9715
- var sandboxValue = (_a = attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) !== null && _a !== void 0 ? _a : this.sandbox;
9716
- var mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9717
- this.setUserAttributes(mappedAttributes);
9718
- var enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9719
- sandbox: sandboxValue
9720
- } : {});
9721
- var enrichedOptions = __assign(__assign({}, options), {
9722
- attributes: enrichedAttributes
9721
+ var _a, _b, _c;
9722
+ return __awaiter(this, void 0, void 0, function () {
9723
+ var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail_1, error_1, enrichedAttributes, enrichedOptions, error_2;
9724
+ var _this = this;
9725
+ return __generator(this, function (_d) {
9726
+ switch (_d.label) {
9727
+ case 0:
9728
+ if (!this.isReady()) {
9729
+ this.queueMessage({
9730
+ methodName: 'selectPlacements',
9731
+ payload: options
9732
+ });
9733
+ return [2 /*return*/, Promise.resolve({})];
9734
+ }
9735
+ _d.label = 1;
9736
+ case 1:
9737
+ _d.trys.push([1, 6,, 7]);
9738
+ attributes = options.attributes;
9739
+ sandboxValue = (_a = attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) !== null && _a !== void 0 ? _a : this.sandbox;
9740
+ mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9741
+ // Get current user identities
9742
+ this.currentUser = this.identityService.getCurrentUser();
9743
+ currentUserIdentities_1 = ((_c = (_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.getUserIdentities()) === null || _c === void 0 ? void 0 : _c.userIdentities) || {};
9744
+ currentEmail = currentUserIdentities_1.email;
9745
+ newEmail_1 = mappedAttributes.email;
9746
+ if (!(newEmail_1 && (!currentEmail || currentEmail !== newEmail_1))) return [3 /*break*/, 5];
9747
+ if (currentEmail && currentEmail !== newEmail_1) {
9748
+ this.logger.warning("Email mismatch detected. Current email, ".concat(currentEmail, " differs from email passed to selectPlacements call, ").concat(newEmail_1, ". Proceeding to call identify with ").concat(newEmail_1, ". Please verify your implementation."));
9749
+ }
9750
+ _d.label = 2;
9751
+ case 2:
9752
+ _d.trys.push([2, 4,, 5]);
9753
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
9754
+ _this.identityService.identify({
9755
+ userIdentities: __assign(__assign({}, currentUserIdentities_1), {
9756
+ email: newEmail_1
9757
+ })
9758
+ }, function () {
9759
+ resolve();
9760
+ });
9761
+ })];
9762
+ case 3:
9763
+ _d.sent();
9764
+ return [3 /*break*/, 5];
9765
+ case 4:
9766
+ error_1 = _d.sent();
9767
+ this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error_1));
9768
+ return [3 /*break*/, 5];
9769
+ case 5:
9770
+ this.setUserAttributes(mappedAttributes);
9771
+ enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9772
+ sandbox: sandboxValue
9773
+ } : {});
9774
+ enrichedOptions = __assign(__assign({}, options), {
9775
+ attributes: enrichedAttributes
9776
+ });
9777
+ return [2 /*return*/, this.kit.selectPlacements(enrichedOptions)];
9778
+ case 6:
9779
+ error_2 = _d.sent();
9780
+ return [2 /*return*/, Promise.reject(error_2 instanceof Error ? error_2 : new Error('Unknown error occurred'))];
9781
+ case 7:
9782
+ return [2 /*return*/];
9783
+ }
9723
9784
  });
9724
- return this.kit.selectPlacements(enrichedOptions);
9725
- } catch (error) {
9726
- return Promise.reject(error instanceof Error ? error : new Error('Unknown error occurred'));
9727
- }
9785
+ });
9728
9786
  };
9787
+
9729
9788
  RoktManager.prototype.hashAttributes = function (attributes) {
9730
9789
  if (!this.isReady()) {
9731
9790
  this.queueMessage({
@@ -10787,6 +10846,12 @@ var mParticle = (function () {
10787
10846
  if (mpInstance._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)) {
10788
10847
  mpInstance._IntegrationCapture.capture();
10789
10848
  }
10849
+ mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats);
10850
+ mpInstance._Forwarders.processPixelConfigs(config);
10851
+ // Checks if session is created, resumed, or needs to be ended
10852
+ // Logs a session start or session end event accordingly
10853
+ mpInstance._SessionManager.initialize();
10854
+ mpInstance._Events.logAST();
10790
10855
  // Configure Rokt Manager with user and filtered user
10791
10856
  var roktConfig = parseConfig(config, 'Rokt', 181);
10792
10857
  if (roktConfig) {
@@ -10797,14 +10862,9 @@ var mParticle = (function () {
10797
10862
  var roktOptions = {
10798
10863
  sandbox: config.isDevelopmentMode
10799
10864
  };
10800
- mpInstance._RoktManager.init(roktConfig, roktFilteredUser, currentUser, roktOptions);
10865
+ // https://go.mparticle.com/work/SQDSDKS-7339
10866
+ mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance.Logger, roktOptions);
10801
10867
  }
10802
- mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats);
10803
- mpInstance._Forwarders.processPixelConfigs(config);
10804
- // Checks if session is created, resumed, or needs to be ended
10805
- // Logs a session start or session end event accordingly
10806
- mpInstance._SessionManager.initialize();
10807
- mpInstance._Events.logAST();
10808
10868
  processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities);
10809
10869
  }
10810
10870
  // We will continue to clear out the ready queue as part of the initial init flow
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.39.1",
3
+ "version": "2.40.0",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -1394,6 +1394,17 @@ function completeSDKInitialization(apiKey, config, mpInstance) {
1394
1394
  mpInstance._IntegrationCapture.capture();
1395
1395
  }
1396
1396
 
1397
+ mpInstance._Forwarders.processForwarders(
1398
+ config,
1399
+ mpInstance._APIClient.prepareForwardingStats
1400
+ );
1401
+ mpInstance._Forwarders.processPixelConfigs(config);
1402
+
1403
+ // Checks if session is created, resumed, or needs to be ended
1404
+ // Logs a session start or session end event accordingly
1405
+ mpInstance._SessionManager.initialize();
1406
+ mpInstance._Events.logAST();
1407
+
1397
1408
  // Configure Rokt Manager with user and filtered user
1398
1409
  const roktConfig: IKitConfigs = parseConfig(config, 'Rokt', 181);
1399
1410
  if (roktConfig) {
@@ -1406,19 +1417,16 @@ function completeSDKInitialization(apiKey, config, mpInstance) {
1406
1417
  const roktOptions: IRoktManagerOptions = {
1407
1418
  sandbox: config.isDevelopmentMode,
1408
1419
  };
1409
- mpInstance._RoktManager.init(roktConfig, roktFilteredUser, currentUser, roktOptions);
1410
- }
1411
1420
 
1412
- mpInstance._Forwarders.processForwarders(
1413
- config,
1414
- mpInstance._APIClient.prepareForwardingStats
1415
- );
1416
- mpInstance._Forwarders.processPixelConfigs(config);
1417
-
1418
- // Checks if session is created, resumed, or needs to be ended
1419
- // Logs a session start or session end event accordingly
1420
- mpInstance._SessionManager.initialize();
1421
- mpInstance._Events.logAST();
1421
+ // https://go.mparticle.com/work/SQDSDKS-7339
1422
+ mpInstance._RoktManager.init(
1423
+ roktConfig,
1424
+ roktFilteredUser,
1425
+ mpInstance.Identity,
1426
+ mpInstance.Logger,
1427
+ roktOptions
1428
+ );
1429
+ }
1422
1430
 
1423
1431
  processIdentityCallback(
1424
1432
  mpInstance,
@@ -3,6 +3,8 @@ import { UserAttributeFilters } from "./forwarders.interfaces";
3
3
  import { IMParticleUser } from "./identity-user-interfaces";
4
4
  import KitFilterHelper from "./kitFilterHelper";
5
5
  import { Dictionary, parseSettingsString } from "./utils";
6
+ import { SDKIdentityApi } from "./identity.interfaces";
7
+ import { SDKLoggerApi } from "./sdkRuntimeModels";
6
8
 
7
9
  // https://docs.rokt.com/developers/integration-guides/web/library/attributes
8
10
  export interface IRoktPartnerAttributes {
@@ -42,7 +44,7 @@ export interface RoktKitFilterSettings {
42
44
  filteredUser?: IMParticleUser | null;
43
45
  }
44
46
 
45
- export interface IRoktKit {
47
+ export interface IRoktKit {
46
48
  filters: RoktKitFilterSettings;
47
49
  filteredUser: IMParticleUser | null;
48
50
  launcher: IRoktLauncher | null;
@@ -68,24 +70,31 @@ export interface IRoktManagerOptions {
68
70
  export default class RoktManager {
69
71
  public kit: IRoktKit = null;
70
72
  public filters: RoktKitFilterSettings = {};
71
-
72
73
  private currentUser: IMParticleUser | null = null;
73
- private filteredUser: IMParticleUser | null = null;
74
74
  private messageQueue: IRoktMessage[] = [];
75
75
  private sandbox: boolean | null = null;
76
76
  private placementAttributesMapping: Dictionary<string>[] = [];
77
+ private identityService: SDKIdentityApi;
78
+ private logger: SDKLoggerApi;
77
79
 
78
80
  /**
79
81
  * Initializes the RoktManager with configuration settings and user data.
80
82
  *
81
83
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
82
84
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
83
- * @param {IMParticleUser} currentUser - Current mParticle user object
85
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
86
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
84
87
  * @param {IRoktManagerOptions} options - Options for the RoktManager
85
88
  *
86
89
  * @throws Logs error to console if placementAttributesMapping parsing fails
87
90
  */
88
- public init(roktConfig: IKitConfigs, filteredUser: IMParticleUser, currentUser: IMParticleUser, options?: IRoktManagerOptions): void {
91
+ public init(
92
+ roktConfig: IKitConfigs,
93
+ filteredUser: IMParticleUser,
94
+ identityService: SDKIdentityApi,
95
+ logger?: SDKLoggerApi,
96
+ options?: IRoktManagerOptions
97
+ ): void {
89
98
  const { userAttributeFilters, settings } = roktConfig || {};
90
99
  const { placementAttributesMapping } = settings || {};
91
100
 
@@ -95,7 +104,8 @@ export default class RoktManager {
95
104
  console.error('Error parsing placement attributes mapping from config', error);
96
105
  }
97
106
 
98
- this.currentUser = currentUser;
107
+ this.identityService = identityService;
108
+ this.logger = logger;
99
109
 
100
110
  this.filters = {
101
111
  userAttributeFilters,
@@ -111,7 +121,22 @@ export default class RoktManager {
111
121
  this.processMessageQueue();
112
122
  }
113
123
 
114
- public selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
124
+ /**
125
+ * Renders ads based on the options provided
126
+ *
127
+ * @param {IRoktSelectPlacementsOptions} options - The options for selecting placements, including attributes and optional identifier
128
+ * @returns {Promise<IRoktSelection>} A promise that resolves to the selection
129
+ *
130
+ * @example
131
+ * // Correct usage with await
132
+ * await window.mParticle.Rokt.selectPlacements({
133
+ * attributes: {
134
+ * email: 'user@example.com',
135
+ * customAttr: 'value'
136
+ * }
137
+ * });
138
+ */
139
+ public async selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
115
140
  if (!this.isReady()) {
116
141
  this.queueMessage({
117
142
  methodName: 'selectPlacements',
@@ -125,12 +150,42 @@ export default class RoktManager {
125
150
  const sandboxValue = attributes?.sandbox ?? this.sandbox;
126
151
  const mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
127
152
 
153
+ // Get current user identities
154
+ this.currentUser = this.identityService.getCurrentUser();
155
+ const currentUserIdentities = this.currentUser?.getUserIdentities()?.userIdentities || {};
156
+ const currentEmail = currentUserIdentities.email;
157
+ const newEmail = mappedAttributes.email as string;
158
+
159
+ // https://go.mparticle.com/work/SQDSDKS-7338
160
+ // Check if email exists and differs
161
+ if (newEmail && (!currentEmail || currentEmail !== newEmail)) {
162
+ if (currentEmail && currentEmail !== newEmail) {
163
+ this.logger.warning(`Email mismatch detected. Current email, ${currentEmail} differs from email passed to selectPlacements call, ${newEmail}. Proceeding to call identify with ${newEmail}. Please verify your implementation.`);
164
+ }
165
+
166
+ // Call identify with the new user identities
167
+ try {
168
+ await new Promise<void>((resolve, reject) => {
169
+ this.identityService.identify({
170
+ userIdentities: {
171
+ ...currentUserIdentities,
172
+ email: newEmail
173
+ }
174
+ }, () => {
175
+ resolve();
176
+ });
177
+ });
178
+ } catch (error) {
179
+ this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error));
180
+ }
181
+ }
182
+
128
183
  this.setUserAttributes(mappedAttributes);
129
184
 
130
185
  const enrichedAttributes = {
131
186
  ...mappedAttributes,
132
187
  ...(sandboxValue !== null ? { sandbox: sandboxValue } : {}),
133
- };
188
+ };
134
189
 
135
190
  const enrichedOptions = {
136
191
  ...options,