Skip to content
11 changes: 6 additions & 5 deletions src/mockBatchCreator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ import { SDKEvent, BaseEvent, MParticleWebSDK } from './sdkRuntimeModels';
import { convertEvents } from './sdkToEventsApiConverter';
import * as EventsApi from '@mparticle/event-models';

const mockFunction = function () {
const mockFunction = function() {
return null;
};
export default class _BatchValidator {
private getMPInstance() {
return {
// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
_Helpers: {
sanitizeAttributes:
window.mParticle.getInstance()._Helpers.sanitizeAttributes,
generateHash: function () {
sanitizeAttributes: window.mParticle.getInstance()._Helpers
.sanitizeAttributes,
generateHash: function() {
return 'mockHash';
},
generateUniqueId: function () {
generateUniqueId: function() {
return 'mockId';
},
extend: window.mParticle.getInstance()._Helpers.extend,
Expand All @@ -39,6 +39,7 @@ export default class _BatchValidator {
_ServerModel: null,
_SessionManager: null,
_Store: {
mpid: 'test-mpid',
sessionId: 'mockSessionId',
devToken: 'test_dev_token',
isFirstRun: true,
Expand Down
103 changes: 103 additions & 0 deletions src/persistence.interfaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { Context } from '@mparticle/event-models';
import {
AllUserAttributes,
ConsentState,
IdentityApiData,
MPID,
Product,
UserIdentities,
} from '@mparticle/web-sdk';
import { ForwardingStatsData } from './apiClient';
import {
IntegrationAttributes,
ServerSettings,
SessionAttributes,
} from './store';
import { Dictionary } from './utils';

export type CookieSyncDate = Dictionary<string>;
export type UploadsTable = Dictionary<any>;
export interface iForwardingStatsBatches {
uploadsTable: UploadsTable;
forwardingStatsEventQueue: ForwardingStatsData[];
}

export interface IGlobalStoreV2DTO {
sid: string; // Session ID
ie: boolean; // Is Enabled
sa: SessionAttributes;
ss: ServerSettings;
dt: string; // Dev Token
av: string; // App Version
cgid: string; // Client Generated ID
das: string; // Device ID/ Device Application String
ia: IntegrationAttributes;
c: Context;
csm: MPID[]; // Current Session MPIDs
les: number; // Last Event Sent Timestamp
ssd: number; // Session Start Date
}

export interface IPersistenceV2DTO {
cu: MPID; // Current User MPID
gs: IGlobalStoreV2DTO;
l: false; // IsLoggedIn
}

export interface IPersistence {
useLocalStorage(): boolean;
initializeStorage(): void;
update(): void;
storeProductsInMemory(products: Product[], mpid: MPID): void;
storeDataInMemory(obj: IPersistenceV2DTO, currentMPID: MPID): void;
determineLocalStorageAvailability(storage: Storage): boolean;
getUserProductsFromLS(mpid: MPID): Product[];
getAllUserProductsFromLS(): Product[];
setLocalStorage(): void;
getLocalStorage(): IPersistenceV2DTO | null;
expireCookies(cookieName: string): void;
getCookie(): IPersistenceV2DTO | null;
setCookie(): void;
reduceAndEncodePersistence(
persistence: IPersistenceV2DTO,
expires: string,
domain: string,
maxCookieSize: number
): void;
findPrevCookiesBasedOnUI(identityApiData: IdentityApiData): void;
encodePersistence(persistance: IPersistenceV2DTO): string;
decodePersistence(persistance: IPersistenceV2DTO): string;
replaceCommasWithPipes(string: string): string;
replacePipesWithCommas(string: string): string;
replaceApostrophesWithQuotes(string: string): string;
replaceQuotesWithApostrophes(string: string): string;
createCookieString(string: string): string;
revertCookieString(string: string): string;
getCookieDomain(): string;
getDomain(doc: string, locationHostname: string): string;
getUserIdentities(mpid: MPID): UserIdentities;
getAllUserAttributes(mpid: MPID): AllUserAttributes;
getCartProducts(mpid: MPID): Product[];
setCartProducts(allProducts: Product[]): void;
saveUserIdentitiesToPersistence(
mpid: MPID,
userIdentities: UserIdentities
): void;
saveUserAttributesToPersistence(
mpid: MPID,
userIdentities: UserIdentities
): void;
saveUserCookieSyncDatesToPersistence(mpid: MPID, csd: CookieSyncDate): void;
saveUserConsentStateToCookies(mpid, consentState: ConsentState): void;
savePersistence(persistance: IPersistenceV2DTO): void;
getPersistence(): IPersistenceV2DTO;
getConsentState(mpid: MPID): ConsentState | null;
getFirstSeenTime(mpid: MPID): string | null;
setFirstSeenTime(mpid: MPID, time: number): void;
getLastSeenTime(mpid: MPID): number | null;
setLastSeenTime(mpid: MPID, time: number): void;
getDeviceId(): string;
setDeviceId(guid: string): void;
resetPersistence(): void;
forwardingStatsBatches: iForwardingStatsBatches;
}
19 changes: 18 additions & 1 deletion src/persistence.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export default function _Persistence(mpInstance) {
this.useLocalStorage = function() {
return (
!mpInstance._Store.SDKConfig.useCookieStorage &&
// FIXME: Should return boolean but is returning an object
mpInstance._Store.isLocalStorageAvailable
);
};
Expand Down Expand Up @@ -139,6 +140,7 @@ export default function _Persistence(mpInstance) {
};

this.storeProductsInMemory = function(products, mpid) {
// TODO: Is it necessary to do a try/catch? When would it throw?
if (products) {
try {
mpInstance._Store.cartProducts =
Expand All @@ -153,9 +155,14 @@ export default function _Persistence(mpInstance) {
}
};

// Stores the state of the Store after being read from Persistence
// If this is a first visit, does a basic assignment of client and
// device IDs
this.storeDataInMemory = function(obj, currentMPID) {
try {
if (!obj) {
// Sets up the default "Store" if a cookie is not found
// (user's fresh visit)
mpInstance.Logger.verbose(
Messages.InformationMessages.CookieNotFound
);
Expand Down Expand Up @@ -215,9 +222,11 @@ export default function _Persistence(mpInstance) {
mpInstance._Store.sessionStartDate = new Date();
}

// TODO: What is the purpose of overwriting the obj?
if (currentMPID) {
obj = obj[currentMPID];
} else {
// FIXME: This could make obj === undefined
obj = obj[obj.cu];
}
}
Expand All @@ -228,7 +237,6 @@ export default function _Persistence(mpInstance) {

this.determineLocalStorageAvailability = function(storage) {
var result;

if (window.mParticle && window.mParticle._forceNoLocalStorage) {
storage = undefined;
}
Expand All @@ -237,6 +245,7 @@ export default function _Persistence(mpInstance) {
storage.setItem('mparticle', 'test');
result = storage.getItem('mparticle') === 'test';
storage.removeItem('mparticle');
// FIXME: This should return a boolean
return result && storage;
} catch (e) {
return false;
Expand Down Expand Up @@ -703,6 +712,8 @@ export default function _Persistence(mpInstance) {
}
};

// TODO: Describe expected functionality and give examples of a persistence object
// FIXME: this should not mutate persistence
this.encodePersistence = function(persistence) {
persistence = JSON.parse(persistence);
for (var key in persistence.gs) {
Expand Down Expand Up @@ -763,6 +774,8 @@ export default function _Persistence(mpInstance) {
return self.createCookieString(JSON.stringify(persistence));
};

// TODO: Describe expected functionality and give examples of a persistence object
// FIXME: this should not mutate persistence
this.decodePersistence = function(persistence) {
try {
if (persistence) {
Expand Down Expand Up @@ -817,18 +830,22 @@ export default function _Persistence(mpInstance) {
}
};

// TODO: This should be a helper
this.replaceCommasWithPipes = function(string) {
return string.replace(/,/g, '|');
};

// TODO: This should be a helper
this.replacePipesWithCommas = function(string) {
return string.replace(/\|/g, ',');
};

// TODO: This should be a helper
this.replaceApostrophesWithQuotes = function(string) {
return string.replace(/\'/g, '"');
};

// TODO: This should be a helper
this.replaceQuotesWithApostrophes = function(string) {
return string.replace(/\"/g, "'");
};
Expand Down
8 changes: 7 additions & 1 deletion src/sdkRuntimeModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ export interface SDKProduct {
}

export interface MParticleWebSDK {
_forceNoLocalStorage?: boolean;

// TODO: Why are tehse both in the Store SDK Config and in the MP SDK object?
maxCookieSize?: number;
useCookieStorage?: boolean;

addForwarder(mockForwarder: MPForwarder): void;
Identity: SDKIdentityApi;
Logger: SDKLoggerApi;
Expand All @@ -141,7 +147,7 @@ export interface MParticleWebSDK {
_NativeSdkHelpers: any; // TODO: Set up API
_Persistence: any; // TODO: Set up Persistence API
_preInit: any; // TODO: Set up API
_resetForTests(MPConfig?: SDKInitConfig): void;
_resetForTests(MPConfig?: SDKInitConfig, keepPersistence?: boolean): void;
init(apiKey: string, config: SDKInitConfig, instanceName?: string): void;
getAppName(): string;
getAppVersion(): string;
Expand Down
12 changes: 8 additions & 4 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ function createSDKConfig(config: SDKInitConfig): SDKConfig {
export type PixelConfiguration = Dictionary;
export type MigrationData = Dictionary;
export type ServerSettings = Dictionary;
export type SessionAttributes = Dictionary;
export type IntegrationAttributes = Dictionary<Dictionary<string>>;

type WrapperSDKTypes = 'flutter' | 'none';
interface WrapperSDKInfo {
Expand All @@ -111,8 +113,10 @@ interface WrapperSDKInfo {

// Temporary Interface until Store can be refactored as a class
export interface IStore {
mpid?: MPID;
isEnabled: boolean;
sessionAttributes: Dictionary;
// sessionAttributes: SessionAttributes;
currentSessionMPIDs: MPID[];
consentState: SDKConsentState | null;
sessionId: string | null;
Expand Down Expand Up @@ -141,6 +145,7 @@ export interface IStore {
isLoggedIn: boolean;
cookieSyncDates: Dictionary<number>;
integrationAttributes: Dictionary<Dictionary<string>>;
// integrationAttributes: IntegrationAttributes;
requireDelay: boolean;
isLocalStorageAvailable: boolean | null;
storageName: string | null;
Expand Down Expand Up @@ -219,10 +224,9 @@ export default function Store(
this.deviceId = config.deviceId;
}
if (config.hasOwnProperty('isDevelopmentMode')) {
this.SDKConfig.isDevelopmentMode =
mpInstance._Helpers.returnConvertedBoolean(
config.isDevelopmentMode
);
this.SDKConfig.isDevelopmentMode = mpInstance._Helpers.returnConvertedBoolean(
config.isDevelopmentMode
);
} else {
this.SDKConfig.isDevelopmentMode = false;
}
Expand Down
Loading