Socket
Socket
Sign inDemoInstall

@mparticle/web-sdk

Package Overview
Dependencies
Maintainers
7
Versions
108
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mparticle/web-sdk - npm Package Compare versions

Comparing version 2.9.16-rc.1 to 2.10.0-rc.1

src/mp-instance.js

4

CHANGELOG.md

@@ -5,2 +5,6 @@ ## Releases

#### 2.10.0 - 2019-11-13
- Feat - Implement Multiple Instances
#### 2.9.16 - 2019-11-06

@@ -7,0 +11,0 @@

5

package.json
{
"name": "@mparticle/web-sdk",
"version": "2.9.16-rc.1",
"version": "2.10.0-rc.1",
"description": "mParticle core SDK for web applications",

@@ -107,4 +107,5 @@ "license": "Apache-2.0",

"dependencies": {
"@babel/runtime": "^7.6.0"
"@babel/runtime": "^7.6.0",
"slugify": "^1.3.6"
}
}

@@ -1,479 +0,500 @@

import Helpers from './helpers';
import Constants from './constants';
import NativeSdkHelpers from './nativeSdkHelpers';
import ServerModel from './serverModel';
import Types from './types';
import { BatchUploader } from './batchUploader';
import Persistence from './persistence';
import Forwarders from './forwarders';
var HTTPCodes = Constants.HTTPCodes,
Messages = Constants.Messages,
uploader = null;
Messages = Constants.Messages;
function queueEventForBatchUpload(event) {
if (!uploader) {
var millis = Helpers.getFeatureFlag(
Constants.FeatureFlags.EventBatchingIntervalMillis
export default function APIClient(mpInstance) {
this.uploader = null;
var self = this;
this.queueEventForBatchUpload = function(event) {
if (!this.uploader) {
var millis = mpInstance._Helpers.getFeatureFlag(
Constants.FeatureFlags.EventBatchingIntervalMillis
);
this.uploader = new BatchUploader(mpInstance, millis);
}
this.uploader.queueEvent(event);
};
this.shouldEnableBatching = function() {
if (!window.fetch) {
return false;
}
// Returns a string of a number that must be parsed
// Invalid strings will be parsed to NaN which is falsey
var eventsV3Percentage = parseInt(
mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventsV3),
10
);
uploader = new BatchUploader(mParticle, millis);
}
uploader.queueEvent(event);
}
function shouldEnableBatching() {
if (!window.fetch) {
return false;
}
if (!eventsV3Percentage) {
return false;
}
// Returns a string of a number that must be parsed
// Invalid strings will be parsed to NaN which is falsey
var eventsV3Percentage = parseInt(
Helpers.getFeatureFlag(Constants.FeatureFlags.EventsV3),
10
);
var rampNumber = mpInstance._Helpers.getRampNumber(
mpInstance._Store.deviceId
);
return eventsV3Percentage >= rampNumber;
};
if (!eventsV3Percentage) {
return false;
}
this.processQueuedEvents = function() {
var mpid,
currentUser = mpInstance.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
if (mpInstance._Store.eventQueue.length && mpid) {
var localQueueCopy = mpInstance._Store.eventQueue;
mpInstance._Store.eventQueue = [];
this.appendUserInfoToEvents(currentUser, localQueueCopy);
localQueueCopy.forEach(function(event) {
self.sendEventToServer(event);
});
}
};
var rampNumber = Helpers.getRampNumber(mParticle.Store.deviceId);
return eventsV3Percentage >= rampNumber;
}
function processQueuedEvents() {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
if (mParticle.Store.eventQueue.length && mpid) {
var localQueueCopy = mParticle.Store.eventQueue;
mParticle.Store.eventQueue = [];
appendUserInfoToEvents(currentUser, localQueueCopy);
localQueueCopy.forEach(function(event) {
sendEventToServer(event);
this.appendUserInfoToEvents = function(user, events) {
events.forEach(function(event) {
if (!event.MPID) {
mpInstance._ServerModel.appendUserInfo(user, event);
}
});
}
}
};
function appendUserInfoToEvents(user, events) {
events.forEach(function(event) {
if (!event.MPID) {
ServerModel.appendUserInfo(user, event);
this.sendEventToServer = function(event) {
if (mpInstance._Store.webviewBridgeEnabled) {
mpInstance._NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.LogEvent,
JSON.stringify(event)
);
return;
}
});
}
function sendEventToServer(event) {
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.LogEvent,
JSON.stringify(event)
var mpid,
currentUser = mpInstance.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mpInstance._Store.requireDelay = mpInstance._Helpers.isDelayedByIntegration(
mpInstance._preInit.integrationDelays,
mpInstance._Store.integrationDelayTimeoutStart,
Date.now()
);
return;
}
// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
if (
!mpid ||
mpInstance._Store.requireDelay ||
!mpInstance._Store.configurationLoaded
) {
mpInstance.Logger.verbose(
'Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.'
);
mpInstance._Store.eventQueue.push(event);
return;
}
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticle.Store.requireDelay = Helpers.isDelayedByIntegration(
mParticle.preInit.integrationDelays,
mParticle.Store.integrationDelayTimeoutStart,
Date.now()
);
// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
if (
!mpid ||
mParticle.Store.requireDelay ||
!mParticle.Store.configurationLoaded
) {
mParticle.Logger.verbose(
'Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.'
);
mParticle.Store.eventQueue.push(event);
return;
}
this.processQueuedEvents();
processQueuedEvents();
if (this.shouldEnableBatching()) {
this.queueEventForBatchUpload(event);
} else {
this.sendSingleEventToServer(event);
}
if (shouldEnableBatching()) {
queueEventForBatchUpload(event);
} else {
sendSingleEventToServer(event);
}
if (event && event.EventName !== Types.MessageType.AppStateTransition) {
mpInstance._Forwarders.sendEventToForwarders(event);
}
};
if (event && event.EventName !== Types.MessageType.AppStateTransition) {
Forwarders.sendEventToForwarders(event);
}
}
this.sendSingleEventToServer = function(event) {
if (event.EventDataType === Types.MessageType.Media) {
return;
}
var xhr,
xhrCallback = function() {
if (xhr.readyState === 4) {
mpInstance.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
self.parseEventResponse(xhr.responseText);
}
};
function sendSingleEventToServer(event) {
if (event.EventDataType === Types.MessageType.Media) {
return;
}
var xhr,
xhrCallback = function() {
if (xhr.readyState === 4) {
mParticle.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
if (!event) {
mpInstance.Logger.error(Messages.ErrorMessages.EventEmpty);
return;
}
mpInstance.Logger.verbose(Messages.InformationMessages.SendHttp);
xhr = mpInstance._Helpers.createXHR(xhrCallback);
if (xhr) {
try {
xhr.open(
'post',
mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.v2SecureServiceUrl,
mpInstance._Store.devToken
) + '/Events'
);
parseEventResponse(xhr.responseText);
xhr.send(
JSON.stringify(
mpInstance._ServerModel.convertEventToDTO(
event,
mpInstance._Store.isFirstRun
)
)
);
} catch (e) {
mpInstance.Logger.error(
'Error sending event to mParticle servers. ' + e
);
}
};
if (!event) {
mParticle.Logger.error(Messages.ErrorMessages.EventEmpty);
return;
}
mParticle.Logger.verbose(Messages.InformationMessages.SendHttp);
xhr = Helpers.createXHR(xhrCallback);
if (xhr) {
try {
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.v2SecureServiceUrl,
mParticle.Store.devToken
) + '/Events'
);
xhr.send(
JSON.stringify(
ServerModel.convertEventToDTO(
event,
mParticle.Store.isFirstRun
)
)
);
} catch (e) {
mParticle.Logger.error(
'Error sending event to mParticle servers. ' + e
);
}
}
}
};
function parseEventResponse(responseText) {
var now = new Date(),
settings,
prop,
fullProp;
this.parseEventResponse = function(responseText) {
var now = new Date(),
settings,
prop,
fullProp;
if (!responseText) {
return;
}
if (!responseText) {
return;
}
try {
mParticle.Logger.verbose('Parsing response from server');
settings = JSON.parse(responseText);
try {
mpInstance.Logger.verbose('Parsing response from server');
settings = JSON.parse(responseText);
if (settings && settings.Store) {
mParticle.Logger.verbose(
'Parsed store from response, updating local settings'
);
if (settings && settings.Store) {
mpInstance.Logger.verbose(
'Parsed store from response, updating local settings'
);
if (!mParticle.Store.serverSettings) {
mParticle.Store.serverSettings = {};
}
for (prop in settings.Store) {
if (!settings.Store.hasOwnProperty(prop)) {
continue;
if (!mpInstance._Store.serverSettings) {
mpInstance._Store.serverSettings = {};
}
fullProp = settings.Store[prop];
for (prop in settings.Store) {
if (!settings.Store.hasOwnProperty(prop)) {
continue;
}
if (!fullProp.Value || new Date(fullProp.Expires) < now) {
// This setting should be deleted from the local store if it exists
fullProp = settings.Store[prop];
if (mParticle.Store.serverSettings.hasOwnProperty(prop)) {
delete mParticle.Store.serverSettings[prop];
if (!fullProp.Value || new Date(fullProp.Expires) < now) {
// This setting should be deleted from the local store if it exists
if (
mpInstance._Store.serverSettings.hasOwnProperty(
prop
)
) {
delete mpInstance._Store.serverSettings[prop];
}
} else {
// This is a valid setting
mpInstance._Store.serverSettings[prop] = fullProp;
}
} else {
// This is a valid setting
mParticle.Store.serverSettings[prop] = fullProp;
}
}
mpInstance._Persistence.update();
} catch (e) {
mpInstance.Logger.error(
'Error parsing JSON response from server: ' + e.name
);
}
Persistence.update();
} catch (e) {
mParticle.Logger.error(
'Error parsing JSON response from server: ' + e.name
);
}
}
};
function sendAliasRequest(aliasRequest, callback) {
var xhr,
xhrCallback = function() {
if (xhr.readyState === 4) {
mParticle.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
//only parse error messages from failing requests
if (xhr.status !== 200 && xhr.status !== 202) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.hasOwnProperty('message')) {
var errorMessage = response.message;
Helpers.invokeAliasCallback(
callback,
xhr.status,
errorMessage
);
return;
this.sendAliasRequest = function(aliasRequest, callback) {
var xhr,
xhrCallback = function() {
if (xhr.readyState === 4) {
mpInstance.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
//only parse error messages from failing requests
if (xhr.status !== 200 && xhr.status !== 202) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.hasOwnProperty('message')) {
var errorMessage = response.message;
mpInstance._Helpers.invokeAliasCallback(
callback,
xhr.status,
errorMessage
);
return;
}
}
}
mpInstance._Helpers.invokeAliasCallback(
callback,
xhr.status
);
}
Helpers.invokeAliasCallback(callback, xhr.status);
}
};
mParticle.Logger.verbose(Messages.InformationMessages.SendAliasHttp);
};
mpInstance.Logger.verbose(Messages.InformationMessages.SendAliasHttp);
xhr = Helpers.createXHR(xhrCallback);
if (xhr) {
try {
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.aliasUrl,
mParticle.Store.devToken
) + '/Alias'
);
xhr.send(JSON.stringify(aliasRequest));
} catch (e) {
Helpers.invokeAliasCallback(callback, HTTPCodes.noHttpCoverage, e);
mParticle.Logger.error(
'Error sending alias request to mParticle servers. ' + e
);
}
}
}
function sendIdentityRequest(
identityApiRequest,
method,
callback,
originalIdentityApiData,
parseIdentityResponse,
mpid
) {
var xhr,
previousMPID,
xhrCallback = function() {
if (xhr.readyState === 4) {
mParticle.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
xhr = mpInstance._Helpers.createXHR(xhrCallback);
if (xhr) {
try {
xhr.open(
'post',
mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.aliasUrl,
mpInstance._Store.devToken
) + '/Alias'
);
parseIdentityResponse(
xhr,
previousMPID,
xhr.send(JSON.stringify(aliasRequest));
} catch (e) {
mpInstance._Helpers.invokeAliasCallback(
callback,
originalIdentityApiData,
method
HTTPCodes.noHttpCoverage,
e
);
mpInstance.Logger.error(
'Error sending alias request to mParticle servers. ' + e
);
}
};
}
};
mParticle.Logger.verbose(Messages.InformationMessages.SendIdentityBegin);
this.sendIdentityRequest = function(
identityApiRequest,
method,
callback,
originalIdentityApiData,
parseIdentityResponse,
mpid
) {
var xhr,
previousMPID,
xhrCallback = function() {
if (xhr.readyState === 4) {
mpInstance.Logger.verbose(
'Received ' + xhr.statusText + ' from server'
);
parseIdentityResponse(
xhr,
previousMPID,
callback,
originalIdentityApiData,
method
);
}
};
if (!identityApiRequest) {
mParticle.Logger.error(Messages.ErrorMessages.APIRequestEmpty);
return;
}
mpInstance.Logger.verbose(
Messages.InformationMessages.SendIdentityBegin
);
mParticle.Logger.verbose(Messages.InformationMessages.SendIdentityHttp);
xhr = Helpers.createXHR(xhrCallback);
if (!identityApiRequest) {
mpInstance.Logger.error(Messages.ErrorMessages.APIRequestEmpty);
return;
}
if (xhr) {
try {
if (mParticle.Store.identityCallInFlight) {
Helpers.invokeCallback(
callback,
HTTPCodes.activeIdentityRequest,
'There is currently an Identity request processing. Please wait for this to return before requesting again'
);
} else {
previousMPID = mpid || null;
if (method === 'modify') {
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.identityUrl
) +
mpid +
'/' +
method
mpInstance.Logger.verbose(
Messages.InformationMessages.SendIdentityHttp
);
xhr = mpInstance._Helpers.createXHR(xhrCallback);
if (xhr) {
try {
if (mpInstance._Store.identityCallInFlight) {
mpInstance._Helpers.invokeCallback(
callback,
HTTPCodes.activeIdentityRequest,
'There is currently an Identity request processing. Please wait for this to return before requesting again'
);
} else {
xhr.open(
'post',
Helpers.createServiceUrl(
mParticle.Store.SDKConfig.identityUrl
) + method
previousMPID = mpid || null;
if (method === 'modify') {
xhr.open(
'post',
mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.identityUrl
) +
mpid +
'/' +
method
);
} else {
xhr.open(
'post',
mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.identityUrl
) + method
);
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader(
'x-mp-key',
mpInstance._Store.devToken
);
mpInstance._Store.identityCallInFlight = true;
xhr.send(JSON.stringify(identityApiRequest));
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('x-mp-key', mParticle.Store.devToken);
mParticle.Store.identityCallInFlight = true;
xhr.send(JSON.stringify(identityApiRequest));
} catch (e) {
mpInstance._Store.identityCallInFlight = false;
mpInstance._Helpers.invokeCallback(
callback,
HTTPCodes.noHttpCoverage,
e
);
mpInstance.Logger.error(
'Error sending identity request to servers with status code ' +
xhr.status +
' - ' +
e
);
}
} catch (e) {
mParticle.Store.identityCallInFlight = false;
Helpers.invokeCallback(callback, HTTPCodes.noHttpCoverage, e);
mParticle.Logger.error(
'Error sending identity request to servers with status code ' +
xhr.status +
' - ' +
e
);
}
}
}
};
function sendBatchForwardingStatsToServer(forwardingStatsData, xhr) {
var url, data;
try {
url = Helpers.createServiceUrl(
mParticle.Store.SDKConfig.v2SecureServiceUrl,
mParticle.Store.devToken
);
data = {
uuid: Helpers.generateUniqueId(),
data: forwardingStatsData,
};
this.sendBatchForwardingStatsToServer = function(forwardingStatsData, xhr) {
var url, data;
try {
url = mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.v2SecureServiceUrl,
mpInstance._Store.devToken
);
data = {
uuid: mpInstance._Helpers.generateUniqueId(),
data: forwardingStatsData,
};
if (xhr) {
xhr.open('post', url + '/Forwarding');
xhr.send(JSON.stringify(data));
if (xhr) {
xhr.open('post', url + '/Forwarding');
xhr.send(JSON.stringify(data));
}
} catch (e) {
mpInstance.Logger.error(
'Error sending forwarding stats to mParticle servers.'
);
}
} catch (e) {
mParticle.Logger.error(
'Error sending forwarding stats to mParticle servers.'
);
}
}
};
function sendSingleForwardingStatsToServer(forwardingStatsData) {
var url, data;
try {
var xhrCallback = function() {
if (xhr.readyState === 4) {
if (xhr.status === 202) {
mParticle.Logger.verbose(
'Successfully sent ' + xhr.statusText + ' from server'
);
this.sendSingleForwardingStatsToServer = function(forwardingStatsData) {
var url, data;
try {
var xhrCallback = function() {
if (xhr.readyState === 4) {
if (xhr.status === 202) {
mpInstance.Logger.verbose(
'Successfully sent ' +
xhr.statusText +
' from server'
);
}
}
};
var xhr = mpInstance._Helpers.createXHR(xhrCallback);
url = mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.v1SecureServiceUrl,
mpInstance._Store.devToken
);
data = forwardingStatsData;
if (xhr) {
xhr.open('post', url + '/Forwarding');
xhr.send(JSON.stringify(data));
}
};
var xhr = Helpers.createXHR(xhrCallback);
url = Helpers.createServiceUrl(
mParticle.Store.SDKConfig.v1SecureServiceUrl,
mParticle.Store.devToken
);
data = forwardingStatsData;
if (xhr) {
xhr.open('post', url + '/Forwarding');
xhr.send(JSON.stringify(data));
} catch (e) {
mpInstance.Logger.error(
'Error sending forwarding stats to mParticle servers.'
);
}
} catch (e) {
mParticle.Logger.error(
'Error sending forwarding stats to mParticle servers.'
);
}
}
};
function getSDKConfiguration(apiKey, config, completeSDKInitialization) {
var url;
try {
var xhrCallback = function() {
if (xhr.readyState === 4) {
// when a 200 returns, merge current config with what comes back from config, prioritizing user inputted config
if (xhr.status === 200) {
config = Helpers.extend(
{},
config,
JSON.parse(xhr.responseText)
);
completeSDKInitialization(apiKey, config);
mParticle.Logger.verbose(
'Successfully received configuration from server'
);
} else {
// if for some reason a 200 doesn't return, then we initialize with the just the passed through config
completeSDKInitialization(apiKey, config);
mParticle.Logger.verbose(
'Issue with receiving configuration from server, received HTTP Code of ' +
xhr.status
);
this.getSDKConfiguration = function(
apiKey,
config,
completeSDKInitialization,
mpInstance
) {
var url;
try {
var xhrCallback = function() {
if (xhr.readyState === 4) {
// when a 200 returns, merge current config with what comes back from config, prioritizing user inputted config
if (xhr.status === 200) {
config = mpInstance._Helpers.extend(
{},
config,
JSON.parse(xhr.responseText)
);
completeSDKInitialization(apiKey, config, mpInstance);
mpInstance.Logger.verbose(
'Successfully received configuration from server'
);
} else {
// if for some reason a 200 doesn't return, then we initialize with the just the passed through config
completeSDKInitialization(apiKey, config, mpInstance);
mpInstance.Logger.verbose(
'Issue with receiving configuration from server, received HTTP Code of ' +
xhr.status
);
}
}
};
var xhr = mpInstance._Helpers.createXHR(xhrCallback);
url =
'https://' +
mpInstance._Store.SDKConfig.configUrl +
apiKey +
'/config?env=';
if (config.isDevelopmentMode) {
url = url + '1';
} else {
url = url + '0';
}
};
var xhr = Helpers.createXHR(xhrCallback);
url =
'https://' +
mParticle.Store.SDKConfig.configUrl +
apiKey +
'/config?env=';
if (config.isDevelopmentMode) {
url = url + '1';
} else {
url = url + '0';
if (xhr) {
xhr.open('get', url);
xhr.send(null);
}
} catch (e) {
completeSDKInitialization(apiKey, config, mpInstance);
mpInstance.Logger.error(
'Error getting forwarder configuration from mParticle servers.'
);
}
};
if (xhr) {
xhr.open('get', url);
xhr.send(null);
}
} catch (e) {
completeSDKInitialization(apiKey, config);
mParticle.Logger.error(
'Error getting forwarder configuration from mParticle servers.'
);
}
}
this.prepareForwardingStats = function(forwarder, event) {
var forwardingStatsData,
queue = mpInstance._Forwarders.getForwarderStatsQueue();
function prepareForwardingStats(forwarder, event) {
var forwardingStatsData,
queue = Forwarders.getForwarderStatsQueue();
if (forwarder && forwarder.isVisible) {
forwardingStatsData = {
mid: forwarder.id,
esid: forwarder.eventSubscriptionId,
n: event.EventName,
attrs: event.EventAttributes,
sdk: event.SDKVersion,
dt: event.EventDataType,
et: event.EventCategory,
dbg: event.Debug,
ct: event.Timestamp,
eec: event.ExpandedEventCount,
dp: event.DataPlan,
};
if (forwarder && forwarder.isVisible) {
forwardingStatsData = {
mid: forwarder.id,
esid: forwarder.eventSubscriptionId,
n: event.EventName,
attrs: event.EventAttributes,
sdk: event.SDKVersion,
dt: event.EventDataType,
et: event.EventCategory,
dbg: event.Debug,
ct: event.Timestamp,
eec: event.ExpandedEventCount,
};
if (Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)) {
queue.push(forwardingStatsData);
Forwarders.setForwarderStatsQueue(queue);
} else {
sendSingleForwardingStatsToServer(forwardingStatsData);
if (
mpInstance._Helpers.getFeatureFlag(
Constants.FeatureFlags.ReportBatching
)
) {
queue.push(forwardingStatsData);
mpInstance._Forwarders.setForwarderStatsQueue(queue);
} else {
self.sendSingleForwardingStatsToServer(forwardingStatsData);
}
}
}
};
}
export default {
sendEventToServer: sendEventToServer,
sendIdentityRequest: sendIdentityRequest,
sendBatchForwardingStatsToServer: sendBatchForwardingStatsToServer,
sendSingleForwardingStatsToServer: sendSingleForwardingStatsToServer,
sendAliasRequest: sendAliasRequest,
getSDKConfiguration: getSDKConfiguration,
prepareForwardingStats: prepareForwardingStats,
processQueuedEvents: processQueuedEvents,
appendUserInfoToEvents: appendUserInfoToEvents,
shouldEnableBatching: shouldEnableBatching,
};
import { Batch } from './eventsApiModels';
import Helpers from './helpers';
import {

@@ -18,8 +17,8 @@ SDKEvent,

pendingUploads: Batch[];
webSdk: MParticleWebSDK;
mpInstance: MParticleWebSDK;
uploadUrl: string;
batchingEnabled: boolean;
constructor(webSdk: MParticleWebSDK, uploadInterval: number) {
this.webSdk = webSdk;
constructor(mpInstance: MParticleWebSDK, uploadInterval: number) {
this.mpInstance = mpInstance;
this.uploadIntervalMillis = uploadInterval;

@@ -34,4 +33,4 @@ this.batchingEnabled =

const { SDKConfig, devToken } = this.webSdk.Store;
const baseUrl = Helpers.createServiceUrl(
const { SDKConfig, devToken } = this.mpInstance._Store;
const baseUrl = this.mpInstance._Helpers.createServiceUrl(
SDKConfig.v3SecureServiceUrl,

@@ -69,9 +68,9 @@ devToken

//add this for cleaner processing later
event.IsFirstRun = this.webSdk.Store.isFirstRun;
event.IsFirstRun = this.mpInstance._Store.isFirstRun;
this.pendingEvents.push(event);
this.webSdk.Logger.verbose(
this.mpInstance.Logger.verbose(
`Queuing event: ${JSON.stringify(event)}`
);
this.webSdk.Logger.verbose(
this.mpInstance.Logger.verbose(
`Queued event count: ${this.pendingEvents.length}`

@@ -96,3 +95,4 @@ );

sdkEvents: SDKEvent[],
defaultUser: MParticleUser
defaultUser: MParticleUser,
mpInstance: MParticleWebSDK
): Batch[] | null {

@@ -133,3 +133,3 @@ if (!defaultUser || !sdkEvents || !sdkEvents.length) {

for (const entry of Array.from(eventsBySession.entries())) {
const upload = convertEvents(mpid, entry[1]);
const upload = convertEvents(mpid, entry[1], mpInstance);
if (upload) {

@@ -152,3 +152,3 @@ newUploads.push(upload);

private async prepareAndUpload(triggerFuture: boolean, useBeacon: boolean) {
const currentUser = this.webSdk.Identity.getCurrentUser();
const currentUser = this.mpInstance.Identity.getCurrentUser();

@@ -159,3 +159,4 @@ const currentEvents = this.pendingEvents;

currentEvents,
currentUser
currentUser,
this.mpInstance
);

@@ -169,3 +170,3 @@ if (newUploads && newUploads.length) {

const remainingUploads = await this.upload(
this.webSdk.Logger,
this.mpInstance.Logger,
currentUploads,

@@ -172,0 +173,0 @@ useBeacon

@@ -1,187 +0,188 @@

import Helpers from './helpers';
function createGDPRConsent(
consented,
timestamp,
consentDocument,
location,
hardwareId
) {
if (typeof consented !== 'boolean') {
mParticle.Logger.error(
'Consented boolean is required when constructing a GDPR Consent object.'
);
return null;
}
if (timestamp && isNaN(timestamp)) {
mParticle.Logger.error(
'Timestamp must be a valid number when constructing a GDPR Consent object.'
);
return null;
}
if (consentDocument && typeof consentDocument !== 'string') {
mParticle.Logger.error(
'Document must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
if (location && typeof location !== 'string') {
mParticle.Logger.error(
'Location must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
if (hardwareId && typeof hardwareId !== 'string') {
mParticle.Logger.error(
'Hardware ID must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
return {
Consented: consented,
Timestamp: timestamp || Date.now(),
ConsentDocument: consentDocument,
Location: location,
HardwareId: hardwareId,
export default function Consent(mpInstance) {
var self = this;
this.createGDPRConsent = function(
consented,
timestamp,
consentDocument,
location,
hardwareId
) {
if (typeof consented !== 'boolean') {
mpInstance.Logger.error(
'Consented boolean is required when constructing a GDPR Consent object.'
);
return null;
}
if (timestamp && isNaN(timestamp)) {
mpInstance.Logger.error(
'Timestamp must be a valid number when constructing a GDPR Consent object.'
);
return null;
}
if (consentDocument && typeof consentDocument !== 'string') {
mpInstance.Logger.error(
'Document must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
if (location && typeof location !== 'string') {
mpInstance.Logger.error(
'Location must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
if (hardwareId && typeof hardwareId !== 'string') {
mpInstance.Logger.error(
'Hardware ID must be a valid string when constructing a GDPR Consent object.'
);
return null;
}
return {
Consented: consented,
Timestamp: timestamp || Date.now(),
ConsentDocument: consentDocument,
Location: location,
HardwareId: hardwareId,
};
};
}
var ConsentSerialization = {
toMinifiedJsonObject: function(state) {
var jsonObject = {};
if (state) {
var gdprConsentState = state.getGDPRConsentState();
if (gdprConsentState) {
jsonObject.gdpr = {};
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var gdprConsent = gdprConsentState[purpose];
jsonObject.gdpr[purpose] = {};
if (typeof gdprConsent.Consented === 'boolean') {
jsonObject.gdpr[purpose].c = gdprConsent.Consented;
this.ConsentSerialization = {
toMinifiedJsonObject: function(state) {
var jsonObject = {};
if (state) {
var gdprConsentState = state.getGDPRConsentState();
if (gdprConsentState) {
jsonObject.gdpr = {};
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var gdprConsent = gdprConsentState[purpose];
jsonObject.gdpr[purpose] = {};
if (typeof gdprConsent.Consented === 'boolean') {
jsonObject.gdpr[purpose].c =
gdprConsent.Consented;
}
if (typeof gdprConsent.Timestamp === 'number') {
jsonObject.gdpr[purpose].ts =
gdprConsent.Timestamp;
}
if (
typeof gdprConsent.ConsentDocument === 'string'
) {
jsonObject.gdpr[purpose].d =
gdprConsent.ConsentDocument;
}
if (typeof gdprConsent.Location === 'string') {
jsonObject.gdpr[purpose].l =
gdprConsent.Location;
}
if (typeof gdprConsent.HardwareId === 'string') {
jsonObject.gdpr[purpose].h =
gdprConsent.HardwareId;
}
}
if (typeof gdprConsent.Timestamp === 'number') {
jsonObject.gdpr[purpose].ts = gdprConsent.Timestamp;
}
if (typeof gdprConsent.ConsentDocument === 'string') {
jsonObject.gdpr[purpose].d =
gdprConsent.ConsentDocument;
}
if (typeof gdprConsent.Location === 'string') {
jsonObject.gdpr[purpose].l = gdprConsent.Location;
}
if (typeof gdprConsent.HardwareId === 'string') {
jsonObject.gdpr[purpose].h = gdprConsent.HardwareId;
}
}
}
}
}
return jsonObject;
},
return jsonObject;
},
fromMinifiedJsonObject: function(json) {
var state = createConsentState();
if (json.gdpr) {
for (var purpose in json.gdpr) {
if (json.gdpr.hasOwnProperty(purpose)) {
var gdprConsent = createGDPRConsent(
json.gdpr[purpose].c,
json.gdpr[purpose].ts,
json.gdpr[purpose].d,
json.gdpr[purpose].l,
json.gdpr[purpose].h
);
state.addGDPRConsentState(purpose, gdprConsent);
fromMinifiedJsonObject: function(json) {
var state = self.createConsentState();
if (json.gdpr) {
for (var purpose in json.gdpr) {
if (json.gdpr.hasOwnProperty(purpose)) {
var gdprConsent = self.createGDPRConsent(
json.gdpr[purpose].c,
json.gdpr[purpose].ts,
json.gdpr[purpose].d,
json.gdpr[purpose].l,
json.gdpr[purpose].h
);
state.addGDPRConsentState(purpose, gdprConsent);
}
}
}
}
return state;
},
};
return state;
},
};
function createConsentState(consentState) {
var gdpr = {};
this.createConsentState = function(consentState) {
var gdpr = {};
if (consentState) {
setGDPRConsentState(consentState.getGDPRConsentState());
}
if (consentState) {
setGDPRConsentState(consentState.getGDPRConsentState());
}
function canonicalizeForDeduplication(purpose) {
if (typeof purpose !== 'string') {
return null;
function canonicalizeForDeduplication(purpose) {
if (typeof purpose !== 'string') {
return null;
}
var trimmedPurpose = purpose.trim();
if (!trimmedPurpose.length) {
return null;
}
return trimmedPurpose.toLowerCase();
}
var trimmedPurpose = purpose.trim();
if (!trimmedPurpose.length) {
return null;
}
return trimmedPurpose.toLowerCase();
}
function setGDPRConsentState(gdprConsentState) {
if (!gdprConsentState) {
gdpr = {};
} else if (Helpers.isObject(gdprConsentState)) {
gdpr = {};
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
addGDPRConsentState(purpose, gdprConsentState[purpose]);
function setGDPRConsentState(gdprConsentState) {
if (!gdprConsentState) {
gdpr = {};
} else if (mpInstance._Helpers.isObject(gdprConsentState)) {
gdpr = {};
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
addGDPRConsentState(purpose, gdprConsentState[purpose]);
}
}
}
return this;
}
return this;
}
function addGDPRConsentState(purpose, gdprConsent) {
var normalizedPurpose = canonicalizeForDeduplication(purpose);
if (!normalizedPurpose) {
mParticle.Logger.error(
'addGDPRConsentState() invoked with bad purpose. Purpose must be a string.'
function addGDPRConsentState(purpose, gdprConsent) {
var normalizedPurpose = canonicalizeForDeduplication(purpose);
if (!normalizedPurpose) {
mpInstance.Logger.error(
'addGDPRConsentState() invoked with bad purpose. Purpose must be a string.'
);
return this;
}
if (!mpInstance._Helpers.isObject(gdprConsent)) {
mpInstance.Logger.error(
'addGDPRConsentState() invoked with bad or empty GDPR consent object.'
);
return this;
}
var gdprConsentCopy = self.createGDPRConsent(
gdprConsent.Consented,
gdprConsent.Timestamp,
gdprConsent.ConsentDocument,
gdprConsent.Location,
gdprConsent.HardwareId
);
if (gdprConsentCopy) {
gdpr[normalizedPurpose] = gdprConsentCopy;
}
return this;
}
if (!Helpers.isObject(gdprConsent)) {
mParticle.Logger.error(
'addGDPRConsentState() invoked with bad or empty GDPR consent object.'
);
function removeGDPRConsentState(purpose) {
var normalizedPurpose = canonicalizeForDeduplication(purpose);
if (!normalizedPurpose) {
return this;
}
delete gdpr[normalizedPurpose];
return this;
}
var gdprConsentCopy = createGDPRConsent(
gdprConsent.Consented,
gdprConsent.Timestamp,
gdprConsent.ConsentDocument,
gdprConsent.Location,
gdprConsent.HardwareId
);
if (gdprConsentCopy) {
gdpr[normalizedPurpose] = gdprConsentCopy;
}
return this;
}
function removeGDPRConsentState(purpose) {
var normalizedPurpose = canonicalizeForDeduplication(purpose);
if (!normalizedPurpose) {
return this;
function getGDPRConsentState() {
return mpInstance._Helpers.extend({}, gdpr);
}
delete gdpr[normalizedPurpose];
return this;
}
function getGDPRConsentState() {
return Helpers.extend({}, gdpr);
}
return {
setGDPRConsentState: setGDPRConsentState,
addGDPRConsentState: addGDPRConsentState,
getGDPRConsentState: getGDPRConsentState,
removeGDPRConsentState: removeGDPRConsentState,
return {
setGDPRConsentState: setGDPRConsentState,
addGDPRConsentState: addGDPRConsentState,
getGDPRConsentState: getGDPRConsentState,
removeGDPRConsentState: removeGDPRConsentState,
};
};
}
export default {
createGDPRConsent: createGDPRConsent,
Serialization: ConsentSerialization,
createConsentState: createConsentState,
};
var Constants = {
sdkVersion: '2.9.16',
sdkVersion: '2.10.0',
sdkVendor: 'mparticle',

@@ -163,4 +163,5 @@ platform: 'web',

},
DefaultInstance: 'default_instance',
};
export default Constants;
import Constants from './constants';
import Persistence from './persistence';
var Messages = Constants.Messages;
var cookieSyncManager = {
attemptCookieSync: function(previousMPID, mpid) {
export default function cookieSyncManager(mpInstance) {
var self = this;
this.attemptCookieSync = function(previousMPID, mpid) {
var pixelConfig, lastSyncDateForModule, url, redirect, urlWithRedirect;
if (mpid && !mParticle.Store.webviewBridgeEnabled) {
mParticle.Store.pixelConfigurations.forEach(function(
if (mpid && !mpInstance._Store.webviewBridgeEnabled) {
mpInstance._Store.pixelConfigurations.forEach(function(
pixelSettings

@@ -16,21 +16,14 @@ ) {

frequencyCap: pixelSettings.frequencyCap,
pixelUrl: cookieSyncManager.replaceAmp(
pixelSettings.pixelUrl
),
pixelUrl: self.replaceAmp(pixelSettings.pixelUrl),
redirectUrl: pixelSettings.redirectUrl
? cookieSyncManager.replaceAmp(
pixelSettings.redirectUrl
)
? self.replaceAmp(pixelSettings.redirectUrl)
: null,
};
url = cookieSyncManager.replaceMPID(pixelConfig.pixelUrl, mpid);
url = self.replaceMPID(pixelConfig.pixelUrl, mpid);
redirect = pixelConfig.redirectUrl
? cookieSyncManager.replaceMPID(
pixelConfig.redirectUrl,
mpid
)
? self.replaceMPID(pixelConfig.redirectUrl, mpid)
: '';
urlWithRedirect = url + encodeURIComponent(redirect);
var cookies = Persistence.getPersistence();
var cookies = mpInstance._Persistence.getPersistence();

@@ -42,3 +35,3 @@ if (previousMPID && previousMPID !== mpid) {

}
performCookieSync(
self.performCookieSync(
urlWithRedirect,

@@ -73,3 +66,3 @@ pixelConfig.moduleId,

) {
performCookieSync(
self.performCookieSync(
urlWithRedirect,

@@ -82,3 +75,3 @@ pixelConfig.moduleId,

} else {
performCookieSync(
self.performCookieSync(
urlWithRedirect,

@@ -94,23 +87,24 @@ pixelConfig.moduleId,

}
},
};
replaceMPID: function(string, mpid) {
this.replaceMPID = function(string, mpid) {
return string.replace('%%mpid%%', mpid);
},
};
replaceAmp: function(string) {
this.replaceAmp = function(string) {
return string.replace(/&amp;/g, '&');
},
};
};
function performCookieSync(url, moduleId, mpid, cookieSyncDates) {
var img = document.createElement('img');
this.performCookieSync = function(url, moduleId, mpid, cookieSyncDates) {
var img = document.createElement('img');
mParticle.Logger.verbose(Messages.InformationMessages.CookieSync);
mpInstance.Logger.verbose(Messages.InformationMessages.CookieSync);
img.src = url;
cookieSyncDates[moduleId.toString()] = new Date().getTime();
Persistence.saveUserCookieSyncDatesToCookies(mpid, cookieSyncDates);
img.src = url;
cookieSyncDates[moduleId.toString()] = new Date().getTime();
mpInstance._Persistence.saveUserCookieSyncDatesToCookies(
mpid,
cookieSyncDates
);
};
}
export default cookieSyncManager;
import Types from './types';
import Helpers from './helpers';
import Constants from './constants';
import ServerModel from './serverModel';
var Validators = Helpers.Validators,
Messages = Constants.Messages;
var Messages = Constants.Messages;
function convertTransactionAttributesToProductAction(
transactionAttributes,
productAction
) {
productAction.TransactionId = transactionAttributes.Id;
productAction.Affiliation = transactionAttributes.Affiliation;
productAction.CouponCode = transactionAttributes.CouponCode;
productAction.TotalAmount = transactionAttributes.Revenue;
productAction.ShippingAmount = transactionAttributes.Shipping;
productAction.TaxAmount = transactionAttributes.Tax;
}
export default function Ecommerce(mpInstance) {
var self = this;
this.convertTransactionAttributesToProductAction = function(
transactionAttributes,
productAction
) {
productAction.TransactionId = transactionAttributes.Id;
productAction.Affiliation = transactionAttributes.Affiliation;
productAction.CouponCode = transactionAttributes.CouponCode;
productAction.TotalAmount = transactionAttributes.Revenue;
productAction.ShippingAmount = transactionAttributes.Shipping;
productAction.TaxAmount = transactionAttributes.Tax;
};
function getProductActionEventName(productActionType) {
switch (productActionType) {
case Types.ProductActionType.AddToCart:
return 'AddToCart';
case Types.ProductActionType.AddToWishlist:
return 'AddToWishlist';
case Types.ProductActionType.Checkout:
return 'Checkout';
case Types.ProductActionType.CheckoutOption:
return 'CheckoutOption';
case Types.ProductActionType.Click:
return 'Click';
case Types.ProductActionType.Purchase:
return 'Purchase';
case Types.ProductActionType.Refund:
return 'Refund';
case Types.ProductActionType.RemoveFromCart:
return 'RemoveFromCart';
case Types.ProductActionType.RemoveFromWishlist:
return 'RemoveFromWishlist';
case Types.ProductActionType.ViewDetail:
return 'ViewDetail';
case Types.ProductActionType.Unknown:
default:
return 'Unknown';
}
}
this.getProductActionEventName = function(productActionType) {
switch (productActionType) {
case Types.ProductActionType.AddToCart:
return 'AddToCart';
case Types.ProductActionType.AddToWishlist:
return 'AddToWishlist';
case Types.ProductActionType.Checkout:
return 'Checkout';
case Types.ProductActionType.CheckoutOption:
return 'CheckoutOption';
case Types.ProductActionType.Click:
return 'Click';
case Types.ProductActionType.Purchase:
return 'Purchase';
case Types.ProductActionType.Refund:
return 'Refund';
case Types.ProductActionType.RemoveFromCart:
return 'RemoveFromCart';
case Types.ProductActionType.RemoveFromWishlist:
return 'RemoveFromWishlist';
case Types.ProductActionType.ViewDetail:
return 'ViewDetail';
case Types.ProductActionType.Unknown:
default:
return 'Unknown';
}
};
function getPromotionActionEventName(promotionActionType) {
switch (promotionActionType) {
case Types.PromotionActionType.PromotionClick:
return 'PromotionClick';
case Types.PromotionActionType.PromotionView:
return 'PromotionView';
default:
return 'Unknown';
}
}
this.getPromotionActionEventName = function(promotionActionType) {
switch (promotionActionType) {
case Types.PromotionActionType.PromotionClick:
return 'PromotionClick';
case Types.PromotionActionType.PromotionView:
return 'PromotionView';
default:
return 'Unknown';
}
};
function convertProductActionToEventType(productActionType) {
switch (productActionType) {
case Types.ProductActionType.AddToCart:
return Types.CommerceEventType.ProductAddToCart;
case Types.ProductActionType.AddToWishlist:
return Types.CommerceEventType.ProductAddToWishlist;
case Types.ProductActionType.Checkout:
return Types.CommerceEventType.ProductCheckout;
case Types.ProductActionType.CheckoutOption:
return Types.CommerceEventType.ProductCheckoutOption;
case Types.ProductActionType.Click:
return Types.CommerceEventType.ProductClick;
case Types.ProductActionType.Purchase:
return Types.CommerceEventType.ProductPurchase;
case Types.ProductActionType.Refund:
return Types.CommerceEventType.ProductRefund;
case Types.ProductActionType.RemoveFromCart:
return Types.CommerceEventType.ProductRemoveFromCart;
case Types.ProductActionType.RemoveFromWishlist:
return Types.CommerceEventType.ProductRemoveFromWishlist;
case Types.ProductActionType.Unknown:
return Types.EventType.Unknown;
case Types.ProductActionType.ViewDetail:
return Types.CommerceEventType.ProductViewDetail;
default:
mParticle.Logger.error(
'Could not convert product action type ' +
productActionType +
' to event type'
);
return null;
}
}
this.convertProductActionToEventType = function(productActionType) {
switch (productActionType) {
case Types.ProductActionType.AddToCart:
return Types.CommerceEventType.ProductAddToCart;
case Types.ProductActionType.AddToWishlist:
return Types.CommerceEventType.ProductAddToWishlist;
case Types.ProductActionType.Checkout:
return Types.CommerceEventType.ProductCheckout;
case Types.ProductActionType.CheckoutOption:
return Types.CommerceEventType.ProductCheckoutOption;
case Types.ProductActionType.Click:
return Types.CommerceEventType.ProductClick;
case Types.ProductActionType.Purchase:
return Types.CommerceEventType.ProductPurchase;
case Types.ProductActionType.Refund:
return Types.CommerceEventType.ProductRefund;
case Types.ProductActionType.RemoveFromCart:
return Types.CommerceEventType.ProductRemoveFromCart;
case Types.ProductActionType.RemoveFromWishlist:
return Types.CommerceEventType.ProductRemoveFromWishlist;
case Types.ProductActionType.Unknown:
return Types.EventType.Unknown;
case Types.ProductActionType.ViewDetail:
return Types.CommerceEventType.ProductViewDetail;
default:
mpInstance.Logger.error(
'Could not convert product action type ' +
productActionType +
' to event type'
);
return null;
}
};
function convertPromotionActionToEventType(promotionActionType) {
switch (promotionActionType) {
case Types.PromotionActionType.PromotionClick:
return Types.CommerceEventType.PromotionClick;
case Types.PromotionActionType.PromotionView:
return Types.CommerceEventType.PromotionView;
default:
mParticle.Logger.error(
'Could not convert promotion action type ' +
promotionActionType +
' to event type'
);
return null;
}
}
this.convertPromotionActionToEventType = function(promotionActionType) {
switch (promotionActionType) {
case Types.PromotionActionType.PromotionClick:
return Types.CommerceEventType.PromotionClick;
case Types.PromotionActionType.PromotionView:
return Types.CommerceEventType.PromotionView;
default:
mpInstance.Logger.error(
'Could not convert promotion action type ' +
promotionActionType +
' to event type'
);
return null;
}
};
function generateExpandedEcommerceName(eventName, plusOne) {
return 'eCommerce - ' + eventName + ' - ' + (plusOne ? 'Total' : 'Item');
}
this.generateExpandedEcommerceName = function(eventName, plusOne) {
return (
'eCommerce - ' + eventName + ' - ' + (plusOne ? 'Total' : 'Item')
);
};
function extractProductAttributes(attributes, product) {
if (product.CouponCode) {
attributes['Coupon Code'] = product.CouponCode;
}
if (product.Brand) {
attributes['Brand'] = product.Brand;
}
if (product.Category) {
attributes['Category'] = product.Category;
}
if (product.Name) {
attributes['Name'] = product.Name;
}
if (product.Sku) {
attributes['Id'] = product.Sku;
}
if (product.Price) {
attributes['Item Price'] = product.Price;
}
if (product.Quantity) {
attributes['Quantity'] = product.Quantity;
}
if (product.Position) {
attributes['Position'] = product.Position;
}
if (product.Variant) {
attributes['Variant'] = product.Variant;
}
attributes['Total Product Amount'] = product.TotalAmount || 0;
}
this.extractProductAttributes = function(attributes, product) {
if (product.CouponCode) {
attributes['Coupon Code'] = product.CouponCode;
}
if (product.Brand) {
attributes['Brand'] = product.Brand;
}
if (product.Category) {
attributes['Category'] = product.Category;
}
if (product.Name) {
attributes['Name'] = product.Name;
}
if (product.Sku) {
attributes['Id'] = product.Sku;
}
if (product.Price) {
attributes['Item Price'] = product.Price;
}
if (product.Quantity) {
attributes['Quantity'] = product.Quantity;
}
if (product.Position) {
attributes['Position'] = product.Position;
}
if (product.Variant) {
attributes['Variant'] = product.Variant;
}
attributes['Total Product Amount'] = product.TotalAmount || 0;
};
function extractTransactionId(attributes, productAction) {
if (productAction.TransactionId) {
attributes['Transaction Id'] = productAction.TransactionId;
}
}
this.extractTransactionId = function(attributes, productAction) {
if (productAction.TransactionId) {
attributes['Transaction Id'] = productAction.TransactionId;
}
};
function extractActionAttributes(attributes, productAction) {
extractTransactionId(attributes, productAction);
this.extractActionAttributes = function(attributes, productAction) {
self.extractTransactionId(attributes, productAction);
if (productAction.Affiliation) {
attributes['Affiliation'] = productAction.Affiliation;
}
if (productAction.Affiliation) {
attributes['Affiliation'] = productAction.Affiliation;
}
if (productAction.CouponCode) {
attributes['Coupon Code'] = productAction.CouponCode;
}
if (productAction.CouponCode) {
attributes['Coupon Code'] = productAction.CouponCode;
}
if (productAction.TotalAmount) {
attributes['Total Amount'] = productAction.TotalAmount;
}
if (productAction.TotalAmount) {
attributes['Total Amount'] = productAction.TotalAmount;
}
if (productAction.ShippingAmount) {
attributes['Shipping Amount'] = productAction.ShippingAmount;
}
if (productAction.ShippingAmount) {
attributes['Shipping Amount'] = productAction.ShippingAmount;
}
if (productAction.TaxAmount) {
attributes['Tax Amount'] = productAction.TaxAmount;
}
if (productAction.TaxAmount) {
attributes['Tax Amount'] = productAction.TaxAmount;
}
if (productAction.CheckoutOptions) {
attributes['Checkout Options'] = productAction.CheckoutOptions;
}
if (productAction.CheckoutOptions) {
attributes['Checkout Options'] = productAction.CheckoutOptions;
}
if (productAction.CheckoutStep) {
attributes['Checkout Step'] = productAction.CheckoutStep;
}
}
if (productAction.CheckoutStep) {
attributes['Checkout Step'] = productAction.CheckoutStep;
}
};
function extractPromotionAttributes(attributes, promotion) {
if (promotion.Id) {
attributes['Id'] = promotion.Id;
}
this.extractPromotionAttributes = function(attributes, promotion) {
if (promotion.Id) {
attributes['Id'] = promotion.Id;
}
if (promotion.Creative) {
attributes['Creative'] = promotion.Creative;
}
if (promotion.Creative) {
attributes['Creative'] = promotion.Creative;
}
if (promotion.Name) {
attributes['Name'] = promotion.Name;
}
if (promotion.Name) {
attributes['Name'] = promotion.Name;
}
if (promotion.Position) {
attributes['Position'] = promotion.Position;
}
}
if (promotion.Position) {
attributes['Position'] = promotion.Position;
}
};
function buildProductList(event, product) {
if (product) {
if (Array.isArray(product)) {
return product;
this.buildProductList = function(event, product) {
if (product) {
if (Array.isArray(product)) {
return product;
}
return [product];
}
return [product];
}
return event.ShoppingCart.ProductList;
};
return event.ShoppingCart.ProductList;
}
this.createProduct = function(
name,
sku,
price,
quantity,
variant,
category,
brand,
position,
couponCode,
attributes
) {
attributes = mpInstance._Helpers.sanitizeAttributes(attributes);
function createProduct(
name,
sku,
price,
quantity,
variant,
category,
brand,
position,
couponCode,
attributes
) {
attributes = Helpers.sanitizeAttributes(attributes);
if (typeof name !== 'string') {
mpInstance.Logger.error('Name is required when creating a product');
return null;
}
if (typeof name !== 'string') {
mParticle.Logger.error('Name is required when creating a product');
return null;
}
if (!mpInstance._Helpers.Validators.isStringOrNumber(sku)) {
mpInstance.Logger.error(
'SKU is required when creating a product, and must be a string or a number'
);
return null;
}
if (!Validators.isStringOrNumber(sku)) {
mParticle.Logger.error(
'SKU is required when creating a product, and must be a string or a number'
);
return null;
}
if (!mpInstance._Helpers.Validators.isStringOrNumber(price)) {
mpInstance.Logger.error(
'Price is required when creating a product, and must be a string or a number'
);
return null;
}
if (!Validators.isStringOrNumber(price)) {
mParticle.Logger.error(
'Price is required when creating a product, and must be a string or a number'
);
return null;
}
if (position && !mpInstance._Helpers.Validators.isNumber(position)) {
mpInstance.Logger.error(
'Position must be a number, it will be set to null.'
);
position = null;
}
if (position && !Validators.isNumber(position)) {
mParticle.Logger.error(
'Position must be a number, it will be set to null.'
);
position = null;
}
if (!quantity) {
quantity = 1;
}
if (!quantity) {
quantity = 1;
}
return {
Name: name,
Sku: sku,
Price: price,
Quantity: quantity,
Brand: brand,
Variant: variant,
Category: category,
Position: position,
CouponCode: couponCode,
TotalAmount: quantity * price,
Attributes: attributes,
return {
Name: name,
Sku: sku,
Price: price,
Quantity: quantity,
Brand: brand,
Variant: variant,
Category: category,
Position: position,
CouponCode: couponCode,
TotalAmount: quantity * price,
Attributes: attributes,
};
};
}
function createPromotion(id, creative, name, position) {
if (!Validators.isStringOrNumber(id)) {
mParticle.Logger.error(Messages.ErrorMessages.PromotionIdRequired);
return null;
}
this.createPromotion = function(id, creative, name, position) {
if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) {
mpInstance.Logger.error(Messages.ErrorMessages.PromotionIdRequired);
return null;
}
return {
Id: id,
Creative: creative,
Name: name,
Position: position,
return {
Id: id,
Creative: creative,
Name: name,
Position: position,
};
};
}
function createImpression(name, product) {
if (typeof name !== 'string') {
mParticle.Logger.error('Name is required when creating an impression.');
return null;
}
this.createImpression = function(name, product) {
if (typeof name !== 'string') {
mpInstance.Logger.error(
'Name is required when creating an impression.'
);
return null;
}
if (!product) {
mParticle.Logger.error(
'Product is required when creating an impression.'
);
return null;
}
if (!product) {
mpInstance.Logger.error(
'Product is required when creating an impression.'
);
return null;
}
return {
Name: name,
Product: product,
return {
Name: name,
Product: product,
};
};
}
function createTransactionAttributes(
id,
affiliation,
couponCode,
revenue,
shipping,
tax
) {
if (!Validators.isStringOrNumber(id)) {
mParticle.Logger.error(Messages.ErrorMessages.TransactionIdRequired);
return null;
}
this.createTransactionAttributes = function(
id,
affiliation,
couponCode,
revenue,
shipping,
tax
) {
if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) {
mpInstance.Logger.error(
Messages.ErrorMessages.TransactionIdRequired
);
return null;
}
return {
Id: id,
Affiliation: affiliation,
CouponCode: couponCode,
Revenue: revenue,
Shipping: shipping,
Tax: tax,
return {
Id: id,
Affiliation: affiliation,
CouponCode: couponCode,
Revenue: revenue,
Shipping: shipping,
Tax: tax,
};
};
}
function expandProductImpression(commerceEvent) {
var appEvents = [];
if (!commerceEvent.ProductImpressions) {
return appEvents;
}
commerceEvent.ProductImpressions.forEach(function(productImpression) {
if (productImpression.ProductList) {
productImpression.ProductList.forEach(function(product) {
var attributes = Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
if (product.Attributes) {
for (var attribute in product.Attributes) {
attributes[attribute] = product.Attributes[attribute];
this.expandProductImpression = function(commerceEvent) {
var appEvents = [];
if (!commerceEvent.ProductImpressions) {
return appEvents;
}
commerceEvent.ProductImpressions.forEach(function(productImpression) {
if (productImpression.ProductList) {
productImpression.ProductList.forEach(function(product) {
var attributes = mpInstance._Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
if (product.Attributes) {
for (var attribute in product.Attributes) {
attributes[attribute] =
product.Attributes[attribute];
}
}
}
extractProductAttributes(attributes, product);
if (productImpression.ProductImpressionList) {
attributes['Product Impression List'] =
productImpression.ProductImpressionList;
}
var appEvent = ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName('Impression'),
data: attributes,
eventType: Types.EventType.Transaction,
self.extractProductAttributes(attributes, product);
if (productImpression.ProductImpressionList) {
attributes['Product Impression List'] =
productImpression.ProductImpressionList;
}
var appEvent = mpInstance._ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: self.generateExpandedEcommerceName('Impression'),
data: attributes,
eventType: Types.EventType.Transaction,
});
appEvents.push(appEvent);
});
appEvents.push(appEvent);
});
}
});
}
});
return appEvents;
}
function expandCommerceEvent(event) {
if (!event) {
return null;
}
return expandProductAction(event)
.concat(expandPromotionAction(event))
.concat(expandProductImpression(event));
}
function expandPromotionAction(commerceEvent) {
var appEvents = [];
if (!commerceEvent.PromotionAction) {
return appEvents;
}
var promotions = commerceEvent.PromotionAction.PromotionList;
promotions.forEach(function(promotion) {
var attributes = Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
extractPromotionAttributes(attributes, promotion);
};
var appEvent = ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName(
Types.PromotionActionType.getExpansionName(
commerceEvent.PromotionAction.PromotionActionType
)
),
data: attributes,
eventType: Types.EventType.Transaction,
});
appEvents.push(appEvent);
});
return appEvents;
}
this.expandCommerceEvent = function(event) {
if (!event) {
return null;
}
return self
.expandProductAction(event)
.concat(self.expandPromotionAction(event))
.concat(self.expandProductImpression(event));
};
function expandProductAction(commerceEvent) {
var appEvents = [];
if (!commerceEvent.ProductAction) {
return appEvents;
}
var shouldExtractActionAttributes = false;
if (
commerceEvent.ProductAction.ProductActionType ===
Types.ProductActionType.Purchase ||
commerceEvent.ProductAction.ProductActionType ===
Types.ProductActionType.Refund
) {
var attributes = Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
attributes['Product Count'] = commerceEvent.ProductAction.ProductList
? commerceEvent.ProductAction.ProductList.length
: 0;
extractActionAttributes(attributes, commerceEvent.ProductAction);
if (commerceEvent.CurrencyCode) {
attributes['Currency Code'] = commerceEvent.CurrencyCode;
this.expandPromotionAction = function(commerceEvent) {
var appEvents = [];
if (!commerceEvent.PromotionAction) {
return appEvents;
}
var plusOneEvent = ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName(
Types.ProductActionType.getExpansionName(
commerceEvent.ProductAction.ProductActionType
var promotions = commerceEvent.PromotionAction.PromotionList;
promotions.forEach(function(promotion) {
var attributes = mpInstance._Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
self.extractPromotionAttributes(attributes, promotion);
var appEvent = mpInstance._ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: self.generateExpandedEcommerceName(
Types.PromotionActionType.getExpansionName(
commerceEvent.PromotionAction.PromotionActionType
)
),
true
),
data: attributes,
eventType: Types.EventType.Transaction,
data: attributes,
eventType: Types.EventType.Transaction,
});
appEvents.push(appEvent);
});
appEvents.push(plusOneEvent);
} else {
shouldExtractActionAttributes = true;
}
var products = commerceEvent.ProductAction.ProductList;
if (!products) {
return appEvents;
}
};
products.forEach(function(product) {
var attributes = Helpers.extend(
false,
commerceEvent.EventAttributes,
product.Attributes
);
if (shouldExtractActionAttributes) {
extractActionAttributes(attributes, commerceEvent.ProductAction);
this.expandProductAction = function(commerceEvent) {
var appEvents = [];
if (!commerceEvent.ProductAction) {
return appEvents;
}
var shouldExtractActionAttributes = false;
if (
commerceEvent.ProductAction.ProductActionType ===
Types.ProductActionType.Purchase ||
commerceEvent.ProductAction.ProductActionType ===
Types.ProductActionType.Refund
) {
var attributes = mpInstance._Helpers.extend(
false,
{},
commerceEvent.EventAttributes
);
attributes['Product Count'] = commerceEvent.ProductAction
.ProductList
? commerceEvent.ProductAction.ProductList.length
: 0;
self.extractActionAttributes(
attributes,
commerceEvent.ProductAction
);
if (commerceEvent.CurrencyCode) {
attributes['Currency Code'] = commerceEvent.CurrencyCode;
}
var plusOneEvent = mpInstance._ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: self.generateExpandedEcommerceName(
Types.ProductActionType.getExpansionName(
commerceEvent.ProductAction.ProductActionType
),
true
),
data: attributes,
eventType: Types.EventType.Transaction,
});
appEvents.push(plusOneEvent);
} else {
extractTransactionId(attributes, commerceEvent.ProductAction);
shouldExtractActionAttributes = true;
}
extractProductAttributes(attributes, product);
var productEvent = ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: generateExpandedEcommerceName(
Types.ProductActionType.getExpansionName(
commerceEvent.ProductAction.ProductActionType
)
),
data: attributes,
eventType: Types.EventType.Transaction,
var products = commerceEvent.ProductAction.ProductList;
if (!products) {
return appEvents;
}
products.forEach(function(product) {
var attributes = mpInstance._Helpers.extend(
false,
commerceEvent.EventAttributes,
product.Attributes
);
if (shouldExtractActionAttributes) {
self.extractActionAttributes(
attributes,
commerceEvent.ProductAction
);
} else {
self.extractTransactionId(
attributes,
commerceEvent.ProductAction
);
}
self.extractProductAttributes(attributes, product);
var productEvent = mpInstance._ServerModel.createEventObject({
messageType: Types.MessageType.PageEvent,
name: self.generateExpandedEcommerceName(
Types.ProductActionType.getExpansionName(
commerceEvent.ProductAction.ProductActionType
)
),
data: attributes,
eventType: Types.EventType.Transaction,
});
appEvents.push(productEvent);
});
appEvents.push(productEvent);
});
return appEvents;
}
return appEvents;
};
function createCommerceEventObject(customFlags) {
var baseEvent,
currentUser = mParticle.Identity.getCurrentUser();
this.createCommerceEventObject = function(customFlags) {
var baseEvent,
currentUser = mpInstance.Identity.getCurrentUser();
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogCommerceEvent
);
mpInstance.Logger.verbose(
Messages.InformationMessages.StartingLogCommerceEvent
);
if (Helpers.canLog()) {
baseEvent = ServerModel.createEventObject({
messageType: Types.MessageType.Commerce,
});
baseEvent.EventName = 'eCommerce - ';
baseEvent.CurrencyCode = mParticle.Store.currencyCode;
baseEvent.ShoppingCart = {
ProductList: currentUser
? currentUser.getCart().getCartProducts()
: [],
};
baseEvent.CustomFlags = customFlags;
if (mpInstance._Helpers.canLog()) {
baseEvent = mpInstance._ServerModel.createEventObject({
messageType: Types.MessageType.Commerce,
});
baseEvent.EventName = 'eCommerce - ';
baseEvent.CurrencyCode = mpInstance._Store.currencyCode;
baseEvent.ShoppingCart = {
ProductList: currentUser
? currentUser.getCart().getCartProducts()
: [],
};
baseEvent.CustomFlags = customFlags;
return baseEvent;
} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
}
return baseEvent;
} else {
mpInstance.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
return null;
return null;
};
}
export default {
convertTransactionAttributesToProductAction: convertTransactionAttributesToProductAction,
getProductActionEventName: getProductActionEventName,
getPromotionActionEventName: getPromotionActionEventName,
convertProductActionToEventType: convertProductActionToEventType,
convertPromotionActionToEventType: convertPromotionActionToEventType,
buildProductList: buildProductList,
createProduct: createProduct,
createPromotion: createPromotion,
createImpression: createImpression,
createTransactionAttributes: createTransactionAttributes,
expandCommerceEvent: expandCommerceEvent,
createCommerceEventObject: createCommerceEventObject,
};
import Types from './types';
import Constants from './constants';
import Helpers from './helpers';
import Ecommerce from './ecommerce';
import ServerModel from './serverModel';
import Persistence from './persistence';
import ApiClient from './apiClient';
var Messages = Constants.Messages,
sendEventToServer = ApiClient.sendEventToServer;
var Messages = Constants.Messages;
function logEvent(event) {
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogEvent + ': ' + event.name
);
if (Helpers.canLog()) {
if (event.data) {
event.data = Helpers.sanitizeAttributes(event.data);
export default function Events(mpInstance) {
var self = this;
this.logEvent = function(event) {
mpInstance.Logger.verbose(
Messages.InformationMessages.StartingLogEvent + ': ' + event.name
);
if (mpInstance._Helpers.canLog()) {
if (event.data) {
event.data = mpInstance._Helpers.sanitizeAttributes(event.data);
}
var uploadObject = mpInstance._ServerModel.createEventObject(event);
mpInstance._APIClient.sendEventToServer(uploadObject);
} else {
mpInstance.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
var uploadObject = ServerModel.createEventObject(event);
sendEventToServer(uploadObject);
} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
}
}
};
function startTracking(callback) {
if (!mParticle.Store.isTracking) {
if ('geolocation' in navigator) {
mParticle.Store.watchPositionId = navigator.geolocation.watchPosition(
successTracking,
errorTracking
);
this.startTracking = function(callback) {
if (!mpInstance._Store.isTracking) {
if ('geolocation' in navigator) {
mpInstance._Store.watchPositionId = navigator.geolocation.watchPosition(
successTracking,
errorTracking
);
}
} else {
var position = {
coords: {
latitude: mpInstance._Store.currentPosition.lat,
longitude: mpInstance._Store.currentPosition.lng,
},
};
triggerCallback(callback, position);
}
} else {
var position = {
coords: {
latitude: mParticle.Store.currentPosition.lat,
longitude: mParticle.Store.currentPosition.lng,
},
};
triggerCallback(callback, position);
}
function successTracking(position) {
mParticle.Store.currentPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
function successTracking(position) {
mpInstance._Store.currentPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
triggerCallback(callback, position);
// prevents callback from being fired multiple times
callback = null;
triggerCallback(callback, position);
// prevents callback from being fired multiple times
callback = null;
mParticle.Store.isTracking = true;
}
mpInstance._Store.isTracking = true;
}
function errorTracking() {
triggerCallback(callback);
// prevents callback from being fired multiple times
callback = null;
mParticle.Store.isTracking = false;
}
function errorTracking() {
triggerCallback(callback);
// prevents callback from being fired multiple times
callback = null;
mpInstance._Store.isTracking = false;
}
function triggerCallback(callback, position) {
if (callback) {
try {
if (position) {
callback(position);
} else {
callback();
function triggerCallback(callback, position) {
if (callback) {
try {
if (position) {
callback(position);
} else {
callback();
}
} catch (e) {
mpInstance.Logger.error(
'Error invoking the callback passed to startTrackingLocation.'
);
mpInstance.Logger.error(e);
}
} catch (e) {
mParticle.Logger.error(
'Error invoking the callback passed to startTrackingLocation.'
);
mParticle.Logger.error(e);
}
}
}
}
};
function stopTracking() {
if (mParticle.Store.isTracking) {
navigator.geolocation.clearWatch(mParticle.Store.watchPositionId);
mParticle.Store.currentPosition = null;
mParticle.Store.isTracking = false;
}
}
this.stopTracking = function() {
if (mpInstance._Store.isTracking) {
navigator.geolocation.clearWatch(mpInstance._Store.watchPositionId);
mpInstance._Store.currentPosition = null;
mpInstance._Store.isTracking = false;
}
};
function logOptOut() {
mParticle.Logger.verbose(Messages.InformationMessages.StartingLogOptOut);
this.logOptOut = function() {
mpInstance.Logger.verbose(
Messages.InformationMessages.StartingLogOptOut
);
var event = ServerModel.createEventObject({
messageType: Types.MessageType.OptOut,
eventType: Types.EventType.Other,
});
sendEventToServer(event);
}
var event = mpInstance._ServerModel.createEventObject({
messageType: Types.MessageType.OptOut,
eventType: Types.EventType.Other,
});
mpInstance._APIClient.sendEventToServer(event);
};
function logAST() {
logEvent({ messageType: Types.MessageType.AppStateTransition });
}
this.logAST = function() {
self.logEvent({ messageType: Types.MessageType.AppStateTransition });
};
function logCheckoutEvent(step, options, attrs, customFlags) {
var event = Ecommerce.createCommerceEventObject(customFlags);
if (event) {
event.EventName += Ecommerce.getProductActionEventName(
Types.ProductActionType.Checkout
this.logCheckoutEvent = function(step, options, attrs, customFlags) {
var event = mpInstance._Ecommerce.createCommerceEventObject(
customFlags
);
event.EventCategory = Types.CommerceEventType.ProductCheckout;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Checkout,
CheckoutStep: step,
CheckoutOptions: options,
ProductList: event.ShoppingCart.ProductList,
};
logCommerceEvent(event, attrs);
}
}
if (event) {
event.EventName += mpInstance._Ecommerce.getProductActionEventName(
Types.ProductActionType.Checkout
);
event.EventCategory = Types.CommerceEventType.ProductCheckout;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Checkout,
CheckoutStep: step,
CheckoutOptions: options,
ProductList: event.ShoppingCart.ProductList,
};
function logProductActionEvent(productActionType, product, attrs, customFlags) {
var event = Ecommerce.createCommerceEventObject(customFlags);
self.logCommerceEvent(event, attrs);
}
};
if (event) {
event.EventCategory = Ecommerce.convertProductActionToEventType(
productActionType
this.logProductActionEvent = function(
productActionType,
product,
attrs,
customFlags
) {
var event = mpInstance._Ecommerce.createCommerceEventObject(
customFlags
);
event.EventName += Ecommerce.getProductActionEventName(
productActionType
);
event.ProductAction = {
ProductActionType: productActionType,
ProductList: Array.isArray(product) ? product : [product],
};
logCommerceEvent(event, attrs);
}
}
if (event) {
event.EventCategory = mpInstance._Ecommerce.convertProductActionToEventType(
productActionType
);
event.EventName += mpInstance._Ecommerce.getProductActionEventName(
productActionType
);
event.ProductAction = {
ProductActionType: productActionType,
ProductList: Array.isArray(product) ? product : [product],
};
function logPurchaseEvent(transactionAttributes, product, attrs, customFlags) {
var event = Ecommerce.createCommerceEventObject(customFlags);
self.logCommerceEvent(event, attrs);
}
};
if (event) {
event.EventName += Ecommerce.getProductActionEventName(
Types.ProductActionType.Purchase
this.logPurchaseEvent = function(
transactionAttributes,
product,
attrs,
customFlags
) {
var event = mpInstance._Ecommerce.createCommerceEventObject(
customFlags
);
event.EventCategory = Types.CommerceEventType.ProductPurchase;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Purchase,
};
event.ProductAction.ProductList = Ecommerce.buildProductList(
event,
product
);
Ecommerce.convertTransactionAttributesToProductAction(
transactionAttributes,
event.ProductAction
);
if (event) {
event.EventName += mpInstance._Ecommerce.getProductActionEventName(
Types.ProductActionType.Purchase
);
event.EventCategory = Types.CommerceEventType.ProductPurchase;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Purchase,
};
event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(
event,
product
);
logCommerceEvent(event, attrs);
}
}
mpInstance._Ecommerce.convertTransactionAttributesToProductAction(
transactionAttributes,
event.ProductAction
);
function logRefundEvent(transactionAttributes, product, attrs, customFlags) {
if (!transactionAttributes) {
mParticle.Logger.error(Messages.ErrorMessages.TransactionRequired);
return;
}
self.logCommerceEvent(event, attrs);
}
};
var event = Ecommerce.createCommerceEventObject(customFlags);
this.logRefundEvent = function(
transactionAttributes,
product,
attrs,
customFlags
) {
if (!transactionAttributes) {
mpInstance.Logger.error(Messages.ErrorMessages.TransactionRequired);
return;
}
if (event) {
event.EventName += Ecommerce.getProductActionEventName(
Types.ProductActionType.Refund
var event = mpInstance._Ecommerce.createCommerceEventObject(
customFlags
);
event.EventCategory = Types.CommerceEventType.ProductRefund;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Refund,
};
event.ProductAction.ProductList = Ecommerce.buildProductList(
event,
product
);
Ecommerce.convertTransactionAttributesToProductAction(
transactionAttributes,
event.ProductAction
);
if (event) {
event.EventName += mpInstance._Ecommerce.getProductActionEventName(
Types.ProductActionType.Refund
);
event.EventCategory = Types.CommerceEventType.ProductRefund;
event.ProductAction = {
ProductActionType: Types.ProductActionType.Refund,
};
event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(
event,
product
);
logCommerceEvent(event, attrs);
}
}
mpInstance._Ecommerce.convertTransactionAttributesToProductAction(
transactionAttributes,
event.ProductAction
);
function logPromotionEvent(promotionType, promotion, attrs, customFlags) {
var event = Ecommerce.createCommerceEventObject(customFlags);
self.logCommerceEvent(event, attrs);
}
};
if (event) {
event.EventName += Ecommerce.getPromotionActionEventName(promotionType);
event.EventCategory = Ecommerce.convertPromotionActionToEventType(
promotionType
this.logPromotionEvent = function(
promotionType,
promotion,
attrs,
customFlags
) {
var event = mpInstance._Ecommerce.createCommerceEventObject(
customFlags
);
event.PromotionAction = {
PromotionActionType: promotionType,
PromotionList: [promotion],
};
logCommerceEvent(event, attrs);
}
}
if (event) {
event.EventName += mpInstance._Ecommerce.getPromotionActionEventName(
promotionType
);
event.EventCategory = mpInstance._Ecommerce.convertPromotionActionToEventType(
promotionType
);
event.PromotionAction = {
PromotionActionType: promotionType,
PromotionList: [promotion],
};
function logImpressionEvent(impression, attrs, customFlags) {
var event = Ecommerce.createCommerceEventObject(customFlags);
if (event) {
event.EventName += 'Impression';
event.EventCategory = Types.CommerceEventType.ProductImpression;
if (!Array.isArray(impression)) {
impression = [impression];
self.logCommerceEvent(event, attrs);
}
};
event.ProductImpressions = [];
this.logImpressionEvent = function(impression, attrs, customFlags) {
var event = mpInstance._Ecommerce.createCommerceEventObject(
customFlags
);
impression.forEach(function(impression) {
event.ProductImpressions.push({
ProductImpressionList: impression.Name,
ProductList: Array.isArray(impression.Product)
? impression.Product
: [impression.Product],
if (event) {
event.EventName += 'Impression';
event.EventCategory = Types.CommerceEventType.ProductImpression;
if (!Array.isArray(impression)) {
impression = [impression];
}
event.ProductImpressions = [];
impression.forEach(function(impression) {
event.ProductImpressions.push({
ProductImpressionList: impression.Name,
ProductList: Array.isArray(impression.Product)
? impression.Product
: [impression.Product],
});
});
});
logCommerceEvent(event, attrs);
}
}
self.logCommerceEvent(event, attrs);
}
};
function logCommerceEvent(commerceEvent, attrs) {
mParticle.Logger.verbose(
Messages.InformationMessages.StartingLogCommerceEvent
);
this.logCommerceEvent = function(commerceEvent, attrs) {
mpInstance.Logger.verbose(
Messages.InformationMessages.StartingLogCommerceEvent
);
attrs = Helpers.sanitizeAttributes(attrs);
attrs = mpInstance._Helpers.sanitizeAttributes(attrs);
if (Helpers.canLog()) {
if (mParticle.Store.webviewBridgeEnabled) {
// Don't send shopping cart to parent sdks
commerceEvent.ShoppingCart = {};
}
if (mpInstance._Helpers.canLog()) {
if (mpInstance._Store.webviewBridgeEnabled) {
// Don't send shopping cart to parent sdks
commerceEvent.ShoppingCart = {};
}
if (attrs) {
commerceEvent.EventAttributes = attrs;
if (attrs) {
commerceEvent.EventAttributes = attrs;
}
mpInstance._APIClient.sendEventToServer(commerceEvent);
mpInstance._Persistence.update();
} else {
mpInstance.Logger.verbose(
Messages.InformationMessages.AbandonLogEvent
);
}
};
sendEventToServer(commerceEvent);
Persistence.update();
} else {
mParticle.Logger.verbose(Messages.InformationMessages.AbandonLogEvent);
}
}
this.addEventHandler = function(
domEvent,
selector,
eventName,
data,
eventType
) {
var elements = [],
handler = function(e) {
var timeoutHandler = function() {
if (element.href) {
window.location.href = element.href;
} else if (element.submit) {
element.submit();
}
};
function addEventHandler(domEvent, selector, eventName, data, eventType) {
var elements = [],
handler = function(e) {
var timeoutHandler = function() {
if (element.href) {
window.location.href = element.href;
} else if (element.submit) {
element.submit();
}
};
mpInstance.Logger.verbose(
'DOM event triggered, handling event'
);
mParticle.Logger.verbose('DOM event triggered, handling event');
self.logEvent({
messageType: Types.MessageType.PageEvent,
name:
typeof eventName === 'function'
? eventName(element)
: eventName,
data: typeof data === 'function' ? data(element) : data,
eventType: eventType || Types.EventType.Other,
});
logEvent({
messageType: Types.MessageType.PageEvent,
name:
typeof eventName === 'function'
? eventName(element)
: eventName,
data: typeof data === 'function' ? data(element) : data,
eventType: eventType || Types.EventType.Other,
});
// TODO: Handle middle-clicks and special keys (ctrl, alt, etc)
if (
(element.href && element.target !== '_blank') ||
element.submit
) {
// Give xmlhttprequest enough time to execute before navigating a link or submitting form
// TODO: Handle middle-clicks and special keys (ctrl, alt, etc)
if (
(element.href && element.target !== '_blank') ||
element.submit
) {
// Give xmlhttprequest enough time to execute before navigating a link or submitting form
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
setTimeout(
timeoutHandler,
mpInstance._Store.SDKConfig.timeout
);
}
},
element,
i;
setTimeout(timeoutHandler, mParticle.Store.SDKConfig.timeout);
}
},
element,
i;
if (!selector) {
mpInstance.Logger.error("Can't bind event, selector is required");
return;
}
if (!selector) {
mParticle.Logger.error("Can't bind event, selector is required");
return;
}
// Handle a css selector string or a dom element
if (typeof selector === 'string') {
elements = document.querySelectorAll(selector);
} else if (selector.nodeType) {
elements = [selector];
}
// Handle a css selector string or a dom element
if (typeof selector === 'string') {
elements = document.querySelectorAll(selector);
} else if (selector.nodeType) {
elements = [selector];
}
if (elements.length) {
mpInstance.Logger.verbose(
'Found ' +
elements.length +
' element' +
(elements.length > 1 ? 's' : '') +
', attaching event handlers'
);
if (elements.length) {
mParticle.Logger.verbose(
'Found ' +
elements.length +
' element' +
(elements.length > 1 ? 's' : '') +
', attaching event handlers'
);
for (i = 0; i < elements.length; i++) {
element = elements[i];
for (i = 0; i < elements.length; i++) {
element = elements[i];
if (element.addEventListener) {
element.addEventListener(domEvent, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + domEvent, handler);
} else {
element['on' + domEvent] = handler;
if (element.addEventListener) {
element.addEventListener(domEvent, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + domEvent, handler);
} else {
element['on' + domEvent] = handler;
}
}
} else {
mpInstance.Logger.verbose('No elements found');
}
} else {
mParticle.Logger.verbose('No elements found');
}
};
}
export default {
logEvent: logEvent,
startTracking: startTracking,
stopTracking: stopTracking,
logCheckoutEvent: logCheckoutEvent,
logProductActionEvent: logProductActionEvent,
logPurchaseEvent: logPurchaseEvent,
logRefundEvent: logRefundEvent,
logPromotionEvent: logPromotionEvent,
logImpressionEvent: logImpressionEvent,
logOptOut: logOptOut,
logAST: logAST,
addEventHandler: addEventHandler,
};

@@ -96,2 +96,3 @@ export interface ApplicationInformation {

job_id?: string;
context?: Context;
}

@@ -302,2 +303,9 @@

export interface Context {
data_plan: {
plan_id: string,
plan_version?: number,
};
}
export interface DeviceInformation {

@@ -304,0 +312,0 @@ brand?: string;

@@ -1,10 +0,9 @@

import Persistence from './persistence';
import Types from './types';
import Helpers from './helpers';
export default function getFilteredMparticleUser(mpid, forwarder) {
export default function filteredMparticleUser(mpid, forwarder, mpInstance) {
var self = this;
return {
getUserIdentities: function() {
var currentUserIdentities = {};
var identities = Persistence.getUserIdentities(mpid);
var identities = mpInstance._Persistence.getUserIdentities(mpid);

@@ -15,3 +14,3 @@ for (var identityType in identities) {

Types.IdentityType.getIdentityName(
Helpers.parseNumber(identityType)
mpInstance._Helpers.parseNumber(identityType)
)

@@ -22,3 +21,3 @@ ] = identities[identityType];

currentUserIdentities = Helpers.filterUserIdentitiesForForwarders(
currentUserIdentities = mpInstance._Helpers.filterUserIdentitiesForForwarders(
currentUserIdentities,

@@ -39,3 +38,3 @@ forwarder.userIdentityFilters

userAttributes = this.getAllUserAttributes();
userAttributes = self.getAllUserAttributes();
for (var key in userAttributes) {

@@ -50,3 +49,3 @@ if (

userAttributesLists = Helpers.filterUserAttributes(
userAttributesLists = mpInstance._Helpers.filterUserAttributes(
userAttributesLists,

@@ -60,3 +59,5 @@ forwarder.userAttributeFilters

var userAttributesCopy = {};
var userAttributes = Persistence.getAllUserAttributes(mpid);
var userAttributes = mpInstance._Persistence.getAllUserAttributes(
mpid
);

@@ -77,3 +78,3 @@ if (userAttributes) {

userAttributesCopy = Helpers.filterUserAttributes(
userAttributesCopy = mpInstance._Helpers.filterUserAttributes(
userAttributesCopy,

@@ -80,0 +81,0 @@ forwarder.userAttributeFilters

@@ -1,621 +0,660 @@

import Helpers from './helpers';
import Types from './types';
import filteredMparticleUser from './filteredMparticleUser';
import Persistence from './persistence';
function initForwarders(userIdentities, forwardingStatsCallback) {
var user = mParticle.Identity.getCurrentUser();
if (
!mParticle.Store.webviewBridgeEnabled &&
mParticle.Store.configuredForwarders
) {
// Some js libraries require that they be loaded first, or last, etc
mParticle.Store.configuredForwarders.sort(function(x, y) {
x.settings.PriorityValue = x.settings.PriorityValue || 0;
y.settings.PriorityValue = y.settings.PriorityValue || 0;
return -1 * (x.settings.PriorityValue - y.settings.PriorityValue);
});
export default function Forwarders(mpInstance) {
var self = this;
this.initForwarders = function(userIdentities, forwardingStatsCallback) {
var user = mpInstance.Identity.getCurrentUser();
if (
!mpInstance._Store.webviewBridgeEnabled &&
mpInstance._Store.configuredForwarders
) {
// Some js libraries require that they be loaded first, or last, etc
mpInstance._Store.configuredForwarders.sort(function(x, y) {
x.settings.PriorityValue = x.settings.PriorityValue || 0;
y.settings.PriorityValue = y.settings.PriorityValue || 0;
return (
-1 * (x.settings.PriorityValue - y.settings.PriorityValue)
);
});
mParticle.Store.activeForwarders = mParticle.Store.configuredForwarders.filter(
function(forwarder) {
if (
!isEnabledForUserConsent(
forwarder.filteringConsentRuleValues,
user
)
) {
return false;
}
if (
!isEnabledForUserAttributes(
forwarder.filteringUserAttributeValue,
user
)
) {
return false;
}
if (
!isEnabledForUnknownUser(
forwarder.excludeAnonymousUser,
user
)
) {
return false;
}
mpInstance._Store.activeForwarders = mpInstance._Store.configuredForwarders.filter(
function(forwarder) {
if (
!self.isEnabledForUserConsent(
forwarder.filteringConsentRuleValues,
user
)
) {
return false;
}
if (
!self.isEnabledForUserAttributes(
forwarder.filteringUserAttributeValue,
user
)
) {
return false;
}
if (
!self.isEnabledForUnknownUser(
forwarder.excludeAnonymousUser,
user
)
) {
return false;
}
var filteredUserIdentities = Helpers.filterUserIdentities(
userIdentities,
forwarder.userIdentityFilters
);
var filteredUserAttributes = Helpers.filterUserAttributes(
user ? user.getAllUserAttributes() : {},
forwarder.userAttributeFilters
);
if (!forwarder.initialized) {
forwarder.init(
forwarder.settings,
forwardingStatsCallback,
false,
null,
filteredUserAttributes,
filteredUserIdentities,
mParticle.Store.SDKConfig.appVersion,
mParticle.Store.SDKConfig.appName,
mParticle.Store.SDKConfig.customFlags,
mParticle.Store.clientId
var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(
userIdentities,
forwarder.userIdentityFilters
);
forwarder.initialized = true;
}
var filteredUserAttributes = mpInstance._Helpers.filterUserAttributes(
user ? user.getAllUserAttributes() : {},
forwarder.userAttributeFilters
);
return true;
}
);
}
}
if (!forwarder.initialized) {
forwarder.init(
forwarder.settings,
forwardingStatsCallback,
false,
null,
filteredUserAttributes,
filteredUserIdentities,
mpInstance._Store.SDKConfig.appVersion,
mpInstance._Store.SDKConfig.appName,
mpInstance._Store.SDKConfig.customFlags,
mpInstance._Store.clientId
);
forwarder.initialized = true;
}
function isEnabledForUserConsent(consentRules, user) {
if (!consentRules || !consentRules.values || !consentRules.values.length) {
return true;
}
if (!user) {
return false;
}
var purposeHashes = {};
var GDPRConsentHashPrefix = '1';
var consentState = user.getConsentState();
if (consentState) {
var gdprConsentState = consentState.getGDPRConsentState();
if (gdprConsentState) {
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var purposeHash = Helpers.generateHash(
GDPRConsentHashPrefix + purpose
).toString();
purposeHashes[purposeHash] =
gdprConsentState[purpose].Consented;
return true;
}
);
}
};
this.isEnabledForUserConsent = function(consentRules, user) {
if (
!consentRules ||
!consentRules.values ||
!consentRules.values.length
) {
return true;
}
if (!user) {
return false;
}
var purposeHashes = {};
var GDPRConsentHashPrefix = '1';
var consentState = user.getConsentState();
if (consentState) {
var gdprConsentState = consentState.getGDPRConsentState();
if (gdprConsentState) {
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var purposeHash = mpInstance._Helpers
.generateHash(GDPRConsentHashPrefix + purpose)
.toString();
purposeHashes[purposeHash] =
gdprConsentState[purpose].Consented;
}
}
}
}
}
var isMatch = false;
consentRules.values.forEach(function(consentRule) {
if (!isMatch) {
var purposeHash = consentRule.consentPurpose;
var hasConsented = consentRule.hasConsented;
if (
purposeHashes.hasOwnProperty(purposeHash) &&
purposeHashes[purposeHash] === hasConsented
) {
isMatch = true;
var isMatch = false;
consentRules.values.forEach(function(consentRule) {
if (!isMatch) {
var purposeHash = consentRule.consentPurpose;
var hasConsented = consentRule.hasConsented;
if (
purposeHashes.hasOwnProperty(purposeHash) &&
purposeHashes[purposeHash] === hasConsented
) {
isMatch = true;
}
}
}
});
});
return consentRules.includeOnMatch === isMatch;
}
return consentRules.includeOnMatch === isMatch;
};
function isEnabledForUserAttributes(filterObject, user) {
if (
!filterObject ||
!Helpers.isObject(filterObject) ||
!Object.keys(filterObject).length
) {
return true;
}
this.isEnabledForUserAttributes = function(filterObject, user) {
if (
!filterObject ||
!mpInstance._Helpers.isObject(filterObject) ||
!Object.keys(filterObject).length
) {
return true;
}
var attrHash, valueHash, userAttributes;
var attrHash, valueHash, userAttributes;
if (!user) {
return false;
} else {
userAttributes = user.getAllUserAttributes();
}
if (!user) {
return false;
} else {
userAttributes = user.getAllUserAttributes();
}
var isMatch = false;
var isMatch = false;
try {
if (
userAttributes &&
Helpers.isObject(userAttributes) &&
Object.keys(userAttributes).length
) {
for (var attrName in userAttributes) {
if (userAttributes.hasOwnProperty(attrName)) {
attrHash = Helpers.generateHash(attrName).toString();
valueHash = Helpers.generateHash(
userAttributes[attrName]
).toString();
try {
if (
userAttributes &&
mpInstance._Helpers.isObject(userAttributes) &&
Object.keys(userAttributes).length
) {
for (var attrName in userAttributes) {
if (userAttributes.hasOwnProperty(attrName)) {
attrHash = mpInstance._Helpers
.generateHash(attrName)
.toString();
valueHash = mpInstance._Helpers
.generateHash(userAttributes[attrName])
.toString();
if (
attrHash === filterObject.userAttributeName &&
valueHash === filterObject.userAttributeValue
) {
isMatch = true;
break;
if (
attrHash === filterObject.userAttributeName &&
valueHash === filterObject.userAttributeValue
) {
isMatch = true;
break;
}
}
}
}
}
if (filterObject) {
return filterObject.includeOnMatch === isMatch;
} else {
if (filterObject) {
return filterObject.includeOnMatch === isMatch;
} else {
return true;
}
} catch (e) {
// in any error scenario, err on side of returning true and forwarding event
return true;
}
} catch (e) {
// in any error scenario, err on side of returning true and forwarding event
return true;
}
}
};
function isEnabledForUnknownUser(excludeAnonymousUserBoolean, user) {
if (!user || !user.isLoggedIn()) {
if (excludeAnonymousUserBoolean) {
return false;
this.isEnabledForUnknownUser = function(excludeAnonymousUserBoolean, user) {
if (!user || !user.isLoggedIn()) {
if (excludeAnonymousUserBoolean) {
return false;
}
}
}
return true;
}
return true;
};
function applyToForwarders(functionName, functionArgs) {
if (mParticle.Store.activeForwarders.length) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
var forwarderFunction = forwarder[functionName];
if (forwarderFunction) {
try {
var result = forwarder[functionName](functionArgs);
this.applyToForwarders = function(functionName, functionArgs) {
if (mpInstance._Store.activeForwarders.length) {
mpInstance._Store.activeForwarders.forEach(function(forwarder) {
var forwarderFunction = forwarder[functionName];
if (forwarderFunction) {
try {
var result = forwarder[functionName](functionArgs);
if (result) {
mParticle.Logger.verbose(result);
if (result) {
mpInstance.Logger.verbose(result);
}
} catch (e) {
mpInstance.Logger.verbose(e);
}
} catch (e) {
mParticle.Logger.verbose(e);
}
}
});
}
}
});
}
};
function sendEventToForwarders(event) {
var clonedEvent,
hashedEventName,
hashedEventType,
filterUserIdentities = function(event, filterList) {
if (event.UserIdentities && event.UserIdentities.length) {
event.UserIdentities.forEach(function(userIdentity, i) {
if (Helpers.inArray(filterList, userIdentity.Type)) {
event.UserIdentities.splice(i, 1);
this.sendEventToForwarders = function(event) {
var clonedEvent,
hashedEventName,
hashedEventType,
filterUserIdentities = function(event, filterList) {
if (event.UserIdentities && event.UserIdentities.length) {
event.UserIdentities.forEach(function(userIdentity, i) {
if (
mpInstance._Helpers.inArray(
filterList,
userIdentity.Type
)
) {
event.UserIdentities.splice(i, 1);
if (i > 0) {
i--;
if (i > 0) {
i--;
}
}
}
});
}
},
filterAttributes = function(event, filterList) {
var hash;
});
}
},
filterAttributes = function(event, filterList) {
var hash;
if (!filterList) {
return;
}
if (!filterList) {
return;
}
for (var attrName in event.EventAttributes) {
if (event.EventAttributes.hasOwnProperty(attrName)) {
hash = Helpers.generateHash(
event.EventCategory + event.EventName + attrName
);
for (var attrName in event.EventAttributes) {
if (event.EventAttributes.hasOwnProperty(attrName)) {
hash = mpInstance._Helpers.generateHash(
event.EventCategory + event.EventName + attrName
);
if (Helpers.inArray(filterList, hash)) {
delete event.EventAttributes[attrName];
if (mpInstance._Helpers.inArray(filterList, hash)) {
delete event.EventAttributes[attrName];
}
}
}
}
},
inFilteredList = function(filterList, hash) {
if (filterList && filterList.length) {
if (Helpers.inArray(filterList, hash)) {
return true;
},
inFilteredList = function(filterList, hash) {
if (filterList && filterList.length) {
if (mpInstance._Helpers.inArray(filterList, hash)) {
return true;
}
}
}
return false;
},
forwardingRuleMessageTypes = [
Types.MessageType.PageEvent,
Types.MessageType.PageView,
Types.MessageType.Commerce,
];
return false;
},
forwardingRuleMessageTypes = [
Types.MessageType.PageEvent,
Types.MessageType.PageView,
Types.MessageType.Commerce,
];
if (
!mParticle.Store.webviewBridgeEnabled &&
mParticle.Store.activeForwarders
) {
hashedEventName = Helpers.generateHash(
event.EventCategory + event.EventName
);
hashedEventType = Helpers.generateHash(event.EventCategory);
if (
!mpInstance._Store.webviewBridgeEnabled &&
mpInstance._Store.activeForwarders
) {
hashedEventName = mpInstance._Helpers.generateHash(
event.EventCategory + event.EventName
);
hashedEventType = mpInstance._Helpers.generateHash(
event.EventCategory
);
for (var i = 0; i < mParticle.Store.activeForwarders.length; i++) {
// Check attribute forwarding rule. This rule allows users to only forward an event if a
// specific attribute exists and has a specific value. Alternatively, they can specify
// that an event not be forwarded if the specified attribute name and value exists.
// The two cases are controlled by the "includeOnMatch" boolean value.
// Supported message types for attribute forwarding rules are defined in the forwardingRuleMessageTypes array
if (
forwardingRuleMessageTypes.indexOf(event.EventDataType) > -1 &&
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue &&
mParticle.Store.activeForwarders[i].filteringEventAttributeValue
.eventAttributeName &&
mParticle.Store.activeForwarders[i].filteringEventAttributeValue
.eventAttributeValue
for (
var i = 0;
i < mpInstance._Store.activeForwarders.length;
i++
) {
var foundProp = null;
// Check attribute forwarding rule. This rule allows users to only forward an event if a
// specific attribute exists and has a specific value. Alternatively, they can specify
// that an event not be forwarded if the specified attribute name and value exists.
// The two cases are controlled by the "includeOnMatch" boolean value.
// Supported message types for attribute forwarding rules are defined in the forwardingRuleMessageTypes array
// Attempt to find the attribute in the collection of event attributes
if (event.EventAttributes) {
for (var prop in event.EventAttributes) {
var hashedEventAttributeName;
hashedEventAttributeName = Helpers.generateHash(
prop
).toString();
if (
forwardingRuleMessageTypes.indexOf(event.EventDataType) >
-1 &&
mpInstance._Store.activeForwarders[i]
.filteringEventAttributeValue &&
mpInstance._Store.activeForwarders[i]
.filteringEventAttributeValue.eventAttributeName &&
mpInstance._Store.activeForwarders[i]
.filteringEventAttributeValue.eventAttributeValue
) {
var foundProp = null;
if (
hashedEventAttributeName ===
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue.eventAttributeName
) {
foundProp = {
name: hashedEventAttributeName,
value: Helpers.generateHash(
event.EventAttributes[prop]
).toString(),
};
}
// Attempt to find the attribute in the collection of event attributes
if (event.EventAttributes) {
for (var prop in event.EventAttributes) {
var hashedEventAttributeName;
hashedEventAttributeName = mpInstance._Helpers
.generateHash(prop)
.toString();
if (foundProp) {
break;
if (
hashedEventAttributeName ===
mpInstance._Store.activeForwarders[i]
.filteringEventAttributeValue
.eventAttributeName
) {
foundProp = {
name: hashedEventAttributeName,
value: mpInstance._Helpers
.generateHash(
event.EventAttributes[prop]
)
.toString(),
};
}
if (foundProp) {
break;
}
}
}
}
var isMatch =
foundProp !== null &&
foundProp.value ===
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue.eventAttributeValue;
var isMatch =
foundProp !== null &&
foundProp.value ===
mpInstance._Store.activeForwarders[i]
.filteringEventAttributeValue
.eventAttributeValue;
var shouldInclude =
mParticle.Store.activeForwarders[i]
.filteringEventAttributeValue.includeOnMatch === true
? isMatch
: !isMatch;
var shouldInclude =
mpInstance._Store.activeForwarders[i]
.filteringEventAttributeValue.includeOnMatch ===
true
? isMatch
: !isMatch;
if (!shouldInclude) {
continue;
if (!shouldInclude) {
continue;
}
}
}
// Clone the event object, as we could be sending different attributes to each forwarder
clonedEvent = {};
clonedEvent = Helpers.extend(true, clonedEvent, event);
// Check event filtering rules
if (
event.EventDataType === Types.MessageType.PageEvent &&
(inFilteredList(
mParticle.Store.activeForwarders[i].eventNameFilters,
hashedEventName
) ||
// Clone the event object, as we could be sending different attributes to each forwarder
clonedEvent = {};
clonedEvent = mpInstance._Helpers.extend(
true,
clonedEvent,
event
);
// Check event filtering rules
if (
event.EventDataType === Types.MessageType.PageEvent &&
(inFilteredList(
mpInstance._Store.activeForwarders[i].eventNameFilters,
hashedEventName
) ||
inFilteredList(
mpInstance._Store.activeForwarders[i]
.eventTypeFilters,
hashedEventType
))
) {
continue;
} else if (
event.EventDataType === Types.MessageType.Commerce &&
inFilteredList(
mParticle.Store.activeForwarders[i].eventTypeFilters,
mpInstance._Store.activeForwarders[i].eventTypeFilters,
hashedEventType
))
) {
continue;
} else if (
event.EventDataType === Types.MessageType.Commerce &&
inFilteredList(
mParticle.Store.activeForwarders[i].eventTypeFilters,
hashedEventType
)
) {
continue;
} else if (
event.EventDataType === Types.MessageType.PageView &&
inFilteredList(
mParticle.Store.activeForwarders[i].screenNameFilters,
hashedEventName
)
) {
continue;
}
)
) {
continue;
} else if (
event.EventDataType === Types.MessageType.PageView &&
inFilteredList(
mpInstance._Store.activeForwarders[i].screenNameFilters,
hashedEventName
)
) {
continue;
}
// Check attribute filtering rules
if (clonedEvent.EventAttributes) {
if (event.EventDataType === Types.MessageType.PageEvent) {
filterAttributes(
clonedEvent,
mParticle.Store.activeForwarders[i].attributeFilters
);
} else if (event.EventDataType === Types.MessageType.PageView) {
filterAttributes(
clonedEvent,
mParticle.Store.activeForwarders[i]
.pageViewAttributeFilters
);
// Check attribute filtering rules
if (clonedEvent.EventAttributes) {
if (event.EventDataType === Types.MessageType.PageEvent) {
filterAttributes(
clonedEvent,
mpInstance._Store.activeForwarders[i]
.attributeFilters
);
} else if (
event.EventDataType === Types.MessageType.PageView
) {
filterAttributes(
clonedEvent,
mpInstance._Store.activeForwarders[i]
.pageViewAttributeFilters
);
}
}
}
// Check user identity filtering rules
filterUserIdentities(
clonedEvent,
mParticle.Store.activeForwarders[i].userIdentityFilters
);
// Check user identity filtering rules
filterUserIdentities(
clonedEvent,
mpInstance._Store.activeForwarders[i].userIdentityFilters
);
// Check user attribute filtering rules
clonedEvent.UserAttributes = Helpers.filterUserAttributes(
clonedEvent.UserAttributes,
mParticle.Store.activeForwarders[i].userAttributeFilters
);
// Check user attribute filtering rules
clonedEvent.UserAttributes = mpInstance._Helpers.filterUserAttributes(
clonedEvent.UserAttributes,
mpInstance._Store.activeForwarders[i].userAttributeFilters
);
mParticle.Logger.verbose(
'Sending message to forwarder: ' +
mParticle.Store.activeForwarders[i].name
);
if (mParticle.Store.activeForwarders[i].process) {
var result = mParticle.Store.activeForwarders[i].process(
clonedEvent
mpInstance.Logger.verbose(
'Sending message to forwarder: ' +
mpInstance._Store.activeForwarders[i].name
);
if (result) {
mParticle.Logger.verbose(result);
if (mpInstance._Store.activeForwarders[i].process) {
var result = mpInstance._Store.activeForwarders[i].process(
clonedEvent
);
if (result) {
mpInstance.Logger.verbose(result);
}
}
}
}
}
}
};
function callSetUserAttributeOnForwarders(key, value) {
if (mParticle.Store.activeForwarders.length) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
if (
forwarder.setUserAttribute &&
forwarder.userAttributeFilters &&
!Helpers.inArray(
forwarder.userAttributeFilters,
Helpers.generateHash(key)
)
) {
try {
var result = forwarder.setUserAttribute(key, value);
this.callSetUserAttributeOnForwarders = function(key, value) {
if (mpInstance._Store.activeForwarders.length) {
mpInstance._Store.activeForwarders.forEach(function(forwarder) {
if (
forwarder.setUserAttribute &&
forwarder.userAttributeFilters &&
!mpInstance._Helpers.inArray(
forwarder.userAttributeFilters,
mpInstance._Helpers.generateHash(key)
)
) {
try {
var result = forwarder.setUserAttribute(key, value);
if (result) {
mpInstance.Logger.verbose(result);
}
} catch (e) {
mpInstance.Logger.error(e);
}
}
});
}
};
this.setForwarderUserIdentities = function(userIdentities) {
mpInstance._Store.activeForwarders.forEach(function(forwarder) {
var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(
userIdentities,
forwarder.userIdentityFilters
);
if (forwarder.setUserIdentity) {
filteredUserIdentities.forEach(function(identity) {
var result = forwarder.setUserIdentity(
identity.Identity,
identity.Type
);
if (result) {
mParticle.Logger.verbose(result);
mpInstance.Logger.verbose(result);
}
} catch (e) {
mParticle.Logger.error(e);
}
});
}
});
}
}
};
function setForwarderUserIdentities(userIdentities) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUserIdentities = Helpers.filterUserIdentities(
userIdentities,
forwarder.userIdentityFilters
);
if (forwarder.setUserIdentity) {
filteredUserIdentities.forEach(function(identity) {
var result = forwarder.setUserIdentity(
identity.Identity,
identity.Type
);
this.setForwarderOnUserIdentified = function(user) {
mpInstance._Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = filteredMparticleUser(
user.getMPID(),
forwarder,
mpInstance
);
if (forwarder.onUserIdentified) {
var result = forwarder.onUserIdentified(filteredUser);
if (result) {
mParticle.Logger.verbose(result);
mpInstance.Logger.verbose(result);
}
});
}
});
}
function setForwarderOnUserIdentified(user) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = filteredMparticleUser(user.getMPID(), forwarder);
if (forwarder.onUserIdentified) {
var result = forwarder.onUserIdentified(filteredUser);
if (result) {
mParticle.Logger.verbose(result);
}
}
});
}
});
};
function setForwarderOnIdentityComplete(user, identityMethod) {
var result;
this.setForwarderOnIdentityComplete = function(user, identityMethod) {
var result;
mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = filteredMparticleUser(user.getMPID(), forwarder);
if (identityMethod === 'identify') {
if (forwarder.onIdentifyComplete) {
result = forwarder.onIdentifyComplete(filteredUser);
if (result) {
mParticle.Logger.verbose(result);
mpInstance._Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = filteredMparticleUser(
user.getMPID(),
forwarder,
mpInstance
);
if (identityMethod === 'identify') {
if (forwarder.onIdentifyComplete) {
result = forwarder.onIdentifyComplete(filteredUser);
if (result) {
mpInstance.Logger.verbose(result);
}
}
}
} else if (identityMethod === 'login') {
if (forwarder.onLoginComplete) {
result = forwarder.onLoginComplete(filteredUser);
if (result) {
mParticle.Logger.verbose(result);
} else if (identityMethod === 'login') {
if (forwarder.onLoginComplete) {
result = forwarder.onLoginComplete(filteredUser);
if (result) {
mpInstance.Logger.verbose(result);
}
}
}
} else if (identityMethod === 'logout') {
if (forwarder.onLogoutComplete) {
result = forwarder.onLogoutComplete(filteredUser);
if (result) {
mParticle.Logger.verbose(result);
} else if (identityMethod === 'logout') {
if (forwarder.onLogoutComplete) {
result = forwarder.onLogoutComplete(filteredUser);
if (result) {
mpInstance.Logger.verbose(result);
}
}
}
} else if (identityMethod === 'modify') {
if (forwarder.onModifyComplete) {
result = forwarder.onModifyComplete(filteredUser);
if (result) {
mParticle.Logger.verbose(result);
} else if (identityMethod === 'modify') {
if (forwarder.onModifyComplete) {
result = forwarder.onModifyComplete(filteredUser);
if (result) {
mpInstance.Logger.verbose(result);
}
}
}
}
});
}
});
};
function getForwarderStatsQueue() {
return Persistence.forwardingStatsBatches.forwardingStatsEventQueue;
}
this.getForwarderStatsQueue = function() {
return mpInstance._Persistence.forwardingStatsBatches
.forwardingStatsEventQueue;
};
function setForwarderStatsQueue(queue) {
Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue;
}
this.setForwarderStatsQueue = function(queue) {
mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue;
};
function configureForwarder(configuration) {
var newForwarder = null,
config = configuration,
forwarders = {};
this.configureForwarder = function(configuration) {
var newForwarder = null,
config = configuration,
forwarders = {};
// if there are kits inside of mParticle.Store.SDKConfig.kits, then mParticle is self hosted
if (
Helpers.isObject(mParticle.Store.SDKConfig.kits) &&
Object.keys(mParticle.Store.SDKConfig.kits).length > 0
) {
forwarders = mParticle.Store.SDKConfig.kits;
// otherwise mParticle is loaded via script tag
} else if (mParticle.preInit.forwarderConstructors.length > 0) {
mParticle.preInit.forwarderConstructors.forEach(function(forwarder) {
forwarders[forwarder.name] = forwarder;
});
}
for (var name in forwarders) {
if (name === config.name) {
if (
config.isDebug ===
mParticle.Store.SDKConfig.isDevelopmentMode ||
config.isSandbox === mParticle.Store.SDKConfig.isDevelopmentMode
// if there are kits inside of mpInstance._Store.SDKConfig.kits, then mParticle is self hosted
if (
mpInstance._Helpers.isObject(mpInstance._Store.SDKConfig.kits) &&
Object.keys(mpInstance._Store.SDKConfig.kits).length > 0
) {
forwarders = mpInstance._Store.SDKConfig.kits;
// otherwise mParticle is loaded via script tag
} else if (mpInstance._preInit.forwarderConstructors.length > 0) {
mpInstance._preInit.forwarderConstructors.forEach(function(
forwarder
) {
newForwarder = new forwarders[name].constructor();
forwarders[forwarder.name] = forwarder;
});
}
newForwarder.id = config.moduleId;
newForwarder.isSandbox = config.isDebug || config.isSandbox;
newForwarder.hasSandbox = config.hasDebugString === 'true';
newForwarder.isVisible = config.isVisible;
newForwarder.settings = config.settings;
for (var name in forwarders) {
if (name === config.name) {
if (
config.isDebug ===
mpInstance._Store.SDKConfig.isDevelopmentMode ||
config.isSandbox ===
mpInstance._Store.SDKConfig.isDevelopmentMode
) {
newForwarder = new forwarders[name].constructor();
newForwarder.eventNameFilters = config.eventNameFilters;
newForwarder.eventTypeFilters = config.eventTypeFilters;
newForwarder.attributeFilters = config.attributeFilters;
newForwarder.id = config.moduleId;
newForwarder.isSandbox = config.isDebug || config.isSandbox;
newForwarder.hasSandbox = config.hasDebugString === 'true';
newForwarder.isVisible = config.isVisible;
newForwarder.settings = config.settings;
newForwarder.screenNameFilters = config.screenNameFilters;
newForwarder.screenNameFilters = config.screenNameFilters;
newForwarder.pageViewAttributeFilters =
config.pageViewAttributeFilters;
newForwarder.eventNameFilters = config.eventNameFilters;
newForwarder.eventTypeFilters = config.eventTypeFilters;
newForwarder.attributeFilters = config.attributeFilters;
newForwarder.userIdentityFilters = config.userIdentityFilters;
newForwarder.userAttributeFilters = config.userAttributeFilters;
newForwarder.screenNameFilters = config.screenNameFilters;
newForwarder.screenNameFilters = config.screenNameFilters;
newForwarder.pageViewAttributeFilters =
config.pageViewAttributeFilters;
newForwarder.filteringEventAttributeValue =
config.filteringEventAttributeValue;
newForwarder.filteringUserAttributeValue =
config.filteringUserAttributeValue;
newForwarder.eventSubscriptionId = config.eventSubscriptionId;
newForwarder.filteringConsentRuleValues =
config.filteringConsentRuleValues;
newForwarder.excludeAnonymousUser = config.excludeAnonymousUser;
newForwarder.userIdentityFilters =
config.userIdentityFilters;
newForwarder.userAttributeFilters =
config.userAttributeFilters;
mParticle.Store.configuredForwarders.push(newForwarder);
break;
newForwarder.filteringEventAttributeValue =
config.filteringEventAttributeValue;
newForwarder.filteringUserAttributeValue =
config.filteringUserAttributeValue;
newForwarder.eventSubscriptionId =
config.eventSubscriptionId;
newForwarder.filteringConsentRuleValues =
config.filteringConsentRuleValues;
newForwarder.excludeAnonymousUser =
config.excludeAnonymousUser;
mpInstance._Store.configuredForwarders.push(newForwarder);
break;
}
}
}
}
}
};
function configurePixel(settings) {
if (
settings.isDebug === mParticle.Store.SDKConfig.isDevelopmentMode ||
settings.isProduction !== mParticle.Store.SDKConfig.isDevelopmentMode
) {
mParticle.Store.pixelConfigurations.push(settings);
}
}
this.configurePixel = function(settings) {
if (
settings.isDebug ===
mpInstance._Store.SDKConfig.isDevelopmentMode ||
settings.isProduction !==
mpInstance._Store.SDKConfig.isDevelopmentMode
) {
mpInstance._Store.pixelConfigurations.push(settings);
}
};
function processForwarders(config, forwardingStatsCallback) {
if (!config) {
mParticle.Logger.warning(
'No config was passed. Cannot process forwarders'
);
} else {
try {
if (Array.isArray(config.kitConfigs) && config.kitConfigs.length) {
config.kitConfigs.forEach(function(kitConfig) {
configureForwarder(kitConfig);
});
}
this.processForwarders = function(config, forwardingStatsCallback) {
if (!config) {
mpInstance.Logger.warning(
'No config was passed. Cannot process forwarders'
);
} else {
try {
if (
Array.isArray(config.kitConfigs) &&
config.kitConfigs.length
) {
config.kitConfigs.forEach(function(kitConfig) {
self.configureForwarder(kitConfig);
});
}
if (
Array.isArray(config.pixelConfigs) &&
config.pixelConfigs.length
) {
config.pixelConfigs.forEach(function(pixelConfig) {
configurePixel(pixelConfig);
});
if (
Array.isArray(config.pixelConfigs) &&
config.pixelConfigs.length
) {
config.pixelConfigs.forEach(function(pixelConfig) {
self.configurePixel(pixelConfig);
});
}
self.initForwarders(
mpInstance._Store.SDKConfig.identifyRequest.userIdentities,
forwardingStatsCallback
);
} catch (e) {
mpInstance.Logger.error(
'Config was not parsed propertly. Forwarders may not be initialized.'
);
}
initForwarders(
mParticle.Store.SDKConfig.identifyRequest.userIdentities,
forwardingStatsCallback
);
} catch (e) {
mParticle.Logger.error(
'Config was not parsed propertly. Forwarders may not be initialized.'
);
}
}
};
}
export default {
initForwarders: initForwarders,
applyToForwarders: applyToForwarders,
sendEventToForwarders: sendEventToForwarders,
callSetUserAttributeOnForwarders: callSetUserAttributeOnForwarders,
setForwarderUserIdentities: setForwarderUserIdentities,
setForwarderOnUserIdentified: setForwarderOnUserIdentified,
setForwarderOnIdentityComplete: setForwarderOnIdentityComplete,
getForwarderStatsQueue: getForwarderStatsQueue,
setForwarderStatsQueue: setForwarderStatsQueue,
isEnabledForUserConsent: isEnabledForUserConsent,
isEnabledForUserAttributes: isEnabledForUserAttributes,
configurePixel: configurePixel,
processForwarders: processForwarders,
};

@@ -1,56 +0,54 @@

import ApiClient from './apiClient';
import Helpers from './helpers';
import Forwarders from './forwarders';
import Persistence from './persistence';
export default function forwardingStatsUploader(mpInstance) {
this.startForwardingStatsTimer = function() {
mParticle._forwardingStatsTimer = setInterval(function() {
prepareAndSendForwardingStatsBatch();
}, mpInstance._Store.SDKConfig.forwarderStatsTimeout);
};
export default function startForwardingStatsTimer() {
mParticle._forwardingStatsTimer = setInterval(function() {
prepareAndSendForwardingStatsBatch();
}, mParticle.Store.SDKConfig.forwarderStatsTimeout);
}
function prepareAndSendForwardingStatsBatch() {
var forwarderQueue = mpInstance._Forwarders.getForwarderStatsQueue(),
uploadsTable =
mpInstance._Persistence.forwardingStatsBatches.uploadsTable,
now = Date.now();
function prepareAndSendForwardingStatsBatch() {
var forwarderQueue = Forwarders.getForwarderStatsQueue(),
uploadsTable = Persistence.forwardingStatsBatches.uploadsTable,
now = Date.now();
if (forwarderQueue.length) {
uploadsTable[now] = { uploading: false, data: forwarderQueue };
mpInstance._Forwarders.setForwarderStatsQueue([]);
}
if (forwarderQueue.length) {
uploadsTable[now] = { uploading: false, data: forwarderQueue };
Forwarders.setForwarderStatsQueue([]);
}
for (var date in uploadsTable) {
(function(date) {
if (uploadsTable.hasOwnProperty(date)) {
if (uploadsTable[date].uploading === false) {
var xhrCallback = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 202) {
mParticle.Logger.verbose(
'Successfully sent ' +
xhr.statusText +
' from server'
);
delete uploadsTable[date];
} else if (xhr.status.toString()[0] === '4') {
if (xhr.status !== 429) {
for (var date in uploadsTable) {
(function(date) {
if (uploadsTable.hasOwnProperty(date)) {
if (uploadsTable[date].uploading === false) {
var xhrCallback = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 202) {
mpInstance.Logger.verbose(
'Successfully sent ' +
xhr.statusText +
' from server'
);
delete uploadsTable[date];
} else if (xhr.status.toString()[0] === '4') {
if (xhr.status !== 429) {
delete uploadsTable[date];
}
} else {
uploadsTable[date].uploading = false;
}
} else {
uploadsTable[date].uploading = false;
}
}
};
};
var xhr = Helpers.createXHR(xhrCallback);
var forwardingStatsData = uploadsTable[date].data;
uploadsTable[date].uploading = true;
ApiClient.sendBatchForwardingStatsToServer(
forwardingStatsData,
xhr
);
var xhr = mpInstance._Helpers.createXHR(xhrCallback);
var forwardingStatsData = uploadsTable[date].data;
uploadsTable[date].uploading = true;
mpInstance._APIClient.sendBatchForwardingStatsToServer(
forwardingStatsData,
xhr
);
}
}
}
})(date);
})(date);
}
}
}
import Types from './types';
import Constants from './constants';
import Slugify from 'slugify';
var StorageNames = Constants.StorageNames,
pluses = /\+/g;
function canLog() {
if (
mParticle.Store.isEnabled &&
(mParticle.Store.devToken || mParticle.Store.webviewBridgeEnabled)
) {
return true;
}
export default function Helpers(mpInstance) {
var self = this;
this.canLog = function() {
if (
mpInstance._Store.isEnabled &&
(mpInstance._Store.devToken ||
mpInstance._Store.webviewBridgeEnabled)
) {
return true;
}
return false;
}
function returnConvertedBoolean(data) {
if (data === 'false' || data === '0') {
return false;
} else {
return Boolean(data);
}
}
};
function getFeatureFlag(feature) {
if (mParticle.Store.SDKConfig.flags.hasOwnProperty(feature)) {
return mParticle.Store.SDKConfig.flags[feature];
}
return null;
}
this.returnConvertedBoolean = function(data) {
if (data === 'false' || data === '0') {
return false;
} else {
return Boolean(data);
}
};
/**
* Returns a value between 1-100 inclusive.
*/
function getRampNumber(deviceId) {
if (!deviceId) {
return 100;
}
var hash = generateHash(deviceId);
return Math.abs(hash % 100) + 1;
}
this.getFeatureFlag = function(feature) {
if (mpInstance._Store.SDKConfig.flags.hasOwnProperty(feature)) {
return mpInstance._Store.SDKConfig.flags[feature];
}
return null;
};
function invokeCallback(callback, code, body, mParticleUser, previousMpid) {
if (!callback) {
mParticle.Logger.warning('There is no callback provided');
}
try {
if (Validators.isFunction(callback)) {
callback({
httpCode: code,
body: body,
getUser: function() {
if (mParticleUser) {
return mParticleUser;
} else {
return mParticle.Identity.getCurrentUser();
}
},
getPreviousUser: function() {
if (!previousMpid) {
var users = mParticle.Identity.getUsers();
var mostRecentUser = users.shift();
var currentUser =
mParticleUser ||
mParticle.Identity.getCurrentUser();
if (
mostRecentUser &&
currentUser &&
mostRecentUser.getMPID() === currentUser.getMPID()
) {
mostRecentUser = users.shift();
}
return mostRecentUser || null;
} else {
return mParticle.Identity.getUser(previousMpid);
}
},
});
/**
* Returns a value between 1-100 inclusive.
*/
this.getRampNumber = function(deviceId) {
if (!deviceId) {
return 100;
}
} catch (e) {
mParticle.Logger.error('There was an error with your callback: ' + e);
}
}
var hash = self.generateHash(deviceId);
return Math.abs(hash % 100) + 1;
};
function invokeAliasCallback(callback, code, message) {
if (!callback) {
mParticle.Logger.warning('There is no callback provided');
}
try {
if (Validators.isFunction(callback)) {
var callbackMessage = {
httpCode: code,
};
if (message) {
callbackMessage.message = message;
this.invokeCallback = function(
callback,
code,
body,
mParticleUser,
previousMpid
) {
if (!callback) {
mpInstance.Logger.warning('There is no callback provided');
}
try {
if (self.Validators.isFunction(callback)) {
callback({
httpCode: code,
body: body,
getUser: function() {
if (mParticleUser) {
return mParticleUser;
} else {
return mpInstance.Identity.getCurrentUser();
}
},
getPreviousUser: function() {
if (!previousMpid) {
var users = mpInstance.Identity.getUsers();
var mostRecentUser = users.shift();
var currentUser =
mParticleUser ||
mpInstance.Identity.getCurrentUser();
if (
mostRecentUser &&
currentUser &&
mostRecentUser.getMPID() ===
currentUser.getMPID()
) {
mostRecentUser = users.shift();
}
return mostRecentUser || null;
} else {
return mpInstance.Identity.getUser(previousMpid);
}
},
});
}
callback(callbackMessage);
} catch (e) {
mpInstance.Logger.error(
'There was an error with your callback: ' + e
);
}
} catch (e) {
mParticle.Logger.error('There was an error with your callback: ' + e);
}
}
};
// Standalone version of jQuery.extend, from https://github.com/dansdom/extend
function extend() {
var options,
name,
src,
copy,
copyIsArray,
clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false,
// helper which replicates the jquery internal functions
objectHelper = {
hasOwn: Object.prototype.hasOwnProperty,
class2type: {},
type: function(obj) {
return obj == null
? String(obj)
: objectHelper.class2type[
Object.prototype.toString.call(obj)
] || 'object';
},
isPlainObject: function(obj) {
if (
!obj ||
objectHelper.type(obj) !== 'object' ||
obj.nodeType ||
objectHelper.isWindow(obj)
) {
return false;
this.invokeAliasCallback = function(callback, code, message) {
if (!callback) {
mpInstance.Logger.warning('There is no callback provided');
}
try {
if (self.Validators.isFunction(callback)) {
var callbackMessage = {
httpCode: code,
};
if (message) {
callbackMessage.message = message;
}
callback(callbackMessage);
}
} catch (e) {
mpInstance.Logger.error(
'There was an error with your callback: ' + e
);
}
};
try {
// Standalone version of jQuery.extend, from https://github.com/dansdom/extend
this.extend = function() {
var options,
name,
src,
copy,
copyIsArray,
clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false,
// helper which replicates the jquery internal functions
objectHelper = {
hasOwn: Object.prototype.hasOwnProperty,
class2type: {},
type: function(obj) {
return obj == null
? String(obj)
: objectHelper.class2type[
Object.prototype.toString.call(obj)
] || 'object';
},
isPlainObject: function(obj) {
if (
obj.constructor &&
!objectHelper.hasOwn.call(obj, 'constructor') &&
!objectHelper.hasOwn.call(
obj.constructor.prototype,
'isPrototypeOf'
)
!obj ||
objectHelper.type(obj) !== 'object' ||
obj.nodeType ||
objectHelper.isWindow(obj)
) {
return false;
}
} catch (e) {
return false;
}
var key;
for (key in obj) {
} // eslint-disable-line no-empty
try {
if (
obj.constructor &&
!objectHelper.hasOwn.call(obj, 'constructor') &&
!objectHelper.hasOwn.call(
obj.constructor.prototype,
'isPrototypeOf'
)
) {
return false;
}
} catch (e) {
return false;
}
return key === undefined || objectHelper.hasOwn.call(obj, key);
},
isArray:
Array.isArray ||
function(obj) {
return objectHelper.type(obj) === 'array';
var key;
for (key in obj) {
} // eslint-disable-line no-empty
return (
key === undefined || objectHelper.hasOwn.call(obj, key)
);
},
isFunction: function(obj) {
return objectHelper.type(obj) === 'function';
},
isWindow: function(obj) {
return obj != null && obj == obj.window;
},
}; // end of objectHelper
isArray:
Array.isArray ||
function(obj) {
return objectHelper.type(obj) === 'array';
},
isFunction: function(obj) {
return objectHelper.type(obj) === 'function';
},
isWindow: function(obj) {
return obj != null && obj == obj.window;
},
}; // end of objectHelper
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== 'object' && !objectHelper.isFunction(target)) {
target = {};
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== 'object' && !objectHelper.isFunction(target)) {
target = {};
}
// If no second argument is used then this can extend an object that is using this method
if (length === i) {
target = this;
--i;
}
// If no second argument is used then this can extend an object that is using this method
if (length === i) {
target = this;
--i;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (
deep &&
copy &&
(objectHelper.isPlainObject(copy) ||
(copyIsArray = objectHelper.isArray(copy)))
) {
if (copyIsArray) {
copyIsArray = false;
clone = src && objectHelper.isArray(src) ? src : [];
} else {
clone =
src && objectHelper.isPlainObject(src) ? src : {};
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Recurse if we're merging plain objects or arrays
if (
deep &&
copy &&
(objectHelper.isPlainObject(copy) ||
(copyIsArray = objectHelper.isArray(copy)))
) {
if (copyIsArray) {
copyIsArray = false;
clone = src && objectHelper.isArray(src) ? src : [];
} else {
clone =
src && objectHelper.isPlainObject(src)
? src
: {};
}
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
// Never move original objects, clone them
target[name] = self.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
}
// Return the modified object
return target;
};
function isObject(value) {
var objType = Object.prototype.toString.call(value);
this.isObject = function(value) {
var objType = Object.prototype.toString.call(value);
return objType === '[object Object]' || objType === '[object Error]';
}
return objType === '[object Object]' || objType === '[object Error]';
};
function inArray(items, name) {
var i = 0;
this.inArray = function(items, name) {
var i = 0;
if (Array.prototype.indexOf) {
return items.indexOf(name, 0) >= 0;
} else {
for (var n = items.length; i < n; i++) {
if (i in items && items[i] === name) {
return true;
if (Array.prototype.indexOf) {
return items.indexOf(name, 0) >= 0;
} else {
for (var n = items.length; i < n; i++) {
if (i in items && items[i] === name) {
return true;
}
}
}
}
}
};
function createServiceUrl(secureServiceUrl, devToken) {
var serviceScheme =
window.mParticle && mParticle.Store.SDKConfig.forceHttps
? 'https://'
: window.location.protocol + '//';
var baseUrl;
if (mParticle.Store.SDKConfig.forceHttps) {
baseUrl = 'https://' + secureServiceUrl;
} else {
baseUrl = serviceScheme + secureServiceUrl;
}
if (devToken) {
baseUrl = baseUrl + devToken;
}
return baseUrl;
}
this.createServiceUrl = function(secureServiceUrl, devToken) {
var serviceScheme =
window.mParticle && mpInstance._Store.SDKConfig.forceHttps
? 'https://'
: window.location.protocol + '//';
var baseUrl;
if (mpInstance._Store.SDKConfig.forceHttps) {
baseUrl = 'https://' + secureServiceUrl;
} else {
baseUrl = serviceScheme + secureServiceUrl;
}
if (devToken) {
baseUrl = baseUrl + devToken;
}
return baseUrl;
};
function createXHR(cb) {
var xhr;
this.createXHR = function(cb) {
var xhr;
try {
xhr = new window.XMLHttpRequest();
} catch (e) {
mParticle.Logger.error('Error creating XMLHttpRequest object.');
}
if (xhr && cb && 'withCredentials' in xhr) {
xhr.onreadystatechange = cb;
} else if (typeof window.XDomainRequest !== 'undefined') {
mParticle.Logger.verbose('Creating XDomainRequest object');
try {
xhr = new window.XDomainRequest();
xhr.onload = cb;
xhr = new window.XMLHttpRequest();
} catch (e) {
mParticle.Logger.error('Error creating XDomainRequest object');
mpInstance.Logger.error('Error creating XMLHttpRequest object.');
}
}
return xhr;
}
if (xhr && cb && 'withCredentials' in xhr) {
xhr.onreadystatechange = cb;
} else if (typeof window.XDomainRequest !== 'undefined') {
mpInstance.Logger.verbose('Creating XDomainRequest object');
function generateRandomValue(a) {
var randomValue;
if (window.crypto && window.crypto.getRandomValues) {
randomValue = window.crypto.getRandomValues(new Uint8Array(1)); // eslint-disable-line no-undef
try {
xhr = new window.XDomainRequest();
xhr.onload = cb;
} catch (e) {
mpInstance.Logger.error('Error creating XDomainRequest object');
}
}
return xhr;
};
function generateRandomValue(a) {
var randomValue;
if (window.crypto && window.crypto.getRandomValues) {
randomValue = window.crypto.getRandomValues(new Uint8Array(1)); // eslint-disable-line no-undef
}
if (randomValue) {
return (a ^ (randomValue[0] % 16 >> (a / 4))).toString(16);
}
return (a ^ ((Math.random() * 16) >> (a / 4))).toString(16);
}
if (randomValue) {
return (a ^ (randomValue[0] % 16 >> (a / 4))).toString(16);
}
return (a ^ ((Math.random() * 16) >> (a / 4))).toString(16);
}
this.generateUniqueId = function(a) {
// https://gist.github.com/jed/982883
// Added support for crypto for better random
function generateUniqueId(a) {
// https://gist.github.com/jed/982883
// Added support for crypto for better random
return a // if the placeholder was passed, return
? generateRandomValue(a) // a random number
: // or otherwise a concatenated string:
(
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11
) // -100000000000,
.replace(
// replacing
/[018]/g, // zeroes, ones, and eights with
self.generateUniqueId // random hex digits
);
};
return a // if the placeholder was passed, return
? generateRandomValue(a) // a random number
: // or otherwise a concatenated string:
(
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11
) // -100000000000,
.replace(
// replacing
/[018]/g, // zeroes, ones, and eights with
generateUniqueId // random hex digits
);
}
this.filterUserIdentities = function(userIdentitiesObject, filterList) {
var filteredUserIdentities = [];
function filterUserIdentities(userIdentitiesObject, filterList) {
var filteredUserIdentities = [];
if (userIdentitiesObject && Object.keys(userIdentitiesObject).length) {
for (var userIdentityName in userIdentitiesObject) {
if (userIdentitiesObject.hasOwnProperty(userIdentityName)) {
var userIdentityType = Types.IdentityType.getIdentityType(
userIdentityName
);
if (!inArray(filterList, userIdentityType)) {
var identity = {
Type: userIdentityType,
Identity: userIdentitiesObject[userIdentityName],
};
if (
userIdentityType === mParticle.IdentityType.CustomerId
) {
filteredUserIdentities.unshift(identity);
} else {
filteredUserIdentities.push(identity);
if (userIdentitiesObject && Object.keys(userIdentitiesObject).length) {
for (var userIdentityName in userIdentitiesObject) {
if (userIdentitiesObject.hasOwnProperty(userIdentityName)) {
var userIdentityType = Types.IdentityType.getIdentityType(
userIdentityName
);
if (!self.inArray(filterList, userIdentityType)) {
var identity = {
Type: userIdentityType,
Identity: userIdentitiesObject[userIdentityName],
};
if (
userIdentityType === Types.IdentityType.CustomerId
) {
filteredUserIdentities.unshift(identity);
} else {
filteredUserIdentities.push(identity);
}
}

@@ -352,205 +373,242 @@ }

}
}
return filteredUserIdentities;
}
return filteredUserIdentities;
};
function filterUserIdentitiesForForwarders(userIdentitiesObject, filterList) {
var filteredUserIdentities = {};
this.filterUserIdentitiesForForwarders = function(
userIdentitiesObject,
filterList
) {
var filteredUserIdentities = {};
if (userIdentitiesObject && Object.keys(userIdentitiesObject).length) {
for (var userIdentityName in userIdentitiesObject) {
if (userIdentitiesObject.hasOwnProperty(userIdentityName)) {
var userIdentityType = Types.IdentityType.getIdentityType(
userIdentityName
);
if (!inArray(filterList, userIdentityType)) {
filteredUserIdentities[userIdentityName] =
userIdentitiesObject[userIdentityName];
if (userIdentitiesObject && Object.keys(userIdentitiesObject).length) {
for (var userIdentityName in userIdentitiesObject) {
if (userIdentitiesObject.hasOwnProperty(userIdentityName)) {
var userIdentityType = Types.IdentityType.getIdentityType(
userIdentityName
);
if (!self.inArray(filterList, userIdentityType)) {
filteredUserIdentities[userIdentityName] =
userIdentitiesObject[userIdentityName];
}
}
}
}
}
return filteredUserIdentities;
}
return filteredUserIdentities;
};
function filterUserAttributes(userAttributes, filterList) {
var filteredUserAttributes = {};
this.filterUserAttributes = function(userAttributes, filterList) {
var filteredUserAttributes = {};
if (userAttributes && Object.keys(userAttributes).length) {
for (var userAttribute in userAttributes) {
if (userAttributes.hasOwnProperty(userAttribute)) {
var hashedUserAttribute = generateHash(userAttribute);
if (!inArray(filterList, hashedUserAttribute)) {
filteredUserAttributes[userAttribute] =
userAttributes[userAttribute];
if (userAttributes && Object.keys(userAttributes).length) {
for (var userAttribute in userAttributes) {
if (userAttributes.hasOwnProperty(userAttribute)) {
var hashedUserAttribute = self.generateHash(userAttribute);
if (!self.inArray(filterList, hashedUserAttribute)) {
filteredUserAttributes[userAttribute] =
userAttributes[userAttribute];
}
}
}
}
}
return filteredUserAttributes;
}
return filteredUserAttributes;
};
function findKeyInObject(obj, key) {
if (key && obj) {
for (var prop in obj) {
if (
obj.hasOwnProperty(prop) &&
prop.toLowerCase() === key.toLowerCase()
) {
return prop;
this.findKeyInObject = function(obj, key) {
if (key && obj) {
for (var prop in obj) {
if (
obj.hasOwnProperty(prop) &&
prop.toLowerCase() === key.toLowerCase()
) {
return prop;
}
}
}
}
return null;
}
return null;
};
function decoded(s) {
return decodeURIComponent(s.replace(pluses, ' '));
}
this.decoded = function(s) {
return decodeURIComponent(s.replace(pluses, ' '));
};
function converted(s) {
if (s.indexOf('"') === 0) {
s = s
.slice(1, -1)
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
}
this.converted = function(s) {
if (s.indexOf('"') === 0) {
s = s
.slice(1, -1)
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
}
return s;
}
return s;
};
function isEventType(type) {
for (var prop in Types.EventType) {
if (Types.EventType.hasOwnProperty(prop)) {
if (Types.EventType[prop] === type) {
return true;
this.isEventType = function(type) {
for (var prop in Types.EventType) {
if (Types.EventType.hasOwnProperty(prop)) {
if (Types.EventType[prop] === type) {
return true;
}
}
}
}
return false;
}
return false;
};
function parseNumber(value) {
if (isNaN(value) || !isFinite(value)) {
return 0;
}
var floatValue = parseFloat(value);
return isNaN(floatValue) ? 0 : floatValue;
}
this.parseNumber = function(value) {
if (isNaN(value) || !isFinite(value)) {
return 0;
}
var floatValue = parseFloat(value);
return isNaN(floatValue) ? 0 : floatValue;
};
function parseStringOrNumber(value) {
if (Validators.isStringOrNumber(value)) {
return value;
} else {
return null;
}
}
this.parseStringOrNumber = function(value) {
if (self.Validators.isStringOrNumber(value)) {
return value;
} else {
return null;
}
};
function generateHash(name) {
var hash = 0,
i = 0,
character;
this.generateHash = function(name) {
var hash = 0,
i = 0,
character;
if (name === undefined || name === null) {
return 0;
}
if (name === undefined || name === null) {
return 0;
}
name = name.toString().toLowerCase();
name = name.toString().toLowerCase();
if (Array.prototype.reduce) {
return name.split('').reduce(function(a, b) {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}
if (Array.prototype.reduce) {
return name.split('').reduce(function(a, b) {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}
if (name.length === 0) {
return hash;
}
if (name.length === 0) {
return hash;
}
for (i = 0; i < name.length; i++) {
character = name.charCodeAt(i);
hash = (hash << 5) - hash + character;
hash = hash & hash;
}
for (i = 0; i < name.length; i++) {
character = name.charCodeAt(i);
hash = (hash << 5) - hash + character;
hash = hash & hash;
}
return hash;
}
return hash;
};
function sanitizeAttributes(attrs) {
if (!attrs || !isObject(attrs)) {
return null;
}
this.sanitizeAttributes = function(attrs) {
if (!attrs || !self.isObject(attrs)) {
return null;
}
var sanitizedAttrs = {};
var sanitizedAttrs = {};
for (var prop in attrs) {
// Make sure that attribute values are not objects or arrays, which are not valid
if (
attrs.hasOwnProperty(prop) &&
Validators.isValidAttributeValue(attrs[prop])
) {
sanitizedAttrs[prop] = attrs[prop];
} else {
mParticle.Logger.warning(
'The corresponding attribute value of ' +
prop +
' must be a string, number, boolean, or null.'
);
for (var prop in attrs) {
// Make sure that attribute values are not objects or arrays, which are not valid
if (
attrs.hasOwnProperty(prop) &&
self.Validators.isValidAttributeValue(attrs[prop])
) {
sanitizedAttrs[prop] = attrs[prop];
} else {
mpInstance.Logger.warning(
'The corresponding attribute value of ' +
prop +
' must be a string, number, boolean, or null.'
);
}
}
}
return sanitizedAttrs;
}
return sanitizedAttrs;
};
var Validators = {
isValidAttributeValue: function(value) {
return value !== undefined && !isObject(value) && !Array.isArray(value);
},
this.Validators = {
isValidAttributeValue: function(value) {
return (
value !== undefined &&
!self.isObject(value) &&
!Array.isArray(value)
);
},
// Neither null nor undefined can be a valid Key
isValidKeyValue: function(key) {
return Boolean(key && !isObject(key) && !Array.isArray(key));
},
// Neither null nor undefined can be a valid Key
isValidKeyValue: function(key) {
return Boolean(key && !self.isObject(key) && !Array.isArray(key));
},
isStringOrNumber: function(value) {
return typeof value === 'string' || typeof value === 'number';
},
isStringOrNumber: function(value) {
return typeof value === 'string' || typeof value === 'number';
},
isNumber: function(value) {
return typeof value === 'number';
},
isNumber: function(value) {
return typeof value === 'number';
},
isFunction: function(fn) {
return typeof fn === 'function';
},
isFunction: function(fn) {
return typeof fn === 'function';
},
validateIdentities: function(identityApiData, method) {
var validIdentityRequestKeys = {
userIdentities: 1,
onUserAlias: 1,
copyUserAttributes: 1,
};
if (identityApiData) {
if (method === 'modify') {
if (
(isObject(identityApiData.userIdentities) &&
!Object.keys(identityApiData.userIdentities).length) ||
!isObject(identityApiData.userIdentities)
) {
validateIdentities: function(identityApiData, method) {
var validIdentityRequestKeys = {
userIdentities: 1,
onUserAlias: 1,
copyUserAttributes: 1,
};
if (identityApiData) {
if (method === 'modify') {
if (
(self.isObject(identityApiData.userIdentities) &&
!Object.keys(identityApiData.userIdentities)
.length) ||
!self.isObject(identityApiData.userIdentities)
) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.ModifyIdentityRequestUserIdentitiesPresent,
};
}
}
for (var key in identityApiData) {
if (identityApiData.hasOwnProperty(key)) {
if (!validIdentityRequestKeys[key]) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.IdentityRequesetInvalidKey,
};
}
if (
key === 'onUserAlias' &&
!mpInstance._Helpers.Validators.isFunction(
identityApiData[key]
)
) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.OnUserAliasType +
typeof identityApiData[key],
};
}
}
}
if (Object.keys(identityApiData).length === 0) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.ModifyIdentityRequestUserIdentitiesPresent,
valid: true,
};
}
}
for (var key in identityApiData) {
if (identityApiData.hasOwnProperty(key)) {
if (!validIdentityRequestKeys[key]) {
} else {
// identityApiData.userIdentities can't be undefined
if (identityApiData.userIdentities === undefined) {
return {

@@ -560,8 +618,8 @@ valid: false,

Constants.Messages.ValidationMessages
.IdentityRequesetInvalidKey,
.UserIdentities,
};
}
if (
key === 'onUserAlias' &&
!Validators.isFunction(identityApiData[key])
// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
} else if (
identityApiData.userIdentities !== null &&
!self.isObject(identityApiData.userIdentities)
) {

@@ -572,71 +630,46 @@ return {

Constants.Messages.ValidationMessages
.OnUserAliasType +
typeof identityApiData[key],
.UserIdentities,
};
}
}
}
if (Object.keys(identityApiData).length === 0) {
return {
valid: true,
};
} else {
// identityApiData.userIdentities can't be undefined
if (identityApiData.userIdentities === undefined) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.UserIdentities,
};
// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
} else if (
identityApiData.userIdentities !== null &&
!isObject(identityApiData.userIdentities)
) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.UserIdentities,
};
}
if (
isObject(identityApiData.userIdentities) &&
Object.keys(identityApiData.userIdentities).length
) {
for (var identityType in identityApiData.userIdentities) {
if (
identityApiData.userIdentities.hasOwnProperty(
identityType
)
) {
if (
self.isObject(identityApiData.userIdentities) &&
Object.keys(identityApiData.userIdentities).length
) {
for (var identityType in identityApiData.userIdentities) {
if (
Types.IdentityType.getIdentityType(
identityApiData.userIdentities.hasOwnProperty(
identityType
) === false
)
) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.UserIdentitiesInvalidKey,
};
}
if (
!(
typeof identityApiData.userIdentities[
if (
Types.IdentityType.getIdentityType(
identityType
] === 'string' ||
identityApiData.userIdentities[
identityType
] === null
)
) {
return {
valid: false,
error:
Constants.Messages.ValidationMessages
.UserIdentitiesInvalidValues,
};
) === false
) {
return {
valid: false,
error:
Constants.Messages
.ValidationMessages
.UserIdentitiesInvalidKey,
};
}
if (
!(
typeof identityApiData.userIdentities[
identityType
] === 'string' ||
identityApiData.userIdentities[
identityType
] === null
)
) {
return {
valid: false,
error:
Constants.Messages
.ValidationMessages
.UserIdentitiesInvalidValues,
};
}
}

@@ -647,70 +680,50 @@ }

}
}
return {
valid: true,
};
},
};
return {
valid: true,
};
},
};
function isDelayedByIntegration(delayedIntegrations, timeoutStart, now) {
if (
now - timeoutStart >
mParticle.Store.SDKConfig.integrationDelayTimeout
this.isDelayedByIntegration = function(
delayedIntegrations,
timeoutStart,
now
) {
if (
now - timeoutStart >
mpInstance._Store.SDKConfig.integrationDelayTimeout
) {
return false;
}
for (var integration in delayedIntegrations) {
if (delayedIntegrations[integration] === true) {
return true;
} else {
continue;
}
}
return false;
}
for (var integration in delayedIntegrations) {
if (delayedIntegrations[integration] === true) {
return true;
};
this.createMainStorageName = function(workspaceToken) {
if (workspaceToken) {
return StorageNames.currentStorageName + '_' + workspaceToken;
} else {
continue;
return StorageNames.currentStorageName;
}
}
return false;
}
};
function createMainStorageName(workspaceToken) {
if (workspaceToken) {
return StorageNames.currentStorageName + '_' + workspaceToken;
} else {
return StorageNames.currentStorageName;
}
}
this.createProductStorageName = function(workspaceToken) {
if (workspaceToken) {
return (
StorageNames.currentStorageProductsName + '_' + workspaceToken
);
} else {
return StorageNames.currentStorageProductsName;
}
};
function createProductStorageName(workspaceToken) {
if (workspaceToken) {
return StorageNames.currentStorageProductsName + '_' + workspaceToken;
} else {
return StorageNames.currentStorageProductsName;
}
this.isSlug = function(str) {
return str === Slugify(str);
};
}
export default {
canLog: canLog,
extend: extend,
isObject: isObject,
inArray: inArray,
createServiceUrl: createServiceUrl,
createXHR: createXHR,
generateUniqueId: generateUniqueId,
filterUserIdentities: filterUserIdentities,
filterUserIdentitiesForForwarders: filterUserIdentitiesForForwarders,
filterUserAttributes: filterUserAttributes,
findKeyInObject: findKeyInObject,
decoded: decoded,
converted: converted,
isEventType: isEventType,
parseNumber: parseNumber,
parseStringOrNumber: parseStringOrNumber,
generateHash: generateHash,
sanitizeAttributes: sanitizeAttributes,
returnConvertedBoolean: returnConvertedBoolean,
invokeCallback: invokeCallback,
invokeAliasCallback: invokeAliasCallback,
getFeatureFlag: getFeatureFlag,
isDelayedByIntegration: isDelayedByIntegration,
createMainStorageName: createMainStorageName,
createProductStorageName: createProductStorageName,
Validators: Validators,
getRampNumber: getRampNumber,
};
function Logger(config) {
var self = this;
var logLevel = config.logLevel || 'warning';

@@ -11,4 +12,4 @@ if (config.hasOwnProperty('logger')) {

if (logLevel !== 'none') {
if (this.logger.verbose && logLevel === 'verbose') {
this.logger.verbose(msg);
if (self.logger.verbose && logLevel === 'verbose') {
self.logger.verbose(msg);
}

@@ -21,6 +22,6 @@ }

if (
this.logger.warning &&
self.logger.warning &&
(logLevel === 'verbose' || logLevel === 'warning')
) {
this.logger.warning(msg);
self.logger.warning(msg);
}

@@ -32,4 +33,4 @@ }

if (logLevel !== 'none') {
if (this.logger.error) {
this.logger.error(msg);
if (self.logger.error) {
self.logger.error(msg);
}

@@ -36,0 +37,0 @@ }

@@ -1,4 +0,2 @@

import Persistence from './persistence';
import Constants from './constants';
import Helpers from './helpers';
import Polyfill from './polyfill';

@@ -15,249 +13,262 @@

// if there is a cookie or localStorage:
// 1. determine which version it is ('mprtcl-api', 'mprtcl-v2', 'mprtcl-v3', 'mprtcl-v4')
// 2. return if 'mprtcl-v4', otherwise migrate to mprtclv4 schema
// 3. if 'mprtcl-api', could be JSSDKv2 or JSSDKv1. JSSDKv2 cookie has a 'globalSettings' key on it
function migrate() {
try {
migrateCookies();
} catch (e) {
Persistence.expireCookies(StorageNames.cookieNameV3);
Persistence.expireCookies(StorageNames.cookieNameV4);
mParticle.Logger.error('Error migrating cookie: ' + e);
}
if (mParticle.Store.isLocalStorageAvailable) {
export default function Migrations(mpInstance) {
var self = this;
// if there is a cookie or localStorage:
// 1. determine which version it is ('mprtcl-api', 'mprtcl-v2', 'mprtcl-v3', 'mprtcl-v4')
// 2. return if 'mprtcl-v4', otherwise migrate to mprtclv4 schema
// 3. if 'mprtcl-api', could be JSSDKv2 or JSSDKv1. JSSDKv2 cookie has a 'globalSettings' key on it
this.migrate = function() {
try {
migrateLocalStorage();
migrateCookies();
} catch (e) {
localStorage.removeItem(StorageNames.localStorageNameV3);
localStorage.removeItem(StorageNames.localStorageNameV4);
mParticle.Logger.error('Error migrating localStorage: ' + e);
mpInstance._Persistence.expireCookies(StorageNames.cookieNameV3);
mpInstance._Persistence.expireCookies(StorageNames.cookieNameV4);
mpInstance.Logger.error('Error migrating cookie: ' + e);
}
}
}
function migrateCookies() {
var cookies = window.document.cookie.split('; '),
foundCookie,
i,
l,
parts,
name,
cookie;
if (mpInstance._Store.isLocalStorageAvailable) {
try {
migrateLocalStorage();
} catch (e) {
localStorage.removeItem(StorageNames.localStorageNameV3);
localStorage.removeItem(StorageNames.localStorageNameV4);
mpInstance.Logger.error('Error migrating localStorage: ' + e);
}
}
};
mParticle.Logger.verbose(
Constants.Messages.InformationMessages.CookieSearch
);
function migrateCookies() {
var cookies = window.document.cookie.split('; '),
foundCookie,
i,
l,
parts,
name,
cookie;
for (i = 0, l = cookies.length; i < l; i++) {
parts = cookies[i].split('=');
name = Helpers.decoded(parts.shift());
cookie = Helpers.decoded(parts.join('='));
mpInstance.Logger.verbose(
Constants.Messages.InformationMessages.CookieSearch
);
//most recent version needs no migration
if (name === mParticle.Store.storageName) {
return;
}
if (name === StorageNames.cookieNameV4) {
// adds cookies to new namespace, removes previous cookie
finishCookieMigration(cookie, StorageNames.cookieNameV4);
if (mParticle.Store.isLocalStorageAvailable) {
migrateProductsToNameSpace();
for (i = 0, l = cookies.length; i < l; i++) {
parts = cookies[i].split('=');
name = mpInstance._Helpers.decoded(parts.shift());
cookie = mpInstance._Helpers.decoded(parts.join('='));
//most recent version needs no migration
if (name === mpInstance._Store.storageName) {
return;
}
return;
// migration path for SDKv1CookiesV3, doesn't need to be encoded
if (name === StorageNames.cookieNameV4) {
// adds cookies to new namespace, removes previous cookie
finishCookieMigration(cookie, StorageNames.cookieNameV4);
if (mpInstance._Store.isLocalStorageAvailable) {
migrateProductsToNameSpace();
}
return;
// migration path for SDKv1CookiesV3, doesn't need to be encoded
}
if (name === StorageNames.cookieNameV3) {
foundCookie = self.convertSDKv1CookiesV3ToSDKv2CookiesV4(
cookie
);
finishCookieMigration(foundCookie, StorageNames.cookieNameV3);
break;
}
}
if (name === StorageNames.cookieNameV3) {
foundCookie = convertSDKv1CookiesV3ToSDKv2CookiesV4(cookie);
finishCookieMigration(foundCookie, StorageNames.cookieNameV3);
break;
}
}
}
function finishCookieMigration(cookie, cookieName) {
var date = new Date(),
cookieDomain = Persistence.getCookieDomain(),
expires,
domain;
function finishCookieMigration(cookie, cookieName) {
var date = new Date(),
cookieDomain = mpInstance._Persistence.getCookieDomain(),
expires,
domain;
expires = new Date(
date.getTime() + StorageNames.CookieExpiration * 24 * 60 * 60 * 1000
).toGMTString();
expires = new Date(
date.getTime() + StorageNames.CookieExpiration * 24 * 60 * 60 * 1000
).toGMTString();
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
mParticle.Logger.verbose(Constants.Messages.InformationMessages.CookieSet);
mpInstance.Logger.verbose(
Constants.Messages.InformationMessages.CookieSet
);
window.document.cookie =
encodeURIComponent(mParticle.Store.storageName) +
'=' +
cookie +
';expires=' +
expires +
';path=/' +
domain;
window.document.cookie =
encodeURIComponent(mpInstance._Store.storageName) +
'=' +
cookie +
';expires=' +
expires +
';path=/' +
domain;
Persistence.expireCookies(cookieName);
mParticle.Store.migratingToIDSyncCookies = true;
}
mpInstance._Persistence.expireCookies(cookieName);
mpInstance._Store.migratingToIDSyncCookies = true;
}
function convertSDKv1CookiesV3ToSDKv2CookiesV4(SDKv1CookiesV3) {
SDKv1CookiesV3 = Persistence.replacePipesWithCommas(
Persistence.replaceApostrophesWithQuotes(SDKv1CookiesV3)
);
var parsedSDKv1CookiesV3 = JSON.parse(SDKv1CookiesV3);
var parsedCookiesV4 = JSON.parse(restructureToV4Cookie(SDKv1CookiesV3));
if (parsedSDKv1CookiesV3.mpid) {
parsedCookiesV4.gs.csm.push(parsedSDKv1CookiesV3.mpid);
// all other values are already encoded, so we have to encode any new values
parsedCookiesV4.gs.csm = Base64.encode(
JSON.stringify(parsedCookiesV4.gs.csm)
this.convertSDKv1CookiesV3ToSDKv2CookiesV4 = function(SDKv1CookiesV3) {
SDKv1CookiesV3 = mpInstance._Persistence.replacePipesWithCommas(
mpInstance._Persistence.replaceApostrophesWithQuotes(SDKv1CookiesV3)
);
migrateProductsFromSDKv1ToSDKv2CookiesV4(
parsedSDKv1CookiesV3,
parsedSDKv1CookiesV3.mpid
);
}
var parsedSDKv1CookiesV3 = JSON.parse(SDKv1CookiesV3);
var parsedCookiesV4 = JSON.parse(restructureToV4Cookie(SDKv1CookiesV3));
return JSON.stringify(parsedCookiesV4);
}
if (parsedSDKv1CookiesV3.mpid) {
parsedCookiesV4.gs.csm.push(parsedSDKv1CookiesV3.mpid);
// all other values are already encoded, so we have to encode any new values
parsedCookiesV4.gs.csm = Base64.encode(
JSON.stringify(parsedCookiesV4.gs.csm)
);
migrateProductsFromSDKv1ToSDKv2CookiesV4(
parsedSDKv1CookiesV3,
parsedSDKv1CookiesV3.mpid
);
}
function restructureToV4Cookie(cookies) {
try {
var cookiesV4Schema = { gs: { csm: [] } };
cookies = JSON.parse(cookies);
return JSON.stringify(parsedCookiesV4);
};
for (var key in cookies) {
if (cookies.hasOwnProperty(key)) {
if (CookiesGlobalSettingsKeys[key]) {
cookiesV4Schema.gs[key] = cookies[key];
} else if (key === 'mpid') {
cookiesV4Schema.cu = cookies[key];
} else if (cookies.mpid) {
cookiesV4Schema[cookies.mpid] =
cookiesV4Schema[cookies.mpid] || {};
if (MPIDKeys[key]) {
cookiesV4Schema[cookies.mpid][key] = cookies[key];
function restructureToV4Cookie(cookies) {
try {
var cookiesV4Schema = { gs: { csm: [] } };
cookies = JSON.parse(cookies);
for (var key in cookies) {
if (cookies.hasOwnProperty(key)) {
if (CookiesGlobalSettingsKeys[key]) {
cookiesV4Schema.gs[key] = cookies[key];
} else if (key === 'mpid') {
cookiesV4Schema.cu = cookies[key];
} else if (cookies.mpid) {
cookiesV4Schema[cookies.mpid] =
cookiesV4Schema[cookies.mpid] || {};
if (MPIDKeys[key]) {
cookiesV4Schema[cookies.mpid][key] = cookies[key];
}
}
}
}
return JSON.stringify(cookiesV4Schema);
} catch (e) {
mpInstance.Logger.error(
'Failed to restructure previous cookie into most current cookie schema'
);
}
return JSON.stringify(cookiesV4Schema);
} catch (e) {
mParticle.Logger.error(
'Failed to restructure previous cookie into most current cookie schema'
}
function migrateProductsToNameSpace() {
var lsProdV4Name = StorageNames.localStorageProductsV4;
var products = localStorage.getItem(
StorageNames.localStorageProductsV4
);
localStorage.setItem(mpInstance._Store.prodStorageName, products);
localStorage.removeItem(lsProdV4Name);
}
}
function migrateProductsToNameSpace() {
var lsProdV4Name = StorageNames.localStorageProductsV4;
var products = localStorage.getItem(StorageNames.localStorageProductsV4);
localStorage.setItem(mParticle.Store.prodStorageName, products);
localStorage.removeItem(lsProdV4Name);
}
function migrateProductsFromSDKv1ToSDKv2CookiesV4(cookies, mpid) {
if (!mpInstance._Store.isLocalStorageAvailable) {
return;
}
function migrateProductsFromSDKv1ToSDKv2CookiesV4(cookies, mpid) {
if (!mParticle.Store.isLocalStorageAvailable) {
return;
}
var localStorageProducts = {};
localStorageProducts[mpid] = {};
if (cookies.cp) {
try {
localStorageProducts[mpid].cp = JSON.parse(
Base64.decode(cookies.cp)
);
} catch (e) {
localStorageProducts[mpid].cp = cookies.cp;
}
var localStorageProducts = {};
localStorageProducts[mpid] = {};
if (cookies.cp) {
try {
localStorageProducts[mpid].cp = JSON.parse(
Base64.decode(cookies.cp)
);
} catch (e) {
localStorageProducts[mpid].cp = cookies.cp;
if (!Array.isArray(localStorageProducts[mpid].cp)) {
localStorageProducts[mpid].cp = [];
}
}
if (!Array.isArray(localStorageProducts[mpid].cp)) {
localStorageProducts[mpid].cp = [];
}
localStorage.setItem(
mpInstance._Store.prodStorageName,
Base64.encode(JSON.stringify(localStorageProducts))
);
}
localStorage.setItem(
mParticle.Store.prodStorageName,
Base64.encode(JSON.stringify(localStorageProducts))
);
}
function migrateLocalStorage() {
var cookies,
v3LSName = StorageNames.localStorageNameV3,
v4LSName = StorageNames.localStorageNameV4,
currentVersionLSData = window.localStorage.getItem(
mpInstance._Store.storageName
),
v4LSData,
v3LSData,
v3LSDataStringCopy;
function migrateLocalStorage() {
var cookies,
v3LSName = StorageNames.localStorageNameV3,
v4LSName = StorageNames.localStorageNameV4,
currentVersionLSData = window.localStorage.getItem(
mParticle.Store.storageName
),
v4LSData,
v3LSData,
v3LSDataStringCopy;
if (currentVersionLSData) {
return;
}
if (currentVersionLSData) {
return;
}
v4LSData = window.localStorage.getItem(v4LSName);
if (v4LSData) {
finishLSMigration(v4LSData, v4LSName);
migrateProductsToNameSpace();
return;
}
v4LSData = window.localStorage.getItem(v4LSName);
if (v4LSData) {
finishLSMigration(v4LSData, v4LSName);
migrateProductsToNameSpace();
return;
}
v3LSData = window.localStorage.getItem(v3LSName);
if (v3LSData) {
mParticle.Store.migratingToIDSyncCookies = true;
v3LSDataStringCopy = v3LSData.slice();
v3LSData = JSON.parse(
Persistence.replacePipesWithCommas(
Persistence.replaceApostrophesWithQuotes(v3LSData)
)
);
// localStorage may contain only products, or the full persistence
// when there is an MPID on the cookie, it is the full persistence
if (v3LSData.mpid) {
v3LSData = window.localStorage.getItem(v3LSName);
if (v3LSData) {
mpInstance._Store.migratingToIDSyncCookies = true;
v3LSDataStringCopy = v3LSData.slice();
v3LSData = JSON.parse(
convertSDKv1CookiesV3ToSDKv2CookiesV4(v3LSDataStringCopy)
mpInstance._Persistence.replacePipesWithCommas(
mpInstance._Persistence.replaceApostrophesWithQuotes(
v3LSData
)
)
);
finishLSMigration(JSON.stringify(v3LSData), v3LSName);
return;
// if no MPID, it is only the products
} else if ((v3LSData.cp || v3LSData.pb) && !v3LSData.mpid) {
cookies = Persistence.getCookie();
if (cookies) {
migrateProductsFromSDKv1ToSDKv2CookiesV4(v3LSData, cookies.cu);
localStorage.removeItem(StorageNames.localStorageNameV3);
// localStorage may contain only products, or the full persistence
// when there is an MPID on the cookie, it is the full persistence
if (v3LSData.mpid) {
v3LSData = JSON.parse(
self.convertSDKv1CookiesV3ToSDKv2CookiesV4(
v3LSDataStringCopy
)
);
finishLSMigration(JSON.stringify(v3LSData), v3LSName);
return;
} else {
localStorage.removeItem(StorageNames.localStorageNameV3);
return;
// if no MPID, it is only the products
} else if ((v3LSData.cp || v3LSData.pb) && !v3LSData.mpid) {
cookies = mpInstance._Persistence.getCookie();
if (cookies) {
migrateProductsFromSDKv1ToSDKv2CookiesV4(
v3LSData,
cookies.cu
);
localStorage.removeItem(StorageNames.localStorageNameV3);
return;
} else {
localStorage.removeItem(StorageNames.localStorageNameV3);
return;
}
}
}
}
function finishLSMigration(data, lsName) {
try {
window.localStorage.setItem(
encodeURIComponent(mParticle.Store.storageName),
data
);
} catch (e) {
mParticle.Logger.error('Error with setting localStorage item.');
function finishLSMigration(data, lsName) {
try {
window.localStorage.setItem(
encodeURIComponent(mpInstance._Store.storageName),
data
);
} catch (e) {
mpInstance.Logger.error(
'Error with setting localStorage item.'
);
}
window.localStorage.removeItem(encodeURIComponent(lsName));
}
window.localStorage.removeItem(encodeURIComponent(lsName));
}
}
export default {
migrate: migrate,
convertSDKv1CookiesV3ToSDKv2CookiesV4: convertSDKv1CookiesV3ToSDKv2CookiesV4,
};

@@ -8,176 +8,191 @@ import Constants from './constants';

function isBridgeV2Available(bridgeName) {
if (!bridgeName) {
export default function NativeSdkHelpers(mpInstance) {
var self = this;
this.isBridgeV2Available = function(bridgeName) {
if (!bridgeName) {
return false;
}
var androidBridgeName =
androidBridgeNameBase + '_' + bridgeName + '_v2';
var iosBridgeName = iosBridgeNameBase + '_' + bridgeName + '_v2';
// iOS v2 bridge
if (
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)
) {
return true;
}
// other iOS v2 bridge
// TODO: what to do about people setting things on mParticle itself?
if (
window.mParticle &&
window.mParticle.uiwebviewBridgeName &&
window.mParticle.uiwebviewBridgeName === iosBridgeName
) {
return true;
}
// android
if (window.hasOwnProperty(androidBridgeName)) {
return true;
}
return false;
}
var androidBridgeName = androidBridgeNameBase + '_' + bridgeName + '_v2';
var iosBridgeName = iosBridgeNameBase + '_' + bridgeName + '_v2';
};
// iOS v2 bridge
if (
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)
this.isWebviewEnabled = function(
requiredWebviewBridgeName,
minWebviewBridgeVersion
) {
return true;
}
// other iOS v2 bridge
if (window.mParticle.uiwebviewBridgeName === iosBridgeName) {
return true;
}
// android
if (window.hasOwnProperty(androidBridgeName)) {
return true;
}
return false;
}
mpInstance._Store.bridgeV2Available = self.isBridgeV2Available(
requiredWebviewBridgeName
);
mpInstance._Store.bridgeV1Available = self.isBridgeV1Available();
function isWebviewEnabled(requiredWebviewBridgeName, minWebviewBridgeVersion) {
mParticle.Store.bridgeV2Available = isBridgeV2Available(
requiredWebviewBridgeName
);
mParticle.Store.bridgeV1Available = isBridgeV1Available();
if (minWebviewBridgeVersion === 2) {
return mpInstance._Store.bridgeV2Available;
}
if (minWebviewBridgeVersion === 2) {
return mParticle.Store.bridgeV2Available;
}
// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName
if (window.mParticle) {
if (
window.mParticle.uiwebviewBridgeName &&
window.mParticle.uiwebviewBridgeName !==
iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2'
) {
return false;
}
}
// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName
if (
window.mParticle.uiwebviewBridgeName &&
window.mParticle.uiwebviewBridgeName !==
iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2'
) {
if (minWebviewBridgeVersion < 2) {
// ios
return (
mpInstance._Store.bridgeV2Available ||
mpInstance._Store.bridgeV1Available
);
}
return false;
}
};
if (minWebviewBridgeVersion < 2) {
// ios
return (
mParticle.Store.bridgeV2Available ||
mParticle.Store.bridgeV1Available
);
}
this.isBridgeV1Available = function() {
if (
mpInstance._Store.SDKConfig.useNativeSdk ||
window.mParticleAndroid ||
mpInstance._Store.SDKConfig.isIOS
) {
return true;
}
return false;
}
return false;
};
function isBridgeV1Available() {
if (
mParticle.Store.SDKConfig.useNativeSdk ||
window.mParticleAndroid ||
mParticle.Store.SDKConfig.isIOS
) {
return true;
}
this.sendToNative = function(path, value) {
if (
mpInstance._Store.bridgeV2Available &&
mpInstance._Store.SDKConfig.minWebviewBridgeVersion === 2
) {
self.sendViaBridgeV2(
path,
value,
mpInstance._Store.SDKConfig.requiredWebviewBridgeName
);
return;
}
if (
mpInstance._Store.bridgeV2Available &&
mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2
) {
self.sendViaBridgeV2(
path,
value,
mpInstance._Store.SDKConfig.requiredWebviewBridgeName
);
return;
}
if (
mpInstance._Store.bridgeV1Available &&
mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2
) {
self.sendViaBridgeV1(path, value);
return;
}
};
return false;
}
this.sendViaBridgeV1 = function(path, value) {
if (
window.mParticleAndroid &&
window.mParticleAndroid.hasOwnProperty(path)
) {
mpInstance.Logger.verbose(
Messages.InformationMessages.SendAndroid + path
);
window.mParticleAndroid[path](value);
} else if (mpInstance._Store.SDKConfig.isIOS) {
mpInstance.Logger.verbose(
Messages.InformationMessages.SendIOS + path
);
self.sendViaIframeToIOS(path, value);
}
};
function sendToNative(path, value) {
if (
mParticle.Store.bridgeV2Available &&
mParticle.Store.SDKConfig.minWebviewBridgeVersion === 2
) {
sendViaBridgeV2(
path,
value,
mParticle.Store.SDKConfig.requiredWebviewBridgeName
this.sendViaIframeToIOS = function(path, value) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute(
'src',
'mp-sdk://' + path + '/' + encodeURIComponent(value)
);
return;
}
if (
mParticle.Store.bridgeV2Available &&
mParticle.Store.SDKConfig.minWebviewBridgeVersion < 2
) {
sendViaBridgeV2(
path,
value,
mParticle.Store.SDKConfig.requiredWebviewBridgeName
);
return;
}
if (
mParticle.Store.bridgeV1Available &&
mParticle.Store.SDKConfig.minWebviewBridgeVersion < 2
) {
sendViaBridgeV1(path, value);
return;
}
}
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
};
function sendViaBridgeV1(path, value) {
if (
window.mParticleAndroid &&
window.mParticleAndroid.hasOwnProperty(path)
) {
mParticle.Logger.verbose(
Messages.InformationMessages.SendAndroid + path
);
window.mParticleAndroid[path](value);
} else if (mParticle.Store.SDKConfig.isIOS) {
mParticle.Logger.verbose(Messages.InformationMessages.SendIOS + path);
sendViaIframeToIOS(path, value);
}
}
this.sendViaBridgeV2 = function(path, value, requiredWebviewBridgeName) {
if (!requiredWebviewBridgeName) {
return;
}
function sendViaIframeToIOS(path, value) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute(
'src',
'mp-sdk://' + path + '/' + encodeURIComponent(value)
);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
}
var androidBridgeName =
androidBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
androidBridge = window[androidBridgeName],
iosBridgeName =
iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
iOSBridgeMessageHandler,
iOSBridgeNonMessageHandler;
function sendViaBridgeV2(path, value, requiredWebviewBridgeName) {
if (!requiredWebviewBridgeName) {
return;
}
if (
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers[iosBridgeName]
) {
iOSBridgeMessageHandler =
window.webkit.messageHandlers[iosBridgeName];
}
var androidBridgeName =
androidBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
androidBridge = window[androidBridgeName],
iosBridgeName =
iosBridgeNameBase + '_' + requiredWebviewBridgeName + '_v2',
iOSBridgeMessageHandler,
iOSBridgeNonMessageHandler;
if (mpInstance.uiwebviewBridgeName === iosBridgeName) {
iOSBridgeNonMessageHandler = mpInstance[iosBridgeName];
}
if (
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers[iosBridgeName]
) {
iOSBridgeMessageHandler = window.webkit.messageHandlers[iosBridgeName];
}
if (window.mParticle.uiwebviewBridgeName === iosBridgeName) {
iOSBridgeNonMessageHandler = window.mParticle[iosBridgeName];
}
if (androidBridge && androidBridge.hasOwnProperty(path)) {
mParticle.Logger.verbose(
Messages.InformationMessages.SendAndroid + path
);
androidBridge[path](value);
return;
} else if (iOSBridgeMessageHandler) {
mParticle.Logger.verbose(Messages.InformationMessages.SendIOS + path);
iOSBridgeMessageHandler.postMessage(
JSON.stringify({
path: path,
value: value ? JSON.parse(value) : null,
})
);
} else if (iOSBridgeNonMessageHandler) {
mParticle.Logger.verbose(Messages.InformationMessages.SendIOS + path);
sendViaIframeToIOS(path, value);
}
if (androidBridge && androidBridge.hasOwnProperty(path)) {
mpInstance.Logger.verbose(
Messages.InformationMessages.SendAndroid + path
);
androidBridge[path](value);
return;
} else if (iOSBridgeMessageHandler) {
mpInstance.Logger.verbose(
Messages.InformationMessages.SendIOS + path
);
iOSBridgeMessageHandler.postMessage(
JSON.stringify({
path: path,
value: value ? JSON.parse(value) : null,
})
);
} else if (iOSBridgeNonMessageHandler) {
mpInstance.Logger.verbose(
Messages.InformationMessages.SendIOS + path
);
self.sendViaIframeToIOS(path, value);
}
};
}
export default {
isWebviewEnabled: isWebviewEnabled,
isBridgeV2Available: isBridgeV2Available,
sendToNative: sendToNative,
};

@@ -1,5 +0,3 @@

import Helpers from './helpers';
import Constants from './constants';
import Polyfill from './polyfill';
import Consent from './consent';

@@ -12,541 +10,539 @@ var Base64 = Polyfill.Base64,

function useLocalStorage() {
return (
!mParticle.Store.SDKConfig.useCookieStorage &&
mParticle.Store.isLocalStorageAvailable
);
}
export default function _Persistence(mpInstance) {
var self = this;
this.useLocalStorage = function() {
return (
!mpInstance._Store.SDKConfig.useCookieStorage &&
mpInstance._Store.isLocalStorageAvailable
);
};
function initializeStorage() {
try {
var storage,
localStorageData = getLocalStorage(),
cookies = getCookie(),
allData;
this.initializeStorage = function() {
try {
var storage,
localStorageData = self.getLocalStorage(),
cookies = self.getCookie(),
allData;
// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle
if (!localStorageData && !cookies) {
mParticle.Store.isFirstRun = true;
mParticle.Store.mpid = 0;
} else {
mParticle.Store.isFirstRun = false;
}
// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle
if (!localStorageData && !cookies) {
mpInstance._Store.isFirstRun = true;
mpInstance._Store.mpid = 0;
} else {
mpInstance._Store.isFirstRun = false;
}
if (!mParticle.Store.isLocalStorageAvailable) {
mParticle.Store.SDKConfig.useCookieStorage = true;
}
if (!mpInstance._Store.isLocalStorageAvailable) {
mpInstance._Store.SDKConfig.useCookieStorage = true;
}
if (mParticle.Store.isLocalStorageAvailable) {
storage = window.localStorage;
if (mParticle.Store.SDKConfig.useCookieStorage) {
// For migrating from localStorage to cookies -- If an instance switches from localStorage to cookies, then
// no mParticle cookie exists yet and there is localStorage. Get the localStorage, set them to cookies, then delete the localStorage item.
if (localStorageData) {
if (mpInstance._Store.isLocalStorageAvailable) {
storage = window.localStorage;
if (mpInstance._Store.SDKConfig.useCookieStorage) {
// For migrating from localStorage to cookies -- If an instance switches from localStorage to cookies, then
// no mParticle cookie exists yet and there is localStorage. Get the localStorage, set them to cookies, then delete the localStorage item.
if (localStorageData) {
if (cookies) {
allData = mpInstance._Helpers.extend(
false,
localStorageData,
cookies
);
} else {
allData = localStorageData;
}
storage.removeItem(mpInstance._Store.storageName);
} else if (cookies) {
allData = cookies;
}
self.storeDataInMemory(allData);
} else {
// For migrating from cookie to localStorage -- If an instance is newly switching from cookies to localStorage, then
// no mParticle localStorage exists yet and there are cookies. Get the cookies, set them to localStorage, then delete the cookies.
if (cookies) {
allData = Helpers.extend(
false,
localStorageData,
cookies
);
if (localStorageData) {
allData = mpInstance._Helpers.extend(
false,
localStorageData,
cookies
);
} else {
allData = cookies;
}
self.storeDataInMemory(allData);
self.expireCookies(mpInstance._Store.storageName);
} else {
allData = localStorageData;
self.storeDataInMemory(localStorageData);
}
storage.removeItem(mParticle.Store.storageName);
} else if (cookies) {
allData = cookies;
}
storeDataInMemory(allData);
} else {
// For migrating from cookie to localStorage -- If an instance is newly switching from cookies to localStorage, then
// no mParticle localStorage exists yet and there are cookies. Get the cookies, set them to localStorage, then delete the cookies.
if (cookies) {
if (localStorageData) {
allData = Helpers.extend(
false,
localStorageData,
cookies
self.storeDataInMemory(cookies);
}
try {
if (mpInstance._Store.isLocalStorageAvailable) {
var encodedProducts = localStorage.getItem(
mpInstance._Store.prodStorageName
);
if (encodedProducts) {
var decodedProducts = JSON.parse(
Base64.decode(encodedProducts)
);
} else {
allData = cookies;
}
storeDataInMemory(allData);
expireCookies(mParticle.Store.storageName);
} else {
storeDataInMemory(localStorageData);
if (mpInstance._Store.mpid) {
self.storeProductsInMemory(
decodedProducts,
mpInstance._Store.mpid
);
}
}
} catch (e) {
if (mpInstance._Store.isLocalStorageAvailable) {
localStorage.removeItem(mpInstance._Store.prodStorageName);
}
mpInstance._Store.cartProducts = [];
mpInstance.Logger.error(
'Error loading products in initialization: ' + e
);
}
} else {
storeDataInMemory(cookies);
}
try {
if (mParticle.Store.isLocalStorageAvailable) {
var encodedProducts = localStorage.getItem(
mParticle.Store.prodStorageName
);
if (encodedProducts) {
var decodedProducts = JSON.parse(
Base64.decode(encodedProducts)
);
for (var key in allData) {
if (allData.hasOwnProperty(key)) {
if (!SDKv2NonMPIDCookieKeys[key]) {
mpInstance._Store.nonCurrentUserMPIDs[key] =
allData[key];
}
}
if (mParticle.Store.mpid) {
storeProductsInMemory(
decodedProducts,
mParticle.Store.mpid
);
}
}
self.update();
} catch (e) {
if (mParticle.Store.isLocalStorageAvailable) {
localStorage.removeItem(mParticle.Store.prodStorageName);
if (
self.useLocalStorage() &&
mpInstance._Store.isLocalStorageAvailable
) {
localStorage.removeItem(mpInstance._Store.storageName);
} else {
self.expireCookies(mpInstance._Store.storageName);
}
mParticle.Store.cartProducts = [];
mParticle.Logger.error(
'Error loading products in initialization: ' + e
);
mpInstance.Logger.error('Error initializing storage: ' + e);
}
};
for (var key in allData) {
if (allData.hasOwnProperty(key)) {
if (!SDKv2NonMPIDCookieKeys[key]) {
mParticle.Store.nonCurrentUserMPIDs[key] = allData[key];
}
this.update = function() {
if (!mpInstance._Store.webviewBridgeEnabled) {
if (mpInstance._Store.SDKConfig.useCookieStorage) {
self.setCookie();
}
self.setLocalStorage();
}
update();
} catch (e) {
if (useLocalStorage() && mParticle.Store.isLocalStorageAvailable) {
localStorage.removeItem(mParticle.Store.storageName);
} else {
expireCookies(mParticle.Store.storageName);
}
mParticle.Logger.error('Error initializing storage: ' + e);
}
}
};
function update() {
if (!mParticle.Store.webviewBridgeEnabled) {
if (mParticle.Store.SDKConfig.useCookieStorage) {
setCookie();
this.storeProductsInMemory = function(products, mpid) {
if (products) {
try {
mpInstance._Store.cartProducts =
products[mpid] && products[mpid].cp
? products[mpid].cp
: [];
} catch (e) {
mpInstance.Logger.error(
Messages.ErrorMessages.CookieParseError
);
}
}
};
setLocalStorage();
}
}
function storeProductsInMemory(products, mpid) {
if (products) {
this.storeDataInMemory = function(obj, currentMPID) {
try {
mParticle.Store.cartProducts =
products[mpid] && products[mpid].cp ? products[mpid].cp : [];
} catch (e) {
mParticle.Logger.error(Messages.ErrorMessages.CookieParseError);
}
}
}
function storeDataInMemory(obj, currentMPID) {
try {
if (!obj) {
mParticle.Logger.verbose(
Messages.InformationMessages.CookieNotFound
);
mParticle.Store.clientId =
mParticle.Store.clientId || Helpers.generateUniqueId();
mParticle.Store.deviceId =
mParticle.Store.deviceId || Helpers.generateUniqueId();
} else {
// Set MPID first, then change object to match MPID data
if (currentMPID) {
mParticle.Store.mpid = currentMPID;
if (!obj) {
mpInstance.Logger.verbose(
Messages.InformationMessages.CookieNotFound
);
mpInstance._Store.clientId =
mpInstance._Store.clientId ||
mpInstance._Helpers.generateUniqueId();
mpInstance._Store.deviceId =
mpInstance._Store.deviceId ||
mpInstance._Helpers.generateUniqueId();
} else {
mParticle.Store.mpid = obj.cu || 0;
}
// Set MPID first, then change object to match MPID data
if (currentMPID) {
mpInstance._Store.mpid = currentMPID;
} else {
mpInstance._Store.mpid = obj.cu || 0;
}
obj.gs = obj.gs || {};
obj.gs = obj.gs || {};
mParticle.Store.sessionId = obj.gs.sid || mParticle.Store.sessionId;
mParticle.Store.isEnabled =
typeof obj.gs.ie !== 'undefined'
? obj.gs.ie
: mParticle.Store.isEnabled;
mParticle.Store.sessionAttributes =
obj.gs.sa || mParticle.Store.sessionAttributes;
mParticle.Store.serverSettings =
obj.gs.ss || mParticle.Store.serverSettings;
mParticle.Store.devToken = mParticle.Store.devToken || obj.gs.dt;
mParticle.Store.SDKConfig.appVersion =
mParticle.Store.SDKConfig.appVersion || obj.gs.av;
mParticle.Store.clientId =
obj.gs.cgid ||
mParticle.Store.clientId ||
Helpers.generateUniqueId();
mParticle.Store.deviceId =
obj.gs.das ||
mParticle.Store.deviceId ||
Helpers.generateUniqueId();
mParticle.Store.integrationAttributes = obj.gs.ia || {};
mParticle.Store.context = obj.gs.c || mParticle.Store.context;
mParticle.Store.currentSessionMPIDs =
obj.gs.csm || mParticle.Store.currentSessionMPIDs;
mpInstance._Store.sessionId =
obj.gs.sid || mpInstance._Store.sessionId;
mpInstance._Store.isEnabled =
typeof obj.gs.ie !== 'undefined'
? obj.gs.ie
: mpInstance._Store.isEnabled;
mpInstance._Store.sessionAttributes =
obj.gs.sa || mpInstance._Store.sessionAttributes;
mpInstance._Store.serverSettings =
obj.gs.ss || mpInstance._Store.serverSettings;
mpInstance._Store.devToken =
mpInstance._Store.devToken || obj.gs.dt;
mpInstance._Store.SDKConfig.appVersion =
mpInstance._Store.SDKConfig.appVersion || obj.gs.av;
mpInstance._Store.clientId =
obj.gs.cgid ||
mpInstance._Store.clientId ||
mpInstance._Helpers.generateUniqueId();
mpInstance._Store.deviceId =
obj.gs.das ||
mpInstance._Store.deviceId ||
mpInstance._Helpers.generateUniqueId();
mpInstance._Store.integrationAttributes = obj.gs.ia || {};
mpInstance._Store.context =
obj.gs.c || mpInstance._Store.context;
mpInstance._Store.currentSessionMPIDs =
obj.gs.csm || mpInstance._Store.currentSessionMPIDs;
mParticle.Store.isLoggedIn = obj.l === true;
mpInstance._Store.isLoggedIn = obj.l === true;
if (obj.gs.les) {
mParticle.Store.dateLastEventSent = new Date(obj.gs.les);
}
if (obj.gs.les) {
mpInstance._Store.dateLastEventSent = new Date(obj.gs.les);
}
if (obj.gs.ssd) {
mParticle.Store.sessionStartDate = new Date(obj.gs.ssd);
} else {
mParticle.Store.sessionStartDate = new Date();
}
if (obj.gs.ssd) {
mpInstance._Store.sessionStartDate = new Date(obj.gs.ssd);
} else {
mpInstance._Store.sessionStartDate = new Date();
}
if (currentMPID) {
obj = obj[currentMPID];
} else {
obj = obj[obj.cu];
if (currentMPID) {
obj = obj[currentMPID];
} else {
obj = obj[obj.cu];
}
}
} catch (e) {
mpInstance.Logger.error(Messages.ErrorMessages.CookieParseError);
}
} catch (e) {
mParticle.Logger.error(Messages.ErrorMessages.CookieParseError);
}
}
};
function determineLocalStorageAvailability(storage) {
var result;
this.determineLocalStorageAvailability = function(storage) {
var result;
if (mParticle._forceNoLocalStorage) {
storage = undefined;
}
if (window.mParticle && window.mParticle._forceNoLocalStorage) {
storage = undefined;
}
try {
storage.setItem('mparticle', 'test');
result = storage.getItem('mparticle') === 'test';
storage.removeItem('mparticle');
return result && storage;
} catch (e) {
return false;
}
}
try {
storage.setItem('mparticle', 'test');
result = storage.getItem('mparticle') === 'test';
storage.removeItem('mparticle');
return result && storage;
} catch (e) {
return false;
}
};
function getUserProductsFromLS(mpid) {
if (!mParticle.Store.isLocalStorageAvailable) {
return [];
}
this.getUserProductsFromLS = function(mpid) {
if (!mpInstance._Store.isLocalStorageAvailable) {
return [];
}
var decodedProducts,
userProducts,
parsedProducts,
encodedProducts = localStorage.getItem(mParticle.Store.prodStorageName);
if (encodedProducts) {
decodedProducts = Base64.decode(encodedProducts);
}
// if there is an MPID, we are retrieving the user's products, which is an array
if (mpid) {
try {
if (decodedProducts) {
parsedProducts = JSON.parse(decodedProducts);
var decodedProducts,
userProducts,
parsedProducts,
encodedProducts = localStorage.getItem(
mpInstance._Store.prodStorageName
);
if (encodedProducts) {
decodedProducts = Base64.decode(encodedProducts);
}
// if there is an MPID, we are retrieving the user's products, which is an array
if (mpid) {
try {
if (decodedProducts) {
parsedProducts = JSON.parse(decodedProducts);
}
if (
decodedProducts &&
parsedProducts[mpid] &&
parsedProducts[mpid].cp &&
Array.isArray(parsedProducts[mpid].cp)
) {
userProducts = parsedProducts[mpid].cp;
} else {
userProducts = [];
}
return userProducts;
} catch (e) {
return [];
}
if (
decodedProducts &&
parsedProducts[mpid] &&
parsedProducts[mpid].cp &&
Array.isArray(parsedProducts[mpid].cp)
) {
userProducts = parsedProducts[mpid].cp;
} else {
userProducts = [];
}
return userProducts;
} catch (e) {
} else {
return [];
}
} else {
return [];
}
}
};
function getAllUserProductsFromLS() {
var decodedProducts,
encodedProducts = localStorage.getItem(mParticle.Store.prodStorageName),
parsedDecodedProducts;
if (encodedProducts) {
decodedProducts = Base64.decode(encodedProducts);
}
// returns an object with keys of MPID and values of array of products
try {
parsedDecodedProducts = JSON.parse(decodedProducts);
} catch (e) {
parsedDecodedProducts = {};
}
return parsedDecodedProducts;
}
function setLocalStorage() {
if (!mParticle.Store.isLocalStorageAvailable) {
return;
}
var key = mParticle.Store.storageName,
allLocalStorageProducts = getAllUserProductsFromLS(),
localStorageData = getLocalStorage() || {},
currentUser = mParticle.Identity.getCurrentUser(),
mpid = currentUser ? currentUser.getMPID() : null,
currentUserProducts = {
cp: allLocalStorageProducts[mpid]
? allLocalStorageProducts[mpid].cp
: [],
};
if (mpid) {
allLocalStorageProducts = allLocalStorageProducts || {};
allLocalStorageProducts[mpid] = currentUserProducts;
this.getAllUserProductsFromLS = function() {
var decodedProducts,
encodedProducts = localStorage.getItem(
mpInstance._Store.prodStorageName
),
parsedDecodedProducts;
if (encodedProducts) {
decodedProducts = Base64.decode(encodedProducts);
}
// returns an object with keys of MPID and values of array of products
try {
window.localStorage.setItem(
encodeURIComponent(mParticle.Store.prodStorageName),
Base64.encode(JSON.stringify(allLocalStorageProducts))
);
parsedDecodedProducts = JSON.parse(decodedProducts);
} catch (e) {
mParticle.Logger.error(
'Error with setting products on localStorage.'
);
parsedDecodedProducts = {};
}
}
if (!mParticle.Store.SDKConfig.useCookieStorage) {
localStorageData.gs = localStorageData.gs || {};
return parsedDecodedProducts;
};
localStorageData.l = mParticle.Store.isLoggedIn ? 1 : 0;
if (mParticle.Store.sessionId) {
localStorageData.gs.csm = mParticle.Store.currentSessionMPIDs;
this.setLocalStorage = function() {
if (!mpInstance._Store.isLocalStorageAvailable) {
return;
}
localStorageData.gs.ie = mParticle.Store.isEnabled;
var key = mpInstance._Store.storageName,
allLocalStorageProducts = self.getAllUserProductsFromLS(),
localStorageData = self.getLocalStorage() || {},
currentUser = mpInstance.Identity.getCurrentUser(),
mpid = currentUser ? currentUser.getMPID() : null,
currentUserProducts = {
cp: allLocalStorageProducts[mpid]
? allLocalStorageProducts[mpid].cp
: [],
};
if (mpid) {
localStorageData.cu = mpid;
allLocalStorageProducts = allLocalStorageProducts || {};
allLocalStorageProducts[mpid] = currentUserProducts;
try {
window.localStorage.setItem(
encodeURIComponent(mpInstance._Store.prodStorageName),
Base64.encode(JSON.stringify(allLocalStorageProducts))
);
} catch (e) {
mpInstance.Logger.error(
'Error with setting products on localStorage.'
);
}
}
if (Object.keys(mParticle.Store.nonCurrentUserMPIDs).length) {
localStorageData = Helpers.extend(
{},
localStorageData,
mParticle.Store.nonCurrentUserMPIDs
);
mParticle.Store.nonCurrentUserMPIDs = {};
}
if (!mpInstance._Store.SDKConfig.useCookieStorage) {
localStorageData.gs = localStorageData.gs || {};
localStorageData = setGlobalStorageAttributes(localStorageData);
localStorageData.l = mpInstance._Store.isLoggedIn ? 1 : 0;
try {
window.localStorage.setItem(
encodeURIComponent(key),
encodeCookies(JSON.stringify(localStorageData))
);
} catch (e) {
mParticle.Logger.error('Error with setting localStorage item.');
}
}
}
if (mpInstance._Store.sessionId) {
localStorageData.gs.csm = mpInstance._Store.currentSessionMPIDs;
}
function setGlobalStorageAttributes(data) {
var store = mParticle.Store;
data.gs.sid = store.sessionId;
data.gs.ie = store.isEnabled;
data.gs.sa = store.sessionAttributes;
data.gs.ss = store.serverSettings;
data.gs.dt = store.devToken;
data.gs.les = store.dateLastEventSent
? store.dateLastEventSent.getTime()
: null;
data.gs.av = store.SDKConfig.appVersion;
data.gs.cgid = store.clientId;
data.gs.das = store.deviceId;
data.gs.c = store.context;
data.gs.ssd = store.sessionStartDate
? store.sessionStartDate.getTime()
: null;
data.gs.ia = store.integrationAttributes;
localStorageData.gs.ie = mpInstance._Store.isEnabled;
return data;
}
if (mpid) {
localStorageData.cu = mpid;
}
function getLocalStorage() {
if (!mParticle.Store.isLocalStorageAvailable) {
return null;
}
if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) {
localStorageData = mpInstance._Helpers.extend(
{},
localStorageData,
mpInstance._Store.nonCurrentUserMPIDs
);
mpInstance._Store.nonCurrentUserMPIDs = {};
}
var key = mParticle.Store.storageName,
localStorageData = decodeCookies(window.localStorage.getItem(key)),
obj = {},
j;
if (localStorageData) {
localStorageData = JSON.parse(localStorageData);
for (j in localStorageData) {
if (localStorageData.hasOwnProperty(j)) {
obj[j] = localStorageData[j];
localStorageData = setGlobalStorageAttributes(localStorageData);
try {
window.localStorage.setItem(
encodeURIComponent(key),
self.encodeCookies(JSON.stringify(localStorageData))
);
} catch (e) {
mpInstance.Logger.error(
'Error with setting localStorage item.'
);
}
}
}
};
if (Object.keys(obj).length) {
return obj;
}
function setGlobalStorageAttributes(data) {
var store = mpInstance._Store;
data.gs.sid = store.sessionId;
data.gs.ie = store.isEnabled;
data.gs.sa = store.sessionAttributes;
data.gs.ss = store.serverSettings;
data.gs.dt = store.devToken;
data.gs.les = store.dateLastEventSent
? store.dateLastEventSent.getTime()
: null;
data.gs.av = store.SDKConfig.appVersion;
data.gs.cgid = store.clientId;
data.gs.das = store.deviceId;
data.gs.c = store.context;
data.gs.ssd = store.sessionStartDate
? store.sessionStartDate.getTime()
: null;
data.gs.ia = store.integrationAttributes;
return null;
}
function removeLocalStorage(localStorageName) {
localStorage.removeItem(localStorageName);
}
function retrieveDeviceId() {
if (mParticle.Store.deviceId) {
return mParticle.Store.deviceId;
} else {
return parseDeviceId(mParticle.Store.serverSettings);
return data;
}
}
function parseDeviceId(serverSettings) {
try {
var paramsObj = {},
parts;
this.getLocalStorage = function() {
if (!mpInstance._Store.isLocalStorageAvailable) {
return null;
}
if (serverSettings && serverSettings.uid && serverSettings.uid.Value) {
serverSettings.uid.Value.split('&').forEach(function(param) {
parts = param.split('=');
paramsObj[parts[0]] = parts[1];
});
if (paramsObj['g']) {
return paramsObj['g'];
var key = mpInstance._Store.storageName,
localStorageData = self.decodeCookies(
window.localStorage.getItem(key)
),
obj = {},
j;
if (localStorageData) {
localStorageData = JSON.parse(localStorageData);
for (j in localStorageData) {
if (localStorageData.hasOwnProperty(j)) {
obj[j] = localStorageData[j];
}
}
}
return Helpers.generateUniqueId();
} catch (e) {
return Helpers.generateUniqueId();
if (Object.keys(obj).length) {
return obj;
}
return null;
};
function removeLocalStorage(localStorageName) {
localStorage.removeItem(localStorageName);
}
}
function expireCookies(cookieName) {
var date = new Date(),
expires,
domain,
cookieDomain;
this.expireCookies = function(cookieName) {
var date = new Date(),
expires,
domain,
cookieDomain;
cookieDomain = getCookieDomain();
cookieDomain = self.getCookieDomain();
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toUTCString();
document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain;
}
date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toUTCString();
document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain;
};
function getCookie() {
var cookies = window.document.cookie.split('; '),
key = mParticle.Store.storageName,
i,
l,
parts,
name,
cookie,
result = key ? undefined : {};
this.getCookie = function() {
var cookies = window.document.cookie.split('; '),
key = mpInstance._Store.storageName,
i,
l,
parts,
name,
cookie,
result = key ? undefined : {};
mParticle.Logger.verbose(Messages.InformationMessages.CookieSearch);
mpInstance.Logger.verbose(Messages.InformationMessages.CookieSearch);
for (i = 0, l = cookies.length; i < l; i++) {
parts = cookies[i].split('=');
name = Helpers.decoded(parts.shift());
cookie = Helpers.decoded(parts.join('='));
for (i = 0, l = cookies.length; i < l; i++) {
parts = cookies[i].split('=');
name = mpInstance._Helpers.decoded(parts.shift());
cookie = mpInstance._Helpers.decoded(parts.join('='));
if (key && key === name) {
result = Helpers.converted(cookie);
break;
if (key && key === name) {
result = mpInstance._Helpers.converted(cookie);
break;
}
if (!key) {
result[name] = mpInstance._Helpers.converted(cookie);
}
}
if (!key) {
result[name] = Helpers.converted(cookie);
if (result) {
mpInstance.Logger.verbose(Messages.InformationMessages.CookieFound);
return JSON.parse(self.decodeCookies(result));
} else {
return null;
}
}
};
if (result) {
mParticle.Logger.verbose(Messages.InformationMessages.CookieFound);
return JSON.parse(decodeCookies(result));
} else {
return null;
}
}
// only used in persistence
this.setCookie = function() {
var mpid,
currentUser = mpInstance.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
var date = new Date(),
key = mpInstance._Store.storageName,
cookies = self.getCookie() || {},
expires = new Date(
date.getTime() +
mpInstance._Store.SDKConfig.cookieExpiration *
24 *
60 *
60 *
1000
).toGMTString(),
cookieDomain,
domain,
encodedCookiesWithExpirationAndPath;
function setCookie() {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
var date = new Date(),
key = mParticle.Store.storageName,
cookies = getCookie() || {},
expires = new Date(
date.getTime() +
mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000
).toGMTString(),
cookieDomain,
domain,
encodedCookiesWithExpirationAndPath;
cookieDomain = self.getCookieDomain();
cookieDomain = getCookieDomain();
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
cookies.gs = cookies.gs || {};
cookies.gs = cookies.gs || {};
if (mpInstance._Store.sessionId) {
cookies.gs.csm = mpInstance._Store.currentSessionMPIDs;
}
if (mParticle.Store.sessionId) {
cookies.gs.csm = mParticle.Store.currentSessionMPIDs;
}
if (mpid) {
cookies.cu = mpid;
}
if (mpid) {
cookies.cu = mpid;
}
cookies.l = mpInstance._Store.isLoggedIn ? 1 : 0;
cookies.l = mParticle.Store.isLoggedIn ? 1 : 0;
cookies = setGlobalStorageAttributes(cookies);
cookies = setGlobalStorageAttributes(cookies);
if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) {
cookies = mpInstance._Helpers.extend(
{},
cookies,
mpInstance._Store.nonCurrentUserMPIDs
);
mpInstance._Store.nonCurrentUserMPIDs = {};
}
if (Object.keys(mParticle.Store.nonCurrentUserMPIDs).length) {
cookies = Helpers.extend(
{},
encodedCookiesWithExpirationAndPath = self.reduceAndEncodeCookies(
cookies,
mParticle.Store.nonCurrentUserMPIDs
expires,
domain,
mpInstance._Store.SDKConfig.maxCookieSize
);
mParticle.Store.nonCurrentUserMPIDs = {};
}
encodedCookiesWithExpirationAndPath = reduceAndEncodeCookies(
cookies,
expires,
domain,
mParticle.Store.SDKConfig.maxCookieSize
);
mpInstance.Logger.verbose(Messages.InformationMessages.CookieSet);
mParticle.Logger.verbose(Messages.InformationMessages.CookieSet);
window.document.cookie =
encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath;
};
window.document.cookie =
encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath;
}
/* This function determines if a cookie is greater than the configured maxCookieSize.
/* This function determines if a cookie is greater than the configured maxCookieSize.
- If it is, we remove an MPID and its associated UI/UA/CSD from the cookie.

@@ -563,39 +559,67 @@ - Once removed, check size, and repeat.

*/
function reduceAndEncodeCookies(cookies, expires, domain, maxCookieSize) {
var encodedCookiesWithExpirationAndPath,
currentSessionMPIDs = cookies.gs.csm ? cookies.gs.csm : [];
// Comment 1 above
if (!currentSessionMPIDs.length) {
for (var key in cookies) {
if (cookies.hasOwnProperty(key)) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (
encodedCookiesWithExpirationAndPath.length > maxCookieSize
) {
if (!SDKv2NonMPIDCookieKeys[key] && key !== cookies.cu) {
delete cookies[key];
this.reduceAndEncodeCookies = function(
cookies,
expires,
domain,
maxCookieSize
) {
var encodedCookiesWithExpirationAndPath,
currentSessionMPIDs = cookies.gs.csm ? cookies.gs.csm : [];
// Comment 1 above
if (!currentSessionMPIDs.length) {
for (var key in cookies) {
if (cookies.hasOwnProperty(key)) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (
encodedCookiesWithExpirationAndPath.length >
maxCookieSize
) {
if (
!SDKv2NonMPIDCookieKeys[key] &&
key !== cookies.cu
) {
delete cookies[key];
}
}
}
}
}
} else {
// Comment 2 above - First create an object of all MPIDs on the cookie
var MPIDsOnCookie = {};
for (var potentialMPID in cookies) {
if (cookies.hasOwnProperty(potentialMPID)) {
if (
!SDKv2NonMPIDCookieKeys[potentialMPID] &&
potentialMPID !== cookies.cu
) {
MPIDsOnCookie[potentialMPID] = 1;
} else {
// Comment 2 above - First create an object of all MPIDs on the cookie
var MPIDsOnCookie = {};
for (var potentialMPID in cookies) {
if (cookies.hasOwnProperty(potentialMPID)) {
if (
!SDKv2NonMPIDCookieKeys[potentialMPID] &&
potentialMPID !== cookies.cu
) {
MPIDsOnCookie[potentialMPID] = 1;
}
}
}
}
// Comment 2a above
if (Object.keys(MPIDsOnCookie).length) {
for (var mpid in MPIDsOnCookie) {
// Comment 2a above
if (Object.keys(MPIDsOnCookie).length) {
for (var mpid in MPIDsOnCookie) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (
encodedCookiesWithExpirationAndPath.length >
maxCookieSize
) {
if (MPIDsOnCookie.hasOwnProperty(mpid)) {
if (currentSessionMPIDs.indexOf(mpid) === -1) {
delete cookies[mpid];
}
}
}
}
}
// Comment 2b above
for (var i = 0; i < currentSessionMPIDs.length; i++) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(

@@ -609,74 +633,59 @@ cookies,

) {
if (MPIDsOnCookie.hasOwnProperty(mpid)) {
if (currentSessionMPIDs.indexOf(mpid) === -1) {
delete cookies[mpid];
}
var MPIDtoRemove = currentSessionMPIDs[i];
if (cookies[MPIDtoRemove]) {
mpInstance.Logger.verbose(
'Size of new encoded cookie is larger than maxCookieSize setting of ' +
maxCookieSize +
'. Removing from cookie the earliest logged in MPID containing: ' +
JSON.stringify(cookies[MPIDtoRemove], 0, 2)
);
delete cookies[MPIDtoRemove];
} else {
mpInstance.Logger.error(
'Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' +
maxCookieSize +
'. We recommend using a maxCookieSize of 1500.'
);
}
}
}
}
// Comment 2b above
for (var i = 0; i < currentSessionMPIDs.length; i++) {
encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
cookies,
expires,
domain
);
if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) {
var MPIDtoRemove = currentSessionMPIDs[i];
if (cookies[MPIDtoRemove]) {
mParticle.Logger.verbose(
'Size of new encoded cookie is larger than maxCookieSize setting of ' +
maxCookieSize +
'. Removing from cookie the earliest logged in MPID containing: ' +
JSON.stringify(cookies[MPIDtoRemove], 0, 2)
);
delete cookies[MPIDtoRemove];
} else {
mParticle.Logger.error(
'Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' +
maxCookieSize +
'. We recommend using a maxCookieSize of 1500.'
);
break;
}
} else {
break;
}
}
}
return encodedCookiesWithExpirationAndPath;
}
return encodedCookiesWithExpirationAndPath;
};
function createFullEncodedCookie(cookies, expires, domain) {
return (
encodeCookies(JSON.stringify(cookies)) +
';expires=' +
expires +
';path=/' +
domain
);
}
function createFullEncodedCookie(cookies, expires, domain) {
return (
self.encodeCookies(JSON.stringify(cookies)) +
';expires=' +
expires +
';path=/' +
domain
);
}
function findPrevCookiesBasedOnUI(identityApiData) {
var cookies = getCookie() || getLocalStorage();
var matchedUser;
this.findPrevCookiesBasedOnUI = function(identityApiData) {
var cookies = self.getCookie() || self.getLocalStorage();
var matchedUser;
if (identityApiData) {
for (var requestedIdentityType in identityApiData.userIdentities) {
if (cookies && Object.keys(cookies).length) {
for (var key in cookies) {
// any value in cookies that has an MPID key will be an MPID to search through
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
if (cookies[key].mpid) {
var cookieUIs = cookies[key].ui;
for (var cookieUIType in cookieUIs) {
if (
requestedIdentityType === cookieUIType &&
identityApiData.userIdentities[
requestedIdentityType
] === cookieUIs[cookieUIType]
) {
matchedUser = key;
break;
if (identityApiData) {
for (var requestedIdentityType in identityApiData.userIdentities) {
if (cookies && Object.keys(cookies).length) {
for (var key in cookies) {
// any value in cookies that has an MPID key will be an MPID to search through
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
if (cookies[key].mpid) {
var cookieUIs = cookies[key].ui;
for (var cookieUIType in cookieUIs) {
if (
requestedIdentityType === cookieUIType &&
identityApiData.userIdentities[
requestedIdentityType
] === cookieUIs[cookieUIType]
) {
matchedUser = key;
break;
}
}

@@ -688,54 +697,56 @@ }

}
}
if (matchedUser) {
storeDataInMemory(cookies, matchedUser);
}
}
if (matchedUser) {
self.storeDataInMemory(cookies, matchedUser);
}
};
function encodeCookies(cookie) {
cookie = JSON.parse(cookie);
for (var key in cookie.gs) {
if (cookie.gs.hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
if (cookie.gs[key]) {
// base64 encode any value that is an object or Array in globalSettings
if (
(Array.isArray(cookie.gs[key]) &&
cookie.gs[key].length) ||
(Helpers.isObject(cookie.gs[key]) &&
Object.keys(cookie.gs[key]).length)
) {
cookie.gs[key] = Base64.encode(
JSON.stringify(cookie.gs[key])
);
this.encodeCookies = function(cookie) {
cookie = JSON.parse(cookie);
for (var key in cookie.gs) {
if (cookie.gs.hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
if (cookie.gs[key]) {
// base64 encode any value that is an object or Array in globalSettings
if (
(Array.isArray(cookie.gs[key]) &&
cookie.gs[key].length) ||
(mpInstance._Helpers.isObject(cookie.gs[key]) &&
Object.keys(cookie.gs[key]).length)
) {
cookie.gs[key] = Base64.encode(
JSON.stringify(cookie.gs[key])
);
} else {
delete cookie.gs[key];
}
} else {
delete cookie.gs[key];
}
} else {
} else if (key === 'ie') {
cookie.gs[key] = cookie.gs[key] ? 1 : 0;
} else if (!cookie.gs[key]) {
delete cookie.gs[key];
}
} else if (key === 'ie') {
cookie.gs[key] = cookie.gs[key] ? 1 : 0;
} else if (!cookie.gs[key]) {
delete cookie.gs[key];
}
}
}
for (var mpid in cookie) {
if (cookie.hasOwnProperty(mpid)) {
if (!SDKv2NonMPIDCookieKeys[mpid]) {
for (key in cookie[mpid]) {
if (cookie[mpid].hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
if (
Helpers.isObject(cookie[mpid][key]) &&
Object.keys(cookie[mpid][key]).length
) {
cookie[mpid][key] = Base64.encode(
JSON.stringify(cookie[mpid][key])
);
} else {
delete cookie[mpid][key];
for (var mpid in cookie) {
if (cookie.hasOwnProperty(mpid)) {
if (!SDKv2NonMPIDCookieKeys[mpid]) {
for (key in cookie[mpid]) {
if (cookie[mpid].hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
if (
mpInstance._Helpers.isObject(
cookie[mpid][key]
) &&
Object.keys(cookie[mpid][key]).length
) {
cookie[mpid][key] = Base64.encode(
JSON.stringify(cookie[mpid][key])
);
} else {
delete cookie[mpid][key];
}
}

@@ -747,435 +758,418 @@ }

}
}
return createCookieString(JSON.stringify(cookie));
}
return self.createCookieString(JSON.stringify(cookie));
};
function decodeCookies(cookie) {
try {
if (cookie) {
cookie = JSON.parse(revertCookieString(cookie));
if (Helpers.isObject(cookie) && Object.keys(cookie).length) {
for (var key in cookie.gs) {
if (cookie.gs.hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
cookie.gs[key] = JSON.parse(
Base64.decode(cookie.gs[key])
);
} else if (key === 'ie') {
cookie.gs[key] = Boolean(cookie.gs[key]);
this.decodeCookies = function(cookie) {
try {
if (cookie) {
cookie = JSON.parse(self.revertCookieString(cookie));
if (
mpInstance._Helpers.isObject(cookie) &&
Object.keys(cookie).length
) {
for (var key in cookie.gs) {
if (cookie.gs.hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
cookie.gs[key] = JSON.parse(
Base64.decode(cookie.gs[key])
);
} else if (key === 'ie') {
cookie.gs[key] = Boolean(cookie.gs[key]);
}
}
}
}
for (var mpid in cookie) {
if (cookie.hasOwnProperty(mpid)) {
if (!SDKv2NonMPIDCookieKeys[mpid]) {
for (key in cookie[mpid]) {
if (cookie[mpid].hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
if (cookie[mpid][key].length) {
cookie[mpid][key] = JSON.parse(
Base64.decode(cookie[mpid][key])
);
for (var mpid in cookie) {
if (cookie.hasOwnProperty(mpid)) {
if (!SDKv2NonMPIDCookieKeys[mpid]) {
for (key in cookie[mpid]) {
if (cookie[mpid].hasOwnProperty(key)) {
if (Base64CookieKeys[key]) {
if (cookie[mpid][key].length) {
cookie[mpid][key] = JSON.parse(
Base64.decode(
cookie[mpid][key]
)
);
}
}
}
}
} else if (mpid === 'l') {
cookie[mpid] = Boolean(cookie[mpid]);
}
} else if (mpid === 'l') {
cookie[mpid] = Boolean(cookie[mpid]);
}
}
}
return JSON.stringify(cookie);
}
return JSON.stringify(cookie);
} catch (e) {
mpInstance.Logger.error('Problem with decoding cookie', e);
}
} catch (e) {
mParticle.Logger.error('Problem with decoding cookie', e);
}
}
};
function replaceCommasWithPipes(string) {
return string.replace(/,/g, '|');
}
this.replaceCommasWithPipes = function(string) {
return string.replace(/,/g, '|');
};
function replacePipesWithCommas(string) {
return string.replace(/\|/g, ',');
}
this.replacePipesWithCommas = function(string) {
return string.replace(/\|/g, ',');
};
function replaceApostrophesWithQuotes(string) {
return string.replace(/\'/g, '"');
}
this.replaceApostrophesWithQuotes = function(string) {
return string.replace(/\'/g, '"');
};
function replaceQuotesWithApostrophes(string) {
return string.replace(/\"/g, "'");
}
this.replaceQuotesWithApostrophes = function(string) {
return string.replace(/\"/g, "'");
};
function createCookieString(string) {
return replaceCommasWithPipes(replaceQuotesWithApostrophes(string));
}
this.createCookieString = function(string) {
return self.replaceCommasWithPipes(
self.replaceQuotesWithApostrophes(string)
);
};
function revertCookieString(string) {
return replacePipesWithCommas(replaceApostrophesWithQuotes(string));
}
this.revertCookieString = function(string) {
return self.replacePipesWithCommas(
self.replaceApostrophesWithQuotes(string)
);
};
function getCookieDomain() {
if (mParticle.Store.SDKConfig.cookieDomain) {
return mParticle.Store.SDKConfig.cookieDomain;
} else {
var rootDomain = getDomain(document, location.hostname);
if (rootDomain === '') {
return '';
this.getCookieDomain = function() {
if (mpInstance._Store.SDKConfig.cookieDomain) {
return mpInstance._Store.SDKConfig.cookieDomain;
} else {
return '.' + rootDomain;
var rootDomain = self.getDomain(document, location.hostname);
if (rootDomain === '') {
return '';
} else {
return '.' + rootDomain;
}
}
}
}
};
// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible.
// For example subdomain.domain.co.uk would try the following combinations:
// "co.uk" -> fail
// "domain.co.uk" -> success, return
// "subdomain.domain.co.uk" -> skipped, because already found
function getDomain(doc, locationHostname) {
var i,
testParts,
mpTest = 'mptest=cookie',
hostname = locationHostname.split('.');
for (i = hostname.length - 1; i >= 0; i--) {
testParts = hostname.slice(i).join('.');
doc.cookie = mpTest + ';domain=.' + testParts + ';';
if (doc.cookie.indexOf(mpTest) > -1) {
doc.cookie =
mpTest.split('=')[0] +
'=;domain=.' +
testParts +
';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
return testParts;
// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible.
// For example subdomain.domain.co.uk would try the following combinations:
// "co.uk" -> fail
// "domain.co.uk" -> success, return
// "subdomain.domain.co.uk" -> skipped, because already found
this.getDomain = function(doc, locationHostname) {
var i,
testParts,
mpTest = 'mptest=cookie',
hostname = locationHostname.split('.');
for (i = hostname.length - 1; i >= 0; i--) {
testParts = hostname.slice(i).join('.');
doc.cookie = mpTest + ';domain=.' + testParts + ';';
if (doc.cookie.indexOf(mpTest) > -1) {
doc.cookie =
mpTest.split('=')[0] +
'=;domain=.' +
testParts +
';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
return testParts;
}
}
}
return '';
}
return '';
};
function getUserIdentities(mpid) {
var cookies = getPersistence();
this.getUserIdentities = function(mpid) {
var cookies = self.getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].ui) {
return cookies[mpid].ui;
} else {
return {};
}
}
if (cookies && cookies[mpid] && cookies[mpid].ui) {
return cookies[mpid].ui;
} else {
return {};
}
};
function getAllUserAttributes(mpid) {
var cookies = getPersistence();
this.getAllUserAttributes = function(mpid) {
var cookies = self.getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].ua) {
return cookies[mpid].ua;
} else {
return {};
}
}
if (cookies && cookies[mpid] && cookies[mpid].ua) {
return cookies[mpid].ua;
} else {
return {};
}
};
function getCartProducts(mpid) {
var allCartProducts,
cartProductsString = localStorage.getItem(
mParticle.Store.prodStorageName
);
if (cartProductsString) {
allCartProducts = JSON.parse(Base64.decode(cartProductsString));
if (
allCartProducts &&
allCartProducts[mpid] &&
allCartProducts[mpid].cp
) {
return allCartProducts[mpid].cp;
this.getCartProducts = function(mpid) {
var allCartProducts,
cartProductsString = localStorage.getItem(
mpInstance._Store.prodStorageName
);
if (cartProductsString) {
allCartProducts = JSON.parse(Base64.decode(cartProductsString));
if (
allCartProducts &&
allCartProducts[mpid] &&
allCartProducts[mpid].cp
) {
return allCartProducts[mpid].cp;
}
}
}
return [];
}
return [];
};
function setCartProducts(allProducts) {
if (!mParticle.Store.isLocalStorageAvailable) {
return;
}
this.setCartProducts = function(allProducts) {
if (!mpInstance._Store.isLocalStorageAvailable) {
return;
}
try {
window.localStorage.setItem(
encodeURIComponent(mParticle.Store.prodStorageName),
Base64.encode(JSON.stringify(allProducts))
);
} catch (e) {
mParticle.Logger.error('Error with setting products on localStorage.');
}
}
function saveUserIdentitiesToCookies(mpid, userIdentities) {
if (userIdentities) {
var cookies = getPersistence();
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].ui = userIdentities;
} else {
cookies[mpid] = {
ui: userIdentities,
};
try {
window.localStorage.setItem(
encodeURIComponent(mpInstance._Store.prodStorageName),
Base64.encode(JSON.stringify(allProducts))
);
} catch (e) {
mpInstance.Logger.error(
'Error with setting products on localStorage.'
);
}
};
this.saveUserIdentitiesToCookies = function(mpid, userIdentities) {
if (userIdentities) {
var cookies = self.getPersistence();
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].ui = userIdentities;
} else {
cookies[mpid] = {
ui: userIdentities,
};
}
self.saveCookies(cookies);
}
saveCookies(cookies);
}
}
}
};
function saveUserAttributesToCookies(mpid, userAttributes) {
var cookies = getPersistence();
if (userAttributes) {
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].ui = userAttributes;
} else {
cookies[mpid] = {
ui: userAttributes,
};
this.saveUserAttributesToCookies = function(mpid, userAttributes) {
var cookies = self.getPersistence();
if (userAttributes) {
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].ui = userAttributes;
} else {
cookies[mpid] = {
ui: userAttributes,
};
}
}
self.saveCookies(cookies);
}
saveCookies(cookies);
}
}
};
function saveUserCookieSyncDatesToCookies(mpid, csd) {
if (csd) {
var cookies = getPersistence();
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].csd = csd;
} else {
cookies[mpid] = {
csd: csd,
};
this.saveUserCookieSyncDatesToCookies = function(mpid, csd) {
if (csd) {
var cookies = self.getPersistence();
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].csd = csd;
} else {
cookies[mpid] = {
csd: csd,
};
}
}
self.saveCookies(cookies);
}
saveCookies(cookies);
}
}
};
function saveUserConsentStateToCookies(mpid, consentState) {
//it's currently not supported to set persistence
//for any MPID that's not the current one.
if (consentState || consentState === null) {
var cookies = getPersistence();
if (cookies) {
if (cookies[mpid]) {
cookies[mpid].con = Consent.Serialization.toMinifiedJsonObject(
consentState
);
} else {
cookies[mpid] = {
con: Consent.Serialization.toMinifiedJsonObject(
this.saveUserConsentStateToCookies = function(mpid, consentState) {
//it's currently not supported to set persistence
//for any MPID that's not the current one.
if (consentState || consentState === null) {
var cookies = self.getPersistence();
if (cookies) {
if (cookies[mpid]) {
cookies[
mpid
].con = mpInstance._Consent.ConsentSerialization.toMinifiedJsonObject(
consentState
),
};
);
} else {
cookies[mpid] = {
con: mpInstance._Consent.ConsentSerialization.toMinifiedJsonObject(
consentState
),
};
}
self.saveCookies(cookies);
}
saveCookies(cookies);
}
}
}
};
function saveCookies(cookies) {
var encodedCookies = encodeCookies(JSON.stringify(cookies)),
date = new Date(),
key = mParticle.Store.storageName,
expires = new Date(
date.getTime() +
mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000
).toGMTString(),
cookieDomain = getCookieDomain(),
domain;
this.saveCookies = function(cookies) {
var encodedCookies = self.encodeCookies(JSON.stringify(cookies)),
date = new Date(),
key = mpInstance._Store.storageName,
expires = new Date(
date.getTime() +
mpInstance._Store.SDKConfig.cookieExpiration *
24 *
60 *
60 *
1000
).toGMTString(),
cookieDomain = self.getCookieDomain(),
domain;
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
if (cookieDomain === '') {
domain = '';
} else {
domain = ';domain=' + cookieDomain;
}
if (mParticle.Store.SDKConfig.useCookieStorage) {
var encodedCookiesWithExpirationAndPath = reduceAndEncodeCookies(
cookies,
expires,
domain,
mParticle.Store.SDKConfig.maxCookieSize
);
window.document.cookie =
encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath;
} else {
if (mParticle.Store.isLocalStorageAvailable) {
localStorage.setItem(mParticle.Store.storageName, encodedCookies);
if (mpInstance._Store.SDKConfig.useCookieStorage) {
var encodedCookiesWithExpirationAndPath = self.reduceAndEncodeCookies(
cookies,
expires,
domain,
mpInstance._Store.SDKConfig.maxCookieSize
);
window.document.cookie =
encodeURIComponent(key) +
'=' +
encodedCookiesWithExpirationAndPath;
} else {
if (mpInstance._Store.isLocalStorageAvailable) {
localStorage.setItem(
mpInstance._Store.storageName,
encodedCookies
);
}
}
}
}
};
function getPersistence() {
var cookies;
if (mParticle.Store.SDKConfig.useCookieStorage) {
cookies = getCookie();
} else {
cookies = getLocalStorage();
}
this.getPersistence = function() {
var cookies;
if (mpInstance._Store.SDKConfig.useCookieStorage) {
cookies = self.getCookie();
} else {
cookies = self.getLocalStorage();
}
return cookies;
}
return cookies;
};
function getConsentState(mpid) {
var cookies = getPersistence();
this.getConsentState = function(mpid) {
var cookies = self.getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].con) {
return Consent.Serialization.fromMinifiedJsonObject(cookies[mpid].con);
} else {
return null;
}
}
if (cookies && cookies[mpid] && cookies[mpid].con) {
return mpInstance._Consent.ConsentSerialization.fromMinifiedJsonObject(
cookies[mpid].con
);
} else {
return null;
}
};
function getFirstSeenTime(mpid) {
if (!mpid) {
return null;
}
var cookies = getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].fst) {
return cookies[mpid].fst;
} else {
return null;
}
}
this.getFirstSeenTime = function(mpid) {
if (!mpid) {
return null;
}
var cookies = self.getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].fst) {
return cookies[mpid].fst;
} else {
return null;
}
};
/**
* set the "first seen" time for a user. the time will only be set once for a given
* mpid after which subsequent calls will be ignored
*/
function setFirstSeenTime(mpid, time) {
if (!mpid) {
return;
}
if (!time) {
time = new Date().getTime();
}
var cookies = getPersistence();
if (cookies) {
if (!cookies[mpid]) {
cookies[mpid] = {};
/**
* set the "first seen" time for a user. the time will only be set once for a given
* mpid after which subsequent calls will be ignored
*/
this.setFirstSeenTime = function(mpid, time) {
if (!mpid) {
return;
}
if (!cookies[mpid].fst) {
cookies[mpid].fst = time;
saveCookies(cookies);
if (!time) {
time = new Date().getTime();
}
}
}
var cookies = self.getPersistence();
if (cookies) {
if (!cookies[mpid]) {
cookies[mpid] = {};
}
if (!cookies[mpid].fst) {
cookies[mpid].fst = time;
self.saveCookies(cookies);
}
}
};
/**
* returns the "last seen" time for a user. If the mpid represents the current user, the
* return value will always be the current time, otherwise it will be to stored "last seen"
* time
*/
function getLastSeenTime(mpid) {
if (!mpid) {
return null;
}
if (mpid === mParticle.Identity.getCurrentUser().getMPID()) {
//if the mpid is the current user, its last seen time is the current time
return new Date().getTime();
} else {
var cookies = getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].lst) {
return cookies[mpid].lst;
/**
* returns the "last seen" time for a user. If the mpid represents the current user, the
* return value will always be the current time, otherwise it will be to stored "last seen"
* time
*/
this.getLastSeenTime = function(mpid) {
if (!mpid) {
return null;
}
return null;
}
}
if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) {
//if the mpid is the current user, its last seen time is the current time
return new Date().getTime();
} else {
var cookies = self.getPersistence();
if (cookies && cookies[mpid] && cookies[mpid].lst) {
return cookies[mpid].lst;
}
return null;
}
};
function setLastSeenTime(mpid, time) {
if (!mpid) {
return;
}
if (!time) {
time = new Date().getTime();
}
var cookies = getPersistence();
if (cookies && cookies[mpid]) {
cookies[mpid].lst = time;
saveCookies(cookies);
}
}
this.setLastSeenTime = function(mpid, time) {
if (!mpid) {
return;
}
if (!time) {
time = new Date().getTime();
}
var cookies = self.getPersistence();
if (cookies && cookies[mpid]) {
cookies[mpid].lst = time;
self.saveCookies(cookies);
}
};
function getDeviceId() {
return mParticle.Store.deviceId;
}
this.getDeviceId = function() {
return mpInstance._Store.deviceId;
};
function resetPersistence() {
removeLocalStorage(StorageNames.localStorageName);
removeLocalStorage(StorageNames.localStorageNameV3);
removeLocalStorage(StorageNames.localStorageNameV4);
removeLocalStorage(mParticle.Store.prodStorageName);
removeLocalStorage(StorageNames.localStorageProductsV4);
this.reset_Persistence = function() {
removeLocalStorage(StorageNames.localStorageName);
removeLocalStorage(StorageNames.localStorageNameV3);
removeLocalStorage(StorageNames.localStorageNameV4);
removeLocalStorage(mpInstance._Store.prodStorageName);
removeLocalStorage(StorageNames.localStorageProductsV4);
expireCookies(StorageNames.cookieName);
expireCookies(StorageNames.cookieNameV2);
expireCookies(StorageNames.cookieNameV3);
expireCookies(StorageNames.cookieNameV4);
if (mParticle._isTestEnv) {
var testWorkspaceToken = 'abcdef';
removeLocalStorage(Helpers.createMainStorageName(testWorkspaceToken));
expireCookies(Helpers.createMainStorageName(testWorkspaceToken));
removeLocalStorage(
Helpers.createProductStorageName(testWorkspaceToken)
);
}
self.expireCookies(StorageNames.cookieName);
self.expireCookies(StorageNames.cookieNameV2);
self.expireCookies(StorageNames.cookieNameV3);
self.expireCookies(StorageNames.cookieNameV4);
if (mParticle._isTestEnv) {
var testWorkspaceToken = 'abcdef';
removeLocalStorage(
mpInstance._Helpers.createMainStorageName(testWorkspaceToken)
);
self.expireCookies(
mpInstance._Helpers.createMainStorageName(testWorkspaceToken)
);
removeLocalStorage(
mpInstance._Helpers.createProductStorageName(testWorkspaceToken)
);
}
};
// Forwarder Batching Code
this.forwardingStatsBatches = {
uploadsTable: {},
forwardingStatsEventQueue: [],
};
}
// Forwarder Batching Code
var forwardingStatsBatches = {
uploadsTable: {},
forwardingStatsEventQueue: [],
};
export default {
useLocalStorage: useLocalStorage,
initializeStorage: initializeStorage,
update: update,
determineLocalStorageAvailability: determineLocalStorageAvailability,
getUserProductsFromLS: getUserProductsFromLS,
getAllUserProductsFromLS: getAllUserProductsFromLS,
setLocalStorage: setLocalStorage,
getLocalStorage: getLocalStorage,
storeDataInMemory: storeDataInMemory,
retrieveDeviceId: retrieveDeviceId,
parseDeviceId: parseDeviceId,
expireCookies: expireCookies,
getCookie: getCookie,
setCookie: setCookie,
reduceAndEncodeCookies: reduceAndEncodeCookies,
findPrevCookiesBasedOnUI: findPrevCookiesBasedOnUI,
replaceCommasWithPipes: replaceCommasWithPipes,
replacePipesWithCommas: replacePipesWithCommas,
replaceApostrophesWithQuotes: replaceApostrophesWithQuotes,
replaceQuotesWithApostrophes: replaceQuotesWithApostrophes,
createCookieString: createCookieString,
revertCookieString: revertCookieString,
decodeCookies: decodeCookies,
getCookieDomain: getCookieDomain,
getUserIdentities: getUserIdentities,
getAllUserAttributes: getAllUserAttributes,
getCartProducts: getCartProducts,
setCartProducts: setCartProducts,
saveCookies: saveCookies,
saveUserIdentitiesToCookies: saveUserIdentitiesToCookies,
saveUserAttributesToCookies: saveUserAttributesToCookies,
saveUserCookieSyncDatesToCookies: saveUserCookieSyncDatesToCookies,
saveUserConsentStateToCookies: saveUserConsentStateToCookies,
getPersistence: getPersistence,
getDeviceId: getDeviceId,
resetPersistence: resetPersistence,
getConsentState: getConsentState,
forwardingStatsBatches: forwardingStatsBatches,
getFirstSeenTime: getFirstSeenTime,
getLastSeenTime: getLastSeenTime,
setFirstSeenTime: setFirstSeenTime,
setLastSeenTime: setLastSeenTime,
};

@@ -33,4 +33,10 @@ import * as EventsApi from './eventsApiModels';

CurrencyCode: string;
DataPlan: SDKDataPlan;
}
export interface SDKDataPlan {
PlanVersion?: number | null;
PlanId?: string | null;
}
export interface SDKUserIdentity {

@@ -106,3 +112,6 @@ Identity?: string;

Logger: SDKLoggerApi;
Store: SDKStoreApi;
_Store: SDKStoreApi;
_Helpers: SDKHelpersApi;
getInstance();
ServerModel();
}

@@ -112,4 +121,10 @@

getCurrentUser();
IdentityAPI;
}
export interface SDKHelpersApi {
createServiceUrl(arg0: string, arg1: string): void;
generateUniqueId();
}
export interface SDKLoggerApi {

@@ -116,0 +131,0 @@ error(arg0: string): void;

@@ -9,10 +9,11 @@ import {

SDKProductActionType,
MParticleWebSDK,
} from './sdkRuntimeModels';
import * as EventsApi from './eventsApiModels';
import Types from './types';
import Helpers from './helpers';
export function convertEvents(
mpid: string,
sdkEvents: SDKEvent[]
sdkEvents: SDKEvent[],
mpInstance: MParticleWebSDK
): EventsApi.Batch | null {

@@ -43,3 +44,3 @@ if (!mpid) {

const upload: EventsApi.Batch = {
source_request_id: Helpers.generateUniqueId(),
source_request_id: mpInstance._Helpers.generateUniqueId(),
mpid,

@@ -63,2 +64,8 @@ timestamp_unixtime_ms: new Date().getTime(),

integration_attributes: lastEvent.IntegrationAttributes,
context: {
data_plan: {
plan_version: lastEvent.DataPlan ? lastEvent.DataPlan.PlanVersion: null,
plan_id: lastEvent.DataPlan ? lastEvent.DataPlan.PlanId : null,
},
}
};

@@ -65,0 +72,0 @@ return upload;

import Types from './types';
import Helpers from './helpers';
import Constants from './constants';
var MessageType = Types.MessageType,
ApplicationTransitionType = Types.ApplicationTransitionType,
parseNumber = Helpers.parseNumber;
ApplicationTransitionType = Types.ApplicationTransitionType;
function convertCustomFlags(event, dto) {
var valueArray = [];
dto.flags = {};
export default function ServerModel(mpInstance) {
var self = this;
function convertCustomFlags(event, dto) {
var valueArray = [];
dto.flags = {};
for (var prop in event.CustomFlags) {
valueArray = [];
for (var prop in event.CustomFlags) {
valueArray = [];
if (event.CustomFlags.hasOwnProperty(prop)) {
if (Array.isArray(event.CustomFlags[prop])) {
event.CustomFlags[prop].forEach(function(customFlagProperty) {
if (
typeof customFlagProperty === 'number' ||
typeof customFlagProperty === 'string' ||
typeof customFlagProperty === 'boolean'
if (event.CustomFlags.hasOwnProperty(prop)) {
if (Array.isArray(event.CustomFlags[prop])) {
event.CustomFlags[prop].forEach(function(
customFlagProperty
) {
valueArray.push(customFlagProperty.toString());
}
});
} else if (
typeof event.CustomFlags[prop] === 'number' ||
typeof event.CustomFlags[prop] === 'string' ||
typeof event.CustomFlags[prop] === 'boolean'
) {
valueArray.push(event.CustomFlags[prop].toString());
}
if (
typeof customFlagProperty === 'number' ||
typeof customFlagProperty === 'string' ||
typeof customFlagProperty === 'boolean'
) {
valueArray.push(customFlagProperty.toString());
}
});
} else if (
typeof event.CustomFlags[prop] === 'number' ||
typeof event.CustomFlags[prop] === 'string' ||
typeof event.CustomFlags[prop] === 'boolean'
) {
valueArray.push(event.CustomFlags[prop].toString());
}
if (valueArray.length) {
dto.flags[prop] = valueArray;
if (valueArray.length) {
dto.flags[prop] = valueArray;
}
}
}
}
}
function appendUserInfo(user, event) {
if (!event) {
return;
}
if (!user) {
event.MPID = null;
event.ConsentState = null;
event.UserAttributes = null;
event.UserIdentities = null;
return;
}
if (event.MPID && event.MPID === user.getMPID()) {
return;
}
event.MPID = user.getMPID();
event.ConsentState = user.getConsentState();
event.UserAttributes = user.getAllUserAttributes();
this.appendUserInfo = function(user, event) {
if (!event) {
return;
}
if (!user) {
event.MPID = null;
event.ConsentState = null;
event.UserAttributes = null;
event.UserIdentities = null;
return;
}
if (event.MPID && event.MPID === user.getMPID()) {
return;
}
event.MPID = user.getMPID();
event.ConsentState = user.getConsentState();
event.UserAttributes = user.getAllUserAttributes();
var userIdentities = user.getUserIdentities().userIdentities;
var dtoUserIdentities = {};
for (var identityKey in userIdentities) {
var identityType = Types.IdentityType.getIdentityType(identityKey);
if (identityType !== false) {
dtoUserIdentities[identityType] = userIdentities[identityKey];
var userIdentities = user.getUserIdentities().userIdentities;
var dtoUserIdentities = {};
for (var identityKey in userIdentities) {
var identityType = Types.IdentityType.getIdentityType(identityKey);
if (identityType !== false) {
dtoUserIdentities[identityType] = userIdentities[identityKey];
}
}
}
var validUserIdentities = [];
if (Helpers.isObject(dtoUserIdentities)) {
if (Object.keys(dtoUserIdentities).length) {
for (var key in dtoUserIdentities) {
var userIdentity = {};
userIdentity.Identity = dtoUserIdentities[key];
userIdentity.Type = Helpers.parseNumber(key);
validUserIdentities.push(userIdentity);
var validUserIdentities = [];
if (mpInstance._Helpers.isObject(dtoUserIdentities)) {
if (Object.keys(dtoUserIdentities).length) {
for (var key in dtoUserIdentities) {
var userIdentity = {};
userIdentity.Identity = dtoUserIdentities[key];
userIdentity.Type = mpInstance._Helpers.parseNumber(key);
validUserIdentities.push(userIdentity);
}
}
}
event.UserIdentities = validUserIdentities;
};
function convertProductListToDTO(productList) {
if (!productList) {
return [];
}
return productList.map(function(product) {
return convertProductToDTO(product);
});
}
event.UserIdentities = validUserIdentities;
}
function convertProductListToDTO(productList) {
if (!productList) {
return [];
function convertProductToDTO(product) {
return {
id: mpInstance._Helpers.parseStringOrNumber(product.Sku),
nm: mpInstance._Helpers.parseStringOrNumber(product.Name),
pr: mpInstance._Helpers.parseNumber(product.Price),
qt: mpInstance._Helpers.parseNumber(product.Quantity),
br: mpInstance._Helpers.parseStringOrNumber(product.Brand),
va: mpInstance._Helpers.parseStringOrNumber(product.Variant),
ca: mpInstance._Helpers.parseStringOrNumber(product.Category),
ps: mpInstance._Helpers.parseNumber(product.Position),
cc: mpInstance._Helpers.parseStringOrNumber(product.CouponCode),
tpa: mpInstance._Helpers.parseNumber(product.TotalAmount),
attrs: product.Attributes,
};
}
return productList.map(function(product) {
return convertProductToDTO(product);
});
}
this.convertToConsentStateDTO = function(state) {
if (!state) {
return null;
}
var jsonObject = {};
var gdprConsentState = state.getGDPRConsentState();
if (gdprConsentState) {
var gdpr = {};
jsonObject.gdpr = gdpr;
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var gdprConsent = gdprConsentState[purpose];
jsonObject.gdpr[purpose] = {};
if (typeof gdprConsent.Consented === 'boolean') {
gdpr[purpose].c = gdprConsent.Consented;
}
if (typeof gdprConsent.Timestamp === 'number') {
gdpr[purpose].ts = gdprConsent.Timestamp;
}
if (typeof gdprConsent.ConsentDocument === 'string') {
gdpr[purpose].d = gdprConsent.ConsentDocument;
}
if (typeof gdprConsent.Location === 'string') {
gdpr[purpose].l = gdprConsent.Location;
}
if (typeof gdprConsent.HardwareId === 'string') {
gdpr[purpose].h = gdprConsent.HardwareId;
}
}
}
}
function convertProductToDTO(product) {
return {
id: Helpers.parseStringOrNumber(product.Sku),
nm: Helpers.parseStringOrNumber(product.Name),
pr: parseNumber(product.Price),
qt: parseNumber(product.Quantity),
br: Helpers.parseStringOrNumber(product.Brand),
va: Helpers.parseStringOrNumber(product.Variant),
ca: Helpers.parseStringOrNumber(product.Category),
ps: parseNumber(product.Position),
cc: Helpers.parseStringOrNumber(product.CouponCode),
tpa: parseNumber(product.TotalAmount),
attrs: product.Attributes,
return jsonObject;
};
}
function convertToConsentStateDTO(state) {
if (!state) {
return null;
}
var jsonObject = {};
var gdprConsentState = state.getGDPRConsentState();
if (gdprConsentState) {
var gdpr = {};
jsonObject.gdpr = gdpr;
for (var purpose in gdprConsentState) {
if (gdprConsentState.hasOwnProperty(purpose)) {
var gdprConsent = gdprConsentState[purpose];
jsonObject.gdpr[purpose] = {};
if (typeof gdprConsent.Consented === 'boolean') {
gdpr[purpose].c = gdprConsent.Consented;
}
if (typeof gdprConsent.Timestamp === 'number') {
gdpr[purpose].ts = gdprConsent.Timestamp;
}
if (typeof gdprConsent.ConsentDocument === 'string') {
gdpr[purpose].d = gdprConsent.ConsentDocument;
}
if (typeof gdprConsent.Location === 'string') {
gdpr[purpose].l = gdprConsent.Location;
}
if (typeof gdprConsent.HardwareId === 'string') {
gdpr[purpose].h = gdprConsent.HardwareId;
}
this.createEventObject = function(event) {
var uploadObject = {};
var eventObject = {};
var optOut =
event.messageType === Types.MessageType.OptOut
? !mpInstance._Store.isEnabled
: null;
if (
mpInstance._Store.sessionId ||
event.messageType == Types.MessageType.OptOut ||
mpInstance._Store.webviewBridgeEnabled
) {
if (event.hasOwnProperty('toEventAPIObject')) {
eventObject = event.toEventAPIObject();
} else {
eventObject = {
EventName: event.name || event.messageType,
EventCategory: event.eventType,
EventAttributes: mpInstance._Helpers.sanitizeAttributes(
event.data
),
EventDataType: event.messageType,
CustomFlags: event.customFlags || {},
UserAttributeChanges: event.userAttributeChanges,
UserIdentityChanges: event.userIdentityChanges,
};
}
}
}
return jsonObject;
}
if (event.messageType !== Types.MessageType.SessionEnd) {
mpInstance._Store.dateLastEventSent = new Date();
}
function createEventObject(event) {
var uploadObject = {};
var eventObject = {};
var optOut =
event.messageType === Types.MessageType.OptOut
? !mParticle.Store.isEnabled
: null;
if (
mParticle.Store.sessionId ||
event.messageType == Types.MessageType.OptOut ||
mParticle.Store.webviewBridgeEnabled
) {
if (event.hasOwnProperty('toEventAPIObject')) {
eventObject = event.toEventAPIObject();
} else {
eventObject = {
EventName: event.name || event.messageType,
EventCategory: event.eventType,
EventAttributes: Helpers.sanitizeAttributes(event.data),
EventDataType: event.messageType,
CustomFlags: event.customFlags || {},
UserAttributeChanges: event.userAttributeChanges,
UserIdentityChanges: event.userIdentityChanges,
uploadObject = {
Store: mpInstance._Store.serverSettings,
SDKVersion: Constants.sdkVersion,
SessionId: mpInstance._Store.sessionId,
SessionStartDate: mpInstance._Store.sessionStartDate
? mpInstance._Store.sessionStartDate.getTime()
: null,
Debug: mpInstance._Store.SDKConfig.isDevelopmentMode,
Location: mpInstance._Store.currentPosition,
OptOut: optOut,
ExpandedEventCount: 0,
AppVersion: mpInstance._Store.SDKConfig.appVersion,
ClientGeneratedId: mpInstance._Store.clientId,
DeviceId: mpInstance._Store.deviceId,
IntegrationAttributes: mpInstance._Store.integrationAttributes,
CurrencyCode: mpInstance._Store.currencyCode,
DataPlan: mpInstance._Store.SDKConfig.dataPlan
? mpInstance._Store.SDKConfig.dataPlan
: {},
};
}
if (event.messageType !== Types.MessageType.SessionEnd) {
mParticle.Store.dateLastEventSent = new Date();
}
eventObject.CurrencyCode = mpInstance._Store.currencyCode;
var currentUser = mpInstance.Identity.getCurrentUser();
self.appendUserInfo(currentUser, eventObject);
uploadObject = {
Store: mParticle.Store.serverSettings,
SDKVersion: Constants.sdkVersion,
SessionId: mParticle.Store.sessionId,
SessionStartDate: mParticle.Store.sessionStartDate
? mParticle.Store.sessionStartDate.getTime()
: null,
Debug: mParticle.Store.SDKConfig.isDevelopmentMode,
Location: mParticle.Store.currentPosition,
OptOut: optOut,
ExpandedEventCount: 0,
AppVersion: mParticle.Store.SDKConfig.appVersion,
ClientGeneratedId: mParticle.Store.clientId,
DeviceId: mParticle.Store.deviceId,
IntegrationAttributes: mParticle.Store.integrationAttributes,
CurrencyCode: mParticle.Store.currencyCode,
};
if (event.messageType === Types.MessageType.SessionEnd) {
eventObject.SessionLength =
mpInstance._Store.dateLastEventSent.getTime() -
mpInstance._Store.sessionStartDate.getTime();
eventObject.currentSessionMPIDs =
mpInstance._Store.currentSessionMPIDs;
eventObject.EventAttributes =
mpInstance._Store.sessionAttributes;
eventObject.CurrencyCode = mParticle.Store.currencyCode;
var currentUser = mParticle.Identity.getCurrentUser();
appendUserInfo(currentUser, eventObject);
mpInstance._Store.currentSessionMPIDs = [];
mpInstance._Store.sessionStartDate = null;
}
if (event.messageType === Types.MessageType.SessionEnd) {
eventObject.SessionLength =
mParticle.Store.dateLastEventSent.getTime() -
mParticle.Store.sessionStartDate.getTime();
eventObject.currentSessionMPIDs =
mParticle.Store.currentSessionMPIDs;
eventObject.EventAttributes = mParticle.Store.sessionAttributes;
uploadObject.Timestamp = mpInstance._Store.dateLastEventSent.getTime();
mParticle.Store.currentSessionMPIDs = [];
mParticle.Store.sessionStartDate = null;
return mpInstance._Helpers.extend({}, eventObject, uploadObject);
}
uploadObject.Timestamp = mParticle.Store.dateLastEventSent.getTime();
return null;
};
return Helpers.extend({}, eventObject, uploadObject);
}
this.convertEventToDTO = function(event, isFirstRun) {
var dto = {
n: event.EventName,
et: event.EventCategory,
ua: event.UserAttributes,
ui: event.UserIdentities,
ia: event.IntegrationAttributes,
str: event.Store,
attrs: event.EventAttributes,
sdk: event.SDKVersion,
sid: event.SessionId,
sl: event.SessionLength,
ssd: event.SessionStartDate,
dt: event.EventDataType,
dbg: event.Debug,
ct: event.Timestamp,
lc: event.Location,
o: event.OptOut,
eec: event.ExpandedEventCount,
av: event.AppVersion,
cgid: event.ClientGeneratedId,
das: event.DeviceId,
dp: event.DataPlan,
mpid: event.MPID,
smpids: event.currentSessionMPIDs,
};
return null;
}
var consent = self.convertToConsentStateDTO(event.ConsentState);
if (consent) {
dto.con = consent;
}
function convertEventToDTO(event, isFirstRun) {
var dto = {
n: event.EventName,
et: event.EventCategory,
ua: event.UserAttributes,
ui: event.UserIdentities,
ia: event.IntegrationAttributes,
str: event.Store,
attrs: event.EventAttributes,
sdk: event.SDKVersion,
sid: event.SessionId,
sl: event.SessionLength,
ssd: event.SessionStartDate,
dt: event.EventDataType,
dbg: event.Debug,
ct: event.Timestamp,
lc: event.Location,
o: event.OptOut,
eec: event.ExpandedEventCount,
av: event.AppVersion,
cgid: event.ClientGeneratedId,
das: event.DeviceId,
mpid: event.MPID,
smpids: event.currentSessionMPIDs,
};
if (event.EventDataType === MessageType.AppStateTransition) {
dto.fr = isFirstRun;
dto.iu = false;
dto.at = ApplicationTransitionType.AppInit;
dto.lr = window.location.href || null;
dto.attrs = null;
}
var consent = convertToConsentStateDTO(event.ConsentState);
if (consent) {
dto.con = consent;
}
if (event.CustomFlags) {
convertCustomFlags(event, dto);
}
if (event.EventDataType === MessageType.AppStateTransition) {
dto.fr = isFirstRun;
dto.iu = false;
dto.at = ApplicationTransitionType.AppInit;
dto.lr = window.location.href || null;
dto.attrs = null;
}
if (event.EventDataType === MessageType.Commerce) {
dto.cu = event.CurrencyCode;
if (event.CustomFlags) {
convertCustomFlags(event, dto);
}
if (event.ShoppingCart) {
dto.sc = {
pl: convertProductListToDTO(event.ShoppingCart.ProductList),
};
}
if (event.EventDataType === MessageType.Commerce) {
dto.cu = event.CurrencyCode;
if (event.ShoppingCart) {
dto.sc = {
pl: convertProductListToDTO(event.ShoppingCart.ProductList),
};
}
if (event.ProductAction) {
dto.pd = {
an: event.ProductAction.ProductActionType,
cs: parseNumber(event.ProductAction.CheckoutStep),
co: event.ProductAction.CheckoutOptions,
pl: convertProductListToDTO(event.ProductAction.ProductList),
ti: event.ProductAction.TransactionId,
ta: event.ProductAction.Affiliation,
tcc: event.ProductAction.CouponCode,
tr: parseNumber(event.ProductAction.TotalAmount),
ts: parseNumber(event.ProductAction.ShippingAmount),
tt: parseNumber(event.ProductAction.TaxAmount),
};
} else if (event.PromotionAction) {
dto.pm = {
an: event.PromotionAction.PromotionActionType,
pl: event.PromotionAction.PromotionList.map(function(
promotion
) {
if (event.ProductAction) {
dto.pd = {
an: event.ProductAction.ProductActionType,
cs: mpInstance._Helpers.parseNumber(
event.ProductAction.CheckoutStep
),
co: event.ProductAction.CheckoutOptions,
pl: convertProductListToDTO(
event.ProductAction.ProductList
),
ti: event.ProductAction.TransactionId,
ta: event.ProductAction.Affiliation,
tcc: event.ProductAction.CouponCode,
tr: mpInstance._Helpers.parseNumber(
event.ProductAction.TotalAmount
),
ts: mpInstance._Helpers.parseNumber(
event.ProductAction.ShippingAmount
),
tt: mpInstance._Helpers.parseNumber(
event.ProductAction.TaxAmount
),
};
} else if (event.PromotionAction) {
dto.pm = {
an: event.PromotionAction.PromotionActionType,
pl: event.PromotionAction.PromotionList.map(function(
promotion
) {
return {
id: promotion.Id,
nm: promotion.Name,
cr: promotion.Creative,
ps: promotion.Position ? promotion.Position : 0,
};
}),
};
} else if (event.ProductImpressions) {
dto.pi = event.ProductImpressions.map(function(impression) {
return {
id: promotion.Id,
nm: promotion.Name,
cr: promotion.Creative,
ps: promotion.Position ? promotion.Position : 0,
pil: impression.ProductImpressionList,
pl: convertProductListToDTO(impression.ProductList),
};
}),
};
} else if (event.ProductImpressions) {
dto.pi = event.ProductImpressions.map(function(impression) {
return {
pil: impression.ProductImpressionList,
pl: convertProductListToDTO(impression.ProductList),
};
});
});
}
} else if (event.EventDataType === MessageType.Profile) {
dto.pet = event.ProfileMessageType;
}
} else if (event.EventDataType === MessageType.Profile) {
dto.pet = event.ProfileMessageType;
}
return dto;
return dto;
};
}
export default {
createEventObject: createEventObject,
convertEventToDTO: convertEventToDTO,
convertToConsentStateDTO: convertToConsentStateDTO,
appendUserInfo: appendUserInfo,
};

@@ -1,184 +0,192 @@

import Helpers from './helpers';
import Constants from './constants';
import Types from './types';
import Identity from './identity';
import Persistence from './persistence';
import Events from './events';
var IdentityAPI = Identity.IdentityAPI,
Messages = Constants.Messages,
logEvent = Events.logEvent;
var Messages = Constants.Messages;
function initialize() {
if (mParticle.Store.sessionId) {
var sessionTimeoutInMilliseconds =
mParticle.Store.SDKConfig.sessionTimeout * 60000;
function SessionManager(mpInstance) {
var self = this;
this.initialize = function() {
if (mpInstance._Store.sessionId) {
var sessionTimeoutInMilliseconds =
mpInstance._Store.SDKConfig.sessionTimeout * 60000;
if (
new Date() >
new Date(
mParticle.Store.dateLastEventSent.getTime() +
sessionTimeoutInMilliseconds
)
) {
endSession();
startNewSession();
if (
new Date() >
new Date(
mpInstance._Store.dateLastEventSent.getTime() +
sessionTimeoutInMilliseconds
)
) {
self.endSession();
self.startNewSession();
} else {
var cookies = mpInstance._Persistence.getPersistence();
if (cookies && !cookies.cu) {
mpInstance.Identity.identify(
mpInstance._Store.SDKConfig.identifyRequest,
mpInstance._Store.SDKConfig.identityCallback
);
mpInstance._Store.identifyCalled = true;
mpInstance._Store.SDKConfig.identityCallback = null;
}
}
} else {
var cookies = Persistence.getPersistence();
if (cookies && !cookies.cu) {
IdentityAPI.identify(
mParticle.Store.SDKConfig.identifyRequest,
mParticle.Store.SDKConfig.identityCallback
);
mParticle.Store.identifyCalled = true;
mParticle.Store.SDKConfig.identityCallback = null;
}
self.startNewSession();
}
} else {
startNewSession();
}
}
};
function getSession() {
return mParticle.Store.sessionId;
}
this.getSession = function() {
return mpInstance._Store.sessionId;
};
function startNewSession() {
mParticle.Logger.verbose(Messages.InformationMessages.StartingNewSession);
this.startNewSession = function() {
mpInstance.Logger.verbose(
Messages.InformationMessages.StartingNewSession
);
if (Helpers.canLog()) {
mParticle.Store.sessionId = Helpers.generateUniqueId().toUpperCase();
var currentUser = mParticle.Identity.getCurrentUser(),
mpid = currentUser ? currentUser.getMPID() : null;
if (mpid) {
mParticle.Store.currentSessionMPIDs = [mpid];
}
if (mpInstance._Helpers.canLog()) {
mpInstance._Store.sessionId = mpInstance._Helpers
.generateUniqueId()
.toUpperCase();
var currentUser = mpInstance.Identity.getCurrentUser(),
mpid = currentUser ? currentUser.getMPID() : null;
if (mpid) {
mpInstance._Store.currentSessionMPIDs = [mpid];
}
if (!mParticle.Store.sessionStartDate) {
var date = new Date();
mParticle.Store.sessionStartDate = date;
mParticle.Store.dateLastEventSent = date;
}
if (!mpInstance._Store.sessionStartDate) {
var date = new Date();
mpInstance._Store.sessionStartDate = date;
mpInstance._Store.dateLastEventSent = date;
}
setSessionTimer();
self.setSessionTimer();
if (!mParticle.Store.identifyCalled) {
IdentityAPI.identify(
mParticle.Store.SDKConfig.identifyRequest,
mParticle.Store.SDKConfig.identityCallback
if (!mpInstance._Store.identifyCalled) {
mpInstance.Identity.identify(
mpInstance._Store.SDKConfig.identifyRequest,
mpInstance._Store.SDKConfig.identityCallback
);
mpInstance._Store.identifyCalled = true;
mpInstance._Store.SDKConfig.identityCallback = null;
}
mpInstance._Events.logEvent({
messageType: Types.MessageType.SessionStart,
});
} else {
mpInstance.Logger.verbose(
Messages.InformationMessages.AbandonStartSession
);
mParticle.Store.identifyCalled = true;
mParticle.Store.SDKConfig.identityCallback = null;
}
};
logEvent({ messageType: Types.MessageType.SessionStart });
} else {
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonStartSession
this.endSession = function(override) {
mpInstance.Logger.verbose(
Messages.InformationMessages.StartingEndSession
);
}
}
function endSession(override) {
mParticle.Logger.verbose(Messages.InformationMessages.StartingEndSession);
if (override) {
mpInstance._Events.logEvent({
messageType: Types.MessageType.SessionEnd,
});
if (override) {
logEvent({ messageType: Types.MessageType.SessionEnd });
mpInstance._Store.sessionId = null;
mpInstance._Store.dateLastEventSent = null;
mpInstance._Store.sessionAttributes = {};
mpInstance._Persistence.update();
} else if (mpInstance._Helpers.canLog()) {
var sessionTimeoutInMilliseconds, cookies, timeSinceLastEventSent;
mParticle.Store.sessionId = null;
mParticle.Store.dateLastEventSent = null;
mParticle.Store.sessionAttributes = {};
Persistence.update();
} else if (Helpers.canLog()) {
var sessionTimeoutInMilliseconds, cookies, timeSinceLastEventSent;
cookies =
mpInstance._Persistence.getCookie() ||
mpInstance._Persistence.getLocalStorage();
cookies = Persistence.getCookie() || Persistence.getLocalStorage();
if (!cookies) {
return;
}
if (!cookies) {
return;
}
if (cookies.gs && !cookies.gs.sid) {
mpInstance.Logger.verbose(
Messages.InformationMessages.NoSessionToEnd
);
return;
}
if (cookies.gs && !cookies.gs.sid) {
mParticle.Logger.verbose(
Messages.InformationMessages.NoSessionToEnd
);
return;
}
// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
if (
cookies.gs.sid &&
mpInstance._Store.sessionId !== cookies.gs.sid
) {
mpInstance._Store.sessionId = cookies.gs.sid;
}
// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
if (cookies.gs.sid && mParticle.Store.sessionId !== cookies.gs.sid) {
mParticle.Store.sessionId = cookies.gs.sid;
}
if (cookies.gs && cookies.gs.les) {
sessionTimeoutInMilliseconds =
mpInstance._Store.SDKConfig.sessionTimeout * 60000;
var newDate = new Date().getTime();
timeSinceLastEventSent = newDate - cookies.gs.les;
if (cookies.gs && cookies.gs.les) {
sessionTimeoutInMilliseconds =
mParticle.Store.SDKConfig.sessionTimeout * 60000;
var newDate = new Date().getTime();
timeSinceLastEventSent = newDate - cookies.gs.les;
if (timeSinceLastEventSent < sessionTimeoutInMilliseconds) {
self.setSessionTimer();
} else {
mpInstance._Events.logEvent({
messageType: Types.MessageType.SessionEnd,
});
if (timeSinceLastEventSent < sessionTimeoutInMilliseconds) {
setSessionTimer();
} else {
logEvent({ messageType: Types.MessageType.SessionEnd });
mParticle.Store.sessionId = null;
mParticle.Store.dateLastEventSent = null;
mParticle.Store.sessionStartDate = null;
mParticle.Store.sessionAttributes = {};
Persistence.update();
mpInstance._Store.sessionId = null;
mpInstance._Store.dateLastEventSent = null;
mpInstance._Store.sessionStartDate = null;
mpInstance._Store.sessionAttributes = {};
mpInstance._Persistence.update();
}
}
} else {
mpInstance.Logger.verbose(
Messages.InformationMessages.AbandonEndSession
);
}
} else {
mParticle.Logger.verbose(
Messages.InformationMessages.AbandonEndSession
);
}
}
};
function setSessionTimer() {
var sessionTimeoutInMilliseconds =
mParticle.Store.SDKConfig.sessionTimeout * 60000;
this.setSessionTimer = function() {
var sessionTimeoutInMilliseconds =
mpInstance._Store.SDKConfig.sessionTimeout * 60000;
mParticle.Store.globalTimer = window.setTimeout(function() {
endSession();
}, sessionTimeoutInMilliseconds);
}
mpInstance._Store.globalTimer = window.setTimeout(function() {
self.endSession();
}, sessionTimeoutInMilliseconds);
};
function resetSessionTimer() {
if (!mParticle.Store.webviewBridgeEnabled) {
if (!mParticle.Store.sessionId) {
startNewSession();
this.resetSessionTimer = function() {
if (!mpInstance._Store.webviewBridgeEnabled) {
if (!mpInstance._Store.sessionId) {
self.startNewSession();
}
self.clearSessionTimeout();
self.setSessionTimer();
}
clearSessionTimeout();
setSessionTimer();
}
startNewSessionIfNeeded();
}
self.startNewSessionIfNeeded();
};
function clearSessionTimeout() {
clearTimeout(mParticle.Store.globalTimer);
}
this.clearSessionTimeout = function() {
clearTimeout(mpInstance._Store.globalTimer);
};
function startNewSessionIfNeeded() {
if (!mParticle.Store.webviewBridgeEnabled) {
var cookies = Persistence.getCookie() || Persistence.getLocalStorage();
this.startNewSessionIfNeeded = function() {
if (!mpInstance._Store.webviewBridgeEnabled) {
var cookies =
mpInstance._Persistence.getCookie() ||
mpInstance._Persistence.getLocalStorage();
if (!mParticle.Store.sessionId && cookies) {
if (cookies.sid) {
mParticle.Store.sessionId = cookies.sid;
} else {
startNewSession();
if (!mpInstance._Store.sessionId && cookies) {
if (cookies.sid) {
mpInstance._Store.sessionId = cookies.sid;
} else {
self.startNewSession();
}
}
}
}
};
}
export default {
initialize: initialize,
getSession: getSession,
startNewSession: startNewSession,
endSession: endSession,
setSessionTimer: setSessionTimer,
resetSessionTimer: resetSessionTimer,
clearSessionTimeout: clearSessionTimeout,
};
export default SessionManager;
import Constants from './constants';
import Helpers from './helpers';
var Validators = Helpers.Validators;
function createSDKConfig(config) {

@@ -29,3 +26,3 @@ var sdkConfig = {};

export default function Store(config, logger) {
export default function Store(config, mpInstance) {
var defaultStore = {

@@ -82,3 +79,3 @@ isEnabled: true,

if (config.hasOwnProperty('isDevelopmentMode')) {
this.SDKConfig.isDevelopmentMode = Helpers.returnConvertedBoolean(
this.SDKConfig.isDevelopmentMode = mpInstance._Helpers.returnConvertedBoolean(
config.isDevelopmentMode

@@ -134,3 +131,6 @@ );

} else {
this.SDKConfig.isIOS = mParticle.isIOS || false;
this.SDKConfig.isIOS =
window.mParticle && window.mParticle.isIOS
? window.mParticle.isIOS
: false;
}

@@ -175,6 +175,6 @@

var callback = config.identityCallback;
if (Validators.isFunction(callback)) {
if (mpInstance._Helpers.Validators.isFunction(callback)) {
this.SDKConfig.identityCallback = config.identityCallback;
} else {
logger.warning(
mpInstance.Logger.warning(
'The optional callback must be a function. You tried entering a(n) ' +

@@ -195,2 +195,35 @@ typeof callback,

if (config.hasOwnProperty('dataPlan')) {
this.SDKConfig.dataPlan = {
PlanVersion: null,
PlanId: null,
};
if (config.dataPlan.hasOwnProperty('planId')) {
if (typeof config.dataPlan.planId === 'string') {
if (mpInstance._Helpers.isSlug(config.dataPlan.planId)) {
this.SDKConfig.dataPlan.PlanId = config.dataPlan.planId;
} else {
mpInstance.Logger.error(
'Your data plan id must be in a slug format'
);
}
} else {
mpInstance.Logger.error(
'Your data plan id must be a string'
);
}
}
if (config.dataPlan.hasOwnProperty('planVersion')) {
if (typeof config.dataPlan.planVersion === 'number') {
this.SDKConfig.dataPlan.PlanVersion =
config.dataPlan.planVersion;
} else {
mpInstance.Logger.error(
'Your data plan version must be a number'
);
}
}
}
if (config.hasOwnProperty('forceHttps')) {

@@ -197,0 +230,0 @@ this.SDKConfig.forceHttps = config.forceHttps;

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc