forked from amplitude/Amplitude-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamplitude.js
4952 lines (4265 loc) · 173 KB
/
amplitude.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
(function umd(require){
if ('object' == typeof exports) {
module.exports = require('1');
} else if ('function' == typeof define && define.amd) {
define(function(){ return require('1'); });
} else {
this['amplitude'] = require('1');
}
})((function outer(modules, cache, entries){
/**
* Global
*/
var global = (function(){ return this; })();
/**
* Require `name`.
*
* @param {String} name
* @param {Boolean} jumped
* @api public
*/
function require(name, jumped){
if (cache[name]) return cache[name].exports;
if (modules[name]) return call(name, require);
throw new Error('cannot find module "' + name + '"');
}
/**
* Call module `id` and cache it.
*
* @param {Number} id
* @param {Function} require
* @return {Function}
* @api private
*/
function call(id, require){
var m = cache[id] = { exports: {} };
var mod = modules[id];
var name = mod[2];
var fn = mod[0];
fn.call(m.exports, function(req){
var dep = modules[id][1][req];
return require(dep ? dep : req);
}, m, m.exports, outer, modules, cache, entries);
// expose as `name`.
if (name) cache[name] = cache[id];
return cache[id].exports;
}
/**
* Require all entries exposing them on global if needed.
*/
for (var id in entries) {
if (entries[id]) {
global[entries[id]] = require(id);
} else {
require(id);
}
}
/**
* Duo flag.
*/
require.duo = true;
/**
* Expose cache.
*/
require.cache = cache;
/**
* Expose modules
*/
require.modules = modules;
/**
* Return newest require.
*/
return require;
})({
1: [function(require, module, exports) {
/* jshint expr:true */
var Amplitude = require('./amplitude');
var old = window.amplitude || {};
var newInstance = new Amplitude();
newInstance._q = old._q || [];
for (var instance in old._iq) { // migrate each instance's queue
if (old._iq.hasOwnProperty(instance)) {
newInstance.getInstance(instance)._q = old._iq[instance]._q || [];
}
}
// export the instance
module.exports = newInstance;
}, {"./amplitude":2}],
2: [function(require, module, exports) {
var AmplitudeClient = require('./amplitude-client');
var Constants = require('./constants');
var Identify = require('./identify');
var object = require('object');
var Revenue = require('./revenue');
var type = require('./type');
var utils = require('./utils');
var version = require('./version');
var DEFAULT_OPTIONS = require('./options');
/**
* Amplitude SDK API - instance manager.
* Function calls directly on amplitude have been deprecated. Please call methods on the default shared instance: amplitude.getInstance() instead.
* See [Readme]{@link https://github.com/amplitude/Amplitude-Javascript#300-update-and-logging-events-to-multiple-amplitude-apps} for more information about this change.
* @constructor Amplitude
* @public
* @example var amplitude = new Amplitude();
*/
var Amplitude = function Amplitude() {
this.options = object.merge({}, DEFAULT_OPTIONS);
this._q = [];
this._instances = {}; // mapping of instance names to instances
};
Amplitude.prototype.Identify = Identify;
Amplitude.prototype.Revenue = Revenue;
Amplitude.prototype.getInstance = function getInstance(instance) {
instance = utils.isEmptyString(instance) ? Constants.DEFAULT_INSTANCE : instance.toLowerCase();
var client = this._instances[instance];
if (client === undefined) {
client = new AmplitudeClient(instance);
this._instances[instance] = client;
}
return client;
};
/**
* 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 [Readme]{@link https://github.com/amplitude/Amplitude-Javascript#configuration-options} for list of options and default values.
* @param {function} opt_callback - (optional) Provide a callback function to run after initialization is complete.
* @deprecated Please use amplitude.getInstance().init(apiKey, opt_userId, opt_config, opt_callback);
* @example amplitude.init('API_KEY', 'USER_ID', {includeReferrer: true, includeUtm: true}, function() { alert('init complete'); });
*/
Amplitude.prototype.init = function init(apiKey, opt_userId, opt_config, opt_callback) {
this.getInstance().init(apiKey, opt_userId, opt_config, function(instance) {
// make options such as deviceId available for callback functions
this.options = instance.options;
if (type(opt_callback) === 'function') {
opt_callback(instance);
}
}.bind(this));
};
/**
* Run functions queued up by proxy loading snippet
* @private
*/
Amplitude.prototype.runQueuedFunctions = function () {
// run queued up old versions of functions
for (var i = 0; i < this._q.length; i++) {
var fn = this[this._q[i][0]];
if (type(fn) === 'function') {
fn.apply(this, this._q[i].slice(1));
}
}
this._q = []; // clear function queue after running
// run queued up functions on instances
for (var instance in this._instances) {
if (this._instances.hasOwnProperty(instance)) {
this._instances[instance].runQueuedFunctions();
}
}
};
/**
* Returns true if a new session was created during initialization, otherwise false.
* @public
* @return {boolean} Whether a new session was created during initialization.
* @deprecated Please use amplitude.getInstance().isNewSession();
*/
Amplitude.prototype.isNewSession = function isNewSession() {
return this.getInstance().isNewSession();
};
/**
* Returns the id of the current session.
* @public
* @return {number} Id of the current session.
* @deprecated Please use amplitude.getInstance().getSessionId();
*/
Amplitude.prototype.getSessionId = function getSessionId() {
return this.getInstance().getSessionId();
};
/**
* Increments the eventId and returns it.
* @private
*/
Amplitude.prototype.nextEventId = function nextEventId() {
return this.getInstance().nextEventId();
};
/**
* Increments the identifyId and returns it.
* @private
*/
Amplitude.prototype.nextIdentifyId = function nextIdentifyId() {
return this.getInstance().nextIdentifyId();
};
/**
* Increments the sequenceNumber and returns it.
* @private
*/
Amplitude.prototype.nextSequenceNumber = function nextSequenceNumber() {
return this.getInstance().nextSequenceNumber();
};
/**
* 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
*/
Amplitude.prototype.saveEvents = function saveEvents() {
this.getInstance().saveEvents();
};
/**
* Sets a customer domain for the amplitude cookie. Useful if you want to support cross-subdomain tracking.
* @public
* @param {string} domain to set.
* @deprecated Please use amplitude.getInstance().setDomain(domain);
* @example amplitude.setDomain('.amplitude.com');
*/
Amplitude.prototype.setDomain = function setDomain(domain) {
this.getInstance().setDomain(domain);
};
/**
* Sets an identifier for the current user.
* @public
* @param {string} userId - identifier to set. Can be null.
* @deprecated Please use amplitude.getInstance().setUserId(userId);
* @example amplitude.setUserId('[email protected]');
*/
Amplitude.prototype.setUserId = function setUserId(userId) {
this.getInstance().setUserId(userId);
};
/**
* 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 [SDK Readme]{@link https://github.com/amplitude/Amplitude-Javascript#setting-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
* @deprecated Please use amplitude.getInstance().setGroup(groupType, groupName);
* @example amplitude.setGroup('orgId', 15); // this adds the current user to orgId 15.
*/
Amplitude.prototype.setGroup = function(groupType, groupName) {
this.getInstance().setGroup(groupType, groupName);
};
/**
* Sets whether to opt current user out of tracking.
* @public
* @param {boolean} enable - if true then no events will be logged or sent.
* @deprecated Please use amplitude.getInstance().setOptOut(enable);
* @example: amplitude.setOptOut(true);
*/
Amplitude.prototype.setOptOut = function setOptOut(enable) {
this.getInstance().setOptOut(enable);
};
/**
* 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
* @deprecated Please use amplitude.getInstance().regenerateDeviceId();
*/
Amplitude.prototype.regenerateDeviceId = function regenerateDeviceId() {
this.getInstance().regenerateDeviceId();
};
/**
* 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.
* @deprecated Please use amplitude.getInstance().setDeviceId(deviceId);
* @example amplitude.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0');
*/
Amplitude.prototype.setDeviceId = function setDeviceId(deviceId) {
this.getInstance().setDeviceId(deviceId);
};
/**
* 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.
* @deprecated Please use amplitude.getInstance.setUserProperties(userProperties);
* @example amplitude.setUserProperties({'gender': 'female', 'sign_up_complete': true})
*/
Amplitude.prototype.setUserProperties = function setUserProperties(userProperties) {
this.getInstance().setUserProperties(userProperties);
};
/**
* Clear all of the user properties for the current user. Note: clearing user properties is irreversible!
* @public
* @deprecated Please use amplitude.getInstance().clearUserProperties();
* @example amplitude.clearUserProperties();
*/
Amplitude.prototype.clearUserProperties = function clearUserProperties(){
this.getInstance().clearUserProperties();
};
/**
* Send an identify call containing user property operations to Amplitude servers.
* See [Readme]{@link https://github.com/amplitude/Amplitude-Javascript#user-properties-and-user-property-operations}
* for more information on the Identify API and user property operations.
* @param {Identify} identify_obj - the Identify object containing the user property operations to send.
* @param {Amplitude~eventCallback} opt_callback - (optional) callback function to run when the identify event has been sent.
* Note: the server response code and response body from the identify event upload are passed to the callback function.
* @deprecated Please use amplitude.getInstance().identify(identify);
* @example
* var identify = new amplitude.Identify().set('colors', ['rose', 'gold']).add('karma', 1).setOnce('sign_up_date', '2016-03-31');
* amplitude.identify(identify);
*/
Amplitude.prototype.identify = function(identify_obj, opt_callback) {
this.getInstance().identify(identify_obj, opt_callback);
};
/**
* Set a versionName for your application.
* @public
* @param {string} versionName - The version to set for your application.
* @deprecated Please use amplitude.getInstance().setVersionName(versionName);
* @example amplitude.setVersionName('1.12.3');
*/
Amplitude.prototype.setVersionName = function setVersionName(versionName) {
this.getInstance().setVersionName(versionName);
};
/**
* This is the callback for logEvent and identify calls. It gets called after the event/identify is uploaded,
* and the server response code and response body from the upload request are passed to the callback function.
* @callback Amplitude~eventCallback
* @param {number} responseCode - Server response code for the event / identify upload request.
* @param {string} responseBody - Server response body for the event / identify upload request.
*/
/**
* Log an event with eventType and eventProperties
* @public
* @param {string} eventType - name of event
* @param {object} eventProperties - (optional) an object with string keys and values for the event properties.
* @param {Amplitude~eventCallback} opt_callback - (optional) a callback function to run after the event is logged.
* Note: the server response code and response body from the event upload are passed to the callback function.
* @deprecated Please use amplitude.getInstance().logEvent(eventType, eventProperties, opt_callback);
* @example amplitude.logEvent('Clicked Homepage Button', {'finished_flow': false, 'clicks': 15});
*/
Amplitude.prototype.logEvent = function logEvent(eventType, eventProperties, opt_callback) {
return this.getInstance().logEvent(eventType, eventProperties, opt_callback);
};
/**
* Log an event with eventType, eventProperties, and groups. Use this to set event-level groups.
* Note: the group(s) set only apply for the specific event type being logged and does not persist on the user
* (unless you explicitly set it with setGroup).
* See the [SDK Readme]{@link https://github.com/amplitude/Amplitude-Javascript#setting-groups} for more information
* about groups and Count by Distinct on the Amplitude platform.
* @public
* @param {string} eventType - name of event
* @param {object} eventProperties - (optional) an object with string keys and values for the event properties.
* @param {object} groups - (optional) an object with string groupType: groupName values for the event being logged.
* groupName can be a string or an array of strings.
* @param {Amplitude~eventCallback} opt_callback - (optional) a callback function to run after the event is logged.
* Note: the server response code and response body from the event upload are passed to the callback function.
* Deprecated Please use amplitude.getInstance().logEventWithGroups(eventType, eventProperties, groups, opt_callback);
* @example amplitude.logEventWithGroups('Clicked Button', null, {'orgId': 24});
*/
Amplitude.prototype.logEventWithGroups = function(eventType, eventProperties, groups, opt_callback) {
return this.getInstance().logEventWithGroups(eventType, eventProperties, groups, opt_callback);
};
/**
* Log revenue with Revenue interface. The new revenue interface allows for more revenue fields like
* revenueType and event properties.
* See [Readme]{@link https://github.com/amplitude/Amplitude-Javascript#tracking-revenue}
* for more information on the Revenue interface and logging revenue.
* @public
* @param {Revenue} revenue_obj - the revenue object containing the revenue data being logged.
* @deprecated Please use amplitude.getInstance().logRevenueV2(revenue_obj);
* @example var revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99);
* amplitude.logRevenueV2(revenue);
*/
Amplitude.prototype.logRevenueV2 = function logRevenueV2(revenue_obj) {
return this.getInstance().logRevenueV2(revenue_obj);
};
/**
* Log revenue event with a price, quantity, and product identifier. DEPRECATED - use logRevenueV2
* @public
* @param {number} price - price of revenue event
* @param {number} quantity - (optional) quantity of products in revenue event. If no quantity specified default to 1.
* @param {string} product - (optional) product identifier
* @deprecated Please use amplitude.getInstance().logRevenueV2(revenue_obj);
* @example amplitude.logRevenue(3.99, 1, 'product_1234');
*/
Amplitude.prototype.logRevenue = function logRevenue(price, quantity, product) {
return this.getInstance().logRevenue(price, quantity, product);
};
/**
* Remove events in storage with event ids up to and including maxEventId.
* @private
*/
Amplitude.prototype.removeEvents = function removeEvents(maxEventId, maxIdentifyId) {
this.getInstance().removeEvents(maxEventId, maxIdentifyId);
};
/**
* Send unsent events. Note: this is called automatically after events are logged if option batchEvents is false.
* If batchEvents is true, then events are only sent when batch criterias are met.
* @private
* @param {Amplitude~eventCallback} callback - (optional) callback to run after events are sent.
* Note the server response code and response body are passed to the callback as input arguments.
*/
Amplitude.prototype.sendEvents = function sendEvents(callback) {
this.getInstance().sendEvents(callback);
};
/**
* Set global user properties. Note this is deprecated, and we recommend using setUserProperties
* @public
* @deprecated
*/
Amplitude.prototype.setGlobalUserProperties = function setGlobalUserProperties(userProperties) {
this.getInstance().setUserProperties(userProperties);
};
/**
* Get the current version of Amplitude's Javascript SDK.
* @public
* @returns {number} version number
* @example var amplitudeVersion = amplitude.__VERSION__;
*/
Amplitude.prototype.__VERSION__ = version;
module.exports = Amplitude;
}, {"./amplitude-client":3,"./constants":4,"./identify":5,"object":6,"./revenue":7,"./type":8,"./utils":9,"./version":10,"./options":11}],
3: [function(require, module, exports) {
var Constants = require('./constants');
var cookieStorage = require('./cookiestorage');
var getUtmData = require('./utm');
var Identify = require('./identify');
var JSON = require('json'); // jshint ignore:line
var localStorage = require('./localstorage'); // jshint ignore:line
var md5 = require('JavaScript-MD5');
var object = require('object');
var Request = require('./xhr');
var Revenue = require('./revenue');
var type = require('./type');
var UAParser = require('ua-parser-js');
var utils = require('./utils');
var UUID = require('./uuid');
var version = require('./version');
var DEFAULT_OPTIONS = require('./options');
/**
* 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._storageSuffix = this._instanceName === Constants.DEFAULT_INSTANCE ? '' : '_' + this._instanceName;
this._unsentEvents = [];
this._unsentIdentifys = [];
this._ua = new UAParser(navigator.userAgent).getResult();
this.options = object.merge({}, DEFAULT_OPTIONS);
this.cookieStorage = new cookieStorage().getStorage();
this._q = []; // queue for proxied functions before script load
this._sending = false;
this._updateScheduled = false;
// event meta data
this._eventId = 0;
this._identifyId = 0;
this._lastEventTime = null;
this._newSession = false;
this._sequenceNumber = 0;
this._sessionId = null;
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 [Readme]{@link https://github.com/amplitude/Amplitude-Javascript#configuration-options} 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('Invalid apiKey. Please re-initialize with a valid apiKey');
return;
}
try {
this.options.apiKey = apiKey;
_parseConfig(this.options, opt_config);
this.cookieStorage.options({
expirationDays: this.options.cookieExpiration,
domain: this.options.domain
});
this.options.domain = this.cookieStorage.options().domain;
if (this._instanceName === Constants.DEFAULT_INSTANCE) {
_upgradeCookeData(this);
}
_loadCookieData(this);
// load deviceId and userId from input, or try to fetch existing value from cookie
this.options.deviceId = (type(opt_config) === 'object' && type(opt_config.deviceId) === 'string' &&
!utils.isEmptyString(opt_config.deviceId) && opt_config.deviceId) || this.options.deviceId || UUID() + 'R';
this.options.userId = (type(opt_userId) === 'string' && !utils.isEmptyString(opt_userId) && opt_userId) ||
this.options.userId || null;
var now = new Date().getTime();
if (!this._sessionId || !this._lastEventTime || now - this._lastEventTime > this.options.sessionTimeout) {
this._newSession = true;
this._sessionId = now;
// only capture UTM params and referrer if new session
if (this.options.includeUtm) {
this._initUtmData();
}
if (this.options.includeReferrer) {
this._saveReferrer(this._getReferrer());
}
}
this._lastEventTime = now;
_saveCookieData(this);
if (this.options.saveEvents) {
this._unsentEvents = this._loadSavedUnsentEvents(this.options.unsentKey);
this._unsentIdentifys = this._loadSavedUnsentEvents(this.options.unsentIdentifyKey);
// validate event properties for unsent events
for (var i = 0; i < this._unsentEvents.length; i++) {
var eventProperties = this._unsentEvents[i].event_properties;
var groups = this._unsentEvents[i].groups;
this._unsentEvents[i].event_properties = utils.validateProperties(eventProperties);
this._unsentEvents[i].groups = utils.validateGroups(groups);
}
// validate user properties for unsent identifys
for (var j = 0; j < this._unsentIdentifys.length; j++) {
var userProperties = this._unsentIdentifys[j].user_properties;
var identifyGroups = this._unsentIdentifys[j].groups;
this._unsentIdentifys[j].user_properties = utils.validateProperties(userProperties);
this._unsentIdentifys[j].groups = utils.validateGroups(identifyGroups);
}
this._sendEventsIfReady(); // try sending unsent events
}
} catch (e) {
utils.log(e);
} finally {
if (type(opt_callback) === 'function') {
opt_callback(this);
}
}
};
/**
* 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 (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
return; // skip bogus config values
}
var inputValue = config[key];
var expectedType = type(DEFAULT_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;
}
};
for (var key in config) {
if (config.hasOwnProperty(key)) {
parseValidateAndLoad(key);
}
}
};
/**
* Run functions queued up by proxy loading snippet
* @private
*/
AmplitudeClient.prototype.runQueuedFunctions = function () {
for (var i = 0; i < this._q.length; i++) {
var fn = this[this._q[i][0]];
if (type(fn) === 'function') {
fn.apply(this, this._q[i].slice(1));
}
}
this._q = []; // clear function queue after running
};
/**
* 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('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);
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('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;
};
/**
* 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(callback) {
if (this._unsentCount() === 0) {
return false;
}
// if batching disabled, send any unsent events immediately
if (!this.options.batchEvents) {
this.sendEvents(callback);
return true;
}
// if batching enabled, check if min threshold met for batch size
if (this._unsentCount() >= this.options.eventUploadThreshold) {
this.sendEvents(callback);
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);
};
/**
* cookieData (deviceId, userId, optOut, sessionId, lastEventTime, eventId, identifyId, sequenceNumber)
* can be stored in many different places (localStorage, cookie, etc).
* Need to unify all sources into one place with a one-time upgrade/migration.
* @private
*/
var _upgradeCookeData = function _upgradeCookeData(scope) {
// skip if migration already happened
var cookieData = scope.cookieStorage.get(scope.options.cookieName);
if (type(cookieData) === 'object' && cookieData.deviceId && cookieData.sessionId && cookieData.lastEventTime) {
return;
}
var _getAndRemoveFromLocalStorage = function _getAndRemoveFromLocalStorage(key) {
var value = localStorage.getItem(key);
localStorage.removeItem(key);
return value;
};
// in v2.6.0, deviceId, userId, optOut was migrated to localStorage with keys + first 6 char of apiKey
var apiKeySuffix = (type(scope.options.apiKey) === 'string' && ('_' + scope.options.apiKey.slice(0, 6))) || '';
var localStorageDeviceId = _getAndRemoveFromLocalStorage(Constants.DEVICE_ID + apiKeySuffix);
var localStorageUserId = _getAndRemoveFromLocalStorage(Constants.USER_ID + apiKeySuffix);
var localStorageOptOut = _getAndRemoveFromLocalStorage(Constants.OPT_OUT + apiKeySuffix);
if (localStorageOptOut !== null && localStorageOptOut !== undefined) {
localStorageOptOut = String(localStorageOptOut) === 'true'; // convert to boolean
}
// pre-v2.7.0 event and session meta-data was stored in localStorage. move to cookie for sub-domain support
var localStorageSessionId = parseInt(_getAndRemoveFromLocalStorage(Constants.SESSION_ID));
var localStorageLastEventTime = parseInt(_getAndRemoveFromLocalStorage(Constants.LAST_EVENT_TIME));
var localStorageEventId = parseInt(_getAndRemoveFromLocalStorage(Constants.LAST_EVENT_ID));
var localStorageIdentifyId = parseInt(_getAndRemoveFromLocalStorage(Constants.LAST_IDENTIFY_ID));
var localStorageSequenceNumber = parseInt(_getAndRemoveFromLocalStorage(Constants.LAST_SEQUENCE_NUMBER));
var _getFromCookie = function _getFromCookie(key) {
return type(cookieData) === 'object' && cookieData[key];
};
scope.options.deviceId = _getFromCookie('deviceId') || localStorageDeviceId;
scope.options.userId = _getFromCookie('userId') || localStorageUserId;
scope._sessionId = _getFromCookie('sessionId') || localStorageSessionId || scope._sessionId;
scope._lastEventTime = _getFromCookie('lastEventTime') || localStorageLastEventTime || scope._lastEventTime;
scope._eventId = _getFromCookie('eventId') || localStorageEventId || scope._eventId;
scope._identifyId = _getFromCookie('identifyId') || localStorageIdentifyId || scope._identifyId;
scope._sequenceNumber = _getFromCookie('sequenceNumber') || localStorageSequenceNumber || scope._sequenceNumber;
// optOut is a little trickier since it is a boolean
scope.options.optOut = localStorageOptOut || false;
if (cookieData && cookieData.optOut !== undefined && cookieData.optOut !== null) {
scope.options.optOut = String(cookieData.optOut) === 'true';
}
_saveCookieData(scope);
};
/**
* Fetches deviceId, userId, event meta data from amplitude cookie
* @private
*/
var _loadCookieData = function _loadCookieData(scope) {
var cookieData = scope.cookieStorage.get(scope.options.cookieName + scope._storageSuffix);
if (type(cookieData) === 'object') {
if (cookieData.deviceId) {
scope.options.deviceId = cookieData.deviceId;
}
if (cookieData.userId) {
scope.options.userId = cookieData.userId;
}
if (cookieData.optOut !== null && cookieData.optOut !== undefined) {
scope.options.optOut = cookieData.optOut;
}
if (cookieData.sessionId) {
scope._sessionId = parseInt(cookieData.sessionId);
}
if (cookieData.lastEventTime) {
scope._lastEventTime = parseInt(cookieData.lastEventTime);
}
if (cookieData.eventId) {
scope._eventId = parseInt(cookieData.eventId);
}
if (cookieData.identifyId) {
scope._identifyId = parseInt(cookieData.identifyId);
}
if (cookieData.sequenceNumber) {
scope._sequenceNumber = parseInt(cookieData.sequenceNumber);
}
}
};
/**
* Saves deviceId, userId, event meta data to amplitude cookie
* @private
*/
var _saveCookieData = function _saveCookieData(scope) {
scope.cookieStorage.set(scope.options.cookieName + scope._storageSuffix, {
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
});
};
/**
* Parse the utm properties out of cookies and query for adding to user properties.
* @private
*/
AmplitudeClient.prototype._initUtmData = function _initUtmData(queryParams, cookieParams) {
queryParams = queryParams || location.search;
cookieParams = cookieParams || this.cookieStorage.get('__utmz');
var utmProperties = getUtmData(cookieParams, queryParams);
_sendUserPropertiesOncePerSession(this, Constants.UTM_PROPERTIES, utmProperties);
};
/**
* Since user properties are propagated on server, only send once per session, don't need to send with every event
* @private
*/
var _sendUserPropertiesOncePerSession = function _sendUserPropertiesOncePerSession(scope, storageKey, 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]);
}
}
// only save userProperties if not already in sessionStorage under key or if storage disabled
var hasSessionStorage = utils.sessionStorageEnabled();
if ((hasSessionStorage && !(scope._getFromStorage(sessionStorage, storageKey))) || !hasSessionStorage) {
for (var property in userProperties) {
if (userProperties.hasOwnProperty(property)) {
identify.set(property, userProperties[property]);
}
}
if (hasSessionStorage) {
scope._setInStorage(sessionStorage, storageKey, JSON.stringify(userProperties));
}
}
scope.identify(identify);
};
/**
* @private
*/
AmplitudeClient.prototype._getReferrer = function _getReferrer() {
return document.referrer;
};
/**
* 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)
};
_sendUserPropertiesOncePerSession(this, Constants.REFERRER, 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 {