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.7-rc.1 to 2.9.8-rc.1

3

CHANGELOG.md
## Releases
--
#### 2.9.8 - 2019-08-07
* Migrate to ES6 Modules; Replace Browserify with Rollup
#### 2.9.7 - 2019-07-16

@@ -5,0 +8,0 @@ * Bugfix - noHttpCoverage code properly sent to callback

32

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

@@ -12,9 +12,11 @@ "license": "Apache-2.0",

"files": [
"build/mParticle.js",
"build/mParticle.common.js",
"src/"
],
"browser": "src/main.js",
"main": "build/mParticle.common.js",
"module": "src/main.js",
"repository": "https://github.com/mParticle/mparticle-web-sdk",
"scripts": {
"test": "node test/runner.js",
"test": "npm run build && npm run build:tests:prod && DEBUG=false karma start test/karma.config.js",
"test:debug": "DEBUG=true karma start test/karma.config.js",
"test:integration": "npm run test:requirejs",

@@ -24,10 +26,9 @@ "test:requirejs": "npm run test:requirejs:before && npm run test:requirejs:after",

"test:requirejs:after": "FILE_ORDER=after_mp karma start test/karma.requirejs.config.js",
"testKarma": "node test/test-karma.js",
"build": "browserify src/main.js -v -o build/mParticle-dev.js",
"buildTest": "browserify test/src/tests-main.js -v -o test/test-bundle.js --debug",
"buildDocs": "yuidoc src/",
"buildSnippet": "uglifyjs snippet.js -nm -o snippet.min.js",
"testBrowser": "karma start --single-run --browsers=$BROWSER test/karma.config.js",
"watch": "watchify src/main.js -v -o build/mParticle-dev.js --debug",
"watchTests": "watchify test/src/tests-main.js -v -o test/test-bundle.js --debug",
"build": "ENVIRONMENT=prod rollup --config rollup.config.js",
"build:dev": "ENVIRONMENT=dev rollup --config rollup.config.js",
"build:tests:prod": "ENVIRONMENT=prod rollup --config rollup.test.config.js",
"build:docs": "yuidoc src/",
"build:snippet": "uglifyjs snippet.js -nm -o snippet.min.js",
"watch": "ENVIRONMENT=dev rollup --config rollup.config.js -w",
"watch:tests": "ENVIRONMENT=dev rollup --config rollup.test.config.js -w",
"lint": "eslint src/ test/src/"

@@ -41,3 +42,3 @@ },

"chai": "^4.2.0",
"eslint": "^3.17.1",
"eslint": "^6.1.0",
"karma": "^4.0.1",

@@ -52,4 +53,8 @@ "karma-chai": "^0.1.0",

"karma-safari-launcher": "^1.0.0",
"karma-should": "^1.0.0",
"mocha": "^6.0.2",
"pre-commit": "^1.2.2",
"rollup": "^1.16.7",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-node-resolve": "^5.2.0",
"shelljs": "^0.7.8",

@@ -60,5 +65,4 @@ "should": "^7.1.0",

"uglify-js": "^3.4.9",
"watchify": "^3.9.0",
"yuidocjs": "^0.10.2"
}
}

@@ -1,7 +0,8 @@

var Helpers = require('./helpers'),
Constants = require('./constants'),
NativeSdkHelpers = require('./nativeSdkHelpers'),
HTTPCodes = Constants.HTTPCodes,
ServerModel = require('./serverModel'),
Types = require('./types'),
import Helpers from './helpers';
import Constants from './constants';
import NativeSdkHelpers from './nativeSdkHelpers';
import ServerModel from './serverModel';
import Types from './types';
var HTTPCodes = Constants.HTTPCodes,
Messages = Constants.Messages;

@@ -202,3 +203,3 @@

try {
var xhrCallback = function () {
var xhrCallback = function() {
if (xhr.readyState === 4) {

@@ -237,3 +238,3 @@ // when a 200 returns, merge current config with what comes back from config, prioritizing user inputted config

module.exports = {
export default {
sendEventToServer: sendEventToServer,

@@ -245,2 +246,2 @@ sendIdentityRequest: sendIdentityRequest,

getSDKConfiguration: getSDKConfiguration
};
};

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

var Helpers = require('./helpers');
import Helpers from './helpers';

@@ -127,6 +127,6 @@ function createGDPRConsent(consented, timestamp, consentDocument, location, hardwareId) {

var gdprConsentCopy = createGDPRConsent(gdprConsent.Consented,
gdprConsent.Timestamp,
gdprConsent.ConsentDocument,
gdprConsent.Location,
gdprConsent.HardwareId);
gdprConsent.Timestamp,
gdprConsent.ConsentDocument,
gdprConsent.Location,
gdprConsent.HardwareId);
if (gdprConsentCopy) {

@@ -159,7 +159,6 @@ gdpr[normalizedPurpose] = gdprConsentCopy;

module.exports = {
export default {
createGDPRConsent: createGDPRConsent,
Serialization: ConsentSerialization,
createConsentState: createConsentState
};
};

@@ -1,5 +0,6 @@

var sdkVersion = '2.9.7',
sdkVendor = 'mparticle',
platform = 'web',
Messages = {
var Constants = {
sdkVersion: '2.9.8',
sdkVendor: 'mparticle',
platform: 'web',
Messages: {
ErrorMessages: {

@@ -62,3 +63,3 @@ NoToken: 'A token must be specified.',

},
NativeSdkPaths = {
NativeSdkPaths: {
LogEvent: 'logEvent',

@@ -84,3 +85,3 @@ SetUserTag: 'setUserTag',

},
StorageNames = {
StorageNames: {
localStorageName: 'mprtcl-api', // Name of the mP localstorage, had cp and pb even if cookies were used, skipped v2

@@ -97,3 +98,3 @@ localStorageNameV3: 'mprtcl-v3', // v3 Name of the mP localstorage, final version on SDKv1

},
DefaultConfig = {
DefaultConfig: {
cookieDomain: null, // If null, defaults to current location.host

@@ -110,3 +111,3 @@ cookieExpiration: 365, // Cookie expiration time in days

},
DefaultUrls = {
DefaultUrls: {
v1SecureServiceUrl: 'jssdks.mparticle.com/v1/JS/',

@@ -118,3 +119,3 @@ v2SecureServiceUrl: 'jssdks.mparticle.com/v2/JS/',

},
Base64CookieKeys = {
Base64CookieKeys: {
csm: 1,

@@ -129,3 +130,3 @@ sa: 1,

},
SDKv2NonMPIDCookieKeys = {
SDKv2NonMPIDCookieKeys: {
gs: 1,

@@ -137,3 +138,3 @@ cu: 1,

},
HTTPCodes = {
HTTPCodes: {
noHttpCoverage: -1,

@@ -147,19 +148,7 @@ activeIdentityRequest: -2,

},
Features = {
Features: {
Batching: 'batching'
};
}
};
module.exports = {
sdkVersion: sdkVersion,
sdkVendor: sdkVendor,
platform: platform,
Messages: Messages,
NativeSdkPaths: NativeSdkPaths,
StorageNames: StorageNames,
DefaultConfig: DefaultConfig,
DefaultUrls: DefaultUrls,
Base64CookieKeys:Base64CookieKeys,
HTTPCodes: HTTPCodes,
Features: Features,
SDKv2NonMPIDCookieKeys: SDKv2NonMPIDCookieKeys
};
export default Constants;

@@ -1,5 +0,6 @@

var Constants = require('./constants'),
Persistence = require('./persistence'),
Messages = Constants.Messages;
import Constants from './constants';
import Persistence from './persistence';
var Messages = Constants.Messages;
var cookieSyncManager = {

@@ -27,3 +28,3 @@ attemptCookieSync: function(previousMPID, mpid) {

}
cookieSyncManager.performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
}

@@ -41,6 +42,6 @@ return;

if ((new Date()).getTime() > (new Date(lastSyncDateForModule).getTime() + (pixelConfig.frequencyCap * 60 * 1000 * 60 * 24))) {
cookieSyncManager.performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
}
} else {
cookieSyncManager.performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
performCookieSync(urlWithRedirect, pixelConfig.moduleId, mpid, cookies[mpid].csd);
}

@@ -53,12 +54,2 @@ }

performCookieSync: function(url, moduleId, mpid, cookieSyncDates) {
var img = document.createElement('img');
mParticle.Logger.verbose(Messages.InformationMessages.CookieSync);
img.src = url;
cookieSyncDates[moduleId.toString()] = (new Date()).getTime();
Persistence.saveUserCookieSyncDatesToCookies(mpid, cookieSyncDates);
},
replaceMPID: function(string, mpid) {

@@ -73,2 +64,12 @@ return string.replace('%%mpid%%', mpid);

module.exports = cookieSyncManager;
function performCookieSync(url, moduleId, mpid, cookieSyncDates) {
var img = document.createElement('img');
mParticle.Logger.verbose(Messages.InformationMessages.CookieSync);
img.src = url;
cookieSyncDates[moduleId.toString()] = (new Date()).getTime();
Persistence.saveUserCookieSyncDatesToCookies(mpid, cookieSyncDates);
}
export default cookieSyncManager;

@@ -1,7 +0,9 @@

var Types = require('./types'),
Helpers = require('./helpers'),
Validators = Helpers.Validators,
Messages = require('./constants').Messages,
ServerModel = require('./serverModel');
import Types from './types';
import Helpers from './helpers';
import Constants from './constants';
import ServerModel from './serverModel';
var Validators = Helpers.Validators,
Messages = Constants.Messages;
function convertTransactionAttributesToProductAction(transactionAttributes, productAction) {

@@ -320,6 +322,6 @@ productAction.TransactionId = transactionAttributes.Id;

var appEvent = ServerModel.createEventObject(Types.MessageType.PageEvent,
generateExpandedEcommerceName('Impression'),
attributes,
Types.EventType.Transaction
);
generateExpandedEcommerceName('Impression'),
attributes,
Types.EventType.Transaction
);
appEvents.push(appEvent);

@@ -353,6 +355,6 @@ });

var appEvent = ServerModel.createEventObject(Types.MessageType.PageEvent,
generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(commerceEvent.PromotionAction.PromotionActionType)),
attributes,
Types.EventType.Transaction
);
generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(commerceEvent.PromotionAction.PromotionActionType)),
attributes,
Types.EventType.Transaction
);
appEvents.push(appEvent);

@@ -439,3 +441,3 @@ });

module.exports = {
export default {
convertTransactionAttributesToProductAction: convertTransactionAttributesToProductAction,

@@ -446,7 +448,2 @@ getProductActionEventName: getProductActionEventName,

convertPromotionActionToEventType: convertPromotionActionToEventType,
generateExpandedEcommerceName: generateExpandedEcommerceName,
extractProductAttributes: extractProductAttributes,
extractActionAttributes: extractActionAttributes,
extractPromotionAttributes: extractPromotionAttributes,
extractTransactionId: extractTransactionId,
buildProductList: buildProductList,

@@ -459,2 +456,2 @@ createProduct: createProduct,

createCommerceEventObject: createCommerceEventObject
};
};

@@ -1,12 +0,14 @@

var Types = require('./types'),
Constants = require('./constants'),
Helpers = require('./helpers'),
Ecommerce = require('./ecommerce'),
ServerModel = require('./serverModel'),
SessionManager = require('./sessionManager'),
Persistence = require('./persistence'),
Messages = Constants.Messages,
sendEventToServer = require('./apiClient').sendEventToServer,
sendEventToForwarders = require('./forwarders').sendEventToForwarders;
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';
import Forwarders from './forwarders';
var Messages = Constants.Messages,
sendEventToServer = ApiClient.sendEventToServer,
sendEventToForwarders = Forwarders.sendEventToForwarders;
function logEvent(type, name, data, category, cflags) {

@@ -16,4 +18,2 @@ mParticle.Logger.verbose(Messages.InformationMessages.StartingLogEvent + ': ' + name);

if (Helpers.canLog()) {
startNewSessionIfNeeded();
if (data) {

@@ -265,3 +265,2 @@ data = Helpers.sanitizeAttributes(data);

if (Helpers.canLog()) {
startNewSessionIfNeeded();
if (mParticle.Store.webviewBridgeEnabled) {

@@ -359,17 +358,3 @@ // Don't send shopping cart to parent sdks

function startNewSessionIfNeeded() {
if (!mParticle.Store.webviewBridgeEnabled) {
var cookies = Persistence.getCookie() || Persistence.getLocalStorage();
if (!mParticle.Store.sessionId && cookies) {
if (cookies.sid) {
mParticle.Store.sessionId = cookies.sid;
} else {
SessionManager.startNewSession();
}
}
}
}
module.exports = {
export default {
logEvent: logEvent,

@@ -387,5 +372,3 @@ startTracking: startTracking,

parseEventResponse: parseEventResponse,
logCommerceEvent: logCommerceEvent,
addEventHandler: addEventHandler,
startNewSessionIfNeeded: startNewSessionIfNeeded
};
addEventHandler: addEventHandler
};

@@ -1,7 +0,7 @@

var Helpers = require('./helpers'),
Types = require('./types'),
Constants = require('./constants'),
MParticleUser = require('./mParticleUser'),
ApiClient = require('./apiClient'),
Persistence = require('./persistence');
import Helpers from './helpers';
import Types from './types';
import Constants from './constants';
import getFilteredMparticleUser from './mParticleUser';
import ApiClient from './apiClient';
import Persistence from './persistence';

@@ -341,3 +341,3 @@ function initForwarders(userIdentities) {

mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = MParticleUser.getFilteredMparticleUser(user.getMPID(), forwarder);
var filteredUser = getFilteredMparticleUser(user.getMPID(), forwarder);
if (forwarder.onUserIdentified) {

@@ -356,3 +356,3 @@ var result = forwarder.onUserIdentified(filteredUser);

mParticle.Store.activeForwarders.forEach(function(forwarder) {
var filteredUser = MParticleUser.getFilteredMparticleUser(user.getMPID(), forwarder);
var filteredUser = getFilteredMparticleUser(user.getMPID(), forwarder);
if (identityMethod === 'identify') {

@@ -505,3 +505,3 @@ if (forwarder.onIdentifyComplete) {

module.exports = {
export default {
initForwarders: initForwarders,

@@ -514,3 +514,2 @@ applyToForwarders: applyToForwarders,

setForwarderOnIdentityComplete: setForwarderOnIdentityComplete,
prepareForwardingStats: prepareForwardingStats,
getForwarderStatsQueue: getForwarderStatsQueue,

@@ -520,5 +519,4 @@ setForwarderStatsQueue: setForwarderStatsQueue,

isEnabledForUserAttributes: isEnabledForUserAttributes,
configureForwarder: configureForwarder,
configurePixel: configurePixel,
processForwarders: processForwarders
};
};

@@ -1,7 +0,7 @@

var ApiClient = require('./apiClient'),
Helpers = require('./helpers'),
Forwarders = require('./forwarders'),
Persistence = require('./persistence');
import ApiClient from './apiClient';
import Helpers from './helpers';
import Forwarders from './forwarders';
import Persistence from './persistence';
function startForwardingStatsTimer() {
export default function startForwardingStatsTimer() {
mParticle._forwardingStatsTimer = setInterval(function() {

@@ -50,6 +50,2 @@ prepareAndSendForwardingStatsBatch();

}
}
module.exports = {
startForwardingStatsTimer: startForwardingStatsTimer
};
}

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

var Types = require('./types'),
Constants = require('./constants'),
StorageNames = Constants.StorageNames,
import Types from './types';
import Constants from './constants';
var StorageNames = Constants.StorageNames,
pluses = /\+/g;

@@ -14,3 +14,2 @@

function returnConvertedBoolean(data) {

@@ -270,4 +269,4 @@ if (data === 'false' || data === '0') {

return a // if the placeholder was passed, return
? generateRandomValue(a) // a random number
: ( // or otherwise a concatenated string:
? generateRandomValue(a) // a random number
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +

@@ -278,6 +277,6 @@ -1e3 + // -1000 +

-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
generateUniqueId // random hex digits
);
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
generateUniqueId // random hex digits
);
}

@@ -578,3 +577,3 @@

module.exports = {
export default {
canLog: canLog,

@@ -581,0 +580,0 @@ extend: extend,

@@ -1,28 +0,26 @@

var Helpers = require('./helpers'),
Constants = require('./constants'),
ServerModel = require('./serverModel'),
Forwarders = require('./forwarders'),
Persistence = require('./persistence'),
Types = require('./types'),
Messages = Constants.Messages,
NativeSdkHelpers = require('./nativeSdkHelpers'),
import Helpers from './helpers';
import Constants from './constants';
import ServerModel from './serverModel';
import Forwarders from './forwarders';
import Persistence from './persistence';
import Types from './types';
import NativeSdkHelpers from './nativeSdkHelpers';
import ApiClient from './apiClient';
import CookieSyncManager from './cookieSyncManager';
import Events from './events';
var Messages = Constants.Messages,
Validators = Helpers.Validators,
sendIdentityRequest = require('./apiClient').sendIdentityRequest,
CookieSyncManager = require('./cookieSyncManager'),
sendEventToServer = require('./apiClient').sendEventToServer,
HTTPCodes = Constants.HTTPCodes,
Events = require('./events'),
sendEventToForwarders = require('./forwarders').sendEventToForwarders,
sendAliasRequest = require('./apiClient').sendAliasRequest;
sendEventToForwarders = Forwarders.sendEventToForwarders,
sendIdentityRequest = ApiClient.sendIdentityRequest;
var Identity = {
checkIdentitySwap: function(previousMPID, currentMPID, currentSessionMPIDs) {
if (previousMPID && currentMPID && previousMPID !== currentMPID) {
var cookies = Persistence.useLocalStorage() ? Persistence.getLocalStorage() : Persistence.getCookie();
cookies.cu = currentMPID;
cookies.gs.csm = currentSessionMPIDs;
Persistence.saveCookies(cookies);
}
function checkIdentitySwap(previousMPID, currentMPID, currentSessionMPIDs) {
if (previousMPID && currentMPID && previousMPID !== currentMPID) {
var cookies = Persistence.useLocalStorage() ? Persistence.getLocalStorage() : Persistence.getCookie();
cookies.cu = currentMPID;
cookies.gs.csm = currentSessionMPIDs;
Persistence.saveCookies(cookies);
}
};
}

@@ -423,3 +421,3 @@ var IdentityRequest = {

var aliasRequestMessage = IdentityRequest.createAliasNetworkRequest(aliasRequest);
sendAliasRequest(aliasRequestMessage, callback);
ApiClient.sendAliasRequest(aliasRequestMessage, callback);
}

@@ -995,5 +993,5 @@ } else {

Identity.checkIdentitySwap(previousMPID, identityApiResult.mpid, mParticle.Store.currentSessionMPIDs);
checkIdentitySwap(previousMPID, identityApiResult.mpid, mParticle.Store.currentSessionMPIDs);
Helpers.processQueuedEvents(mParticle.Store.eventQueue, identityApiResult.mpid, !mParticle.Store.requireDelay, sendEventToServer, sendEventToForwarders, Events.parseEventResponse);
Helpers.processQueuedEvents(mParticle.Store.eventQueue, identityApiResult.mpid, !mParticle.Store.requireDelay, ApiClient.sendEventToServer, sendEventToForwarders, Events.parseEventResponse);

@@ -1063,8 +1061,8 @@ //if there is any previous migration data

module.exports = {
export default {
checkIdentitySwap: checkIdentitySwap,
IdentityRequest: IdentityRequest,
IdentityAPI: IdentityAPI,
Identity: Identity,
IdentityRequest: IdentityRequest,
mParticleUser: mParticleUser,
mParticleUserCart: mParticleUserCart
};
};

@@ -57,2 +57,2 @@ function Logger(config) {

module.exports = Logger;
export default Logger;

@@ -19,879 +19,872 @@ //

var Polyfill = require('./polyfill'),
Types = require('./types'),
Constants = require('./constants'),
Helpers = require('./helpers'),
NativeSdkHelpers = require('./nativeSdkHelpers'),
CookieSyncManager = require('./cookieSyncManager'),
SessionManager = require('./sessionManager'),
Ecommerce = require('./ecommerce'),
Store = require('./store'),
Logger = require('./logger'),
Persistence = require('./persistence'),
getDeviceId = Persistence.getDeviceId,
Events = require('./events'),
import Polyfill from './polyfill';
import Types from './types';
import Constants from './constants';
import Helpers from './helpers';
import NativeSdkHelpers from './nativeSdkHelpers';
import CookieSyncManager from './cookieSyncManager';
import SessionManager from './sessionManager';
import Ecommerce from './ecommerce';
import Store from './store';
import Logger from './logger';
import Persistence from './persistence';
import Events from './events';
import Migrations from './migrations';
import Forwarders from './forwarders';
import startForwardingStatsTimer from './forwardingStatsUploader';
import Identity from './identity';
import ApiClient from './apiClient';
import Consent from './consent';
var getDeviceId = Persistence.getDeviceId,
Messages = Constants.Messages,
Validators = Helpers.Validators,
Migrations = require('./migrations'),
Forwarders = require('./forwarders'),
ForwardingStatsUploader = require('./forwardingStatsUploader'),
IdentityRequest = require('./identity').IdentityRequest,
Identity = require('./identity').Identity,
IdentityAPI = require('./identity').IdentityAPI,
HTTPCodes = IdentityAPI.HTTPCodes,
mParticleUserCart = require('./identity').mParticleUserCart,
mParticleUser = require('./identity').mParticleUser,
ApiClient = require('./apiClient'),
Consent = require('./consent');
mParticleUser = Identity.mParticleUser,
IdentityAPI = Identity.IdentityAPI,
mParticleUserCart = Identity.mParticleUserCart,
HTTPCodes = Constants.HTTPCodes;
(function(window) {
if (!Array.prototype.forEach) {
Array.prototype.forEach = Polyfill.forEach;
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = Polyfill.forEach;
}
if (!Array.prototype.map) {
Array.prototype.map = Polyfill.map;
}
if (!Array.prototype.map) {
Array.prototype.map = Polyfill.map;
}
if (!Array.prototype.filter) {
Array.prototype.filter = Polyfill.filter;
}
if (!Array.prototype.filter) {
Array.prototype.filter = Polyfill.filter;
}
if (!Array.isArray) {
Array.prototype.isArray = Polyfill.isArray;
}
if (!Array.isArray) {
Array.prototype.isArray = Polyfill.isArray;
}
/**
* Invoke these methods on the mParticle object.
* Example: mParticle.endSession()
*
* @class mParticle
*/
var mParticle = {
config: window.mParticle ? window.mParticle.config : {},
Store: {},
getDeviceId: getDeviceId,
generateHash: Helpers.generateHash,
sessionManager: SessionManager,
cookieSyncManager: CookieSyncManager,
persistence: Persistence,
isIOS: window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false,
Identity: IdentityAPI,
Validators: Validators,
_Identity: Identity,
_IdentityRequest: Identity.IdentityRequest,
IdentityType: Types.IdentityType,
EventType: Types.EventType,
CommerceEventType: Types.CommerceEventType,
PromotionType: Types.PromotionActionType,
ProductActionType: Types.ProductActionType,
/**
* Invoke these methods on the mParticle object.
* Example: mParticle.endSession()
* Initializes the mParticle SDK
*
* @class mParticle
* @method init
* @param {String} apiKey your mParticle assigned API key
* @param {Object} [options] an options object for additional configuration
*/
init: function(apiKey, config) {
if (!config && window.mParticle.config) {
window.console.warn('You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly');
config = window.mParticle.config;
}
// Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
// to it for it to be run after fetched
if (config) {
if (!config.hasOwnProperty('requestConfig') || config.requestConfig) {
ApiClient.getSDKConfiguration(apiKey, config, completeSDKInitialization);
} else {
completeSDKInitialization(apiKey, config);
}
} else {
window.console.error('No config available on the window, please pass a config object to mParticle.init()');
return;
}
},
setLogLevel: function(newLogLevel) {
mParticle.Logger.setLogLevel(newLogLevel);
},
/**
* Completely resets the state of the SDK. mParticle.init(apiKey, window.mParticle.config) will need to be called again.
* @method reset
* @param {Boolean} keepPersistence if passed as true, this method will only reset the in-memory SDK state.
*/
reset: function(config, keepPersistence) {
if (mParticle.Store) {
delete mParticle.Store;
}
mParticle.Store = new Store(config);
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(window.localStorage);
Events.stopTracking();
if (!keepPersistence) {
Persistence.resetPersistence();
}
Persistence.forwardingStatsBatches.uploadsTable = {};
Persistence.forwardingStatsBatches.forwardingStatsEventQueue = [];
mParticle.preInit = {
readyQueue: [],
pixelConfigurations: [],
integrationDelays: {},
featureFlags: {},
forwarderConstructors: [],
isDevelopmentMode: false
};
},
ready: function(f) {
if (mParticle.Store.isInitialized && typeof f === 'function') {
f();
}
else {
mParticle.preInit.readyQueue.push(f);
}
},
/**
* Returns the mParticle SDK version number
* @method getVersion
* @return {String} mParticle SDK version number
*/
getVersion: function() {
return Constants.sdkVersion;
},
/**
* Sets the app version
* @method setAppVersion
* @param {String} version version number
*/
setAppVersion: function(version) {
mParticle.Store.SDKConfig.appVersion = version;
Persistence.update();
},
/**
* Gets the app name
* @method getAppName
* @return {String} App name
*/
getAppName: function() {
return mParticle.Store.SDKConfig.appName;
},
/**
* Sets the app name
* @method setAppName
* @param {String} name App Name
*/
setAppName: function(name) {
mParticle.Store.SDKConfig.appName = name;
},
/**
* Gets the app version
* @method getAppVersion
* @return {String} App version
*/
getAppVersion: function() {
return mParticle.Store.SDKConfig.appVersion;
},
/**
* Stops tracking the location of the user
* @method stopTrackingLocation
*/
stopTrackingLocation: function() {
SessionManager.resetSessionTimer();
Events.stopTracking();
},
/**
* Starts tracking the location of the user
* @method startTrackingLocation
* @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback
*/
startTrackingLocation: function(callback) {
if (!Validators.isFunction(callback)) {
mParticle.Logger.warning('Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.');
}
var mParticle = {
config: window.mParticle ? window.mParticle.config : {},
Store: {},
getDeviceId: getDeviceId,
generateHash: Helpers.generateHash,
sessionManager: SessionManager,
cookieSyncManager: CookieSyncManager,
persistence: Persistence,
isIOS: window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false,
migrations: Migrations,
Identity: IdentityAPI,
Validators: Validators,
_Identity: Identity,
_IdentityRequest: IdentityRequest,
IdentityType: Types.IdentityType,
EventType: Types.EventType,
CommerceEventType: Types.CommerceEventType,
PromotionType: Types.PromotionActionType,
ProductActionType: Types.ProductActionType,
/**
* Initializes the mParticle SDK
*
* @method init
* @param {String} apiKey your mParticle assigned API key
* @param {Object} [options] an options object for additional configuration
*/
init: function(apiKey, config) {
if (!config && window.mParticle.config) {
window.console.warn('You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly');
config = window.mParticle.config;
SessionManager.resetSessionTimer();
Events.startTracking(callback);
},
/**
* Sets the position of the user
* @method setPosition
* @param {Number} lattitude lattitude digit
* @param {Number} longitude longitude digit
*/
setPosition: function(lat, lng) {
SessionManager.resetSessionTimer();
if (typeof lat === 'number' && typeof lng === 'number') {
mParticle.Store.currentPosition = {
lat: lat,
lng: lng
};
}
else {
mParticle.Logger.error('Position latitude and/or longitude must both be of type number');
}
},
/**
* Starts a new session
* @method startNewSession
*/
startNewSession: function() {
SessionManager.startNewSession();
},
/**
* Ends the current session
* @method endSession
*/
endSession: function() {
// Sends true as an over ride vs when endSession is called from the setInterval
SessionManager.endSession(true);
},
/**
* Logs an event to mParticle's servers
* @method logEvent
* @param {String} eventName The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* @param {Object} [customFlags] Additional customFlags
*/
logEvent: function(eventName, eventType, eventInfo, customFlags) {
SessionManager.resetSessionTimer();
if (typeof (eventName) !== 'string') {
mParticle.Logger.error(Messages.ErrorMessages.EventNameInvalidType);
return;
}
if (!eventType) {
eventType = Types.EventType.Unknown;
}
if (!Helpers.isEventType(eventType)) {
mParticle.Logger.error('Invalid event type: ' + eventType + ', must be one of: \n' + JSON.stringify(Types.EventType));
return;
}
if (!Helpers.canLog()) {
mParticle.Logger.error(Messages.ErrorMessages.LoggingDisabled);
return;
}
Events.logEvent(Types.MessageType.PageEvent, eventName, eventInfo, eventType, customFlags);
},
/**
* Used to log custom errors
*
* @method logError
* @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'}
* @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean
*/
logError: function(error, attrs) {
SessionManager.resetSessionTimer();
if (!error) {
return;
}
if (typeof error === 'string') {
error = {
message: error
};
}
var data = {
m: error.message ? error.message : error,
s: 'Error',
t: error.stack
};
if (attrs) {
var sanitized = Helpers.sanitizeAttributes(attrs);
for (var prop in sanitized) {
data[prop] = sanitized[prop];
}
// Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
// to it for it to be run after fetched
if (config) {
if (!config.hasOwnProperty('requestConfig') || config.requestConfig) {
ApiClient.getSDKConfiguration(apiKey, config, completeSDKInitialization);
} else {
completeSDKInitialization(apiKey, config);
}
} else {
window.console.error('No config available on the window, please pass a config object to mParticle.init()');
return;
}
Events.logEvent(Types.MessageType.CrashReport,
error.name ? error.name : 'Error',
data,
Types.EventType.Other);
},
/**
* Logs `click` events
* @method logLink
* @param {String} selector The selector to add a 'click' event to (ex. #purchase-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
logLink: function(selector, eventName, eventType, eventInfo) {
SessionManager.resetSessionTimer();
Events.addEventHandler('click', selector, eventName, eventInfo, eventType);
},
/**
* Logs `submit` events
* @method logForm
* @param {String} selector The selector to add the event handler to (ex. #search-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
logForm: function(selector, eventName, eventType, eventInfo) {
SessionManager.resetSessionTimer();
Events.addEventHandler('submit', selector, eventName, eventInfo, eventType);
},
/**
* Logs a page view
* @method logPageView
* @param {String} eventName The name of the event. Defaults to 'PageView'.
* @param {Object} [attrs] Attributes for the event
* @param {Object} [customFlags] Custom flags for the event
*/
logPageView: function(eventName, attrs, customFlags) {
SessionManager.resetSessionTimer();
if (Helpers.canLog()) {
if (!Validators.isStringOrNumber(eventName)) {
eventName = 'PageView';
}
},
setLogLevel: function(newLogLevel) {
mParticle.Logger.setLogLevel(newLogLevel);
},
/**
* Completely resets the state of the SDK. mParticle.init(apiKey, window.mParticle.config) will need to be called again.
* @method reset
* @param {Boolean} keepPersistence if passed as true, this method will only reset the in-memory SDK state.
*/
reset: function(config, keepPersistence) {
if (mParticle.Store) {
delete mParticle.Store;
if (!attrs) {
attrs = {
hostname: window.location.hostname,
title: window.document.title
};
}
mParticle.Store = new Store(config);
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(window.localStorage);
Events.stopTracking();
if (!keepPersistence) {
Persistence.resetPersistence();
else if (!Helpers.isObject(attrs)){
mParticle.Logger.error('The attributes argument must be an object. A ' + typeof attrs + ' was entered. Please correct and retry.');
return;
}
Persistence.forwardingStatsBatches.uploadsTable = {};
Persistence.forwardingStatsBatches.forwardingStatsEventQueue = [];
mParticle.preInit = {
readyQueue: [],
pixelConfigurations: [],
integrationDelays: {},
featureFlags: {},
forwarderConstructors: [],
isDevelopmentMode: false
};
},
ready: function(f) {
if (mParticle.Store.isInitialized && typeof f === 'function') {
f();
if (customFlags && !Helpers.isObject(customFlags)) {
mParticle.Logger.error('The customFlags argument must be an object. A ' + typeof customFlags + ' was entered. Please correct and retry.');
return;
}
else {
mParticle.preInit.readyQueue.push(f);
}
},
}
Events.logEvent(Types.MessageType.PageView, eventName, attrs, Types.EventType.Unknown, customFlags);
},
Consent: {
createGDPRConsent: Consent.createGDPRConsent,
createConsentState: Consent.createConsentState
},
/**
* Invoke these methods on the mParticle.eCommerce object.
* Example: mParticle.eCommerce.createImpresion(...)
* @class mParticle.eCommerce
*/
eCommerce: {
/**
* Returns the mParticle SDK version number
* @method getVersion
* @return {String} mParticle SDK version number
* Invoke these methods on the mParticle.eCommerce.Cart object.
* Example: mParticle.eCommerce.Cart.add(...)
* @class mParticle.eCommerce.Cart
*/
getVersion: function() {
return Constants.sdkVersion;
Cart: {
/**
* Adds a product to the cart
* @method add
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
add: function(product, logEventBoolean) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticleUserCart(mpid).add(product, logEventBoolean);
},
/**
* Removes a product from the cart
* @method remove
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
remove: function(product, logEventBoolean) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticleUserCart(mpid).remove(product, logEventBoolean);
},
/**
* Clears the cart
* @method clear
*/
clear: function() {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticleUserCart(mpid).clear();
}
},
/**
* Sets the app version
* @method setAppVersion
* @param {String} version version number
* Sets the currency code
* @for mParticle.eCommerce
* @method setCurrencyCode
* @param {String} code The currency code
*/
setAppVersion: function(version) {
mParticle.Store.SDKConfig.appVersion = version;
Persistence.update();
setCurrencyCode: function(code) {
if (typeof code !== 'string') {
mParticle.Logger.error('Code must be a string');
return;
}
SessionManager.resetSessionTimer();
mParticle.Store.currencyCode = code;
},
/**
* Gets the app name
* @method getAppName
* @return {String} App name
* Creates a product
* @for mParticle.eCommerce
* @method createProduct
* @param {String} name product name
* @param {String} sku product sku
* @param {Number} price product price
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
* @param {String} [variant] product variant
* @param {String} [category] product category
* @param {String} [brand] product brand
* @param {Number} [position] product position
* @param {String} [coupon] product coupon
* @param {Object} [attributes] product attributes
*/
getAppName: function() {
return mParticle.Store.SDKConfig.appName;
createProduct: function(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) {
SessionManager.resetSessionTimer();
return Ecommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes);
},
/**
* Sets the app name
* @method setAppName
* @param {String} name App Name
* Creates a promotion
* @for mParticle.eCommerce
* @method createPromotion
* @param {String} id a unique promotion id
* @param {String} [creative] promotion creative
* @param {String} [name] promotion name
* @param {Number} [position] promotion position
*/
setAppName: function(name) {
mParticle.Store.SDKConfig.appName = name;
createPromotion: function(id, creative, name, position) {
SessionManager.resetSessionTimer();
return Ecommerce.createPromotion(id, creative, name, position);
},
/**
* Gets the app version
* @method getAppVersion
* @return {String} App version
* Creates a product impression
* @for mParticle.eCommerce
* @method createImpression
* @param {String} name impression name
* @param {Object} product the product for which an impression is being created
*/
getAppVersion: function() {
return mParticle.Store.SDKConfig.appVersion;
createImpression: function(name, product) {
SessionManager.resetSessionTimer();
return Ecommerce.createImpression(name, product);
},
/**
* Stops tracking the location of the user
* @method stopTrackingLocation
* Creates a transaction attributes object to be used with a checkout
* @for mParticle.eCommerce
* @method createTransactionAttributes
* @param {String or Number} id a unique transaction id
* @param {String} [affiliation] affilliation
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
* @param {Number} [revenue] total revenue for the product being purchased
* @param {String} [shipping] the shipping method
* @param {Number} [tax] the tax amount
*/
stopTrackingLocation: function() {
createTransactionAttributes: function(id, affiliation, couponCode, revenue, shipping, tax) {
SessionManager.resetSessionTimer();
Events.stopTracking();
return Ecommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax);
},
/**
* Starts tracking the location of the user
* @method startTrackingLocation
* @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback
* Logs a checkout action
* @for mParticle.eCommerce
* @method logCheckout
* @param {Number} step checkout step number
* @param {Object} options
* @param {Object} attrs
* @param {Object} [customFlags] Custom flags for the event
*/
startTrackingLocation: function(callback) {
if (!Validators.isFunction(callback)) {
mParticle.Logger.warning('Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.');
}
logCheckout: function(step, options, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.startTracking(callback);
Events.logCheckoutEvent(step, options, attrs, customFlags);
},
/**
* Sets the position of the user
* @method setPosition
* @param {Number} lattitude lattitude digit
* @param {Number} longitude longitude digit
* Logs a product action
* @for mParticle.eCommerce
* @method logProductAction
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
* @param {Object} product the product for which you are creating the product action
* @param {Object} [attrs] attributes related to the product action
* @param {Object} [customFlags] Custom flags for the event
*/
setPosition: function(lat, lng) {
logProductAction: function(productActionType, product, attrs, customFlags) {
SessionManager.resetSessionTimer();
if (typeof lat === 'number' && typeof lng === 'number') {
mParticle.Store.currentPosition = {
lat: lat,
lng: lng
};
}
else {
mParticle.Logger.error('Position latitude and/or longitude must both be of type number');
}
Events.logProductActionEvent(productActionType, product, attrs, customFlags);
},
/**
* Starts a new session
* @method startNewSession
* Logs a product purchase
* @for mParticle.eCommerce
* @method logPurchase
* @param {Object} transactionAttributes transactionAttributes object
* @param {Object} product the product being purchased
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
* @param {Object} [attrs] other attributes related to the product purchase
* @param {Object} [customFlags] Custom flags for the event
*/
startNewSession: function() {
SessionManager.startNewSession();
},
/**
* Ends the current session
* @method endSession
*/
endSession: function() {
// Sends true as an over ride vs when endSession is called from the setInterval
SessionManager.endSession(true);
},
/**
* Logs an event to mParticle's servers
* @method logEvent
* @param {String} eventName The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* @param {Object} [customFlags] Additional customFlags
*/
logEvent: function(eventName, eventType, eventInfo, customFlags) {
SessionManager.resetSessionTimer();
if (typeof (eventName) !== 'string') {
mParticle.Logger.error(Messages.ErrorMessages.EventNameInvalidType);
logPurchase: function(transactionAttributes, product, clearCart, attrs, customFlags) {
if (!transactionAttributes || !product) {
mParticle.Logger.error(Messages.ErrorMessages.BadLogPurchase);
return;
}
if (!eventType) {
eventType = Types.EventType.Unknown;
}
if (!Helpers.isEventType(eventType)) {
mParticle.Logger.error('Invalid event type: ' + eventType + ', must be one of: \n' + JSON.stringify(Types.EventType));
return;
}
if (!Helpers.canLog()) {
mParticle.Logger.error(Messages.ErrorMessages.LoggingDisabled);
return;
}
Events.logEvent(Types.MessageType.PageEvent, eventName, eventInfo, eventType, customFlags);
},
/**
* Used to log custom errors
*
* @method logError
* @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'}
* @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean
*/
logError: function(error, attrs) {
SessionManager.resetSessionTimer();
if (!error) {
return;
}
Events.logPurchaseEvent(transactionAttributes, product, attrs, customFlags);
if (typeof error === 'string') {
error = {
message: error
};
if (clearCart === true) {
mParticle.eCommerce.Cart.clear();
}
var data = {
m: error.message ? error.message : error,
s: 'Error',
t: error.stack
};
if (attrs) {
var sanitized = Helpers.sanitizeAttributes(attrs);
for (var prop in sanitized) {
data[prop] = sanitized[prop];
}
}
Events.logEvent(Types.MessageType.CrashReport,
error.name ? error.name : 'Error',
data,
Types.EventType.Other);
},
/**
* Logs `click` events
* @method logLink
* @param {String} selector The selector to add a 'click' event to (ex. #purchase-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* Logs a product promotion
* @for mParticle.eCommerce
* @method logPromotion
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
* @param {Object} promotion promotion object
* @param {Object} [attrs] boolean to clear the cart after logging or not
* @param {Object} [customFlags] Custom flags for the event
*/
logLink: function(selector, eventName, eventType, eventInfo) {
logPromotion: function(type, promotion, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.addEventHandler('click', selector, eventName, eventInfo, eventType);
Events.logPromotionEvent(type, promotion, attrs, customFlags);
},
/**
* Logs `submit` events
* @method logForm
* @param {String} selector The selector to add the event handler to (ex. #search-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/javascript/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* Logs a product impression
* @for mParticle.eCommerce
* @method logImpression
* @param {Object} impression product impression object
* @param {Object} attrs attributes related to the impression log
* @param {Object} [customFlags] Custom flags for the event
*/
logForm: function(selector, eventName, eventType, eventInfo) {
logImpression: function(impression, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.addEventHandler('submit', selector, eventName, eventInfo, eventType);
Events.logImpressionEvent(impression, attrs, customFlags);
},
/**
* Logs a page view
* @method logPageView
* @param {String} eventName The name of the event. Defaults to 'PageView'.
* @param {Object} [attrs] Attributes for the event
* Logs a refund
* @for mParticle.eCommerce
* @method logRefund
* @param {Object} transactionAttributes transaction attributes related to the refund
* @param {Object} product product being refunded
* @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false.
* @param {Object} [attrs] attributes related to the refund
* @param {Object} [customFlags] Custom flags for the event
*/
logPageView: function(eventName, attrs, customFlags) {
logRefund: function(transactionAttributes, product, clearCart, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.logRefundEvent(transactionAttributes, product, attrs, customFlags);
if (Helpers.canLog()) {
if (!Validators.isStringOrNumber(eventName)) {
eventName = 'PageView';
}
if (!attrs) {
attrs = {
hostname: window.location.hostname,
title: window.document.title
};
}
else if (!Helpers.isObject(attrs)){
mParticle.Logger.error('The attributes argument must be an object. A ' + typeof attrs + ' was entered. Please correct and retry.');
return;
}
if (customFlags && !Helpers.isObject(customFlags)) {
mParticle.Logger.error('The customFlags argument must be an object. A ' + typeof customFlags + ' was entered. Please correct and retry.');
return;
}
if (clearCart === true) {
mParticle.eCommerce.Cart.clear();
}
Events.logEvent(Types.MessageType.PageView, eventName, attrs, Types.EventType.Unknown, customFlags);
},
Consent: {
createGDPRConsent: Consent.createGDPRConsent,
createConsentState: Consent.createConsentState
},
/**
* Invoke these methods on the mParticle.eCommerce object.
* Example: mParticle.eCommerce.createImpresion(...)
* @class mParticle.eCommerce
*/
eCommerce: {
/**
* Invoke these methods on the mParticle.eCommerce.Cart object.
* Example: mParticle.eCommerce.Cart.add(...)
* @class mParticle.eCommerce.Cart
*/
Cart: {
/**
* Adds a product to the cart
* @method add
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
add: function(product, logEventBoolean) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticleUserCart(mpid).add(product, logEventBoolean);
},
/**
* Removes a product from the cart
* @method remove
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
*/
remove: function(product, logEventBoolean) {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticleUserCart(mpid).remove(product, logEventBoolean);
},
/**
* Clears the cart
* @method clear
*/
clear: function() {
var mpid,
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mParticleUserCart(mpid).clear();
}
},
/**
* Sets the currency code
* @for mParticle.eCommerce
* @method setCurrencyCode
* @param {String} code The currency code
*/
setCurrencyCode: function(code) {
if (typeof code !== 'string') {
mParticle.Logger.error('Code must be a string');
return;
}
SessionManager.resetSessionTimer();
mParticle.Store.currencyCode = code;
},
/**
* Creates a product
* @for mParticle.eCommerce
* @method createProduct
* @param {String} name product name
* @param {String} sku product sku
* @param {Number} price product price
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
* @param {String} [variant] product variant
* @param {String} [category] product category
* @param {String} [brand] product brand
* @param {Number} [position] product position
* @param {String} [coupon] product coupon
* @param {Object} [attributes] product attributes
*/
createProduct: function(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) {
SessionManager.resetSessionTimer();
return Ecommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes);
},
/**
* Creates a promotion
* @for mParticle.eCommerce
* @method createPromotion
* @param {String} id a unique promotion id
* @param {String} [creative] promotion creative
* @param {String} [name] promotion name
* @param {Number} [position] promotion position
*/
createPromotion: function(id, creative, name, position) {
SessionManager.resetSessionTimer();
return Ecommerce.createPromotion(id, creative, name, position);
},
/**
* Creates a product impression
* @for mParticle.eCommerce
* @method createImpression
* @param {String} name impression name
* @param {Object} product the product for which an impression is being created
*/
createImpression: function(name, product) {
SessionManager.resetSessionTimer();
return Ecommerce.createImpression(name, product);
},
/**
* Creates a transaction attributes object to be used with a checkout
* @for mParticle.eCommerce
* @method createTransactionAttributes
* @param {String or Number} id a unique transaction id
* @param {String} [affiliation] affilliation
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
* @param {Number} [revenue] total revenue for the product being purchased
* @param {String} [shipping] the shipping method
* @param {Number} [tax] the tax amount
*/
createTransactionAttributes: function(id, affiliation, couponCode, revenue, shipping, tax) {
SessionManager.resetSessionTimer();
return Ecommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax);
},
/**
* Logs a checkout action
* @for mParticle.eCommerce
* @method logCheckout
* @param {Number} step checkout step number
* @param {Object} options
* @param {Object} attrs
* @param {Object} [customFlags] Custom flags for the event
*/
logCheckout: function(step, options, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.logCheckoutEvent(step, options, attrs, customFlags);
},
/**
* Logs a product action
* @for mParticle.eCommerce
* @method logProductAction
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
* @param {Object} product the product for which you are creating the product action
* @param {Object} [attrs] attributes related to the product action
* @param {Object} [customFlags] Custom flags for the event
*/
logProductAction: function(productActionType, product, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.logProductActionEvent(productActionType, product, attrs, customFlags);
},
/**
* Logs a product purchase
* @for mParticle.eCommerce
* @method logPurchase
* @param {Object} transactionAttributes transactionAttributes object
* @param {Object} product the product being purchased
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
* @param {Object} [attrs] other attributes related to the product purchase
* @param {Object} [customFlags] Custom flags for the event
*/
logPurchase: function(transactionAttributes, product, clearCart, attrs, customFlags) {
if (!transactionAttributes || !product) {
mParticle.Logger.error(Messages.ErrorMessages.BadLogPurchase);
return;
}
SessionManager.resetSessionTimer();
Events.logPurchaseEvent(transactionAttributes, product, attrs, customFlags);
expandCommerceEvent: function(event) {
SessionManager.resetSessionTimer();
return Ecommerce.expandCommerceEvent(event);
}
},
/**
* Sets a session attribute
* @for mParticle
* @method setSessionAttribute
* @param {String} key key for session attribute
* @param {String or Number} value value for session attribute
*/
setSessionAttribute: function(key, value) {
SessionManager.resetSessionTimer();
// Logs to cookie
// And logs to in-memory object
// Example: mParticle.setSessionAttribute('location', '33431');
if (Helpers.canLog()) {
if (!Validators.isValidAttributeValue(value)) {
mParticle.Logger.error(Messages.ErrorMessages.BadAttribute);
return;
}
if (clearCart === true) {
mParticle.eCommerce.Cart.clear();
}
},
/**
* Logs a product promotion
* @for mParticle.eCommerce
* @method logPromotion
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
* @param {Object} promotion promotion object
* @param {Object} [attrs] boolean to clear the cart after logging or not
* @param {Object} [customFlags] Custom flags for the event
*/
logPromotion: function(type, promotion, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.logPromotionEvent(type, promotion, attrs, customFlags);
},
/**
* Logs a product impression
* @for mParticle.eCommerce
* @method logImpression
* @param {Object} impression product impression object
* @param {Object} attrs attributes related to the impression log
* @param {Object} [customFlags] Custom flags for the event
*/
logImpression: function(impression, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.logImpressionEvent(impression, attrs, customFlags);
},
/**
* Logs a refund
* @for mParticle.eCommerce
* @method logRefund
* @param {Object} transactionAttributes transaction attributes related to the refund
* @param {Object} product product being refunded
* @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false.
* @param {Object} [attrs] attributes related to the refund
* @param {Object} [customFlags] Custom flags for the event
*/
logRefund: function(transactionAttributes, product, clearCart, attrs, customFlags) {
SessionManager.resetSessionTimer();
Events.logRefundEvent(transactionAttributes, product, attrs, customFlags);
if (clearCart === true) {
mParticle.eCommerce.Cart.clear();
}
},
expandCommerceEvent: function(event) {
SessionManager.resetSessionTimer();
return Ecommerce.expandCommerceEvent(event);
if (!Validators.isValidKeyValue(key)) {
mParticle.Logger.error(Messages.ErrorMessages.BadKey);
return;
}
},
/**
* Sets a session attribute
* @for mParticle
* @method setSessionAttribute
* @param {String} key key for session attribute
* @param {String or Number} value value for session attribute
*/
setSessionAttribute: function(key, value) {
SessionManager.resetSessionTimer();
// Logs to cookie
// And logs to in-memory object
// Example: mParticle.setSessionAttribute('location', '33431');
if (Helpers.canLog()) {
if (!Validators.isValidAttributeValue(value)) {
mParticle.Logger.error(Messages.ErrorMessages.BadAttribute);
return;
}
if (!Validators.isValidKeyValue(key)) {
mParticle.Logger.error(Messages.ErrorMessages.BadKey);
return;
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: key, value: value }));
} else {
var existingProp = Helpers.findKeyInObject(mParticle.Store.sessionAttributes, key);
if (existingProp) {
key = existingProp;
}
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: key, value: value }));
} else {
var existingProp = Helpers.findKeyInObject(mParticle.Store.sessionAttributes, key);
mParticle.Store.sessionAttributes[key] = value;
Persistence.update();
if (existingProp) {
key = existingProp;
}
mParticle.Store.sessionAttributes[key] = value;
Persistence.update();
Forwarders.applyToForwarders('setSessionAttribute', [key, value]);
}
Forwarders.applyToForwarders('setSessionAttribute', [key, value]);
}
},
/**
* Set opt out of logging
* @for mParticle
* @method setOptOut
* @param {Boolean} isOptingOut boolean to opt out or not. When set to true, opt out of logging.
*/
setOptOut: function(isOptingOut) {
SessionManager.resetSessionTimer();
mParticle.Store.isEnabled = !isOptingOut;
}
},
/**
* Set opt out of logging
* @for mParticle
* @method setOptOut
* @param {Boolean} isOptingOut boolean to opt out or not. When set to true, opt out of logging.
*/
setOptOut: function(isOptingOut) {
SessionManager.resetSessionTimer();
mParticle.Store.isEnabled = !isOptingOut;
Events.logOptOut();
Persistence.update();
Events.logOptOut();
Persistence.update();
if (mParticle.Store.activeForwarders.length) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
if (forwarder.setOptOut) {
var result = forwarder.setOptOut(isOptingOut);
if (mParticle.Store.activeForwarders.length) {
mParticle.Store.activeForwarders.forEach(function(forwarder) {
if (forwarder.setOptOut) {
var result = forwarder.setOptOut(isOptingOut);
if (result) {
mParticle.Logger.verbose(result);
}
if (result) {
mParticle.Logger.verbose(result);
}
});
}
},
/**
* Set or remove the integration attributes for a given integration ID.
* Integration attributes are keys and values specific to a given integration. For example,
* many integrations have their own internal user/device ID. mParticle will store integration attributes
* for a given device, and will be able to use these values for server-to-server communication to services.
* This is often useful when used in combination with a server-to-server feed, allowing the feed to be enriched
* with the necessary integration attributes to be properly forwarded to the given integration.
* @for mParticle
* @method setIntegrationAttribute
* @param {Number} integrationId mParticle integration ID
* @param {Object} attrs a map of attributes that will replace any current attributes. The keys are predefined by mParticle.
* Please consult with the mParticle docs or your solutions consultant for the correct value. You may
* also pass a null or empty map here to remove all of the attributes.
*/
setIntegrationAttribute: function(integrationId, attrs) {
if (typeof integrationId !== 'number') {
mParticle.Logger.error('integrationId must be a number');
return;
}
if (attrs === null) {
}
});
}
},
/**
* Set or remove the integration attributes for a given integration ID.
* Integration attributes are keys and values specific to a given integration. For example,
* many integrations have their own internal user/device ID. mParticle will store integration attributes
* for a given device, and will be able to use these values for server-to-server communication to services.
* This is often useful when used in combination with a server-to-server feed, allowing the feed to be enriched
* with the necessary integration attributes to be properly forwarded to the given integration.
* @for mParticle
* @method setIntegrationAttribute
* @param {Number} integrationId mParticle integration ID
* @param {Object} attrs a map of attributes that will replace any current attributes. The keys are predefined by mParticle.
* Please consult with the mParticle docs or your solutions consultant for the correct value. You may
* also pass a null or empty map here to remove all of the attributes.
*/
setIntegrationAttribute: function(integrationId, attrs) {
if (typeof integrationId !== 'number') {
mParticle.Logger.error('integrationId must be a number');
return;
}
if (attrs === null) {
mParticle.Store.integrationAttributes[integrationId] = {};
} else if (Helpers.isObject(attrs)) {
if (Object.keys(attrs).length === 0) {
mParticle.Store.integrationAttributes[integrationId] = {};
} else if (Helpers.isObject(attrs)) {
if (Object.keys(attrs).length === 0) {
mParticle.Store.integrationAttributes[integrationId] = {};
} else {
for (var key in attrs) {
if (typeof key === 'string') {
if (typeof attrs[key] === 'string') {
if (Helpers.isObject(mParticle.Store.integrationAttributes[integrationId])) {
mParticle.Store.integrationAttributes[integrationId][key] = attrs[key];
} else {
mParticle.Store.integrationAttributes[integrationId] = {};
mParticle.Store.integrationAttributes[integrationId][key] = attrs[key];
}
} else {
for (var key in attrs) {
if (typeof key === 'string') {
if (typeof attrs[key] === 'string') {
if (Helpers.isObject(mParticle.Store.integrationAttributes[integrationId])) {
mParticle.Store.integrationAttributes[integrationId][key] = attrs[key];
} else {
mParticle.Logger.error('Values for integration attributes must be strings. You entered a ' + typeof attrs[key]);
continue;
mParticle.Store.integrationAttributes[integrationId] = {};
mParticle.Store.integrationAttributes[integrationId][key] = attrs[key];
}
} else {
mParticle.Logger.error('Keys must be strings, you entered a ' + typeof key);
mParticle.Logger.error('Values for integration attributes must be strings. You entered a ' + typeof attrs[key]);
continue;
}
} else {
mParticle.Logger.error('Keys must be strings, you entered a ' + typeof key);
continue;
}
}
} else {
mParticle.Logger.error('Attrs must be an object with keys and values. You entered a ' + typeof attrs);
return;
}
Persistence.update();
},
/**
* Get integration attributes for a given integration ID.
* @method getIntegrationAttributes
* @param {Number} integrationId mParticle integration ID
* @return {Object} an object map of the integrationId's attributes
*/
getIntegrationAttributes: function(integrationId) {
if (mParticle.Store.integrationAttributes[integrationId]) {
return mParticle.Store.integrationAttributes[integrationId];
} else {
return {};
} else {
mParticle.Logger.error('Attrs must be an object with keys and values. You entered a ' + typeof attrs);
return;
}
Persistence.update();
},
/**
* Get integration attributes for a given integration ID.
* @method getIntegrationAttributes
* @param {Number} integrationId mParticle integration ID
* @return {Object} an object map of the integrationId's attributes
*/
getIntegrationAttributes: function(integrationId) {
if (mParticle.Store.integrationAttributes[integrationId]) {
return mParticle.Store.integrationAttributes[integrationId];
} else {
return {};
}
},
addForwarder: function(forwarder) {
mParticle.preInit.forwarderConstructors.push(forwarder);
},
configurePixel: function(settings) {
Forwarders.configurePixel(settings);
},
_getActiveForwarders: function() {
return mParticle.Store.activeForwarders;
},
_getIntegrationDelays: function() {
return mParticle.preInit.integrationDelays;
},
_configureFeatures: function(featureFlags) {
for (var key in featureFlags) {
if (mParticle.Store && mParticle.preInit.featureFlags) {
mParticle.preInit.featureFlags[key] = featureFlags[key];
}
},
addForwarder: function(forwarder) {
mParticle.preInit.forwarderConstructors.push(forwarder);
},
// TODO: think about timing of release
// configureForwarder: function(configuration) {
// Forwarders.configureForwarder(configuration);
// },
configurePixel: function(settings) {
Forwarders.configurePixel(settings);
},
_getActiveForwarders: function() {
return mParticle.Store.activeForwarders;
},
_getIntegrationDelays: function() {
return mParticle.preInit.integrationDelays;
},
_configureFeatures: function(featureFlags) {
for (var key in featureFlags) {
if (mParticle.Store && mParticle.preInit.featureFlags) {
mParticle.preInit.featureFlags[key] = featureFlags[key];
}
}
},
_setIntegrationDelay: function(module, boolean) {
mParticle.preInit.integrationDelays[module] = boolean;
}
};
},
_setIntegrationDelay: function(module, boolean) {
mParticle.preInit.integrationDelays[module] = boolean;
}
};
function completeSDKInitialization(apiKey, config) {
mParticle.Logger = new Logger(config);
mParticle.Store = new Store(config, mParticle.Logger);
function completeSDKInitialization(apiKey, config) {
mParticle.Logger = new Logger(config);
mParticle.Store.webviewBridgeEnabled = NativeSdkHelpers.isWebviewEnabled(mParticle.Store.SDKConfig.requiredWebviewBridgeName, mParticle.Store.SDKConfig.minWebviewBridgeVersion);
mParticle.Store = new Store(config, mParticle.Logger);
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: '$src_env', value: 'webview' }));
if (apiKey) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: '$src_key', value: apiKey }));
}
} else {
var currentUser;
mParticle.Store.webviewBridgeEnabled = NativeSdkHelpers.isWebviewEnabled(mParticle.Store.SDKConfig.requiredWebviewBridgeName, mParticle.Store.SDKConfig.minWebviewBridgeVersion);
mParticle.Store.devToken = apiKey || null;
mParticle.Logger.verbose(Messages.InformationMessages.StartingInitialization);
//check to see if localStorage is available for migrating purposes
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(window.localStorage);
if (mParticle.Store.webviewBridgeEnabled) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: '$src_env', value: 'webview' }));
if (apiKey) {
NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({ key: '$src_key', value: apiKey }));
}
} else {
var currentUser;
// Migrate any cookies from previous versions to current cookie version
Migrations.migrate();
mParticle.Store.devToken = apiKey || null;
mParticle.Logger.verbose(Messages.InformationMessages.StartingInitialization);
//check to see if localStorage is available for migrating purposes
mParticle.Store.isLocalStorageAvailable = Persistence.determineLocalStorageAvailability(window.localStorage);
// Load any settings/identities/attributes from cookie or localStorage
Persistence.initializeStorage();
// Migrate any cookies from previous versions to current cookie version
Migrations.migrate();
// If no initialIdentityRequest is passed in, we set the user identities to what is currently in cookies for the identify request
if ((Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest) && Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest.userIdentities) &&
Object.keys(mParticle.Store.SDKConfig.identifyRequest.userIdentities).length === 0) || !mParticle.Store.SDKConfig.identifyRequest) {
var modifiedUIforIdentityRequest = {};
// Load any settings/identities/attributes from cookie or localStorage
Persistence.initializeStorage();
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
var identities = currentUser.getUserIdentities().userIdentities || {};
for (var identityKey in identities) {
if (identities.hasOwnProperty(identityKey)) {
modifiedUIforIdentityRequest[identityKey] = identities[identityKey];
}
// If no initialIdentityRequest is passed in, we set the user identities to what is currently in cookies for the identify request
if ((Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest) && Helpers.isObject(mParticle.Store.SDKConfig.identifyRequest.userIdentities) &&
Object.keys(mParticle.Store.SDKConfig.identifyRequest.userIdentities).length === 0) || !mParticle.Store.SDKConfig.identifyRequest) {
var modifiedUIforIdentityRequest = {};
currentUser = mParticle.Identity.getCurrentUser();
if (currentUser) {
var identities = currentUser.getUserIdentities().userIdentities || {};
for (var identityKey in identities) {
if (identities.hasOwnProperty(identityKey)) {
modifiedUIforIdentityRequest[identityKey] = identities[identityKey];
}
}
mParticle.Store.SDKConfig.identifyRequest = {
userIdentities: modifiedUIforIdentityRequest
};
}
// If migrating from pre-IDSync to IDSync, a sessionID will exist and an identify request will not have been fired, so we need this check
if (mParticle.Store.migratingToIDSyncCookies) {
IdentityAPI.identify(mParticle.Store.SDKConfig.identifyRequest, mParticle.Store.SDKConfig.identityCallback);
mParticle.Store.migratingToIDSyncCookies = false;
}
mParticle.Store.SDKConfig.identifyRequest = {
userIdentities: modifiedUIforIdentityRequest
};
}
currentUser = IdentityAPI.getCurrentUser();
// If migrating from pre-IDSync to IDSync, a sessionID will exist and an identify request will not have been fired, so we need this check
if (mParticle.Store.migratingToIDSyncCookies) {
IdentityAPI.identify(mParticle.Store.SDKConfig.identifyRequest, mParticle.Store.SDKConfig.identityCallback);
mParticle.Store.migratingToIDSyncCookies = false;
}
if (Helpers.hasFeatureFlag(Constants.Features.Batching)) {
ForwardingStatsUploader.startForwardingStatsTimer();
}
currentUser = IdentityAPI.getCurrentUser();
Forwarders.processForwarders(config);
if (Helpers.hasFeatureFlag(Constants.Features.Batching)) {
startForwardingStatsTimer();
}
// Call mParticle.Store.SDKConfig.identityCallback when identify was not called due to a reload or a sessionId already existing
if (!mParticle.Store.identifyCalled && mParticle.Store.SDKConfig.identityCallback && currentUser && currentUser.getMPID()) {
mParticle.Store.SDKConfig.identityCallback({
httpCode: HTTPCodes.activeSession,
getUser: function () {
return mParticleUser(currentUser.getMPID());
},
getPreviousUser: function () {
var users = mParticle.Identity.getUsers();
var mostRecentUser = users.shift();
if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) {
mostRecentUser = users.shift();
}
return mostRecentUser || null;
},
body: {
mpid: currentUser.getMPID(),
is_logged_in: mParticle.Store.isLoggedIn,
matched_identities: currentUser.getUserIdentities().userIdentities,
context: null,
is_ephemeral: false
Forwarders.processForwarders(config);
// Call mParticle.Store.SDKConfig.identityCallback when identify was not called due to a reload or a sessionId already existing
if (!mParticle.Store.identifyCalled && mParticle.Store.SDKConfig.identityCallback && currentUser && currentUser.getMPID()) {
mParticle.Store.SDKConfig.identityCallback({
httpCode: HTTPCodes.activeSession,
getUser: function () {
return mParticleUser(currentUser.getMPID());
},
getPreviousUser: function () {
var users = mParticle.Identity.getUsers();
var mostRecentUser = users.shift();
if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) {
mostRecentUser = users.shift();
}
});
}
mParticle.sessionManager.initialize();
Events.logAST();
}
// Call any functions that are waiting for the library to be initialized
if (mParticle.preInit.readyQueue && mParticle.preInit.readyQueue.length) {
mParticle.preInit.readyQueue.forEach(function (readyQueueItem) {
if (Validators.isFunction(readyQueueItem)) {
readyQueueItem();
} else if (Array.isArray(readyQueueItem)) {
processPreloadedItem(readyQueueItem);
return mostRecentUser || null;
},
body: {
mpid: currentUser.getMPID(),
is_logged_in: mParticle.Store.isLoggedIn,
matched_identities: currentUser.getUserIdentities().userIdentities,
context: null,
is_ephemeral: false
}
});
mParticle.preInit.readyQueue = [];
}
mParticle.Store.isInitialized = true;
mParticle.sessionManager.initialize();
Events.logAST();
}
// Call any functions that are waiting for the library to be initialized
if (mParticle.preInit.readyQueue && mParticle.preInit.readyQueue.length) {
mParticle.preInit.readyQueue.forEach(function (readyQueueItem) {
if (Validators.isFunction(readyQueueItem)) {
readyQueueItem();
} else if (Array.isArray(readyQueueItem)) {
processPreloadedItem(readyQueueItem);
}
});
if (mParticle.Store.isFirstRun) {
mParticle.Store.isFirstRun = false;
}
mParticle.preInit.readyQueue = [];
}
mParticle.Store.isInitialized = true;
function processPreloadedItem(readyQueueItem) {
var currentUser,
args = readyQueueItem,
method = args.splice(0, 1)[0];
if (mParticle[args[0]]) {
mParticle[method].apply(this, args);
} else {
var methodArray = method.split('.');
try {
var computedMPFunction = mParticle;
for (var i = 0; i < methodArray.length; i++) {
var currentMethod = methodArray[i];
computedMPFunction = computedMPFunction[currentMethod];
}
computedMPFunction.apply(currentUser, args);
} catch(e) {
mParticle.Logger.verbose('Unable to compute proper mParticle function ' + e);
if (mParticle.Store.isFirstRun) {
mParticle.Store.isFirstRun = false;
}
}
function processPreloadedItem(readyQueueItem) {
var currentUser,
args = readyQueueItem,
method = args.splice(0, 1)[0];
if (mParticle[args[0]]) {
mParticle[method].apply(this, args);
} else {
var methodArray = method.split('.');
try {
var computedMPFunction = mParticle;
for (var i = 0; i < methodArray.length; i++) {
var currentMethod = methodArray[i];
computedMPFunction = computedMPFunction[currentMethod];
}
computedMPFunction.apply(currentUser, args);
} catch(e) {
mParticle.Logger.verbose('Unable to compute proper mParticle function ' + e);
}
}
}
mParticle.preInit = {
readyQueue: [],
featureFlags: {},
integrationDelays: {},
forwarderConstructors: []
};
mParticle.preInit = {
readyQueue: [],
featureFlags: {},
integrationDelays: {},
forwarderConstructors: []
};
if (window.mParticle && window.mParticle.config) {
if (window.mParticle.config.hasOwnProperty('rq')) {
mParticle.preInit.readyQueue = window.mParticle.config.rq;
}
if (window.mParticle && window.mParticle.config) {
if (window.mParticle.config.hasOwnProperty('rq')) {
mParticle.preInit.readyQueue = window.mParticle.config.rq;
}
}
window.mParticle = mParticle;
module.exports = mParticle;
})(window);
window.mParticle = mParticle;
export default mParticle;

@@ -1,7 +0,8 @@

var Persistence = require('./persistence'),
Constants = require('./constants'),
StorageNames = Constants.StorageNames,
Helpers = require('./helpers'),
SDKv2NonMPIDCookieKeys = Constants.SDKv2NonMPIDCookieKeys,
Base64 = require('./polyfill').Base64,
import Persistence from './persistence';
import Constants from './constants';
import Helpers from './helpers';
import Polyfill from './polyfill';
var StorageNames = Constants.StorageNames,
Base64 = Polyfill.Base64,
CookiesGlobalSettingsKeys = {

@@ -17,3 +18,3 @@ das: 1

// 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
// 3. if 'mprtcl-api', could be JSSDKv2 or JSSDKv1. JSSDKv2 cookie has a 'globalSettings' key on it
function migrate() {

@@ -230,32 +231,5 @@ try {

function convertUIFromArrayToObject(cookie) {
try {
if (cookie && Helpers.isObject(cookie)) {
for (var mpid in cookie) {
if (cookie.hasOwnProperty(mpid)) {
if (!SDKv2NonMPIDCookieKeys[mpid]) {
if (cookie[mpid].ui && Array.isArray(cookie[mpid].ui)) {
cookie[mpid].ui = cookie[mpid].ui.reduce(function(accum, identity) {
if (identity.Type && Helpers.Validators.isStringOrNumber(identity.Identity)) {
accum[identity.Type] = identity.Identity;
}
return accum;
}, {});
}
}
}
}
}
return cookie;
}
catch (e) {
mParticle.Logger.error('An error ocurred when converting the user identities array to an object', e);
}
}
module.exports = {
export default {
migrate: migrate,
convertUIFromArrayToObject: convertUIFromArrayToObject,
convertSDKv1CookiesV3ToSDKv2CookiesV4: convertSDKv1CookiesV3ToSDKv2CookiesV4
};
};

@@ -1,6 +0,6 @@

var Persistence = require('./persistence'),
Types = require('./types'),
Helpers = require('./helpers');
import Persistence from './persistence';
import Types from './types';
import Helpers from './helpers';
function getFilteredMparticleUser(mpid, forwarder) {
export default function getFilteredMparticleUser(mpid, forwarder) {
return {

@@ -63,6 +63,2 @@ getUserIdentities: function() {

};
}
module.exports = {
getFilteredMparticleUser: getFilteredMparticleUser
};
}

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

var Messages = require('./constants').Messages;
import Constants from './constants';
var Messages = Constants.Messages;
var androidBridgeNameBase = 'mParticleAndroid';

@@ -124,8 +126,6 @@ var iosBridgeNameBase = 'mParticle';

module.exports = {
export default {
isWebviewEnabled: isWebviewEnabled,
isBridgeV2Available:isBridgeV2Available,
sendToNative: sendToNative,
sendViaBridgeV1: sendViaBridgeV1,
sendViaBridgeV2: sendViaBridgeV2
};
isBridgeV2Available: isBridgeV2Available,
sendToNative: sendToNative
};

@@ -1,10 +0,13 @@

var Helpers = require('./helpers'),
Constants = require('./constants'),
Base64 = require('./polyfill').Base64,
import Helpers from './helpers';
import Constants from './constants';
import Polyfill from './polyfill';
import Consent from './consent';
var Base64 = Polyfill.Base64,
Messages = Constants.Messages,
Base64CookieKeys = Constants.Base64CookieKeys,
SDKv2NonMPIDCookieKeys = Constants.SDKv2NonMPIDCookieKeys,
StorageNames = Constants.StorageNames,
Consent = require('./consent');
StorageNames = Constants.StorageNames;
function useLocalStorage() {

@@ -17,4 +20,4 @@ return (!mParticle.Store.SDKConfig.useCookieStorage && mParticle.Store.isLocalStorageAvailable);

var storage,
localStorageData = this.getLocalStorage(),
cookies = this.getCookie(),
localStorageData = getLocalStorage(),
cookies = getCookie(),
allData;

@@ -49,3 +52,3 @@

}
this.storeDataInMemory(allData);
storeDataInMemory(allData);
}

@@ -61,10 +64,10 @@ else {

}
this.storeDataInMemory(allData);
this.expireCookies(mParticle.Store.storageName);
storeDataInMemory(allData);
expireCookies(mParticle.Store.storageName);
} else {
this.storeDataInMemory(localStorageData);
storeDataInMemory(localStorageData);
}
}
} else {
this.storeDataInMemory(cookies);
storeDataInMemory(cookies);
}

@@ -99,3 +102,3 @@

}
this.update();
update();
} catch (e) {

@@ -114,6 +117,6 @@ if (useLocalStorage() && mParticle.Store.isLocalStorageAvailable) {

if (mParticle.Store.SDKConfig.useCookieStorage) {
this.setCookie();
setCookie();
}
this.setLocalStorage();
setLocalStorage();
}

@@ -259,3 +262,3 @@ }

allLocalStorageProducts = getAllUserProductsFromLS(),
localStorageData = this.getLocalStorage() || {},
localStorageData = getLocalStorage() || {},
currentUser = mParticle.Identity.getCurrentUser(),

@@ -297,3 +300,3 @@ mpid = currentUser ? currentUser.getMPID() : null,

localStorageData = this.setGlobalStorageAttributes(localStorageData);
localStorageData = setGlobalStorageAttributes(localStorageData);

@@ -360,3 +363,3 @@ try {

} else {
return this.parseDeviceId(mParticle.Store.serverSettings);
return parseDeviceId(mParticle.Store.serverSettings);
}

@@ -450,3 +453,3 @@ }

key = mParticle.Store.storageName,
cookies = this.getCookie() || {},
cookies = getCookie() || {},
expires = new Date(date.getTime() +

@@ -478,3 +481,3 @@ (mParticle.Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1000)).toGMTString(),

cookies = this.setGlobalStorageAttributes(cookies);
cookies = setGlobalStorageAttributes(cookies);

@@ -569,3 +572,3 @@ if (Object.keys(mParticle.Store.nonCurrentUserMPIDs).length) {

function findPrevCookiesBasedOnUI(identityApiData) {
var cookies = this.getCookie() || this.getLocalStorage();
var cookies = getCookie() || getLocalStorage();
var matchedUser;

@@ -595,3 +598,3 @@

if (matchedUser) {
this.storeDataInMemory(cookies, matchedUser);
storeDataInMemory(cookies, matchedUser);
}

@@ -745,6 +748,2 @@ }

function decodeProducts() {
return JSON.parse(Base64.decode(localStorage.getItem(mParticle.Store.prodStorageName)));
}
function getUserIdentities(mpid) {

@@ -791,3 +790,2 @@ var cookies = getPersistence();

}
function saveUserIdentitiesToCookies(mpid, userIdentities) {

@@ -842,4 +840,4 @@ if (userIdentities) {

function saveUserConsentStateToCookies(mpid, consentState) {
//it's currently not supported to set persistence
//for any MPID that's not the current one.
//it's currently not supported to set persistence
//for any MPID that's not the current one.
if (consentState || consentState === null) {

@@ -1006,3 +1004,3 @@ var cookies = getPersistence();

module.exports = {
export default {
useLocalStorage: useLocalStorage,

@@ -1015,3 +1013,2 @@ initializeStorage: initializeStorage,

setLocalStorage: setLocalStorage,
setGlobalStorageAttributes: setGlobalStorageAttributes,
getLocalStorage: getLocalStorage,

@@ -1032,6 +1029,4 @@ storeDataInMemory: storeDataInMemory,

revertCookieString: revertCookieString,
encodeCookies: encodeCookies,
decodeCookies: decodeCookies,
getCookieDomain: getCookieDomain,
decodeProducts: decodeProducts,
getUserIdentities: getUserIdentities,

@@ -1055,2 +1050,2 @@ getAllUserAttributes: getAllUserAttributes,

setLastSeenTime: setLastSeenTime
};
};

@@ -136,3 +136,3 @@ // Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html

module.exports = {
export default {
// forEach polyfill

@@ -245,2 +245,2 @@ // Production steps of ECMA-262, Edition 5, 15.4.4.18

Base64: Base64
};
};

@@ -1,7 +0,8 @@

var Types = require('./types'),
MessageType = Types.MessageType,
import Types from './types';
import Helpers from './helpers';
import Constants from './constants';
var MessageType = Types.MessageType,
ApplicationTransitionType = Types.ApplicationTransitionType,
Constants = require('./constants'),
Helpers = require('./helpers'),
parseNumber = require('./helpers').parseNumber;
parseNumber = Helpers.parseNumber;

@@ -249,6 +250,6 @@ function convertCustomFlags(event, dto) {

module.exports = {
export default {
createEventObject: createEventObject,
convertEventToDTO: convertEventToDTO,
convertToConsentStateDTO: convertToConsentStateDTO
};
};

@@ -1,8 +0,12 @@

var Helpers = require('./helpers'),
Messages = require('./constants').Messages,
Types = require('./types'),
IdentityAPI = require('./identity').IdentityAPI,
Persistence = require('./persistence'),
logEvent = require('./events').logEvent;
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;
function initialize() {

@@ -133,2 +137,3 @@ if (mParticle.Store.sessionId) {

}
startNewSessionIfNeeded();
}

@@ -140,3 +145,17 @@

module.exports = {
function startNewSessionIfNeeded() {
if (!mParticle.Store.webviewBridgeEnabled) {
var cookies = Persistence.getCookie() || Persistence.getLocalStorage();
if (!mParticle.Store.sessionId && cookies) {
if (cookies.sid) {
mParticle.Store.sessionId = cookies.sid;
} else {
startNewSession();
}
}
}
}
export default {
initialize: initialize,

@@ -149,2 +168,2 @@ getSession: getSession,

clearSessionTimeout: clearSessionTimeout
};
};

@@ -1,5 +0,6 @@

var Constants = require('./constants'),
Helpers = require('./helpers'),
Validators = Helpers.Validators;
import Constants from './constants';
import Helpers from './helpers';
var Validators = Helpers.Validators;
function createSDKConfig(config) {

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

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

@@ -218,4 +219,2 @@ isEnabled: true,

}
}
module.exports = Store;
}

@@ -309,3 +309,3 @@ var MessageType = {

module.exports = {
export default {
MessageType: MessageType,

@@ -317,4 +317,4 @@ EventType: EventType,

ApplicationTransitionType: ApplicationTransitionType,
ProductActionType:ProductActionType,
PromotionActionType:PromotionActionType
};
ProductActionType: ProductActionType,
PromotionActionType: PromotionActionType
};
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