@mparticle/web-sdk 2.17.4 → 2.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.17.4",
3
+ "version": "2.18.1",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -101,7 +101,7 @@
101
101
  "karma-chai": "^0.1.0",
102
102
  "karma-chrome-launcher": "^3.1.0",
103
103
  "karma-edge-launcher": "^0.4.1",
104
- "karma-firefox-launcher": "^2.1.0",
104
+ "karma-firefox-launcher": "^2.1.2",
105
105
  "karma-ie-launcher": "^1.0.0",
106
106
  "karma-junit-reporter": "^2.0.1",
107
107
  "karma-mocha": "^2.0.1",
@@ -7,6 +7,7 @@ import {
7
7
  } from './sdkRuntimeModels';
8
8
  import { convertEvents } from './sdkToEventsApiConverter';
9
9
  import Types from './types';
10
+ import { isEmpty } from './utils';
10
11
 
11
12
  export class BatchUploader {
12
13
  //we upload JSON, but this content type is required to avoid a CORS preflight request
@@ -64,8 +65,8 @@ export class BatchUploader {
64
65
  return false;
65
66
  }
66
67
 
67
- queueEvent(event: SDKEvent) {
68
- if (event) {
68
+ queueEvent(event: SDKEvent): void {
69
+ if (!isEmpty(event)) {
69
70
  this.pendingEvents.push(event);
70
71
  this.mpInstance.Logger.verbose(
71
72
  `Queuing event: ${JSON.stringify(event)}`
@@ -131,15 +132,24 @@ export class BatchUploader {
131
132
  eventsBySession.set(sdkEvent.SessionId, events);
132
133
  }
133
134
  for (const entry of Array.from(eventsBySession.entries())) {
134
- let uploadBatchObject = convertEvents(mpid, entry[1], mpInstance);
135
- const onCreateBatchCallback = mpInstance._Store.SDKConfig.onCreateBatch;
135
+ let uploadBatchObject = convertEvents(
136
+ mpid,
137
+ entry[1],
138
+ mpInstance
139
+ );
140
+ const onCreateBatchCallback =
141
+ mpInstance._Store.SDKConfig.onCreateBatch;
136
142
 
137
143
  if (onCreateBatchCallback) {
138
- uploadBatchObject = onCreateBatchCallback(uploadBatchObject);
144
+ uploadBatchObject = onCreateBatchCallback(
145
+ uploadBatchObject
146
+ );
139
147
  if (uploadBatchObject) {
140
148
  uploadBatchObject.modified = true;
141
149
  } else {
142
- mpInstance.Logger.warning('Skiping batch upload because no batch was returned from onCreateBatch callback');
150
+ mpInstance.Logger.warning(
151
+ 'Skiping batch upload because no batch was returned from onCreateBatch callback'
152
+ );
143
153
  }
144
154
  }
145
155
 
@@ -193,13 +203,18 @@ export class BatchUploader {
193
203
 
194
204
  private async upload(
195
205
  logger: SDKLoggerApi,
196
- uploads: Batch[],
206
+ _uploads: Batch[],
197
207
  useBeacon: boolean
198
208
  ): Promise<Batch[]> {
199
209
  let uploader;
200
- if (!uploads || uploads.length < 1) {
210
+
211
+ // Filter out any batches that don't have events
212
+ const uploads = _uploads.filter(upload => !isEmpty(upload.events));
213
+
214
+ if (isEmpty(uploads)) {
201
215
  return null;
202
216
  }
217
+
203
218
  logger.verbose(`Uploading batches: ${JSON.stringify(uploads)}`);
204
219
  logger.verbose(`Batch count: ${uploads.length}`);
205
220
 
package/src/helpers.js CHANGED
@@ -398,14 +398,6 @@ export default function Helpers(mpInstance) {
398
398
  return false;
399
399
  };
400
400
 
401
- this.parseStringOrNumber = function(value) {
402
- if (Validators.isStringOrNumber(value)) {
403
- return value;
404
- } else {
405
- return null;
406
- }
407
- };
408
-
409
401
  this.generateHash = function(name) {
410
402
  var hash = 0,
411
403
  i = 0,
@@ -512,6 +504,7 @@ export default function Helpers(mpInstance) {
512
504
  this.isObject = utils.isObject;
513
505
  this.decoded = utils.decoded;
514
506
  this.returnConvertedBoolean = utils.returnConvertedBoolean;
507
+ this.parseStringOrNumber = utils.parseStringOrNumber;
515
508
 
516
509
  // Imported Validators
517
510
  this.Validators = Validators;
@@ -4,6 +4,10 @@ import ServerModel from './serverModel';
4
4
  import { SDKEvent, BaseEvent, MParticleWebSDK } from './sdkRuntimeModels';
5
5
  import { convertEvents } from './sdkToEventsApiConverter';
6
6
  import * as EventsApi from '@mparticle/event-models';
7
+
8
+ const mockFunction = function () {
9
+ return null;
10
+ }
7
11
  export default class _BatchValidator {
8
12
  private getMPInstance() {
9
13
  return {
@@ -15,22 +19,89 @@ export default class _BatchValidator {
15
19
  return 'mockId';
16
20
  },
17
21
  extend: window.mParticle.getInstance()._Helpers.extend,
22
+ createServiceUrl: mockFunction,
23
+ parseNumber: mockFunction,
24
+ isObject: mockFunction,
25
+ returnConvertedBoolean: mockFunction,
26
+ Validators: null,
18
27
  },
28
+ _resetForTests: mockFunction,
29
+ _APIClient: null,
30
+ _Consent: null,
31
+ _ServerModel: null,
32
+ _SessionManager: null,
19
33
  _Store: {
20
34
  sessionId: 'mockSessionId',
21
- SDKConfig: {},
22
- },
23
- Identity: {
24
- getCurrentUser: function() {
25
- return null;
35
+ devToken: 'test_dev_token',
36
+ isFirstRun: true,
37
+ isEnabled: true,
38
+ sessionAttributes: {},
39
+ currentSessionMPIDs: [],
40
+ consentState: null,
41
+ clientId: null,
42
+ deviceId: null,
43
+ migrationData: {},
44
+ serverSettings: {},
45
+ dateLastEventSent: null,
46
+ sessionStartDate: null,
47
+ currentPosition: null,
48
+ isTracking: false,
49
+ watchPositionId: null,
50
+ cartProducts: [],
51
+ eventQueue: [],
52
+ currencyCode: null,
53
+ globalTimer: null,
54
+ context: null,
55
+ configurationLoaded: false,
56
+ identityCallInFlight: false,
57
+ migratingToIDSyncCookies: false,
58
+ nonCurrentUserMPIDs: {},
59
+ identifyCalled: false,
60
+ isLoggedIn: false,
61
+ cookieSyncDates: {},
62
+ integrationAttributes: {},
63
+ requireDelay: true,
64
+ isLocalStorageAvailable: null,
65
+ integrationDelayTimeoutStart: null,
66
+ storageName: null,
67
+ prodStorageName: null,
68
+ activeForwarders: [],
69
+ kits: {},
70
+ configuredForwarders: [],
71
+ pixelConfigurations: [],
72
+ SDKConfig: {
73
+ isDevelopmentMode: false,
74
+ onCreateBatch: mockFunction,
26
75
  },
27
76
  },
28
- getAppVersion: function() {
29
- return null;
77
+ config: null,
78
+ eCommerce: null,
79
+ Identity: {
80
+ getCurrentUser: mockFunction,
81
+ IdentityAPI: {},
82
+ identify: mockFunction,
83
+ login: mockFunction,
84
+ logout: mockFunction,
85
+ modify: mockFunction,
30
86
  },
31
- getAppName: function() {
32
- return null;
87
+ Logger: {
88
+ verbose: mockFunction,
89
+ error: mockFunction,
90
+ warning: mockFunction,
33
91
  },
92
+ ProductActionType: null,
93
+ ServerModel: null,
94
+ addForwarder: mockFunction,
95
+ generateHash: mockFunction,
96
+ getAppVersion: mockFunction,
97
+ getAppName: mockFunction,
98
+ getInstance: mockFunction,
99
+ init: mockFunction,
100
+ logBaseEvent: mockFunction,
101
+ logEvent: mockFunction,
102
+ logLevel: 'none',
103
+ setPosition: mockFunction,
104
+ upload: mockFunction,
34
105
  };
35
106
  }
36
107
 
@@ -188,6 +188,16 @@ export default function mParticleInstance(instanceName) {
188
188
  self._preInit.readyQueue.push(f);
189
189
  }
190
190
  };
191
+ /**
192
+ * Returns the current mParticle environment setting
193
+ * @method getEnvironment
194
+ * @returns {String} mParticle environment setting
195
+ */
196
+ this.getEnvironment = function() {
197
+ return self._Store.SDKConfig.isDevelopmentMode
198
+ ? Types.Environment.Development
199
+ : Types.Environment.Production;
200
+ };
191
201
  /**
192
202
  * Returns the mParticle SDK version number
193
203
  * @method getVersion
@@ -1205,8 +1215,51 @@ export default function mParticleInstance(instanceName) {
1205
1215
  this._getIntegrationDelays = function() {
1206
1216
  return self._preInit.integrationDelays;
1207
1217
  };
1208
- this._setIntegrationDelay = function(module, boolean) {
1209
- self._preInit.integrationDelays[module] = boolean;
1218
+ /*
1219
+ An integration delay is a workaround that prevents events from being sent when it is necessary to do so.
1220
+ Some server side integrations require a client side value to be included in the payload to successfully
1221
+ forward. This value can only be pulled from the client side partner SDK.
1222
+
1223
+ During the kit initialization, the kit:
1224
+ * sets an integration delay to `true`
1225
+ * grabs the required value from the partner SDK,
1226
+ * sets it via `setIntegrationAttribute`
1227
+ * sets the integration delay to `false`
1228
+
1229
+ The core SDK can then read via `isDelayedByIntegration` to no longer delay sending events.
1230
+
1231
+ This integration attribute is now on the batch payload for the server side to read.
1232
+
1233
+ If there is no delay, then the events sent before an integration attribute is included would not
1234
+ be forwarded successfully server side.
1235
+ */
1236
+ this._setIntegrationDelay = function(module, shouldDelayIntegration) {
1237
+ self._preInit.integrationDelays[module] = shouldDelayIntegration;
1238
+
1239
+ // If the integration delay is set to true, no further action needed
1240
+ if (shouldDelayIntegration === true) {
1241
+ return;
1242
+ }
1243
+ // If the integration delay is set to false, check to see if there are any
1244
+ // other integration delays set to true. It not, process the queued events/.
1245
+
1246
+ const integrationDelaysKeys = Object.keys(
1247
+ self._preInit.integrationDelays
1248
+ );
1249
+
1250
+ if (integrationDelaysKeys.length === 0) {
1251
+ return;
1252
+ }
1253
+
1254
+ const hasIntegrationDelays = integrationDelaysKeys.some(function(
1255
+ integration
1256
+ ) {
1257
+ return self._preInit.integrationDelays[integration] === true;
1258
+ });
1259
+
1260
+ if (!hasIntegrationDelays) {
1261
+ self._APIClient.processQueuedEvents();
1262
+ }
1210
1263
  };
1211
1264
  }
1212
1265
 
@@ -128,6 +128,9 @@ function mParticle() {
128
128
  this.getAppVersion = function() {
129
129
  return self.getInstance().getAppVersion();
130
130
  };
131
+ this.getEnvironment = function() {
132
+ return self.getInstance().getEnvironment();
133
+ };
131
134
  this.stopTrackingLocation = function() {
132
135
  self.getInstance().stopTrackingLocation();
133
136
  };
@@ -1,9 +1,15 @@
1
- import { DataPlanVersion } from '@mparticle/data-planning-models';
1
+ import * as EventsApi from '@mparticle/event-models';
2
2
  import { Batch } from '@mparticle/event-models';
3
- import { MPConfiguration, SDKEventCustomFlags } from '@mparticle/web-sdk';
4
- import { SDKConfig } from './store';
5
- import { Dictionary } from './utils';
3
+ import { DataPlanVersion, DataPlan } from '@mparticle/data-planning-models';
4
+ import { MPConfiguration, IdentityApiData } from '@mparticle/web-sdk';
5
+ import { IStore, SDKConfig } from './store';
6
6
  import Validators from './validators';
7
+ import { Dictionary } from './utils';
8
+ import { IServerModel } from './serverModel';
9
+
10
+
11
+ // TODO: Resolve this with version in @mparticle/web-sdk
12
+ export type SDKEventCustomFlags = Dictionary<any>;
7
13
 
8
14
  export interface SDKEvent {
9
15
  DeviceId: string;
@@ -25,7 +31,7 @@ export interface SDKEvent {
25
31
  Debug: boolean;
26
32
  Location?: SDKGeoLocation;
27
33
  OptOut?: boolean;
28
- CustomFlags?: { [key: string]: string };
34
+ CustomFlags?: SDKEventCustomFlags;
29
35
  AppVersion?: string;
30
36
  AppName?: string;
31
37
  Package?: string;
@@ -123,12 +129,18 @@ export interface MParticleWebSDK {
123
129
  addForwarder(mockForwarder: MPForwarder): void;
124
130
  Identity: SDKIdentityApi;
125
131
  Logger: SDKLoggerApi;
126
- _Store: SDKStoreApi;
132
+ _APIClient: any; // TODO: Set up API Client
133
+ _Store: IStore;
127
134
  _Helpers: SDKHelpersApi;
128
135
  config: SDKInitConfig;
129
- _resetForTests(MPConfig: SDKConfig): void;
136
+ _ServerModel: IServerModel;
137
+ _SessionManager: any; // TODO: Set up Session Manager
138
+ _Consent: any; // TODO: Set up Consent SDK
139
+ _resetForTests(MPConfig?: SDKConfig): void;
130
140
  init(apiKey: string, config: SDKInitConfig, instanceName?: string): void;
131
- getInstance();
141
+ getAppName(): string;
142
+ getAppVersion(): string;
143
+ getInstance(): MParticleWebSDK; // TODO: Create a new type for MParticleWebSDKInstance
132
144
  ServerModel();
133
145
  upload();
134
146
  setPosition(lat: number | string, lng: number | string): void;
@@ -160,7 +172,7 @@ export type MPForwarder = Dictionary;
160
172
  // Currently, this extends MPConfiguration in @types/mparticle__web-sdk
161
173
  // and the two will be merged in once the Store module is refactored
162
174
  export interface SDKInitConfig
163
- extends Omit<MPConfiguration, 'dataPlan' | 'logLevel'> {
175
+ extends Omit<MPConfiguration, 'dataPlan' | 'logLevel'> {
164
176
  dataPlan?: DataPlanConfig | KitBlockerDataPlan; // TODO: These should be eventually split into two different attributes
165
177
  logLevel?: LogLevelType;
166
178
 
@@ -204,10 +216,12 @@ export interface SDKIdentityApi {
204
216
 
205
217
  export interface SDKHelpersApi {
206
218
  createServiceUrl(arg0: string, arg1: string): void;
207
- parseNumber(value: number);
219
+ extend(...args: any[]);
220
+ parseNumber(value: string | number): number;
208
221
  generateUniqueId();
209
222
  isObject(item: any);
210
223
  returnConvertedBoolean(data: string | boolean | number): boolean;
224
+ sanitizeAttributes(attrs: Dictionary<string>, name: string): Dictionary<string> | null;
211
225
  Validators: typeof Validators;
212
226
  }
213
227
 
@@ -217,7 +231,9 @@ export interface SDKLoggerApi {
217
231
  warning(arg0: string): void;
218
232
  }
219
233
 
234
+ // TODO: Merge this with IStore in store.ts
220
235
  export interface SDKStoreApi {
236
+ isEnabled: boolean;
221
237
  isFirstRun: boolean;
222
238
  devToken: string;
223
239
  SDKConfig: SDKConfigApi;
@@ -229,10 +245,13 @@ export interface SDKConfigApi {
229
245
  v3SecureServiceUrl?: string;
230
246
  isDevelopmentMode: boolean;
231
247
  appVersion?: string;
232
- onCreateBatch(batch: Batch): Batch;
248
+ onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch;
233
249
  }
234
250
  export interface MParticleUser {
235
251
  getMPID(): string;
252
+ getConsentState(): any; // FIXME:
253
+ getAllUserAttributes(): any; // FIXME;
254
+ getUserIdentities(): IdentityApiData; // FIXME: Is this correct?
236
255
  }
237
256
 
238
257
  export interface SDKConsentState {
@@ -280,6 +299,10 @@ export interface BaseEvent {
280
299
  eventType?: number;
281
300
  data?: { [key: string]: string };
282
301
  customFlags?: { [key: string]: string };
302
+ toEventAPIObject?(): SDKEvent;
303
+ sourceMessageId?: string;
304
+ userAttributeChanges?: SDKUserAttributeChangeData;
305
+ userIdentityChanges?: SDKUserIdentityChangeData;
283
306
  }
284
307
 
285
308
  export interface KitBlockerOptions {