@mparticle/web-sdk 2.43.1 → 2.43.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,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.43.1";
18
+ var version = "2.43.3";
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/"},// These are the paths that are used to construct the CNAME urls
@@ -444,7 +444,8 @@ function appendUserInfo(a,b){if(b){if(!a)return b.MPID=null,b.ConsentState=null,
444
444
  // TODO: Handle cases where Local Storage is unavailable
445
445
  // Potentially shared between Vault and Persistence as well
446
446
  // https://go.mparticle.com/work/SQDSDKS-5022
447
- return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a=Date.now(),b=this.mpInstance,c=b._Store,d=b.Identity,e=b._timeOnSiteTimer,f=b._Helpers,g=c.sessionId,h=c.deviceId,i=c.sessionStartDate,j=c.SDKConfig,k=f.generateUniqueId,l=d.getCurrentUser,m={AppName:j.appName,AppVersion:j.appVersion,Package:j["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:a,SessionId:g,DeviceId:h,IsFirstRun:!1,SourceMessageId:k(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===i||void 0===i?void 0:i.getTime())||a,Debug:j.isDevelopmentMode,ActiveTimeOnSite:(null===e||void 0===e?void 0:e.getTimeInForeground())||0,IsBackgroundAST:!0};return appendUserInfo(l(),m),m},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
447
+ return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a=Date.now(),b=this.mpInstance,c=b._Store,d=b.Identity,e=b._timeOnSiteTimer,f=b._Helpers,g=c.sessionId,h=c.deviceId,i=c.sessionStartDate,j=c.SDKConfig,k=f.generateUniqueId,l=f.getFeatureFlag,m=d.getCurrentUser,n={AppName:j.appName,AppVersion:j.appVersion,Package:j["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:a,SessionId:g,DeviceId:h,IsFirstRun:!1,SourceMessageId:k(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===i||void 0===i?void 0:i.getTime())||a,Debug:j.isDevelopmentMode,ActiveTimeOnSite:(null===e||void 0===e?void 0:e.getTimeInForeground())||0,IsBackgroundAST:!0},o=__assign({},n.CustomFlags),p=c.integrationAttributes;// https://go.mparticle.com/work/SQDSDKS-5053
448
+ if(l&&l(Constants.FeatureFlags.CaptureIntegrationSpecificIds)){this.mpInstance._IntegrationCapture.capture();var q=this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();o=__assign(__assign({},q),o);var r=this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();p=__assign(__assign({},r),p);}return n.CustomFlags=o,n.IntegrationAttributes=p,appendUserInfo(m(),n),n},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
448
449
  var c=a.mpInstance._Helpers.getFeatureFlag,d=Constants.FeatureFlags.AstBackgroundEvents;if(c(d)){if(b.shouldDebounceAndUpdateLastASTTime())return;// Add application state transition event to queue
449
450
  var e=b.createBackgroundASTEvent();b.queueEvent(e);}// Then trigger the upload with beacon
450
451
  b.prepareAndUpload(!1,b.isBeaconAvailable());};document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&c();}),window.addEventListener("beforeunload",c),window.addEventListener("pagehide",c);},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){if(!isEmpty(a)){var b=this.mpInstance.Logger.verbose;this.eventsQueuedForProcessing.push(a),this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store(this.eventsQueuedForProcessing),b("Queuing event: ".concat(JSON.stringify(a))),b("Queued event count: ".concat(this.eventsQueuedForProcessing.length)),this.shouldTriggerImmediateUpload(a.EventDataType)&&this.prepareAndUpload(!1,!1);}},a.prototype.shouldTriggerImmediateUpload=function(a){var b=[MessageType$1.Commerce,MessageType$1.UserIdentityChange];return !this.batchingEnabled||b.includes(a)},(a.createNewBatches=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
@@ -1427,7 +1428,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1427
1428
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1428
1429
  //
1429
1430
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1430
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1431
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[];}/**
1431
1432
  * Initializes the RoktManager with configuration settings and user data.
1432
1433
  *
1433
1434
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1443,8 +1444,8 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1443
1444
  // as that is independent of this setting, though they share the same name.
1444
1445
  var j=(null===e||void 0===e?void 0:e.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1445
1446
  // to the Rokt Launcher.
1446
- this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),[2/*return*/,Promise.resolve({})];o.label=1;case 1:if(o.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,!i||h&&h===i)return [3/*break*/,5];h&&h!==i&&this.logger.warning("Email mismatch detected. Current email, ".concat(h," differs from email passed to selectPlacements call, ").concat(i,". Proceeding to call identify with ").concat(i,". Please verify your implementation.")),o.label=2;case 2:return o.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){n.identityService.identify({userIdentities:__assign(__assign({},g),{email:i})},function(){a();});})];case 3:return o.sent(),[3/*break*/,5];case 4:return j=o.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(j)),[3/*break*/,5];case 5:return this.setUserAttributes(f),k=__assign(__assign({},f),null===e?{}:{sandbox:e}),l=__assign(__assign({},a),{attributes:k}),[2/*return*/,this.kit.selectPlacements(l)];case 6:return m=o.sent(),[2/*return*/,Promise.reject(m instanceof Error?m: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
1447
- 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}();
1447
+ this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];o.label=1;case 1:if(o.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,!i||h&&h===i)return [3/*break*/,5];h&&h!==i&&this.logger.warning("Email mismatch detected. Current email, ".concat(h," differs from email passed to selectPlacements call, ").concat(i,". Proceeding to call identify with ").concat(i,". Please verify your implementation.")),o.label=2;case 2:return o.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){n.identityService.identify({userIdentities:__assign(__assign({},g),{email:i})},function(){a();});})];case 3:return o.sent(),[3/*break*/,5];case 4:return j=o.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(j)),[3/*break*/,5];case 5:return this.setUserAttributes(f),k=__assign(__assign({},f),null===e?{}:{sandbox:e}),l=__assign(__assign({},a),{attributes:k}),[2/*return*/,this.kit.selectPlacements(l)];case 6:return m=o.sent(),[2/*return*/,Promise.reject(m instanceof Error?m:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.deferredCall("hashAttributes",a);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.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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1448
+ 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,b=this;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")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b.kit)||!isFunction(b.kit[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found in kit")));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.kit[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));}}));},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}();
1448
1449
 
1449
1450
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
1450
1451
  * <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- var version = "2.43.1";
18
+ var version = "2.43.3";
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/"},// These are the paths that are used to construct the CNAME urls
@@ -444,7 +444,8 @@ function appendUserInfo(a,b){if(b){if(!a)return b.MPID=null,b.ConsentState=null,
444
444
  // TODO: Handle cases where Local Storage is unavailable
445
445
  // Potentially shared between Vault and Persistence as well
446
446
  // https://go.mparticle.com/work/SQDSDKS-5022
447
- return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a=Date.now(),b=this.mpInstance,c=b._Store,d=b.Identity,e=b._timeOnSiteTimer,f=b._Helpers,g=c.sessionId,h=c.deviceId,i=c.sessionStartDate,j=c.SDKConfig,k=f.generateUniqueId,l=d.getCurrentUser,m={AppName:j.appName,AppVersion:j.appVersion,Package:j["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:a,SessionId:g,DeviceId:h,IsFirstRun:!1,SourceMessageId:k(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===i||void 0===i?void 0:i.getTime())||a,Debug:j.isDevelopmentMode,ActiveTimeOnSite:(null===e||void 0===e?void 0:e.getTimeInForeground())||0,IsBackgroundAST:!0};return appendUserInfo(l(),m),m},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
447
+ return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTime<this.AST_DEBOUNCE_MS)||(this.lastASTEventTime=a,!1)},a.prototype.createBackgroundASTEvent=function(){var a=Date.now(),b=this.mpInstance,c=b._Store,d=b.Identity,e=b._timeOnSiteTimer,f=b._Helpers,g=c.sessionId,h=c.deviceId,i=c.sessionStartDate,j=c.SDKConfig,k=f.generateUniqueId,l=f.getFeatureFlag,m=d.getCurrentUser,n={AppName:j.appName,AppVersion:j.appVersion,Package:j["package"],EventDataType:MessageType$1.AppStateTransition,Timestamp:a,SessionId:g,DeviceId:h,IsFirstRun:!1,SourceMessageId:k(),SDKVersion:Constants.sdkVersion,CustomFlags:{},EventAttributes:{},SessionStartDate:(null===i||void 0===i?void 0:i.getTime())||a,Debug:j.isDevelopmentMode,ActiveTimeOnSite:(null===e||void 0===e?void 0:e.getTimeInForeground())||0,IsBackgroundAST:!0},o=__assign({},n.CustomFlags),p=c.integrationAttributes;// https://go.mparticle.com/work/SQDSDKS-5053
448
+ if(l&&l(Constants.FeatureFlags.CaptureIntegrationSpecificIds)){this.mpInstance._IntegrationCapture.capture();var q=this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();o=__assign(__assign({},q),o);var r=this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();p=__assign(__assign({},r),p);}return n.CustomFlags=o,n.IntegrationAttributes=p,appendUserInfo(m(),n),n},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
448
449
  var c=a.mpInstance._Helpers.getFeatureFlag,d=Constants.FeatureFlags.AstBackgroundEvents;if(c(d)){if(b.shouldDebounceAndUpdateLastASTTime())return;// Add application state transition event to queue
449
450
  var e=b.createBackgroundASTEvent();b.queueEvent(e);}// Then trigger the upload with beacon
450
451
  b.prepareAndUpload(!1,b.isBeaconAvailable());};document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&c();}),window.addEventListener("beforeunload",c),window.addEventListener("pagehide",c);},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){if(!isEmpty(a)){var b=this.mpInstance.Logger.verbose;this.eventsQueuedForProcessing.push(a),this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store(this.eventsQueuedForProcessing),b("Queuing event: ".concat(JSON.stringify(a))),b("Queued event count: ".concat(this.eventsQueuedForProcessing.length)),this.shouldTriggerImmediateUpload(a.EventDataType)&&this.prepareAndUpload(!1,!1);}},a.prototype.shouldTriggerImmediateUpload=function(a){var b=[MessageType$1.Commerce,MessageType$1.UserIdentityChange];return !this.batchingEnabled||b.includes(a)},(a.createNewBatches=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
@@ -1427,7 +1428,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1427
1428
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1428
1429
  //
1429
1430
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1430
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1431
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[];}/**
1431
1432
  * Initializes the RoktManager with configuration settings and user data.
1432
1433
  *
1433
1434
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1443,8 +1444,8 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1443
1444
  // as that is independent of this setting, though they share the same name.
1444
1445
  var j=(null===e||void 0===e?void 0:e.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1445
1446
  // to the Rokt Launcher.
1446
- this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),[2/*return*/,Promise.resolve({})];o.label=1;case 1:if(o.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,!i||h&&h===i)return [3/*break*/,5];h&&h!==i&&this.logger.warning("Email mismatch detected. Current email, ".concat(h," differs from email passed to selectPlacements call, ").concat(i,". Proceeding to call identify with ").concat(i,". Please verify your implementation.")),o.label=2;case 2:return o.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){n.identityService.identify({userIdentities:__assign(__assign({},g),{email:i})},function(){a();});})];case 3:return o.sent(),[3/*break*/,5];case 4:return j=o.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(j)),[3/*break*/,5];case 5:return this.setUserAttributes(f),k=__assign(__assign({},f),null===e?{}:{sandbox:e}),l=__assign(__assign({},a),{attributes:k}),[2/*return*/,this.kit.selectPlacements(l)];case 6:return m=o.sent(),[2/*return*/,Promise.reject(m instanceof Error?m: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
1447
- 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}();
1447
+ this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];o.label=1;case 1:if(o.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,!i||h&&h===i)return [3/*break*/,5];h&&h!==i&&this.logger.warning("Email mismatch detected. Current email, ".concat(h," differs from email passed to selectPlacements call, ").concat(i,". Proceeding to call identify with ").concat(i,". Please verify your implementation.")),o.label=2;case 2:return o.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){n.identityService.identify({userIdentities:__assign(__assign({},g),{email:i})},function(){a();});})];case 3:return o.sent(),[3/*break*/,5];case 4:return j=o.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(j)),[3/*break*/,5];case 5:return this.setUserAttributes(f),k=__assign(__assign({},f),null===e?{}:{sandbox:e}),l=__assign(__assign({},a),{attributes:k}),[2/*return*/,this.kit.selectPlacements(l)];case 6:return m=o.sent(),[2/*return*/,Promise.reject(m instanceof Error?m:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.deferredCall("hashAttributes",a);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.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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1448
+ 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,b=this;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")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b.kit)||!isFunction(b.kit[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found in kit")));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.kit[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));}}));},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}();
1448
1449
 
1449
1450
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
1450
1451
  * <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
package/dist/mparticle.js CHANGED
@@ -203,7 +203,7 @@ var mParticle = (function () {
203
203
  Base64: Base64$1
204
204
  };
205
205
 
206
- var version = "2.43.1";
206
+ var version = "2.43.3";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -2391,7 +2391,8 @@ var mParticle = (function () {
2391
2391
  deviceId = _Store.deviceId,
2392
2392
  sessionStartDate = _Store.sessionStartDate,
2393
2393
  SDKConfig = _Store.SDKConfig;
2394
- var generateUniqueId = _Helpers.generateUniqueId;
2394
+ var generateUniqueId = _Helpers.generateUniqueId,
2395
+ getFeatureFlag = _Helpers.getFeatureFlag;
2395
2396
  var getCurrentUser = Identity.getCurrentUser;
2396
2397
  var event = {
2397
2398
  AppName: SDKConfig.appName,
@@ -2411,6 +2412,20 @@ var mParticle = (function () {
2411
2412
  ActiveTimeOnSite: (_timeOnSiteTimer === null || _timeOnSiteTimer === void 0 ? void 0 : _timeOnSiteTimer.getTimeInForeground()) || 0,
2412
2413
  IsBackgroundAST: true
2413
2414
  };
2415
+ var customFlags = __assign({}, event.CustomFlags);
2416
+ var integrationAttributes = _Store.integrationAttributes;
2417
+ // https://go.mparticle.com/work/SQDSDKS-5053
2418
+ if (getFeatureFlag && getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds)) {
2419
+ // Attempt to recapture click IDs in case a third party integration
2420
+ // has added or updated new click IDs since the last event was sent.
2421
+ this.mpInstance._IntegrationCapture.capture();
2422
+ var transformedClickIDs = this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();
2423
+ customFlags = __assign(__assign({}, transformedClickIDs), customFlags);
2424
+ var transformedIntegrationAttributes = this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();
2425
+ integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes);
2426
+ }
2427
+ event.CustomFlags = customFlags;
2428
+ event.IntegrationAttributes = integrationAttributes;
2414
2429
  appendUserInfo(getCurrentUser(), event);
2415
2430
  return event;
2416
2431
  };
@@ -9721,7 +9736,7 @@ var mParticle = (function () {
9721
9736
  this.kit = null;
9722
9737
  this.filters = {};
9723
9738
  this.currentUser = null;
9724
- this.messageQueue = [];
9739
+ this.messageQueue = new Map();
9725
9740
  this.sandbox = null;
9726
9741
  this.placementAttributesMapping = [];
9727
9742
  }
@@ -9795,11 +9810,7 @@ var mParticle = (function () {
9795
9810
  switch (_c.label) {
9796
9811
  case 0:
9797
9812
  if (!this.isReady()) {
9798
- this.queueMessage({
9799
- methodName: 'selectPlacements',
9800
- payload: options
9801
- });
9802
- return [2 /*return*/, Promise.resolve({})];
9813
+ return [2 /*return*/, this.deferredCall('selectPlacements', options)];
9803
9814
  }
9804
9815
  _c.label = 1;
9805
9816
  case 1:
@@ -9856,11 +9867,7 @@ var mParticle = (function () {
9856
9867
 
9857
9868
  RoktManager.prototype.hashAttributes = function (attributes) {
9858
9869
  if (!this.isReady()) {
9859
- this.queueMessage({
9860
- methodName: 'hashAttributes',
9861
- payload: attributes
9862
- });
9863
- return Promise.resolve({});
9870
+ return this.deferredCall('hashAttributes', attributes);
9864
9871
  }
9865
9872
  try {
9866
9873
  return this.kit.hashAttributes(attributes);
@@ -9870,10 +9877,7 @@ var mParticle = (function () {
9870
9877
  };
9871
9878
  RoktManager.prototype.setExtensionData = function (extensionData) {
9872
9879
  if (!this.isReady()) {
9873
- this.queueMessage({
9874
- methodName: 'setExtensionData',
9875
- payload: extensionData
9876
- });
9880
+ this.deferredCall('setExtensionData', extensionData);
9877
9881
  return;
9878
9882
  }
9879
9883
  try {
@@ -9918,29 +9922,57 @@ var mParticle = (function () {
9918
9922
  };
9919
9923
  RoktManager.prototype.processMessageQueue = function () {
9920
9924
  var _this = this;
9921
- if (this.messageQueue.length > 0 && this.isReady()) {
9922
- this.messageQueue.forEach(function (message) {
9923
- return __awaiter(_this, void 0, void 0, function () {
9924
- return __generator(this, function (_a) {
9925
- switch (_a.label) {
9926
- case 0:
9927
- if (!(this.kit && message.methodName in this.kit)) return [3 /*break*/, 2];
9928
- return [4 /*yield*/, this.kit[message.methodName](message.payload)];
9929
- case 1:
9930
- _a.sent();
9931
- _a.label = 2;
9932
- case 2:
9933
- return [2 /*return*/];
9934
- }
9935
- });
9936
- });
9937
- });
9938
-
9939
- this.messageQueue = [];
9925
+ var _a;
9926
+ if (!this.isReady() || this.messageQueue.size === 0) {
9927
+ return;
9940
9928
  }
9929
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages"));
9930
+ this.messageQueue.forEach(function (message) {
9931
+ var _a, _b, _c;
9932
+ if (!(message.methodName in _this.kit) || !isFunction(_this.kit[message.methodName])) {
9933
+ (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Method ".concat(message.methodName, " not found in kit"));
9934
+ return;
9935
+ }
9936
+ (_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)));
9937
+ try {
9938
+ var result = _this.kit[message.methodName](message.payload);
9939
+ _this.completePendingPromise(message.messageId, result);
9940
+ } catch (error) {
9941
+ var errorMessage = error instanceof Error ? error.message : String(error);
9942
+ (_c = _this.logger) === null || _c === void 0 ? void 0 : _c.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage));
9943
+ _this.completePendingPromise(message.messageId, Promise.reject(error));
9944
+ }
9945
+ });
9941
9946
  };
9942
9947
  RoktManager.prototype.queueMessage = function (message) {
9943
- this.messageQueue.push(message);
9948
+ this.messageQueue.set(message.messageId, message);
9949
+ };
9950
+ RoktManager.prototype.deferredCall = function (methodName, payload) {
9951
+ var _this = this;
9952
+ return new Promise(function (resolve, reject) {
9953
+ var messageId = "".concat(methodName, "_").concat(generateUniqueId());
9954
+ _this.queueMessage({
9955
+ messageId: messageId,
9956
+ methodName: methodName,
9957
+ payload: payload,
9958
+ resolve: resolve,
9959
+ reject: reject
9960
+ });
9961
+ });
9962
+ };
9963
+ RoktManager.prototype.completePendingPromise = function (messageId, resultOrError) {
9964
+ if (!messageId || !this.messageQueue.has(messageId)) {
9965
+ return;
9966
+ }
9967
+ var message = this.messageQueue.get(messageId);
9968
+ if (message.resolve) {
9969
+ Promise.resolve(resultOrError).then(function (result) {
9970
+ return message.resolve(result);
9971
+ })["catch"](function (error) {
9972
+ return message.reject(error);
9973
+ });
9974
+ }
9975
+ this.messageQueue["delete"](messageId);
9944
9976
  };
9945
9977
  return RoktManager;
9946
9978
  }();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.43.1",
3
+ "version": "2.43.3",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -1,6 +1,6 @@
1
1
  import { Batch } from '@mparticle/event-models';
2
2
  import Constants from './constants';
3
- import { SDKEvent, SDKLoggerApi } from './sdkRuntimeModels';
3
+ import { SDKEvent, SDKEventCustomFlags, SDKLoggerApi } from './sdkRuntimeModels';
4
4
  import { convertEvents } from './sdkToEventsApiConverter';
5
5
  import { MessageType, EventType } from './types';
6
6
  import { getRampNumber, isEmpty } from './utils';
@@ -14,6 +14,7 @@ import {
14
14
  import { IMParticleUser } from './identity-user-interfaces';
15
15
  import { IMParticleWebSDKInstance } from './mp-instance';
16
16
  import { appendUserInfo } from './user-utils';
17
+ import { IntegrationAttributes } from './store';
17
18
  /**
18
19
  * BatchUploader contains all the logic to store/retrieve events and batches
19
20
  * to/from persistence, and upload batches to mParticle.
@@ -147,7 +148,7 @@ export class BatchUploader {
147
148
  const now = Date.now();
148
149
  const { _Store, Identity, _timeOnSiteTimer, _Helpers } = this.mpInstance;
149
150
  const { sessionId, deviceId, sessionStartDate, SDKConfig } = _Store;
150
- const { generateUniqueId } = _Helpers;
151
+ const { generateUniqueId, getFeatureFlag } = _Helpers;
151
152
  const { getCurrentUser } = Identity;
152
153
 
153
154
  const event = {
@@ -169,7 +170,28 @@ export class BatchUploader {
169
170
  IsBackgroundAST: true
170
171
  } as SDKEvent;
171
172
 
173
+
174
+ let customFlags: SDKEventCustomFlags = {...event.CustomFlags};
175
+ let integrationAttributes: IntegrationAttributes = _Store.integrationAttributes;
176
+
177
+ // https://go.mparticle.com/work/SQDSDKS-5053
178
+ if (getFeatureFlag && getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds)) {
179
+
180
+ // Attempt to recapture click IDs in case a third party integration
181
+ // has added or updated new click IDs since the last event was sent.
182
+ this.mpInstance._IntegrationCapture.capture();
183
+ const transformedClickIDs = this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();
184
+ customFlags = {...transformedClickIDs, ...customFlags};
185
+
186
+ const transformedIntegrationAttributes = this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();
187
+ integrationAttributes = {...transformedIntegrationAttributes, ...integrationAttributes};
188
+ }
189
+
190
+ event.CustomFlags = customFlags;
191
+ event.IntegrationAttributes = integrationAttributes;
192
+
172
193
  appendUserInfo(getCurrentUser(), event);
194
+
173
195
  return event;
174
196
  }
175
197
 
@@ -2,7 +2,7 @@ import { IKitConfigs } from "./configAPIClient";
2
2
  import { UserAttributeFilters } from "./forwarders.interfaces";
3
3
  import { IMParticleUser } from "./identity-user-interfaces";
4
4
  import KitFilterHelper from "./kitFilterHelper";
5
- import { Dictionary, parseSettingsString } from "./utils";
5
+ import { Dictionary, parseSettingsString, generateUniqueId, isFunction } from "./utils";
6
6
  import { SDKIdentityApi } from "./identity.interfaces";
7
7
  import { SDKLoggerApi } from "./sdkRuntimeModels";
8
8
 
@@ -34,8 +34,11 @@ export interface IRoktLauncher {
34
34
  }
35
35
 
36
36
  export interface IRoktMessage {
37
+ messageId: string;
37
38
  methodName: string;
38
39
  payload: any;
40
+ resolve?: Function;
41
+ reject?: Function;
39
42
  }
40
43
 
41
44
  export interface RoktKitFilterSettings {
@@ -76,7 +79,7 @@ export default class RoktManager {
76
79
  public kit: IRoktKit = null;
77
80
  public filters: RoktKitFilterSettings = {};
78
81
  private currentUser: IMParticleUser | null = null;
79
- private messageQueue: IRoktMessage[] = [];
82
+ private messageQueue: Map<string, IRoktMessage> = new Map();
80
83
  private sandbox: boolean | null = null;
81
84
  private placementAttributesMapping: Dictionary<string>[] = [];
82
85
  private identityService: SDKIdentityApi;
@@ -156,11 +159,7 @@ export default class RoktManager {
156
159
  */
157
160
  public async selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
158
161
  if (!this.isReady()) {
159
- this.queueMessage({
160
- methodName: 'selectPlacements',
161
- payload: options,
162
- });
163
- return Promise.resolve({} as IRoktSelection);
162
+ return this.deferredCall<IRoktSelection>('selectPlacements', options);
164
163
  }
165
164
 
166
165
  try {
@@ -216,13 +215,9 @@ export default class RoktManager {
216
215
  }
217
216
  }
218
217
 
219
- public hashAttributes(attributes: IRoktPartnerAttributes): Promise<Record<string, string>> {
218
+ public hashAttributes(attributes: IRoktPartnerAttributes): Promise<IRoktPartnerAttributes> {
220
219
  if (!this.isReady()) {
221
- this.queueMessage({
222
- methodName: 'hashAttributes',
223
- payload: attributes,
224
- });
225
- return Promise.resolve({} as Record<string, string>);
220
+ return this.deferredCall<IRoktPartnerAttributes>('hashAttributes', attributes);
226
221
  }
227
222
 
228
223
  try {
@@ -234,10 +229,7 @@ export default class RoktManager {
234
229
 
235
230
  public setExtensionData<T>(extensionData: IRoktPartnerExtensionData<T>): void {
236
231
  if (!this.isReady()) {
237
- this.queueMessage({
238
- methodName: 'setExtensionData',
239
- payload: extensionData,
240
- });
232
+ this.deferredCall<void>('setExtensionData', extensionData);
241
233
  return;
242
234
  }
243
235
 
@@ -288,17 +280,62 @@ export default class RoktManager {
288
280
  }
289
281
 
290
282
  private processMessageQueue(): void {
291
- if (this.messageQueue.length > 0 && this.isReady()) {
292
- this.messageQueue.forEach(async (message) => {
293
- if (this.kit && message.methodName in this.kit) {
294
- await (this.kit[message.methodName] as Function)(message.payload);
295
- }
296
- });
297
- this.messageQueue = [];
283
+ if (!this.isReady() || this.messageQueue.size === 0) {
284
+ return;
298
285
  }
286
+
287
+ this.logger?.verbose(`RoktManager: Processing ${this.messageQueue.size} queued messages`);
288
+
289
+ this.messageQueue.forEach((message) => {
290
+ if(!(message.methodName in this.kit) || !isFunction(this.kit[message.methodName])) {
291
+ this.logger?.error(`RoktManager: Method ${message.methodName} not found in kit`);
292
+ return;
293
+ }
294
+
295
+ this.logger?.verbose(`RoktManager: Processing queued message: ${message.methodName} with payload: ${JSON.stringify(message.payload)}`);
296
+
297
+ try {
298
+ const result = (this.kit[message.methodName] as Function)(message.payload);
299
+ this.completePendingPromise(message.messageId, result);
300
+ } catch (error) {
301
+ const errorMessage = error instanceof Error ? error.message : String(error);
302
+ this.logger?.error(`RoktManager: Error processing message '${message.methodName}': ${errorMessage}`);
303
+ this.completePendingPromise(message.messageId, Promise.reject(error));
304
+ }
305
+ });
299
306
  }
300
307
 
301
308
  private queueMessage(message: IRoktMessage): void {
302
- this.messageQueue.push(message);
309
+ this.messageQueue.set(message.messageId, message);
310
+ }
311
+
312
+ private deferredCall<T>(methodName: string, payload: any): Promise<T> {
313
+ return new Promise<T>((resolve, reject) => {
314
+ const messageId = `${methodName}_${generateUniqueId()}`;
315
+
316
+ this.queueMessage({
317
+ messageId,
318
+ methodName,
319
+ payload,
320
+ resolve,
321
+ reject,
322
+ });
323
+ });
324
+ }
325
+
326
+ private completePendingPromise(messageId: string | undefined, resultOrError: any): void {
327
+ if (!messageId || !this.messageQueue.has(messageId)) {
328
+ return;
329
+ }
330
+
331
+ const message = this.messageQueue.get(messageId)!;
332
+
333
+ if (message.resolve) {
334
+ Promise.resolve(resultOrError)
335
+ .then((result) => message.resolve!(result))
336
+ .catch((error) => message.reject!(error));
337
+ }
338
+
339
+ this.messageQueue.delete(messageId);
303
340
  }
304
341
  }