-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathamplitude-client.js
1699 lines (1515 loc) · 57.9 KB
/
amplitude-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Core of SDK code
import Constants from './constants';
import cookieStorage from './cookiestorage';
import MetadataStorage from '../src/metadata-storage';
import getUtmData from './utm'; // Urchin Tracking Module
import Identify from './identify';
import localStorage from './localstorage'; // jshint ignore:line
import md5 from 'blueimp-md5';
import Request from './xhr';
import Revenue from './revenue';
import type from './type';
import UAParser from '@amplitude/ua-parser-js'; // Identifying device and browser info (maybe move to backend?)
import utils from './utils';
import UUID from './uuid';
import base64Id from './base64Id';
import { version } from '../package.json';
import DEFAULT_OPTIONS from './options';
import getHost from './get-host';
import baseCookie from './base-cookie';
let AsyncStorage;
let Platform;
let DeviceInfo;
if (BUILD_COMPAT_REACT_NATIVE) {
const reactNative = require('react-native');
AsyncStorage = require('@react-native-community/async-storage').default;
Platform = reactNative.Platform;
DeviceInfo = require('react-native-device-info');
}
/**
* AmplitudeClient SDK API - instance constructor.
* The Amplitude class handles creation of client instances, all you need to do is call amplitude.getInstance()
* @constructor AmplitudeClient
* @public
* @example var amplitudeClient = new AmplitudeClient();
*/
var AmplitudeClient = function AmplitudeClient(instanceName) {
this._instanceName = utils.isEmptyString(instanceName) ? Constants.DEFAULT_INSTANCE : instanceName.toLowerCase();
this._unsentEvents = [];
this._unsentIdentifys = [];
this._ua = new UAParser(navigator.userAgent).getResult();
this.options = {...DEFAULT_OPTIONS, trackingOptions: {...DEFAULT_OPTIONS.trackingOptions}};
this.cookieStorage = new cookieStorage().getStorage();
this._q = []; // queue for proxied functions before script load
this._sending = false;
this._updateScheduled = false;
this._onInit = [];
// event meta data
this._eventId = 0;
this._identifyId = 0;
this._lastEventTime = null;
this._newSession = false;
// sequence used for by frontend for prioritizing event send retries
this._sequenceNumber = 0;
this._sessionId = null;
this._isInitialized = false;
this._userAgent = (navigator && navigator.userAgent) || null;
};
AmplitudeClient.prototype.Identify = Identify;
AmplitudeClient.prototype.Revenue = Revenue;
/**
* Initializes the Amplitude Javascript SDK with your apiKey and any optional configurations.
* This is required before any other methods can be called.
* @public
* @param {string} apiKey - The API key for your app.
* @param {string} opt_userId - (optional) An identifier for this user.
* @param {object} opt_config - (optional) Configuration options.
* See [options.js](https://github.com/amplitude/Amplitude-JavaScript/blob/master/src/options.js#L14) for list of options and default values.
* @param {function} opt_callback - (optional) Provide a callback function to run after initialization is complete.
* @example amplitudeClient.init('API_KEY', 'USER_ID', {includeReferrer: true, includeUtm: true}, function() { alert('init complete'); });
*/
AmplitudeClient.prototype.init = function init(apiKey, opt_userId, opt_config, opt_callback) {
if (type(apiKey) !== 'string' || utils.isEmptyString(apiKey)) {
utils.log.error('Invalid apiKey. Please re-initialize with a valid apiKey');
return;
}
try {
_parseConfig(this.options, opt_config);
if (this.options.cookieName !== DEFAULT_OPTIONS.cookieName) {
utils.log.warn('The cookieName option is deprecated. We will be ignoring it for newer cookies');
}
this.options.apiKey = apiKey;
this._storageSuffix = '_' + apiKey + (this._instanceName === Constants.DEFAULT_INSTANCE ? '' : '_' + this._instanceName);
this._storageSuffixV5 = apiKey.slice(0,6);
this._oldCookiename = this.options.cookieName + this._storageSuffix;
this._unsentKey = this.options.unsentKey + this._storageSuffix;
this._unsentIdentifyKey = this.options.unsentIdentifyKey + this._storageSuffix;
this._cookieName = Constants.COOKIE_PREFIX + '_' + this._storageSuffixV5;
this.cookieStorage.options({
expirationDays: this.options.cookieExpiration,
domain: this.options.domain,
secure: this.options.secureCookie,
sameSite: this.options.sameSiteCookie
});
this._metadataStorage = new MetadataStorage({
storageKey: this._cookieName,
disableCookies: this.options.disableCookies,
expirationDays: this.options.cookieExpiration,
domain: this.options.domain,
secure: this.options.secureCookie,
sameSite: this.options.sameSiteCookie
});
const hasOldCookie = !!this.cookieStorage.get(this._oldCookiename);
const hasNewCookie = !!this._metadataStorage.load();
this._useOldCookie = (!hasNewCookie && hasOldCookie) && !this.options.cookieForceUpgrade;
const hasCookie = hasNewCookie || hasOldCookie;
this.options.domain = this.cookieStorage.options().domain;
if (this.options.deferInitialization && !hasCookie) {
this._deferInitialization(apiKey, opt_userId, opt_config, opt_callback);
return;
}
if (type(this.options.logLevel) === 'string') {
utils.setLogLevel(this.options.logLevel);
}
var trackingOptions = _generateApiPropertiesTrackingConfig(this);
this._apiPropertiesTrackingOptions = Object.keys(trackingOptions).length > 0 ? {tracking_options: trackingOptions} : {};
if (this.options.cookieForceUpgrade && hasOldCookie) {
if (!hasNewCookie) {
_upgradeCookieData(this);
}
this.cookieStorage.remove(this._oldCookiename);
}
_loadCookieData(this);
this._pendingReadStorage = true;
const initFromStorage = (storedDeviceId) => {
this.options.deviceId = this._getInitialDeviceId(
opt_config && opt_config.deviceId, storedDeviceId
);
this.options.userId =
(type(opt_userId) === 'string' && !utils.isEmptyString(opt_userId) && opt_userId) ||
(type(opt_userId) === 'number' && opt_userId.toString()) ||
this.options.userId || null;
var now = new Date().getTime();
if (!this._sessionId || !this._lastEventTime || now - this._lastEventTime > this.options.sessionTimeout) {
if (this.options.unsetParamsReferrerOnNewSession) {
this._unsetUTMParams();
}
this._newSession = true;
this._sessionId = now;
// only capture UTM params and referrer if new session
if (this.options.saveParamsReferrerOncePerSession) {
this._trackParamsAndReferrer();
}
}
if (!this.options.saveParamsReferrerOncePerSession) {
this._trackParamsAndReferrer();
}
// load unsent events and identifies before any attempt to log new ones
if (this.options.saveEvents) {
_validateUnsentEventQueue(this._unsentEvents);
_validateUnsentEventQueue(this._unsentIdentifys);
}
this._lastEventTime = now;
_saveCookieData(this);
this._pendingReadStorage = false;
this._sendEventsIfReady(); // try sending unsent events
for (let i = 0; i < this._onInit.length; i++) {
this._onInit[i](this);
}
this._onInit = [];
this._isInitialized = true;
};
if (AsyncStorage) {
this._migrateUnsentEvents(() => {
Promise.all([
AsyncStorage.getItem(this._storageSuffix),
AsyncStorage.getItem(this.options.unsentKey + this._storageSuffix),
AsyncStorage.getItem(this.options.unsentIdentifyKey + this._storageSuffix),
]).then((values) => {
if (values[0]) {
const cookieData = JSON.parse(values[0]);
if (cookieData) {
_loadCookieDataProps(this, cookieData);
}
}
if (this.options.saveEvents) {
this._unsentEvents = this._parseSavedUnsentEventsString(values[1]).map(event => ({event})).concat(this._unsentEvents);
this._unsentIdentifys = this._parseSavedUnsentEventsString(values[2]).map(event => ({event})).concat(this._unsentIdentifys);
}
if (DeviceInfo) {
Promise.all([
DeviceInfo.getCarrier(),
DeviceInfo.getModel(),
DeviceInfo.getManufacturer(),
DeviceInfo.getVersion(),
DeviceInfo.getUniqueId(),
]).then(values => {
this.deviceInfo = {
carrier: values[0],
model: values[1],
manufacturer: values[2],
version: values[3]
};
initFromStorage(values[4]);
this.runQueuedFunctions();
if (type(opt_callback) === 'function') {
opt_callback(this);
}
}).catch((err) => {
this.options.onError(err);
});
} else {
initFromStorage();
this.runQueuedFunctions();
}
}).catch((err) => {
this.options.onError(err);
});
});
} else {
if (this.options.saveEvents) {
this._unsentEvents = this._loadSavedUnsentEvents(this.options.unsentKey).map(event => ({event})).concat(this._unsentEvents);
this._unsentIdentifys = this._loadSavedUnsentEvents(this.options.unsentIdentifyKey).map(event => ({event})).concat(this._unsentIdentifys);
}
initFromStorage();
this.runQueuedFunctions();
if (type(opt_callback) === 'function') {
opt_callback(this);
}
}
} catch (err) {
utils.log.error(err);
this.options.onError(err);
}
};
AmplitudeClient.prototype.deleteLowerLevelDomainCookies = function () {
const host = getHost();
const cookieHost =
(this.options.domain && this.options.domain[0] === '.') ?
this.options.domain.slice(1) : this.options.domain;
if (!cookieHost) {
return;
}
if (host !== cookieHost) {
if (new RegExp(cookieHost + '$').test(host)) {
const hostParts = host.split('.');
const cookieHostParts = cookieHost.split('.');
for (let i = hostParts.length; i > cookieHostParts.length; --i) {
const deleteDomain = hostParts.slice(hostParts.length - i).join('.');
baseCookie.set(this._cookieName, null, {domain: '.' + deleteDomain});
}
baseCookie.set(this._cookieName, null, {});
}
}
};
AmplitudeClient.prototype._getInitialDeviceId = function (configDeviceId, storedDeviceId) {
if (configDeviceId) {
return configDeviceId;
}
if (this.options.deviceIdFromUrlParam) {
return this._getDeviceIdFromUrlParam(this._getUrlParams());
}
if (this.options.deviceId) {
return this.options.deviceId;
}
if (storedDeviceId) {
return storedDeviceId;
}
return base64Id();
};
// validate properties for unsent events
const _validateUnsentEventQueue = (queue) => {
for (let i = 0; i < queue.length; i++) {
const userProperties = queue[i].event.user_properties;
const eventProperties = queue[i].event.event_properties;
const groups = queue[i].event.groups;
queue[i].event.user_properties = utils.validateProperties(userProperties);
queue[i].event.event_properties = utils.validateProperties(eventProperties);
queue[i].event.groups = utils.validateGroups(groups);
}
};
/**
* @private
*/
AmplitudeClient.prototype._migrateUnsentEvents = function _migrateUnsentEvents(cb) {
Promise.all([
AsyncStorage.getItem(this.options.unsentKey),
AsyncStorage.getItem(this.options.unsentIdentifyKey),
]).then((values) => {
if (this.options.saveEvents) {
var unsentEventsString = values[0];
var unsentIdentifyKey = values[1];
var itemsToSet = [];
var itemsToRemove = [];
if (!!unsentEventsString) {
itemsToSet.push(AsyncStorage.setItem(this.options.unsentKey + this._storageSuffix, JSON.stringify(unsentEventsString)));
itemsToRemove.push(AsyncStorage.removeItem(this.options.unsentKey));
}
if (!!unsentIdentifyKey) {
itemsToSet.push(AsyncStorage.setItem(this.options.unsentIdentifyKey + this._storageSuffix, JSON.stringify(unsentIdentifyKey)));
itemsToRemove.push(AsyncStorage.removeItem(this.options.unsentIdentifyKey));
}
if (itemsToSet.length > 0) {
Promise.all(itemsToSet).then(() => {
Promise.all(itemsToRemove);
}).catch((err) => {
this.options.onError(err);
});
}
}
})
.then(cb)
.catch((err) => {
this.options.onError(err);
});
};
/**
* @private
*/
AmplitudeClient.prototype._trackParamsAndReferrer = function _trackParamsAndReferrer() {
let utmProperties;
let referrerProperties;
let gclidProperties;
if (this.options.includeUtm) {
utmProperties = this._initUtmData();
}
if (this.options.includeReferrer) {
referrerProperties = this._saveReferrer(this._getReferrer());
}
if (this.options.includeGclid) {
gclidProperties = this._saveGclid(this._getUrlParams());
}
if (this.options.logAttributionCapturedEvent) {
const attributionProperties = {
...utmProperties,
...referrerProperties,
...gclidProperties,
};
if (Object.keys(attributionProperties).length > 0) {
this.logEvent(Constants.ATTRIBUTION_EVENT, attributionProperties);
}
}
};
/**
* Parse and validate user specified config values and overwrite existing option value
* DEFAULT_OPTIONS provides list of all config keys that are modifiable, as well as expected types for values
* @private
*/
var _parseConfig = function _parseConfig(options, config) {
if (type(config) !== 'object') {
return;
}
// validates config value is defined, is the correct type, and some additional value sanity checks
var parseValidateAndLoad = function parseValidateAndLoad(key) {
if (!options.hasOwnProperty(key)) {
return; // skip bogus config values
}
var inputValue = config[key];
var expectedType = type(options[key]);
if (!utils.validateInput(inputValue, key + ' option', expectedType)) {
return;
}
if (expectedType === 'boolean') {
options[key] = !!inputValue;
} else if ((expectedType === 'string' && !utils.isEmptyString(inputValue)) ||
(expectedType === 'number' && inputValue > 0)) {
options[key] = inputValue;
} else if (expectedType === 'object') {
_parseConfig(options[key], inputValue);
}
};
for (var key in config) {
if (config.hasOwnProperty(key)) {
parseValidateAndLoad(key);
}
}
};
/**
* Run functions queued up by proxy loading snippet
* @private
*/
AmplitudeClient.prototype.runQueuedFunctions = function () {
const queue = this._q;
this._q = [];
for (var i = 0; i < queue.length; i++) {
var fn = this[queue[i][0]];
if (type(fn) === 'function') {
fn.apply(this, queue[i].slice(1));
}
}
};
/**
* Check that the apiKey is set before calling a function. Logs a warning message if not set.
* @private
*/
AmplitudeClient.prototype._apiKeySet = function _apiKeySet(methodName) {
if (utils.isEmptyString(this.options.apiKey)) {
utils.log.error('Invalid apiKey. Please set a valid apiKey with init() before calling ' + methodName);
return false;
}
return true;
};
/**
* Load saved events from localStorage. JSON deserializes event array. Handles case where string is corrupted.
* @private
*/
AmplitudeClient.prototype._loadSavedUnsentEvents = function _loadSavedUnsentEvents(unsentKey) {
var savedUnsentEventsString = this._getFromStorage(localStorage, unsentKey);
var unsentEvents = this._parseSavedUnsentEventsString(savedUnsentEventsString, unsentKey);
this._setInStorage(localStorage, unsentKey, JSON.stringify(unsentEvents));
return unsentEvents;
};
/**
* Load saved events from localStorage. JSON deserializes event array. Handles case where string is corrupted.
* @private
*/
AmplitudeClient.prototype._parseSavedUnsentEventsString = function _parseSavedUnsentEventsString(savedUnsentEventsString, unsentKey) {
if (utils.isEmptyString(savedUnsentEventsString)) {
return []; // new app, does not have any saved events
}
if (type(savedUnsentEventsString) === 'string') {
try {
var events = JSON.parse(savedUnsentEventsString);
if (type(events) === 'array') { // handle case where JSON dumping of unsent events is corrupted
return events;
}
} catch (e) {}
}
utils.log.error('Unable to load ' + unsentKey + ' events. Restart with a new empty queue.');
return [];
};
/**
* Returns true if a new session was created during initialization, otherwise false.
* @public
* @return {boolean} Whether a new session was created during initialization.
*/
AmplitudeClient.prototype.isNewSession = function isNewSession() {
return this._newSession;
};
/**
* Store callbacks to call after init
* @private
*/
AmplitudeClient.prototype.onInit = function (callback) {
if (this._isInitialized) {
callback(this);
} else {
this._onInit.push(callback);
}
};
/**
* Returns the id of the current session.
* @public
* @return {number} Id of the current session.
*/
AmplitudeClient.prototype.getSessionId = function getSessionId() {
return this._sessionId;
};
/**
* Increments the eventId and returns it.
* @private
*/
AmplitudeClient.prototype.nextEventId = function nextEventId() {
this._eventId++;
return this._eventId;
};
/**
* Increments the identifyId and returns it.
* @private
*/
AmplitudeClient.prototype.nextIdentifyId = function nextIdentifyId() {
this._identifyId++;
return this._identifyId;
};
/**
* Increments the sequenceNumber and returns it.
* @private
*/
AmplitudeClient.prototype.nextSequenceNumber = function nextSequenceNumber() {
this._sequenceNumber++;
return this._sequenceNumber;
};
/**
* Returns the total count of unsent events and identifys
* @private
*/
AmplitudeClient.prototype._unsentCount = function _unsentCount() {
return this._unsentEvents.length + this._unsentIdentifys.length;
};
/**
* Send events if ready. Returns true if events are sent.
* @private
*/
AmplitudeClient.prototype._sendEventsIfReady = function _sendEventsIfReady() {
if (this._unsentCount() === 0) {
return false;
}
// if batching disabled, send any unsent events immediately
if (!this.options.batchEvents) {
this.sendEvents();
return true;
}
// if batching enabled, check if min threshold met for batch size
if (this._unsentCount() >= this.options.eventUploadThreshold) {
this.sendEvents();
return true;
}
// otherwise schedule an upload after 30s
if (!this._updateScheduled) { // make sure we only schedule 1 upload
this._updateScheduled = true;
setTimeout(function() {
this._updateScheduled = false;
this.sendEvents();
}.bind(this), this.options.eventUploadPeriodMillis
);
}
return false; // an upload was scheduled, no events were uploaded
};
/**
* Helper function to fetch values from storage
* Storage argument allows for localStoraoge and sessionStoraoge
* @private
*/
AmplitudeClient.prototype._getFromStorage = function _getFromStorage(storage, key) {
return storage.getItem(key + this._storageSuffix);
};
/**
* Helper function to set values in storage
* Storage argument allows for localStoraoge and sessionStoraoge
* @private
*/
AmplitudeClient.prototype._setInStorage = function _setInStorage(storage, key, value) {
storage.setItem(key + this._storageSuffix, value);
};
/**
* Fetches deviceId, userId, event meta data from amplitude cookie
* @private
*/
var _loadCookieData = function _loadCookieData(scope) {
if (!scope._useOldCookie) {
const props = scope._metadataStorage.load();
if (type(props) === 'object') {
_loadCookieDataProps(scope, props);
}
return;
}
var cookieData = scope.cookieStorage.get(scope._oldCookiename);
if (type(cookieData) === 'object') {
_loadCookieDataProps(scope, cookieData);
return;
}
};
const _upgradeCookieData = (scope) => {
var cookieData = scope.cookieStorage.get(scope._oldCookiename);
if (type(cookieData) === 'object') {
_loadCookieDataProps(scope, cookieData);
_saveCookieData(scope);
}
};
var _loadCookieDataProps = function _loadCookieDataProps(scope, cookieData) {
if (cookieData.deviceId) {
scope.options.deviceId = cookieData.deviceId;
}
if (cookieData.userId) {
scope.options.userId = cookieData.userId;
}
if (cookieData.optOut !== null && cookieData.optOut !== undefined) {
// Do not clobber config opt out value if cookieData has optOut as false
if (cookieData.optOut !== false) {
scope.options.optOut = cookieData.optOut;
}
}
if (cookieData.sessionId) {
scope._sessionId = parseInt(cookieData.sessionId, 10);
}
if (cookieData.lastEventTime) {
scope._lastEventTime = parseInt(cookieData.lastEventTime, 10);
}
if (cookieData.eventId) {
scope._eventId = parseInt(cookieData.eventId, 10);
}
if (cookieData.identifyId) {
scope._identifyId = parseInt(cookieData.identifyId, 10);
}
if (cookieData.sequenceNumber) {
scope._sequenceNumber = parseInt(cookieData.sequenceNumber, 10);
}
};
/**
* Saves deviceId, userId, event meta data to amplitude cookie
* @private
*/
var _saveCookieData = function _saveCookieData(scope) {
const cookieData = {
deviceId: scope.options.deviceId,
userId: scope.options.userId,
optOut: scope.options.optOut,
sessionId: scope._sessionId,
lastEventTime: scope._lastEventTime,
eventId: scope._eventId,
identifyId: scope._identifyId,
sequenceNumber: scope._sequenceNumber
};
if (AsyncStorage) {
AsyncStorage.setItem(scope._storageSuffix, JSON.stringify(cookieData));
}
if (scope._useOldCookie) {
scope.cookieStorage.set(scope.options.cookieName + scope._storageSuffix, cookieData);
} else {
scope._metadataStorage.save(cookieData);
}
};
/**
* Parse the utm properties out of cookies and query for adding to user properties.
* @private
*/
AmplitudeClient.prototype._initUtmData = function _initUtmData(queryParams, cookieParams) {
queryParams = queryParams || this._getUrlParams();
cookieParams = cookieParams || this.cookieStorage.get('__utmz');
var utmProperties = getUtmData(cookieParams, queryParams);
_sendParamsReferrerUserProperties(this, utmProperties);
return utmProperties;
};
/**
* Unset the utm params from the Amplitude instance and update the identify.
* @private
*/
AmplitudeClient.prototype._unsetUTMParams = function _unsetUTMParams() {
var identify = new Identify();
identify.unset(Constants.REFERRER);
identify.unset(Constants.UTM_SOURCE);
identify.unset(Constants.UTM_MEDIUM);
identify.unset(Constants.UTM_CAMPAIGN);
identify.unset(Constants.UTM_TERM);
identify.unset(Constants.UTM_CONTENT);
this.identify(identify);
};
/**
* The calling function should determine when it is appropriate to send these user properties. This function
* will no longer contain any session storage checking logic.
* @private
*/
var _sendParamsReferrerUserProperties = function _sendParamsReferrerUserProperties(scope, userProperties) {
if (type(userProperties) !== 'object' || Object.keys(userProperties).length === 0) {
return;
}
// setOnce the initial user properties
var identify = new Identify();
for (var key in userProperties) {
if (userProperties.hasOwnProperty(key)) {
identify.setOnce('initial_' + key, userProperties[key]);
identify.set(key, userProperties[key]);
}
}
scope.identify(identify);
};
/**
* @private
*/
AmplitudeClient.prototype._getReferrer = function _getReferrer() {
return document.referrer;
};
/**
* @private
*/
AmplitudeClient.prototype._getUrlParams = function _getUrlParams() {
return location.search;
};
/**
* Try to fetch Google Gclid from url params.
* @private
*/
AmplitudeClient.prototype._saveGclid = function _saveGclid(urlParams) {
var gclid = utils.getQueryParam('gclid', urlParams);
if (utils.isEmptyString(gclid)) {
return;
}
var gclidProperties = {'gclid': gclid};
_sendParamsReferrerUserProperties(this, gclidProperties);
return gclidProperties;
};
/**
* Try to fetch Amplitude device id from url params.
* @private
*/
AmplitudeClient.prototype._getDeviceIdFromUrlParam = function _getDeviceIdFromUrlParam(urlParams) {
return utils.getQueryParam(Constants.AMP_DEVICE_ID_PARAM, urlParams);
};
/**
* Parse the domain from referrer info
* @private
*/
AmplitudeClient.prototype._getReferringDomain = function _getReferringDomain(referrer) {
if (utils.isEmptyString(referrer)) {
return null;
}
var parts = referrer.split('/');
if (parts.length >= 3) {
return parts[2];
}
return null;
};
/**
* Fetch the referrer information, parse the domain and send.
* Since user properties are propagated on the server, only send once per session, don't need to send with every event
* @private
*/
AmplitudeClient.prototype._saveReferrer = function _saveReferrer(referrer) {
if (utils.isEmptyString(referrer)) {
return;
}
var referrerInfo = {
'referrer': referrer,
'referring_domain': this._getReferringDomain(referrer)
};
_sendParamsReferrerUserProperties(this, referrerInfo);
return referrerInfo;
};
/**
* Saves unsent events and identifies to localStorage. JSON stringifies event queues before saving.
* Note: this is called automatically every time events are logged, unless you explicitly set option saveEvents to false.
* @private
*/
AmplitudeClient.prototype.saveEvents = function saveEvents() {
try {
const serializedUnsentEvents = JSON.stringify(this._unsentEvents.map(({event}) => event));
if (AsyncStorage) {
AsyncStorage.setItem(this.options.unsentKey + this._storageSuffix, serializedUnsentEvents);
} else {
this._setInStorage(localStorage, this.options.unsentKey, serializedUnsentEvents);
}
} catch (e) {}
try {
const serializedIdentifys = JSON.stringify(this._unsentIdentifys.map(unsentIdentify => unsentIdentify.event));
if (AsyncStorage) {
AsyncStorage.setItem(this.options.unsentIdentifyKey + this._storageSuffix, serializedIdentifys);
} else {
this._setInStorage(localStorage, this.options.unsentIdentifyKey, serializedIdentifys);
}
} catch (e) {}
};
/**
* Sets a customer domain for the amplitude cookie. Useful if you want to support cross-subdomain tracking.
* @public
* @param {string} domain to set.
* @example amplitudeClient.setDomain('.amplitude.com');
*/
AmplitudeClient.prototype.setDomain = function setDomain(domain) {
if (this._shouldDeferCall()) {
return this._q.push(['setDomain'].concat(Array.prototype.slice.call(arguments, 0)));
}
if (!utils.validateInput(domain, 'domain', 'string')) {
return;
}
try {
this.cookieStorage.options({
expirationDays: this.options.cookieExpiration,
secure: this.options.secureCookie,
domain: domain,
sameSite: this.options.sameSiteCookie
});
this.options.domain = this.cookieStorage.options().domain;
_loadCookieData(this);
_saveCookieData(this);
} catch (e) {
utils.log.error(e);
}
};
/**
* Sets an identifier for the current user.
* @public
* @param {string} userId - identifier to set. Can be null.
* @example amplitudeClient.setUserId('joe@gmail.com');
*/
AmplitudeClient.prototype.setUserId = function setUserId(userId) {
if (this._shouldDeferCall()) {
return this._q.push(['setUserId'].concat(Array.prototype.slice.call(arguments, 0)));
}
try {
this.options.userId = (userId !== undefined && userId !== null && ('' + userId)) || null;
_saveCookieData(this);
} catch (e) {
utils.log.error(e);
}
};
/**
* Add user to a group or groups. You need to specify a groupType and groupName(s).
*
* For example you can group people by their organization.
* In that case, groupType is "orgId" and groupName would be the actual ID(s).
* groupName can be a string or an array of strings to indicate a user in multiple gruups.
* You can also call setGroup multiple times with different groupTypes to track multiple types of groups (up to 5 per app).
*
* Note: this will also set groupType: groupName as a user property.
* See the [advanced topics article](https://developers.amplitude.com/docs/setting-user-groups) for more information.
* @public
* @param {string} groupType - the group type (ex: orgId)
* @param {string|list} groupName - the name of the group (ex: 15), or a list of names of the groups
* @example amplitudeClient.setGroup('orgId', 15); // this adds the current user to orgId 15.
*/
AmplitudeClient.prototype.setGroup = function(groupType, groupName) {
if (this._shouldDeferCall()) {
return this._q.push(['setGroup'].concat(Array.prototype.slice.call(arguments, 0)));
}
if (!this._apiKeySet('setGroup()') || !utils.validateInput(groupType, 'groupType', 'string') ||
utils.isEmptyString(groupType)) {
return;
}
var groups = {};
groups[groupType] = groupName;
var identify = new Identify().set(groupType, groupName);
this._logEvent(Constants.IDENTIFY_EVENT, null, null, identify.userPropertiesOperations, groups, null, null, null);
};
/**
* Sets whether to opt current user out of tracking.
* @public
* @param {boolean} enable - if true then no events will be logged or sent.
* @example: amplitude.setOptOut(true);
*/
AmplitudeClient.prototype.setOptOut = function setOptOut(enable) {
if (this._shouldDeferCall()) {
return this._q.push(['setOptOut'].concat(Array.prototype.slice.call(arguments, 0)));
}
if (!utils.validateInput(enable, 'enable', 'boolean')) {
return;
}
try {
this.options.optOut = enable;
_saveCookieData(this);
} catch (e) {
utils.log.error(e);
}
};
AmplitudeClient.prototype.setSessionId = function setSessionId(sessionId) {
if (!utils.validateInput(sessionId, 'sessionId', 'number')) {
return;
}
try {
this._sessionId = sessionId;
_saveCookieData(this);
} catch (e) {
utils.log.error(e);
}
};
AmplitudeClient.prototype.resetSessionId = function resetSessionId() {
this.setSessionId(new Date().getTime());
};
/**
* Regenerates a new random deviceId for current user. Note: this is not recommended unless you know what you
* are doing. This can be used in conjunction with `setUserId(null)` to anonymize users after they log out.
* With a null userId and a completely new deviceId, the current user would appear as a brand new user in dashboard.
* This uses src/uuid.js to regenerate the deviceId.
* @public
*/
AmplitudeClient.prototype.regenerateDeviceId = function regenerateDeviceId() {
if (this._shouldDeferCall()) {
return this._q.push(['regenerateDeviceId'].concat(Array.prototype.slice.call(arguments, 0)));
}
this.setDeviceId(base64Id());
};
/**
* Sets a custom deviceId for current user. Note: this is not recommended unless you know what you are doing
* (like if you have your own system for managing deviceIds). Make sure the deviceId you set is sufficiently unique
* (we recommend something like a UUID - see src/uuid.js for an example of how to generate) to prevent conflicts with other devices in our system.
* @public
* @param {string} deviceId - custom deviceId for current user.
* @example amplitudeClient.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0');
*/
AmplitudeClient.prototype.setDeviceId = function setDeviceId(deviceId) {
if (this._shouldDeferCall()) {
return this._q.push(['setDeviceId'].concat(Array.prototype.slice.call(arguments, 0)));
}
if (!utils.validateInput(deviceId, 'deviceId', 'string')) {
return;
}
try {
if (!utils.isEmptyString(deviceId)) {
this.options.deviceId = ('' + deviceId);
_saveCookieData(this);
}
} catch (e) {
utils.log.error(e);
}
};
/**
* Sets user properties for the current user.
* @public
* @param {object} - object with string keys and values for the user properties to set.
* @param {boolean} - DEPRECATED opt_replace: in earlier versions of the JS SDK the user properties object was kept in
* memory and replace = true would replace the object in memory. Now the properties are no longer stored in memory, so replace is deprecated.
* @example amplitudeClient.setUserProperties({'gender': 'female', 'sign_up_complete': true})
*/
AmplitudeClient.prototype.setUserProperties = function setUserProperties(userProperties) {
if (this._shouldDeferCall()) {
return this._q.push(['setUserProperties'].concat(Array.prototype.slice.call(arguments, 0)));
}
if (!this._apiKeySet('setUserProperties()') || !utils.validateInput(userProperties, 'userProperties', 'object')) {