@mparticle/web-sdk 2.29.0 → 2.30.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.
- package/dist/mparticle.common.js +10 -13
- package/dist/mparticle.esm.js +10 -13
- package/dist/mparticle.js +111 -67
- package/package.json +1 -1
- package/src/aliasRequestApiClient.ts +1 -1
- package/src/identity-utils.ts +1 -28
- package/src/identity.js +1 -5
- package/src/identityApiClient.js +100 -82
- package/src/mp-instance.js +2 -2
- package/src/sdkToEventsApiConverter.ts +2 -2
- package/src/uploaders.ts +11 -3
package/dist/mparticle.common.js
CHANGED
|
@@ -154,7 +154,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
|
|
|
154
154
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
155
155
|
};
|
|
156
156
|
|
|
157
|
-
var version = "2.
|
|
157
|
+
var version = "2.30.0";
|
|
158
158
|
|
|
159
159
|
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
|
|
160
160
|
},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
|
|
@@ -426,7 +426,7 @@ var SDKIdentityTypeEnum;(function(a){a.other="other",a.customerId="customerid",a
|
|
|
426
426
|
|
|
427
427
|
function convertEvents(a,b,c){if(!a)return null;if(!b||1>b.length)return null;for(var d,e=c.Identity.getCurrentUser(),f=[],g=null,h=0,i=b;h<i.length;h++)if(d=i[h],d){g=d;var j=convertEvent(d);j&&f.push(j);}if(!g)return null;var k=null;// Add the consent state from either the Last Event or the user
|
|
428
428
|
isEmpty(g.ConsentState)?!isEmpty(e)&&(k=e.getConsentState()):k=g.ConsentState;var l={source_request_id:c._Helpers.generateUniqueId(),mpid:a,timestamp_unixtime_ms:new Date().getTime(),environment:g.Debug?dist.BatchEnvironmentEnum.development:dist.BatchEnvironmentEnum.production,events:f,mp_deviceid:g.DeviceId,sdk_version:g.SDKVersion,// TODO: Refactor this to read from _Store or a global config
|
|
429
|
-
application_info:{application_version:g.AppVersion,application_name:g.AppName,package:g.Package,sideloaded_kits_count:c._Store.sideloadedKitsCount},device_info:{platform:dist.DeviceInformationPlatformEnum.web,screen_width:window.screen.width,screen_height:window.screen.height},user_attributes:g.UserAttributes,user_identities:convertUserIdentities(g.UserIdentities),consent_state:convertConsentState(k),integration_attributes:g.IntegrationAttributes};return g.DataPlan&&g.DataPlan.PlanId&&(l.context={data_plan:{plan_id:g.DataPlan.PlanId,plan_version:g.DataPlan.PlanVersion||void 0}}),l}function convertConsentState(a){if(isEmpty(a))return null;var b={gdpr:convertGdprConsentState(a.getGDPRConsentState()),ccpa:convertCcpaConsentState(a.getCCPAConsentState())};return b}function convertGdprConsentState(a){if(!a)return null;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]={consented:a[c].Consented,hardware_id:a[c].HardwareId,document:a[c].ConsentDocument,timestamp_unixtime_ms:a[c].Timestamp,location:a[c].Location});return b}function convertCcpaConsentState(a){if(!a)return null;var b={data_sale_opt_out:{consented:a.Consented,hardware_id:a.HardwareId,document:a.ConsentDocument,timestamp_unixtime_ms:a.Timestamp,location:a.Location}};return b}function convertUserIdentities(a){if(!a||!a.length)return null;for(var b,c={},d=0,e=a;d<e.length;d++)switch(b=e[d],b.Type){case Types.IdentityType.CustomerId:c.customer_id=b.Identity;break;case Types.IdentityType.Email:c.email=b.Identity;break;case Types.IdentityType.Facebook:c.facebook=b.Identity;break;case Types.IdentityType.FacebookCustomAudienceId:c.facebook_custom_audience_id=b.Identity;break;case Types.IdentityType.Google:c.google=b.Identity;break;case Types.IdentityType.Microsoft:c.microsoft=b.Identity;break;case Types.IdentityType.Other:c.other=b.Identity;break;case Types.IdentityType.Other2:c.other_id_2=b.Identity;break;case Types.IdentityType.Other3:c.other_id_3=b.Identity;break;case Types.IdentityType.Other4:c.other_id_4=b.Identity;break;case Types.IdentityType.Other5:c.other_id_5=b.Identity;break;case Types.IdentityType.Other6:c.other_id_6=b.Identity;break;case Types.IdentityType.Other7:c.other_id_7=b.Identity;break;case Types.IdentityType.Other8:c.other_id_8=b.Identity;break;case Types.IdentityType.Other9:c.other_id_9=b.Identity;break;case Types.IdentityType.Other10:c.other_id_10=b.Identity;break;case Types.IdentityType.MobileNumber:c.mobile_number=b.Identity;break;case Types.IdentityType.PhoneNumber2:c.phone_number_2=b.Identity;break;case Types.IdentityType.PhoneNumber3:c.phone_number_3=b.Identity;break;}return c}function convertEvent(a){if(!a)return null;switch(a.EventDataType){case Types.MessageType.AppStateTransition:return convertAST(a);case Types.MessageType.Commerce:return convertCommerceEvent(a);case Types.MessageType.CrashReport:return convertCrashReportEvent(a);case Types.MessageType.OptOut:return convertOptOutEvent(a);case Types.MessageType.PageEvent:// Note: Media Events are also sent as PageEvents/CustomEvents
|
|
429
|
+
application_info:{application_version:g.AppVersion,application_name:g.AppName,package:g.Package,sideloaded_kits_count:c._Store.sideloadedKitsCount},device_info:{platform:dist.DeviceInformationPlatformEnum.web,screen_width:"undefined"==typeof window?0:window.screen.width,screen_height:"undefined"==typeof window?0:window.screen.height},user_attributes:g.UserAttributes,user_identities:convertUserIdentities(g.UserIdentities),consent_state:convertConsentState(k),integration_attributes:g.IntegrationAttributes};return g.DataPlan&&g.DataPlan.PlanId&&(l.context={data_plan:{plan_id:g.DataPlan.PlanId,plan_version:g.DataPlan.PlanVersion||void 0}}),l}function convertConsentState(a){if(isEmpty(a))return null;var b={gdpr:convertGdprConsentState(a.getGDPRConsentState()),ccpa:convertCcpaConsentState(a.getCCPAConsentState())};return b}function convertGdprConsentState(a){if(!a)return null;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]={consented:a[c].Consented,hardware_id:a[c].HardwareId,document:a[c].ConsentDocument,timestamp_unixtime_ms:a[c].Timestamp,location:a[c].Location});return b}function convertCcpaConsentState(a){if(!a)return null;var b={data_sale_opt_out:{consented:a.Consented,hardware_id:a.HardwareId,document:a.ConsentDocument,timestamp_unixtime_ms:a.Timestamp,location:a.Location}};return b}function convertUserIdentities(a){if(!a||!a.length)return null;for(var b,c={},d=0,e=a;d<e.length;d++)switch(b=e[d],b.Type){case Types.IdentityType.CustomerId:c.customer_id=b.Identity;break;case Types.IdentityType.Email:c.email=b.Identity;break;case Types.IdentityType.Facebook:c.facebook=b.Identity;break;case Types.IdentityType.FacebookCustomAudienceId:c.facebook_custom_audience_id=b.Identity;break;case Types.IdentityType.Google:c.google=b.Identity;break;case Types.IdentityType.Microsoft:c.microsoft=b.Identity;break;case Types.IdentityType.Other:c.other=b.Identity;break;case Types.IdentityType.Other2:c.other_id_2=b.Identity;break;case Types.IdentityType.Other3:c.other_id_3=b.Identity;break;case Types.IdentityType.Other4:c.other_id_4=b.Identity;break;case Types.IdentityType.Other5:c.other_id_5=b.Identity;break;case Types.IdentityType.Other6:c.other_id_6=b.Identity;break;case Types.IdentityType.Other7:c.other_id_7=b.Identity;break;case Types.IdentityType.Other8:c.other_id_8=b.Identity;break;case Types.IdentityType.Other9:c.other_id_9=b.Identity;break;case Types.IdentityType.Other10:c.other_id_10=b.Identity;break;case Types.IdentityType.MobileNumber:c.mobile_number=b.Identity;break;case Types.IdentityType.PhoneNumber2:c.phone_number_2=b.Identity;break;case Types.IdentityType.PhoneNumber3:c.phone_number_3=b.Identity;break;}return c}function convertEvent(a){if(!a)return null;switch(a.EventDataType){case Types.MessageType.AppStateTransition:return convertAST(a);case Types.MessageType.Commerce:return convertCommerceEvent(a);case Types.MessageType.CrashReport:return convertCrashReportEvent(a);case Types.MessageType.OptOut:return convertOptOutEvent(a);case Types.MessageType.PageEvent:// Note: Media Events are also sent as PageEvents/CustomEvents
|
|
430
430
|
return convertCustomEvent(a);case Types.MessageType.PageView:return convertPageViewEvent(a);case Types.MessageType.Profile://deprecated and not supported by the web SDK
|
|
431
431
|
return null;case Types.MessageType.SessionEnd:return convertSessionEndEvent(a);case Types.MessageType.SessionStart:return convertSessionStartEvent(a);case Types.MessageType.UserAttributeChange:return convertUserAttributeChangeEvent(a);case Types.MessageType.UserIdentityChange:return convertUserIdentityChangeEvent(a);}return null}function convertProductActionType(a){if(!a)return dist.ProductActionActionEnum.unknown;return a===SDKProductActionType.AddToCart?dist.ProductActionActionEnum.addToCart:a===SDKProductActionType.AddToWishlist?dist.ProductActionActionEnum.addToWishlist:a===SDKProductActionType.Checkout?dist.ProductActionActionEnum.checkout:a===SDKProductActionType.CheckoutOption?dist.ProductActionActionEnum.checkoutOption:a===SDKProductActionType.Click?dist.ProductActionActionEnum.click:a===SDKProductActionType.Purchase?dist.ProductActionActionEnum.purchase:a===SDKProductActionType.Refund?dist.ProductActionActionEnum.refund:a===SDKProductActionType.RemoveFromCart?dist.ProductActionActionEnum.removeFromCart:a===SDKProductActionType.RemoveFromWishlist?dist.ProductActionActionEnum.removeFromWishlist:a===SDKProductActionType.ViewDetail?dist.ProductActionActionEnum.viewDetail:dist.ProductActionActionEnum.unknown}function convertProductAction(a){if(!a.ProductAction)return null;var b={action:convertProductActionType(a.ProductAction.ProductActionType),checkout_step:a.ProductAction.CheckoutStep,checkout_options:a.ProductAction.CheckoutOptions,transaction_id:a.ProductAction.TransactionId,affiliation:a.ProductAction.Affiliation,total_amount:a.ProductAction.TotalAmount,tax_amount:a.ProductAction.TaxAmount,shipping_amount:a.ProductAction.ShippingAmount,coupon_code:a.ProductAction.CouponCode,products:convertProducts(a.ProductAction.ProductList)};return b}function convertProducts(a){if(!a||!a.length)return null;for(var b=[],c=0,d=a;c<d.length;c++){var e=d[c],f={id:e.Sku,name:e.Name,brand:e.Brand,category:e.Category,variant:e.Variant,total_product_amount:e.TotalAmount,position:e.Position,price:e.Price,quantity:e.Quantity,coupon_code:e.CouponCode,custom_attributes:e.Attributes};b.push(f);}return b}function convertPromotionAction(a){if(!a.PromotionAction)return null;var b={action:a.PromotionAction.PromotionActionType,promotions:convertPromotions(a.PromotionAction.PromotionList)};return b}function convertPromotions(a){if(!a||!a.length)return null;for(var b=[],c=0,d=a;c<d.length;c++){var e=d[c],f={id:e.Id,name:e.Name,creative:e.Creative,position:e.Position};b.push(f);}return b}function convertImpressions(a){if(!a.ProductImpressions)return null;for(var b=[],c=0,d=a.ProductImpressions;c<d.length;c++){var e=d[c],f={product_impression_list:e.ProductImpressionList,products:convertProducts(e.ProductList)};b.push(f);}return b}function convertShoppingCart(a){if(!a.ShoppingCart||!a.ShoppingCart.ProductList||!a.ShoppingCart.ProductList.length)return null;var b={products:convertProducts(a.ShoppingCart.ProductList)};return b}function convertCommerceEvent(a){var b=convertBaseEventData(a),c={custom_flags:a.CustomFlags,product_action:convertProductAction(a),promotion_action:convertPromotionAction(a),product_impressions:convertImpressions(a),shopping_cart:convertShoppingCart(a),currency_code:a.CurrencyCode};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.commerceEvent,data:c}}function convertCrashReportEvent(a){var b=convertBaseEventData(a),c={message:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.crashReport,data:c}}function convertAST(a){var b=convertBaseEventData(a),c={application_transition_type:dist.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum.applicationInitialized,is_first_run:a.IsFirstRun,is_upgrade:!1,launch_referral:a.LaunchReferral};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.applicationStateTransition,data:c}}function convertSessionEndEvent(a){var b=convertBaseEventData(a),c={session_duration_ms:a.SessionLength//note: External Events DTO does not support the session mpids array as of this time.
|
|
432
432
|
//spanning_mpids: sdkEvent.SessionMpids
|
|
@@ -445,10 +445,10 @@ var BaseVault=/** @class */function(){/**
|
|
|
445
445
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
446
446
|
var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.parse(a):null,this.logger.verbose("Retrieving item from Storage: ".concat(a)),this.contents},a.prototype.purge=function(){this.logger.verbose("Purging Storage"),this.contents=null,this.storageObject.removeItem(this._storageKey);},a}();var LocalStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.localStorage,c)||this}return __extends(b,a),b}(BaseVault);var SessionStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.sessionStorage,c)||this}return __extends(b,a),b}(BaseVault);
|
|
447
447
|
|
|
448
|
-
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body,a.method)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b,c){return void 0===c&&(c="post"),__awaiter(this,void 0,void 0,function(){var
|
|
448
|
+
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body,a.method,a.headers)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b,c,d){return void 0===c&&(c="post"),void 0===d&&(d={}),__awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(){return e=new XMLHttpRequest,[2/*return*/,new Promise(function(f,g){e.onreadystatechange=function(){4!==e.readyState||// Process the response
|
|
449
449
|
// We resolve all xhr responses whose ready state is 4 regardless of HTTP codes that may be errors (400+)
|
|
450
450
|
// because these are valid HTTP responses.
|
|
451
|
-
e
|
|
451
|
+
f(e);},e.onerror=function(){g(e);},e.open(c,a),Object.entries(d).forEach(function(a){var b=a[0],c=a[1];e.setRequestHeader(b,c);}),e.send(b);})]})})},b}(AsyncUploader);
|
|
452
452
|
|
|
453
453
|
/**
|
|
454
454
|
* BatchUploader contains all the logic to store/retrieve events and batches
|
|
@@ -1098,10 +1098,7 @@ Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store
|
|
|
1098
1098
|
|
|
1099
1099
|
function forwardingStatsUploader(a){function b(){var b=a._Forwarders.getForwarderStatsQueue(),c=a._Persistence.forwardingStatsBatches.uploadsTable,d=Date.now();for(var e in b.length&&(c[d]={uploading:!1,data:b},a._Forwarders.setForwarderStatsQueue([])),c)(function(b){if(c.hasOwnProperty(b)&&!1===c[b].uploading){var d=function(){4===e.readyState&&(200===e.status||202===e.status?(a.Logger.verbose("Successfully sent "+e.statusText+" from server"),delete c[b]):"4"===e.status.toString()[0]?429!==e.status&&delete c[b]:c[b].uploading=!1);},e=a._Helpers.createXHR(d),f=c[b].data;c[b].uploading=!0,a._APIClient.sendBatchForwardingStatsToServer(f,e);}})(e);}this.startForwardingStatsTimer=function(){mParticle._forwardingStatsTimer=setInterval(function(){b();},a._Store.SDKConfig.forwarderStatsTimeout);};}
|
|
1100
1100
|
|
|
1101
|
-
var _a=Constants.IdentityMethods,Identify$1=_a.Identify,Modify$2=_a.Modify,Login$1=_a.Login,Logout$1=_a.Logout
|
|
1102
|
-
// Temporary adapter to convert the XMLHttpRequest response to the IIdentityResponse interface
|
|
1103
|
-
var xhrIdentityResponseAdapter=function(a){return a.hasOwnProperty("expireTimestamp")?a:{status:a.status,// Sometimes responseText can be an empty string, such as a 404 response
|
|
1104
|
-
responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber((null===a||void 0===a?void 0:a.getResponseHeader(CACHE_HEADER))||""),expireTimestamp:0}};var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
1101
|
+
var _a=Constants.IdentityMethods,Identify$1=_a.Identify,Modify$2=_a.Modify,Login$1=_a.Login,Logout$1=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
1105
1102
|
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
1106
1103
|
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$1||a===Identify$1?cacheIdentityRequest(a,b,f,c,d):a===Modify$2||a===Logout$1?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
|
|
1107
1104
|
// we sort the identities based on their enum.
|
|
@@ -1300,8 +1297,8 @@ return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audie
|
|
|
1300
1297
|
* @method getCartProducts
|
|
1301
1298
|
* @return {Array} array of cart products
|
|
1302
1299
|
* @deprecated
|
|
1303
|
-
*/getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,a,d,o,g,l){var u,p,y,c=t.Identity.getUser(i),I=c?c.getMPID():null,_=c?c.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,S,b;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(S=p)||void 0===S?void 0:S.is_logged_in)||!1,hasMPIDChanged(c,p)&&(t._Store.mpid=p.mpid,c&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){
|
|
1304
|
-
n.sendUserIdentityChangeEvent(
|
|
1300
|
+
*/getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,a,d,o,g,l){var u,p,y,c=t.Identity.getUser(i),I=c?c.getMPID():null,_=c?c.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,S,b;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(S=p)||void 0===S?void 0:S.is_logged_in)||!1,hasMPIDChanged(c,p)&&(t._Store.mpid=p.mpid,c&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){s(CacheIdentity)&&cacheOrClearIdCache(o,g,n.idCache,r,l);var A=n.IdentityAPI.getUser(p.mpid),P=A?A.getUserIdentities().userIdentities:{};o===Modify$1?(v=t._Identity.IdentityRequest.combineUserIdentities(_,d.userIdentities),t._Store.setUserIdentities(i,v)):(o===Identify&&c&&p.mpid===I&&t._Persistence.setFirstSeenTime(p.mpid),t._Store.addMpidToSessionHistory(p.mpid,i),t._CookieSyncManager.attemptCookieSync(i,p.mpid,u),t._Persistence.swapCurrentUser(i,p.mpid,t._Store.currentSessionMPIDs),d&&!isEmpty(d.userIdentities)&&(v=n.IdentityRequest.combineUserIdentities(P,d.userIdentities)),t._Store.setUserIdentities(p.mpid,v),t._Persistence.update(),t._Store.syncPersistenceData(),t._Persistence.findPrevCookiesBasedOnUI(d),t._Store.context=p.context||t._Store.context),y=t.Identity.getCurrentUser(),tryOnUserAlias(c,y,d,t.Logger);var U=t._Persistence.getPersistence();y&&(t._Persistence.storeDataInMemory(U,y.getMPID()),n.reinitForwardersOnUserChange(c,y),n.setForwarderCallbacks(y,o));var C=getNewIdentitiesByName(v),k=o===Modify$1?_:P;// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1301
|
+
n.sendUserIdentityChangeEvent(C,o,p.mpid,k);}if(a){var f=0===r.status?HTTPCodes$3.noHttpCoverage:r.status;t._Helpers.invokeCallback(a,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
|
|
1305
1302
|
t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(b=t._APIClient)||void 0===b||b.processQueuedEvents();}catch(s){a&&t._Helpers.invokeCallback(a,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1306
1303
|
{// https://go.mparticle.com/work/SQDSDKS-6354
|
|
1307
1304
|
var a=this.IdentityAPI.getUser(s);for(var d in e)// Verifies a change actually happened
|
|
@@ -1404,8 +1401,7 @@ return [2/*return*/,b]}})})};}
|
|
|
1404
1401
|
|
|
1405
1402
|
var HTTPCodes$2=Constants.HTTPCodes,Messages$2=Constants.Messages;function sendAliasRequest(a,b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,t;return __generator(this,function(u){switch(u.label){case 0:d=a.Logger,e=d.verbose,f=d.error,g=a._Helpers.invokeAliasCallback,h=a._Store.SDKConfig.aliasUrl,i=a._Store.devToken,e(Messages$2.InformationMessages.SendAliasHttp),j="https://".concat(h).concat(i,"/Alias"),k=window.fetch?new FetchUploader(j):new XHRUploader(j),l={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},u.label=1;case 1:return u.trys.push([1,9,,10]),[4/*yield*/,k.upload(l)];case 2:if(m=u.sent(),n=void 0,o=void 0,!m.json)return [3/*break*/,7];u.label=3;case 3:return u.trys.push([3,5,,6]),[4/*yield*/,m.json()];case 4:return o=u.sent(),[3/*break*/,6];case 5:return u.sent(),e("The request has no response body"),[3/*break*/,6];case 6:return [3/*break*/,8];case 7:q=m,o=q.responseText?JSON.parse(q.responseText):"",u.label=8;case 8:switch(r=void 0,m.status){case HTTP_OK:case HTTP_ACCEPTED:n="Successfully sent forwarding stats to mParticle Servers";break;default:(null===o||void 0===o?void 0:o.message)&&(r=o.message),n="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+m.status;}return e(n),g(c,m.status,r),[3/*break*/,10];case 9:return s=u.sent(),t=s,f("Error sending alias request to mParticle servers. "+t),g(c,HTTPCodes$2.noHttpCoverage,t.message),[3/*break*/,10];case 10:return [2/*return*/]}})})}
|
|
1406
1403
|
|
|
1407
|
-
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,Modify=Constants.IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=/*#__PURE__*/function(){var b=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function d(b,c){return _regeneratorRuntime.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.next=2,sendAliasRequest(a,b,c);case 2:case"end":return d.stop()}},d)}));return function(){return b.apply(this,arguments)}}(),this.sendIdentityRequest=function(b,c,d,e,f,g,h){var
|
|
1408
|
-
var b=xhrIdentityResponseAdapter(i);f(b,j,d,e,c,h,!1);}}),i)try{a._Store.identityCallInFlight?a._Helpers.invokeCallback(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"):(j=g||null,c===Modify?i.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl)+g+"/"+c):i.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl)+c),i.setRequestHeader("Content-Type","application/json"),i.setRequestHeader("x-mp-key",a._Store.devToken),a._Store.identityCallInFlight=!0,i.send(JSON.stringify(b)));}catch(b){a._Store.identityCallInFlight=!1,a._Helpers.invokeCallback(d,HTTPCodes$1.noHttpCoverage,b),a.Logger.error("Error sending identity request to servers with status code "+i.status+" - "+b);}};}
|
|
1404
|
+
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,Modify=Constants.IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=/*#__PURE__*/function(){var b=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function d(b,c){return _regeneratorRuntime.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.next=2,sendAliasRequest(a,b,c);case 2:case"end":return d.stop()}},d)}));return function(){return b.apply(this,arguments)}}(),this.sendIdentityRequest=/*#__PURE__*/function(){var b=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function i(b,c,d,e,f,g,h){var j,k,l,m,n,o,p,q,r,s,t;return _regeneratorRuntime.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(j=a.Logger,k=j.verbose,l=j.error,m=a._Helpers.invokeCallback,k(Messages$1.InformationMessages.SendIdentityBegin),b){i.next=6;break}return l(Messages$1.ErrorMessages.APIRequestEmpty),i.abrupt("return");case 6:if(k(Messages$1.InformationMessages.SendIdentityHttp),!a._Store.identityCallInFlight){i.next=10;break}return m(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),i.abrupt("return");case 10:return n=g||null,o=this.getUploadUrl(c,g),p=window.fetch?new FetchUploader(o):new XHRUploader(o),q={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},i.prev=14,a._Store.identityCallInFlight=!0,i.next=18,p.upload(q);case 18:if(r=i.sent,!r.json){i.next=26;break}return i.next=22,r.json();case 22:t=i.sent,s=this.getIdentityResponseFromFetch(r,t),i.next=27;break;case 26:s=this.getIdentityResponseFromXHR(r);case 27:k("Received Identity Response from server: "+JSON.stringify(s.responseText)),f(s,n,d,e,c,h,!1),i.next=36;break;case 31:i.prev=31,i.t0=i["catch"](14),a._Store.identityCallInFlight=!1,m(d,HTTPCodes$1.noHttpCoverage,i.t0),l("Error sending identity request to servers - "+i.t0);case 36:case"end":return i.stop()}},i,this,[[14,31]])}));return function(){return b.apply(this,arguments)}}(),this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
|
|
1409
1405
|
|
|
1410
1406
|
// The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
|
|
1411
1407
|
// - version is always this prefix: fb
|
|
@@ -1767,7 +1763,8 @@ c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}function createKitBlocker(a,b){va
|
|
|
1767
1763
|
// since we will need this for the current implementation of user persistence
|
|
1768
1764
|
// TODO: Refactor this when we refactor User Identity Persistence
|
|
1769
1765
|
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function processPreloadedItem(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
|
|
1770
|
-
if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){
|
|
1766
|
+
if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){// https://go.mparticle.com/work/SQDSDKS-6835
|
|
1767
|
+
return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
|
|
1771
1768
|
|
|
1772
1769
|
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1773
1770
|
var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
|
package/dist/mparticle.esm.js
CHANGED
|
@@ -154,7 +154,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
|
|
|
154
154
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
155
155
|
};
|
|
156
156
|
|
|
157
|
-
var version = "2.
|
|
157
|
+
var version = "2.30.0";
|
|
158
158
|
|
|
159
159
|
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
|
|
160
160
|
},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
|
|
@@ -426,7 +426,7 @@ var SDKIdentityTypeEnum;(function(a){a.other="other",a.customerId="customerid",a
|
|
|
426
426
|
|
|
427
427
|
function convertEvents(a,b,c){if(!a)return null;if(!b||1>b.length)return null;for(var d,e=c.Identity.getCurrentUser(),f=[],g=null,h=0,i=b;h<i.length;h++)if(d=i[h],d){g=d;var j=convertEvent(d);j&&f.push(j);}if(!g)return null;var k=null;// Add the consent state from either the Last Event or the user
|
|
428
428
|
isEmpty(g.ConsentState)?!isEmpty(e)&&(k=e.getConsentState()):k=g.ConsentState;var l={source_request_id:c._Helpers.generateUniqueId(),mpid:a,timestamp_unixtime_ms:new Date().getTime(),environment:g.Debug?dist.BatchEnvironmentEnum.development:dist.BatchEnvironmentEnum.production,events:f,mp_deviceid:g.DeviceId,sdk_version:g.SDKVersion,// TODO: Refactor this to read from _Store or a global config
|
|
429
|
-
application_info:{application_version:g.AppVersion,application_name:g.AppName,package:g.Package,sideloaded_kits_count:c._Store.sideloadedKitsCount},device_info:{platform:dist.DeviceInformationPlatformEnum.web,screen_width:window.screen.width,screen_height:window.screen.height},user_attributes:g.UserAttributes,user_identities:convertUserIdentities(g.UserIdentities),consent_state:convertConsentState(k),integration_attributes:g.IntegrationAttributes};return g.DataPlan&&g.DataPlan.PlanId&&(l.context={data_plan:{plan_id:g.DataPlan.PlanId,plan_version:g.DataPlan.PlanVersion||void 0}}),l}function convertConsentState(a){if(isEmpty(a))return null;var b={gdpr:convertGdprConsentState(a.getGDPRConsentState()),ccpa:convertCcpaConsentState(a.getCCPAConsentState())};return b}function convertGdprConsentState(a){if(!a)return null;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]={consented:a[c].Consented,hardware_id:a[c].HardwareId,document:a[c].ConsentDocument,timestamp_unixtime_ms:a[c].Timestamp,location:a[c].Location});return b}function convertCcpaConsentState(a){if(!a)return null;var b={data_sale_opt_out:{consented:a.Consented,hardware_id:a.HardwareId,document:a.ConsentDocument,timestamp_unixtime_ms:a.Timestamp,location:a.Location}};return b}function convertUserIdentities(a){if(!a||!a.length)return null;for(var b,c={},d=0,e=a;d<e.length;d++)switch(b=e[d],b.Type){case Types.IdentityType.CustomerId:c.customer_id=b.Identity;break;case Types.IdentityType.Email:c.email=b.Identity;break;case Types.IdentityType.Facebook:c.facebook=b.Identity;break;case Types.IdentityType.FacebookCustomAudienceId:c.facebook_custom_audience_id=b.Identity;break;case Types.IdentityType.Google:c.google=b.Identity;break;case Types.IdentityType.Microsoft:c.microsoft=b.Identity;break;case Types.IdentityType.Other:c.other=b.Identity;break;case Types.IdentityType.Other2:c.other_id_2=b.Identity;break;case Types.IdentityType.Other3:c.other_id_3=b.Identity;break;case Types.IdentityType.Other4:c.other_id_4=b.Identity;break;case Types.IdentityType.Other5:c.other_id_5=b.Identity;break;case Types.IdentityType.Other6:c.other_id_6=b.Identity;break;case Types.IdentityType.Other7:c.other_id_7=b.Identity;break;case Types.IdentityType.Other8:c.other_id_8=b.Identity;break;case Types.IdentityType.Other9:c.other_id_9=b.Identity;break;case Types.IdentityType.Other10:c.other_id_10=b.Identity;break;case Types.IdentityType.MobileNumber:c.mobile_number=b.Identity;break;case Types.IdentityType.PhoneNumber2:c.phone_number_2=b.Identity;break;case Types.IdentityType.PhoneNumber3:c.phone_number_3=b.Identity;break;}return c}function convertEvent(a){if(!a)return null;switch(a.EventDataType){case Types.MessageType.AppStateTransition:return convertAST(a);case Types.MessageType.Commerce:return convertCommerceEvent(a);case Types.MessageType.CrashReport:return convertCrashReportEvent(a);case Types.MessageType.OptOut:return convertOptOutEvent(a);case Types.MessageType.PageEvent:// Note: Media Events are also sent as PageEvents/CustomEvents
|
|
429
|
+
application_info:{application_version:g.AppVersion,application_name:g.AppName,package:g.Package,sideloaded_kits_count:c._Store.sideloadedKitsCount},device_info:{platform:dist.DeviceInformationPlatformEnum.web,screen_width:"undefined"==typeof window?0:window.screen.width,screen_height:"undefined"==typeof window?0:window.screen.height},user_attributes:g.UserAttributes,user_identities:convertUserIdentities(g.UserIdentities),consent_state:convertConsentState(k),integration_attributes:g.IntegrationAttributes};return g.DataPlan&&g.DataPlan.PlanId&&(l.context={data_plan:{plan_id:g.DataPlan.PlanId,plan_version:g.DataPlan.PlanVersion||void 0}}),l}function convertConsentState(a){if(isEmpty(a))return null;var b={gdpr:convertGdprConsentState(a.getGDPRConsentState()),ccpa:convertCcpaConsentState(a.getCCPAConsentState())};return b}function convertGdprConsentState(a){if(!a)return null;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]={consented:a[c].Consented,hardware_id:a[c].HardwareId,document:a[c].ConsentDocument,timestamp_unixtime_ms:a[c].Timestamp,location:a[c].Location});return b}function convertCcpaConsentState(a){if(!a)return null;var b={data_sale_opt_out:{consented:a.Consented,hardware_id:a.HardwareId,document:a.ConsentDocument,timestamp_unixtime_ms:a.Timestamp,location:a.Location}};return b}function convertUserIdentities(a){if(!a||!a.length)return null;for(var b,c={},d=0,e=a;d<e.length;d++)switch(b=e[d],b.Type){case Types.IdentityType.CustomerId:c.customer_id=b.Identity;break;case Types.IdentityType.Email:c.email=b.Identity;break;case Types.IdentityType.Facebook:c.facebook=b.Identity;break;case Types.IdentityType.FacebookCustomAudienceId:c.facebook_custom_audience_id=b.Identity;break;case Types.IdentityType.Google:c.google=b.Identity;break;case Types.IdentityType.Microsoft:c.microsoft=b.Identity;break;case Types.IdentityType.Other:c.other=b.Identity;break;case Types.IdentityType.Other2:c.other_id_2=b.Identity;break;case Types.IdentityType.Other3:c.other_id_3=b.Identity;break;case Types.IdentityType.Other4:c.other_id_4=b.Identity;break;case Types.IdentityType.Other5:c.other_id_5=b.Identity;break;case Types.IdentityType.Other6:c.other_id_6=b.Identity;break;case Types.IdentityType.Other7:c.other_id_7=b.Identity;break;case Types.IdentityType.Other8:c.other_id_8=b.Identity;break;case Types.IdentityType.Other9:c.other_id_9=b.Identity;break;case Types.IdentityType.Other10:c.other_id_10=b.Identity;break;case Types.IdentityType.MobileNumber:c.mobile_number=b.Identity;break;case Types.IdentityType.PhoneNumber2:c.phone_number_2=b.Identity;break;case Types.IdentityType.PhoneNumber3:c.phone_number_3=b.Identity;break;}return c}function convertEvent(a){if(!a)return null;switch(a.EventDataType){case Types.MessageType.AppStateTransition:return convertAST(a);case Types.MessageType.Commerce:return convertCommerceEvent(a);case Types.MessageType.CrashReport:return convertCrashReportEvent(a);case Types.MessageType.OptOut:return convertOptOutEvent(a);case Types.MessageType.PageEvent:// Note: Media Events are also sent as PageEvents/CustomEvents
|
|
430
430
|
return convertCustomEvent(a);case Types.MessageType.PageView:return convertPageViewEvent(a);case Types.MessageType.Profile://deprecated and not supported by the web SDK
|
|
431
431
|
return null;case Types.MessageType.SessionEnd:return convertSessionEndEvent(a);case Types.MessageType.SessionStart:return convertSessionStartEvent(a);case Types.MessageType.UserAttributeChange:return convertUserAttributeChangeEvent(a);case Types.MessageType.UserIdentityChange:return convertUserIdentityChangeEvent(a);}return null}function convertProductActionType(a){if(!a)return dist.ProductActionActionEnum.unknown;return a===SDKProductActionType.AddToCart?dist.ProductActionActionEnum.addToCart:a===SDKProductActionType.AddToWishlist?dist.ProductActionActionEnum.addToWishlist:a===SDKProductActionType.Checkout?dist.ProductActionActionEnum.checkout:a===SDKProductActionType.CheckoutOption?dist.ProductActionActionEnum.checkoutOption:a===SDKProductActionType.Click?dist.ProductActionActionEnum.click:a===SDKProductActionType.Purchase?dist.ProductActionActionEnum.purchase:a===SDKProductActionType.Refund?dist.ProductActionActionEnum.refund:a===SDKProductActionType.RemoveFromCart?dist.ProductActionActionEnum.removeFromCart:a===SDKProductActionType.RemoveFromWishlist?dist.ProductActionActionEnum.removeFromWishlist:a===SDKProductActionType.ViewDetail?dist.ProductActionActionEnum.viewDetail:dist.ProductActionActionEnum.unknown}function convertProductAction(a){if(!a.ProductAction)return null;var b={action:convertProductActionType(a.ProductAction.ProductActionType),checkout_step:a.ProductAction.CheckoutStep,checkout_options:a.ProductAction.CheckoutOptions,transaction_id:a.ProductAction.TransactionId,affiliation:a.ProductAction.Affiliation,total_amount:a.ProductAction.TotalAmount,tax_amount:a.ProductAction.TaxAmount,shipping_amount:a.ProductAction.ShippingAmount,coupon_code:a.ProductAction.CouponCode,products:convertProducts(a.ProductAction.ProductList)};return b}function convertProducts(a){if(!a||!a.length)return null;for(var b=[],c=0,d=a;c<d.length;c++){var e=d[c],f={id:e.Sku,name:e.Name,brand:e.Brand,category:e.Category,variant:e.Variant,total_product_amount:e.TotalAmount,position:e.Position,price:e.Price,quantity:e.Quantity,coupon_code:e.CouponCode,custom_attributes:e.Attributes};b.push(f);}return b}function convertPromotionAction(a){if(!a.PromotionAction)return null;var b={action:a.PromotionAction.PromotionActionType,promotions:convertPromotions(a.PromotionAction.PromotionList)};return b}function convertPromotions(a){if(!a||!a.length)return null;for(var b=[],c=0,d=a;c<d.length;c++){var e=d[c],f={id:e.Id,name:e.Name,creative:e.Creative,position:e.Position};b.push(f);}return b}function convertImpressions(a){if(!a.ProductImpressions)return null;for(var b=[],c=0,d=a.ProductImpressions;c<d.length;c++){var e=d[c],f={product_impression_list:e.ProductImpressionList,products:convertProducts(e.ProductList)};b.push(f);}return b}function convertShoppingCart(a){if(!a.ShoppingCart||!a.ShoppingCart.ProductList||!a.ShoppingCart.ProductList.length)return null;var b={products:convertProducts(a.ShoppingCart.ProductList)};return b}function convertCommerceEvent(a){var b=convertBaseEventData(a),c={custom_flags:a.CustomFlags,product_action:convertProductAction(a),promotion_action:convertPromotionAction(a),product_impressions:convertImpressions(a),shopping_cart:convertShoppingCart(a),currency_code:a.CurrencyCode};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.commerceEvent,data:c}}function convertCrashReportEvent(a){var b=convertBaseEventData(a),c={message:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.crashReport,data:c}}function convertAST(a){var b=convertBaseEventData(a),c={application_transition_type:dist.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum.applicationInitialized,is_first_run:a.IsFirstRun,is_upgrade:!1,launch_referral:a.LaunchReferral};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.applicationStateTransition,data:c}}function convertSessionEndEvent(a){var b=convertBaseEventData(a),c={session_duration_ms:a.SessionLength//note: External Events DTO does not support the session mpids array as of this time.
|
|
432
432
|
//spanning_mpids: sdkEvent.SessionMpids
|
|
@@ -445,10 +445,10 @@ var BaseVault=/** @class */function(){/**
|
|
|
445
445
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
446
446
|
var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.parse(a):null,this.logger.verbose("Retrieving item from Storage: ".concat(a)),this.contents},a.prototype.purge=function(){this.logger.verbose("Purging Storage"),this.contents=null,this.storageObject.removeItem(this._storageKey);},a}();var LocalStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.localStorage,c)||this}return __extends(b,a),b}(BaseVault);var SessionStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.sessionStorage,c)||this}return __extends(b,a),b}(BaseVault);
|
|
447
447
|
|
|
448
|
-
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body,a.method)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b,c){return void 0===c&&(c="post"),__awaiter(this,void 0,void 0,function(){var
|
|
448
|
+
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body,a.method,a.headers)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b,c,d){return void 0===c&&(c="post"),void 0===d&&(d={}),__awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(){return e=new XMLHttpRequest,[2/*return*/,new Promise(function(f,g){e.onreadystatechange=function(){4!==e.readyState||// Process the response
|
|
449
449
|
// We resolve all xhr responses whose ready state is 4 regardless of HTTP codes that may be errors (400+)
|
|
450
450
|
// because these are valid HTTP responses.
|
|
451
|
-
e
|
|
451
|
+
f(e);},e.onerror=function(){g(e);},e.open(c,a),Object.entries(d).forEach(function(a){var b=a[0],c=a[1];e.setRequestHeader(b,c);}),e.send(b);})]})})},b}(AsyncUploader);
|
|
452
452
|
|
|
453
453
|
/**
|
|
454
454
|
* BatchUploader contains all the logic to store/retrieve events and batches
|
|
@@ -1098,10 +1098,7 @@ Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store
|
|
|
1098
1098
|
|
|
1099
1099
|
function forwardingStatsUploader(a){function b(){var b=a._Forwarders.getForwarderStatsQueue(),c=a._Persistence.forwardingStatsBatches.uploadsTable,d=Date.now();for(var e in b.length&&(c[d]={uploading:!1,data:b},a._Forwarders.setForwarderStatsQueue([])),c)(function(b){if(c.hasOwnProperty(b)&&!1===c[b].uploading){var d=function(){4===e.readyState&&(200===e.status||202===e.status?(a.Logger.verbose("Successfully sent "+e.statusText+" from server"),delete c[b]):"4"===e.status.toString()[0]?429!==e.status&&delete c[b]:c[b].uploading=!1);},e=a._Helpers.createXHR(d),f=c[b].data;c[b].uploading=!0,a._APIClient.sendBatchForwardingStatsToServer(f,e);}})(e);}this.startForwardingStatsTimer=function(){mParticle._forwardingStatsTimer=setInterval(function(){b();},a._Store.SDKConfig.forwarderStatsTimeout);};}
|
|
1100
1100
|
|
|
1101
|
-
var _a=Constants.IdentityMethods,Identify$1=_a.Identify,Modify$2=_a.Modify,Login$1=_a.Login,Logout$1=_a.Logout
|
|
1102
|
-
// Temporary adapter to convert the XMLHttpRequest response to the IIdentityResponse interface
|
|
1103
|
-
var xhrIdentityResponseAdapter=function(a){return a.hasOwnProperty("expireTimestamp")?a:{status:a.status,// Sometimes responseText can be an empty string, such as a 404 response
|
|
1104
|
-
responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber((null===a||void 0===a?void 0:a.getResponseHeader(CACHE_HEADER))||""),expireTimestamp:0}};var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
1101
|
+
var _a=Constants.IdentityMethods,Identify$1=_a.Identify,Modify$2=_a.Modify,Login$1=_a.Login,Logout$1=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
1105
1102
|
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
1106
1103
|
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$1||a===Identify$1?cacheIdentityRequest(a,b,f,c,d):a===Modify$2||a===Logout$1?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
|
|
1107
1104
|
// we sort the identities based on their enum.
|
|
@@ -1300,8 +1297,8 @@ return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audie
|
|
|
1300
1297
|
* @method getCartProducts
|
|
1301
1298
|
* @return {Array} array of cart products
|
|
1302
1299
|
* @deprecated
|
|
1303
|
-
*/getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,a,d,o,g,l){var u,p,y,c=t.Identity.getUser(i),I=c?c.getMPID():null,_=c?c.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,S,b;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(S=p)||void 0===S?void 0:S.is_logged_in)||!1,hasMPIDChanged(c,p)&&(t._Store.mpid=p.mpid,c&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){
|
|
1304
|
-
n.sendUserIdentityChangeEvent(
|
|
1300
|
+
*/getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,a,d,o,g,l){var u,p,y,c=t.Identity.getUser(i),I=c?c.getMPID():null,_=c?c.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,S,b;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(S=p)||void 0===S?void 0:S.is_logged_in)||!1,hasMPIDChanged(c,p)&&(t._Store.mpid=p.mpid,c&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){s(CacheIdentity)&&cacheOrClearIdCache(o,g,n.idCache,r,l);var A=n.IdentityAPI.getUser(p.mpid),P=A?A.getUserIdentities().userIdentities:{};o===Modify$1?(v=t._Identity.IdentityRequest.combineUserIdentities(_,d.userIdentities),t._Store.setUserIdentities(i,v)):(o===Identify&&c&&p.mpid===I&&t._Persistence.setFirstSeenTime(p.mpid),t._Store.addMpidToSessionHistory(p.mpid,i),t._CookieSyncManager.attemptCookieSync(i,p.mpid,u),t._Persistence.swapCurrentUser(i,p.mpid,t._Store.currentSessionMPIDs),d&&!isEmpty(d.userIdentities)&&(v=n.IdentityRequest.combineUserIdentities(P,d.userIdentities)),t._Store.setUserIdentities(p.mpid,v),t._Persistence.update(),t._Store.syncPersistenceData(),t._Persistence.findPrevCookiesBasedOnUI(d),t._Store.context=p.context||t._Store.context),y=t.Identity.getCurrentUser(),tryOnUserAlias(c,y,d,t.Logger);var U=t._Persistence.getPersistence();y&&(t._Persistence.storeDataInMemory(U,y.getMPID()),n.reinitForwardersOnUserChange(c,y),n.setForwarderCallbacks(y,o));var C=getNewIdentitiesByName(v),k=o===Modify$1?_:P;// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1301
|
+
n.sendUserIdentityChangeEvent(C,o,p.mpid,k);}if(a){var f=0===r.status?HTTPCodes$3.noHttpCoverage:r.status;t._Helpers.invokeCallback(a,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
|
|
1305
1302
|
t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(b=t._APIClient)||void 0===b||b.processQueuedEvents();}catch(s){a&&t._Helpers.invokeCallback(a,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
|
|
1306
1303
|
{// https://go.mparticle.com/work/SQDSDKS-6354
|
|
1307
1304
|
var a=this.IdentityAPI.getUser(s);for(var d in e)// Verifies a change actually happened
|
|
@@ -1404,8 +1401,7 @@ return [2/*return*/,b]}})})};}
|
|
|
1404
1401
|
|
|
1405
1402
|
var HTTPCodes$2=Constants.HTTPCodes,Messages$2=Constants.Messages;function sendAliasRequest(a,b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,t;return __generator(this,function(u){switch(u.label){case 0:d=a.Logger,e=d.verbose,f=d.error,g=a._Helpers.invokeAliasCallback,h=a._Store.SDKConfig.aliasUrl,i=a._Store.devToken,e(Messages$2.InformationMessages.SendAliasHttp),j="https://".concat(h).concat(i,"/Alias"),k=window.fetch?new FetchUploader(j):new XHRUploader(j),l={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},u.label=1;case 1:return u.trys.push([1,9,,10]),[4/*yield*/,k.upload(l)];case 2:if(m=u.sent(),n=void 0,o=void 0,!m.json)return [3/*break*/,7];u.label=3;case 3:return u.trys.push([3,5,,6]),[4/*yield*/,m.json()];case 4:return o=u.sent(),[3/*break*/,6];case 5:return u.sent(),e("The request has no response body"),[3/*break*/,6];case 6:return [3/*break*/,8];case 7:q=m,o=q.responseText?JSON.parse(q.responseText):"",u.label=8;case 8:switch(r=void 0,m.status){case HTTP_OK:case HTTP_ACCEPTED:n="Successfully sent forwarding stats to mParticle Servers";break;default:(null===o||void 0===o?void 0:o.message)&&(r=o.message),n="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+m.status;}return e(n),g(c,m.status,r),[3/*break*/,10];case 9:return s=u.sent(),t=s,f("Error sending alias request to mParticle servers. "+t),g(c,HTTPCodes$2.noHttpCoverage,t.message),[3/*break*/,10];case 10:return [2/*return*/]}})})}
|
|
1406
1403
|
|
|
1407
|
-
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,Modify=Constants.IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=/*#__PURE__*/function(){var b=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function d(b,c){return _regeneratorRuntime.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.next=2,sendAliasRequest(a,b,c);case 2:case"end":return d.stop()}},d)}));return function(){return b.apply(this,arguments)}}(),this.sendIdentityRequest=function(b,c,d,e,f,g,h){var
|
|
1408
|
-
var b=xhrIdentityResponseAdapter(i);f(b,j,d,e,c,h,!1);}}),i)try{a._Store.identityCallInFlight?a._Helpers.invokeCallback(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"):(j=g||null,c===Modify?i.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl)+g+"/"+c):i.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl)+c),i.setRequestHeader("Content-Type","application/json"),i.setRequestHeader("x-mp-key",a._Store.devToken),a._Store.identityCallInFlight=!0,i.send(JSON.stringify(b)));}catch(b){a._Store.identityCallInFlight=!1,a._Helpers.invokeCallback(d,HTTPCodes$1.noHttpCoverage,b),a.Logger.error("Error sending identity request to servers with status code "+i.status+" - "+b);}};}
|
|
1404
|
+
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,Modify=Constants.IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=/*#__PURE__*/function(){var b=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function d(b,c){return _regeneratorRuntime.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.next=2,sendAliasRequest(a,b,c);case 2:case"end":return d.stop()}},d)}));return function(){return b.apply(this,arguments)}}(),this.sendIdentityRequest=/*#__PURE__*/function(){var b=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function i(b,c,d,e,f,g,h){var j,k,l,m,n,o,p,q,r,s,t;return _regeneratorRuntime.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(j=a.Logger,k=j.verbose,l=j.error,m=a._Helpers.invokeCallback,k(Messages$1.InformationMessages.SendIdentityBegin),b){i.next=6;break}return l(Messages$1.ErrorMessages.APIRequestEmpty),i.abrupt("return");case 6:if(k(Messages$1.InformationMessages.SendIdentityHttp),!a._Store.identityCallInFlight){i.next=10;break}return m(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),i.abrupt("return");case 10:return n=g||null,o=this.getUploadUrl(c,g),p=window.fetch?new FetchUploader(o):new XHRUploader(o),q={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},i.prev=14,a._Store.identityCallInFlight=!0,i.next=18,p.upload(q);case 18:if(r=i.sent,!r.json){i.next=26;break}return i.next=22,r.json();case 22:t=i.sent,s=this.getIdentityResponseFromFetch(r,t),i.next=27;break;case 26:s=this.getIdentityResponseFromXHR(r);case 27:k("Received Identity Response from server: "+JSON.stringify(s.responseText)),f(s,n,d,e,c,h,!1),i.next=36;break;case 31:i.prev=31,i.t0=i["catch"](14),a._Store.identityCallInFlight=!1,m(d,HTTPCodes$1.noHttpCoverage,i.t0),l("Error sending identity request to servers - "+i.t0);case 36:case"end":return i.stop()}},i,this,[[14,31]])}));return function(){return b.apply(this,arguments)}}(),this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
|
|
1409
1405
|
|
|
1410
1406
|
// The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
|
|
1411
1407
|
// - version is always this prefix: fb
|
|
@@ -1767,7 +1763,8 @@ c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}function createKitBlocker(a,b){va
|
|
|
1767
1763
|
// since we will need this for the current implementation of user persistence
|
|
1768
1764
|
// TODO: Refactor this when we refactor User Identity Persistence
|
|
1769
1765
|
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function processPreloadedItem(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
|
|
1770
|
-
if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){
|
|
1766
|
+
if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){// https://go.mparticle.com/work/SQDSDKS-6835
|
|
1767
|
+
return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
|
|
1771
1768
|
|
|
1772
1769
|
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1773
1770
|
var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
|
package/dist/mparticle.js
CHANGED
|
@@ -393,7 +393,7 @@ var mParticle = (function () {
|
|
|
393
393
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
394
394
|
};
|
|
395
395
|
|
|
396
|
-
var version = "2.
|
|
396
|
+
var version = "2.30.0";
|
|
397
397
|
|
|
398
398
|
var Constants = {
|
|
399
399
|
sdkVersion: version,
|
|
@@ -1542,8 +1542,8 @@ var mParticle = (function () {
|
|
|
1542
1542
|
},
|
|
1543
1543
|
device_info: {
|
|
1544
1544
|
platform: dist.DeviceInformationPlatformEnum.web,
|
|
1545
|
-
screen_width: window.screen.width,
|
|
1546
|
-
screen_height: window.screen.height
|
|
1545
|
+
screen_width: typeof window !== 'undefined' ? window.screen.width : 0,
|
|
1546
|
+
screen_height: typeof window !== 'undefined' ? window.screen.height : 0
|
|
1547
1547
|
},
|
|
1548
1548
|
user_attributes: lastEvent.UserAttributes,
|
|
1549
1549
|
user_identities: convertUserIdentities(lastEvent.UserIdentities),
|
|
@@ -2194,7 +2194,7 @@ var mParticle = (function () {
|
|
|
2194
2194
|
return __generator(this, function (_a) {
|
|
2195
2195
|
switch (_a.label) {
|
|
2196
2196
|
case 0:
|
|
2197
|
-
return [4 /*yield*/, this.makeRequest(this.url, fetchPayload.body, fetchPayload.method)];
|
|
2197
|
+
return [4 /*yield*/, this.makeRequest(this.url, fetchPayload.body, fetchPayload.method, fetchPayload.headers)];
|
|
2198
2198
|
case 1:
|
|
2199
2199
|
response = _a.sent();
|
|
2200
2200
|
return [2 /*return*/, response];
|
|
@@ -2210,10 +2210,13 @@ var mParticle = (function () {
|
|
|
2210
2210
|
// 3 LOADING Downloading; responseText holds partial data.
|
|
2211
2211
|
// 4 DONE The operation is complete.
|
|
2212
2212
|
// https://go.mparticle.com/work/SQDSDKS-6736
|
|
2213
|
-
XHRUploader.prototype.makeRequest = function (url, data, method) {
|
|
2213
|
+
XHRUploader.prototype.makeRequest = function (url, data, method, headers) {
|
|
2214
2214
|
if (method === void 0) {
|
|
2215
2215
|
method = 'post';
|
|
2216
2216
|
}
|
|
2217
|
+
if (headers === void 0) {
|
|
2218
|
+
headers = {};
|
|
2219
|
+
}
|
|
2217
2220
|
return __awaiter(this, void 0, void 0, function () {
|
|
2218
2221
|
var xhr;
|
|
2219
2222
|
return __generator(this, function (_a) {
|
|
@@ -2231,6 +2234,11 @@ var mParticle = (function () {
|
|
|
2231
2234
|
reject(xhr);
|
|
2232
2235
|
};
|
|
2233
2236
|
xhr.open(method, url);
|
|
2237
|
+
Object.entries(headers).forEach(function (_a) {
|
|
2238
|
+
var key = _a[0],
|
|
2239
|
+
value = _a[1];
|
|
2240
|
+
xhr.setRequestHeader(key, value);
|
|
2241
|
+
});
|
|
2234
2242
|
xhr.send(data);
|
|
2235
2243
|
})];
|
|
2236
2244
|
});
|
|
@@ -6819,23 +6827,6 @@ var mParticle = (function () {
|
|
|
6819
6827
|
Login$1 = _a.Login,
|
|
6820
6828
|
Logout$1 = _a.Logout;
|
|
6821
6829
|
var CACHE_HEADER = 'x-mp-max-age';
|
|
6822
|
-
// https://go.mparticle.com/work/SQDSDKS-6568
|
|
6823
|
-
// Temporary adapter to convert the XMLHttpRequest response to the IIdentityResponse interface
|
|
6824
|
-
var xhrIdentityResponseAdapter = function xhrIdentityResponseAdapter(possiblyXhr) {
|
|
6825
|
-
if (possiblyXhr.hasOwnProperty('expireTimestamp')) {
|
|
6826
|
-
// If there is an `expireTimestamp`, it is an IIdentityResponse object, so just return it. This indicates it was a previously cached value.
|
|
6827
|
-
return possiblyXhr;
|
|
6828
|
-
} else {
|
|
6829
|
-
// If there is no `expireTimestamp`, then it is an XHR object and needs to be parsed.
|
|
6830
|
-
return {
|
|
6831
|
-
status: possiblyXhr.status,
|
|
6832
|
-
// Sometimes responseText can be an empty string, such as a 404 response
|
|
6833
|
-
responseText: possiblyXhr.responseText ? JSON.parse(possiblyXhr.responseText) : {},
|
|
6834
|
-
cacheMaxAge: parseNumber((possiblyXhr === null || possiblyXhr === void 0 ? void 0 : possiblyXhr.getResponseHeader(CACHE_HEADER)) || ''),
|
|
6835
|
-
expireTimestamp: 0
|
|
6836
|
-
};
|
|
6837
|
-
}
|
|
6838
|
-
};
|
|
6839
6830
|
var cacheOrClearIdCache = function cacheOrClearIdCache(method, knownIdentities, idCache, identityResponse, parsingCachedResponse) {
|
|
6840
6831
|
// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
6841
6832
|
if (parsingCachedResponse) {
|
|
@@ -7993,8 +7984,7 @@ var mParticle = (function () {
|
|
|
7993
7984
|
}
|
|
7994
7985
|
if (identityResponse.status === HTTP_OK) {
|
|
7995
7986
|
if (getFeatureFlag(CacheIdentity)) {
|
|
7996
|
-
|
|
7997
|
-
cacheOrClearIdCache(method, knownIdentities, self.idCache, identityResponseForCache, parsingCachedResponse);
|
|
7987
|
+
cacheOrClearIdCache(method, knownIdentities, self.idCache, identityResponse, parsingCachedResponse);
|
|
7998
7988
|
}
|
|
7999
7989
|
var incomingUser = self.IdentityAPI.getUser(identityApiResult.mpid);
|
|
8000
7990
|
var incomingUIByName = incomingUser ? incomingUser.getUserIdentities().userIdentities : {};
|
|
@@ -9031,7 +9021,6 @@ var mParticle = (function () {
|
|
|
9031
9021
|
return [3 /*break*/, 8];
|
|
9032
9022
|
case 7:
|
|
9033
9023
|
xhrResponse = response;
|
|
9034
|
-
// debugger;
|
|
9035
9024
|
aliasResponseBody = xhrResponse.responseText ? JSON.parse(xhrResponse.responseText) : '';
|
|
9036
9025
|
_b.label = 8;
|
|
9037
9026
|
case 8:
|
|
@@ -9086,48 +9075,102 @@ var mParticle = (function () {
|
|
|
9086
9075
|
return _ref.apply(this, arguments);
|
|
9087
9076
|
};
|
|
9088
9077
|
}();
|
|
9089
|
-
this.sendIdentityRequest = function (
|
|
9090
|
-
var
|
|
9091
|
-
previousMPID,
|
|
9092
|
-
|
|
9093
|
-
|
|
9094
|
-
|
|
9095
|
-
|
|
9096
|
-
|
|
9097
|
-
|
|
9098
|
-
|
|
9099
|
-
|
|
9100
|
-
|
|
9101
|
-
|
|
9102
|
-
|
|
9103
|
-
|
|
9104
|
-
|
|
9105
|
-
|
|
9106
|
-
|
|
9107
|
-
|
|
9108
|
-
|
|
9109
|
-
|
|
9110
|
-
|
|
9111
|
-
|
|
9112
|
-
|
|
9113
|
-
|
|
9114
|
-
|
|
9115
|
-
|
|
9116
|
-
|
|
9117
|
-
|
|
9118
|
-
|
|
9119
|
-
|
|
9120
|
-
|
|
9121
|
-
|
|
9122
|
-
|
|
9123
|
-
|
|
9078
|
+
this.sendIdentityRequest = /*#__PURE__*/function () {
|
|
9079
|
+
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid, knownIdentities) {
|
|
9080
|
+
var _mpInstance$Logger, verbose, error, invokeCallback, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, responseBody;
|
|
9081
|
+
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
|
|
9082
|
+
while (1) switch (_context2.prev = _context2.next) {
|
|
9083
|
+
case 0:
|
|
9084
|
+
_mpInstance$Logger = mpInstance.Logger, verbose = _mpInstance$Logger.verbose, error = _mpInstance$Logger.error;
|
|
9085
|
+
invokeCallback = mpInstance._Helpers.invokeCallback;
|
|
9086
|
+
verbose(Messages$1.InformationMessages.SendIdentityBegin);
|
|
9087
|
+
if (identityApiRequest) {
|
|
9088
|
+
_context2.next = 6;
|
|
9089
|
+
break;
|
|
9090
|
+
}
|
|
9091
|
+
error(Messages$1.ErrorMessages.APIRequestEmpty);
|
|
9092
|
+
return _context2.abrupt("return");
|
|
9093
|
+
case 6:
|
|
9094
|
+
verbose(Messages$1.InformationMessages.SendIdentityHttp);
|
|
9095
|
+
if (!mpInstance._Store.identityCallInFlight) {
|
|
9096
|
+
_context2.next = 10;
|
|
9097
|
+
break;
|
|
9098
|
+
}
|
|
9099
|
+
invokeCallback(callback, HTTPCodes$1.activeIdentityRequest, 'There is currently an Identity request processing. Please wait for this to return before requesting again');
|
|
9100
|
+
return _context2.abrupt("return");
|
|
9101
|
+
case 10:
|
|
9102
|
+
previousMPID = mpid || null;
|
|
9103
|
+
uploadUrl = this.getUploadUrl(method, mpid);
|
|
9104
|
+
uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl);
|
|
9105
|
+
fetchPayload = {
|
|
9106
|
+
method: 'post',
|
|
9107
|
+
headers: {
|
|
9108
|
+
Accept: 'text/plain;charset=UTF-8',
|
|
9109
|
+
'Content-Type': 'application/json',
|
|
9110
|
+
'x-mp-key': mpInstance._Store.devToken
|
|
9111
|
+
},
|
|
9112
|
+
body: JSON.stringify(identityApiRequest)
|
|
9113
|
+
};
|
|
9114
|
+
_context2.prev = 14;
|
|
9115
|
+
mpInstance._Store.identityCallInFlight = true;
|
|
9116
|
+
_context2.next = 18;
|
|
9117
|
+
return uploader.upload(fetchPayload);
|
|
9118
|
+
case 18:
|
|
9119
|
+
response = _context2.sent;
|
|
9120
|
+
if (!response.json) {
|
|
9121
|
+
_context2.next = 26;
|
|
9122
|
+
break;
|
|
9123
|
+
}
|
|
9124
|
+
_context2.next = 22;
|
|
9125
|
+
return response.json();
|
|
9126
|
+
case 22:
|
|
9127
|
+
responseBody = _context2.sent;
|
|
9128
|
+
identityResponse = this.getIdentityResponseFromFetch(response, responseBody);
|
|
9129
|
+
_context2.next = 27;
|
|
9130
|
+
break;
|
|
9131
|
+
case 26:
|
|
9132
|
+
identityResponse = this.getIdentityResponseFromXHR(response);
|
|
9133
|
+
case 27:
|
|
9134
|
+
verbose('Received Identity Response from server: ' + JSON.stringify(identityResponse.responseText));
|
|
9135
|
+
parseIdentityResponse(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false);
|
|
9136
|
+
_context2.next = 36;
|
|
9137
|
+
break;
|
|
9138
|
+
case 31:
|
|
9139
|
+
_context2.prev = 31;
|
|
9140
|
+
_context2.t0 = _context2["catch"](14);
|
|
9141
|
+
mpInstance._Store.identityCallInFlight = false;
|
|
9142
|
+
invokeCallback(callback, HTTPCodes$1.noHttpCoverage, _context2.t0);
|
|
9143
|
+
error('Error sending identity request to servers' + ' - ' + _context2.t0);
|
|
9144
|
+
case 36:
|
|
9145
|
+
case "end":
|
|
9146
|
+
return _context2.stop();
|
|
9124
9147
|
}
|
|
9125
|
-
}
|
|
9126
|
-
|
|
9127
|
-
|
|
9128
|
-
|
|
9129
|
-
|
|
9130
|
-
|
|
9148
|
+
}, _callee2, this, [[14, 31]]);
|
|
9149
|
+
}));
|
|
9150
|
+
return function (_x3, _x4, _x5, _x6, _x7, _x8, _x9) {
|
|
9151
|
+
return _ref2.apply(this, arguments);
|
|
9152
|
+
};
|
|
9153
|
+
}();
|
|
9154
|
+
this.getUploadUrl = function (method, mpid) {
|
|
9155
|
+
var uploadServiceUrl = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.identityUrl);
|
|
9156
|
+
var uploadUrl = method === Modify ? uploadServiceUrl + mpid + '/' + method : uploadServiceUrl + method;
|
|
9157
|
+
return uploadUrl;
|
|
9158
|
+
};
|
|
9159
|
+
this.getIdentityResponseFromFetch = function (response, responseBody) {
|
|
9160
|
+
return {
|
|
9161
|
+
status: response.status,
|
|
9162
|
+
responseText: responseBody,
|
|
9163
|
+
cacheMaxAge: parseInt(response.headers.get(CACHE_HEADER)) || 0,
|
|
9164
|
+
expireTimestamp: 0
|
|
9165
|
+
};
|
|
9166
|
+
};
|
|
9167
|
+
this.getIdentityResponseFromXHR = function (response) {
|
|
9168
|
+
return {
|
|
9169
|
+
status: response.status,
|
|
9170
|
+
responseText: response.responseText ? JSON.parse(response.responseText) : {},
|
|
9171
|
+
cacheMaxAge: parseNumber(response.getResponseHeader(CACHE_HEADER) || ''),
|
|
9172
|
+
expireTimestamp: 0
|
|
9173
|
+
};
|
|
9131
9174
|
};
|
|
9132
9175
|
}
|
|
9133
9176
|
|
|
@@ -10395,8 +10438,9 @@ var mParticle = (function () {
|
|
|
10395
10438
|
processPreloadedItem(readyQueueItem);
|
|
10396
10439
|
}
|
|
10397
10440
|
});
|
|
10398
|
-
return [];
|
|
10399
10441
|
}
|
|
10442
|
+
// https://go.mparticle.com/work/SQDSDKS-6835
|
|
10443
|
+
return [];
|
|
10400
10444
|
}
|
|
10401
10445
|
function queueIfNotInitialized(func, self) {
|
|
10402
10446
|
if (!self.isInitialized()) {
|
package/package.json
CHANGED
|
@@ -54,7 +54,7 @@ export async function sendAliasRequest (mpInstance: MParticleWebSDK, aliasReques
|
|
|
54
54
|
// https://go.mparticle.com/work/SQDSDKS-6568
|
|
55
55
|
// XHRUploader returns the response as a string that we need to parse
|
|
56
56
|
const xhrResponse = response as unknown as XMLHttpRequest;
|
|
57
|
-
|
|
57
|
+
|
|
58
58
|
aliasResponseBody = xhrResponse.responseText
|
|
59
59
|
? JSON.parse(xhrResponse.responseText)
|
|
60
60
|
: '';
|
package/src/identity-utils.ts
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
} from './identity-user-interfaces';
|
|
15
15
|
|
|
16
16
|
const { Identify, Modify, Login, Logout } = Constants.IdentityMethods;
|
|
17
|
-
const CACHE_HEADER = 'x-mp-max-age' as const;
|
|
17
|
+
export const CACHE_HEADER = 'x-mp-max-age' as const;
|
|
18
18
|
|
|
19
19
|
export type IdentityCache = BaseVault<Dictionary<ICachedIdentityCall>>;
|
|
20
20
|
|
|
@@ -40,33 +40,6 @@ export interface ICachedIdentityCall {
|
|
|
40
40
|
expireTimestamp: number;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
// https://go.mparticle.com/work/SQDSDKS-6568
|
|
44
|
-
// Temporary adapter to convert the XMLHttpRequest response to the IIdentityResponse interface
|
|
45
|
-
export const xhrIdentityResponseAdapter = (
|
|
46
|
-
possiblyXhr: XMLHttpRequest | IIdentityResponse
|
|
47
|
-
): IIdentityResponse => {
|
|
48
|
-
if (possiblyXhr.hasOwnProperty('expireTimestamp')) {
|
|
49
|
-
// If there is an `expireTimestamp`, it is an IIdentityResponse object, so just return it. This indicates it was a previously cached value.
|
|
50
|
-
return possiblyXhr as IIdentityResponse;
|
|
51
|
-
} else {
|
|
52
|
-
// If there is no `expireTimestamp`, then it is an XHR object and needs to be parsed.
|
|
53
|
-
return {
|
|
54
|
-
status: possiblyXhr.status,
|
|
55
|
-
|
|
56
|
-
// Sometimes responseText can be an empty string, such as a 404 response
|
|
57
|
-
responseText: (possiblyXhr as XMLHttpRequest).responseText
|
|
58
|
-
? JSON.parse((possiblyXhr as XMLHttpRequest).responseText)
|
|
59
|
-
: {},
|
|
60
|
-
cacheMaxAge: parseNumber(
|
|
61
|
-
(possiblyXhr as XMLHttpRequest)?.getResponseHeader(
|
|
62
|
-
CACHE_HEADER
|
|
63
|
-
) || ''
|
|
64
|
-
),
|
|
65
|
-
expireTimestamp: 0,
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
|
|
70
43
|
export const cacheOrClearIdCache = (
|
|
71
44
|
method: string,
|
|
72
45
|
knownIdentities: IKnownIdentities,
|
package/src/identity.js
CHANGED
|
@@ -4,7 +4,6 @@ import {
|
|
|
4
4
|
cacheOrClearIdCache,
|
|
5
5
|
createKnownIdentities,
|
|
6
6
|
tryCacheIdentity,
|
|
7
|
-
xhrIdentityResponseAdapter,
|
|
8
7
|
} from './identity-utils';
|
|
9
8
|
import AudienceManager from './audienceManager';
|
|
10
9
|
const { Messages, HTTPCodes, FeatureFlags, IdentityMethods } = Constants;
|
|
@@ -1514,14 +1513,11 @@ export default function Identity(mpInstance) {
|
|
|
1514
1513
|
|
|
1515
1514
|
if (identityResponse.status === HTTP_OK) {
|
|
1516
1515
|
if (getFeatureFlag(CacheIdentity)) {
|
|
1517
|
-
const identityResponseForCache = xhrIdentityResponseAdapter(
|
|
1518
|
-
identityResponse
|
|
1519
|
-
);
|
|
1520
1516
|
cacheOrClearIdCache(
|
|
1521
1517
|
method,
|
|
1522
1518
|
knownIdentities,
|
|
1523
1519
|
self.idCache,
|
|
1524
|
-
|
|
1520
|
+
identityResponse,
|
|
1525
1521
|
parsingCachedResponse
|
|
1526
1522
|
);
|
|
1527
1523
|
}
|
package/src/identityApiClient.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import Constants from './constants';
|
|
2
|
-
import { xhrIdentityResponseAdapter } from './identity-utils';
|
|
3
2
|
import { sendAliasRequest } from './aliasRequestApiClient';
|
|
3
|
+
import { FetchUploader, XHRUploader } from './uploaders';
|
|
4
|
+
import { CACHE_HEADER } from './identity-utils';
|
|
5
|
+
import { parseNumber } from './utils';
|
|
4
6
|
|
|
5
7
|
var HTTPCodes = Constants.HTTPCodes,
|
|
6
8
|
Messages = Constants.Messages;
|
|
@@ -12,7 +14,7 @@ export default function IdentityAPIClient(mpInstance) {
|
|
|
12
14
|
await sendAliasRequest(mpInstance, aliasRequest, callback);
|
|
13
15
|
};
|
|
14
16
|
|
|
15
|
-
this.sendIdentityRequest = function(
|
|
17
|
+
this.sendIdentityRequest = async function(
|
|
16
18
|
identityApiRequest,
|
|
17
19
|
method,
|
|
18
20
|
callback,
|
|
@@ -21,93 +23,109 @@ export default function IdentityAPIClient(mpInstance) {
|
|
|
21
23
|
mpid,
|
|
22
24
|
knownIdentities
|
|
23
25
|
) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
xhrCallback = function() {
|
|
27
|
-
if (xhr.readyState === 4) {
|
|
28
|
-
// https://go.mparticle.com/work/SQDSDKS-6368
|
|
29
|
-
mpInstance.Logger.verbose(
|
|
30
|
-
'Received ' + xhr.statusText + ' from server'
|
|
31
|
-
);
|
|
32
|
-
|
|
33
|
-
// https://go.mparticle.com/work/SQDSDKS-6565
|
|
34
|
-
const identityResponse = xhrIdentityResponseAdapter(xhr);
|
|
35
|
-
parseIdentityResponse(
|
|
36
|
-
identityResponse,
|
|
37
|
-
previousMPID,
|
|
38
|
-
callback,
|
|
39
|
-
originalIdentityApiData,
|
|
40
|
-
method,
|
|
41
|
-
knownIdentities,
|
|
42
|
-
false
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
mpInstance.Logger.verbose(
|
|
48
|
-
Messages.InformationMessages.SendIdentityBegin
|
|
49
|
-
);
|
|
26
|
+
const { verbose, error } = mpInstance.Logger;
|
|
27
|
+
const { invokeCallback } = mpInstance._Helpers;
|
|
50
28
|
|
|
29
|
+
verbose(Messages.InformationMessages.SendIdentityBegin);
|
|
51
30
|
if (!identityApiRequest) {
|
|
52
|
-
|
|
31
|
+
error(Messages.ErrorMessages.APIRequestEmpty);
|
|
53
32
|
return;
|
|
54
33
|
}
|
|
34
|
+
verbose(Messages.InformationMessages.SendIdentityHttp);
|
|
55
35
|
|
|
56
|
-
mpInstance.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
xhr.send(JSON.stringify(identityApiRequest));
|
|
96
|
-
}
|
|
97
|
-
} catch (e) {
|
|
98
|
-
mpInstance._Store.identityCallInFlight = false;
|
|
99
|
-
mpInstance._Helpers.invokeCallback(
|
|
100
|
-
callback,
|
|
101
|
-
HTTPCodes.noHttpCoverage,
|
|
102
|
-
e
|
|
103
|
-
);
|
|
104
|
-
mpInstance.Logger.error(
|
|
105
|
-
'Error sending identity request to servers with status code ' +
|
|
106
|
-
xhr.status +
|
|
107
|
-
' - ' +
|
|
108
|
-
e
|
|
36
|
+
if (mpInstance._Store.identityCallInFlight) {
|
|
37
|
+
invokeCallback(
|
|
38
|
+
callback,
|
|
39
|
+
HTTPCodes.activeIdentityRequest,
|
|
40
|
+
'There is currently an Identity request processing. Please wait for this to return before requesting again'
|
|
41
|
+
);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const previousMPID = mpid || null;
|
|
46
|
+
const uploadUrl = this.getUploadUrl(method, mpid);
|
|
47
|
+
|
|
48
|
+
const uploader = window.fetch
|
|
49
|
+
? new FetchUploader(uploadUrl)
|
|
50
|
+
: new XHRUploader(uploadUrl);
|
|
51
|
+
|
|
52
|
+
const fetchPayload = {
|
|
53
|
+
method: 'post',
|
|
54
|
+
headers: {
|
|
55
|
+
Accept: 'text/plain;charset=UTF-8',
|
|
56
|
+
'Content-Type': 'application/json',
|
|
57
|
+
'x-mp-key': mpInstance._Store.devToken,
|
|
58
|
+
},
|
|
59
|
+
body: JSON.stringify(identityApiRequest),
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
mpInstance._Store.identityCallInFlight = true;
|
|
64
|
+
const response = await uploader.upload(fetchPayload);
|
|
65
|
+
|
|
66
|
+
let identityResponse;
|
|
67
|
+
|
|
68
|
+
if (response.json) {
|
|
69
|
+
// https://go.mparticle.com/work/SQDSDKS-6568
|
|
70
|
+
// FetchUploader returns the response as a JSON object that we have to await
|
|
71
|
+
const responseBody = await response.json();
|
|
72
|
+
identityResponse = this.getIdentityResponseFromFetch(
|
|
73
|
+
response,
|
|
74
|
+
responseBody
|
|
109
75
|
);
|
|
76
|
+
} else {
|
|
77
|
+
identityResponse = this.getIdentityResponseFromXHR(response);
|
|
110
78
|
}
|
|
79
|
+
|
|
80
|
+
verbose(
|
|
81
|
+
'Received Identity Response from server: ' +
|
|
82
|
+
JSON.stringify(identityResponse.responseText)
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
parseIdentityResponse(
|
|
86
|
+
identityResponse,
|
|
87
|
+
previousMPID,
|
|
88
|
+
callback,
|
|
89
|
+
originalIdentityApiData,
|
|
90
|
+
method,
|
|
91
|
+
knownIdentities,
|
|
92
|
+
false
|
|
93
|
+
);
|
|
94
|
+
} catch (err) {
|
|
95
|
+
mpInstance._Store.identityCallInFlight = false;
|
|
96
|
+
invokeCallback(callback, HTTPCodes.noHttpCoverage, err);
|
|
97
|
+
error('Error sending identity request to servers' + ' - ' + err);
|
|
111
98
|
}
|
|
112
99
|
};
|
|
100
|
+
|
|
101
|
+
this.getUploadUrl = (method, mpid) => {
|
|
102
|
+
const uploadServiceUrl = mpInstance._Helpers.createServiceUrl(
|
|
103
|
+
mpInstance._Store.SDKConfig.identityUrl
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
const uploadUrl =
|
|
107
|
+
method === Modify
|
|
108
|
+
? uploadServiceUrl + mpid + '/' + method
|
|
109
|
+
: uploadServiceUrl + method;
|
|
110
|
+
|
|
111
|
+
return uploadUrl;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
this.getIdentityResponseFromFetch = (response, responseBody) => ({
|
|
115
|
+
status: response.status,
|
|
116
|
+
responseText: responseBody,
|
|
117
|
+
cacheMaxAge: parseInt(response.headers.get(CACHE_HEADER)) || 0,
|
|
118
|
+
expireTimestamp: 0,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
this.getIdentityResponseFromXHR = response => ({
|
|
122
|
+
status: response.status,
|
|
123
|
+
responseText: response.responseText
|
|
124
|
+
? JSON.parse(response.responseText)
|
|
125
|
+
: {},
|
|
126
|
+
cacheMaxAge: parseNumber(
|
|
127
|
+
response.getResponseHeader(CACHE_HEADER) || ''
|
|
128
|
+
),
|
|
129
|
+
expireTimestamp: 0,
|
|
130
|
+
});
|
|
113
131
|
}
|
package/src/mp-instance.js
CHANGED
|
@@ -1539,9 +1539,9 @@ function processReadyQueue(readyQueue) {
|
|
|
1539
1539
|
processPreloadedItem(readyQueueItem);
|
|
1540
1540
|
}
|
|
1541
1541
|
});
|
|
1542
|
-
|
|
1543
|
-
return [];
|
|
1544
1542
|
}
|
|
1543
|
+
// https://go.mparticle.com/work/SQDSDKS-6835
|
|
1544
|
+
return [];
|
|
1545
1545
|
}
|
|
1546
1546
|
|
|
1547
1547
|
function queueIfNotInitialized(func, self) {
|
|
@@ -77,8 +77,8 @@ export function convertEvents(
|
|
|
77
77
|
|
|
78
78
|
device_info: {
|
|
79
79
|
platform: EventsApi.DeviceInformationPlatformEnum.web,
|
|
80
|
-
screen_width: window.screen.width,
|
|
81
|
-
screen_height: window.screen.height,
|
|
80
|
+
screen_width: typeof window !== 'undefined' ? window.screen.width : 0,
|
|
81
|
+
screen_height: typeof window !== 'undefined' ? window.screen.height : 0,
|
|
82
82
|
},
|
|
83
83
|
user_attributes: lastEvent.UserAttributes,
|
|
84
84
|
user_identities: convertUserIdentities(lastEvent.UserIdentities),
|
package/src/uploaders.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
type HTTPMethod = 'get' | 'post';
|
|
2
|
+
|
|
1
3
|
export interface fetchPayload {
|
|
2
4
|
method: string;
|
|
3
5
|
headers: {
|
|
@@ -34,7 +36,8 @@ export class XHRUploader extends AsyncUploader {
|
|
|
34
36
|
const response: Response = await this.makeRequest(
|
|
35
37
|
this.url,
|
|
36
38
|
fetchPayload.body,
|
|
37
|
-
fetchPayload.method as
|
|
39
|
+
fetchPayload.method as HTTPMethod,
|
|
40
|
+
fetchPayload.headers
|
|
38
41
|
);
|
|
39
42
|
return response;
|
|
40
43
|
}
|
|
@@ -51,7 +54,8 @@ export class XHRUploader extends AsyncUploader {
|
|
|
51
54
|
private async makeRequest(
|
|
52
55
|
url: string,
|
|
53
56
|
data: string,
|
|
54
|
-
method:
|
|
57
|
+
method: HTTPMethod = 'post',
|
|
58
|
+
headers: Record<string, string> = {}
|
|
55
59
|
): Promise<Response> {
|
|
56
60
|
const xhr: XMLHttpRequest = new XMLHttpRequest();
|
|
57
61
|
return new Promise((resolve, reject) => {
|
|
@@ -69,8 +73,12 @@ export class XHRUploader extends AsyncUploader {
|
|
|
69
73
|
reject((xhr as unknown) as Response);
|
|
70
74
|
};
|
|
71
75
|
|
|
72
|
-
|
|
73
76
|
xhr.open(method, url);
|
|
77
|
+
|
|
78
|
+
Object.entries(headers).forEach(([key, value]) => {
|
|
79
|
+
xhr.setRequestHeader(key, value);
|
|
80
|
+
});
|
|
81
|
+
|
|
74
82
|
xhr.send(data);
|
|
75
83
|
});
|
|
76
84
|
}
|