@mparticle/web-sdk 2.79.3 → 2.80.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.
Files changed (39) hide show
  1. package/dist/mparticle.common.js +220 -574
  2. package/dist/mparticle.esm.js +220 -574
  3. package/dist/mparticle.js +1489 -1793
  4. package/dist/types/src/configAPIClient.d.ts +1 -0
  5. package/dist/types/src/ecommerce.d.ts +3 -53
  6. package/dist/types/src/ecommerce.interfaces.d.ts +11 -12
  7. package/dist/types/src/events.interfaces.d.ts +1 -1
  8. package/dist/types/src/forwarders.d.ts +4 -26
  9. package/dist/types/src/forwarders.interfaces.d.ts +41 -10
  10. package/dist/types/src/identity-utils.d.ts +3 -3
  11. package/dist/types/src/identity.d.ts +3 -0
  12. package/dist/types/src/identity.interfaces.d.ts +45 -11
  13. package/dist/types/src/identityApiClient.d.ts +5 -4
  14. package/dist/types/src/mp-instance.d.ts +2 -2
  15. package/dist/types/src/pageViewTracker.d.ts +12 -5
  16. package/dist/types/src/persistence.d.ts +3 -44
  17. package/dist/types/src/persistence.interfaces.d.ts +12 -13
  18. package/dist/types/src/sdkRuntimeModels.d.ts +3 -2
  19. package/dist/types/src/store.d.ts +5 -3
  20. package/package.json +1 -1
  21. package/src/configAPIClient.ts +1 -0
  22. package/src/ecommerce.interfaces.ts +12 -21
  23. package/src/{ecommerce.js → ecommerce.ts} +144 -73
  24. package/src/events.interfaces.ts +1 -1
  25. package/src/events.ts +10 -2
  26. package/src/forwarders.interfaces.ts +73 -10
  27. package/src/{forwarders.js → forwarders.ts} +214 -176
  28. package/src/helpers.ts +7 -3
  29. package/src/identity-utils.ts +2 -2
  30. package/src/identity.interfaces.ts +58 -14
  31. package/src/{identity.js → identity.ts} +237 -192
  32. package/src/identityApiClient.ts +9 -9
  33. package/src/mp-instance.ts +2 -2
  34. package/src/pageViewTracker.ts +176 -42
  35. package/src/persistence.interfaces.ts +12 -13
  36. package/src/persistence.ts +1210 -0
  37. package/src/sdkRuntimeModels.ts +3 -1
  38. package/src/store.ts +5 -3
  39. package/src/persistence.js +0 -985
@@ -1,985 +0,0 @@
1
- import Constants from './constants';
2
- import Polyfill from './polyfill';
3
- import * as Utils from './utils';
4
-
5
- var Base64 = Polyfill.Base64,
6
- Messages = Constants.Messages,
7
- Base64CookieKeys = Constants.Base64CookieKeys,
8
- SDKv2NonMPIDCookieKeys = Constants.SDKv2NonMPIDCookieKeys,
9
- StorageNames = Constants.StorageNames;
10
-
11
- export default function _Persistence(mpInstance) {
12
- var self = this;
13
-
14
- // https://go.mparticle.com/work/SQDSDKS-5022
15
- this.useLocalStorage = function() {
16
- return (
17
- !mpInstance._Store.SDKConfig.useCookieStorage &&
18
- mpInstance._Store.isLocalStorageAvailable
19
- );
20
- };
21
-
22
- this.initializeStorage = function() {
23
- try {
24
- var storage,
25
- localStorageData = self.getLocalStorage(),
26
- cookies = self.getCookie(),
27
- allData;
28
-
29
- // https://go.mparticle.com/work/SQDSDKS-6045
30
- // Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle
31
- if (!localStorageData && !cookies) {
32
- mpInstance._Store.isFirstRun = true;
33
- mpInstance._Store.mpid = 0;
34
- } else {
35
- mpInstance._Store.isFirstRun = false;
36
- }
37
-
38
- // https://go.mparticle.com/work/SQDSDKS-6045
39
- if (!mpInstance._Store.isLocalStorageAvailable) {
40
- mpInstance._Store.SDKConfig.useCookieStorage = true;
41
- }
42
-
43
- // https://go.mparticle.com/work/SQDSDKS-6046
44
- if (mpInstance._Store.isLocalStorageAvailable) {
45
- storage = window.localStorage;
46
- if (mpInstance._Store.SDKConfig.useCookieStorage) {
47
- // For migrating from localStorage to cookies -- If an instance switches from localStorage to cookies, then
48
- // no mParticle cookie exists yet and there is localStorage. Get the localStorage, set them to cookies, then delete the localStorage item.
49
- if (localStorageData) {
50
- if (cookies) {
51
- // https://go.mparticle.com/work/SQDSDKS-6047
52
- allData = Utils.extend(
53
- false,
54
- localStorageData,
55
- cookies
56
- );
57
- } else {
58
- allData = localStorageData;
59
- }
60
- storage.removeItem(mpInstance._Store.storageName);
61
- } else if (cookies) {
62
- allData = cookies;
63
- }
64
- self.storeDataInMemory(allData);
65
- } else {
66
- // For migrating from cookie to localStorage -- If an instance is newly switching from cookies to localStorage, then
67
- // no mParticle localStorage exists yet and there are cookies. Get the cookies, set them to localStorage, then delete the cookies.
68
- if (cookies) {
69
- if (localStorageData) {
70
- // https://go.mparticle.com/work/SQDSDKS-6047
71
- allData = Utils.extend(
72
- false,
73
- localStorageData,
74
- cookies
75
- );
76
- } else {
77
- allData = cookies;
78
- }
79
- self.storeDataInMemory(allData);
80
- self.expireCookies(mpInstance._Store.storageName);
81
- } else {
82
- self.storeDataInMemory(localStorageData);
83
- }
84
- }
85
- } else {
86
- self.storeDataInMemory(cookies);
87
- }
88
-
89
- // https://go.mparticle.com/work/SQDSDKS-6046
90
- // Stores all non-current user MPID information into the store
91
- for (var key in allData) {
92
- if (allData.hasOwnProperty(key)) {
93
- if (!SDKv2NonMPIDCookieKeys[key]) {
94
- mpInstance._Store.nonCurrentUserMPIDs[key] =
95
- allData[key];
96
- }
97
- }
98
- }
99
- self.update();
100
- } catch (e) {
101
- // If cookies or local storage is corrupt, we want to remove it
102
- // so that in the future, initializeStorage will work
103
- if (
104
- self.useLocalStorage() &&
105
- mpInstance._Store.isLocalStorageAvailable
106
- ) {
107
- localStorage.removeItem(mpInstance._Store.storageName);
108
- } else {
109
- self.expireCookies(mpInstance._Store.storageName);
110
- }
111
- mpInstance.Logger.error('Error initializing storage: ' + e);
112
- }
113
- };
114
-
115
- this.update = function() {
116
- if (!mpInstance._Store.webviewBridgeEnabled) {
117
- if (mpInstance._Store.SDKConfig.useCookieStorage) {
118
- self.setCookie();
119
- }
120
-
121
- self.setLocalStorage();
122
- }
123
- };
124
-
125
- // https://go.mparticle.com/work/SQDSDKS-6045
126
- this.storeDataInMemory = function(obj, currentMPID) {
127
- try {
128
- if (!obj) {
129
- mpInstance.Logger.verbose(
130
- Messages.InformationMessages.CookieNotFound
131
- );
132
- mpInstance._Store.clientId =
133
- mpInstance._Store.clientId ||
134
- mpInstance._Helpers.generateUniqueId();
135
- mpInstance._Store.deviceId =
136
- mpInstance._Store.deviceId ||
137
- mpInstance._Helpers.generateUniqueId();
138
- } else {
139
- // Set MPID first, then change object to match MPID data
140
- if (currentMPID) {
141
- mpInstance._Store.mpid = currentMPID;
142
- } else {
143
- mpInstance._Store.mpid = obj.cu || 0;
144
- }
145
-
146
- obj.gs = obj.gs || {};
147
-
148
- mpInstance._Store.sessionId =
149
- obj.gs.sid || mpInstance._Store.sessionId;
150
- mpInstance._Store.isEnabled =
151
- typeof obj.gs.ie !== 'undefined'
152
- ? obj.gs.ie
153
- : mpInstance._Store.isEnabled;
154
- mpInstance._Store.sessionAttributes =
155
- obj.gs.sa || mpInstance._Store.sessionAttributes;
156
- mpInstance._Store.localSessionAttributes =
157
- obj.gs.lsa || mpInstance._Store.localSessionAttributes;
158
- mpInstance._Store.serverSettings =
159
- obj.gs.ss || mpInstance._Store.serverSettings;
160
- mpInstance._Store.devToken =
161
- mpInstance._Store.devToken || obj.gs.dt;
162
- mpInstance._Store.SDKConfig.appVersion =
163
- mpInstance._Store.SDKConfig.appVersion || obj.gs.av;
164
- mpInstance._Store.clientId =
165
- obj.gs.cgid ||
166
- mpInstance._Store.clientId ||
167
- mpInstance._Helpers.generateUniqueId();
168
-
169
- // For most persistence values, we prioritize localstorage/cookie values over
170
- // Store. However, we allow device ID to be overriden via a config value and
171
- // thus the priority of the deviceId value is
172
- // 1. value passed via config.deviceId
173
- // 2. previous value in persistence
174
- // 3. generate new guid
175
- mpInstance._Store.deviceId =
176
- mpInstance._Store.deviceId ||
177
- obj.gs.das ||
178
- mpInstance._Helpers.generateUniqueId();
179
-
180
- mpInstance._Store.integrationAttributes = obj.gs.ia || {};
181
- mpInstance._Store.context =
182
- obj.gs.c || mpInstance._Store.context;
183
- mpInstance._Store.currentSessionMPIDs =
184
- obj.gs.csm || mpInstance._Store.currentSessionMPIDs;
185
-
186
- mpInstance._Store.isLoggedIn = obj.l === true;
187
-
188
- if (obj.gs.les) {
189
- mpInstance._Store.dateLastEventSent = new Date(obj.gs.les);
190
- }
191
-
192
- if (obj.gs.ssd) {
193
- mpInstance._Store.sessionStartDate = new Date(obj.gs.ssd);
194
- } else {
195
- mpInstance._Store.sessionStartDate = new Date();
196
- }
197
-
198
- if (currentMPID) {
199
- obj = obj[currentMPID];
200
- } else {
201
- obj = obj[obj.cu];
202
- }
203
- }
204
- } catch (e) {
205
- mpInstance.Logger.error(Messages.ErrorMessages.CookieParseError);
206
- }
207
- };
208
-
209
- // https://go.mparticle.com/work/SQDSDKS-5022
210
- this.determineLocalStorageAvailability = function(storage) {
211
- var result;
212
-
213
- if (window.mParticle && window.mParticle._forceNoLocalStorage) {
214
- storage = undefined;
215
- }
216
-
217
- try {
218
- storage.setItem('mparticle', 'test');
219
- result = storage.getItem('mparticle') === 'test';
220
- storage.removeItem('mparticle');
221
- return result && storage;
222
- } catch (e) {
223
- return false;
224
- }
225
- };
226
-
227
- // https://go.mparticle.com/work/SQDSDKS-6021
228
- this.setLocalStorage = function() {
229
- if (!mpInstance._Store.isLocalStorageAvailable) {
230
- return;
231
- }
232
-
233
- // Block mprtcl-v4 localStorage when noFunctional is true
234
- if (mpInstance._CookieConsentManager?.getNoFunctional()) {
235
- return;
236
- }
237
-
238
- var key = mpInstance._Store.storageName,
239
- localStorageData = self.getLocalStorage() || {},
240
- currentUser = mpInstance.Identity.getCurrentUser(),
241
- mpid = currentUser ? currentUser.getMPID() : null;
242
- if (!mpInstance._Store.SDKConfig.useCookieStorage) {
243
- localStorageData.gs = localStorageData.gs || {};
244
-
245
- localStorageData.l = mpInstance._Store.isLoggedIn ? 1 : 0;
246
-
247
- if (mpInstance._Store.sessionId) {
248
- localStorageData.gs.csm = mpInstance._Store.currentSessionMPIDs;
249
- }
250
-
251
- localStorageData.gs.ie = mpInstance._Store.isEnabled;
252
-
253
- if (mpid) {
254
- localStorageData.cu = mpid;
255
- }
256
-
257
- if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) {
258
- localStorageData = Utils.extend(
259
- {},
260
- localStorageData,
261
- mpInstance._Store.nonCurrentUserMPIDs
262
- );
263
- mpInstance._Store.nonCurrentUserMPIDs = {};
264
- }
265
-
266
- localStorageData = setGlobalStorageAttributes(localStorageData);
267
-
268
- try {
269
- window.localStorage.setItem(
270
- encodeURIComponent(key),
271
- self.encodePersistence(JSON.stringify(localStorageData))
272
- );
273
- } catch (e) {
274
- mpInstance.Logger.error(
275
- 'Error with setting localStorage item.'
276
- );
277
- }
278
- }
279
- };
280
-
281
- function setGlobalStorageAttributes(data) {
282
- var store = mpInstance._Store;
283
- data.gs.sid = store.sessionId;
284
- data.gs.ie = store.isEnabled;
285
- data.gs.sa = store.sessionAttributes;
286
- data.gs.lsa = store.localSessionAttributes;
287
- data.gs.ss = store.serverSettings;
288
- data.gs.dt = store.devToken;
289
- data.gs.les = store.dateLastEventSent
290
- ? store.dateLastEventSent.getTime()
291
- : null;
292
- data.gs.av = store.SDKConfig.appVersion;
293
- data.gs.cgid = store.clientId;
294
- data.gs.das = store.deviceId;
295
- data.gs.c = store.context;
296
- data.gs.ssd = store.sessionStartDate
297
- ? store.sessionStartDate.getTime()
298
- : 0;
299
- data.gs.ia = store.integrationAttributes;
300
-
301
- return data;
302
- }
303
-
304
- this.getLocalStorage = function() {
305
- if (!mpInstance._Store.isLocalStorageAvailable) {
306
- return null;
307
- }
308
-
309
- var key = mpInstance._Store.storageName,
310
- localStorageData = self.decodePersistence(
311
- window.localStorage.getItem(key)
312
- ),
313
- obj = {},
314
- j;
315
-
316
- if (localStorageData) {
317
- localStorageData = JSON.parse(localStorageData);
318
- for (j in localStorageData) {
319
- if (localStorageData.hasOwnProperty(j)) {
320
- obj[j] = localStorageData[j];
321
- }
322
- }
323
- }
324
-
325
- if (Object.keys(obj).length) {
326
- return obj;
327
- }
328
-
329
- return null;
330
- };
331
-
332
- function removeLocalStorage(localStorageName) {
333
- localStorage.removeItem(localStorageName);
334
- }
335
-
336
- this.expireCookies = function(cookieName) {
337
- var date = new Date(),
338
- expires,
339
- domain,
340
- cookieDomain;
341
-
342
- cookieDomain = self.getCookieDomain();
343
-
344
- if (cookieDomain === '') {
345
- domain = '';
346
- } else {
347
- domain = ';domain=' + cookieDomain;
348
- }
349
-
350
- date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
351
- expires = '; expires=' + date.toUTCString();
352
- document.cookie = cookieName + '=' + '' + expires + '; path=/' + domain;
353
- };
354
-
355
- this.getCookie = function() {
356
- var cookies,
357
- key = mpInstance._Store.storageName,
358
- i,
359
- l,
360
- parts,
361
- name,
362
- cookie,
363
- result = key ? undefined : {};
364
-
365
- mpInstance.Logger.verbose(Messages.InformationMessages.CookieSearch);
366
-
367
- try {
368
- cookies = window.document.cookie.split('; ');
369
- } catch (e) {
370
- mpInstance.Logger.verbose('Unable to parse undefined cookie');
371
- return null;
372
- }
373
-
374
- for (i = 0, l = cookies.length; i < l; i++) {
375
- try {
376
- parts = cookies[i].split('=');
377
- name = parts.shift();
378
- cookie = parts.join('=');
379
- } catch (e) {
380
- mpInstance.Logger.verbose(
381
- 'Unable to parse cookie: ' + name + '. Skipping.'
382
- );
383
- }
384
-
385
- if (key && key === name) {
386
- result = mpInstance._Helpers.converted(cookie);
387
- break;
388
- }
389
-
390
- if (!key) {
391
- result[name] = mpInstance._Helpers.converted(cookie);
392
- }
393
- }
394
-
395
- if (result) {
396
- mpInstance.Logger.verbose(Messages.InformationMessages.CookieFound);
397
- return JSON.parse(self.decodePersistence(result));
398
- } else {
399
- return null;
400
- }
401
- };
402
-
403
- // https://go.mparticle.com/work/SQDSDKS-5022
404
- // https://go.mparticle.com/work/SQDSDKS-6021
405
- this.setCookie = function() {
406
- // Block mprtcl-v4 cookies when noFunctional is true
407
- if (mpInstance._CookieConsentManager?.getNoFunctional()) {
408
- return;
409
- }
410
-
411
- var mpid,
412
- currentUser = mpInstance.Identity.getCurrentUser();
413
- if (currentUser) {
414
- mpid = currentUser.getMPID();
415
- }
416
- var date = new Date(),
417
- key = mpInstance._Store.storageName,
418
- cookies = self.getCookie() || {},
419
- expires = new Date(
420
- date.getTime() +
421
- mpInstance._Store.SDKConfig.cookieExpiration *
422
- 24 *
423
- 60 *
424
- 60 *
425
- 1000
426
- ).toGMTString(),
427
- cookieDomain,
428
- domain,
429
- encodedCookiesWithExpirationAndPath;
430
-
431
- cookieDomain = self.getCookieDomain();
432
-
433
- if (cookieDomain === '') {
434
- domain = '';
435
- } else {
436
- domain = ';domain=' + cookieDomain;
437
- }
438
-
439
- cookies.gs = cookies.gs || {};
440
-
441
- if (mpInstance._Store.sessionId) {
442
- cookies.gs.csm = mpInstance._Store.currentSessionMPIDs;
443
- }
444
-
445
- if (mpid) {
446
- cookies.cu = mpid;
447
- }
448
-
449
- cookies.l = mpInstance._Store.isLoggedIn ? 1 : 0;
450
-
451
- cookies = setGlobalStorageAttributes(cookies);
452
-
453
- if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) {
454
- cookies = Utils.extend(
455
- {},
456
- cookies,
457
- mpInstance._Store.nonCurrentUserMPIDs
458
- );
459
- mpInstance._Store.nonCurrentUserMPIDs = {};
460
- }
461
-
462
- encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(
463
- cookies,
464
- expires,
465
- domain,
466
- mpInstance._Store.SDKConfig.maxCookieSize
467
- );
468
-
469
- mpInstance.Logger.verbose(Messages.InformationMessages.CookieSet);
470
-
471
- window.document.cookie =
472
- encodeURIComponent(key) + '=' + encodedCookiesWithExpirationAndPath;
473
- };
474
-
475
- /* This function determines if a cookie is greater than the configured maxCookieSize.
476
- - If it is, we remove an MPID and its associated UI/UA/CSD from the cookie.
477
- - Once removed, check size, and repeat.
478
- - Never remove the currentUser's MPID from the cookie.
479
-
480
- MPID removal priority:
481
- 1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie.
482
- 2. If there are currentSessionMPIDs:
483
- a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs
484
- b. Then remove MPIDs based on order in currentSessionMPIDs array, which
485
- stores MPIDs based on earliest login.
486
- */
487
- this.reduceAndEncodePersistence = function(
488
- persistence,
489
- expires,
490
- domain,
491
- maxCookieSize
492
- ) {
493
- var encodedCookiesWithExpirationAndPath,
494
- currentSessionMPIDs = persistence.gs.csm ? persistence.gs.csm : [];
495
- // Comment 1 above
496
- if (!currentSessionMPIDs.length) {
497
- for (var key in persistence) {
498
- if (persistence.hasOwnProperty(key)) {
499
- encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
500
- persistence,
501
- expires,
502
- domain
503
- );
504
- if (
505
- encodedCookiesWithExpirationAndPath.length >
506
- maxCookieSize
507
- ) {
508
- if (
509
- !SDKv2NonMPIDCookieKeys[key] &&
510
- key !== persistence.cu
511
- ) {
512
- delete persistence[key];
513
- }
514
- }
515
- }
516
- }
517
- } else {
518
- // Comment 2 above - First create an object of all MPIDs on the cookie
519
- var MPIDsOnCookie = {};
520
- for (var potentialMPID in persistence) {
521
- if (persistence.hasOwnProperty(potentialMPID)) {
522
- if (
523
- !SDKv2NonMPIDCookieKeys[potentialMPID] &&
524
- potentialMPID !== persistence.cu
525
- ) {
526
- MPIDsOnCookie[potentialMPID] = 1;
527
- }
528
- }
529
- }
530
- // Comment 2a above
531
- if (Object.keys(MPIDsOnCookie).length) {
532
- for (var mpid in MPIDsOnCookie) {
533
- encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
534
- persistence,
535
- expires,
536
- domain
537
- );
538
- if (
539
- encodedCookiesWithExpirationAndPath.length >
540
- maxCookieSize
541
- ) {
542
- if (MPIDsOnCookie.hasOwnProperty(mpid)) {
543
- if (currentSessionMPIDs.indexOf(mpid) === -1) {
544
- delete persistence[mpid];
545
- }
546
- }
547
- }
548
- }
549
- }
550
- // Comment 2b above
551
- for (var i = 0; i < currentSessionMPIDs.length; i++) {
552
- encodedCookiesWithExpirationAndPath = createFullEncodedCookie(
553
- persistence,
554
- expires,
555
- domain
556
- );
557
- if (
558
- encodedCookiesWithExpirationAndPath.length > maxCookieSize
559
- ) {
560
- var MPIDtoRemove = currentSessionMPIDs[i];
561
- if (persistence[MPIDtoRemove]) {
562
- mpInstance.Logger.verbose(
563
- 'Size of new encoded cookie is larger than maxCookieSize setting of ' +
564
- maxCookieSize +
565
- '. Removing from cookie the earliest logged in MPID containing: ' +
566
- JSON.stringify(persistence[MPIDtoRemove], 0, 2)
567
- );
568
- delete persistence[MPIDtoRemove];
569
- } else {
570
- mpInstance.Logger.error(
571
- 'Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of ' +
572
- maxCookieSize +
573
- '. We recommend using a maxCookieSize of 1500.'
574
- );
575
- }
576
- } else {
577
- break;
578
- }
579
- }
580
- }
581
-
582
- return encodedCookiesWithExpirationAndPath;
583
- };
584
-
585
- function createFullEncodedCookie(persistence, expires, domain) {
586
- return (
587
- self.encodePersistence(JSON.stringify(persistence)) +
588
- ';expires=' +
589
- expires +
590
- ';path=/' +
591
- domain
592
- );
593
- }
594
-
595
- this.findPrevCookiesBasedOnUI = function(identityApiData) {
596
- var persistence = mpInstance._Persistence.getPersistence();
597
- var matchedUser;
598
-
599
- if (identityApiData) {
600
- for (var requestedIdentityType in identityApiData.userIdentities) {
601
- if (persistence && Object.keys(persistence).length) {
602
- for (var key in persistence) {
603
- // any value in persistence that has an MPID key will be an MPID to search through
604
- // other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
605
- if (persistence[key].mpid) {
606
- var cookieUIs = persistence[key].ui;
607
- for (var cookieUIType in cookieUIs) {
608
- if (
609
- requestedIdentityType === cookieUIType &&
610
- identityApiData.userIdentities[
611
- requestedIdentityType
612
- ] === cookieUIs[cookieUIType]
613
- ) {
614
- matchedUser = key;
615
- break;
616
- }
617
- }
618
- }
619
- }
620
- }
621
- }
622
- }
623
-
624
- if (matchedUser) {
625
- self.storeDataInMemory(persistence, matchedUser);
626
- }
627
- };
628
-
629
- this.encodePersistence = function(persistence) {
630
- persistence = JSON.parse(persistence);
631
- for (var key in persistence.gs) {
632
- if (persistence.gs.hasOwnProperty(key)) {
633
- if (Base64CookieKeys[key]) {
634
- if (persistence.gs[key]) {
635
- // base64 encode any value that is an object or Array in globalSettings
636
- if (
637
- (Array.isArray(persistence.gs[key]) &&
638
- persistence.gs[key].length) ||
639
- (mpInstance._Helpers.isObject(
640
- persistence.gs[key]
641
- ) &&
642
- Object.keys(persistence.gs[key]).length)
643
- ) {
644
- persistence.gs[key] = Base64.encode(
645
- JSON.stringify(persistence.gs[key])
646
- );
647
- } else {
648
- delete persistence.gs[key];
649
- }
650
- } else {
651
- delete persistence.gs[key];
652
- }
653
- } else if (key === 'ie') {
654
- persistence.gs[key] = persistence.gs[key] ? 1 : 0;
655
- } else if (!persistence.gs[key]) {
656
- delete persistence.gs[key];
657
- }
658
- }
659
- }
660
-
661
- for (var mpid in persistence) {
662
- if (persistence.hasOwnProperty(mpid)) {
663
- if (!SDKv2NonMPIDCookieKeys[mpid]) {
664
- for (key in persistence[mpid]) {
665
- if (persistence[mpid].hasOwnProperty(key)) {
666
- if (Base64CookieKeys[key]) {
667
- if (
668
- mpInstance._Helpers.isObject(
669
- persistence[mpid][key]
670
- ) &&
671
- Object.keys(persistence[mpid][key]).length
672
- ) {
673
- persistence[mpid][key] = Base64.encode(
674
- JSON.stringify(persistence[mpid][key])
675
- );
676
- } else {
677
- delete persistence[mpid][key];
678
- }
679
- }
680
- }
681
- }
682
- }
683
- }
684
- }
685
-
686
- return Utils.createCookieString(JSON.stringify(persistence));
687
- };
688
-
689
- // TODO: This should actually be decodePersistenceString or
690
- // we should refactor this to take a string and return an object
691
- this.decodePersistence = function(persistence) {
692
- try {
693
- if (persistence) {
694
- persistence = JSON.parse(Utils.revertCookieString(persistence));
695
- if (
696
- mpInstance._Helpers.isObject(persistence) &&
697
- Object.keys(persistence).length
698
- ) {
699
- for (var key in persistence.gs) {
700
- if (persistence.gs.hasOwnProperty(key)) {
701
- if (Base64CookieKeys[key]) {
702
- persistence.gs[key] = JSON.parse(
703
- Base64.decode(persistence.gs[key])
704
- );
705
- } else if (key === 'ie') {
706
- persistence.gs[key] = Boolean(
707
- persistence.gs[key]
708
- );
709
- }
710
- }
711
- }
712
-
713
- for (var mpid in persistence) {
714
- if (persistence.hasOwnProperty(mpid)) {
715
- if (!SDKv2NonMPIDCookieKeys[mpid]) {
716
- for (key in persistence[mpid]) {
717
- if (persistence[mpid].hasOwnProperty(key)) {
718
- if (Base64CookieKeys[key]) {
719
- if (persistence[mpid][key].length) {
720
- persistence[mpid][
721
- key
722
- ] = JSON.parse(
723
- Base64.decode(
724
- persistence[mpid][key]
725
- )
726
- );
727
- }
728
- }
729
- }
730
- }
731
- } else if (mpid === 'l') {
732
- persistence[mpid] = Boolean(persistence[mpid]);
733
- }
734
- }
735
- }
736
- }
737
-
738
- return JSON.stringify(persistence);
739
- }
740
- } catch (e) {
741
- mpInstance.Logger.error('Problem with decoding cookie', e);
742
- }
743
- };
744
-
745
- this.getCookieDomain = function() {
746
- if (mpInstance._Store.SDKConfig.cookieDomain) {
747
- return mpInstance._Store.SDKConfig.cookieDomain;
748
- } else {
749
- var rootDomain = self.getDomain(document, location.hostname);
750
- if (rootDomain === '') {
751
- return '';
752
- } else {
753
- return '.' + rootDomain;
754
- }
755
- }
756
- };
757
-
758
- // This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible.
759
- // For example subdomain.domain.co.uk would try the following combinations:
760
- // "co.uk" -> fail
761
- // "domain.co.uk" -> success, return
762
- // "subdomain.domain.co.uk" -> skipped, because already found
763
- this.getDomain = function(doc, locationHostname) {
764
- var i,
765
- testParts,
766
- mpTest = 'mptest=cookie',
767
- hostname = locationHostname.split('.');
768
- for (i = hostname.length - 1; i >= 0; i--) {
769
- testParts = hostname.slice(i).join('.');
770
- doc.cookie = mpTest + ';domain=.' + testParts + ';';
771
- if (doc.cookie.indexOf(mpTest) > -1) {
772
- doc.cookie =
773
- mpTest.split('=')[0] +
774
- '=;domain=.' +
775
- testParts +
776
- ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
777
- return testParts;
778
- }
779
- }
780
- return '';
781
- };
782
-
783
- this.saveUserCookieSyncDatesToPersistence = function(mpid, csd) {
784
- if (csd) {
785
- var persistence = self.getPersistence();
786
- if (persistence) {
787
- if (persistence[mpid]) {
788
- persistence[mpid].csd = csd;
789
- } else {
790
- persistence[mpid] = {
791
- csd: csd,
792
- };
793
- }
794
- }
795
- self.savePersistence(persistence);
796
- }
797
- };
798
-
799
- this.swapCurrentUser = function(
800
- previousMPID,
801
- currentMPID,
802
- currentSessionMPIDs
803
- ) {
804
- if (previousMPID && currentMPID && previousMPID !== currentMPID) {
805
- var persistence = self.getPersistence();
806
- if (persistence) {
807
- persistence.cu = currentMPID;
808
- persistence.gs.csm = currentSessionMPIDs;
809
- self.savePersistence(persistence);
810
- }
811
- }
812
- };
813
-
814
- // https://go.mparticle.com/work/SQDSDKS-6021
815
- this.savePersistence = function(persistence) {
816
- // Block mprtcl-v4 persistence when noFunctional is true
817
- if (mpInstance._CookieConsentManager?.getNoFunctional()) {
818
- return;
819
- }
820
-
821
- var encodedPersistence = self.encodePersistence(
822
- JSON.stringify(persistence)
823
- ),
824
- date = new Date(),
825
- key = mpInstance._Store.storageName,
826
- expires = new Date(
827
- date.getTime() +
828
- mpInstance._Store.SDKConfig.cookieExpiration *
829
- 24 *
830
- 60 *
831
- 60 *
832
- 1000
833
- ).toGMTString(),
834
- cookieDomain = self.getCookieDomain(),
835
- domain;
836
-
837
- if (cookieDomain === '') {
838
- domain = '';
839
- } else {
840
- domain = ';domain=' + cookieDomain;
841
- }
842
-
843
- if (mpInstance._Store.SDKConfig.useCookieStorage) {
844
- var encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(
845
- persistence,
846
- expires,
847
- domain,
848
- mpInstance._Store.SDKConfig.maxCookieSize
849
- );
850
- window.document.cookie =
851
- encodeURIComponent(key) +
852
- '=' +
853
- encodedCookiesWithExpirationAndPath;
854
- } else {
855
- if (mpInstance._Store.isLocalStorageAvailable) {
856
- try {
857
- localStorage.setItem(
858
- mpInstance._Store.storageName,
859
- encodedPersistence
860
- );
861
- } catch (e) {
862
- mpInstance.Logger.error(
863
- 'Error saving persistence to localStorage.'
864
- );
865
- }
866
- }
867
- }
868
- };
869
-
870
- this.getPersistence = function() {
871
- var persistence = this.useLocalStorage()
872
- ? this.getLocalStorage()
873
- : this.getCookie();
874
-
875
- return persistence;
876
- };
877
-
878
- this.getFirstSeenTime = function(mpid) {
879
- if (!mpid) {
880
- return null;
881
- }
882
- var persistence = self.getPersistence();
883
- if (persistence && persistence[mpid] && persistence[mpid].fst) {
884
- return persistence[mpid].fst;
885
- } else {
886
- return null;
887
- }
888
- };
889
-
890
- /**
891
- * set the "first seen" time for a user. the time will only be set once for a given
892
- * mpid after which subsequent calls will be ignored
893
- */
894
- this.setFirstSeenTime = function(mpid, time) {
895
- if (!mpid) {
896
- return;
897
- }
898
- // https://go.mparticle.com/work/SQDSDKS-6329
899
- if (!time) {
900
- time = new Date().getTime();
901
- }
902
- var persistence = self.getPersistence();
903
- if (persistence) {
904
- if (!persistence[mpid]) {
905
- persistence[mpid] = {};
906
- }
907
- if (!persistence[mpid].fst) {
908
- persistence[mpid].fst = time;
909
- self.savePersistence(persistence);
910
- }
911
- }
912
- };
913
-
914
- /**
915
- * returns the "last seen" time for a user. If the mpid represents the current user, the
916
- * return value will always be the current time, otherwise it will be to stored "last seen"
917
- * time
918
- */
919
- this.getLastSeenTime = function(mpid) {
920
- if (!mpid) {
921
- return null;
922
- }
923
- if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) {
924
- //if the mpid is the current user, its last seen time is the current time
925
- return new Date().getTime();
926
- } else {
927
- var persistence = self.getPersistence();
928
- if (persistence && persistence[mpid] && persistence[mpid].lst) {
929
- return persistence[mpid].lst;
930
- }
931
- return null;
932
- }
933
- };
934
-
935
- this.setLastSeenTime = function(mpid, time) {
936
- if (!mpid) {
937
- return;
938
- }
939
- // https://go.mparticle.com/work/SQDSDKS-6329
940
- if (!time) {
941
- time = new Date().getTime();
942
- }
943
- var persistence = self.getPersistence();
944
- if (persistence && persistence[mpid]) {
945
- persistence[mpid].lst = time;
946
- self.savePersistence(persistence);
947
- }
948
- };
949
-
950
- this.getDeviceId = function() {
951
- return mpInstance._Store.deviceId;
952
- };
953
-
954
- this.setDeviceId = function(guid) {
955
- mpInstance._Store.deviceId = guid;
956
- self.update();
957
- };
958
-
959
- this.resetPersistence = function() {
960
- localStorage.clear();
961
-
962
- self.expireCookies(StorageNames.cookieName);
963
- self.expireCookies(StorageNames.cookieNameV2);
964
- self.expireCookies(StorageNames.cookieNameV3);
965
- self.expireCookies(StorageNames.cookieNameV4);
966
- self.expireCookies(mpInstance._Store.storageName);
967
-
968
- if (mParticle._isTestEnv) {
969
- var testWorkspaceToken = 'abcdef';
970
- removeLocalStorage(
971
- mpInstance._Helpers.createMainStorageName(testWorkspaceToken)
972
- );
973
- self.expireCookies(
974
- mpInstance._Helpers.createMainStorageName(testWorkspaceToken)
975
- );
976
- }
977
- };
978
-
979
- // https://go.mparticle.com/work/SQDSDKS-6045
980
- // Forwarder Batching Code
981
- this.forwardingStatsBatches = {
982
- uploadsTable: {},
983
- forwardingStatsEventQueue: [],
984
- };
985
- }