-
Notifications
You must be signed in to change notification settings - Fork 147
/
countly.js
5604 lines (5373 loc) · 268 KB
/
countly.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
/** **********
* Countly Web SDK
* https://github.com/Countly/countly-sdk-web
*********** */
/**
* Countly object to manage the internal queue and send requests to Countly server. More information on {@link https://resources.count.ly/docs/countly-sdk-for-web}
* @name Countly
* @global
* @namespace Countly
* @example <caption>SDK integration</caption>
* <script type="text/javascript">
*
* //some default pre init
* var Countly = Countly || {};
* Countly.q = Countly.q || [];
*
* //provide your app key that you retrieved from Countly dashboard
* Countly.app_key = "YOUR_APP_KEY";
*
* //provide your server IP or name. Use try.count.ly for EE trial server.
* //if you use your own server, make sure you have https enabled if you use
* //https below.
* Countly.url = "https://yourdomain.com";
*
* //start pushing function calls to queue
* //track sessions automatically
* Countly.q.push(["track_sessions"]);
*
* //track sessions automatically
* Countly.q.push(["track_pageview"]);
*
* //load countly script asynchronously
* (function() {
* var cly = document.createElement("script"); cly.type = "text/javascript";
* cly.async = true;
* //enter url of script here
* cly.src = "https://cdn.jsdelivr.net/countly-sdk-web/latest/countly.min.js";
* cly.onload = function(){Countly.init()};
* var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(cly, s);
* })();
* </script>
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Countly = global.Countly || {}));
})(this, (function (exports) {
'use strict';
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
// Feature ENUMS
var featureEnums = {
SESSIONS: "sessions",
EVENTS: "events",
VIEWS: "views",
SCROLLS: "scrolls",
CLICKS: "clicks",
FORMS: "forms",
CRASHES: "crashes",
ATTRIBUTION: "attribution",
USERS: "users",
STAR_RATING: "star-rating",
LOCATION: "location",
APM: "apm",
FEEDBACK: "feedback",
REMOTE_CONFIG: "remote-config"
};
/**
* At the current moment there are following internal events and their respective required consent:
[CLY]_nps - "feedback" consent
[CLY]_survey - "feedback" consent
[CLY]_star_rating - "star_rating" consent
[CLY]_view - "views" consent
[CLY]_orientation - "users" consent
[CLY]_push_action - "push" consent
[CLY]_action - "clicks" or "scroll" consent
*/
var internalEventKeyEnums = {
NPS: "[CLY]_nps",
SURVEY: "[CLY]_survey",
STAR_RATING: "[CLY]_star_rating",
VIEW: "[CLY]_view",
ORIENTATION: "[CLY]_orientation",
ACTION: "[CLY]_action"
};
var internalEventKeyEnumsArray = Object.values(internalEventKeyEnums);
/**
*
*log level Enums:
*Error - this is a issues that needs attention right now.
*Warning - this is something that is potentially a issue. Maybe a deprecated usage of something, maybe consent is enabled but consent is not given.
*Info - All publicly exposed functions should log a call at this level to indicate that they were called. These calls should include the function name.
*Debug - this should contain logs from the internal workings of the SDK and it's important calls. This should include things like the SDK configuration options, success or fail of the current network request, "request queue is full" and the oldest request get's dropped, etc.
*Verbose - this should give a even deeper look into the SDK's inner working and should contain things that are more noisy and happen often.
*/
var logLevelEnums = {
ERROR: "[ERROR] ",
WARNING: "[WARNING] ",
INFO: "[INFO] ",
DEBUG: "[DEBUG] ",
VERBOSE: "[VERBOSE] "
};
/**
*
*device ID type:
*0 - device ID was set by the developer during init
*1 - device ID was auto generated by Countly
*2 - device ID was temporarily given by Countly
*3 - device ID was provided from location.search
*/
var DeviceIdTypeInternalEnums = {
DEVELOPER_SUPPLIED: 0,
SDK_GENERATED: 1,
TEMPORARY_ID: 2,
URL_PROVIDED: 3
};
/**
* to be used as a default value for certain configuration key values
*/
var configurationDefaultValues = {
BEAT_INTERVAL: 500,
QUEUE_SIZE: 1000,
FAIL_TIMEOUT_AMOUNT: 60,
INACTIVITY_TIME: 20,
SESSION_UPDATE: 60,
MAX_EVENT_BATCH: 100,
SESSION_COOKIE_TIMEOUT: 30,
MAX_KEY_LENGTH: 128,
MAX_VALUE_SIZE: 256,
MAX_SEGMENTATION_VALUES: 100,
MAX_BREADCRUMB_COUNT: 100,
MAX_STACKTRACE_LINES_PER_THREAD: 30,
MAX_STACKTRACE_LINE_LENGTH: 200
};
/**
* BoomerangJS and countly
*/
var CDN = {
BOOMERANG_SRC: "https://cdn.jsdelivr.net/npm/countly-sdk-web@latest/plugin/boomerang/boomerang.min.js",
CLY_BOOMERANG_SRC: "https://cdn.jsdelivr.net/npm/countly-sdk-web@latest/plugin/boomerang/countly_boomerang.js"
};
/**
* Health check counters' local storage keys
*/
var healthCheckCounterEnum = Object.freeze({
errorCount: "cly_hc_error_count",
warningCount: "cly_hc_warning_count",
statusCode: "cly_hc_status_code",
errorMessage: "cly_hc_error_message"
});
var SDK_VERSION = "24.4.1";
var SDK_NAME = "javascript_native_web";
// Using this on document.referrer would return an array with 17 elements in it. The 12th element (array[11]) would be the path we are looking for. Others would be things like password and such (use https://regex101.com/ to check more)
// an example URL:
// http://user:pass@host:8080/path/to/resource?query=value#fragment
// this url would yield the following result for matches = urlParseRE.exec(document.referrer);
//
// 0: "http://user:pass@host:8080/path/to/resource?query=value#fragment"
// 1: "http://user:pass@host:8080/path/to/resource?query=value"
// 2: "http://user:pass@host:8080/path/to/resource"
// 3: "http://user:pass@host:8080"
// 4: "http:"
// 5: "//"
// 6: "user:pass@host:8080"
// 7: "user:pass"
// 8: "user"
// 9: "pass"
// 10: "host:8080"
// 11: "host"
// 12: "8080"
// 13: "/path/to/resource"
// 14: "/path/to/"
// 15: "resource"
// 16: "?query=value"
// 17: "#fragment"
var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
var isBrowser = typeof window !== "undefined";
var Countly = globalThis.Countly || {};
/**
* Get selected values from multi select input
* @param {HTMLElement} input - select with multi true option
* @returns {String} coma concatenated values
*/
function getMultiSelectValues(input) {
var values = [];
if (typeof input.options !== "undefined") {
for (var j = 0; j < input.options.length; j++) {
if (input.options[j].selected) {
values.push(input.options[j].value);
}
}
}
return values.join(", ");
}
/**
* Return a crypto-safe random string
* @memberof Countly._internals
* @returns {string} - random string
*/
function secureRandom() {
var id = "xxxxxxxx";
id = replacePatternWithRandomValues(id, "[x]");
// timestamp in milliseconds
var timestamp = Date.now().toString();
return id + timestamp;
}
/**
* Generate random UUID value
* @memberof Countly._internals
* @returns {String} random UUID value
*/
function generateUUID() {
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
uuid = replacePatternWithRandomValues(uuid, "[xy]");
return uuid;
}
/**
* Generate random value based on pattern
*
* @param {string} str - string to replace
* @param {string} pattern - pattern to replace
* @returns {string} - replaced string
*/
function replacePatternWithRandomValues(str, pattern) {
var d = new Date().getTime();
var regex = new RegExp(pattern, "g");
return str.replace(regex, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
return (c === "x" ? r : r & 0x3 | 0x8).toString(16);
});
}
/**
* Get unix timestamp
* @memberof Countly._internals
* @returns {Number} unix timestamp
*/
function getTimestamp() {
return Math.floor(new Date().getTime() / 1000);
}
var lastMsTs = 0;
/**
* Get unique timestamp in milliseconds
* @memberof Countly._internals
* @returns {Number} milliseconds timestamp
*/
function getMsTimestamp() {
var ts = new Date().getTime();
if (lastMsTs >= ts) {
lastMsTs++;
} else {
lastMsTs = ts;
}
return lastMsTs;
}
/**
* Get config value from multiple sources
* like config object, global object or fallback value
* @param {String} key - config key
* @param {Object} ob - config object
* @param {Varies} override - fallback value
* @returns {Varies} value to be used as config
*/
function getConfig(key, ob, override) {
if (ob && Object.keys(ob).length) {
if (typeof ob[key] !== "undefined") {
return ob[key];
}
} else if (typeof Countly[key] !== "undefined") {
return Countly[key];
}
return override;
}
/**
* Dispatch errors to instances that lister to errors
* @param {Error} error - Error object
* @param {Boolean} fatality - fatal if false and nonfatal if true
* @param {Object} segments - custom crash segments
*/
function dispatchErrors(error, fatality, segments) {
// Check each instance like Countly.i[app_key_1], Countly.i[app_key_2] ...
for (var app_key in Countly.i) {
// If track_errors is enabled for that instance
if (Countly.i[app_key].tracking_crashes) {
// Trigger recordError function for that instance
Countly.i[app_key].recordError(error, fatality, segments);
}
}
}
/**
* Convert JSON object to URL encoded query parameter string
* @memberof Countly._internals
* @param {Object} params - object with query parameters
* @param {String} salt - salt to be used for checksum calculation
* @returns {String} URL encode query string
*/
function prepareParams(params, salt) {
var str = [];
for (var i in params) {
str.push(i + "=" + encodeURIComponent(params[i]));
}
var data = str.join("&");
if (salt) {
return calculateChecksum(data, salt).then(function (checksum) {
data += "&checksum256=" + checksum;
return data;
});
}
return Promise.resolve(data);
}
/**
* Removing trailing slashes
* @memberof Countly._internals
* @param {String} str - string from which to remove trailing slash
* @returns {String} modified string
*/
function stripTrailingSlash(str) {
if (typeof str === "string") {
if (str.substring(str.length - 1) === "/") {
return str.substring(0, str.length - 1);
}
}
return str;
}
/**
* Retrieve only specific properties from object
* @memberof Countly._internals
* @param {Object} orig - original object
* @param {Array} props - array with properties to get from object
* @returns {Object} new object with requested properties
*/
function createNewObjectFromProperties(orig, props) {
var ob = {};
var prop;
for (var i = 0, len = props.length; i < len; i++) {
prop = props[i];
if (typeof orig[prop] !== "undefined") {
ob[prop] = orig[prop];
}
}
return ob;
}
/**
* Add specified properties to an object from another object
* @memberof Countly._internals
* @param {Object} orig - original object
* @param {Object} transferOb - object to copy values from
* @param {Array} props - array with properties to get from object
* @returns {Object} original object with additional requested properties
*/
function addNewProperties(orig, transferOb, props) {
if (!props) {
return;
}
var prop;
for (var i = 0, len = props.length; i < len; i++) {
prop = props[i];
if (typeof transferOb[prop] !== "undefined") {
orig[prop] = transferOb[prop];
}
}
return orig;
}
/**
* Truncates an object's key/value pairs to a certain length
* @param {Object} obj - original object to be truncated
* @param {Number} keyLimit - limit for key length
* @param {Number} valueLimit - limit for value length
* @param {Number} segmentLimit - limit for segments pairs
* @param {string} errorLog - prefix for error log
* @param {function} logCall - internal logging function
* @returns {Object} - the new truncated object
*/
function truncateObject(obj, keyLimit, valueLimit, segmentLimit, errorLog, logCall) {
var ob = {};
if (obj) {
if (Object.keys(obj).length > segmentLimit) {
var resizedObj = {};
var i = 0;
for (var e in obj) {
if (i < segmentLimit) {
resizedObj[e] = obj[e];
i++;
}
}
obj = resizedObj;
}
for (var key in obj) {
var newKey = truncateSingleValue(key, keyLimit, errorLog, logCall);
var newValue = truncateSingleValue(obj[key], valueLimit, errorLog, logCall);
ob[newKey] = newValue;
}
}
return ob;
}
/**
* Truncates a single value to a certain length
* @param {string|number} str - original value to be truncated
* @param {Number} limit - limit length
* @param {string} errorLog - prefix for error log
* @param {function} logCall - internal logging function
* @returns {string|number} - the new truncated value
*/
function truncateSingleValue(str, limit, errorLog, logCall) {
var newStr = str;
if (typeof str === "number") {
str = str.toString();
}
if (typeof str === "string") {
if (str.length > limit) {
newStr = str.substring(0, limit);
logCall(logLevelEnums.DEBUG, errorLog + ", Key: [ " + str + " ] is longer than accepted length. It will be truncated.");
}
}
return newStr;
}
/**
* Calculates the checksum of the data with the given salt
* Uses SHA-256 algorithm with web crypto API
* Implementation based on https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
* TODO: Turn to async function when we drop support for older browsers
* @param {string} data - data to be used for checksum calculation (concatenated query parameters)
* @param {string} salt - salt to be used for checksum calculation
* @returns {string} checksum in hex format
*/
function calculateChecksum(data, salt) {
var msgUint8 = new TextEncoder().encode(data + salt); // encode as (utf-8) Uint8Array
return crypto.subtle.digest("SHA-256", msgUint8).then(function (hashBuffer) {
// hash the message
var hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
var hashHex = hashArray.map(function (b) {
return b.toString(16).padStart(2, "0");
}).join(""); // convert bytes to hex string
return hashHex;
});
}
/**
* Polyfill to get closest parent matching nodeName
* @param {HTMLElement} el - element from which to search
* @param {String} nodeName - tag/node name
* @returns {HTMLElement} closest parent element
*/
function get_closest_element(el, nodeName) {
nodeName = nodeName.toUpperCase();
while (el) {
if (el.nodeName.toUpperCase() === nodeName) {
return el;
}
el = el.parentElement;
}
}
/**
* Listen to specific browser event
* @memberof Countly._internals
* @param {HTMLElement} element - HTML element that should listen to event
* @param {String} type - event name or action
* @param {Function} listener - callback when event is fired
*/
function add_event_listener(element, type, listener) {
if (!isBrowser) {
return;
}
if (element === null || typeof element === "undefined") {
// element can be null so lets check it first
if (checkIfLoggingIsOn()) {
// eslint-disable-next-line no-console
console.warn("[WARNING] [Countly] add_event_listener, Can't bind [" + type + "] event to nonexisting element");
}
return;
}
if (typeof element.addEventListener !== "undefined") {
element.addEventListener(type, listener, false);
}
// for old browser use attachEvent instead
else {
element.attachEvent("on" + type, listener);
}
}
/**
* Get element that fired event
* @memberof Countly._internals
* @param {Event} event - event that was filed
* @returns {HTMLElement} HTML element that caused event to fire
*/
function get_event_target(event) {
if (!event) {
return window.event.srcElement;
}
if (typeof event.target !== "undefined") {
return event.target;
}
return event.srcElement;
}
/**
* Returns raw user agent string
* @memberof Countly._internals
* @param {string} uaOverride - a string value to pass instead of ua value
* @returns {string} currentUserAgentString - raw user agent string
*/
function currentUserAgentString(uaOverride) {
if (uaOverride) {
return uaOverride;
}
var ua_raw = navigator.userAgent;
// check if userAgentData is supported and userAgent is not available, then use it
if (!ua_raw) {
ua_raw = currentUserAgentDataString();
}
// RAW USER AGENT STRING
return ua_raw;
}
/**
* Forms user agent string from userAgentData by concatenating brand, version, mobile and platform
* @memberof Countly._internals
* @param {string} uaOverride - a string value to pass instead of ua value
* @returns {string} currentUserAgentString - user agent string from userAgentData
*/
function currentUserAgentDataString(uaOverride) {
if (uaOverride) {
return uaOverride;
}
var ua = "";
if (navigator.userAgentData) {
// turn brands array into string
ua = navigator.userAgentData.brands.map(function (e) {
return e.brand + ":" + e.version;
}).join();
// add mobile info
ua += navigator.userAgentData.mobile ? " mobi " : " ";
// add platform info
ua += navigator.userAgentData.platform;
}
return ua;
}
/**
* Returns device type information according to user agent string
* @memberof Countly._internals
* @param {string} uaOverride - a string value to pass instead of ua value
* @returns {string} userAgentDeviceDetection - current device type (desktop, tablet, phone)
*/
function userAgentDeviceDetection(uaOverride) {
var userAgent;
// TODO: refactor here
if (uaOverride) {
userAgent = uaOverride;
} else if (navigator.userAgentData && navigator.userAgentData.mobile) {
return "phone";
} else {
userAgent = currentUserAgentString();
}
// make it lowercase for regex to work properly
userAgent = userAgent.toLowerCase();
// assign the default device
var device = "desktop";
// regexps corresponding to tablets or phones that can be found in userAgent string
var tabletCheck = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/;
var phoneCheck = /(mobi|ipod|phone|blackberry|opera mini|fennec|minimo|symbian|psp|nintendo ds|archos|skyfire|puffin|blazer|bolt|gobrowser|iris|maemo|semc|teashark|uzard)/;
// check whether the regexp values corresponds to something in the user agent string
if (tabletCheck.test(userAgent)) {
device = "tablet";
} else if (phoneCheck.test(userAgent)) {
device = "phone";
}
// set the device type
return device;
}
/**
* Returns information regarding if the current user is a search bot or not
* @memberof Countly._internals
* @param {string} uaOverride - a string value to pass instead of ua value
* @returns {boolean} userAgentSearchBotDetection - if a search bot is reaching the site or not
*/
function userAgentSearchBotDetection(uaOverride) {
// search bot regexp
var searchBotRE = /(CountlySiteBot|nuhk|Googlebot|GoogleSecurityScanner|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver|bingbot|Google Web Preview|Mediapartners-Google|AdsBot-Google|Baiduspider|Ezooms|YahooSeeker|AltaVista|AVSearch|Mercator|Scooter|InfoSeek|Ultraseek|Lycos|Wget|YandexBot|Yandex|YaDirectFetcher|SiteBot|Exabot|AhrefsBot|MJ12bot|TurnitinBot|magpie-crawler|Nutch Crawler|CMS Crawler|rogerbot|Domnutch|ssearch_bot|XoviBot|netseer|digincore|fr-crawler|wesee|AliasIO|contxbot|PingdomBot|BingPreview|HeadlessChrome|Lighthouse)/;
// check override first
if (uaOverride) {
return searchBotRE.test(uaOverride);
}
// check both userAgent and userAgentData, as one of them might be containing the information we are looking for
var ua_bot = searchBotRE.test(currentUserAgentString());
var uaData_bot = searchBotRE.test(currentUserAgentDataString());
return ua_bot || uaData_bot;
}
/**
* Modify event to set standard coordinate properties if they are not available
* @memberof Countly._internals
* @param {Event} e - event object
* @returns {Event} modified event object
*/
function get_page_coord(e) {
// checking if pageY and pageX is already available
if (typeof e.pageY === "undefined" && typeof e.clientX === "number" && document.documentElement) {
// if not, then add scrolling positions
e.pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
e.pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
// return e which now contains pageX and pageY attributes
return e;
}
/**
* Get height of whole document
* @memberof Countly._internals
* @returns {Number} height in pixels
*/
function getDocHeight() {
var D = document;
return Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
}
/**
* Get width of whole document
* @memberof Countly._internals
* @returns {Number} width in pixels
*/
function getDocWidth() {
var D = document;
return Math.max(Math.max(D.body.scrollWidth, D.documentElement.scrollWidth), Math.max(D.body.offsetWidth, D.documentElement.offsetWidth), Math.max(D.body.clientWidth, D.documentElement.clientWidth));
}
/**
* Get height of viewable area
* @memberof Countly._internals
* @returns {Number} height in pixels
*/
function getViewportHeight() {
var D = document;
return Math.min(Math.min(D.body.clientHeight, D.documentElement.clientHeight), Math.min(D.body.offsetHeight, D.documentElement.offsetHeight), window.innerHeight);
}
/**
* Get device's orientation
* @returns {String} device orientation
*/
function getOrientation() {
return window.innerWidth > window.innerHeight ? "landscape" : "portrait";
}
/**
* Load external js files
* @param {String} tag - Tag/node name to load file in
* @param {String} attr - Attribute name for type
* @param {String} type - Type value
* @param {String} src - Attribute name for file path
* @param {String} data - File path
* @param {Function} callback - callback when done
*/
function loadFile(tag, attr, type, src, data, callback) {
var fileRef = document.createElement(tag);
var loaded;
fileRef.setAttribute(attr, type);
fileRef.setAttribute(src, data);
var callbackFunction = function callbackFunction() {
if (!loaded) {
callback();
}
loaded = true;
};
if (callback) {
fileRef.onreadystatechange = callbackFunction;
fileRef.onload = callbackFunction;
}
document.getElementsByTagName("head")[0].appendChild(fileRef);
}
/**
* Load external js files
* @memberof Countly._internals
* @param {String} js - path to JS file
* @param {Function} callback - callback when done
*/
function loadJS(js, callback) {
loadFile("script", "type", "text/javascript", "src", js, callback);
}
/**
* Load external css files
* @memberof Countly._internals
* @param {String} css - path to CSS file
* @param {Function} callback - callback when done
*/
function loadCSS(css, callback) {
loadFile("link", "rel", "stylesheet", "href", css, callback);
}
/**
* Show loader UI when loading external data
* @memberof Countly._internals
*/
function showLoader() {
if (!isBrowser) {
return;
}
var loader = document.getElementById("cly-loader");
if (!loader) {
var css = "#cly-loader {height: 4px; width: 100%; position: absolute; z-index: 99999; overflow: hidden; background-color: #fff; top:0px; left:0px;}" + "#cly-loader:before{display: block; position: absolute; content: ''; left: -200px; width: 200px; height: 4px; background-color: #2EB52B; animation: cly-loading 2s linear infinite;}" + "@keyframes cly-loading { from {left: -200px; width: 30%;} 50% {width: 30%;} 70% {width: 70%;} 80% { left: 50%;} 95% {left: 120%;} to {left: 100%;}}";
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
loader = document.createElement("div");
loader.setAttribute("id", "cly-loader");
document.body.onload = function () {
// check if hideLoader is on and if so return
if (Countly.showLoaderProtection) {
if (checkIfLoggingIsOn()) {
// eslint-disable-next-line no-console
console.warn("[WARNING] [Countly] showloader, Loader is already on");
}
return;
}
try {
document.body.appendChild(loader);
} catch (e) {
if (checkIfLoggingIsOn()) {
// eslint-disable-next-line no-console
console.error("[ERROR] [Countly] showLoader, Body is not loaded for loader to append: " + e);
}
}
};
}
loader.style.display = "block";
}
/**
* Checks if debug is true and console is available in Countly object
* @memberof Countly._internals
* @returns {Boolean} true if debug is true and console is available in Countly object
*/
function checkIfLoggingIsOn() {
// check if logging is enabled
if (Countly && Countly.debug && typeof console !== "undefined") {
return true;
}
return false;
}
/**
* Hide loader UI
* @memberof Countly._internals
*/
function hideLoader() {
if (!isBrowser) {
return;
}
// Inform showLoader that it should not append the loader
Countly.showLoaderProtection = true;
var loader = document.getElementById("cly-loader");
if (loader) {
loader.style.display = "none";
}
}
var CountlyClass = /*#__PURE__*/_createClass(function CountlyClass(ob) {
_classCallCheck(this, CountlyClass);
var self = this;
var global = !Countly.i;
var sessionStarted = false;
var apiPath = "/i";
var readPath = "/o/sdk";
var beatInterval = getConfig("interval", ob, configurationDefaultValues.BEAT_INTERVAL);
var queueSize = getConfig("queue_size", ob, configurationDefaultValues.QUEUE_SIZE);
var requestQueue = [];
var eventQueue = [];
var remoteConfigs = {};
var crashLogs = [];
var timedEvents = {};
var ignoreReferrers = getConfig("ignore_referrers", ob, []);
var crashSegments = null;
var autoExtend = true;
var lastBeat;
var storedDuration = 0;
var lastView = null;
var lastViewTime = 0;
var lastViewStoredDuration = 0;
var failTimeout = 0;
var failTimeoutAmount = getConfig("fail_timeout", ob, configurationDefaultValues.FAIL_TIMEOUT_AMOUNT);
var inactivityTime = getConfig("inactivity_time", ob, configurationDefaultValues.INACTIVITY_TIME);
var inactivityCounter = 0;
var sessionUpdate = getConfig("session_update", ob, configurationDefaultValues.SESSION_UPDATE);
var maxEventBatch = getConfig("max_events", ob, configurationDefaultValues.MAX_EVENT_BATCH);
var maxCrashLogs = getConfig("max_logs", ob, null);
var useSessionCookie = getConfig("use_session_cookie", ob, true);
var sessionCookieTimeout = getConfig("session_cookie_timeout", ob, configurationDefaultValues.SESSION_COOKIE_TIMEOUT);
var readyToProcess = true;
var hasPulse = false;
var offlineMode = getConfig("offline_mode", ob, false);
var lastParams = {};
var trackTime = true;
var startTime = getTimestamp();
var lsSupport = true;
var firstView = null;
var deviceIdType = DeviceIdTypeInternalEnums.SDK_GENERATED;
var isScrollRegistryOpen = false;
var scrollRegistryTopPosition = 0;
var trackingScrolls = false;
var currentViewId = null; // this is the global variable for tracking the current view's ID. Used in view tracking. Becomes previous view ID at the end.
var previousViewId = null; // this is the global variable for tracking the previous view's ID. Used in view tracking. First view has no previous view ID.
var freshUTMTags = null;
var sdkName = getConfig("sdk_name", ob, SDK_NAME);
var sdkVersion = getConfig("sdk_version", ob, SDK_VERSION);
try {
localStorage.setItem("cly_testLocal", true);
// clean up test
localStorage.removeItem("cly_testLocal");
} catch (e) {
log(logLevelEnums.ERROR, "Local storage test failed, Halting local storage support: " + e);
lsSupport = false;
}
// create object to store consents
var consents = {};
for (var it = 0; it < Countly.features.length; it++) {
consents[Countly.features[it]] = {};
}
this.initialize = function () {
this.serialize = getConfig("serialize", ob, Countly.serialize);
this.deserialize = getConfig("deserialize", ob, Countly.deserialize);
this.getViewName = getConfig("getViewName", ob, Countly.getViewName);
this.getViewUrl = getConfig("getViewUrl", ob, Countly.getViewUrl);
this.getSearchQuery = getConfig("getSearchQuery", ob, Countly.getSearchQuery);
this.DeviceIdType = Countly.DeviceIdType; // it is Countly device Id type Enums for clients to use
this.namespace = getConfig("namespace", ob, "");
this.clearStoredId = getConfig("clear_stored_id", ob, false);
this.app_key = getConfig("app_key", ob, null);
this.onload = getConfig("onload", ob, []);
this.utm = getConfig("utm", ob, {
source: true,
medium: true,
campaign: true,
term: true,
content: true
});
this.ignore_prefetch = getConfig("ignore_prefetch", ob, true);
this.rcAutoOptinAb = getConfig("rc_automatic_optin_for_ab", ob, true);
this.useExplicitRcApi = getConfig("use_explicit_rc_api", ob, false);
this.debug = getConfig("debug", ob, false);
this.test_mode = getConfig("test_mode", ob, false);
this.test_mode_eq = getConfig("test_mode_eq", ob, false);
this.metrics = getConfig("metrics", ob, {});
this.headers = getConfig("headers", ob, {});
this.url = stripTrailingSlash(getConfig("url", ob, ""));
this.app_version = getConfig("app_version", ob, "0.0");
this.country_code = getConfig("country_code", ob, null);
this.city = getConfig("city", ob, null);
this.ip_address = getConfig("ip_address", ob, null);
this.ignore_bots = getConfig("ignore_bots", ob, true);
this.force_post = getConfig("force_post", ob, false);
this.remote_config = getConfig("remote_config", ob, false);
this.ignore_visitor = getConfig("ignore_visitor", ob, false);
this.require_consent = getConfig("require_consent", ob, false);
this.track_domains = !isBrowser ? undefined : getConfig("track_domains", ob, true);
this.storage = getConfig("storage", ob, "default");
this.enableOrientationTracking = !isBrowser ? undefined : getConfig("enable_orientation_tracking", ob, true);
this.maxKeyLength = getConfig("max_key_length", ob, configurationDefaultValues.MAX_KEY_LENGTH);
this.maxValueSize = getConfig("max_value_size", ob, configurationDefaultValues.MAX_VALUE_SIZE);
this.maxSegmentationValues = getConfig("max_segmentation_values", ob, configurationDefaultValues.MAX_SEGMENTATION_VALUES);
this.maxBreadcrumbCount = getConfig("max_breadcrumb_count", ob, null);
this.maxStackTraceLinesPerThread = getConfig("max_stack_trace_lines_per_thread", ob, configurationDefaultValues.MAX_STACKTRACE_LINES_PER_THREAD);
this.maxStackTraceLineLength = getConfig("max_stack_trace_line_length", ob, configurationDefaultValues.MAX_STACKTRACE_LINE_LENGTH);
this.heatmapWhitelist = getConfig("heatmap_whitelist", ob, []);
self.salt = getConfig("salt", ob, null);
self.hcErrorCount = getValueFromStorage(healthCheckCounterEnum.errorCount) || 0;
self.hcWarningCount = getValueFromStorage(healthCheckCounterEnum.warningCount) || 0;
self.hcStatusCode = getValueFromStorage(healthCheckCounterEnum.statusCode) || -1;
self.hcErrorMessage = getValueFromStorage(healthCheckCounterEnum.errorMessage) || "";
if (maxCrashLogs && !this.maxBreadcrumbCount) {
this.maxBreadcrumbCount = maxCrashLogs;
log(logLevelEnums.WARNING, "initialize, 'maxCrashLogs' is deprecated. Use 'maxBreadcrumbCount' instead!");
} else if (!maxCrashLogs && !this.maxBreadcrumbCount) {
this.maxBreadcrumbCount = 100;
}
if (this.storage === "cookie") {
lsSupport = false;
}
if (!this.rcAutoOptinAb && !this.useExplicitRcApi) {
log(logLevelEnums.WARNING, "initialize, Auto opting is disabled, switching to explicit RC API");
this.useExplicitRcApi = true;
}
if (!Array.isArray(ignoreReferrers)) {
ignoreReferrers = [];
}
if (this.url === "") {
log(logLevelEnums.ERROR, "initialize, Please provide server URL");
this.ignore_visitor = true;
}
if (getValueFromStorage("cly_ignore")) {
// opted out user
this.ignore_visitor = true;
}
migrate();
requestQueue = getValueFromStorage("cly_queue") || [];
eventQueue = getValueFromStorage("cly_event") || [];
remoteConfigs = getValueFromStorage("cly_remote_configs") || {};
if (this.clearStoredId) {
// retrieve stored device ID and type from local storage and use it to flush existing events
if (getValueFromStorage("cly_id") && !tempIdModeWasEnabled) {
this.device_id = getValueFromStorage("cly_id");
log(logLevelEnums.DEBUG, "initialize, temporarily using the previous device ID to flush existing events");
deviceIdType = getValueFromStorage("cly_id_type");
if (!deviceIdType) {
log(logLevelEnums.DEBUG, "initialize, No device ID type info from the previous session, falling back to DEVELOPER_SUPPLIED, for event flushing");
deviceIdType = DeviceIdTypeInternalEnums.DEVELOPER_SUPPLIED;
}
// don't process async queue here, just send the events (most likely async data is for the new user)
sendEventsForced();
// set them back to their initial values
this.device_id = undefined;
deviceIdType = DeviceIdTypeInternalEnums.SDK_GENERATED;
}
// then clear the storage so that a new device ID is set again later
log(logLevelEnums.INFO, "initialize, Clearing the device ID storage");
removeValueFromStorage("cly_id");
removeValueFromStorage("cly_id_type");
removeValueFromStorage("cly_session");
}