· 6 years ago · Feb 26, 2020, 11:50 PM
1var instrumentationKey = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Replace with your instrumentation key!
2
3/*!
4 * Application Insights JavaScript SDK - Web, 2.4.4
5 * Copyright (c) Microsoft and contributors. All rights reserved.
6 */
7this.Microsoft = this.Microsoft || {};
8this.Microsoft.ApplicationInsights = (function (exports) {
9 'use strict';
10
11 /**
12 * Type of storage to differentiate between local storage and session storage
13 */
14 var StorageType;
15 (function (StorageType) {
16 StorageType[StorageType["LocalStorage"] = 0] = "LocalStorage";
17 StorageType[StorageType["SessionStorage"] = 1] = "SessionStorage";
18 })(StorageType || (StorageType = {}));
19 /**
20 * Enum is used in aiDataContract to describe how fields are serialized.
21 * For instance: (Fieldtype.Required | FieldType.Array) will mark the field as required and indicate it's an array
22 */
23 var FieldType;
24 (function (FieldType) {
25 FieldType[FieldType["Default"] = 0] = "Default";
26 FieldType[FieldType["Required"] = 1] = "Required";
27 FieldType[FieldType["Array"] = 2] = "Array";
28 FieldType[FieldType["Hidden"] = 4] = "Hidden";
29 })(FieldType || (FieldType = {}));
30 var DistributedTracingModes;
31 (function (DistributedTracingModes) {
32 /**
33 * (Default) Send Application Insights correlation headers
34 */
35 DistributedTracingModes[DistributedTracingModes["AI"] = 0] = "AI";
36 /**
37 * Send both W3C Trace Context headers and back-compatibility Application Insights headers
38 */
39 DistributedTracingModes[DistributedTracingModes["AI_AND_W3C"] = 1] = "AI_AND_W3C";
40 /**
41 * Send W3C Trace Context headers
42 */
43 DistributedTracingModes[DistributedTracingModes["W3C"] = 2] = "W3C";
44 })(DistributedTracingModes || (DistributedTracingModes = {}));
45
46 /**
47 * The EventsDiscardedReason enumeration contains a set of values that specify the reason for discarding an event.
48 */
49 var EventsDiscardedReason = {
50 /**
51 * Unknown.
52 */
53 Unknown: 0,
54 /**
55 * Status set to non-retryable.
56 */
57 NonRetryableStatus: 1,
58 /**
59 * The event is invalid.
60 */
61 InvalidEvent: 2,
62 /**
63 * The size of the event is too large.
64 */
65 SizeLimitExceeded: 3,
66 /**
67 * The server is not accepting events from this instrumentation key.
68 */
69 KillSwitch: 4,
70 /**
71 * The event queue is full.
72 */
73 QueueFull: 5
74 };
75
76 /*! *****************************************************************************
77 Copyright (c) Microsoft Corporation. All rights reserved.
78 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
79 this file except in compliance with the License. You may obtain a copy of the
80 License at http://www.apache.org/licenses/LICENSE-2.0
81
82 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
83 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
84 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
85 MERCHANTABLITY OR NON-INFRINGEMENT.
86
87 See the Apache Version 2.0 License for specific language governing permissions
88 and limitations under the License.
89 ***************************************************************************** */
90 /* global Reflect, Promise */
91
92 var extendStatics = function(d, b) {
93 extendStatics = Object.setPrototypeOf ||
94 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
95 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
96 return extendStatics(d, b);
97 };
98
99 function __extends(d, b) {
100 extendStatics(d, b);
101 function __() { this.constructor = d; }
102 d.prototype = b === null ? (function(obj) { /* ai_es3_polyfil create */ var func = Object["create"]; if (func) { return func(obj); } if (obj == null) { return {}; } var type = typeof obj; if (type !== 'object' && type !== 'function') { throw new TypeError('Object prototype may only be an Object:' + obj); } function tmpFunc() {} tmpFunc.prototype = obj; return new tmpFunc(); })(b) : (__.prototype = b.prototype, new __());
103 }
104
105 var __assign = function() {
106 __assign = Object.assign || function __assign(t) {
107 for (var s, i = 1, n = arguments.length; i < n; i++) {
108 s = arguments[i];
109 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
110 }
111 return t;
112 };
113 return __assign.apply(this, arguments);
114 };
115
116 /**
117 * This file exists to hold environment utilities that are requied to check and
118 * validate the current operating environment. Unless otherwise required, please
119 * only defined methods (functions) in this class so that users of these
120 * functions/properties only need to include those that are used within their own modules.
121 */
122 var strUndefined = "undefined";
123 var strObject = "object";
124 var strWindow = "window";
125 var strDocument = "document";
126 var strNavigator = "navigator";
127 var strHistory = "history";
128 var strLocation = "location";
129 var strPerformance = "performance";
130 var strJSON = "JSON";
131 /**
132 * Returns the current global scope object, for a normal web page this will be the current
133 * window, for a Web Worker this will be current worker global scope via "self". The internal
134 * implementation returns the first available instance object in the following order
135 * - globalThis (New standard)
136 * - self (Will return the current window instance for supported browsers)
137 * - window (fallback for older browser implementations)
138 * - global (NodeJS standard)
139 * - <null> (When all else fails)
140 * While the return type is a Window for the normal case, not all environments will support all
141 * of the properties or functions.
142 */
143 function getGlobal() {
144 if (typeof globalThis !== strUndefined && globalThis) {
145 return globalThis;
146 }
147 if (typeof self !== strUndefined && self) {
148 return self;
149 }
150 if (typeof window !== strUndefined && window) {
151 return window;
152 }
153 if (typeof global !== strUndefined && global) {
154 return global;
155 }
156 return null;
157 }
158 /**
159 * Return the named global object if available, will return null if the object is not available.
160 * @param name The globally named object
161 */
162 function getGlobalInst(name) {
163 var gbl = getGlobal();
164 if (gbl && gbl[name]) {
165 return gbl[name];
166 }
167 // Test workaround, for environments where <global>.window (when global == window) doesn't return the base window
168 if (name === strWindow && hasWindow()) {
169 // tslint:disable-next-line: no-angle-bracket-type-assertion
170 return window;
171 }
172 return null;
173 }
174 /**
175 * Checks if window object is available, this is required as we support the API running without a
176 * window /document (eg. Node server, electron webworkers) and if we attempt to assign a window
177 * object to a local variable or pass as an argument an "Uncaught ReferenceError: window is not defined"
178 * exception will be thrown.
179 * Defined as a function to support lazy / late binding environments.
180 */
181 function hasWindow() {
182 return Boolean(typeof window === strObject && window);
183 }
184 /**
185 * Returns the global window object if it is present otherwise null.
186 * This helper is used to access the window object without causing an exception
187 * "Uncaught ReferenceError: window is not defined"
188 */
189 function getWindow() {
190 if (hasWindow()) {
191 return window;
192 }
193 // Return the global instance or null
194 return getGlobalInst(strWindow);
195 }
196 /**
197 * Checks if document object is available, this is required as we support the API running without a
198 * window /document (eg. Node server, electron webworkers) and if we attempt to assign a document
199 * object to a local variable or pass as an argument an "Uncaught ReferenceError: document is not defined"
200 * exception will be thrown.
201 * Defined as a function to support lazy / late binding environments.
202 */
203 function hasDocument() {
204 return Boolean(typeof document === strObject && document);
205 }
206 /**
207 * Returns the global document object if it is present otherwise null.
208 * This helper is used to access the document object without causing an exception
209 * "Uncaught ReferenceError: document is not defined"
210 */
211 function getDocument() {
212 if (hasDocument()) {
213 return document;
214 }
215 return getGlobalInst(strDocument);
216 }
217 /**
218 * Checks if navigator object is available, this is required as we support the API running without a
219 * window /document (eg. Node server, electron webworkers) and if we attempt to assign a navigator
220 * object to a local variable or pass as an argument an "Uncaught ReferenceError: navigator is not defined"
221 * exception will be thrown.
222 * Defined as a function to support lazy / late binding environments.
223 */
224 function hasNavigator() {
225 return Boolean(typeof navigator === strObject && navigator);
226 }
227 /**
228 * Returns the global navigator object if it is present otherwise null.
229 * This helper is used to access the navigator object without causing an exception
230 * "Uncaught ReferenceError: navigator is not defined"
231 */
232 function getNavigator() {
233 if (hasNavigator()) {
234 return navigator;
235 }
236 return getGlobalInst(strNavigator);
237 }
238 /**
239 * Checks if history object is available, this is required as we support the API running without a
240 * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history
241 * object to a local variable or pass as an argument an "Uncaught ReferenceError: history is not defined"
242 * exception will be thrown.
243 * Defined as a function to support lazy / late binding environments.
244 */
245 function hasHistory() {
246 return Boolean(typeof history === strObject && history);
247 }
248 /**
249 * Returns the global history object if it is present otherwise null.
250 * This helper is used to access the history object without causing an exception
251 * "Uncaught ReferenceError: history is not defined"
252 */
253 function getHistory() {
254 if (hasHistory()) {
255 return history;
256 }
257 return getGlobalInst(strHistory);
258 }
259 /**
260 * Returns the global location object if it is present otherwise null.
261 * This helper is used to access the location object without causing an exception
262 * "Uncaught ReferenceError: location is not defined"
263 */
264 function getLocation() {
265 if (typeof location === strObject && location) {
266 return location;
267 }
268 return getGlobalInst(strLocation);
269 }
270 /**
271 * Returns the performance object if it is present otherwise null.
272 * This helper is used to access the performance object from the current
273 * global instance which could be window or globalThis for a web worker
274 */
275 function getPerformance() {
276 return getGlobalInst(strPerformance);
277 }
278 /**
279 * Checks if JSON object is available, this is required as we support the API running without a
280 * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history
281 * object to a local variable or pass as an argument an "Uncaught ReferenceError: JSON is not defined"
282 * exception will be thrown.
283 * Defined as a function to support lazy / late binding environments.
284 */
285 function hasJSON() {
286 return Boolean((typeof JSON === strObject && JSON) || getGlobalInst(strJSON) !== null);
287 }
288 /**
289 * Returns the global JSON object if it is present otherwise null.
290 * This helper is used to access the JSON object without causing an exception
291 * "Uncaught ReferenceError: JSON is not defined"
292 */
293 function getJSON() {
294 if (hasJSON()) {
295 return JSON || getGlobalInst(strJSON);
296 }
297 return null;
298 }
299
300 // Added to help with minfication
301 var Undefined = strUndefined;
302 var prototype = "prototype";
303 var strFunction = "function";
304 var strObject$1 = "object";
305 var strOnPrefix = "on";
306 var strAttachEvent = "attachEvent";
307 var strAddEventHelper = "addEventListener";
308 var strDetachEvent = "detachEvent";
309 var strRemoveEventListener = "removeEventListener";
310 function _isTypeof(value, theType) {
311 return typeof value === theType;
312 }
313 function _isUndefined(value) {
314 return value === undefined || _isTypeof(value, Undefined);
315 }
316 function _isNullOrUndefined(value) {
317 return (_isUndefined(value) || value === null);
318 }
319 function _hasOwnProperty(obj, prop) {
320 return obj && Object[prototype].hasOwnProperty.call(obj, prop);
321 }
322 function _isObject(value) {
323 return _isTypeof(value, strObject$1);
324 }
325 function _isFunction(value) {
326 return _isTypeof(value, strFunction);
327 }
328 /**
329 * Binds the specified function to an event, so that the function gets called whenever the event fires on the object
330 * @param obj Object to add the event too.
331 * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without "on" prefix
332 * @param handlerRef Pointer that specifies the function to call when event fires
333 * @param useCapture [Optional] Defaults to false
334 * @returns True if the function was bound successfully to the event, otherwise false
335 */
336 function _attachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {
337 if (useCapture === void 0) { useCapture = false; }
338 var result = false;
339 if (!_isNullOrUndefined(obj)) {
340 try {
341 if (!_isNullOrUndefined(obj[strAddEventHelper])) {
342 // all browsers except IE before version 9
343 obj[strAddEventHelper](eventNameWithoutOn, handlerRef, useCapture);
344 result = true;
345 }
346 else if (!_isNullOrUndefined(obj[strAttachEvent])) {
347 // IE before version 9
348 obj[strAttachEvent](strOnPrefix + eventNameWithoutOn, handlerRef);
349 result = true;
350 }
351 }
352 catch (e) {
353 // Just Ignore any error so that we don't break any execution path
354 }
355 }
356 return result;
357 }
358 /**
359 * Removes an event handler for the specified event
360 * @param Object to remove the event from
361 * @param eventNameWithoutOn {string} - The name of the event
362 * @param handlerRef {any} - The callback function that needs to be executed for the given event
363 * @param useCapture [Optional] Defaults to false
364 */
365 function _detachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {
366 if (useCapture === void 0) { useCapture = false; }
367 if (!_isNullOrUndefined(obj)) {
368 try {
369 if (!_isNullOrUndefined(obj[strRemoveEventListener])) {
370 obj[strRemoveEventListener](eventNameWithoutOn, handlerRef, useCapture);
371 }
372 else if (!_isNullOrUndefined(obj[strDetachEvent])) {
373 obj[strDetachEvent](strOnPrefix + eventNameWithoutOn, handlerRef);
374 }
375 }
376 catch (e) {
377 // Just Ignore any error so that we don't break any execution path
378 }
379 }
380 }
381 var CoreUtils = /** @class */ (function () {
382 function CoreUtils() {
383 }
384 /**
385 * Check if an object is of type Date
386 */
387 CoreUtils.isDate = function (obj) {
388 return Object[prototype].toString.call(obj) === "[object Date]";
389 };
390 /**
391 * Checks if the type of value is a string.
392 * @param {any} value - Value to be checked.
393 * @return {boolean} True if the value is a string, false otherwise.
394 */
395 CoreUtils.isString = function (value) {
396 return _isTypeof(value, "string");
397 };
398 /**
399 * Checks if the type of value is a number.
400 * @param {any} value - Value to be checked.
401 * @return {boolean} True if the value is a number, false otherwise.
402 */
403 CoreUtils.isNumber = function (value) {
404 return _isTypeof(value, "number");
405 };
406 /**
407 * Checks if the type of value is a boolean.
408 * @param {any} value - Value to be checked.
409 * @return {boolean} True if the value is a boolean, false otherwise.
410 */
411 CoreUtils.isBoolean = function (value) {
412 return _isTypeof(value, "boolean");
413 };
414 /**
415 * Creates a new GUID.
416 * @return {string} A GUID.
417 */
418 CoreUtils.disableCookies = function () {
419 CoreUtils._canUseCookies = false;
420 };
421 CoreUtils.newGuid = function () {
422 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(GuidRegex, function (c) {
423 var r = (Math.random() * 16 | 0), v = (c === 'x' ? r : r & 0x3 | 0x8);
424 return v.toString(16);
425 });
426 };
427 /**
428 * Convert a date to I.S.O. format in IE8
429 */
430 CoreUtils.toISOString = function (date) {
431 if (CoreUtils.isDate(date)) {
432 var pad = function (num) {
433 var r = String(num);
434 if (r.length === 1) {
435 r = "0" + r;
436 }
437 return r;
438 };
439 return date.getUTCFullYear()
440 + "-" + pad(date.getUTCMonth() + 1)
441 + "-" + pad(date.getUTCDate())
442 + "T" + pad(date.getUTCHours())
443 + ":" + pad(date.getUTCMinutes())
444 + ":" + pad(date.getUTCSeconds())
445 + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
446 + "Z";
447 }
448 };
449 /**
450 * Performs the specified action for each element in an array. This helper exists to avoid adding a polyfil for older browsers
451 * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype
452 * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would
453 * cause a testing requirement to test with and without the implementations
454 * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
455 * @param thisArg [Optional] An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
456 */
457 CoreUtils.arrForEach = function (arr, callbackfn, thisArg) {
458 var len = arr.length;
459 for (var idx = 0; idx < len; ++idx) {
460 if (idx in arr) {
461 callbackfn.call(thisArg || arr, arr[idx], idx, arr);
462 }
463 }
464 };
465 /**
466 * Returns the index of the first occurrence of a value in an array. This helper exists to avoid adding a polyfil for older browsers
467 * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype
468 * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would
469 * cause a testing requirement to test with and without the implementations
470 * @param searchElement The value to locate in the array.
471 * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
472 */
473 CoreUtils.arrIndexOf = function (arr, searchElement, fromIndex) {
474 var len = arr.length;
475 var from = fromIndex || 0;
476 for (var lp = Math.max(from >= 0 ? from : len - Math.abs(from), 0); lp < len; lp++) {
477 if (lp in arr && arr[lp] === searchElement) {
478 return lp;
479 }
480 }
481 return -1;
482 };
483 /**
484 * Calls a defined callback function on each element of an array, and returns an array that contains the results. This helper exists
485 * to avoid adding a polyfil for older browsers that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page
486 * checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Array.prototype.xxxx
487 * implementation if it exists as this would cause a testing requirement to test with and without the implementations
488 * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
489 * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
490 */
491 CoreUtils.arrMap = function (arr, callbackfn, thisArg) {
492 var len = arr.length;
493 var _this = thisArg || arr;
494 var results = new Array(len);
495 for (var lp = 0; lp < len; lp++) {
496 if (lp in arr) {
497 results[lp] = callbackfn.call(_this, arr[lp], arr);
498 }
499 }
500 return results;
501 };
502 /**
503 * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is
504 * provided as an argument in the next call to the callback function. This helper exists to avoid adding a polyfil for older browsers that do not define
505 * Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype implementation. Note: For consistency
506 * this will not use the Array.prototype.xxxx implementation if it exists as this would cause a testing requirement to test with and without the implementations
507 * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
508 * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
509 */
510 CoreUtils.arrReduce = function (arr, callbackfn, initialValue) {
511 var len = arr.length;
512 var lp = 0;
513 var value;
514 // Specifically checking the number of passed arguments as the value could be anything
515 if (arguments.length >= 3) {
516 value = arguments[2];
517 }
518 else {
519 while (lp < len && !(lp in arr)) {
520 lp++;
521 }
522 value = arr[lp++];
523 }
524 while (lp < len) {
525 if (lp in arr) {
526 value = callbackfn(value, arr[lp], lp, arr);
527 }
528 lp++;
529 }
530 return value;
531 };
532 /**
533 * Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil
534 * for older browsers that do not define Object.create eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation.
535 * Note: For consistency this will not use the Object.create implementation if it exists as this would cause a testing requirement to test with and without the implementations
536 * @param obj Object to use as a prototype. May be null
537 */
538 CoreUtils.objCreate = function (obj) {
539 if (obj == null) {
540 return {};
541 }
542 if (!_isObject(obj) && !_isFunction(obj)) {
543 throw new TypeError('Object prototype may only be an Object: ' + obj);
544 }
545 function tmpFunc() { }
546 tmpFunc[prototype] = obj;
547 return new tmpFunc();
548 };
549 /**
550 * Returns the names of the enumerable string properties and methods of an object. This helper exists to avoid adding a polyfil for older browsers
551 * that do not define Object.keys eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation.
552 * Note: For consistency this will not use the Object.keys implementation if it exists as this would cause a testing requirement to test with and without the implementations
553 * @param obj Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
554 */
555 CoreUtils.objKeys = function (obj) {
556 var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
557 if (!_isFunction(obj) && (!_isObject(obj) || obj === null)) {
558 throw new TypeError('objKeys called on non-object');
559 }
560 var result = [];
561 for (var prop in obj) {
562 if (_hasOwnProperty(obj, prop)) {
563 result.push(prop);
564 }
565 }
566 if (hasDontEnumBug) {
567 var dontEnums = [
568 'toString',
569 'toLocaleString',
570 'valueOf',
571 'hasOwnProperty',
572 'isPrototypeOf',
573 'propertyIsEnumerable',
574 'constructor'
575 ];
576 var dontEnumsLength = dontEnums.length;
577 for (var lp = 0; lp < dontEnumsLength; lp++) {
578 if (_hasOwnProperty(obj, dontEnums[lp])) {
579 result.push(dontEnums[lp]);
580 }
581 }
582 }
583 return result;
584 };
585 /**
586 * Try to define get/set object property accessors for the target object/prototype, this will provide compatibility with
587 * existing API definition when run within an ES5+ container that supports accessors but still enable the code to be loaded
588 * and executed in an ES3 container, providing basic IE8 compatibility.
589 * @param target The object on which to define the property.
590 * @param prop The name of the property to be defined or modified.
591 * @param getProp The getter function to wire against the getter.
592 * @param setProp The setter function to wire against the setter.
593 * @returns True if it was able to create the accessors otherwise false
594 */
595 CoreUtils.objDefineAccessors = function (target, prop, getProp, setProp) {
596 var defineProp = Object["defineProperty"];
597 if (defineProp) {
598 try {
599 var descriptor = {
600 enumerable: true,
601 configurable: true
602 };
603 if (getProp) {
604 descriptor.get = getProp;
605 }
606 if (setProp) {
607 descriptor.set = setProp;
608 }
609 defineProp(target, prop, descriptor);
610 return true;
611 }
612 catch (e) {
613 // IE8 Defines a defineProperty on Object but it's only supported for DOM elements so it will throw
614 // We will just ignore this here.
615 }
616 }
617 return false;
618 };
619 /**
620 * Trys to add an event handler for the specified event to the window, body and document
621 * @param eventName {string} - The name of the event
622 * @param callback {any} - The callback function that needs to be executed for the given event
623 * @return {boolean} - true if the handler was successfully added
624 */
625 CoreUtils.addEventHandler = function (eventName, callback) {
626 var result = false;
627 var w = getWindow();
628 if (w) {
629 result = _attachEvent(w, eventName, callback);
630 result = _attachEvent(w["body"], eventName, callback) || result;
631 }
632 var doc = getDocument();
633 if (doc) {
634 result = EventHelper.Attach(doc, eventName, callback) || result;
635 }
636 return result;
637 };
638 CoreUtils.isTypeof = _isTypeof;
639 CoreUtils.isUndefined = _isUndefined;
640 CoreUtils.isNullOrUndefined = _isNullOrUndefined;
641 CoreUtils.hasOwnProperty = _hasOwnProperty;
642 /**
643 * Checks if the passed of value is a function.
644 * @param {any} value - Value to be checked.
645 * @return {boolean} True if the value is a boolean, false otherwise.
646 */
647 CoreUtils.isFunction = _isFunction;
648 /**
649 * Checks if the passed of value is a function.
650 * @param {any} value - Value to be checked.
651 * @return {boolean} True if the value is a boolean, false otherwise.
652 */
653 CoreUtils.isObject = _isObject;
654 return CoreUtils;
655 }());
656 var GuidRegex = /[xy]/g;
657 var EventHelper = /** @class */ (function () {
658 function EventHelper() {
659 }
660 /**
661 * Binds the specified function to an event, so that the function gets called whenever the event fires on the object
662 * @param obj Object to add the event too.
663 * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without "on" prefix
664 * @param handlerRef Pointer that specifies the function to call when event fires
665 * @returns True if the function was bound successfully to the event, otherwise false
666 */
667 EventHelper.Attach = _attachEvent;
668 /**
669 * Binds the specified function to an event, so that the function gets called whenever the event fires on the object
670 * @deprecated Use {@link EventHelper#Attach} as we are already in a class call EventHelper the extra "Event" just causes a larger result
671 * @param obj Object to add the event too.
672 * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without "on" prefix
673 * @param handlerRef Pointer that specifies the function to call when event fires
674 * @returns True if the function was bound successfully to the event, otherwise false
675 */
676 EventHelper.AttachEvent = _attachEvent;
677 /**
678 * Removes an event handler for the specified event
679 * @param eventName {string} - The name of the event
680 * @param callback {any} - The callback function that needs to be executed for the given event
681 * @return {boolean} - true if the handler was successfully added
682 */
683 EventHelper.Detach = _detachEvent;
684 /**
685 * Removes an event handler for the specified event
686 * @deprecated Use {@link EventHelper#Detach} as we are already in a class call EventHelper the extra "Event" just causes a larger result
687 * @param eventName {string} - The name of the event
688 * @param callback {any} - The callback function that needs to be executed for the given event
689 * @return {boolean} - true if the handler was successfully added
690 */
691 EventHelper.DetachEvent = _detachEvent;
692 return EventHelper;
693 }());
694
695 var LoggingSeverity;
696 (function (LoggingSeverity) {
697 /**
698 * Error will be sent as internal telemetry
699 */
700 LoggingSeverity[LoggingSeverity["CRITICAL"] = 1] = "CRITICAL";
701 /**
702 * Error will NOT be sent as internal telemetry, and will only be shown in browser console
703 */
704 LoggingSeverity[LoggingSeverity["WARNING"] = 2] = "WARNING";
705 })(LoggingSeverity || (LoggingSeverity = {}));
706 /**
707 * Internal message ID. Please create a new one for every conceptually different message. Please keep alphabetically ordered
708 */
709 var _InternalMessageId = {
710 // Non user actionable
711 BrowserDoesNotSupportLocalStorage: 0,
712 BrowserCannotReadLocalStorage: 1,
713 BrowserCannotReadSessionStorage: 2,
714 BrowserCannotWriteLocalStorage: 3,
715 BrowserCannotWriteSessionStorage: 4,
716 BrowserFailedRemovalFromLocalStorage: 5,
717 BrowserFailedRemovalFromSessionStorage: 6,
718 CannotSendEmptyTelemetry: 7,
719 ClientPerformanceMathError: 8,
720 ErrorParsingAISessionCookie: 9,
721 ErrorPVCalc: 10,
722 ExceptionWhileLoggingError: 11,
723 FailedAddingTelemetryToBuffer: 12,
724 FailedMonitorAjaxAbort: 13,
725 FailedMonitorAjaxDur: 14,
726 FailedMonitorAjaxOpen: 15,
727 FailedMonitorAjaxRSC: 16,
728 FailedMonitorAjaxSend: 17,
729 FailedMonitorAjaxGetCorrelationHeader: 18,
730 FailedToAddHandlerForOnBeforeUnload: 19,
731 FailedToSendQueuedTelemetry: 20,
732 FailedToReportDataLoss: 21,
733 FlushFailed: 22,
734 MessageLimitPerPVExceeded: 23,
735 MissingRequiredFieldSpecification: 24,
736 NavigationTimingNotSupported: 25,
737 OnError: 26,
738 SessionRenewalDateIsZero: 27,
739 SenderNotInitialized: 28,
740 StartTrackEventFailed: 29,
741 StopTrackEventFailed: 30,
742 StartTrackFailed: 31,
743 StopTrackFailed: 32,
744 TelemetrySampledAndNotSent: 33,
745 TrackEventFailed: 34,
746 TrackExceptionFailed: 35,
747 TrackMetricFailed: 36,
748 TrackPVFailed: 37,
749 TrackPVFailedCalc: 38,
750 TrackTraceFailed: 39,
751 TransmissionFailed: 40,
752 FailedToSetStorageBuffer: 41,
753 FailedToRestoreStorageBuffer: 42,
754 InvalidBackendResponse: 43,
755 FailedToFixDepricatedValues: 44,
756 InvalidDurationValue: 45,
757 TelemetryEnvelopeInvalid: 46,
758 CreateEnvelopeError: 47,
759 // User actionable
760 CannotSerializeObject: 48,
761 CannotSerializeObjectNonSerializable: 49,
762 CircularReferenceDetected: 50,
763 ClearAuthContextFailed: 51,
764 ExceptionTruncated: 52,
765 IllegalCharsInName: 53,
766 ItemNotInArray: 54,
767 MaxAjaxPerPVExceeded: 55,
768 MessageTruncated: 56,
769 NameTooLong: 57,
770 SampleRateOutOfRange: 58,
771 SetAuthContextFailed: 59,
772 SetAuthContextFailedAccountName: 60,
773 StringValueTooLong: 61,
774 StartCalledMoreThanOnce: 62,
775 StopCalledWithoutStart: 63,
776 TelemetryInitializerFailed: 64,
777 TrackArgumentsNotSpecified: 65,
778 UrlTooLong: 66,
779 SessionStorageBufferFull: 67,
780 CannotAccessCookie: 68,
781 IdTooLong: 69,
782 InvalidEvent: 70,
783 FailedMonitorAjaxSetRequestHeader: 71,
784 SendBrowserInfoOnUserInit: 72,
785 PluginException: 73
786 };
787
788 var _InternalLogMessage = /** @class */ (function () {
789 function _InternalLogMessage(msgId, msg, isUserAct, properties) {
790 if (isUserAct === void 0) { isUserAct = false; }
791 this.messageId = msgId;
792 this.message =
793 (isUserAct ? _InternalLogMessage.AiUserActionablePrefix : _InternalLogMessage.AiNonUserActionablePrefix) +
794 msgId;
795 var strProps = "";
796 if (hasJSON()) {
797 strProps = getJSON().stringify(properties);
798 }
799 var diagnosticText = (msg ? " message:" + _InternalLogMessage.sanitizeDiagnosticText(msg) : "") +
800 (properties ? " props:" + _InternalLogMessage.sanitizeDiagnosticText(strProps) : "");
801 this.message += diagnosticText;
802 }
803 _InternalLogMessage.sanitizeDiagnosticText = function (text) {
804 if (text) {
805 return "\"" + text.replace(/\"/g, "") + "\"";
806 }
807 return "";
808 };
809 _InternalLogMessage.dataType = "MessageData";
810 /**
811 * For user non actionable traces use AI Internal prefix.
812 */
813 _InternalLogMessage.AiNonUserActionablePrefix = "AI (Internal): ";
814 /**
815 * Prefix of the traces in portal.
816 */
817 _InternalLogMessage.AiUserActionablePrefix = "AI: ";
818 return _InternalLogMessage;
819 }());
820 var DiagnosticLogger = /** @class */ (function () {
821 function DiagnosticLogger(config) {
822 /**
823 * The internal logging queue
824 */
825 this.queue = [];
826 /**
827 * Session storage key for the prefix for the key indicating message type already logged
828 */
829 this.AIInternalMessagePrefix = "AITR_";
830 /**
831 * Count of internal messages sent
832 */
833 this._messageCount = 0;
834 /**
835 * Holds information about what message types were already logged to console or sent to server.
836 */
837 this._messageLogged = {};
838 /**
839 * When this is true the SDK will throw exceptions to aid in debugging.
840 */
841 this.enableDebugExceptions = function () { return false; };
842 /**
843 * 0: OFF (default)
844 * 1: CRITICAL
845 * 2: >= WARNING
846 */
847 this.consoleLoggingLevel = function () { return 0; };
848 /**
849 * 0: OFF
850 * 1: CRITICAL (default)
851 * 2: >= WARNING
852 */
853 this.telemetryLoggingLevel = function () { return 1; };
854 /**
855 * The maximum number of internal messages allowed to be sent per page view
856 */
857 this.maxInternalMessageLimit = function () { return 25; };
858 if (CoreUtils.isNullOrUndefined(config)) {
859 // TODO: Use default config
860 // config = AppInsightsCore.defaultConfig;
861 // For now, use defaults specified in DiagnosticLogger members;
862 return;
863 }
864 if (!CoreUtils.isNullOrUndefined(config.loggingLevelConsole)) {
865 this.consoleLoggingLevel = function () { return config.loggingLevelConsole; };
866 }
867 if (!CoreUtils.isNullOrUndefined(config.loggingLevelTelemetry)) {
868 this.telemetryLoggingLevel = function () { return config.loggingLevelTelemetry; };
869 }
870 if (!CoreUtils.isNullOrUndefined(config.maxMessageLimit)) {
871 this.maxInternalMessageLimit = function () { return config.maxMessageLimit; };
872 }
873 if (!CoreUtils.isNullOrUndefined(config.enableDebugExceptions)) {
874 this.enableDebugExceptions = function () { return config.enableDebugExceptions; };
875 }
876 }
877 /**
878 * This method will throw exceptions in debug mode or attempt to log the error as a console warning.
879 * @param severity {LoggingSeverity} - The severity of the log message
880 * @param message {_InternalLogMessage} - The log message.
881 */
882 DiagnosticLogger.prototype.throwInternal = function (severity, msgId, msg, properties, isUserAct) {
883 if (isUserAct === void 0) { isUserAct = false; }
884 var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
885 var _this = this;
886 if (_this.enableDebugExceptions()) {
887 throw message;
888 }
889 else {
890 if (!CoreUtils.isUndefined(message) && !!message) {
891 if (!CoreUtils.isUndefined(message.message)) {
892 if (isUserAct) {
893 // check if this message type was already logged to console for this page view and if so, don't log it again
894 var messageKey = +message.messageId;
895 if (!_this._messageLogged[messageKey] && _this.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
896 _this.warnToConsole(message.message);
897 _this._messageLogged[messageKey] = true;
898 }
899 }
900 else {
901 // don't log internal AI traces in the console, unless the verbose logging is enabled
902 if (_this.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
903 _this.warnToConsole(message.message);
904 }
905 }
906 _this.logInternalMessage(severity, message);
907 }
908 }
909 }
910 };
911 /**
912 * This will write a warning to the console if possible
913 * @param message {string} - The warning message
914 */
915 DiagnosticLogger.prototype.warnToConsole = function (message) {
916 if (!CoreUtils.isUndefined(console) && !!console) {
917 if (CoreUtils.isFunction(console.warn)) {
918 console.warn(message);
919 }
920 else if (CoreUtils.isFunction(console.log)) {
921 console.log(message);
922 }
923 }
924 };
925 /**
926 * Resets the internal message count
927 */
928 DiagnosticLogger.prototype.resetInternalMessageCount = function () {
929 this._messageCount = 0;
930 this._messageLogged = {};
931 };
932 /**
933 * Logs a message to the internal queue.
934 * @param severity {LoggingSeverity} - The severity of the log message
935 * @param message {_InternalLogMessage} - The message to log.
936 */
937 DiagnosticLogger.prototype.logInternalMessage = function (severity, message) {
938 var _this = this;
939 if (_this._areInternalMessagesThrottled()) {
940 return;
941 }
942 // check if this message type was already logged for this session and if so, don't log it again
943 var logMessage = true;
944 var messageKey = _this.AIInternalMessagePrefix + message.messageId;
945 // if the session storage is not available, limit to only one message type per page view
946 if (_this._messageLogged[messageKey]) {
947 logMessage = false;
948 }
949 else {
950 _this._messageLogged[messageKey] = true;
951 }
952 if (logMessage) {
953 // Push the event in the internal queue
954 if (severity <= _this.telemetryLoggingLevel()) {
955 _this.queue.push(message);
956 _this._messageCount++;
957 }
958 // When throttle limit reached, send a special event
959 if (_this._messageCount === _this.maxInternalMessageLimit()) {
960 var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
961 var throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
962 _this.queue.push(throttleMessage);
963 _this.warnToConsole(throttleLimitMessage);
964 }
965 }
966 };
967 /**
968 * Indicates whether the internal events are throttled
969 */
970 DiagnosticLogger.prototype._areInternalMessagesThrottled = function () {
971 return this._messageCount >= this.maxInternalMessageLimit();
972 };
973 return DiagnosticLogger;
974 }());
975
976 var _isFunction$1 = CoreUtils.isFunction;
977 var TelemetryPluginChain = /** @class */ (function () {
978 function TelemetryPluginChain(plugin, defItemCtx) {
979 var _self = this;
980 var _nextProxy = null;
981 var _hasProcessTelemetry = _isFunction$1(plugin.processTelemetry);
982 var _hasSetNext = _isFunction$1(plugin.setNextPlugin);
983 _self._hasRun = false;
984 _self.getPlugin = function () {
985 return plugin;
986 };
987 _self.getNext = function () {
988 return _nextProxy;
989 };
990 _self.setNext = function (nextPlugin) {
991 _nextProxy = nextPlugin;
992 };
993 _self.processTelemetry = function (env, itemCtx) {
994 if (!itemCtx) {
995 // Looks like a plugin didn't pass the (optional) context, so restore to the default
996 itemCtx = defItemCtx;
997 }
998 if (plugin && _hasProcessTelemetry) {
999 _self._hasRun = true;
1000 try {
1001 // Ensure that we keep the context in sync (for processNext()), just in case a plugin
1002 // doesn't calls processTelemetry() instead of itemContext.processNext() or some
1003 // other form of error occurred
1004 itemCtx.setNext(_nextProxy);
1005 if (_hasSetNext) {
1006 // Backward compatibility setting the next plugin on the instance
1007 plugin.setNextPlugin(_nextProxy);
1008 }
1009 // Set a flag on the next plugin so we know if it was attempted to be executed
1010 _nextProxy && (_nextProxy._hasRun = false);
1011 plugin.processTelemetry(env, itemCtx);
1012 }
1013 catch (error) {
1014 var hasRun = _nextProxy && _nextProxy._hasRun;
1015 if (!_nextProxy || !hasRun) {
1016 // Either we have no next plugin or the current one did not attempt to call the next plugin
1017 // Which means the current one is the root of the failure so log/report this failure
1018 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.PluginException, "Plugin [" + plugin.identifier + "] failed during processTelemetry - " + error);
1019 }
1020 if (_nextProxy && !hasRun) {
1021 // As part of the failure the current plugin did not attempt to call the next plugin in the cahin
1022 // So rather than leave the pipeline dead in the water we call the next plugin
1023 _nextProxy.processTelemetry(env, itemCtx);
1024 }
1025 }
1026 }
1027 else if (_nextProxy) {
1028 _self._hasRun = true;
1029 // The underlying plugin is either not defined or does not have a processTelemetry implementation
1030 // so we still want the next plugin to be executed.
1031 _nextProxy.processTelemetry(env, itemCtx);
1032 }
1033 };
1034 }
1035 return TelemetryPluginChain;
1036 }());
1037
1038 var _isNullOrUndefined$1 = CoreUtils.isNullOrUndefined;
1039 /**
1040 * Creates the instance execution chain for the plugins
1041 */
1042 function _createProxyChain(plugins, itemCtx) {
1043 var proxies = [];
1044 if (plugins && plugins.length > 0) {
1045 // Create the proxies and wire up the next plugin chain
1046 var lastProxy = null;
1047 for (var idx = 0; idx < plugins.length; idx++) {
1048 var thePlugin = plugins[idx];
1049 if (thePlugin && CoreUtils.isFunction(thePlugin.processTelemetry)) {
1050 // Only add plugins that are processors
1051 var newProxy = new TelemetryPluginChain(thePlugin, itemCtx);
1052 proxies.push(newProxy);
1053 if (lastProxy) {
1054 // Set this new proxy as the next for the previous one
1055 lastProxy.setNext(newProxy);
1056 }
1057 lastProxy = newProxy;
1058 }
1059 }
1060 }
1061 return proxies.length > 0 ? proxies[0] : null;
1062 }
1063 function _copyProxyChain(proxy, itemCtx, startAt) {
1064 var plugins = [];
1065 var add = startAt ? false : true;
1066 if (proxy) {
1067 while (proxy) {
1068 var thePlugin = proxy.getPlugin();
1069 if (add || thePlugin === startAt) {
1070 add = true;
1071 plugins.push(thePlugin);
1072 }
1073 proxy = proxy.getNext();
1074 }
1075 }
1076 if (!add) {
1077 plugins.push(startAt);
1078 }
1079 return _createProxyChain(plugins, itemCtx);
1080 }
1081 function _copyPluginChain(srcPlugins, itemCtx, startAt) {
1082 var plugins = srcPlugins;
1083 var add = false;
1084 if (startAt && srcPlugins) {
1085 plugins = [];
1086 CoreUtils.arrForEach(srcPlugins, function (thePlugin) {
1087 if (add || thePlugin === startAt) {
1088 add = true;
1089 plugins.push(thePlugin);
1090 }
1091 });
1092 }
1093 if (startAt && !add) {
1094 if (!plugins) {
1095 plugins = [];
1096 }
1097 plugins.push(startAt);
1098 }
1099 return _createProxyChain(plugins, itemCtx);
1100 }
1101 var ProcessTelemetryContext = /** @class */ (function () {
1102 /**
1103 * Creates a new Telemetry Item context with the current config, core and plugin execution chain
1104 * @param plugins - The plugin instances that will be executed
1105 * @param config - The current config
1106 * @param core - The current core instance
1107 */
1108 function ProcessTelemetryContext(plugins, config, core, startAt) {
1109 var _self = this;
1110 var _nextProxy = null; // Null == No next plugin
1111 // There is no next element (null) vs not defined (undefined)
1112 if (startAt !== null) {
1113 if (plugins && CoreUtils.isFunction(plugins.getPlugin)) {
1114 // We have a proxy chain object
1115 _nextProxy = _copyProxyChain(plugins, _self, startAt || plugins.getPlugin());
1116 }
1117 else {
1118 // We just have an array
1119 if (startAt) {
1120 _nextProxy = _copyPluginChain(plugins, _self, startAt);
1121 }
1122 else if (CoreUtils.isUndefined(startAt)) {
1123 // Undefined means copy the existing chain
1124 _nextProxy = _createProxyChain(plugins, _self);
1125 }
1126 }
1127 }
1128 _self.core = function () {
1129 return core;
1130 };
1131 _self.diagLog = function () {
1132 var logger = (core || {}).logger;
1133 if (!logger) {
1134 // Fallback so we always have a logger
1135 logger = new DiagnosticLogger(config || {});
1136 }
1137 return logger;
1138 };
1139 _self.getCfg = function () {
1140 return config;
1141 };
1142 _self.getExtCfg = function (identifier, defaultValue) {
1143 if (defaultValue === void 0) { defaultValue = {}; }
1144 var theConfig;
1145 if (config) {
1146 var extConfig = config.extensionConfig;
1147 if (extConfig && identifier) {
1148 theConfig = extConfig[identifier];
1149 }
1150 }
1151 return (theConfig ? theConfig : defaultValue);
1152 };
1153 _self.getConfig = function (identifier, field, defaultValue) {
1154 if (defaultValue === void 0) { defaultValue = false; }
1155 var theValue;
1156 var extConfig = _self.getExtCfg(identifier, null);
1157 if (extConfig && !_isNullOrUndefined$1(extConfig[field])) {
1158 theValue = extConfig[field];
1159 }
1160 else if (config && !_isNullOrUndefined$1(config[field])) {
1161 theValue = config[field];
1162 }
1163 return !_isNullOrUndefined$1(theValue) ? theValue : defaultValue;
1164 };
1165 _self.hasNext = function () {
1166 return _nextProxy != null;
1167 };
1168 _self.getNext = function () {
1169 return _nextProxy;
1170 };
1171 _self.setNext = function (nextPlugin) {
1172 _nextProxy = nextPlugin;
1173 };
1174 _self.processNext = function (env) {
1175 var nextPlugin = _nextProxy;
1176 if (nextPlugin) {
1177 // Automatically move to the next plugin
1178 _nextProxy = nextPlugin.getNext();
1179 nextPlugin.processTelemetry(env, _self);
1180 }
1181 };
1182 _self.createNew = function (plugins, startAt) {
1183 if (plugins === void 0) { plugins = null; }
1184 return new ProcessTelemetryContext(plugins || _nextProxy, config, core, startAt);
1185 };
1186 }
1187 return ProcessTelemetryContext;
1188 }());
1189
1190 var _isFunction$2 = CoreUtils.isFunction;
1191 var getPlugin = "getPlugin";
1192 /**
1193 * BaseTelemetryPlugin provides a basic implementation of the ITelemetryPlugin interface so that plugins
1194 * can avoid implementation the same set of boiler plate code as well as provide a base
1195 * implementation so that new default implementations can be added without breaking all plugins.
1196 */
1197 var BaseTelemetryPlugin = /** @class */ (function () {
1198 function BaseTelemetryPlugin() {
1199 var _self = this;
1200 var _isinitialized = false;
1201 var _rootCtx = null; // Used as the root context, holding the current config and initialized core
1202 var _nextPlugin = null; // Used for backward compatibility where plugins don't call the main pipeline
1203 _self.core = null;
1204 _self.diagLog = function (itemCtx) {
1205 return _self._getTelCtx(itemCtx).diagLog();
1206 };
1207 _self.isInitialized = function () {
1208 return _isinitialized;
1209 };
1210 _self.setInitialized = function (isInitialized) {
1211 _isinitialized = isInitialized;
1212 };
1213 // _self.getNextPlugin = () => DO NOT IMPLEMENT
1214 // Sub-classes of this base class *should* not be relying on this value and instead
1215 // should use processNext() function. If you require access to the plugin use the
1216 // IProcessTelemetryContext.getNext().getPlugin() while in the pipeline, Note getNext() may return null.
1217 _self.setNextPlugin = function (next) {
1218 _nextPlugin = next;
1219 };
1220 _self.processNext = function (env, itemCtx) {
1221 if (itemCtx) {
1222 // Normal core execution sequence
1223 itemCtx.processNext(env);
1224 }
1225 else if (_nextPlugin && _isFunction$2(_nextPlugin.processTelemetry)) {
1226 // Looks like backward compatibility or out of band processing. And as it looks
1227 // like a ITelemetryPlugin or ITelemetryPluginChain, just call processTelemetry
1228 _nextPlugin.processTelemetry(env, null);
1229 }
1230 };
1231 _self._getTelCtx = function (currentCtx) {
1232 if (currentCtx === void 0) { currentCtx = null; }
1233 var itemCtx = currentCtx;
1234 if (!itemCtx) {
1235 var rootCtx = _rootCtx || new ProcessTelemetryContext(null, {}, _self.core);
1236 // tslint:disable-next-line: prefer-conditional-expression
1237 if (_nextPlugin && _nextPlugin[getPlugin]) {
1238 // Looks like a chain object
1239 itemCtx = rootCtx.createNew(null, _nextPlugin[getPlugin]);
1240 }
1241 else {
1242 itemCtx = rootCtx.createNew(null, _nextPlugin);
1243 }
1244 }
1245 return itemCtx;
1246 };
1247 _self._baseTelInit = function (config, core, extensions, pluginChain) {
1248 if (config) {
1249 // Make sure the extensionConfig exists
1250 config.extensionConfig = config.extensionConfig || [];
1251 }
1252 if (!pluginChain && core) {
1253 // Get the first plugin from the core
1254 pluginChain = core.getProcessTelContext().getNext();
1255 }
1256 var nextPlugin = _nextPlugin;
1257 if (_nextPlugin && _nextPlugin[getPlugin]) {
1258 // If it looks like a proxy/chain then get the plugin
1259 nextPlugin = _nextPlugin[getPlugin]();
1260 }
1261 // Support legacy plugins where core was defined as a property
1262 _self.core = core;
1263 _rootCtx = new ProcessTelemetryContext(pluginChain, config, core, nextPlugin);
1264 _isinitialized = true;
1265 };
1266 }
1267 BaseTelemetryPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {
1268 this._baseTelInit(config, core, extensions, pluginChain);
1269 };
1270 return BaseTelemetryPlugin;
1271 }());
1272
1273 var _isFunction$3 = CoreUtils.isFunction;
1274 var processTelemetry = "processTelemetry";
1275 var priority = "priority";
1276 var setNextPlugin = "setNextPlugin";
1277 var isInitialized = "isInitialized";
1278 /**
1279 * Initialize the queue of plugins
1280 * @param plugins - The array of plugins to initialize and setting of the next plugin
1281 * @param config The current config for the instance
1282 * @param core THe current core instance
1283 * @param extensions The extensions
1284 */
1285 function initializePlugins(processContext, extensions) {
1286 // Set the next plugin and identified the uninitialized plugins
1287 var initPlugins = [];
1288 var lastPlugin = null;
1289 var proxy = processContext.getNext();
1290 while (proxy) {
1291 var thePlugin = proxy.getPlugin();
1292 if (thePlugin) {
1293 if (lastPlugin &&
1294 _isFunction$3(lastPlugin[setNextPlugin]) &&
1295 _isFunction$3(thePlugin[processTelemetry])) {
1296 // Set this plugin as the next for the previous one
1297 lastPlugin[setNextPlugin](thePlugin);
1298 }
1299 if (!_isFunction$3(thePlugin[isInitialized]) || !thePlugin[isInitialized]()) {
1300 initPlugins.push(thePlugin);
1301 }
1302 lastPlugin = thePlugin;
1303 proxy = proxy.getNext();
1304 }
1305 }
1306 // Now initiatilize the plugins
1307 CoreUtils.arrForEach(initPlugins, function (thePlugin) {
1308 thePlugin.initialize(processContext.getCfg(), processContext.core(), extensions, processContext.getNext());
1309 });
1310 }
1311 function sortPlugins(plugins) {
1312 // Sort by priority
1313 return plugins.sort(function (extA, extB) {
1314 var result = 0;
1315 var bHasProcess = _isFunction$3(extB[processTelemetry]);
1316 if (_isFunction$3(extA[processTelemetry])) {
1317 result = bHasProcess ? extA[priority] - extB[priority] : 1;
1318 }
1319 else if (bHasProcess) {
1320 result = -1;
1321 }
1322 return result;
1323 });
1324 // sort complete
1325 }
1326
1327 var ChannelControllerPriority = 500;
1328 var ChannelValidationMessage = "Channel has invalid priority";
1329 var _arrForEach = CoreUtils.arrForEach;
1330 var _objDefineAccessors = CoreUtils.objDefineAccessors;
1331 function _checkQueuePriority(queue) {
1332 _arrForEach(queue, function (queueItem) {
1333 if (queueItem.priority < ChannelControllerPriority) {
1334 throw Error(ChannelValidationMessage + queueItem.identifier);
1335 }
1336 });
1337 }
1338 function _addChannelQueue(channelQueues, queue) {
1339 if (queue && queue.length > 0) {
1340 queue = queue.sort(function (a, b) {
1341 return a.priority - b.priority;
1342 });
1343 _checkQueuePriority(queue);
1344 channelQueues.push(queue);
1345 }
1346 }
1347 function _createChannelQueues(channels, extensions) {
1348 var channelQueues = [];
1349 if (channels) {
1350 // Add and sort the configuration channel queues
1351 _arrForEach(channels, function (queue) { return _addChannelQueue(channelQueues, queue); });
1352 }
1353 if (extensions) {
1354 // Create a new channel queue for any extensions with a priority > the ChannelControllerPriority
1355 var extensionQueue_1 = [];
1356 _arrForEach(extensions, function (plugin) {
1357 if (plugin.priority > ChannelControllerPriority) {
1358 extensionQueue_1.push(plugin);
1359 }
1360 });
1361 _addChannelQueue(channelQueues, extensionQueue_1);
1362 }
1363 return channelQueues;
1364 }
1365 var ChannelController = /** @class */ (function (_super) {
1366 __extends(ChannelController, _super);
1367 function ChannelController() {
1368 var _this = _super !== null && _super.apply(this, arguments) || this;
1369 _this.identifier = "ChannelControllerPlugin";
1370 _this.priority = ChannelControllerPriority; // in reserved range 100 to 200
1371 return _this;
1372 }
1373 ChannelController.prototype.processTelemetry = function (item, itemCtx) {
1374 var _this = this;
1375 if (this._channelQueue) {
1376 _arrForEach(this._channelQueue, function (queues) {
1377 // pass on to first item in queue
1378 if (queues.length > 0) {
1379 // Copying the item context as we could have mutiple chains that are executing asynchronously
1380 // and calling _getDefTelCtx as it's possible that the caller doesn't pass any context
1381 var chainCtx = _this._getTelCtx(itemCtx).createNew(queues);
1382 chainCtx.processNext(item);
1383 }
1384 });
1385 }
1386 };
1387 ChannelController.prototype.getChannelControls = function () {
1388 return this._channelQueue;
1389 };
1390 ChannelController.prototype.initialize = function (config, core, extensions) {
1391 var _self = this;
1392 if (_self.isInitialized()) {
1393 // already initialized
1394 return;
1395 }
1396 _super.prototype.initialize.call(this, config, core, extensions);
1397 if (config.isCookieUseDisabled) {
1398 CoreUtils.disableCookies();
1399 }
1400 var channelQueue = _self._channelQueue = _createChannelQueues((config || {}).channels, extensions);
1401 // Initialize the Queues
1402 _arrForEach(channelQueue, function (queue) { return initializePlugins(new ProcessTelemetryContext(queue, config, core), extensions); });
1403 };
1404 /**
1405 * Static constructor, attempt to create accessors
1406 */
1407 // tslint:disable-next-line
1408 ChannelController._staticInit = (function () {
1409 // Dynamically create get/set property accessors
1410 _objDefineAccessors(ChannelController.prototype, "ChannelControls", ChannelController.prototype.getChannelControls);
1411 _objDefineAccessors(ChannelController.prototype, "channelQueue", ChannelController.prototype.getChannelControls);
1412 })();
1413 return ChannelController;
1414 }(BaseTelemetryPlugin));
1415
1416 var validationError = "Extensions must provide callback to initialize";
1417 var _arrForEach$1 = CoreUtils.arrForEach;
1418 var _isNullOrUndefined$2 = CoreUtils.isNullOrUndefined;
1419 var BaseCore = /** @class */ (function () {
1420 function BaseCore() {
1421 var _isInitialized = false;
1422 var _this = this;
1423 _this._extensions = new Array();
1424 _this._channelController = new ChannelController();
1425 _this.isInitialized = function () { return _isInitialized; };
1426 _this._setInit = function (value) { _isInitialized = value; };
1427 _this._eventQueue = [];
1428 }
1429 BaseCore.prototype.initialize = function (config, extensions, logger, notificationManager) {
1430 var _this = this;
1431 // Make sure core is only initialized once
1432 if (_this.isInitialized()) {
1433 throw Error("Core should not be initialized more than once");
1434 }
1435 if (!config || _isNullOrUndefined$2(config.instrumentationKey)) {
1436 throw Error("Please provide instrumentation key");
1437 }
1438 _this.config = config;
1439 var channelController = _this._channelController;
1440 if (!notificationManager) {
1441 // Create Dummy notification manager
1442 notificationManager = CoreUtils.objCreate({
1443 addNotificationListener: function (listener) { },
1444 removeNotificationListener: function (listener) { },
1445 eventsSent: function (events) { },
1446 eventsDiscarded: function (events, reason) { }
1447 });
1448 }
1449 _this._notificationManager = notificationManager;
1450 config.extensions = _isNullOrUndefined$2(config.extensions) ? [] : config.extensions;
1451 // add notification to the extensions in the config so other plugins can access it
1452 var extConfig = config.extensionConfig = _isNullOrUndefined$2(config.extensionConfig) ? {} : config.extensionConfig;
1453 extConfig.NotificationManager = notificationManager;
1454 if (!logger) {
1455 logger = CoreUtils.objCreate({
1456 throwInternal: function (severity, msgId, msg, properties, isUserAct) {
1457 if (isUserAct === void 0) { isUserAct = false; }
1458 },
1459 warnToConsole: function (message) { },
1460 resetInternalMessageCount: function () { }
1461 });
1462 }
1463 _this.logger = logger;
1464 // Concat all available extensions
1465 var allExtensions = [];
1466 allExtensions.push.apply(allExtensions, extensions.concat(config.extensions));
1467 allExtensions = sortPlugins(allExtensions);
1468 var coreExtensions = [];
1469 // Check if any two extensions have the same priority, then warn to console
1470 // And extract the local extensions from the
1471 var extPriorities = {};
1472 // Extension validation
1473 _arrForEach$1(allExtensions, function (ext) {
1474 if (_isNullOrUndefined$2(ext) || _isNullOrUndefined$2(ext.initialize)) {
1475 throw Error(validationError);
1476 }
1477 var extPriority = ext.priority;
1478 var identifier = ext.identifier;
1479 if (ext && extPriority) {
1480 if (!_isNullOrUndefined$2(extPriorities[extPriority])) {
1481 logger.warnToConsole("Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier);
1482 }
1483 else {
1484 // set a value
1485 extPriorities[extPriority] = identifier;
1486 }
1487 }
1488 // Split extensions to core and channelController
1489 if (!extPriority || extPriority < channelController.priority) {
1490 // Add to core extension that will be managed by BaseCore
1491 coreExtensions.push(ext);
1492 }
1493 });
1494 // Validation complete
1495 // Add the channelController to the complete extension collection and
1496 // to the end of the core extensions
1497 allExtensions.push(channelController);
1498 coreExtensions.push(channelController);
1499 // Sort the complete set of extensions by priority
1500 allExtensions = sortPlugins(allExtensions);
1501 _this._extensions = allExtensions;
1502 // initialize channel controller first, this will initialize all channel plugins
1503 initializePlugins(new ProcessTelemetryContext([channelController], config, _this), allExtensions);
1504 initializePlugins(new ProcessTelemetryContext(coreExtensions, config, _this), allExtensions);
1505 // Now reset the extensions to just those being managed by Basecore
1506 _this._extensions = coreExtensions;
1507 if (_this.getTransmissionControls().length === 0) {
1508 throw new Error("No channels available");
1509 }
1510 _this._setInit(true);
1511 };
1512 BaseCore.prototype.getTransmissionControls = function () {
1513 return this._channelController.getChannelControls();
1514 };
1515 BaseCore.prototype.track = function (telemetryItem) {
1516 var _this = this;
1517 if (!telemetryItem.iKey) {
1518 // setup default iKey if not passed in
1519 telemetryItem.iKey = _this.config.instrumentationKey;
1520 }
1521 if (!telemetryItem.time) {
1522 // add default timestamp if not passed in
1523 telemetryItem.time = CoreUtils.toISOString(new Date());
1524 }
1525 if (_isNullOrUndefined$2(telemetryItem.ver)) {
1526 // CommonSchema 4.0
1527 telemetryItem.ver = "4.0";
1528 }
1529 if (_this.isInitialized()) {
1530 // Release queue
1531 if (_this._eventQueue.length > 0) {
1532 _arrForEach$1(_this._eventQueue, function (event) {
1533 _this.getProcessTelContext().processNext(event);
1534 });
1535 _this._eventQueue = [];
1536 }
1537 // Process the telemetry plugin chain
1538 _this.getProcessTelContext().processNext(telemetryItem);
1539 }
1540 else {
1541 // Queue events until all extensions are initialized
1542 _this._eventQueue.push(telemetryItem);
1543 }
1544 };
1545 BaseCore.prototype.getProcessTelContext = function () {
1546 var _this = this;
1547 var extensions = _this._extensions;
1548 var thePlugins = extensions;
1549 // invoke any common telemetry processors before sending through pipeline
1550 if (!extensions || extensions.length === 0) {
1551 // Pass to Channel controller so data is sent to correct channel queues
1552 thePlugins = [_this._channelController];
1553 }
1554 return new ProcessTelemetryContext(thePlugins, _this.config, _this);
1555 };
1556 return BaseCore;
1557 }());
1558
1559 /**
1560 * Class to manage sending notifications to all the listeners.
1561 */
1562 var NotificationManager = /** @class */ (function () {
1563 function NotificationManager() {
1564 this.listeners = [];
1565 }
1566 /**
1567 * Adds a notification listener.
1568 * @param {INotificationListener} listener - The notification listener to be added.
1569 */
1570 NotificationManager.prototype.addNotificationListener = function (listener) {
1571 this.listeners.push(listener);
1572 };
1573 /**
1574 * Removes all instances of the listener.
1575 * @param {INotificationListener} listener - AWTNotificationListener to remove.
1576 */
1577 NotificationManager.prototype.removeNotificationListener = function (listener) {
1578 var index = CoreUtils.arrIndexOf(this.listeners, listener);
1579 while (index > -1) {
1580 this.listeners.splice(index, 1);
1581 index = CoreUtils.arrIndexOf(this.listeners, listener);
1582 }
1583 };
1584 /**
1585 * Notification for events sent.
1586 * @param {ITelemetryItem[]} events - The array of events that have been sent.
1587 */
1588 NotificationManager.prototype.eventsSent = function (events) {
1589 var _this = this;
1590 var _loop_1 = function (i) {
1591 if (this_1.listeners[i].eventsSent) {
1592 setTimeout(function () { return _this.listeners[i].eventsSent(events); }, 0);
1593 }
1594 };
1595 var this_1 = this;
1596 for (var i = 0; i < this.listeners.length; ++i) {
1597 _loop_1(i);
1598 }
1599 };
1600 /**
1601 * Notification for events being discarded.
1602 * @param {ITelemetryItem[]} events - The array of events that have been discarded by the SDK.
1603 * @param {number} reason - The reason for which the SDK discarded the events. The EventsDiscardedReason
1604 * constant should be used to check the different values.
1605 */
1606 NotificationManager.prototype.eventsDiscarded = function (events, reason) {
1607 var _this = this;
1608 var _loop_2 = function (i) {
1609 if (this_2.listeners[i].eventsDiscarded) {
1610 setTimeout(function () { return _this.listeners[i].eventsDiscarded(events, reason); }, 0);
1611 }
1612 };
1613 var this_2 = this;
1614 for (var i = 0; i < this.listeners.length; ++i) {
1615 _loop_2(i);
1616 }
1617 };
1618 return NotificationManager;
1619 }());
1620
1621 var AppInsightsCore = /** @class */ (function (_super) {
1622 __extends(AppInsightsCore, _super);
1623 function AppInsightsCore() {
1624 return _super.call(this) || this;
1625 }
1626 AppInsightsCore.prototype.initialize = function (config, extensions) {
1627 var _self = this;
1628 _self._notificationManager = new NotificationManager();
1629 _self.logger = new DiagnosticLogger(config);
1630 _self.config = config;
1631 _super.prototype.initialize.call(this, config, extensions, _self.logger, _self._notificationManager);
1632 };
1633 AppInsightsCore.prototype.getTransmissionControls = function () {
1634 return _super.prototype.getTransmissionControls.call(this);
1635 };
1636 AppInsightsCore.prototype.track = function (telemetryItem) {
1637 if (telemetryItem === null) {
1638 this._notifyInvalidEvent(telemetryItem);
1639 // throw error
1640 throw Error("Invalid telemetry item");
1641 }
1642 // do basic validation before sending it through the pipeline
1643 this._validateTelemetryItem(telemetryItem);
1644 _super.prototype.track.call(this, telemetryItem);
1645 };
1646 /**
1647 * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.
1648 * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be
1649 * called.
1650 * @param {INotificationListener} listener - An INotificationListener object.
1651 */
1652 AppInsightsCore.prototype.addNotificationListener = function (listener) {
1653 if (this._notificationManager) {
1654 this._notificationManager.addNotificationListener(listener);
1655 }
1656 };
1657 /**
1658 * Removes all instances of the listener.
1659 * @param {INotificationListener} listener - INotificationListener to remove.
1660 */
1661 AppInsightsCore.prototype.removeNotificationListener = function (listener) {
1662 if (this._notificationManager) {
1663 this._notificationManager.removeNotificationListener(listener);
1664 }
1665 };
1666 /**
1667 * Periodically check logger.queue for
1668 */
1669 AppInsightsCore.prototype.pollInternalLogs = function (eventName) {
1670 var _this = this;
1671 var interval = this.config.diagnosticLogInterval;
1672 if (!(interval > 0)) {
1673 interval = 10000;
1674 }
1675 return setInterval(function () {
1676 var _self = _this;
1677 var queue = _self.logger ? _self.logger.queue : [];
1678 CoreUtils.arrForEach(queue, function (logMessage) {
1679 var item = {
1680 name: eventName ? eventName : "InternalMessageId: " + logMessage.messageId,
1681 iKey: _self.config.instrumentationKey,
1682 time: CoreUtils.toISOString(new Date()),
1683 baseType: _InternalLogMessage.dataType,
1684 baseData: { message: logMessage.message }
1685 };
1686 _self.track(item);
1687 });
1688 queue.length = 0;
1689 }, interval);
1690 };
1691 AppInsightsCore.prototype._validateTelemetryItem = function (telemetryItem) {
1692 if (CoreUtils.isNullOrUndefined(telemetryItem.name)) {
1693 this._notifyInvalidEvent(telemetryItem);
1694 throw Error("telemetry name required");
1695 }
1696 };
1697 AppInsightsCore.prototype._notifyInvalidEvent = function (telemetryItem) {
1698 if (this._notificationManager) {
1699 this._notificationManager.eventsDiscarded([telemetryItem], EventsDiscardedReason.InvalidEvent);
1700 }
1701 };
1702 return AppInsightsCore;
1703 }(BaseCore));
1704
1705 var RequestHeaders = /** @class */ (function () {
1706 function RequestHeaders() {
1707 }
1708 /**
1709 * Request-Context header
1710 */
1711 RequestHeaders.requestContextHeader = "Request-Context";
1712 /**
1713 * Target instrumentation header that is added to the response and retrieved by the
1714 * calling application when processing incoming responses.
1715 */
1716 RequestHeaders.requestContextTargetKey = "appId";
1717 /**
1718 * Request-Context appId format
1719 */
1720 RequestHeaders.requestContextAppIdFormat = "appId=cid-v1:";
1721 /**
1722 * Request-Id header
1723 */
1724 RequestHeaders.requestIdHeader = "Request-Id";
1725 /**
1726 * W3C distributed tracing protocol header
1727 */
1728 RequestHeaders.traceParentHeader = "traceparent";
1729 /**
1730 * Sdk-Context header
1731 * If this header passed with appId in content then appId will be returned back by the backend.
1732 */
1733 RequestHeaders.sdkContextHeader = "Sdk-Context";
1734 /**
1735 * String to pass in header for requesting appId back from the backend.
1736 */
1737 RequestHeaders.sdkContextHeaderAppIdRequest = "appId";
1738 RequestHeaders.requestContextHeaderLowerCase = "request-context";
1739 return RequestHeaders;
1740 }());
1741
1742 var DataSanitizer = /** @class */ (function () {
1743 function DataSanitizer() {
1744 }
1745 DataSanitizer.sanitizeKeyAndAddUniqueness = function (logger, key, map) {
1746 var origLength = key.length;
1747 var field = DataSanitizer.sanitizeKey(logger, key);
1748 // validation truncated the length. We need to add uniqueness
1749 if (field.length !== origLength) {
1750 var i = 0;
1751 var uniqueField = field;
1752 while (map[uniqueField] !== undefined) {
1753 i++;
1754 uniqueField = field.substring(0, DataSanitizer.MAX_NAME_LENGTH - 3) + DataSanitizer.padNumber(i);
1755 }
1756 field = uniqueField;
1757 }
1758 return field;
1759 };
1760 DataSanitizer.sanitizeKey = function (logger, name) {
1761 var nameTrunc;
1762 if (name) {
1763 // Remove any leading or trailing whitepace
1764 name = DataSanitizer.trim(name.toString());
1765 // truncate the string to 150 chars
1766 if (name.length > DataSanitizer.MAX_NAME_LENGTH) {
1767 nameTrunc = name.substring(0, DataSanitizer.MAX_NAME_LENGTH);
1768 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.NameTooLong, "name is too long. It has been truncated to " + DataSanitizer.MAX_NAME_LENGTH + " characters.", { name: name }, true);
1769 }
1770 }
1771 return nameTrunc || name;
1772 };
1773 DataSanitizer.sanitizeString = function (logger, value, maxLength) {
1774 if (maxLength === void 0) { maxLength = DataSanitizer.MAX_STRING_LENGTH; }
1775 var valueTrunc;
1776 if (value) {
1777 maxLength = maxLength ? maxLength : DataSanitizer.MAX_STRING_LENGTH; // in case default parameters dont work
1778 value = DataSanitizer.trim(value);
1779 if (value.toString().length > maxLength) {
1780 valueTrunc = value.toString().substring(0, maxLength);
1781 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.StringValueTooLong, "string value is too long. It has been truncated to " + maxLength + " characters.", { value: value }, true);
1782 }
1783 }
1784 return valueTrunc || value;
1785 };
1786 DataSanitizer.sanitizeUrl = function (logger, url) {
1787 return DataSanitizer.sanitizeInput(logger, url, DataSanitizer.MAX_URL_LENGTH, _InternalMessageId.UrlTooLong);
1788 };
1789 DataSanitizer.sanitizeMessage = function (logger, message) {
1790 var messageTrunc;
1791 if (message) {
1792 if (message.length > DataSanitizer.MAX_MESSAGE_LENGTH) {
1793 messageTrunc = message.substring(0, DataSanitizer.MAX_MESSAGE_LENGTH);
1794 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.MessageTruncated, "message is too long, it has been truncated to " + DataSanitizer.MAX_MESSAGE_LENGTH + " characters.", { message: message }, true);
1795 }
1796 }
1797 return messageTrunc || message;
1798 };
1799 DataSanitizer.sanitizeException = function (logger, exception) {
1800 var exceptionTrunc;
1801 if (exception) {
1802 if (exception.length > DataSanitizer.MAX_EXCEPTION_LENGTH) {
1803 exceptionTrunc = exception.substring(0, DataSanitizer.MAX_EXCEPTION_LENGTH);
1804 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.ExceptionTruncated, "exception is too long, it has been truncated to " + DataSanitizer.MAX_EXCEPTION_LENGTH + " characters.", { exception: exception }, true);
1805 }
1806 }
1807 return exceptionTrunc || exception;
1808 };
1809 DataSanitizer.sanitizeProperties = function (logger, properties) {
1810 if (properties) {
1811 var tempProps = {};
1812 for (var prop in properties) {
1813 var value = properties[prop];
1814 if (CoreUtils.isObject(value) && hasJSON()) {
1815 // Stringify any part C properties
1816 try {
1817 value = getJSON().stringify(value);
1818 }
1819 catch (e) {
1820 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CannotSerializeObjectNonSerializable, "custom property is not valid", { exception: e }, true);
1821 }
1822 }
1823 value = DataSanitizer.sanitizeString(logger, value, DataSanitizer.MAX_PROPERTY_LENGTH);
1824 prop = DataSanitizer.sanitizeKeyAndAddUniqueness(logger, prop, tempProps);
1825 tempProps[prop] = value;
1826 }
1827 properties = tempProps;
1828 }
1829 return properties;
1830 };
1831 DataSanitizer.sanitizeMeasurements = function (logger, measurements) {
1832 if (measurements) {
1833 var tempMeasurements = {};
1834 for (var measure in measurements) {
1835 var value = measurements[measure];
1836 measure = DataSanitizer.sanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements);
1837 tempMeasurements[measure] = value;
1838 }
1839 measurements = tempMeasurements;
1840 }
1841 return measurements;
1842 };
1843 DataSanitizer.sanitizeId = function (logger, id) {
1844 return id ? DataSanitizer.sanitizeInput(logger, id, DataSanitizer.MAX_ID_LENGTH, _InternalMessageId.IdTooLong).toString() : id;
1845 };
1846 DataSanitizer.sanitizeInput = function (logger, input, maxLength, _msgId) {
1847 var inputTrunc;
1848 if (input) {
1849 input = DataSanitizer.trim(input);
1850 if (input.length > maxLength) {
1851 inputTrunc = input.substring(0, maxLength);
1852 logger.throwInternal(LoggingSeverity.WARNING, _msgId, "input is too long, it has been truncated to " + maxLength + " characters.", { data: input }, true);
1853 }
1854 }
1855 return inputTrunc || input;
1856 };
1857 DataSanitizer.padNumber = function (num) {
1858 var s = "00" + num;
1859 return s.substr(s.length - 3);
1860 };
1861 /**
1862 * helper method to trim strings (IE8 does not implement String.prototype.trim)
1863 */
1864 DataSanitizer.trim = function (str) {
1865 if (!CoreUtils.isString(str)) {
1866 return str;
1867 }
1868 return str.replace(/^\s+|\s+$/g, "");
1869 };
1870 /**
1871 * Max length allowed for custom names.
1872 */
1873 DataSanitizer.MAX_NAME_LENGTH = 150;
1874 /**
1875 * Max length allowed for Id field in page views.
1876 */
1877 DataSanitizer.MAX_ID_LENGTH = 128;
1878 /**
1879 * Max length allowed for custom values.
1880 */
1881 DataSanitizer.MAX_PROPERTY_LENGTH = 8192;
1882 /**
1883 * Max length allowed for names
1884 */
1885 DataSanitizer.MAX_STRING_LENGTH = 1024;
1886 /**
1887 * Max length allowed for url.
1888 */
1889 DataSanitizer.MAX_URL_LENGTH = 2048;
1890 /**
1891 * Max length allowed for messages.
1892 */
1893 DataSanitizer.MAX_MESSAGE_LENGTH = 32768;
1894 /**
1895 * Max length allowed for exceptions.
1896 */
1897 DataSanitizer.MAX_EXCEPTION_LENGTH = 32768;
1898 return DataSanitizer;
1899 }());
1900
1901 // Adding common usage of prototype as a string to enable indexed lookup to assist with minification
1902 var prototype$1 = "prototype";
1903 var _navigator = getNavigator();
1904 var _isString = CoreUtils.isString;
1905 var _uaDisallowsSameSiteNone = null;
1906 function _endsWith(value, search) {
1907 var len = value.length;
1908 var start = len - search.length;
1909 return value.substring(start >= 0 ? start : 0, len) === search;
1910 }
1911 var Util = /** @class */ (function () {
1912 function Util() {
1913 }
1914 Util.createDomEvent = function (eventName) {
1915 var event = null;
1916 if (CoreUtils.isFunction(Event)) {
1917 event = new Event(eventName);
1918 }
1919 else {
1920 var doc = getDocument();
1921 if (doc && doc.createEvent) {
1922 event = doc.createEvent("Event");
1923 event.initEvent(eventName, true, true);
1924 }
1925 }
1926 return event;
1927 };
1928 /*
1929 * Force the SDK not to use local and session storage
1930 */
1931 Util.disableStorage = function () {
1932 Util._canUseLocalStorage = false;
1933 Util._canUseSessionStorage = false;
1934 };
1935 /**
1936 * Gets the localStorage object if available
1937 * @return {Storage} - Returns the storage object if available else returns null
1938 */
1939 Util._getLocalStorageObject = function () {
1940 if (Util.canUseLocalStorage()) {
1941 return Util._getVerifiedStorageObject(StorageType.LocalStorage);
1942 }
1943 return null;
1944 };
1945 /**
1946 * Tests storage object (localStorage or sessionStorage) to verify that it is usable
1947 * More details here: https://mathiasbynens.be/notes/localstorage-pattern
1948 * @param storageType Type of storage
1949 * @return {Storage} Returns storage object verified that it is usable
1950 */
1951 Util._getVerifiedStorageObject = function (storageType) {
1952 var storage = null;
1953 var fail;
1954 var uid;
1955 try {
1956 if (CoreUtils.isNullOrUndefined(getGlobal())) {
1957 return null;
1958 }
1959 uid = new Date;
1960 storage = storageType === StorageType.LocalStorage ? getGlobalInst("localStorage") : getGlobalInst("sessionStorage");
1961 storage.setItem(uid.toString(), uid.toString());
1962 fail = storage.getItem(uid.toString()) !== uid.toString();
1963 storage.removeItem(uid.toString());
1964 if (fail) {
1965 storage = null;
1966 }
1967 }
1968 catch (exception) {
1969 storage = null;
1970 }
1971 return storage;
1972 };
1973 /**
1974 * Checks if endpoint URL is application insights internal injestion service URL.
1975 *
1976 * @param endpointUrl Endpoint URL to check.
1977 * @returns {boolean} True if if endpoint URL is application insights internal injestion service URL.
1978 */
1979 Util.isInternalApplicationInsightsEndpoint = function (endpointUrl) {
1980 return Util._internalEndpoints.indexOf(endpointUrl.toLowerCase()) !== -1;
1981 };
1982 /**
1983 * Check if the browser supports local storage.
1984 *
1985 * @returns {boolean} True if local storage is supported.
1986 */
1987 Util.canUseLocalStorage = function () {
1988 if (Util._canUseLocalStorage === undefined) {
1989 Util._canUseLocalStorage = !!Util._getVerifiedStorageObject(StorageType.LocalStorage);
1990 }
1991 return Util._canUseLocalStorage;
1992 };
1993 /**
1994 * Get an object from the browser's local storage
1995 *
1996 * @param {string} name - the name of the object to get from storage
1997 * @returns {string} The contents of the storage object with the given name. Null if storage is not supported.
1998 */
1999 Util.getStorage = function (logger, name) {
2000 var storage = Util._getLocalStorageObject();
2001 if (storage !== null) {
2002 try {
2003 return storage.getItem(name);
2004 }
2005 catch (e) {
2006 Util._canUseLocalStorage = false;
2007 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserCannotReadLocalStorage, "Browser failed read of local storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
2008 }
2009 }
2010 return null;
2011 };
2012 /**
2013 * Set the contents of an object in the browser's local storage
2014 *
2015 * @param {string} name - the name of the object to set in storage
2016 * @param {string} data - the contents of the object to set in storage
2017 * @returns {boolean} True if the storage object could be written.
2018 */
2019 Util.setStorage = function (logger, name, data) {
2020 var storage = Util._getLocalStorageObject();
2021 if (storage !== null) {
2022 try {
2023 storage.setItem(name, data);
2024 return true;
2025 }
2026 catch (e) {
2027 Util._canUseLocalStorage = false;
2028 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserCannotWriteLocalStorage, "Browser failed write to local storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
2029 }
2030 }
2031 return false;
2032 };
2033 /**
2034 * Remove an object from the browser's local storage
2035 *
2036 * @param {string} name - the name of the object to remove from storage
2037 * @returns {boolean} True if the storage object could be removed.
2038 */
2039 Util.removeStorage = function (logger, name) {
2040 var storage = Util._getLocalStorageObject();
2041 if (storage !== null) {
2042 try {
2043 storage.removeItem(name);
2044 return true;
2045 }
2046 catch (e) {
2047 Util._canUseLocalStorage = false;
2048 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserFailedRemovalFromLocalStorage, "Browser failed removal of local storage item. " + Util.getExceptionName(e), { exception: Util.dump(e) });
2049 }
2050 }
2051 return false;
2052 };
2053 /**
2054 * Gets the sessionStorage object if available
2055 * @return {Storage} - Returns the storage object if available else returns null
2056 */
2057 Util._getSessionStorageObject = function () {
2058 if (Util.canUseSessionStorage()) {
2059 return Util._getVerifiedStorageObject(StorageType.SessionStorage);
2060 }
2061 return null;
2062 };
2063 /**
2064 * Check if the browser supports session storage.
2065 *
2066 * @returns {boolean} True if session storage is supported.
2067 */
2068 Util.canUseSessionStorage = function () {
2069 if (Util._canUseSessionStorage === undefined) {
2070 Util._canUseSessionStorage = !!Util._getVerifiedStorageObject(StorageType.SessionStorage);
2071 }
2072 return Util._canUseSessionStorage;
2073 };
2074 /**
2075 * Gets the list of session storage keys
2076 *
2077 * @returns {string[]} List of session storage keys
2078 */
2079 Util.getSessionStorageKeys = function () {
2080 var keys = [];
2081 if (Util.canUseSessionStorage()) {
2082 for (var key in getGlobalInst("sessionStorage")) {
2083 keys.push(key);
2084 }
2085 }
2086 return keys;
2087 };
2088 /**
2089 * Get an object from the browser's session storage
2090 *
2091 * @param {string} name - the name of the object to get from storage
2092 * @returns {string} The contents of the storage object with the given name. Null if storage is not supported.
2093 */
2094 Util.getSessionStorage = function (logger, name) {
2095 var storage = Util._getSessionStorageObject();
2096 if (storage !== null) {
2097 try {
2098 return storage.getItem(name);
2099 }
2100 catch (e) {
2101 Util._canUseSessionStorage = false;
2102 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserCannotReadSessionStorage, "Browser failed read of session storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
2103 }
2104 }
2105 return null;
2106 };
2107 /**
2108 * Set the contents of an object in the browser's session storage
2109 *
2110 * @param {string} name - the name of the object to set in storage
2111 * @param {string} data - the contents of the object to set in storage
2112 * @returns {boolean} True if the storage object could be written.
2113 */
2114 Util.setSessionStorage = function (logger, name, data) {
2115 var storage = Util._getSessionStorageObject();
2116 if (storage !== null) {
2117 try {
2118 storage.setItem(name, data);
2119 return true;
2120 }
2121 catch (e) {
2122 Util._canUseSessionStorage = false;
2123 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserCannotWriteSessionStorage, "Browser failed write to session storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
2124 }
2125 }
2126 return false;
2127 };
2128 /**
2129 * Remove an object from the browser's session storage
2130 *
2131 * @param {string} name - the name of the object to remove from storage
2132 * @returns {boolean} True if the storage object could be removed.
2133 */
2134 Util.removeSessionStorage = function (logger, name) {
2135 var storage = Util._getSessionStorageObject();
2136 if (storage !== null) {
2137 try {
2138 storage.removeItem(name);
2139 return true;
2140 }
2141 catch (e) {
2142 Util._canUseSessionStorage = false;
2143 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserFailedRemovalFromSessionStorage, "Browser failed removal of session storage item. " + Util.getExceptionName(e), { exception: Util.dump(e) });
2144 }
2145 }
2146 return false;
2147 };
2148 /*
2149 * Force the SDK not to store and read any data from cookies
2150 */
2151 Util.disableCookies = function () {
2152 CoreUtils.disableCookies();
2153 };
2154 /*
2155 * helper method to tell if document.cookie object is available
2156 */
2157 Util.canUseCookies = function (logger) {
2158 if (CoreUtils._canUseCookies === undefined) {
2159 CoreUtils._canUseCookies = false;
2160 try {
2161 CoreUtils._canUseCookies = Util.document.cookie !== undefined;
2162 }
2163 catch (e) {
2164 logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CannotAccessCookie, "Cannot access document.cookie - " + Util.getExceptionName(e), { exception: Util.dump(e) });
2165 }
2166 }
2167 return CoreUtils._canUseCookies;
2168 };
2169 Util.disallowsSameSiteNone = function (userAgent) {
2170 if (!_isString(userAgent)) {
2171 return false;
2172 }
2173 // Cover all iOS based browsers here. This includes:
2174 // - Safari on iOS 12 for iPhone, iPod Touch, iPad
2175 // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
2176 // - Chrome on iOS 12 for iPhone, iPod Touch, iPad
2177 // All of which are broken by SameSite=None, because they use the iOS networking stack
2178 if (userAgent.indexOf("CPU iPhone OS 12") !== -1 || userAgent.indexOf("iPad; CPU OS 12") !== -1) {
2179 return true;
2180 }
2181 // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:
2182 // - Safari on Mac OS X
2183 // This does not include:
2184 // - Internal browser on Mac OS X
2185 // - Chrome on Mac OS X
2186 // - Chromium on Mac OS X
2187 // Because they do not use the Mac OS networking stack.
2188 if (userAgent.indexOf("Macintosh; Intel Mac OS X 10_14") !== -1 && userAgent.indexOf("Version/") !== -1 && userAgent.indexOf("Safari") !== -1) {
2189 return true;
2190 }
2191 // Cover Mac OS X internal browsers that use the Mac OS networking stack. This includes:
2192 // - Internal browser on Mac OS X
2193 // This does not include:
2194 // - Safari on Mac OS X
2195 // - Chrome on Mac OS X
2196 // - Chromium on Mac OS X
2197 // Because they do not use the Mac OS networking stack.
2198 if (userAgent.indexOf("Macintosh; Intel Mac OS X 10_14") !== -1 && _endsWith(userAgent, "AppleWebKit/605.1.15 (KHTML, like Gecko)")) {
2199 return true;
2200 }
2201 // Cover Chrome 50-69, because some versions are broken by SameSite=None, and none in this range require it.
2202 // Note: this covers some pre-Chromium Edge versions, but pre-Chromim Edge does not require SameSite=None, so this is fine.
2203 // Note: this regex applies to Windows, Mac OS X, and Linux, deliberately.
2204 if (userAgent.indexOf("Chrome/5") !== -1 || userAgent.indexOf("Chrome/6") !== -1) {
2205 return true;
2206 }
2207 // Unreal Engine runs Chromium 59, but does not advertise as Chrome until 4.23. Treat versions of Unreal
2208 // that don't specify their Chrome version as lacking support for SameSite=None.
2209 if (userAgent.indexOf("UnrealEngine") !== -1 && userAgent.indexOf("Chrome") === -1) {
2210 return true;
2211 }
2212 // UCBrowser < 12.13.2 ignores Set-Cookie headers with SameSite=None
2213 // NB: this rule isn't complete - you need regex to make a complete rule.
2214 // See: https://www.chromium.org/updates/same-site/incompatible-clients
2215 if (userAgent.indexOf("UCBrowser/12") !== -1 || userAgent.indexOf("UCBrowser/11") !== -1) {
2216 return true;
2217 }
2218 return false;
2219 };
2220 /**
2221 * helper method to set userId and sessionId cookie
2222 */
2223 Util.setCookie = function (logger, name, value, domain) {
2224 if (Util.canUseCookies(logger)) {
2225 var domainAttrib = "";
2226 var secureAttrib = "";
2227 if (domain) {
2228 domainAttrib = ";domain=" + domain;
2229 }
2230 var location_1 = getLocation();
2231 if (location_1 && location_1.protocol === "https:") {
2232 secureAttrib = ";secure";
2233 if (_uaDisallowsSameSiteNone === null) {
2234 _uaDisallowsSameSiteNone = Util.disallowsSameSiteNone((getNavigator() || {}).userAgent);
2235 }
2236 if (!_uaDisallowsSameSiteNone) {
2237 value = value + ";SameSite=None"; // SameSite can only be set on secure pages
2238 }
2239 }
2240 Util.document.cookie = name + "=" + value + domainAttrib + ";path=/" + secureAttrib;
2241 }
2242 };
2243 Util.stringToBoolOrDefault = function (str, defaultValue) {
2244 if (defaultValue === void 0) { defaultValue = false; }
2245 if (str === undefined || str === null) {
2246 return defaultValue;
2247 }
2248 return str.toString().toLowerCase() === "true";
2249 };
2250 /**
2251 * helper method to access userId and sessionId cookie
2252 */
2253 Util.getCookie = function (logger, name) {
2254 if (!Util.canUseCookies(logger)) {
2255 return;
2256 }
2257 var value = "";
2258 if (name && name.length) {
2259 var cookieName = name + "=";
2260 var cookies = Util.document.cookie.split(";");
2261 for (var i = 0; i < cookies.length; i++) {
2262 var cookie = cookies[i];
2263 cookie = Util.trim(cookie);
2264 if (cookie && cookie.indexOf(cookieName) === 0) {
2265 value = cookie.substring(cookieName.length, cookies[i].length);
2266 break;
2267 }
2268 }
2269 }
2270 return value;
2271 };
2272 /**
2273 * Deletes a cookie by setting it's expiration time in the past.
2274 * @param name - The name of the cookie to delete.
2275 */
2276 Util.deleteCookie = function (logger, name) {
2277 if (Util.canUseCookies(logger)) {
2278 // Setting the expiration date in the past immediately removes the cookie
2279 Util.document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
2280 }
2281 };
2282 /**
2283 * helper method to trim strings (IE8 does not implement String.prototype.trim)
2284 */
2285 Util.trim = function (str) {
2286 if (!_isString(str)) {
2287 return str;
2288 }
2289 return str.replace(/^\s+|\s+$/g, "");
2290 };
2291 /**
2292 * generate random id string
2293 */
2294 Util.newId = function () {
2295 var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2296 var result = "";
2297 // tslint:disable-next-line:insecure-random
2298 var random = Math.random() * 1073741824; // 5 symbols in base64, almost maxint
2299 while (random > 0) {
2300 var char = base64chars.charAt(random % 64);
2301 result += char;
2302 random = Math.floor(random / 64);
2303 }
2304 return result;
2305 };
2306 /**
2307 * generate a random 32bit number (-0x80000000..0x7FFFFFFF).
2308 */
2309 Util.random32 = function () {
2310 return (0x100000000 * Math.random()) | 0;
2311 };
2312 /**
2313 * generate W3C trace id
2314 */
2315 Util.generateW3CId = function () {
2316 var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
2317 // rfc4122 version 4 UUID without dashes and with lowercase letters
2318 var oct = "", tmp;
2319 for (var a = 0; a < 4; a++) {
2320 tmp = Util.random32();
2321 oct +=
2322 hexValues[tmp & 0xF] +
2323 hexValues[tmp >> 4 & 0xF] +
2324 hexValues[tmp >> 8 & 0xF] +
2325 hexValues[tmp >> 12 & 0xF] +
2326 hexValues[tmp >> 16 & 0xF] +
2327 hexValues[tmp >> 20 & 0xF] +
2328 hexValues[tmp >> 24 & 0xF] +
2329 hexValues[tmp >> 28 & 0xF];
2330 }
2331 // "Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively"
2332 var clockSequenceHi = hexValues[8 + (Math.random() * 4) | 0];
2333 return oct.substr(0, 8) + oct.substr(9, 4) + "4" + oct.substr(13, 3) + clockSequenceHi + oct.substr(16, 3) + oct.substr(19, 12);
2334 };
2335 /**
2336 * Check if an object is of type Array
2337 */
2338 Util.isArray = function (obj) {
2339 return Object[prototype$1].toString.call(obj) === "[object Array]";
2340 };
2341 /**
2342 * Check if an object is of type Error
2343 */
2344 Util.isError = function (obj) {
2345 return Object[prototype$1].toString.call(obj) === "[object Error]";
2346 };
2347 /**
2348 * Gets IE version if we are running on IE, or null otherwise
2349 */
2350 Util.getIEVersion = function (userAgentStr) {
2351 if (userAgentStr === void 0) { userAgentStr = null; }
2352 var myNav = userAgentStr ? userAgentStr.toLowerCase() : (_navigator ? (_navigator.userAgent || "").toLowerCase() : "");
2353 return (myNav.indexOf('msie') !== -1) ? parseInt(myNav.split('msie')[1]) : null;
2354 };
2355 /**
2356 * Convert ms to c# time span format
2357 */
2358 Util.msToTimeSpan = function (totalms) {
2359 if (isNaN(totalms) || totalms < 0) {
2360 totalms = 0;
2361 }
2362 totalms = Math.round(totalms);
2363 var ms = "" + totalms % 1000;
2364 var sec = "" + Math.floor(totalms / 1000) % 60;
2365 var min = "" + Math.floor(totalms / (1000 * 60)) % 60;
2366 var hour = "" + Math.floor(totalms / (1000 * 60 * 60)) % 24;
2367 var days = Math.floor(totalms / (1000 * 60 * 60 * 24));
2368 ms = ms.length === 1 ? "00" + ms : ms.length === 2 ? "0" + ms : ms;
2369 sec = sec.length < 2 ? "0" + sec : sec;
2370 min = min.length < 2 ? "0" + min : min;
2371 hour = hour.length < 2 ? "0" + hour : hour;
2372 return (days > 0 ? days + "." : "") + hour + ":" + min + ":" + sec + "." + ms;
2373 };
2374 /**
2375 * Checks if error has no meaningful data inside. Ususally such errors are received by window.onerror when error
2376 * happens in a script from other domain (cross origin, CORS).
2377 */
2378 Util.isCrossOriginError = function (message, url, lineNumber, columnNumber, error) {
2379 return (message === "Script error." || message === "Script error") && !error;
2380 };
2381 /**
2382 * Returns string representation of an object suitable for diagnostics logging.
2383 */
2384 Util.dump = function (object) {
2385 var objectTypeDump = Object[prototype$1].toString.call(object);
2386 var propertyValueDump = "";
2387 if (objectTypeDump === "[object Error]") {
2388 propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'";
2389 }
2390 else if (hasJSON()) {
2391 propertyValueDump = getJSON().stringify(object);
2392 }
2393 return objectTypeDump + propertyValueDump;
2394 };
2395 /**
2396 * Returns the name of object if it's an Error. Otherwise, returns empty string.
2397 */
2398 Util.getExceptionName = function (object) {
2399 var objectTypeDump = Object[prototype$1].toString.call(object);
2400 if (objectTypeDump === "[object Error]") {
2401 return object.name;
2402 }
2403 return "";
2404 };
2405 /**
2406 * Adds an event handler for the specified event to the window
2407 * @param eventName {string} - The name of the event
2408 * @param callback {any} - The callback function that needs to be executed for the given event
2409 * @return {boolean} - true if the handler was successfully added
2410 */
2411 Util.addEventHandler = function (eventName, callback) {
2412 return EventHelper.Attach(getWindow(), eventName, callback);
2413 };
2414 /**
2415 * Tells if a browser supports a Beacon API
2416 */
2417 Util.IsBeaconApiSupported = function () {
2418 return ('sendBeacon' in _navigator && _navigator.sendBeacon);
2419 };
2420 Util.getExtension = function (extensions, identifier) {
2421 var extension = null;
2422 var extIx = 0;
2423 while (!extension && extIx < extensions.length) {
2424 if (extensions[extIx] && extensions[extIx].identifier === identifier) {
2425 extension = extensions[extIx];
2426 }
2427 extIx++;
2428 }
2429 return extension;
2430 };
2431 Util.document = getDocument() || {};
2432 Util._canUseLocalStorage = undefined;
2433 Util._canUseSessionStorage = undefined;
2434 // listing only non-geo specific locations
2435 Util._internalEndpoints = [
2436 "https://dc.services.visualstudio.com/v2/track",
2437 "https://breeze.aimon.applicationinsights.io/v2/track",
2438 "https://dc-int.services.visualstudio.com/v2/track"
2439 ];
2440 Util.NotSpecified = "not_specified";
2441 /**
2442 * Check if an object is of type Date
2443 */
2444 Util.isDate = CoreUtils.isDate;
2445 // Keeping this name for backward compatibility (for now)
2446 Util.toISOStringForIE8 = CoreUtils.toISOString;
2447 return Util;
2448 }());
2449 var UrlHelper = /** @class */ (function () {
2450 function UrlHelper() {
2451 }
2452 UrlHelper.parseUrl = function (url) {
2453 if (!UrlHelper.htmlAnchorElement) {
2454 UrlHelper.htmlAnchorElement = !!UrlHelper.document.createElement ? UrlHelper.document.createElement('a') : { host: UrlHelper.parseHost(url) }; // fill host field in the fallback case as that is the only externally required field from this fn
2455 }
2456 UrlHelper.htmlAnchorElement.href = url;
2457 return UrlHelper.htmlAnchorElement;
2458 };
2459 UrlHelper.getAbsoluteUrl = function (url) {
2460 var result;
2461 var a = UrlHelper.parseUrl(url);
2462 if (a) {
2463 result = a.href;
2464 }
2465 return result;
2466 };
2467 UrlHelper.getPathName = function (url) {
2468 var result;
2469 var a = UrlHelper.parseUrl(url);
2470 if (a) {
2471 result = a.pathname;
2472 }
2473 return result;
2474 };
2475 UrlHelper.getCompleteUrl = function (method, absoluteUrl) {
2476 if (method) {
2477 return method.toUpperCase() + " " + absoluteUrl;
2478 }
2479 else {
2480 return absoluteUrl;
2481 }
2482 };
2483 // Fallback method to grab host from url if document.createElement method is not available
2484 UrlHelper.parseHost = function (url) {
2485 if (url) {
2486 var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
2487 if (match != null && match.length > 2 && _isString(match[2]) && match[2].length > 0) {
2488 return match[2];
2489 }
2490 }
2491 return null;
2492 };
2493 UrlHelper.document = getDocument() || {};
2494 return UrlHelper;
2495 }());
2496 var CorrelationIdHelper = /** @class */ (function () {
2497 function CorrelationIdHelper() {
2498 }
2499 /**
2500 * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers.
2501 * Headers are always included if the current domain matches the request domain. If they do not match (CORS),
2502 * they are regexed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included.
2503 * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must
2504 * manually supply domains to include correlation headers on. Else, no headers will be included at all.
2505 */
2506 CorrelationIdHelper.canIncludeCorrelationHeader = function (config, requestUrl, currentHost) {
2507 if (config && config.disableCorrelationHeaders) {
2508 return false;
2509 }
2510 if (!requestUrl) {
2511 return false;
2512 }
2513 var requestHost = UrlHelper.parseUrl(requestUrl).host.toLowerCase();
2514 if ((!config || !config.enableCorsCorrelation) && requestHost !== currentHost) {
2515 return false;
2516 }
2517 var includedDomains = config && config.correlationHeaderDomains;
2518 if (includedDomains) {
2519 var matchExists_1;
2520 CoreUtils.arrForEach(includedDomains, function (domain) {
2521 var regex = new RegExp(domain.toLowerCase().replace(/\./g, "\.").replace(/\*/g, ".*"));
2522 matchExists_1 = matchExists_1 || regex.test(requestHost);
2523 });
2524 if (!matchExists_1) {
2525 return false;
2526 }
2527 }
2528 var excludedDomains = config && config.correlationHeaderExcludedDomains;
2529 if (!excludedDomains || excludedDomains.length === 0) {
2530 return true;
2531 }
2532 for (var i = 0; i < excludedDomains.length; i++) {
2533 var regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\./g, "\.").replace(/\*/g, ".*"));
2534 if (regex.test(requestHost)) {
2535 return false;
2536 }
2537 }
2538 // if we don't know anything about the requestHost, require the user to use included/excludedDomains.
2539 // Previously we always returned false for a falsy requestHost
2540 return requestHost && requestHost.length > 0;
2541 };
2542 /**
2543 * Combines target appId and target role name from response header.
2544 */
2545 CorrelationIdHelper.getCorrelationContext = function (responseHeader) {
2546 if (responseHeader) {
2547 var correlationId = CorrelationIdHelper.getCorrelationContextValue(responseHeader, RequestHeaders.requestContextTargetKey);
2548 if (correlationId && correlationId !== CorrelationIdHelper.correlationIdPrefix) {
2549 return correlationId;
2550 }
2551 }
2552 };
2553 /**
2554 * Gets key from correlation response header
2555 */
2556 CorrelationIdHelper.getCorrelationContextValue = function (responseHeader, key) {
2557 if (responseHeader) {
2558 var keyValues = responseHeader.split(",");
2559 for (var i = 0; i < keyValues.length; ++i) {
2560 var keyValue = keyValues[i].split("=");
2561 if (keyValue.length === 2 && keyValue[0] === key) {
2562 return keyValue[1];
2563 }
2564 }
2565 }
2566 };
2567 CorrelationIdHelper.correlationIdPrefix = "cid-v1:";
2568 return CorrelationIdHelper;
2569 }());
2570 var AjaxHelper = /** @class */ (function () {
2571 function AjaxHelper() {
2572 }
2573 AjaxHelper.ParseDependencyPath = function (logger, absoluteUrl, method, commandName) {
2574 var target, name = commandName, data = commandName;
2575 if (absoluteUrl && absoluteUrl.length > 0) {
2576 var parsedUrl = UrlHelper.parseUrl(absoluteUrl);
2577 target = parsedUrl.host;
2578 if (!name) {
2579 if (parsedUrl.pathname != null) {
2580 var pathName = (parsedUrl.pathname.length === 0) ? "/" : parsedUrl.pathname;
2581 if (pathName.charAt(0) !== '/') {
2582 pathName = "/" + pathName;
2583 }
2584 data = parsedUrl.pathname;
2585 name = DataSanitizer.sanitizeString(logger, method ? method + " " + pathName : pathName);
2586 }
2587 else {
2588 name = DataSanitizer.sanitizeString(logger, absoluteUrl);
2589 }
2590 }
2591 }
2592 else {
2593 target = commandName;
2594 name = commandName;
2595 }
2596 return {
2597 target: target,
2598 name: name,
2599 data: data
2600 };
2601 };
2602 return AjaxHelper;
2603 }());
2604 /**
2605 * A utility class that helps getting time related parameters
2606 */
2607 var DateTimeUtils = /** @class */ (function () {
2608 function DateTimeUtils() {
2609 }
2610 /**
2611 * Get the number of milliseconds since 1970/01/01 in local timezone
2612 */
2613 DateTimeUtils.Now = function () {
2614 // returns the window or webworker performance object
2615 var perf = getPerformance();
2616 if (perf && perf.now && perf.timing) {
2617 return perf.now() + perf.timing.navigationStart;
2618 }
2619 return new Date().getTime();
2620 };
2621 /**
2622 * Gets duration between two timestamps
2623 */
2624 DateTimeUtils.GetDuration = function (start, end) {
2625 var result = null;
2626 if (start !== 0 && end !== 0 && !CoreUtils.isNullOrUndefined(start) && !CoreUtils.isNullOrUndefined(end)) {
2627 result = end - start;
2628 }
2629 return result;
2630 };
2631 return DateTimeUtils;
2632 }());
2633
2634 var DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation";
2635 var SampleRate = "sampleRate";
2636 var ProcessLegacy = "ProcessLegacy";
2637 var HttpMethod = "http.method";
2638 var DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com";
2639
2640 var ConnectionStringParser = /** @class */ (function () {
2641 function ConnectionStringParser() {
2642 }
2643 ConnectionStringParser.parse = function (connectionString) {
2644 if (!connectionString) {
2645 return {};
2646 }
2647 var kvPairs = connectionString.split(ConnectionStringParser._FIELDS_SEPARATOR);
2648 var result = CoreUtils.arrReduce(kvPairs, function (fields, kv) {
2649 var kvParts = kv.split(ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR);
2650 if (kvParts.length === 2) {
2651 var key = kvParts[0].toLowerCase();
2652 var value = kvParts[1];
2653 fields[key] = value;
2654 }
2655 return fields;
2656 }, {});
2657 if (CoreUtils.objKeys(result).length > 0) {
2658 // this is a valid connection string, so parse the results
2659 if (result.endpointsuffix) {
2660 // use endpoint suffix where overrides are not provided
2661 var locationPrefix = result.location ? result.location + "." : "";
2662 result.ingestionendpoint = result.ingestionendpoint || ("https://" + locationPrefix + "dc." + result.endpointsuffix);
2663 }
2664 // apply the default endpoints
2665 result.ingestionendpoint = result.ingestionendpoint || DEFAULT_BREEZE_ENDPOINT;
2666 }
2667 return result;
2668 };
2669 ConnectionStringParser._FIELDS_SEPARATOR = ";";
2670 ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR = "=";
2671 return ConnectionStringParser;
2672 }());
2673
2674 // THIS FILE WAS AUTOGENERATED
2675 /**
2676 * Data struct to contain only C section with custom fields.
2677 */
2678 var Base = /** @class */ (function () {
2679 function Base() {
2680 }
2681 return Base;
2682 }());
2683
2684 /**
2685 * Data struct to contain both B and C sections.
2686 */
2687 var Data = /** @class */ (function (_super) {
2688 __extends(Data, _super);
2689 function Data() {
2690 return _super.call(this) || this;
2691 }
2692 return Data;
2693 }(Base));
2694
2695 /**
2696 * System variables for a telemetry item.
2697 */
2698 var Envelope = /** @class */ (function () {
2699 function Envelope() {
2700 this.ver = 1;
2701 this.sampleRate = 100.0;
2702 this.tags = {};
2703 }
2704 return Envelope;
2705 }());
2706
2707 var Envelope$1 = /** @class */ (function (_super) {
2708 __extends(Envelope$$1, _super);
2709 /**
2710 * Constructs a new instance of telemetry data.
2711 */
2712 function Envelope$$1(logger, data, name) {
2713 var _this = _super.call(this) || this;
2714 _this.name = DataSanitizer.sanitizeString(logger, name) || Util.NotSpecified;
2715 _this.data = data;
2716 _this.time = CoreUtils.toISOString(new Date());
2717 _this.aiDataContract = {
2718 time: FieldType.Required,
2719 iKey: FieldType.Required,
2720 name: FieldType.Required,
2721 sampleRate: function () {
2722 return (_this.sampleRate === 100) ? FieldType.Hidden : FieldType.Required;
2723 },
2724 tags: FieldType.Required,
2725 data: FieldType.Required
2726 };
2727 return _this;
2728 }
2729 return Envelope$$1;
2730 }(Envelope));
2731
2732 // THIS FILE WAS AUTOGENERATED
2733 /**
2734 * The abstract common base of all domains.
2735 */
2736 var Domain = /** @class */ (function () {
2737 function Domain() {
2738 }
2739 return Domain;
2740 }());
2741
2742 /**
2743 * Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name.
2744 */
2745 var EventData = /** @class */ (function (_super) {
2746 __extends(EventData, _super);
2747 function EventData() {
2748 var _this = _super.call(this) || this;
2749 _this.ver = 2;
2750 _this.properties = {};
2751 _this.measurements = {};
2752 return _this;
2753 }
2754 return EventData;
2755 }(Domain));
2756
2757 var Event$1 = /** @class */ (function (_super) {
2758 __extends(Event, _super);
2759 /**
2760 * Constructs a new instance of the EventTelemetry object
2761 */
2762 function Event(logger, name, properties, measurements) {
2763 var _this = _super.call(this) || this;
2764 _this.aiDataContract = {
2765 ver: FieldType.Required,
2766 name: FieldType.Required,
2767 properties: FieldType.Default,
2768 measurements: FieldType.Default
2769 };
2770 _this.name = DataSanitizer.sanitizeString(logger, name) || Util.NotSpecified;
2771 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
2772 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
2773 return _this;
2774 }
2775 Event.envelopeType = "Microsoft.ApplicationInsights.{0}.Event";
2776 Event.dataType = "EventData";
2777 return Event;
2778 }(EventData));
2779
2780 // THIS FILE WAS AUTOGENERATED
2781 /**
2782 * Stack frame information.
2783 */
2784 var StackFrame = /** @class */ (function () {
2785 function StackFrame() {
2786 }
2787 return StackFrame;
2788 }());
2789
2790 /**
2791 * An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application.
2792 */
2793 var ExceptionData = /** @class */ (function (_super) {
2794 __extends(ExceptionData, _super);
2795 function ExceptionData() {
2796 var _this = _super.call(this) || this;
2797 _this.ver = 2;
2798 _this.exceptions = [];
2799 _this.properties = {};
2800 _this.measurements = {};
2801 return _this;
2802 }
2803 return ExceptionData;
2804 }(Domain));
2805
2806 /**
2807 * Exception details of the exception in a chain.
2808 */
2809 var ExceptionDetails = /** @class */ (function () {
2810 function ExceptionDetails() {
2811 this.hasFullStack = true;
2812 this.parsedStack = [];
2813 }
2814 return ExceptionDetails;
2815 }());
2816
2817 var Exception = /** @class */ (function (_super) {
2818 __extends(Exception, _super);
2819 /**
2820 * Constructs a new instance of the ExceptionTelemetry object
2821 */
2822 function Exception(logger, exception, properties, measurements, severityLevel, id) {
2823 var _this = _super.call(this) || this;
2824 _this.aiDataContract = {
2825 ver: FieldType.Required,
2826 exceptions: FieldType.Required,
2827 severityLevel: FieldType.Default,
2828 properties: FieldType.Default,
2829 measurements: FieldType.Default
2830 };
2831 if (exception instanceof Error) {
2832 _this.exceptions = [new _ExceptionDetails(logger, exception)];
2833 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
2834 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
2835 if (severityLevel) {
2836 _this.severityLevel = severityLevel;
2837 }
2838 if (id) {
2839 _this.id = id;
2840 }
2841 }
2842 else {
2843 _this.exceptions = exception.exceptions;
2844 _this.properties = exception.properties;
2845 _this.measurements = exception.measurements;
2846 if (exception.severityLevel) {
2847 _this.severityLevel = exception.severityLevel;
2848 }
2849 if (exception.id) {
2850 _this.id = exception.id;
2851 }
2852 if (exception.problemGroup) {
2853 _this.problemGroup = exception.problemGroup;
2854 }
2855 // bool/int types, use isNullOrUndefined
2856 _this.ver = 2; // TODO: handle the CS"4.0" ==> breeze 2 conversion in a better way
2857 if (!CoreUtils.isNullOrUndefined(exception.isManual)) {
2858 _this.isManual = exception.isManual;
2859 }
2860 }
2861 return _this;
2862 }
2863 Exception.CreateFromInterface = function (logger, exception) {
2864 var exceptions = exception.exceptions
2865 && CoreUtils.arrMap(exception.exceptions, function (ex) { return _ExceptionDetails.CreateFromInterface(logger, ex); });
2866 var exceptionData = new Exception(logger, __assign({}, exception, { exceptions: exceptions }));
2867 return exceptionData;
2868 };
2869 Exception.prototype.toInterface = function () {
2870 var _a = this, exceptions = _a.exceptions, properties = _a.properties, measurements = _a.measurements, severityLevel = _a.severityLevel, ver = _a.ver, problemGroup = _a.problemGroup, id = _a.id, isManual = _a.isManual;
2871 var exceptionDetailsInterface = exceptions instanceof Array
2872 && CoreUtils.arrMap(exceptions, function (exception) { return exception.toInterface(); })
2873 || undefined;
2874 return {
2875 ver: "4.0",
2876 exceptions: exceptionDetailsInterface,
2877 severityLevel: severityLevel,
2878 properties: properties,
2879 measurements: measurements,
2880 problemGroup: problemGroup,
2881 id: id,
2882 isManual: isManual
2883 };
2884 };
2885 /**
2886 * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.
2887 */
2888 Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) {
2889 return {
2890 exceptions: [
2891 {
2892 hasFullStack: true,
2893 message: message,
2894 stack: details,
2895 typeName: typeName
2896 }
2897 ]
2898 };
2899 };
2900 Exception.envelopeType = "Microsoft.ApplicationInsights.{0}.Exception";
2901 Exception.dataType = "ExceptionData";
2902 return Exception;
2903 }(ExceptionData));
2904 var _ExceptionDetails = /** @class */ (function (_super) {
2905 __extends(_ExceptionDetails, _super);
2906 function _ExceptionDetails(logger, exception) {
2907 var _this = _super.call(this) || this;
2908 _this.aiDataContract = {
2909 id: FieldType.Default,
2910 outerId: FieldType.Default,
2911 typeName: FieldType.Required,
2912 message: FieldType.Required,
2913 hasFullStack: FieldType.Default,
2914 stack: FieldType.Default,
2915 parsedStack: FieldType.Array
2916 };
2917 if (exception instanceof Error) {
2918 _this.typeName = DataSanitizer.sanitizeString(logger, exception.name) || Util.NotSpecified;
2919 _this.message = DataSanitizer.sanitizeMessage(logger, exception.message) || Util.NotSpecified;
2920 var stack = exception.stack;
2921 _this.parsedStack = _ExceptionDetails.parseStack(stack);
2922 _this.stack = DataSanitizer.sanitizeException(logger, stack);
2923 _this.hasFullStack = Util.isArray(_this.parsedStack) && _this.parsedStack.length > 0;
2924 }
2925 else {
2926 _this.typeName = exception.typeName;
2927 _this.message = exception.message;
2928 _this.stack = exception.stack;
2929 _this.parsedStack = exception.parsedStack;
2930 _this.hasFullStack = exception.hasFullStack;
2931 }
2932 return _this;
2933 }
2934 _ExceptionDetails.prototype.toInterface = function () {
2935 var parsedStack = this.parsedStack instanceof Array
2936 && CoreUtils.arrMap(this.parsedStack, function (frame) { return frame.toInterface(); });
2937 var exceptionDetailsInterface = {
2938 id: this.id,
2939 outerId: this.outerId,
2940 typeName: this.typeName,
2941 message: this.message,
2942 hasFullStack: this.hasFullStack,
2943 stack: this.stack,
2944 parsedStack: parsedStack || undefined
2945 };
2946 return exceptionDetailsInterface;
2947 };
2948 _ExceptionDetails.CreateFromInterface = function (logger, exception) {
2949 var parsedStack = (exception.parsedStack instanceof Array
2950 && CoreUtils.arrMap(exception.parsedStack, function (frame) { return _StackFrame.CreateFromInterface(frame); }))
2951 || exception.parsedStack;
2952 var exceptionDetails = new _ExceptionDetails(logger, __assign({}, exception, { parsedStack: parsedStack }));
2953 return exceptionDetails;
2954 };
2955 _ExceptionDetails.parseStack = function (stack) {
2956 var parsedStack;
2957 if (CoreUtils.isString(stack)) {
2958 var frames_1 = stack.split('\n');
2959 parsedStack = [];
2960 var level = 0;
2961 var totalSizeInBytes = 0;
2962 for (var i = 0; i <= frames_1.length; i++) {
2963 var frame = frames_1[i];
2964 if (_StackFrame.regex.test(frame)) {
2965 var parsedFrame = new _StackFrame(frames_1[i], level++);
2966 totalSizeInBytes += parsedFrame.sizeInBytes;
2967 parsedStack.push(parsedFrame);
2968 }
2969 }
2970 // DP Constraint - exception parsed stack must be < 32KB
2971 // remove frames from the middle to meet the threshold
2972 var exceptionParsedStackThreshold = 32 * 1024;
2973 if (totalSizeInBytes > exceptionParsedStackThreshold) {
2974 var left = 0;
2975 var right = parsedStack.length - 1;
2976 var size = 0;
2977 var acceptedLeft = left;
2978 var acceptedRight = right;
2979 while (left < right) {
2980 // check size
2981 var lSize = parsedStack[left].sizeInBytes;
2982 var rSize = parsedStack[right].sizeInBytes;
2983 size += lSize + rSize;
2984 if (size > exceptionParsedStackThreshold) {
2985 // remove extra frames from the middle
2986 var howMany = acceptedRight - acceptedLeft + 1;
2987 parsedStack.splice(acceptedLeft, howMany);
2988 break;
2989 }
2990 // update pointers
2991 acceptedLeft = left;
2992 acceptedRight = right;
2993 left++;
2994 right--;
2995 }
2996 }
2997 }
2998 return parsedStack;
2999 };
3000 return _ExceptionDetails;
3001 }(ExceptionDetails));
3002 var _StackFrame = /** @class */ (function (_super) {
3003 __extends(_StackFrame, _super);
3004 function _StackFrame(sourceFrame, level) {
3005 var _this = _super.call(this) || this;
3006 _this.sizeInBytes = 0;
3007 _this.aiDataContract = {
3008 level: FieldType.Required,
3009 method: FieldType.Required,
3010 assembly: FieldType.Default,
3011 fileName: FieldType.Default,
3012 line: FieldType.Default
3013 };
3014 // Not converting this to CoreUtils.isString() as typescript uses this logic to "understand" the different
3015 // types for the 2 different code paths
3016 if (typeof sourceFrame === "string") {
3017 var frame = sourceFrame;
3018 _this.level = level;
3019 _this.method = "<no_method>";
3020 _this.assembly = Util.trim(frame);
3021 _this.fileName = "";
3022 _this.line = 0;
3023 var matches = frame.match(_StackFrame.regex);
3024 if (matches && matches.length >= 5) {
3025 _this.method = Util.trim(matches[2]) || _this.method;
3026 _this.fileName = Util.trim(matches[4]);
3027 _this.line = parseInt(matches[5]) || 0;
3028 }
3029 }
3030 else {
3031 _this.level = sourceFrame.level;
3032 _this.method = sourceFrame.method;
3033 _this.assembly = sourceFrame.assembly;
3034 _this.fileName = sourceFrame.fileName;
3035 _this.line = sourceFrame.line;
3036 _this.sizeInBytes = 0;
3037 }
3038 _this.sizeInBytes += _this.method.length;
3039 _this.sizeInBytes += _this.fileName.length;
3040 _this.sizeInBytes += _this.assembly.length;
3041 // todo: these might need to be removed depending on how the back-end settles on their size calculation
3042 _this.sizeInBytes += _StackFrame.baseSize;
3043 _this.sizeInBytes += _this.level.toString().length;
3044 _this.sizeInBytes += _this.line.toString().length;
3045 return _this;
3046 }
3047 _StackFrame.CreateFromInterface = function (frame) {
3048 return new _StackFrame(frame, null /* level is available in frame interface */);
3049 };
3050 _StackFrame.prototype.toInterface = function () {
3051 return {
3052 level: this.level,
3053 method: this.method,
3054 assembly: this.assembly,
3055 fileName: this.fileName,
3056 line: this.line
3057 };
3058 };
3059 // regex to match stack frames from ie/chrome/ff
3060 // methodName=$2, fileName=$4, lineNo=$5, column=$6
3061 _StackFrame.regex = /^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/;
3062 _StackFrame.baseSize = 58; // '{"method":"","level":,"assembly":"","fileName":"","line":}'.length
3063 return _StackFrame;
3064 }(StackFrame));
3065
3066 /**
3067 * An instance of the Metric item is a list of measurements (single data points) and/or aggregations.
3068 */
3069 var MetricData = /** @class */ (function (_super) {
3070 __extends(MetricData, _super);
3071 function MetricData() {
3072 var _this = _super.call(this) || this;
3073 _this.ver = 2;
3074 _this.metrics = [];
3075 _this.properties = {};
3076 _this.measurements = {};
3077 return _this;
3078 }
3079 return MetricData;
3080 }(Domain));
3081
3082 // THIS FILE WAS AUTOGENERATED
3083 /**
3084 * Type of the metric data measurement.
3085 */
3086 var DataPointType;
3087 (function (DataPointType) {
3088 DataPointType[DataPointType["Measurement"] = 0] = "Measurement";
3089 DataPointType[DataPointType["Aggregation"] = 1] = "Aggregation";
3090 })(DataPointType || (DataPointType = {}));
3091
3092 /**
3093 * Metric data single measurement.
3094 */
3095 var DataPoint = /** @class */ (function () {
3096 function DataPoint() {
3097 this.kind = DataPointType.Measurement;
3098 }
3099 return DataPoint;
3100 }());
3101
3102 var DataPoint$1 = /** @class */ (function (_super) {
3103 __extends(DataPoint$$1, _super);
3104 function DataPoint$$1() {
3105 var _this = _super !== null && _super.apply(this, arguments) || this;
3106 /**
3107 * The data contract for serializing this object.
3108 */
3109 _this.aiDataContract = {
3110 name: FieldType.Required,
3111 kind: FieldType.Default,
3112 value: FieldType.Required,
3113 count: FieldType.Default,
3114 min: FieldType.Default,
3115 max: FieldType.Default,
3116 stdDev: FieldType.Default
3117 };
3118 return _this;
3119 }
3120 return DataPoint$$1;
3121 }(DataPoint));
3122
3123 var Metric = /** @class */ (function (_super) {
3124 __extends(Metric, _super);
3125 /**
3126 * Constructs a new instance of the MetricTelemetry object
3127 */
3128 function Metric(logger, name, value, count, min, max, properties, measurements) {
3129 var _this = _super.call(this) || this;
3130 _this.aiDataContract = {
3131 ver: FieldType.Required,
3132 metrics: FieldType.Required,
3133 properties: FieldType.Default
3134 };
3135 var dataPoint = new DataPoint$1();
3136 dataPoint.count = count > 0 ? count : undefined;
3137 dataPoint.max = isNaN(max) || max === null ? undefined : max;
3138 dataPoint.min = isNaN(min) || min === null ? undefined : min;
3139 dataPoint.name = DataSanitizer.sanitizeString(logger, name) || Util.NotSpecified;
3140 dataPoint.value = value;
3141 _this.metrics = [dataPoint];
3142 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
3143 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
3144 return _this;
3145 }
3146 Metric.envelopeType = "Microsoft.ApplicationInsights.{0}.Metric";
3147 Metric.dataType = "MetricData";
3148 return Metric;
3149 }(MetricData));
3150
3151 /**
3152 * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView.
3153 */
3154 var PageViewData = /** @class */ (function (_super) {
3155 __extends(PageViewData, _super);
3156 function PageViewData() {
3157 var _this = _super.call(this) || this;
3158 _this.ver = 2;
3159 _this.properties = {};
3160 _this.measurements = {};
3161 return _this;
3162 }
3163 return PageViewData;
3164 }(EventData));
3165
3166 var PageView = /** @class */ (function (_super) {
3167 __extends(PageView, _super);
3168 /**
3169 * Constructs a new instance of the PageEventTelemetry object
3170 */
3171 function PageView(logger, name, url, durationMs, properties, measurements, id) {
3172 var _this = _super.call(this) || this;
3173 _this.aiDataContract = {
3174 ver: FieldType.Required,
3175 name: FieldType.Default,
3176 url: FieldType.Default,
3177 duration: FieldType.Default,
3178 properties: FieldType.Default,
3179 measurements: FieldType.Default,
3180 id: FieldType.Default
3181 };
3182 _this.id = DataSanitizer.sanitizeId(logger, id);
3183 _this.url = DataSanitizer.sanitizeUrl(logger, url);
3184 _this.name = DataSanitizer.sanitizeString(logger, name) || Util.NotSpecified;
3185 if (!isNaN(durationMs)) {
3186 _this.duration = Util.msToTimeSpan(durationMs);
3187 }
3188 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
3189 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
3190 return _this;
3191 }
3192 PageView.envelopeType = "Microsoft.ApplicationInsights.{0}.Pageview";
3193 PageView.dataType = "PageviewData";
3194 return PageView;
3195 }(PageViewData));
3196
3197 /**
3198 * An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint.
3199 */
3200 var RemoteDependencyData = /** @class */ (function (_super) {
3201 __extends(RemoteDependencyData, _super);
3202 function RemoteDependencyData() {
3203 var _this = _super.call(this) || this;
3204 _this.ver = 2;
3205 _this.success = true;
3206 _this.properties = {};
3207 _this.measurements = {};
3208 return _this;
3209 }
3210 return RemoteDependencyData;
3211 }(Domain));
3212
3213 var RemoteDependencyData$1 = /** @class */ (function (_super) {
3214 __extends(RemoteDependencyData$$1, _super);
3215 /**
3216 * Constructs a new instance of the RemoteDependencyData object
3217 */
3218 function RemoteDependencyData$$1(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) {
3219 if (requestAPI === void 0) { requestAPI = "Ajax"; }
3220 var _this = _super.call(this) || this;
3221 _this.aiDataContract = {
3222 id: FieldType.Required,
3223 ver: FieldType.Required,
3224 name: FieldType.Default,
3225 resultCode: FieldType.Default,
3226 duration: FieldType.Default,
3227 success: FieldType.Default,
3228 data: FieldType.Default,
3229 target: FieldType.Default,
3230 type: FieldType.Default,
3231 properties: FieldType.Default,
3232 measurements: FieldType.Default,
3233 kind: FieldType.Default,
3234 value: FieldType.Default,
3235 count: FieldType.Default,
3236 min: FieldType.Default,
3237 max: FieldType.Default,
3238 stdDev: FieldType.Default,
3239 dependencyKind: FieldType.Default,
3240 dependencySource: FieldType.Default,
3241 commandName: FieldType.Default,
3242 dependencyTypeName: FieldType.Default
3243 };
3244 _this.id = id;
3245 _this.duration = Util.msToTimeSpan(value);
3246 _this.success = success;
3247 _this.resultCode = resultCode + "";
3248 _this.type = DataSanitizer.sanitizeString(logger, requestAPI);
3249 var dependencyFields = AjaxHelper.ParseDependencyPath(logger, absoluteUrl, method, commandName);
3250 _this.data = DataSanitizer.sanitizeUrl(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available
3251 _this.target = DataSanitizer.sanitizeString(logger, dependencyFields.target);
3252 if (correlationContext) {
3253 _this.target = _this.target + " | " + correlationContext;
3254 }
3255 _this.name = DataSanitizer.sanitizeString(logger, dependencyFields.name);
3256 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
3257 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
3258 return _this;
3259 }
3260 RemoteDependencyData$$1.envelopeType = "Microsoft.ApplicationInsights.{0}.RemoteDependency";
3261 RemoteDependencyData$$1.dataType = "RemoteDependencyData";
3262 return RemoteDependencyData$$1;
3263 }(RemoteDependencyData));
3264
3265 /**
3266 * Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements.
3267 */
3268 var MessageData = /** @class */ (function (_super) {
3269 __extends(MessageData, _super);
3270 function MessageData() {
3271 var _this = _super.call(this) || this;
3272 _this.ver = 2;
3273 _this.properties = {};
3274 _this.measurements = {};
3275 return _this;
3276 }
3277 return MessageData;
3278 }(Domain));
3279
3280 var Trace = /** @class */ (function (_super) {
3281 __extends(Trace, _super);
3282 /**
3283 * Constructs a new instance of the TraceTelemetry object
3284 */
3285 function Trace(logger, message, severityLevel, properties, measurements) {
3286 var _this = _super.call(this) || this;
3287 _this.aiDataContract = {
3288 ver: FieldType.Required,
3289 message: FieldType.Required,
3290 severityLevel: FieldType.Default,
3291 properties: FieldType.Default
3292 };
3293 message = message || Util.NotSpecified;
3294 _this.message = DataSanitizer.sanitizeMessage(logger, message);
3295 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
3296 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
3297 if (severityLevel) {
3298 _this.severityLevel = severityLevel;
3299 }
3300 return _this;
3301 }
3302 Trace.envelopeType = "Microsoft.ApplicationInsights.{0}.Message";
3303 Trace.dataType = "MessageData";
3304 return Trace;
3305 }(MessageData));
3306
3307 /**
3308 * An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request.
3309 */
3310 var PageViewPerfData = /** @class */ (function (_super) {
3311 __extends(PageViewPerfData, _super);
3312 function PageViewPerfData() {
3313 var _this = _super.call(this) || this;
3314 _this.ver = 2;
3315 _this.properties = {};
3316 _this.measurements = {};
3317 return _this;
3318 }
3319 return PageViewPerfData;
3320 }(PageViewData));
3321
3322 var PageViewPerformance = /** @class */ (function (_super) {
3323 __extends(PageViewPerformance, _super);
3324 /**
3325 * Constructs a new instance of the PageEventTelemetry object
3326 */
3327 function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) {
3328 var _this = _super.call(this) || this;
3329 _this.aiDataContract = {
3330 ver: FieldType.Required,
3331 name: FieldType.Default,
3332 url: FieldType.Default,
3333 duration: FieldType.Default,
3334 perfTotal: FieldType.Default,
3335 networkConnect: FieldType.Default,
3336 sentRequest: FieldType.Default,
3337 receivedResponse: FieldType.Default,
3338 domProcessing: FieldType.Default,
3339 properties: FieldType.Default,
3340 measurements: FieldType.Default
3341 };
3342 _this.url = DataSanitizer.sanitizeUrl(logger, url);
3343 _this.name = DataSanitizer.sanitizeString(logger, name) || Util.NotSpecified;
3344 _this.properties = DataSanitizer.sanitizeProperties(logger, properties);
3345 _this.measurements = DataSanitizer.sanitizeMeasurements(logger, measurements);
3346 if (cs4BaseData) {
3347 _this.domProcessing = cs4BaseData.domProcessing;
3348 _this.duration = cs4BaseData.duration;
3349 _this.networkConnect = cs4BaseData.networkConnect;
3350 _this.perfTotal = cs4BaseData.perfTotal;
3351 _this.receivedResponse = cs4BaseData.receivedResponse;
3352 _this.sentRequest = cs4BaseData.sentRequest;
3353 }
3354 return _this;
3355 }
3356 PageViewPerformance.envelopeType = "Microsoft.ApplicationInsights.{0}.PageviewPerformance";
3357 PageViewPerformance.dataType = "PageviewPerformanceData";
3358 return PageViewPerformance;
3359 }(PageViewPerfData));
3360
3361 var Data$1 = /** @class */ (function (_super) {
3362 __extends(Data$$1, _super);
3363 /**
3364 * Constructs a new instance of telemetry data.
3365 */
3366 function Data$$1(baseType, data) {
3367 var _this = _super.call(this) || this;
3368 /**
3369 * The data contract for serializing this object.
3370 */
3371 _this.aiDataContract = {
3372 baseType: FieldType.Required,
3373 baseData: FieldType.Required
3374 };
3375 _this.baseType = baseType;
3376 _this.baseData = data;
3377 return _this;
3378 }
3379 return Data$$1;
3380 }(Data));
3381
3382 // THIS FILE WAS AUTOGENERATED
3383 /**
3384 * Defines the level of severity for the event.
3385 */
3386 var SeverityLevel;
3387 (function (SeverityLevel) {
3388 SeverityLevel[SeverityLevel["Verbose"] = 0] = "Verbose";
3389 SeverityLevel[SeverityLevel["Information"] = 1] = "Information";
3390 SeverityLevel[SeverityLevel["Warning"] = 2] = "Warning";
3391 SeverityLevel[SeverityLevel["Error"] = 3] = "Error";
3392 SeverityLevel[SeverityLevel["Critical"] = 4] = "Critical";
3393 })(SeverityLevel || (SeverityLevel = {}));
3394
3395 var ConfigurationManager = /** @class */ (function () {
3396 function ConfigurationManager() {
3397 }
3398 ConfigurationManager.getConfig = function (config, field, identifier, defaultValue) {
3399 if (defaultValue === void 0) { defaultValue = false; }
3400 var configValue;
3401 if (identifier && config.extensionConfig && config.extensionConfig[identifier] && !CoreUtils.isNullOrUndefined(config.extensionConfig[identifier][field])) {
3402 configValue = config.extensionConfig[identifier][field];
3403 }
3404 else {
3405 configValue = config[field];
3406 }
3407 return !CoreUtils.isNullOrUndefined(configValue) ? configValue : defaultValue;
3408 };
3409 return ConfigurationManager;
3410 }());
3411
3412 // THIS FILE WAS AUTOGENERATED
3413 var ContextTagKeys = /** @class */ (function () {
3414 function ContextTagKeys() {
3415 this.applicationVersion = "ai.application.ver";
3416 this.applicationBuild = "ai.application.build";
3417 this.applicationTypeId = "ai.application.typeId";
3418 this.applicationId = "ai.application.applicationId";
3419 this.applicationLayer = "ai.application.layer";
3420 this.deviceId = "ai.device.id";
3421 this.deviceIp = "ai.device.ip";
3422 this.deviceLanguage = "ai.device.language";
3423 this.deviceLocale = "ai.device.locale";
3424 this.deviceModel = "ai.device.model";
3425 this.deviceFriendlyName = "ai.device.friendlyName";
3426 this.deviceNetwork = "ai.device.network";
3427 this.deviceNetworkName = "ai.device.networkName";
3428 this.deviceOEMName = "ai.device.oemName";
3429 this.deviceOS = "ai.device.os";
3430 this.deviceOSVersion = "ai.device.osVersion";
3431 this.deviceRoleInstance = "ai.device.roleInstance";
3432 this.deviceRoleName = "ai.device.roleName";
3433 this.deviceScreenResolution = "ai.device.screenResolution";
3434 this.deviceType = "ai.device.type";
3435 this.deviceMachineName = "ai.device.machineName";
3436 this.deviceVMName = "ai.device.vmName";
3437 this.deviceBrowser = "ai.device.browser";
3438 this.deviceBrowserVersion = "ai.device.browserVersion";
3439 this.locationIp = "ai.location.ip";
3440 this.locationCountry = "ai.location.country";
3441 this.locationProvince = "ai.location.province";
3442 this.locationCity = "ai.location.city";
3443 this.operationId = "ai.operation.id";
3444 this.operationName = "ai.operation.name";
3445 this.operationParentId = "ai.operation.parentId";
3446 this.operationRootId = "ai.operation.rootId";
3447 this.operationSyntheticSource = "ai.operation.syntheticSource";
3448 this.operationCorrelationVector = "ai.operation.correlationVector";
3449 this.sessionId = "ai.session.id";
3450 this.sessionIsFirst = "ai.session.isFirst";
3451 this.sessionIsNew = "ai.session.isNew";
3452 this.userAccountAcquisitionDate = "ai.user.accountAcquisitionDate";
3453 this.userAccountId = "ai.user.accountId";
3454 this.userAgent = "ai.user.userAgent";
3455 this.userId = "ai.user.id";
3456 this.userStoreRegion = "ai.user.storeRegion";
3457 this.userAuthUserId = "ai.user.authUserId";
3458 this.userAnonymousUserAcquisitionDate = "ai.user.anonUserAcquisitionDate";
3459 this.userAuthenticatedUserAcquisitionDate = "ai.user.authUserAcquisitionDate";
3460 this.cloudName = "ai.cloud.name";
3461 this.cloudRole = "ai.cloud.role";
3462 this.cloudRoleVer = "ai.cloud.roleVer";
3463 this.cloudRoleInstance = "ai.cloud.roleInstance";
3464 this.cloudEnvironment = "ai.cloud.environment";
3465 this.cloudLocation = "ai.cloud.location";
3466 this.cloudDeploymentUnit = "ai.cloud.deploymentUnit";
3467 this.internalNodeName = "ai.internal.nodeName";
3468 this.internalSdkVersion = "ai.internal.sdkVersion";
3469 this.internalAgentVersion = "ai.internal.agentVersion";
3470 }
3471 return ContextTagKeys;
3472 }());
3473
3474 var TelemetryItemCreator = /** @class */ (function () {
3475 function TelemetryItemCreator() {
3476 }
3477 /**
3478 * Create a telemetry item that the 1DS channel understands
3479 * @param item domain specific properties; part B
3480 * @param baseType telemetry item type. ie PageViewData
3481 * @param envelopeName name of the envelope. ie Microsoft.ApplicationInsights.<instrumentation key>.PageView
3482 * @param customProperties user defined custom properties; part C
3483 * @param systemProperties system properties that are added to the context; part A
3484 * @returns ITelemetryItem that is sent to channel
3485 */
3486 TelemetryItemCreator.create = function (item, baseType, envelopeName, logger, customProperties, systemProperties) {
3487 envelopeName = DataSanitizer.sanitizeString(logger, envelopeName) || Util.NotSpecified;
3488 if (CoreUtils.isNullOrUndefined(item) ||
3489 CoreUtils.isNullOrUndefined(baseType) ||
3490 CoreUtils.isNullOrUndefined(envelopeName)) {
3491 throw Error("Input doesn't contain all required fields");
3492 }
3493 var telemetryItem = {
3494 name: envelopeName,
3495 time: CoreUtils.toISOString(new Date()),
3496 iKey: "",
3497 ext: systemProperties ? systemProperties : {},
3498 tags: [],
3499 data: {},
3500 baseType: baseType,
3501 baseData: item // Part B
3502 };
3503 // Part C
3504 if (!CoreUtils.isNullOrUndefined(customProperties)) {
3505 for (var prop in customProperties) {
3506 if (customProperties.hasOwnProperty(prop)) {
3507 telemetryItem.data[prop] = customProperties[prop];
3508 }
3509 }
3510 }
3511 return telemetryItem;
3512 };
3513 return TelemetryItemCreator;
3514 }());
3515
3516 var Extensions = /** @class */ (function () {
3517 function Extensions() {
3518 }
3519 Extensions.UserExt = "user";
3520 Extensions.DeviceExt = "device";
3521 Extensions.TraceExt = "trace";
3522 Extensions.WebExt = "web";
3523 Extensions.AppExt = "app";
3524 Extensions.OSExt = "os";
3525 Extensions.SessionExt = "ses";
3526 Extensions.SDKExt = "sdk";
3527 return Extensions;
3528 }());
3529 var CtxTagKeys = new ContextTagKeys();
3530
3531 var PropertiesPluginIdentifier = "AppInsightsPropertiesPlugin";
3532 var BreezeChannelIdentifier = "AppInsightsChannelPlugin";
3533
3534 var Common = /*#__PURE__*/(function(obj) { /* ai_es3_polyfil freeze */ var func = Object["freeze"]; if (func) { return func(obj); } return obj; })({
3535 PropertiesPluginIdentifier: PropertiesPluginIdentifier,
3536 BreezeChannelIdentifier: BreezeChannelIdentifier,
3537 Util: Util,
3538 CorrelationIdHelper: CorrelationIdHelper,
3539 UrlHelper: UrlHelper,
3540 DateTimeUtils: DateTimeUtils,
3541 ConnectionStringParser: ConnectionStringParser,
3542 FieldType: (function(obj) { /* ai_es3polyfil get FieldType */ if (obj == null || typeof obj !== "object") { return obj; } var cpy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } } return cpy; })(FieldType),
3543 RequestHeaders: RequestHeaders,
3544 DisabledPropertyName: DisabledPropertyName,
3545 ProcessLegacy: ProcessLegacy,
3546 SampleRate: SampleRate,
3547 HttpMethod: HttpMethod,
3548 DEFAULT_BREEZE_ENDPOINT: DEFAULT_BREEZE_ENDPOINT,
3549 AIData: Data,
3550 AIBase: Base,
3551 Envelope: Envelope$1,
3552 Event: Event$1,
3553 Exception: Exception,
3554 Metric: Metric,
3555 PageView: PageView,
3556 PageViewData: PageViewData,
3557 RemoteDependencyData: RemoteDependencyData$1,
3558 Trace: Trace,
3559 PageViewPerformance: PageViewPerformance,
3560 Data: Data$1,
3561 SeverityLevel: (function(obj) { /* ai_es3polyfil get SeverityLevel */ if (obj == null || typeof obj !== "object") { return obj; } var cpy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } } return cpy; })(SeverityLevel),
3562 ConfigurationManager: ConfigurationManager,
3563 ContextTagKeys: ContextTagKeys,
3564 DataSanitizer: DataSanitizer,
3565 TelemetryItemCreator: TelemetryItemCreator,
3566 CtxTagKeys: CtxTagKeys,
3567 Extensions: Extensions,
3568 DistributedTracingModes: (function(obj) { /* ai_es3polyfil get DistributedTracingModes */ if (obj == null || typeof obj !== "object") { return obj; } var cpy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { cpy[attr] = obj[attr]; } } return cpy; })(DistributedTracingModes)
3569 });
3570
3571 // ToDo: fix properties and measurements once updates are done to common
3572 var AppInsightsDeprecated = /** @class */ (function () {
3573 function AppInsightsDeprecated(snippet, appInsightsNew) {
3574 this._hasLegacyInitializers = false;
3575 this._queue = [];
3576 this.config = AppInsightsDeprecated.getDefaultConfig(snippet.config);
3577 this.appInsightsNew = appInsightsNew;
3578 this.context = { addTelemetryInitializer: this.addTelemetryInitializers.bind(this) };
3579 }
3580 AppInsightsDeprecated.getDefaultConfig = function (config) {
3581 if (!config) {
3582 config = {};
3583 }
3584 // set default values
3585 config.endpointUrl = config.endpointUrl || "https://dc.services.visualstudio.com/v2/track";
3586 config.sessionRenewalMs = 30 * 60 * 1000;
3587 config.sessionExpirationMs = 24 * 60 * 60 * 1000;
3588 config.maxBatchSizeInBytes = config.maxBatchSizeInBytes > 0 ? config.maxBatchSizeInBytes : 102400; // 100kb
3589 config.maxBatchInterval = !isNaN(config.maxBatchInterval) ? config.maxBatchInterval : 15000;
3590 config.enableDebug = Util.stringToBoolOrDefault(config.enableDebug);
3591 config.disableExceptionTracking = Util.stringToBoolOrDefault(config.disableExceptionTracking);
3592 config.disableTelemetry = Util.stringToBoolOrDefault(config.disableTelemetry);
3593 config.verboseLogging = Util.stringToBoolOrDefault(config.verboseLogging);
3594 config.emitLineDelimitedJson = Util.stringToBoolOrDefault(config.emitLineDelimitedJson);
3595 config.diagnosticLogInterval = config.diagnosticLogInterval || 10000;
3596 config.autoTrackPageVisitTime = Util.stringToBoolOrDefault(config.autoTrackPageVisitTime);
3597 if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
3598 config.samplingPercentage = 100;
3599 }
3600 config.disableAjaxTracking = Util.stringToBoolOrDefault(config.disableAjaxTracking);
3601 config.maxAjaxCallsPerView = !isNaN(config.maxAjaxCallsPerView) ? config.maxAjaxCallsPerView : 500;
3602 config.isBeaconApiDisabled = Util.stringToBoolOrDefault(config.isBeaconApiDisabled, true);
3603 config.disableCorrelationHeaders = Util.stringToBoolOrDefault(config.disableCorrelationHeaders);
3604 config.correlationHeaderExcludedDomains = config.correlationHeaderExcludedDomains || [
3605 "*.blob.core.windows.net",
3606 "*.blob.core.chinacloudapi.cn",
3607 "*.blob.core.cloudapi.de",
3608 "*.blob.core.usgovcloudapi.net"
3609 ];
3610 config.disableFlushOnBeforeUnload = Util.stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
3611 config.disableFlushOnUnload = Util.stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
3612 config.enableSessionStorageBuffer = Util.stringToBoolOrDefault(config.enableSessionStorageBuffer, true);
3613 config.isRetryDisabled = Util.stringToBoolOrDefault(config.isRetryDisabled);
3614 config.isCookieUseDisabled = Util.stringToBoolOrDefault(config.isCookieUseDisabled);
3615 config.isStorageUseDisabled = Util.stringToBoolOrDefault(config.isStorageUseDisabled);
3616 config.isBrowserLinkTrackingEnabled = Util.stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
3617 config.enableCorsCorrelation = Util.stringToBoolOrDefault(config.enableCorsCorrelation);
3618 return config;
3619 };
3620 /**
3621 * The array of telemetry initializers to call before sending each telemetry item.
3622 */
3623 AppInsightsDeprecated.prototype.addTelemetryInitializers = function (callBack) {
3624 var _this = this;
3625 // Add initializer to current processing only if there is any old telemetry initializer
3626 if (!this._hasLegacyInitializers) {
3627 this.appInsightsNew.addTelemetryInitializer(function (item) {
3628 _this._processLegacyInitializers(item); // setup call back for each legacy processor
3629 });
3630 this._hasLegacyInitializers = true;
3631 }
3632 this._queue.push(callBack);
3633 };
3634 AppInsightsDeprecated.prototype.startTrackPage = function (name) {
3635 this.appInsightsNew.startTrackPage(name);
3636 };
3637 AppInsightsDeprecated.prototype.stopTrackPage = function (name, url, properties, measurements) {
3638 this.appInsightsNew.stopTrackPage(name, url, properties); // update
3639 };
3640 AppInsightsDeprecated.prototype.trackPageView = function (name, url, properties, measurements, duration) {
3641 var telemetry = {
3642 name: name,
3643 uri: url,
3644 properties: properties,
3645 measurements: measurements
3646 };
3647 // fix for props, measurements, duration
3648 this.appInsightsNew.trackPageView(telemetry);
3649 };
3650 AppInsightsDeprecated.prototype.trackEvent = function (name, properties, measurements) {
3651 this.appInsightsNew.trackEvent({ name: name });
3652 };
3653 AppInsightsDeprecated.prototype.trackDependency = function (id, method, absoluteUrl, pathName, totalTime, success, resultCode) {
3654 this.appInsightsNew.trackDependencyData({
3655 id: id,
3656 target: absoluteUrl,
3657 type: pathName,
3658 duration: totalTime,
3659 properties: { HttpMethod: method },
3660 success: success,
3661 responseCode: resultCode
3662 });
3663 };
3664 AppInsightsDeprecated.prototype.trackException = function (exception, handledAt, properties, measurements, severityLevel) {
3665 this.appInsightsNew.trackException({
3666 exception: exception
3667 });
3668 };
3669 AppInsightsDeprecated.prototype.trackMetric = function (name, average, sampleCount, min, max, properties) {
3670 this.appInsightsNew.trackMetric({ name: name, average: average, sampleCount: sampleCount, min: min, max: max });
3671 };
3672 AppInsightsDeprecated.prototype.trackTrace = function (message, properties, severityLevel) {
3673 this.appInsightsNew.trackTrace({ message: message, severityLevel: severityLevel });
3674 };
3675 AppInsightsDeprecated.prototype.flush = function (async) {
3676 this.appInsightsNew.flush(async);
3677 };
3678 AppInsightsDeprecated.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {
3679 this.appInsightsNew.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId, storeInCookie);
3680 };
3681 AppInsightsDeprecated.prototype.clearAuthenticatedUserContext = function () {
3682 this.appInsightsNew.context.user.clearAuthenticatedUserContext();
3683 };
3684 AppInsightsDeprecated.prototype._onerror = function (message, url, lineNumber, columnNumber, error) {
3685 this.appInsightsNew._onerror({ message: message, url: url, lineNumber: lineNumber, columnNumber: columnNumber, error: error });
3686 };
3687 AppInsightsDeprecated.prototype.startTrackEvent = function (name) {
3688 this.appInsightsNew.startTrackEvent(name);
3689 };
3690 AppInsightsDeprecated.prototype.stopTrackEvent = function (name, properties, measurements) {
3691 this.appInsightsNew.stopTrackEvent(name, properties, measurements);
3692 };
3693 AppInsightsDeprecated.prototype.downloadAndSetup = function (config) {
3694 throw new Error("downloadAndSetup not implemented in web SKU");
3695 };
3696 AppInsightsDeprecated.prototype.updateSnippetDefinitions = function (snippet) {
3697 // apply full appInsights to the global instance
3698 // Note: This must be called before loadAppInsights is called
3699 for (var field in this) {
3700 if (typeof field === 'string') {
3701 snippet[field] = this[field];
3702 }
3703 }
3704 };
3705 // note: these are split into methods to enable unit tests
3706 AppInsightsDeprecated.prototype.loadAppInsights = function () {
3707 // initialize global instance of appInsights
3708 // var appInsights = new Microsoft.ApplicationInsights.AppInsights(this.config);
3709 var _this = this;
3710 // implement legacy version of trackPageView for 0.10<
3711 if (this.config["iKey"]) {
3712 var originalTrackPageView_1 = this.trackPageView;
3713 this.trackPageView = function (pagePath, properties, measurements) {
3714 originalTrackPageView_1.apply(_this, [null, pagePath, properties, measurements]);
3715 };
3716 }
3717 // implement legacy pageView interface if it is present in the snippet
3718 var legacyPageView = "logPageView";
3719 if (typeof this.snippet[legacyPageView] === "function") {
3720 this[legacyPageView] = function (pagePath, properties, measurements) {
3721 _this.trackPageView(null, pagePath, properties, measurements);
3722 };
3723 }
3724 // implement legacy event interface if it is present in the snippet
3725 var legacyEvent = "logEvent";
3726 if (typeof this.snippet[legacyEvent] === "function") {
3727 this[legacyEvent] = function (name, props, measurements) {
3728 _this.trackEvent(name, props, measurements);
3729 };
3730 }
3731 return this;
3732 };
3733 AppInsightsDeprecated.prototype._processLegacyInitializers = function (item) {
3734 // instead of mapping new to legacy and then back again and repeating in channel, attach callback for channel to call
3735 item.tags[ProcessLegacy] = this._queue;
3736 return item;
3737 };
3738 return AppInsightsDeprecated;
3739 }());
3740
3741 /**
3742 * Class encapsulates sending page views and page view performance telemetry.
3743 */
3744 var PageViewManager = /** @class */ (function () {
3745 function PageViewManager(appInsights, overridePageViewDuration, core, pageViewPerformanceManager) {
3746 this.pageViewPerformanceSent = false;
3747 this.overridePageViewDuration = false;
3748 this.overridePageViewDuration = overridePageViewDuration;
3749 this.appInsights = appInsights;
3750 this._pageViewPerformanceManager = pageViewPerformanceManager;
3751 if (core) {
3752 this._channel = function () { return (core.getTransmissionControls()); };
3753 this._logger = core.logger;
3754 }
3755 }
3756 /**
3757 * Currently supported cases:
3758 * 1) (default case) track page view called with default parameters, overridePageViewDuration = false. Page view is sent with page view performance when navigation timing data is available.
3759 * a. If navigation timing is not supported then page view is sent right away with undefined duration. Page view performance is not sent.
3760 * 2) overridePageViewDuration = true, custom duration provided. Custom duration is used, page view sends right away.
3761 * 3) overridePageViewDuration = true, custom duration NOT provided. Page view is sent right away, duration is time spent from page load till now (or undefined if navigation timing is not supported).
3762 * 4) overridePageViewDuration = false, custom duration is provided. Page view is sent right away with custom duration.
3763 *
3764 * In all cases page view performance is sent once (only for the 1st call of trackPageView), or not sent if navigation timing is not supported.
3765 */
3766 PageViewManager.prototype.trackPageView = function (pageView, customProperties) {
3767 var _this = this;
3768 var name = pageView.name;
3769 if (CoreUtils.isNullOrUndefined(name) || typeof name !== "string") {
3770 var doc = getDocument();
3771 name = pageView.name = doc && doc.title || "";
3772 }
3773 var uri = pageView.uri;
3774 if (CoreUtils.isNullOrUndefined(uri) || typeof uri !== "string") {
3775 var location_1 = getLocation();
3776 uri = pageView.uri = location_1 && location_1.href || "";
3777 }
3778 // case 1a. if performance timing is not supported by the browser, send the page view telemetry with the duration provided by the user. If the user
3779 // do not provide the duration, set duration to undefined
3780 // Also this is case 4
3781 if (!this._pageViewPerformanceManager.isPerformanceTimingSupported()) {
3782 this.appInsights.sendPageViewInternal(pageView, customProperties);
3783 CoreUtils.arrForEach(this._channel(), function (queues) { CoreUtils.arrForEach(queues, function (q) { return q.flush(true); }); });
3784 // no navigation timing (IE 8, iOS Safari 8.4, Opera Mini 8 - see http://caniuse.com/#feat=nav-timing)
3785 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.NavigationTimingNotSupported, "trackPageView: navigation timing API used for calculation of page duration is not supported in this browser. This page view will be collected without duration and timing info.");
3786 return;
3787 }
3788 var pageViewSent = false;
3789 var customDuration;
3790 // if the performance timing is supported by the browser, calculate the custom duration
3791 var start = this._pageViewPerformanceManager.getPerformanceTiming().navigationStart;
3792 customDuration = DateTimeUtils.GetDuration(start, +new Date);
3793 if (!this._pageViewPerformanceManager.shouldCollectDuration(customDuration)) {
3794 customDuration = undefined;
3795 }
3796 // if the user has provided duration, send a page view telemetry with the provided duration. Otherwise, if
3797 // overridePageViewDuration is set to true, send a page view telemetry with the custom duration calculated earlier
3798 var duration;
3799 if (!CoreUtils.isNullOrUndefined(customProperties) &&
3800 !CoreUtils.isNullOrUndefined(customProperties.duration)) {
3801 duration = customProperties.duration;
3802 }
3803 if (this.overridePageViewDuration || !isNaN(duration)) {
3804 if (isNaN(duration)) {
3805 // case 3
3806 if (!customProperties) {
3807 customProperties = {};
3808 }
3809 customProperties["duration"] = customDuration;
3810 }
3811 // case 2
3812 this.appInsights.sendPageViewInternal(pageView, customProperties);
3813 CoreUtils.arrForEach(this._channel(), function (queues) { CoreUtils.arrForEach(queues, function (q) { return q.flush(true); }); });
3814 pageViewSent = true;
3815 }
3816 // now try to send the page view performance telemetry
3817 var maxDurationLimit = 60000;
3818 if (!customProperties) {
3819 customProperties = {};
3820 }
3821 var handle = setInterval((function () {
3822 try {
3823 if (_this._pageViewPerformanceManager.isPerformanceTimingDataReady()) {
3824 clearInterval(handle);
3825 var pageViewPerformance = {
3826 name: name,
3827 uri: uri
3828 };
3829 _this._pageViewPerformanceManager.populatePageViewPerformanceEvent(pageViewPerformance);
3830 if (!pageViewPerformance.isValid && !pageViewSent) {
3831 // If navigation timing gives invalid numbers, then go back to "override page view duration" mode.
3832 // That's the best value we can get that makes sense.
3833 customProperties["duration"] = customDuration;
3834 _this.appInsights.sendPageViewInternal(pageView, customProperties);
3835 CoreUtils.arrForEach(_this._channel(), function (queues) { CoreUtils.arrForEach(queues, function (q) { return q.flush(true); }); });
3836 }
3837 else {
3838 if (!pageViewSent) {
3839 customProperties["duration"] = pageViewPerformance.durationMs;
3840 _this.appInsights.sendPageViewInternal(pageView, customProperties);
3841 }
3842 if (!_this.pageViewPerformanceSent) {
3843 _this.appInsights.sendPageViewPerformanceInternal(pageViewPerformance, customProperties);
3844 _this.pageViewPerformanceSent = true;
3845 }
3846 CoreUtils.arrForEach(_this._channel(), function (queues) { CoreUtils.arrForEach(queues, function (q) { return q.flush(true); }); });
3847 }
3848 }
3849 else if (DateTimeUtils.GetDuration(start, +new Date) > maxDurationLimit) {
3850 // if performance timings are not ready but we exceeded the maximum duration limit, just log a page view telemetry
3851 // with the maximum duration limit. Otherwise, keep waiting until performance timings are ready
3852 clearInterval(handle);
3853 if (!pageViewSent) {
3854 customProperties["duration"] = maxDurationLimit;
3855 _this.appInsights.sendPageViewInternal(pageView, customProperties);
3856 CoreUtils.arrForEach(_this._channel(), function (queues) { CoreUtils.arrForEach(queues, function (q) { return q.flush(true); }); });
3857 }
3858 }
3859 }
3860 catch (e) {
3861 _this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackPVFailedCalc, "trackPageView failed on page load calculation: " + Util.getExceptionName(e), { exception: Util.dump(e) });
3862 }
3863 }), 100);
3864 };
3865 return PageViewManager;
3866 }());
3867
3868 /**
3869 * Used to track page visit durations
3870 */
3871 var PageVisitTimeManager = /** @class */ (function () {
3872 /**
3873 * Creates a new instance of PageVisitTimeManager
3874 * @param pageVisitTimeTrackingHandler Delegate that will be called to send telemetry data to AI (when trackPreviousPageVisit is called)
3875 * @returns {}
3876 */
3877 function PageVisitTimeManager(logger, pageVisitTimeTrackingHandler) {
3878 this.prevPageVisitDataKeyName = "prevPageVisitData";
3879 this.pageVisitTimeTrackingHandler = pageVisitTimeTrackingHandler;
3880 this._logger = logger;
3881 }
3882 /**
3883 * Tracks the previous page visit time telemetry (if exists) and starts timing of new page visit time
3884 * @param currentPageName Name of page to begin timing for visit duration
3885 * @param currentPageUrl Url of page to begin timing for visit duration
3886 */
3887 PageVisitTimeManager.prototype.trackPreviousPageVisit = function (currentPageName, currentPageUrl) {
3888 try {
3889 // Restart timer for new page view
3890 var prevPageVisitTimeData = this.restartPageVisitTimer(currentPageName, currentPageUrl);
3891 // If there was a page already being timed, track the visit time for it now.
3892 if (prevPageVisitTimeData) {
3893 this.pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);
3894 }
3895 }
3896 catch (e) {
3897 this._logger.warnToConsole("Auto track page visit time failed, metric will not be collected: " + Util.dump(e));
3898 }
3899 };
3900 /**
3901 * Stops timing of current page (if exists) and starts timing for duration of visit to pageName
3902 * @param pageName Name of page to begin timing visit duration
3903 * @returns {PageVisitData} Page visit data (including duration) of pageName from last call to start or restart, if exists. Null if not.
3904 */
3905 PageVisitTimeManager.prototype.restartPageVisitTimer = function (pageName, pageUrl) {
3906 try {
3907 var prevPageVisitData = this.stopPageVisitTimer();
3908 this.startPageVisitTimer(pageName, pageUrl);
3909 return prevPageVisitData;
3910 }
3911 catch (e) {
3912 this._logger.warnToConsole("Call to restart failed: " + Util.dump(e));
3913 return null;
3914 }
3915 };
3916 /**
3917 * Starts timing visit duration of pageName
3918 * @param pageName
3919 * @returns {}
3920 */
3921 PageVisitTimeManager.prototype.startPageVisitTimer = function (pageName, pageUrl) {
3922 try {
3923 if (Util.canUseSessionStorage()) {
3924 if (Util.getSessionStorage(this._logger, this.prevPageVisitDataKeyName) != null) {
3925 throw new Error("Cannot call startPageVisit consecutively without first calling stopPageVisit");
3926 }
3927 var currPageVisitData = new PageVisitData(pageName, pageUrl);
3928 var currPageVisitDataStr = getJSON().stringify(currPageVisitData);
3929 Util.setSessionStorage(this._logger, this.prevPageVisitDataKeyName, currPageVisitDataStr);
3930 }
3931 }
3932 catch (e) {
3933 // TODO: Remove this catch in next phase, since if start is called twice in a row the exception needs to be propagated out
3934 this._logger.warnToConsole("Call to start failed: " + Util.dump(e));
3935 }
3936 };
3937 /**
3938 * Stops timing of current page, if exists.
3939 * @returns {PageVisitData} Page visit data (including duration) of pageName from call to start, if exists. Null if not.
3940 */
3941 PageVisitTimeManager.prototype.stopPageVisitTimer = function () {
3942 try {
3943 if (Util.canUseSessionStorage()) {
3944 // Define end time of page's visit
3945 var pageVisitEndTime = Date.now();
3946 // Try to retrieve page name and start time from session storage
3947 var pageVisitDataJsonStr = Util.getSessionStorage(this._logger, this.prevPageVisitDataKeyName);
3948 if (pageVisitDataJsonStr && hasJSON()) {
3949 // if previous page data exists, set end time of visit
3950 var prevPageVisitData = getJSON().parse(pageVisitDataJsonStr);
3951 prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData.pageVisitStartTime;
3952 // Remove data from storage since we already used it
3953 Util.removeSessionStorage(this._logger, this.prevPageVisitDataKeyName);
3954 // Return page visit data
3955 return prevPageVisitData;
3956 }
3957 else {
3958 return null;
3959 }
3960 }
3961 return null;
3962 }
3963 catch (e) {
3964 this._logger.warnToConsole("Stop page visit timer failed: " + Util.dump(e));
3965 return null;
3966 }
3967 };
3968 return PageVisitTimeManager;
3969 }());
3970 var PageVisitData = /** @class */ (function () {
3971 function PageVisitData(pageName, pageUrl) {
3972 this.pageVisitStartTime = Date.now();
3973 this.pageName = pageName;
3974 this.pageUrl = pageUrl;
3975 }
3976 return PageVisitData;
3977 }());
3978
3979 /**
3980 * Class encapsulates sending page view performance telemetry.
3981 */
3982 var PageViewPerformanceManager = /** @class */ (function () {
3983 function PageViewPerformanceManager(core) {
3984 this.MAX_DURATION_ALLOWED = 3600000; // 1h
3985 if (core) {
3986 this._logger = core.logger;
3987 }
3988 }
3989 PageViewPerformanceManager.prototype.populatePageViewPerformanceEvent = function (pageViewPerformance) {
3990 pageViewPerformance.isValid = false;
3991 /*
3992 * http://www.w3.org/TR/navigation-timing/#processing-model
3993 * |-navigationStart
3994 * | |-connectEnd
3995 * | ||-requestStart
3996 * | || |-responseStart
3997 * | || | |-responseEnd
3998 * | || | |
3999 * | || | | |-loadEventEnd
4000 * |---network---||---request---|---response---|---dom---|
4001 * |--------------------------total----------------------|
4002 */
4003 var navigationTiming = this.getPerformanceNavigationTiming();
4004 var timing = this.getPerformanceTiming();
4005 if (navigationTiming || timing) {
4006 if (navigationTiming) {
4007 var total = navigationTiming.duration;
4008 var network = DateTimeUtils.GetDuration(navigationTiming.startTime, navigationTiming.connectEnd);
4009 var request = DateTimeUtils.GetDuration(navigationTiming.requestStart, navigationTiming.responseStart);
4010 var response = DateTimeUtils.GetDuration(navigationTiming.responseStart, navigationTiming.responseEnd);
4011 var dom = DateTimeUtils.GetDuration(navigationTiming.responseEnd, navigationTiming.loadEventEnd);
4012 }
4013 else {
4014 var total = DateTimeUtils.GetDuration(timing.navigationStart, timing.loadEventEnd);
4015 var network = DateTimeUtils.GetDuration(timing.navigationStart, timing.connectEnd);
4016 var request = DateTimeUtils.GetDuration(timing.requestStart, timing.responseStart);
4017 var response = DateTimeUtils.GetDuration(timing.responseStart, timing.responseEnd);
4018 var dom = DateTimeUtils.GetDuration(timing.responseEnd, timing.loadEventEnd);
4019 }
4020 if (total === 0) {
4021 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.ErrorPVCalc, "error calculating page view performance.", { total: total, network: network, request: request, response: response, dom: dom });
4022 }
4023 else if (!this.shouldCollectDuration(total, network, request, response, dom)) {
4024 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.InvalidDurationValue, "Invalid page load duration value. Browser perf data won't be sent.", { total: total, network: network, request: request, response: response, dom: dom });
4025 }
4026 else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) {
4027 // some browsers may report individual components incorrectly so that the sum of the parts will be bigger than total PLT
4028 // in this case, don't report client performance from this page
4029 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.ClientPerformanceMathError, "client performance math error.", { total: total, network: network, request: request, response: response, dom: dom });
4030 }
4031 else {
4032 pageViewPerformance.durationMs = total;
4033 // // convert to timespans
4034 pageViewPerformance.perfTotal = pageViewPerformance.duration = Util.msToTimeSpan(total);
4035 pageViewPerformance.networkConnect = Util.msToTimeSpan(network);
4036 pageViewPerformance.sentRequest = Util.msToTimeSpan(request);
4037 pageViewPerformance.receivedResponse = Util.msToTimeSpan(response);
4038 pageViewPerformance.domProcessing = Util.msToTimeSpan(dom);
4039 pageViewPerformance.isValid = true;
4040 }
4041 }
4042 };
4043 PageViewPerformanceManager.prototype.getPerformanceTiming = function () {
4044 if (this.isPerformanceTimingSupported()) {
4045 return getPerformance().timing;
4046 }
4047 return null;
4048 };
4049 PageViewPerformanceManager.prototype.getPerformanceNavigationTiming = function () {
4050 if (this.isPerformanceNavigationTimingSupported()) {
4051 return getPerformance().getEntriesByType("navigation")[0];
4052 }
4053 return null;
4054 };
4055 /**
4056 * Returns true is window PerformanceNavigationTiming API is supported, false otherwise.
4057 */
4058 PageViewPerformanceManager.prototype.isPerformanceNavigationTimingSupported = function () {
4059 var perf = getPerformance();
4060 return perf && perf.getEntriesByType && perf.getEntriesByType("navigation").length > 0;
4061 };
4062 /**
4063 * Returns true is window performance timing API is supported, false otherwise.
4064 */
4065 PageViewPerformanceManager.prototype.isPerformanceTimingSupported = function () {
4066 var perf = getPerformance();
4067 return perf && perf.timing;
4068 };
4069 /**
4070 * As page loads different parts of performance timing numbers get set. When all of them are set we can report it.
4071 * Returns true if ready, false otherwise.
4072 */
4073 PageViewPerformanceManager.prototype.isPerformanceTimingDataReady = function () {
4074 var perf = getPerformance();
4075 var timing = perf ? perf.timing : 0;
4076 return timing
4077 && timing.domainLookupStart > 0
4078 && timing.navigationStart > 0
4079 && timing.responseStart > 0
4080 && timing.requestStart > 0
4081 && timing.loadEventEnd > 0
4082 && timing.responseEnd > 0
4083 && timing.connectEnd > 0
4084 && timing.domLoading > 0;
4085 };
4086 /**
4087 * This method tells if given durations should be excluded from collection.
4088 */
4089 PageViewPerformanceManager.prototype.shouldCollectDuration = function () {
4090 var durations = [];
4091 for (var _i = 0; _i < arguments.length; _i++) {
4092 durations[_i] = arguments[_i];
4093 }
4094 var _navigator = getNavigator() || {};
4095 // a full list of Google crawlers user agent strings - https://support.google.com/webmasters/answer/1061943?hl=en
4096 var botAgentNames = ['googlebot', 'adsbot-google', 'apis-google', 'mediapartners-google'];
4097 var userAgent = _navigator.userAgent;
4098 var isGoogleBot = false;
4099 if (userAgent) {
4100 for (var i = 0; i < botAgentNames.length; i++) {
4101 isGoogleBot = isGoogleBot || userAgent.toLowerCase().indexOf(botAgentNames[i]) !== -1;
4102 }
4103 }
4104 if (isGoogleBot) {
4105 // Don't report durations for GoogleBot, it is returning invalid values in performance.timing API.
4106 return false;
4107 }
4108 else {
4109 // for other page views, don't report if it's outside of a reasonable range
4110 for (var i = 0; i < durations.length; i++) {
4111 if (durations[i] >= this.MAX_DURATION_ALLOWED) {
4112 return false;
4113 }
4114 }
4115 }
4116 return true;
4117 };
4118 return PageViewPerformanceManager;
4119 }());
4120
4121 /**
4122 * ApplicationInsights.ts
4123 * @copyright Microsoft 2018
4124 */
4125 var durationProperty = "duration";
4126 function _dispatchEvent(target, evnt) {
4127 if (target && target.dispatchEvent && evnt) {
4128 target.dispatchEvent(evnt);
4129 }
4130 }
4131 var ApplicationInsights = /** @class */ (function (_super) {
4132 __extends(ApplicationInsights, _super);
4133 function ApplicationInsights() {
4134 var _this = _super.call(this) || this;
4135 _this.identifier = "ApplicationInsightsAnalytics"; // do not change name or priority
4136 _this.priority = 180; // take from reserved priority range 100- 200
4137 _this.autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place
4138 // Counts number of trackAjax invokations.
4139 // By default we only monitor X ajax call per view to avoid too much load.
4140 // Default value is set in config.
4141 // This counter keeps increasing even after the limit is reached.
4142 _this._trackAjaxAttempts = 0;
4143 var location = getLocation();
4144 _this._prevUri = location && location.href || "";
4145 return _this;
4146 }
4147 ApplicationInsights.getDefaultConfig = function (config) {
4148 if (!config) {
4149 config = {};
4150 }
4151 // set default values
4152 config.sessionRenewalMs = 30 * 60 * 1000;
4153 config.sessionExpirationMs = 24 * 60 * 60 * 1000;
4154 config.disableExceptionTracking = Util.stringToBoolOrDefault(config.disableExceptionTracking);
4155 config.autoTrackPageVisitTime = Util.stringToBoolOrDefault(config.autoTrackPageVisitTime);
4156 config.overridePageViewDuration = Util.stringToBoolOrDefault(config.overridePageViewDuration);
4157 config.enableUnhandledPromiseRejectionTracking = Util.stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
4158 if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
4159 config.samplingPercentage = 100;
4160 }
4161 config.isCookieUseDisabled = Util.stringToBoolOrDefault(config.isCookieUseDisabled);
4162 config.isStorageUseDisabled = Util.stringToBoolOrDefault(config.isStorageUseDisabled);
4163 config.isBrowserLinkTrackingEnabled = Util.stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
4164 config.enableAutoRouteTracking = Util.stringToBoolOrDefault(config.enableAutoRouteTracking);
4165 config.namePrefix = config.namePrefix || "";
4166 return config;
4167 };
4168 ApplicationInsights.prototype.processTelemetry = function (env, itemCtx) {
4169 var doNotSendItem = false;
4170 var telemetryInitializersCount = this._telemetryInitializers.length;
4171 itemCtx = this._getTelCtx(itemCtx);
4172 for (var i = 0; i < telemetryInitializersCount; ++i) {
4173 var telemetryInitializer = this._telemetryInitializers[i];
4174 if (telemetryInitializer) {
4175 try {
4176 if (telemetryInitializer.apply(null, [env]) === false) {
4177 doNotSendItem = true;
4178 break;
4179 }
4180 }
4181 catch (e) {
4182 // log error but dont stop executing rest of the telemetry initializers
4183 // doNotSendItem = true;
4184 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + Util.getExceptionName(e), { exception: Util.dump(e) }, true);
4185 }
4186 }
4187 }
4188 if (!doNotSendItem) {
4189 this.processNext(env, itemCtx);
4190 }
4191 };
4192 ApplicationInsights.prototype.trackEvent = function (event, customProperties) {
4193 try {
4194 var telemetryItem = TelemetryItemCreator.create(event, Event$1.dataType, Event$1.envelopeType, this.diagLog(), customProperties);
4195 this.core.track(telemetryItem);
4196 }
4197 catch (e) {
4198 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TrackTraceFailed, "trackTrace failed, trace will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4199 }
4200 };
4201 /**
4202 * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.
4203 * @param name A string that identifies this event uniquely within the document.
4204 */
4205 ApplicationInsights.prototype.startTrackEvent = function (name) {
4206 try {
4207 this._eventTracking.start(name);
4208 }
4209 catch (e) {
4210 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StartTrackEventFailed, "startTrackEvent failed, event will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4211 }
4212 };
4213 /**
4214 * Log an extended event that you started timing with `startTrackEvent`.
4215 * @param name The string you used to identify this event in `startTrackEvent`.
4216 * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
4217 * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
4218 */
4219 ApplicationInsights.prototype.stopTrackEvent = function (name, properties, measurements) {
4220 try {
4221 this._eventTracking.stop(name, undefined, properties); // Todo: Fix to pass measurements once type is updated
4222 }
4223 catch (e) {
4224 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StopTrackEventFailed, "stopTrackEvent failed, event will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4225 }
4226 };
4227 /**
4228 * @description Log a diagnostic message
4229 * @param {ITraceTelemetry} trace
4230 * @param ICustomProperties.
4231 * @memberof ApplicationInsights
4232 */
4233 ApplicationInsights.prototype.trackTrace = function (trace, customProperties) {
4234 try {
4235 var telemetryItem = TelemetryItemCreator.create(trace, Trace.dataType, Trace.envelopeType, this.diagLog(), customProperties);
4236 this.core.track(telemetryItem);
4237 }
4238 catch (e) {
4239 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TrackTraceFailed, "trackTrace failed, trace will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4240 }
4241 };
4242 /**
4243 * @description Log a numeric value that is not associated with a specific event. Typically
4244 * used to send regular reports of performance indicators. To send single measurement, just
4245 * use the name and average fields of {@link IMetricTelemetry}. If you take measurements
4246 * frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements
4247 * and sending the resulting average at intervals
4248 * @param {IMetricTelemetry} metric input object argument. Only name and average are mandatory.
4249 * @param {{[key: string]: any}} customProperties additional data used to filter metrics in the
4250 * portal. Defaults to empty.
4251 * @memberof ApplicationInsights
4252 */
4253 ApplicationInsights.prototype.trackMetric = function (metric, customProperties) {
4254 try {
4255 var telemetryItem = TelemetryItemCreator.create(metric, Metric.dataType, Metric.envelopeType, this.diagLog(), customProperties);
4256 this.core.track(telemetryItem);
4257 }
4258 catch (e) {
4259 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackMetricFailed, "trackMetric failed, metric will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4260 }
4261 };
4262 /**
4263 * Logs that a page or other item was viewed.
4264 * @param IPageViewTelemetry The string you used as the name in startTrackPage. Defaults to the document title.
4265 * @param customProperties Additional data used to filter events and metrics. Defaults to empty.
4266 * If a user wants to provide duration for pageLoad, it'll have to be in pageView.properties.duration
4267 */
4268 ApplicationInsights.prototype.trackPageView = function (pageView, customProperties) {
4269 try {
4270 var inPv = pageView || {};
4271 this._pageViewManager.trackPageView(inPv, __assign({}, inPv.properties, inPv.measurements, customProperties));
4272 if (this.config.autoTrackPageVisitTime) {
4273 this._pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
4274 }
4275 }
4276 catch (e) {
4277 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackPVFailed, "trackPageView failed, page view will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4278 }
4279 };
4280 /**
4281 * Create a page view telemetry item and send it to the SDK pipeline through the core.track API
4282 * @param pageView Page view item to be sent
4283 * @param properties Custom properties (Part C) that a user can add to the telemetry item
4284 * @param systemProperties System level properties (Part A) that a user can add to the telemetry item
4285 */
4286 ApplicationInsights.prototype.sendPageViewInternal = function (pageView, properties, systemProperties) {
4287 var doc = getDocument();
4288 if (doc) {
4289 pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;
4290 }
4291 var telemetryItem = TelemetryItemCreator.create(pageView, PageView.dataType, PageView.envelopeType, this.diagLog(), properties, systemProperties);
4292 this.core.track(telemetryItem);
4293 // reset ajaxes counter
4294 this._trackAjaxAttempts = 0;
4295 };
4296 /**
4297 * @ignore INTERNAL ONLY
4298 * @param pageViewPerformance
4299 * @param properties
4300 */
4301 ApplicationInsights.prototype.sendPageViewPerformanceInternal = function (pageViewPerformance, properties, systemProperties) {
4302 var telemetryItem = TelemetryItemCreator.create(pageViewPerformance, PageViewPerformance.dataType, PageViewPerformance.envelopeType, this.diagLog(), properties, systemProperties);
4303 this.core.track(telemetryItem);
4304 };
4305 /**
4306 * Send browser performance metrics.
4307 * @param pageViewPerformance
4308 * @param customProperties
4309 */
4310 ApplicationInsights.prototype.trackPageViewPerformance = function (pageViewPerformance, customProperties) {
4311 try {
4312 this._pageViewPerformanceManager.populatePageViewPerformanceEvent(pageViewPerformance);
4313 this.sendPageViewPerformanceInternal(pageViewPerformance, customProperties);
4314 }
4315 catch (e) {
4316 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackPVFailed, "trackPageViewPerformance failed, page view will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4317 }
4318 };
4319 /**
4320 * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,
4321 * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view
4322 * and send the event.
4323 * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
4324 */
4325 ApplicationInsights.prototype.startTrackPage = function (name) {
4326 try {
4327 if (typeof name !== "string") {
4328 var doc = getDocument();
4329 name = doc && doc.title || "";
4330 }
4331 this._pageTracking.start(name);
4332 }
4333 catch (e) {
4334 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StartTrackFailed, "startTrackPage failed, page view may not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4335 }
4336 };
4337 /**
4338 * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
4339 * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
4340 * @param name The string you used as the name in startTrackPage. Defaults to the document title.
4341 * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
4342 * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
4343 * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
4344 */
4345 ApplicationInsights.prototype.stopTrackPage = function (name, url, properties, measurement) {
4346 try {
4347 if (typeof name !== "string") {
4348 var doc = getDocument();
4349 name = doc && doc.title || "";
4350 }
4351 if (typeof url !== "string") {
4352 var loc = getLocation();
4353 url = loc && loc.href || "";
4354 }
4355 this._pageTracking.stop(name, url, properties, measurement);
4356 if (this.config.autoTrackPageVisitTime) {
4357 this._pageVisitTimeManager.trackPreviousPageVisit(name, url);
4358 }
4359 }
4360 catch (e) {
4361 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StopTrackFailed, "stopTrackPage failed, page view will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4362 }
4363 };
4364 /**
4365 * @ignore INTERNAL ONLY
4366 * @param exception
4367 * @param properties
4368 * @param systemProperties
4369 */
4370 ApplicationInsights.prototype.sendExceptionInternal = function (exception, customProperties, systemProperties) {
4371 var exceptionPartB = new Exception(this.diagLog(), exception.exception || new Error(Util.NotSpecified), exception.properties, exception.measurements, exception.severityLevel, exception.id).toInterface();
4372 var telemetryItem = TelemetryItemCreator.create(exceptionPartB, Exception.dataType, Exception.envelopeType, this.diagLog(), customProperties, systemProperties);
4373 this.core.track(telemetryItem);
4374 };
4375 /**
4376 * Log an exception you have caught.
4377 *
4378 * @param {IExceptionTelemetry} exception Object which contains exception to be sent
4379 * @param {{[key: string]: any}} customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.
4380 *
4381 * Any property of type double will be considered a measurement, and will be treated by Application Insights as a metric.
4382 * @memberof ApplicationInsights
4383 */
4384 ApplicationInsights.prototype.trackException = function (exception, customProperties) {
4385 try {
4386 this.sendExceptionInternal(exception, customProperties);
4387 }
4388 catch (e) {
4389 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackExceptionFailed, "trackException failed, exception will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
4390 }
4391 };
4392 /**
4393 * @description Custom error handler for Application Insights Analytics
4394 * @param {IAutoExceptionTelemetry} exception
4395 * @memberof ApplicationInsights
4396 */
4397 ApplicationInsights.prototype._onerror = function (exception) {
4398 try {
4399 var properties_1 = {
4400 url: (exception && exception.url) || (getDocument() || {}).URL,
4401 lineNumber: exception.lineNumber,
4402 columnNumber: exception.columnNumber,
4403 message: exception.message
4404 };
4405 if (Util.isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception.error)) {
4406 this._sendCORSException(properties_1.url);
4407 }
4408 else {
4409 if (!Util.isError(exception.error)) {
4410 var stack = "window.onerror@" + properties_1.url + ":" + exception.lineNumber + ":" + (exception.columnNumber || 0);
4411 exception.error = new Error(exception.message);
4412 exception.error.stack = stack;
4413 }
4414 this.trackException({ exception: exception.error, severityLevel: SeverityLevel.Error }, properties_1);
4415 }
4416 }
4417 catch (e) {
4418 var errorString = exception.error ?
4419 (exception.error.name + ", " + exception.error.message)
4420 : "null";
4421 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.ExceptionWhileLoggingError, "_onError threw exception while logging error, error will not be collected: "
4422 + Util.getExceptionName(e), { exception: Util.dump(e), errorString: errorString });
4423 }
4424 };
4425 ApplicationInsights.prototype.addTelemetryInitializer = function (telemetryInitializer) {
4426 this._telemetryInitializers.push(telemetryInitializer);
4427 };
4428 ApplicationInsights.prototype.initialize = function (config, core, extensions, pluginChain) {
4429 var _this = this;
4430 if (this.isInitialized()) {
4431 return;
4432 }
4433 if (CoreUtils.isNullOrUndefined(core)) {
4434 throw Error("Error initializing");
4435 }
4436 _super.prototype.initialize.call(this, config, core, extensions, pluginChain);
4437 this.setInitialized(false); // resetting the initialized state, just in case the following fails
4438 var ctx = this._getTelCtx();
4439 var identifier = this.identifier;
4440 this._globalconfig = {
4441 instrumentationKey: config.instrumentationKey,
4442 endpointUrl: config.endpointUrl || "https://dc.services.visualstudio.com/v2/track"
4443 };
4444 this.config = ctx.getExtCfg(identifier);
4445 // load default values if specified
4446 var defaults = ApplicationInsights.getDefaultConfig();
4447 if (defaults !== undefined) {
4448 for (var field in defaults) {
4449 // for each unspecified field, set the default value
4450 this.config[field] = ctx.getConfig(identifier, field, defaults[field]);
4451 }
4452 if (this._globalconfig) {
4453 for (var field in defaults) {
4454 if (this._globalconfig[field] === undefined) {
4455 this._globalconfig[field] = defaults[field];
4456 }
4457 }
4458 }
4459 }
4460 // Todo: move this out of static state
4461 if (this.config.isCookieUseDisabled) {
4462 Util.disableCookies();
4463 }
4464 // Todo: move this out of static state
4465 if (this.config.isStorageUseDisabled) {
4466 Util.disableStorage();
4467 }
4468 var configGetters = {
4469 instrumentationKey: function () { return config.instrumentationKey; },
4470 accountId: function () { return _this.config.accountId || config.accountId; },
4471 sessionRenewalMs: function () { return _this.config.sessionRenewalMs || config.sessionRenewalMs; },
4472 sessionExpirationMs: function () { return _this.config.sessionExpirationMs || config.sessionExpirationMs; },
4473 sampleRate: function () { return _this.config.samplingPercentage || config.samplingPercentage; },
4474 cookieDomain: function () { return _this.config.cookieDomain || config.cookieDomain; },
4475 sdkExtension: function () { return _this.config.sdkExtension || config.sdkExtension; },
4476 isBrowserLinkTrackingEnabled: function () { return _this.config.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled; },
4477 appId: function () { return _this.config.appId || config.appId; }
4478 };
4479 this._pageViewPerformanceManager = new PageViewPerformanceManager(this.core);
4480 this._pageViewManager = new PageViewManager(this, this.config.overridePageViewDuration, this.core, this._pageViewPerformanceManager);
4481 this._pageVisitTimeManager = new PageVisitTimeManager(this.diagLog(), function (pageName, pageUrl, pageVisitTime) { return _this.trackPageVisitTime(pageName, pageUrl, pageVisitTime); });
4482 this._telemetryInitializers = this._telemetryInitializers || [];
4483 this._addDefaultTelemetryInitializers(configGetters);
4484 this._eventTracking = new Timing(this.diagLog(), "trackEvent");
4485 this._eventTracking.action =
4486 function (name, url, duration, properties) {
4487 if (!properties) {
4488 properties = {};
4489 }
4490 properties[durationProperty] = duration.toString();
4491 _this.trackEvent({ name: name, properties: properties });
4492 };
4493 // initialize page view timing
4494 this._pageTracking = new Timing(this.diagLog(), "trackPageView");
4495 this._pageTracking.action = function (name, url, duration, properties, measurements) {
4496 // duration must be a custom property in order for the collector to extract it
4497 if (CoreUtils.isNullOrUndefined(properties)) {
4498 properties = {};
4499 }
4500 properties[durationProperty] = duration.toString();
4501 var pageViewItem = {
4502 name: name,
4503 uri: url,
4504 properties: properties,
4505 measurements: measurements
4506 };
4507 _this.sendPageViewInternal(pageViewItem, properties);
4508 };
4509 var _window = getWindow();
4510 var _history = getHistory();
4511 var _location = getLocation();
4512 var instance = this;
4513 if (this.config.disableExceptionTracking === false &&
4514 !this.config.autoExceptionInstrumented && _window) {
4515 // We want to enable exception auto collection and it has not been done so yet
4516 var onerror_1 = "onerror";
4517 var originalOnError_1 = _window[onerror_1];
4518 _window.onerror = function (message, url, lineNumber, columnNumber, error) {
4519 var handled = originalOnError_1 && originalOnError_1(message, url, lineNumber, columnNumber, error);
4520 if (handled !== true) {
4521 instance._onerror({
4522 message: message,
4523 url: url,
4524 lineNumber: lineNumber,
4525 columnNumber: columnNumber,
4526 error: error
4527 });
4528 }
4529 return handled;
4530 };
4531 this.config.autoExceptionInstrumented = true;
4532 }
4533 if (this.config.disableExceptionTracking === false &&
4534 this.config.enableUnhandledPromiseRejectionTracking === true &&
4535 !this.config.autoUnhandledPromiseInstrumented && _window) {
4536 // We want to enable exception auto collection and it has not been done so yet
4537 var onunhandledrejection = "onunhandledrejection";
4538 var originalOnUnhandledRejection_1 = _window[onunhandledrejection];
4539 _window[onunhandledrejection] = function (error) {
4540 var handled = originalOnUnhandledRejection_1 && originalOnUnhandledRejection_1.call(_window, error);
4541 if (handled !== true) {
4542 instance._onerror({
4543 message: error.reason.toString(),
4544 error: error.reason instanceof Error ? error.reason : new Error(error.reason.toString()),
4545 url: _location ? _location.href : "",
4546 lineNumber: 0,
4547 columnNumber: 0
4548 });
4549 }
4550 return handled;
4551 };
4552 this.config.autoUnhandledPromiseInstrumented = true;
4553 }
4554 /**
4555 * Create a custom "locationchange" event which is triggered each time the history object is changed
4556 */
4557 if (this.config.enableAutoRouteTracking === true
4558 && _history && CoreUtils.isFunction(_history.pushState) && CoreUtils.isFunction(_history.replaceState)
4559 && _window
4560 && typeof Event !== "undefined") {
4561 var _self_1 = this;
4562 // Find the properties plugin
4563 CoreUtils.arrForEach(extensions, function (extension) {
4564 if (extension.identifier === PropertiesPluginIdentifier) {
4565 _this._properties = extension;
4566 }
4567 });
4568 _history.pushState = (function (f) { return function pushState() {
4569 var ret = f.apply(this, arguments);
4570 _dispatchEvent(_window, Util.createDomEvent(_self_1.config.namePrefix + "pushState"));
4571 _dispatchEvent(_window, Util.createDomEvent(_self_1.config.namePrefix + "locationchange"));
4572 return ret;
4573 }; })(_history.pushState);
4574 _history.replaceState = (function (f) { return function replaceState() {
4575 var ret = f.apply(this, arguments);
4576 _dispatchEvent(_window, Util.createDomEvent(_self_1.config.namePrefix + "replaceState"));
4577 _dispatchEvent(_window, Util.createDomEvent(_self_1.config.namePrefix + "locationchange"));
4578 return ret;
4579 }; })(_history.replaceState);
4580 if (_window.addEventListener) {
4581 _window.addEventListener(_self_1.config.namePrefix + "popstate", function () {
4582 _dispatchEvent(_window, Util.createDomEvent(_self_1.config.namePrefix + "locationchange"));
4583 });
4584 _window.addEventListener(_self_1.config.namePrefix + "locationchange", function () {
4585 if (_self_1._properties && _self_1._properties.context && _self_1._properties.context.telemetryTrace) {
4586 _self_1._properties.context.telemetryTrace.traceID = Util.generateW3CId();
4587 _self_1._properties.context.telemetryTrace.name = _location && _location.pathname || "_unknown_";
4588 }
4589 if (_this._currUri) {
4590 _this._prevUri = _this._currUri;
4591 _this._currUri = _location && _location.href || "";
4592 }
4593 else {
4594 _this._currUri = _location && _location.href || "";
4595 }
4596 setTimeout((function (uri) {
4597 // todo: override start time so that it is not affected by autoRoutePVDelay
4598 _self_1.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
4599 }).bind(_this, _this._prevUri), _self_1.autoRoutePVDelay);
4600 });
4601 }
4602 }
4603 this.setInitialized(true);
4604 };
4605 /**
4606 * Log a page visit time
4607 * @param pageName Name of page
4608 * @param pageVisitDuration Duration of visit to the page in milleseconds
4609 */
4610 ApplicationInsights.prototype.trackPageVisitTime = function (pageName, pageUrl, pageVisitTime) {
4611 var properties = { PageName: pageName, PageUrl: pageUrl };
4612 this.trackMetric({
4613 name: "PageVisitTime",
4614 average: pageVisitTime,
4615 max: pageVisitTime,
4616 min: pageVisitTime,
4617 sampleCount: 1
4618 }, properties);
4619 };
4620 ApplicationInsights.prototype._addDefaultTelemetryInitializers = function (configGetters) {
4621 if (!configGetters.isBrowserLinkTrackingEnabled()) {
4622 var browserLinkPaths_1 = ['/browserLinkSignalR/', '/__browserLink/'];
4623 var dropBrowserLinkRequests = function (envelope) {
4624 if (envelope.baseType === RemoteDependencyData$1.dataType) {
4625 var remoteData = envelope.baseData;
4626 if (remoteData) {
4627 for (var i = 0; i < browserLinkPaths_1.length; i++) {
4628 if (remoteData.target && remoteData.target.indexOf(browserLinkPaths_1[i]) >= 0) {
4629 return false;
4630 }
4631 }
4632 }
4633 }
4634 return true;
4635 };
4636 this._addTelemetryInitializer(dropBrowserLinkRequests);
4637 }
4638 };
4639 ApplicationInsights.prototype._addTelemetryInitializer = function (telemetryInitializer) {
4640 this._telemetryInitializers.push(telemetryInitializer);
4641 };
4642 ApplicationInsights.prototype._sendCORSException = function (url) {
4643 var exception = {
4644 message: "Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.",
4645 url: url,
4646 lineNumber: 0,
4647 columnNumber: 0,
4648 error: undefined
4649 };
4650 var telemetryItem = TelemetryItemCreator.create(exception, Exception.dataType, Exception.envelopeType, this.diagLog(), { url: url });
4651 this.core.track(telemetryItem);
4652 };
4653 ApplicationInsights.Version = "2.4.4"; // Not currently used anywhere
4654 return ApplicationInsights;
4655 }(BaseTelemetryPlugin));
4656 /**
4657 * Used to record timed events and page views.
4658 */
4659 var Timing = /** @class */ (function () {
4660 function Timing(logger, name) {
4661 this._name = name;
4662 this._events = {};
4663 this._logger = logger;
4664 }
4665 Timing.prototype.start = function (name) {
4666 if (typeof this._events[name] !== "undefined") {
4667 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.StartCalledMoreThanOnce, "start was called more than once for this event without calling stop.", { name: this._name, key: name }, true);
4668 }
4669 this._events[name] = +new Date;
4670 };
4671 Timing.prototype.stop = function (name, url, properties, measurements) {
4672 var start = this._events[name];
4673 if (isNaN(start)) {
4674 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.StopCalledWithoutStart, "stop was called without a corresponding start.", { name: this._name, key: name }, true);
4675 }
4676 else {
4677 var end = +new Date;
4678 var duration = DateTimeUtils.GetDuration(start, end);
4679 this.action(name, url, duration, properties, measurements);
4680 }
4681 delete this._events[name];
4682 this._events[name] = undefined;
4683 };
4684 return Timing;
4685 }());
4686
4687 /*
4688 * An array based send buffer.
4689 */
4690 var ArraySendBuffer = /** @class */ (function () {
4691 function ArraySendBuffer(config) {
4692 this._config = config;
4693 this._buffer = [];
4694 }
4695 ArraySendBuffer.prototype.enqueue = function (payload) {
4696 this._buffer.push(payload);
4697 };
4698 ArraySendBuffer.prototype.count = function () {
4699 return this._buffer.length;
4700 };
4701 ArraySendBuffer.prototype.clear = function () {
4702 this._buffer.length = 0;
4703 };
4704 ArraySendBuffer.prototype.getItems = function () {
4705 return this._buffer.slice(0);
4706 };
4707 ArraySendBuffer.prototype.batchPayloads = function (payload) {
4708 if (payload && payload.length > 0) {
4709 var batch = this._config.emitLineDelimitedJson() ?
4710 payload.join("\n") :
4711 "[" + payload.join(",") + "]";
4712 return batch;
4713 }
4714 return null;
4715 };
4716 ArraySendBuffer.prototype.markAsSent = function (payload) {
4717 this.clear();
4718 };
4719 ArraySendBuffer.prototype.clearSent = function (payload) {
4720 // not supported
4721 };
4722 return ArraySendBuffer;
4723 }());
4724 /*
4725 * Session storege buffer holds a copy of all unsent items in the browser session storage.
4726 */
4727 var SessionStorageSendBuffer = /** @class */ (function () {
4728 function SessionStorageSendBuffer(logger, config) {
4729 this._bufferFullMessageSent = false;
4730 this._logger = logger;
4731 this._config = config;
4732 var bufferItems = this.getBuffer(SessionStorageSendBuffer.BUFFER_KEY);
4733 var notDeliveredItems = this.getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY);
4734 this._buffer = bufferItems.concat(notDeliveredItems);
4735 // If the buffer has too many items, drop items from the end.
4736 if (this._buffer.length > SessionStorageSendBuffer.MAX_BUFFER_SIZE) {
4737 this._buffer.length = SessionStorageSendBuffer.MAX_BUFFER_SIZE;
4738 }
4739 // update DataLossAnalyzer with the number of recovered items
4740 // Uncomment if you want to use DataLossanalyzer
4741 // DataLossAnalyzer.itemsRestoredFromSessionBuffer = this._buffer.length;
4742 this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, []);
4743 this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, this._buffer);
4744 }
4745 SessionStorageSendBuffer.prototype.enqueue = function (payload) {
4746 if (this._buffer.length >= SessionStorageSendBuffer.MAX_BUFFER_SIZE) {
4747 // sent internal log only once per page view
4748 if (!this._bufferFullMessageSent) {
4749 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.SessionStorageBufferFull, "Maximum buffer size reached: " + this._buffer.length, true);
4750 this._bufferFullMessageSent = true;
4751 }
4752 return;
4753 }
4754 this._buffer.push(payload);
4755 this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, this._buffer);
4756 };
4757 SessionStorageSendBuffer.prototype.count = function () {
4758 return this._buffer.length;
4759 };
4760 SessionStorageSendBuffer.prototype.clear = function () {
4761 this._buffer.length = 0;
4762 this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, []);
4763 this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, []);
4764 this._bufferFullMessageSent = false;
4765 };
4766 SessionStorageSendBuffer.prototype.getItems = function () {
4767 return this._buffer.slice(0);
4768 };
4769 SessionStorageSendBuffer.prototype.batchPayloads = function (payload) {
4770 if (payload && payload.length > 0) {
4771 var batch = this._config.emitLineDelimitedJson() ?
4772 payload.join("\n") :
4773 "[" + payload.join(",") + "]";
4774 return batch;
4775 }
4776 return null;
4777 };
4778 SessionStorageSendBuffer.prototype.markAsSent = function (payload) {
4779 this._buffer = this.removePayloadsFromBuffer(payload, this._buffer);
4780 this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, this._buffer);
4781 var sentElements = this.getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY);
4782 if (sentElements instanceof Array && payload instanceof Array) {
4783 sentElements = sentElements.concat(payload);
4784 if (sentElements.length > SessionStorageSendBuffer.MAX_BUFFER_SIZE) {
4785 // We send telemetry normally. If the SENT_BUFFER is too big we don't add new elements
4786 // until we receive a response from the backend and the buffer has free space again (see clearSent method)
4787 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.SessionStorageBufferFull, "Sent buffer reached its maximum size: " + sentElements.length, true);
4788 sentElements.length = SessionStorageSendBuffer.MAX_BUFFER_SIZE;
4789 }
4790 this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, sentElements);
4791 }
4792 };
4793 SessionStorageSendBuffer.prototype.clearSent = function (payload) {
4794 var sentElements = this.getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY);
4795 sentElements = this.removePayloadsFromBuffer(payload, sentElements);
4796 this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, sentElements);
4797 };
4798 SessionStorageSendBuffer.prototype.removePayloadsFromBuffer = function (payloads, buffer) {
4799 var remaining = [];
4800 for (var i in buffer) {
4801 var contains = false;
4802 for (var j in payloads) {
4803 if (payloads[j] === buffer[i]) {
4804 contains = true;
4805 break;
4806 }
4807 }
4808 if (!contains) {
4809 remaining.push(buffer[i]);
4810 }
4811 }
4812 return remaining;
4813 };
4814 SessionStorageSendBuffer.prototype.getBuffer = function (key) {
4815 var prefixedKey = key;
4816 try {
4817 prefixedKey = this._config.namePrefix && this._config.namePrefix() ? this._config.namePrefix() + "_" + prefixedKey : prefixedKey;
4818 var bufferJson = Util.getSessionStorage(this._logger, prefixedKey);
4819 if (bufferJson) {
4820 var buffer = getJSON().parse(bufferJson);
4821 if (buffer) {
4822 return buffer;
4823 }
4824 }
4825 }
4826 catch (e) {
4827 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedToRestoreStorageBuffer, " storage key: " + prefixedKey + ", " + Util.getExceptionName(e), { exception: Util.dump(e) });
4828 }
4829 return [];
4830 };
4831 SessionStorageSendBuffer.prototype.setBuffer = function (key, buffer) {
4832 var prefixedKey = key;
4833 try {
4834 prefixedKey = this._config.namePrefix && this._config.namePrefix() ? this._config.namePrefix() + "_" + prefixedKey : prefixedKey;
4835 var bufferJson = JSON.stringify(buffer);
4836 Util.setSessionStorage(this._logger, prefixedKey, bufferJson);
4837 }
4838 catch (e) {
4839 // if there was an error, clear the buffer
4840 // telemetry is stored in the _buffer array so we won't loose any items
4841 Util.setSessionStorage(this._logger, prefixedKey, JSON.stringify([]));
4842 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedToSetStorageBuffer, " storage key: " + prefixedKey + ", " + Util.getExceptionName(e) + ". Buffer cleared", { exception: Util.dump(e) });
4843 }
4844 };
4845 SessionStorageSendBuffer.BUFFER_KEY = "AI_buffer";
4846 SessionStorageSendBuffer.SENT_BUFFER_KEY = "AI_sentBuffer";
4847 // Maximum number of payloads stored in the buffer. If the buffer is full, new elements will be dropped.
4848 SessionStorageSendBuffer.MAX_BUFFER_SIZE = 2000;
4849 return SessionStorageSendBuffer;
4850 }());
4851
4852 var EnvelopeCreator = /** @class */ (function () {
4853 function EnvelopeCreator() {
4854 }
4855 EnvelopeCreator.extractPropsAndMeasurements = function (data, properties, measurements) {
4856 if (!CoreUtils.isNullOrUndefined(data)) {
4857 for (var key in data) {
4858 if (data.hasOwnProperty(key)) {
4859 var value = data[key];
4860 if (CoreUtils.isNumber(value)) {
4861 measurements[key] = value;
4862 }
4863 else if (CoreUtils.isString(value)) {
4864 properties[key] = value;
4865 }
4866 else if (hasJSON()) {
4867 properties[key] = getJSON().stringify(value);
4868 }
4869 }
4870 }
4871 }
4872 };
4873 // TODO: Do we want this to take logger as arg or use this._logger as nonstatic?
4874 EnvelopeCreator.createEnvelope = function (logger, envelopeType, telemetryItem, data) {
4875 var envelope = new Envelope$1(logger, data, envelopeType);
4876 if (telemetryItem[SampleRate]) {
4877 envelope.sampleRate = telemetryItem[SampleRate];
4878 }
4879 envelope.iKey = telemetryItem.iKey;
4880 var iKeyNoDashes = telemetryItem.iKey.replace(/-/g, "");
4881 envelope.name = envelope.name.replace("{0}", iKeyNoDashes);
4882 // extract all extensions from ctx
4883 EnvelopeCreator.extractPartAExtensions(telemetryItem, envelope);
4884 // loop through the envelope tags (extension of Part A) and pick out the ones that should go in outgoing envelope tags
4885 if (!telemetryItem.tags) {
4886 telemetryItem.tags = [];
4887 }
4888 return envelope;
4889 };
4890 /*
4891 * Maps Part A data from CS 4.0
4892 */
4893 EnvelopeCreator.extractPartAExtensions = function (item, env) {
4894 // todo: switch to keys from common in this method
4895 if (!env.tags) {
4896 env.tags = {};
4897 }
4898 if (!item.ext) {
4899 item.ext = {};
4900 }
4901 if (!item.tags) {
4902 item.tags = [];
4903 }
4904 if (item.ext.user) {
4905 if (item.ext.user.authId) {
4906 env.tags[CtxTagKeys.userAuthUserId] = item.ext.user.authId;
4907 }
4908 var userId = item.ext.user.id || item.ext.user.localId;
4909 if (userId) {
4910 env.tags[CtxTagKeys.userId] = userId;
4911 }
4912 }
4913 if (item.ext.app) {
4914 if (item.ext.app.sesId) {
4915 env.tags[CtxTagKeys.sessionId] = item.ext.app.sesId;
4916 }
4917 }
4918 if (item.ext.device) {
4919 if (item.ext.device.id || item.ext.device.localId) {
4920 env.tags[CtxTagKeys.deviceId] = item.ext.device.id || item.ext.device.localId;
4921 }
4922 if (item.ext.device.deviceClass) {
4923 env.tags[CtxTagKeys.deviceType] = item.ext.device.deviceClass;
4924 }
4925 if (item.ext.device.ip) {
4926 env.tags[CtxTagKeys.deviceIp] = item.ext.device.ip;
4927 }
4928 }
4929 if (item.ext.web) {
4930 var web = item.ext.web;
4931 if (web.browserLang) {
4932 env.tags[CtxTagKeys.deviceLanguage] = web.browserLang;
4933 }
4934 if (web.browserVer) {
4935 env.tags[CtxTagKeys.deviceBrowserVersion] = web.browserVer;
4936 }
4937 if (web.browser) {
4938 env.tags[CtxTagKeys.deviceBrowser] = web.browser;
4939 }
4940 env.data = env.data || {};
4941 env.data.baseData = env.data.baseData || {};
4942 env.data.baseData.properties = env.data.baseData.properties || {};
4943 if (web.domain) {
4944 env.data.baseData.properties['domain'] = web.domain;
4945 }
4946 if (web.isManual) {
4947 env.data.baseData.properties['isManual'] = web.isManual.toString();
4948 }
4949 if (web.screenRes) {
4950 env.data.baseData.properties['screenRes'] = web.screenRes;
4951 }
4952 if (web.userConsent) {
4953 env.data.baseData.properties['userConsent'] = web.userConsent.toString();
4954 }
4955 }
4956 if (item.ext.device) {
4957 if (item.ext.device.model) {
4958 env.tags[CtxTagKeys.deviceModel] = item.ext.device.model;
4959 }
4960 }
4961 if (item.ext.os && item.ext.os.name) {
4962 env.tags[CtxTagKeys.deviceOS] = item.ext.os.name;
4963 }
4964 if (item.ext.device) {
4965 if (item.ext.device.deviceType) {
4966 env.tags[CtxTagKeys.deviceType] = item.ext.device.deviceType;
4967 }
4968 }
4969 // No support for mapping Trace.traceState to 2.0 as it is currently empty
4970 if (item.ext.trace) {
4971 if (item.ext.trace.parentID) {
4972 env.tags[CtxTagKeys.operationParentId] = item.ext.trace.parentID;
4973 }
4974 if (item.ext.trace.name) {
4975 env.tags[CtxTagKeys.operationName] = item.ext.trace.name;
4976 }
4977 if (item.ext.trace.traceID) {
4978 env.tags[CtxTagKeys.operationId] = item.ext.trace.traceID;
4979 }
4980 }
4981 // Sample 4.0 schema
4982 // {
4983 // "time" : "2018-09-05T22:51:22.4936Z",
4984 // "name" : "MetricWithNamespace",
4985 // "iKey" : "ABC-5a4cbd20-e601-4ef5-a3c6-5d6577e4398e",
4986 // "ext": { "cloud": {
4987 // "role": "WATSON3",
4988 // "roleInstance": "CO4AEAP00000260"
4989 // },
4990 // "device": {}, "correlation": {} },
4991 // "tags": [
4992 // { "amazon.region" : "east2" },
4993 // { "os.expid" : "wp:02df239" }
4994 // ]
4995 // }
4996 var tgs = {};
4997 var _loop_1 = function (i) {
4998 var tg = item.tags[i];
4999 // CoreUtils.objKeys returns an array of keys
5000 CoreUtils.arrForEach(CoreUtils.objKeys(tg), function (key) {
5001 tgs[key] = tg[key];
5002 });
5003 item.tags.splice(i, 1);
5004 };
5005 // deals with tags.push({object})
5006 for (var i = item.tags.length - 1; i >= 0; i--) {
5007 _loop_1(i);
5008 }
5009 // deals with tags[key]=value
5010 for (var tg in item.tags) {
5011 tgs[tg] = item.tags[tg];
5012 }
5013 env.tags = __assign({}, env.tags, tgs);
5014 if (!env.tags[CtxTagKeys.internalSdkVersion]) {
5015 // Append a version in case it is not already set
5016 env.tags[CtxTagKeys.internalSdkVersion] = "javascript:" + EnvelopeCreator.Version;
5017 }
5018 };
5019 EnvelopeCreator.Version = "2.4.4";
5020 return EnvelopeCreator;
5021 }());
5022 var DependencyEnvelopeCreator = /** @class */ (function (_super) {
5023 __extends(DependencyEnvelopeCreator, _super);
5024 function DependencyEnvelopeCreator() {
5025 return _super !== null && _super.apply(this, arguments) || this;
5026 }
5027 DependencyEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5028 this._logger = logger;
5029 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5030 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5031 }
5032 var customMeasurements = telemetryItem.baseData.measurements || {};
5033 var customProperties = telemetryItem.baseData.properties || {};
5034 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.data, customProperties, customMeasurements);
5035 var bd = telemetryItem.baseData;
5036 if (CoreUtils.isNullOrUndefined(bd)) {
5037 logger.warnToConsole("Invalid input for dependency data");
5038 return null;
5039 }
5040 var id = bd.id;
5041 var absoluteUrl = bd.target;
5042 var command = bd.name;
5043 var duration = bd.duration;
5044 var success = bd.success;
5045 var resultCode = bd.responseCode;
5046 var requestAPI = bd.type;
5047 var correlationContext = bd.correlationContext;
5048 var method = bd.properties && bd.properties[HttpMethod] ? bd.properties[HttpMethod] : "GET";
5049 var baseData = new RemoteDependencyData$1(logger, id, absoluteUrl, command, duration, success, resultCode, method, requestAPI, correlationContext, customProperties, customMeasurements);
5050 var data = new Data$1(RemoteDependencyData$1.dataType, baseData);
5051 return EnvelopeCreator.createEnvelope(logger, RemoteDependencyData$1.envelopeType, telemetryItem, data);
5052 };
5053 DependencyEnvelopeCreator.DependencyEnvelopeCreator = new DependencyEnvelopeCreator();
5054 return DependencyEnvelopeCreator;
5055 }(EnvelopeCreator));
5056 var EventEnvelopeCreator = /** @class */ (function (_super) {
5057 __extends(EventEnvelopeCreator, _super);
5058 function EventEnvelopeCreator() {
5059 return _super !== null && _super.apply(this, arguments) || this;
5060 }
5061 EventEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5062 this._logger = logger;
5063 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5064 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5065 }
5066 var customProperties = {};
5067 var customMeasurements = {};
5068 if (telemetryItem.baseType !== Event$1.dataType) {
5069 customProperties['baseTypeSource'] = telemetryItem.baseType; // save the passed in base type as a property
5070 }
5071 if (telemetryItem.baseType === Event$1.dataType) {
5072 customProperties = telemetryItem.baseData.properties || {};
5073 customMeasurements = telemetryItem.baseData.measurements || {};
5074 }
5075 else {
5076 if (telemetryItem.baseData) {
5077 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.baseData, customProperties, customMeasurements);
5078 }
5079 }
5080 // Exract root level properties from part C telemetryItem.data
5081 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.data, customProperties, customMeasurements);
5082 var eventName = telemetryItem.baseData.name;
5083 var baseData = new Event$1(logger, eventName, customProperties, customMeasurements);
5084 var data = new Data$1(Event$1.dataType, baseData);
5085 return EnvelopeCreator.createEnvelope(logger, Event$1.envelopeType, telemetryItem, data);
5086 };
5087 EventEnvelopeCreator.EventEnvelopeCreator = new EventEnvelopeCreator();
5088 return EventEnvelopeCreator;
5089 }(EnvelopeCreator));
5090 var ExceptionEnvelopeCreator = /** @class */ (function (_super) {
5091 __extends(ExceptionEnvelopeCreator, _super);
5092 function ExceptionEnvelopeCreator() {
5093 return _super !== null && _super.apply(this, arguments) || this;
5094 }
5095 ExceptionEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5096 this._logger = logger;
5097 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5098 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5099 }
5100 var bd = telemetryItem.baseData;
5101 var baseData = Exception.CreateFromInterface(logger, bd);
5102 var data = new Data$1(Exception.dataType, baseData);
5103 return EnvelopeCreator.createEnvelope(logger, Exception.envelopeType, telemetryItem, data);
5104 };
5105 ExceptionEnvelopeCreator.ExceptionEnvelopeCreator = new ExceptionEnvelopeCreator();
5106 return ExceptionEnvelopeCreator;
5107 }(EnvelopeCreator));
5108 var MetricEnvelopeCreator = /** @class */ (function (_super) {
5109 __extends(MetricEnvelopeCreator, _super);
5110 function MetricEnvelopeCreator() {
5111 return _super !== null && _super.apply(this, arguments) || this;
5112 }
5113 MetricEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5114 this._logger = logger;
5115 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5116 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5117 }
5118 var props = telemetryItem.baseData.properties || {};
5119 var measurements = telemetryItem.baseData.measurements || {};
5120 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.data, props, measurements);
5121 var name = telemetryItem.baseData.name;
5122 var average = telemetryItem.baseData.average;
5123 var sampleCount = telemetryItem.baseData.sampleCount;
5124 var min = telemetryItem.baseData.min;
5125 var max = telemetryItem.baseData.max;
5126 var baseData = new Metric(logger, name, average, sampleCount, min, max, props, measurements);
5127 var data = new Data$1(Metric.dataType, baseData);
5128 return EnvelopeCreator.createEnvelope(logger, Metric.envelopeType, telemetryItem, data);
5129 };
5130 MetricEnvelopeCreator.MetricEnvelopeCreator = new MetricEnvelopeCreator();
5131 return MetricEnvelopeCreator;
5132 }(EnvelopeCreator));
5133 var PageViewEnvelopeCreator = /** @class */ (function (_super) {
5134 __extends(PageViewEnvelopeCreator, _super);
5135 function PageViewEnvelopeCreator() {
5136 return _super !== null && _super.apply(this, arguments) || this;
5137 }
5138 PageViewEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5139 this._logger = logger;
5140 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5141 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5142 }
5143 // Since duration is not part of the domain properties in Common Schema, extract it from part C
5144 var duration;
5145 if (!CoreUtils.isNullOrUndefined(telemetryItem.baseData) &&
5146 !CoreUtils.isNullOrUndefined(telemetryItem.baseData.properties) &&
5147 !CoreUtils.isNullOrUndefined(telemetryItem.baseData.properties.duration)) {
5148 duration = telemetryItem.baseData.properties.duration;
5149 delete telemetryItem.baseData.properties.duration;
5150 }
5151 else if (!CoreUtils.isNullOrUndefined(telemetryItem.data) &&
5152 !CoreUtils.isNullOrUndefined(telemetryItem.data["duration"])) {
5153 duration = telemetryItem.data["duration"];
5154 delete telemetryItem.data["duration"];
5155 }
5156 var bd = telemetryItem.baseData;
5157 // special case: pageview.id is grabbed from current operation id. Analytics plugin is decoupled from properties plugin, so this is done here instead. This can be made a default telemetry intializer instead if needed to be decoupled from channel
5158 var currentContextId;
5159 if (telemetryItem.ext && telemetryItem.ext.trace && telemetryItem.ext.trace.traceID) {
5160 currentContextId = telemetryItem.ext.trace.traceID;
5161 }
5162 var id = bd.id || currentContextId;
5163 var name = bd.name;
5164 var url = bd.uri;
5165 var properties = bd.properties || {};
5166 var measurements = bd.measurements || {};
5167 // refUri is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property
5168 if (!CoreUtils.isNullOrUndefined(bd.refUri)) {
5169 properties["refUri"] = bd.refUri;
5170 }
5171 // pageType is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property
5172 if (!CoreUtils.isNullOrUndefined(bd.pageType)) {
5173 properties["pageType"] = bd.pageType;
5174 }
5175 // isLoggedIn is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property
5176 if (!CoreUtils.isNullOrUndefined(bd.isLoggedIn)) {
5177 properties["isLoggedIn"] = bd.isLoggedIn.toString();
5178 }
5179 // pageTags is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property
5180 if (!CoreUtils.isNullOrUndefined(bd.properties)) {
5181 var pageTags = bd.properties;
5182 for (var key in pageTags) {
5183 if (pageTags.hasOwnProperty(key)) {
5184 properties[key] = pageTags[key];
5185 }
5186 }
5187 }
5188 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.data, properties, measurements);
5189 var baseData = new PageView(logger, name, url, duration, properties, measurements, id);
5190 var data = new Data$1(PageView.dataType, baseData);
5191 return EnvelopeCreator.createEnvelope(logger, PageView.envelopeType, telemetryItem, data);
5192 };
5193 PageViewEnvelopeCreator.PageViewEnvelopeCreator = new PageViewEnvelopeCreator();
5194 return PageViewEnvelopeCreator;
5195 }(EnvelopeCreator));
5196 var PageViewPerformanceEnvelopeCreator = /** @class */ (function (_super) {
5197 __extends(PageViewPerformanceEnvelopeCreator, _super);
5198 function PageViewPerformanceEnvelopeCreator() {
5199 return _super !== null && _super.apply(this, arguments) || this;
5200 }
5201 PageViewPerformanceEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5202 this._logger = logger;
5203 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5204 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5205 }
5206 var bd = telemetryItem.baseData;
5207 var name = bd.name;
5208 var url = bd.uri || bd.url;
5209 var properties = bd.properties || {};
5210 var measurements = bd.measurements || {};
5211 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.data, properties, measurements);
5212 var baseData = new PageViewPerformance(logger, name, url, undefined, properties, measurements, bd);
5213 var data = new Data$1(PageViewPerformance.dataType, baseData);
5214 return EnvelopeCreator.createEnvelope(logger, PageViewPerformance.envelopeType, telemetryItem, data);
5215 };
5216 PageViewPerformanceEnvelopeCreator.PageViewPerformanceEnvelopeCreator = new PageViewPerformanceEnvelopeCreator();
5217 return PageViewPerformanceEnvelopeCreator;
5218 }(EnvelopeCreator));
5219 var TraceEnvelopeCreator = /** @class */ (function (_super) {
5220 __extends(TraceEnvelopeCreator, _super);
5221 function TraceEnvelopeCreator() {
5222 return _super !== null && _super.apply(this, arguments) || this;
5223 }
5224 TraceEnvelopeCreator.prototype.Create = function (logger, telemetryItem) {
5225 this._logger = logger;
5226 if (CoreUtils.isNullOrUndefined(telemetryItem.baseData)) {
5227 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryEnvelopeInvalid, "telemetryItem.baseData cannot be null.");
5228 }
5229 var message = telemetryItem.baseData.message;
5230 var severityLevel = telemetryItem.baseData.severityLevel;
5231 var props = telemetryItem.baseData.properties || {};
5232 var measurements = telemetryItem.baseData.measurements || {};
5233 EnvelopeCreator.extractPropsAndMeasurements(telemetryItem.data, props, measurements);
5234 var baseData = new Trace(logger, message, severityLevel, props, measurements);
5235 var data = new Data$1(Trace.dataType, baseData);
5236 return EnvelopeCreator.createEnvelope(logger, Trace.envelopeType, telemetryItem, data);
5237 };
5238 TraceEnvelopeCreator.TraceEnvelopeCreator = new TraceEnvelopeCreator();
5239 return TraceEnvelopeCreator;
5240 }(EnvelopeCreator));
5241
5242 var Serializer = /** @class */ (function () {
5243 function Serializer(logger) {
5244 this._logger = logger;
5245 }
5246 /**
5247 * Serializes the current object to a JSON string.
5248 */
5249 Serializer.prototype.serialize = function (input) {
5250 var output = this._serializeObject(input, "root");
5251 try {
5252 return getJSON().stringify(output);
5253 }
5254 catch (e) {
5255 // if serialization fails return an empty string
5256 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSerializeObject, (e && CoreUtils.isFunction(e.toString)) ? e.toString() : "Error serializing object", null, true);
5257 }
5258 };
5259 Serializer.prototype._serializeObject = function (source, name) {
5260 var circularReferenceCheck = "__aiCircularRefCheck";
5261 var output = {};
5262 if (!source) {
5263 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSerializeObject, "cannot serialize object because it is null or undefined", { name: name }, true);
5264 return output;
5265 }
5266 if (source[circularReferenceCheck]) {
5267 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CircularReferenceDetected, "Circular reference detected while serializing object", { name: name }, true);
5268 return output;
5269 }
5270 if (!source.aiDataContract) {
5271 // special case for measurements/properties/tags
5272 if (name === "measurements") {
5273 output = this._serializeStringMap(source, "number", name);
5274 }
5275 else if (name === "properties") {
5276 output = this._serializeStringMap(source, "string", name);
5277 }
5278 else if (name === "tags") {
5279 output = this._serializeStringMap(source, "string", name);
5280 }
5281 else if (Util.isArray(source)) {
5282 output = this._serializeArray(source, name);
5283 }
5284 else {
5285 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CannotSerializeObjectNonSerializable, "Attempting to serialize an object which does not implement ISerializable", { name: name }, true);
5286 try {
5287 // verify that the object can be stringified
5288 getJSON().stringify(source);
5289 output = source;
5290 }
5291 catch (e) {
5292 // if serialization fails return an empty string
5293 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSerializeObject, (e && CoreUtils.isFunction(e.toString)) ? e.toString() : "Error serializing object", null, true);
5294 }
5295 }
5296 return output;
5297 }
5298 source[circularReferenceCheck] = true;
5299 for (var field in source.aiDataContract) {
5300 var contract = source.aiDataContract[field];
5301 var isRequired = (CoreUtils.isFunction(contract)) ? (contract() & FieldType.Required) : (contract & FieldType.Required);
5302 var isHidden = (CoreUtils.isFunction(contract)) ? (contract() & FieldType.Hidden) : (contract & FieldType.Hidden);
5303 var isArray = contract & FieldType.Array;
5304 var isPresent = source[field] !== undefined;
5305 var isObject = CoreUtils.isObject(source[field]) && source[field] !== null;
5306 if (isRequired && !isPresent && !isArray) {
5307 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.MissingRequiredFieldSpecification, "Missing required field specification. The field is required but not present on source", { field: field, name: name });
5308 // If not in debug mode, continue and hope the error is permissible
5309 continue;
5310 }
5311 if (isHidden) {
5312 // Don't serialize hidden fields
5313 continue;
5314 }
5315 var value = void 0;
5316 if (isObject) {
5317 if (isArray) {
5318 // special case; resurse on each object in the source array
5319 value = this._serializeArray(source[field], field);
5320 }
5321 else {
5322 // recurse on the source object in this field
5323 value = this._serializeObject(source[field], field);
5324 }
5325 }
5326 else {
5327 // assign the source field to the output even if undefined or required
5328 value = source[field];
5329 }
5330 // only emit this field if the value is defined
5331 if (value !== undefined) {
5332 output[field] = value;
5333 }
5334 }
5335 delete source[circularReferenceCheck];
5336 return output;
5337 };
5338 Serializer.prototype._serializeArray = function (sources, name) {
5339 var output;
5340 if (!!sources) {
5341 if (!Util.isArray(sources)) {
5342 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.ItemNotInArray, "This field was specified as an array in the contract but the item is not an array.\r\n", { name: name }, true);
5343 }
5344 else {
5345 output = [];
5346 for (var i = 0; i < sources.length; i++) {
5347 var source = sources[i];
5348 var item = this._serializeObject(source, name + "[" + i + "]");
5349 output.push(item);
5350 }
5351 }
5352 }
5353 return output;
5354 };
5355 Serializer.prototype._serializeStringMap = function (map, expectedType, name) {
5356 var output;
5357 if (map) {
5358 output = {};
5359 for (var field in map) {
5360 var value = map[field];
5361 if (expectedType === "string") {
5362 if (value === undefined) {
5363 output[field] = "undefined";
5364 }
5365 else if (value === null) {
5366 output[field] = "null";
5367 }
5368 else if (!value.toString) {
5369 output[field] = "invalid field: toString() is not defined.";
5370 }
5371 else {
5372 output[field] = value.toString();
5373 }
5374 }
5375 else if (expectedType === "number") {
5376 if (value === undefined) {
5377 output[field] = "undefined";
5378 }
5379 else if (value === null) {
5380 output[field] = "null";
5381 }
5382 else {
5383 var num = parseFloat(value);
5384 if (isNaN(num)) {
5385 output[field] = "NaN";
5386 }
5387 else {
5388 output[field] = num;
5389 }
5390 }
5391 }
5392 else {
5393 output[field] = "invalid field: " + name + " is of unknown type.";
5394 this._logger.throwInternal(LoggingSeverity.CRITICAL, output[field], null, true);
5395 }
5396 }
5397 }
5398 return output;
5399 };
5400 return Serializer;
5401 }());
5402
5403 /**
5404 * @description Monitors browser for offline events
5405 * @export default - Offline: Static instance of OfflineListener
5406 * @class OfflineListener
5407 */
5408 var OfflineListener = /** @class */ (function () {
5409 function OfflineListener() {
5410 this._onlineStatus = true;
5411 var _window = getWindow();
5412 var _document = getDocument();
5413 var isListening = false;
5414 var _this = this;
5415 try {
5416 if (_window) {
5417 if (EventHelper.Attach(_window, 'online', this._setOnline.bind(_this))) {
5418 EventHelper.Attach(_window, 'offline', this._setOffline.bind(_this));
5419 isListening = true;
5420 }
5421 }
5422 if (_document) {
5423 // Also attach to the document.body or document
5424 var target = _document.body || _document;
5425 if (!CoreUtils.isUndefined(target.ononline)) {
5426 target.ononline = this._setOnline.bind(_this);
5427 target.onoffline = this._setOffline.bind(_this);
5428 isListening = true;
5429 }
5430 }
5431 }
5432 catch (e) {
5433 // this makes react-native less angry
5434 isListening = false;
5435 }
5436 this.isListening = isListening;
5437 }
5438 OfflineListener.prototype.isOnline = function () {
5439 var _navigator = getNavigator();
5440 if (this.isListening) {
5441 return this._onlineStatus;
5442 }
5443 else if (_navigator && !CoreUtils.isNullOrUndefined(_navigator.onLine)) {
5444 return _navigator.onLine;
5445 }
5446 else {
5447 // Cannot determine online status - report as online
5448 return true;
5449 }
5450 };
5451 OfflineListener.prototype.isOffline = function () {
5452 return !this.isOnline();
5453 };
5454 OfflineListener.prototype._setOnline = function () {
5455 this._onlineStatus = true;
5456 };
5457 OfflineListener.prototype._setOffline = function () {
5458 this._onlineStatus = false;
5459 };
5460 OfflineListener.Offline = new OfflineListener;
5461 return OfflineListener;
5462 }());
5463 var Offline = OfflineListener.Offline;
5464
5465 var HashCodeScoreGenerator = /** @class */ (function () {
5466 function HashCodeScoreGenerator() {
5467 }
5468 HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) {
5469 var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE;
5470 return score * 100;
5471 };
5472 HashCodeScoreGenerator.prototype.getHashCode = function (input) {
5473 if (input === "") {
5474 return 0;
5475 }
5476 while (input.length < HashCodeScoreGenerator.MIN_INPUT_LENGTH) {
5477 input = input.concat(input);
5478 }
5479 // 5381 is a magic number: http://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function
5480 var hash = 5381;
5481 for (var i = 0; i < input.length; ++i) {
5482 hash = ((hash << 5) + hash) + input.charCodeAt(i);
5483 // 'hash' is of number type which means 53 bit integer (http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types-number-type)
5484 // 'hash & hash' will keep it 32 bit integer - just to make it clearer what the result is.
5485 hash = hash & hash;
5486 }
5487 return Math.abs(hash);
5488 };
5489 // We're using 32 bit math, hence max value is (2^31 - 1)
5490 HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;
5491 // (Magic number) DJB algorithm can't work on shorter strings (results in poor distribution
5492 HashCodeScoreGenerator.MIN_INPUT_LENGTH = 8;
5493 return HashCodeScoreGenerator;
5494 }());
5495
5496 var SamplingScoreGenerator = /** @class */ (function () {
5497 function SamplingScoreGenerator() {
5498 this.hashCodeGeneragor = new HashCodeScoreGenerator();
5499 this.keys = new ContextTagKeys();
5500 }
5501 SamplingScoreGenerator.prototype.getSamplingScore = function (item) {
5502 var score = 0;
5503 if (item.tags && item.tags[this.keys.userId]) {
5504 score = this.hashCodeGeneragor.getHashCodeScore(item.tags[this.keys.userId]);
5505 }
5506 else if (item.ext && item.ext.user && item.ext.user.id) {
5507 score = this.hashCodeGeneragor.getHashCodeScore(item.ext.user.id);
5508 }
5509 else if (item.tags && item.tags[this.keys.operationId]) {
5510 score = this.hashCodeGeneragor.getHashCodeScore(item.tags[this.keys.operationId]);
5511 }
5512 else if (item.ext && item.ext.telemetryTrace && item.ext.telemetryTrace.traceID) {
5513 score = this.hashCodeGeneragor.getHashCodeScore(item.ext.telemetryTrace.traceID);
5514 }
5515 else {
5516 // tslint:disable-next-line:insecure-random
5517 score = (Math.random() * 100);
5518 }
5519 return score;
5520 };
5521 return SamplingScoreGenerator;
5522 }());
5523
5524 var Sample = /** @class */ (function () {
5525 function Sample(sampleRate, logger) {
5526 // We're using 32 bit math, hence max value is (2^31 - 1)
5527 this.INT_MAX_VALUE = 2147483647;
5528 this._logger = CoreUtils.isNullOrUndefined(logger) ? new DiagnosticLogger() : logger;
5529 if (sampleRate > 100 || sampleRate < 0) {
5530 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.SampleRateOutOfRange, "Sampling rate is out of range (0..100). Sampling will be disabled, you may be sending too much data which may affect your AI service level.", { samplingRate: sampleRate }, true);
5531 this.sampleRate = 100;
5532 }
5533 this.sampleRate = sampleRate;
5534 this.samplingScoreGenerator = new SamplingScoreGenerator();
5535 }
5536 /**
5537 * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).
5538 */
5539 Sample.prototype.isSampledIn = function (envelope) {
5540 var samplingPercentage = this.sampleRate; // 0 - 100
5541 var isSampledIn = false;
5542 if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {
5543 return true;
5544 }
5545 else if (envelope.baseType === Metric.dataType) {
5546 // exclude MetricData telemetry from sampling
5547 return true;
5548 }
5549 isSampledIn = this.samplingScoreGenerator.getSamplingScore(envelope) < samplingPercentage;
5550 return isSampledIn;
5551 };
5552 return Sample;
5553 }());
5554
5555 var Sender = /** @class */ (function (_super) {
5556 __extends(Sender, _super);
5557 function Sender() {
5558 var _this = _super !== null && _super.apply(this, arguments) || this;
5559 _this.priority = 1001;
5560 _this.identifier = BreezeChannelIdentifier;
5561 /**
5562 * Whether XMLHttpRequest object is supported. Older version of IE (8,9) do not support it.
5563 */
5564 _this._XMLHttpRequestSupported = false;
5565 return _this;
5566 }
5567 Sender.constructEnvelope = function (orig, iKey, logger) {
5568 var envelope;
5569 if (iKey !== orig.iKey && !CoreUtils.isNullOrUndefined(iKey)) {
5570 envelope = __assign({}, orig, { iKey: iKey });
5571 }
5572 else {
5573 envelope = orig;
5574 }
5575 switch (envelope.baseType) {
5576 case Event$1.dataType:
5577 return EventEnvelopeCreator.EventEnvelopeCreator.Create(logger, envelope);
5578 case Trace.dataType:
5579 return TraceEnvelopeCreator.TraceEnvelopeCreator.Create(logger, envelope);
5580 case PageView.dataType:
5581 return PageViewEnvelopeCreator.PageViewEnvelopeCreator.Create(logger, envelope);
5582 case PageViewPerformance.dataType:
5583 return PageViewPerformanceEnvelopeCreator.PageViewPerformanceEnvelopeCreator.Create(logger, envelope);
5584 case Exception.dataType:
5585 return ExceptionEnvelopeCreator.ExceptionEnvelopeCreator.Create(logger, envelope);
5586 case Metric.dataType:
5587 return MetricEnvelopeCreator.MetricEnvelopeCreator.Create(logger, envelope);
5588 case RemoteDependencyData$1.dataType:
5589 return DependencyEnvelopeCreator.DependencyEnvelopeCreator.Create(logger, envelope);
5590 default:
5591 return EventEnvelopeCreator.EventEnvelopeCreator.Create(logger, envelope);
5592 }
5593 };
5594 Sender._getDefaultAppInsightsChannelConfig = function () {
5595 // set default values
5596 return {
5597 endpointUrl: function () { return "https://dc.services.visualstudio.com/v2/track"; },
5598 emitLineDelimitedJson: function () { return false; },
5599 maxBatchInterval: function () { return 15000; },
5600 maxBatchSizeInBytes: function () { return 102400; },
5601 disableTelemetry: function () { return false; },
5602 enableSessionStorageBuffer: function () { return true; },
5603 isRetryDisabled: function () { return false; },
5604 isBeaconApiDisabled: function () { return true; },
5605 onunloadDisableBeacon: function () { return false; },
5606 instrumentationKey: function () { return undefined; },
5607 namePrefix: function () { return undefined; },
5608 samplingPercentage: function () { return 100; }
5609 };
5610 };
5611 Sender._getEmptyAppInsightsChannelConfig = function () {
5612 return {
5613 endpointUrl: undefined,
5614 emitLineDelimitedJson: undefined,
5615 maxBatchInterval: undefined,
5616 maxBatchSizeInBytes: undefined,
5617 disableTelemetry: undefined,
5618 enableSessionStorageBuffer: undefined,
5619 isRetryDisabled: undefined,
5620 isBeaconApiDisabled: undefined,
5621 onunloadDisableBeacon: undefined,
5622 instrumentationKey: undefined,
5623 namePrefix: undefined,
5624 samplingPercentage: undefined
5625 };
5626 };
5627 Sender.prototype.pause = function () {
5628 throw new Error("Method not implemented.");
5629 };
5630 Sender.prototype.resume = function () {
5631 throw new Error("Method not implemented.");
5632 };
5633 Sender.prototype.flush = function () {
5634 try {
5635 this.triggerSend();
5636 }
5637 catch (e) {
5638 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FlushFailed, "flush failed, telemetry will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
5639 }
5640 };
5641 Sender.prototype.onunloadFlush = function () {
5642 if ((this._senderConfig.onunloadDisableBeacon() === false || this._senderConfig.isBeaconApiDisabled() === false) && Util.IsBeaconApiSupported()) {
5643 try {
5644 this.triggerSend(true, this._beaconSender);
5645 }
5646 catch (e) {
5647 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedToSendQueuedTelemetry, "failed to flush with beacon sender on page unload, telemetry will not be collected: " + Util.getExceptionName(e), { exception: Util.dump(e) });
5648 }
5649 }
5650 else {
5651 this.flush();
5652 }
5653 };
5654 Sender.prototype.teardown = function () {
5655 throw new Error("Method not implemented.");
5656 };
5657 Sender.prototype.initialize = function (config, core, extensions, pluginChain) {
5658 _super.prototype.initialize.call(this, config, core, extensions, pluginChain);
5659 var ctx = this._getTelCtx();
5660 var identifier = this.identifier;
5661 this._serializer = new Serializer(core.logger);
5662 this._consecutiveErrors = 0;
5663 this._retryAt = null;
5664 this._lastSend = 0;
5665 this._sender = null;
5666 var defaultConfig = Sender._getDefaultAppInsightsChannelConfig();
5667 this._senderConfig = Sender._getEmptyAppInsightsChannelConfig();
5668 var _loop_1 = function (field) {
5669 this_1._senderConfig[field] = function () { return ctx.getConfig(identifier, field, defaultConfig[field]()); };
5670 };
5671 var this_1 = this;
5672 for (var field in defaultConfig) {
5673 _loop_1(field);
5674 }
5675 this._buffer = (this._senderConfig.enableSessionStorageBuffer && Util.canUseSessionStorage())
5676 ? new SessionStorageSendBuffer(this.diagLog(), this._senderConfig) : new ArraySendBuffer(this._senderConfig);
5677 this._sample = new Sample(this._senderConfig.samplingPercentage(), this.diagLog());
5678 if (!this._senderConfig.isBeaconApiDisabled() && Util.IsBeaconApiSupported()) {
5679 this._sender = this._beaconSender;
5680 }
5681 else {
5682 if (!CoreUtils.isUndefined(XMLHttpRequest)) {
5683 var testXhr = new XMLHttpRequest();
5684 if ("withCredentials" in testXhr) {
5685 this._sender = this._xhrSender;
5686 this._XMLHttpRequestSupported = true;
5687 }
5688 else if (!CoreUtils.isUndefined(XDomainRequest)) {
5689 this._sender = this._xdrSender; // IE 8 and 9
5690 }
5691 }
5692 }
5693 };
5694 Sender.prototype.processTelemetry = function (telemetryItem, itemCtx) {
5695 itemCtx = this._getTelCtx(itemCtx);
5696 try {
5697 // if master off switch is set, don't send any data
5698 if (this._senderConfig.disableTelemetry()) {
5699 // Do not send/save data
5700 return;
5701 }
5702 // validate input
5703 if (!telemetryItem) {
5704 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSendEmptyTelemetry, "Cannot send empty telemetry");
5705 return;
5706 }
5707 // validate event
5708 if (telemetryItem.baseData && !telemetryItem.baseType) {
5709 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.InvalidEvent, "Cannot send telemetry without baseData and baseType");
5710 return;
5711 }
5712 if (!telemetryItem.baseType) {
5713 // Default
5714 telemetryItem.baseType = "EventData";
5715 }
5716 // ensure a sender was constructed
5717 if (!this._sender) {
5718 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.SenderNotInitialized, "Sender was not initialized");
5719 return;
5720 }
5721 // check if this item should be sampled in, else add sampleRate tag
5722 if (!this._isSampledIn(telemetryItem)) {
5723 // Item is sampled out, do not send it
5724 itemCtx.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TelemetrySampledAndNotSent, "Telemetry item was sampled out and not sent", { SampleRate: this._sample.sampleRate });
5725 return;
5726 }
5727 else {
5728 telemetryItem[SampleRate] = this._sample.sampleRate;
5729 }
5730 // construct an envelope that Application Insights endpoint can understand
5731 var aiEnvelope_1 = Sender.constructEnvelope(telemetryItem, this._senderConfig.instrumentationKey(), itemCtx.diagLog());
5732 if (!aiEnvelope_1) {
5733 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CreateEnvelopeError, "Unable to create an AppInsights envelope");
5734 return;
5735 }
5736 var doNotSendItem_1 = false;
5737 // this is for running in legacy mode, where customer may already have a custom initializer present
5738 if (telemetryItem.tags && telemetryItem.tags[ProcessLegacy]) {
5739 CoreUtils.arrForEach(telemetryItem.tags[ProcessLegacy], function (callBack) {
5740 try {
5741 if (callBack && callBack(aiEnvelope_1) === false) {
5742 doNotSendItem_1 = true;
5743 itemCtx.diagLog().warnToConsole("Telemetry processor check returns false");
5744 }
5745 }
5746 catch (e) {
5747 // log error but dont stop executing rest of the telemetry initializers
5748 // doNotSendItem = true;
5749 itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + Util.getExceptionName(e), { exception: Util.dump(e) }, true);
5750 }
5751 });
5752 delete telemetryItem.tags[ProcessLegacy];
5753 }
5754 if (doNotSendItem_1) {
5755 return; // do not send, no need to execute next plugin
5756 }
5757 // check if the incoming payload is too large, truncate if necessary
5758 var payload = this._serializer.serialize(aiEnvelope_1);
5759 // flush if we would exceed the max-size limit by adding this item
5760 var bufferPayload = this._buffer.getItems();
5761 var batch = this._buffer.batchPayloads(bufferPayload);
5762 if (batch && (batch.length + payload.length > this._senderConfig.maxBatchSizeInBytes())) {
5763 this.triggerSend();
5764 }
5765 // enqueue the payload
5766 this._buffer.enqueue(payload);
5767 // ensure an invocation timeout is set
5768 this._setupTimer();
5769 }
5770 catch (e) {
5771 itemCtx.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedAddingTelemetryToBuffer, "Failed adding telemetry to the sender's buffer, some telemetry will be lost: " + Util.getExceptionName(e), { exception: Util.dump(e) });
5772 }
5773 // hand off the telemetry item to the next plugin
5774 this.processNext(telemetryItem, itemCtx);
5775 };
5776 /**
5777 * xhr state changes
5778 */
5779 Sender.prototype._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) {
5780 if (xhr.readyState === 4) {
5781 var response = null;
5782 if (!this._appId) {
5783 response = this._parseResponse(xhr.responseText || xhr.response);
5784 if (response && response.appId) {
5785 this._appId = response.appId;
5786 }
5787 }
5788 if ((xhr.status < 200 || xhr.status >= 300) && xhr.status !== 0) {
5789 if (!this._senderConfig.isRetryDisabled() && this._isRetriable(xhr.status)) {
5790 this._resendPayload(payload);
5791 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, ". " +
5792 "Response code " + xhr.status + ". Will retry to send " + payload.length + " items.");
5793 }
5794 else {
5795 this._onError(payload, this._formatErrorMessageXhr(xhr));
5796 }
5797 }
5798 else if (Offline.isOffline()) {
5799 // Note: Don't check for staus == 0, since adblock gives this code
5800 if (!this._senderConfig.isRetryDisabled()) {
5801 var offlineBackOffMultiplier = 10; // arbritrary number
5802 this._resendPayload(payload, offlineBackOffMultiplier);
5803 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, ". Offline - Response Code: " + xhr.status + ". Offline status: " + Offline.isOffline() + ". Will retry to send " + payload.length + " items.");
5804 }
5805 }
5806 else {
5807 if (xhr.status === 206) {
5808 if (!response) {
5809 response = this._parseResponse(xhr.responseText || xhr.response);
5810 }
5811 if (response && !this._senderConfig.isRetryDisabled()) {
5812 this._onPartialSuccess(payload, response);
5813 }
5814 else {
5815 this._onError(payload, this._formatErrorMessageXhr(xhr));
5816 }
5817 }
5818 else {
5819 this._consecutiveErrors = 0;
5820 this._onSuccess(payload, countOfItemsInPayload);
5821 }
5822 }
5823 }
5824 };
5825 /**
5826 * Immediately send buffered data
5827 * @param async {boolean} - Indicates if the events should be sent asynchronously
5828 * @param forcedSender {SenderFunction} - Indicates the forcedSender, undefined if not passed
5829 */
5830 Sender.prototype.triggerSend = function (async, forcedSender) {
5831 if (async === void 0) { async = true; }
5832 try {
5833 // Send data only if disableTelemetry is false
5834 if (!this._senderConfig.disableTelemetry()) {
5835 if (this._buffer.count() > 0) {
5836 var payload = this._buffer.getItems();
5837 // invoke send
5838 if (forcedSender) {
5839 forcedSender.call(this, payload, async);
5840 }
5841 else {
5842 this._sender(payload, async);
5843 }
5844 }
5845 // update lastSend time to enable throttling
5846 this._lastSend = +new Date;
5847 }
5848 else {
5849 this._buffer.clear();
5850 }
5851 clearTimeout(this._timeoutHandle);
5852 this._timeoutHandle = null;
5853 this._retryAt = null;
5854 }
5855 catch (e) {
5856 /* Ignore this error for IE under v10 */
5857 if (!Util.getIEVersion() || Util.getIEVersion() > 9) {
5858 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TransmissionFailed, "Telemetry transmission failed, some telemetry will be lost: " + Util.getExceptionName(e), { exception: Util.dump(e) });
5859 }
5860 }
5861 };
5862 /**
5863 * error handler
5864 */
5865 Sender.prototype._onError = function (payload, message, event) {
5866 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.OnError, "Failed to send telemetry.", { message: message });
5867 this._buffer.clearSent(payload);
5868 };
5869 /**
5870 * partial success handler
5871 */
5872 Sender.prototype._onPartialSuccess = function (payload, results) {
5873 var failed = [];
5874 var retry = [];
5875 // Iterate through the reversed array of errors so that splicing doesn't have invalid indexes after the first item.
5876 var errors = results.errors.reverse();
5877 for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {
5878 var error = errors_1[_i];
5879 var extracted = payload.splice(error.index, 1)[0];
5880 if (this._isRetriable(error.statusCode)) {
5881 retry.push(extracted);
5882 }
5883 else {
5884 // All other errors, including: 402 (Monthly quota exceeded) and 439 (Too many requests and refresh cache).
5885 failed.push(extracted);
5886 }
5887 }
5888 if (payload.length > 0) {
5889 this._onSuccess(payload, results.itemsAccepted);
5890 }
5891 if (failed.length > 0) {
5892 this._onError(failed, this._formatErrorMessageXhr(null, ['partial success', results.itemsAccepted, 'of', results.itemsReceived].join(' ')));
5893 }
5894 if (retry.length > 0) {
5895 this._resendPayload(retry);
5896 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, "Partial success. " +
5897 "Delivered: " + payload.length + ", Failed: " + failed.length +
5898 ". Will retry to send " + retry.length + " our of " + results.itemsReceived + " items");
5899 }
5900 };
5901 /**
5902 * success handler
5903 */
5904 Sender.prototype._onSuccess = function (payload, countOfItemsInPayload) {
5905 this._buffer.clearSent(payload);
5906 };
5907 /**
5908 * xdr state changes
5909 */
5910 Sender.prototype._xdrOnLoad = function (xdr, payload) {
5911 if (xdr && (xdr.responseText + "" === "200" || xdr.responseText === "")) {
5912 this._consecutiveErrors = 0;
5913 this._onSuccess(payload, 0);
5914 }
5915 else {
5916 var results = this._parseResponse(xdr.responseText);
5917 if (results && results.itemsReceived && results.itemsReceived > results.itemsAccepted
5918 && !this._senderConfig.isRetryDisabled()) {
5919 this._onPartialSuccess(payload, results);
5920 }
5921 else {
5922 this._onError(payload, this._formatErrorMessageXdr(xdr));
5923 }
5924 }
5925 };
5926 Sender.prototype._isSampledIn = function (envelope) {
5927 return this._sample.isSampledIn(envelope);
5928 };
5929 /**
5930 * Send Beacon API request
5931 * @param payload {string} - The data payload to be sent.
5932 * @param isAsync {boolean} - not used
5933 * Note: Beacon API does not support custom headers and we are not able to get
5934 * appId from the backend for the correct correlation.
5935 */
5936 Sender.prototype._beaconSender = function (payload, isAsync) {
5937 var url = this._senderConfig.endpointUrl();
5938 var batch = this._buffer.batchPayloads(payload);
5939 // Chrome only allows CORS-safelisted values for the sendBeacon data argument
5940 // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283
5941 var plainTextBatch = new Blob([batch], { type: 'text/plain;charset=UTF-8' });
5942 // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.
5943 var queued = getNavigator().sendBeacon(url, plainTextBatch);
5944 if (queued) {
5945 this._buffer.markAsSent(payload);
5946 // no response from beaconSender, clear buffer
5947 this._onSuccess(payload, payload.length);
5948 }
5949 else {
5950 this._xhrSender(payload, true);
5951 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, ". " + "Failed to send telemetry with Beacon API, retried with xhrSender.");
5952 }
5953 };
5954 /**
5955 * Send XMLHttpRequest
5956 * @param payload {string} - The data payload to be sent.
5957 * @param isAsync {boolean} - Indicates if the request should be sent asynchronously
5958 */
5959 Sender.prototype._xhrSender = function (payload, isAsync) {
5960 var _this = this;
5961 var xhr = new XMLHttpRequest();
5962 xhr[DisabledPropertyName] = true;
5963 xhr.open("POST", this._senderConfig.endpointUrl(), isAsync);
5964 xhr.setRequestHeader("Content-type", "application/json");
5965 // append Sdk-Context request header only in case of breeze endpoint
5966 if (Util.isInternalApplicationInsightsEndpoint(this._senderConfig.endpointUrl())) {
5967 xhr.setRequestHeader(RequestHeaders.sdkContextHeader, RequestHeaders.sdkContextHeaderAppIdRequest);
5968 }
5969 xhr.onreadystatechange = function () { return _this._xhrReadyStateChange(xhr, payload, payload.length); };
5970 xhr.onerror = function (event) { return _this._onError(payload, _this._formatErrorMessageXhr(xhr), event); };
5971 // compose an array of payloads
5972 var batch = this._buffer.batchPayloads(payload);
5973 xhr.send(batch);
5974 this._buffer.markAsSent(payload);
5975 };
5976 /**
5977 * Parses the response from the backend.
5978 * @param response - XMLHttpRequest or XDomainRequest response
5979 */
5980 Sender.prototype._parseResponse = function (response) {
5981 try {
5982 if (response && response !== "") {
5983 var result = getJSON().parse(response);
5984 if (result && result.itemsReceived && result.itemsReceived >= result.itemsAccepted &&
5985 result.itemsReceived - result.itemsAccepted === result.errors.length) {
5986 return result;
5987 }
5988 }
5989 }
5990 catch (e) {
5991 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.InvalidBackendResponse, "Cannot parse the response. " + Util.getExceptionName(e), {
5992 response: response
5993 });
5994 }
5995 return null;
5996 };
5997 /**
5998 * Resend payload. Adds payload back to the send buffer and setup a send timer (with exponential backoff).
5999 * @param payload
6000 */
6001 Sender.prototype._resendPayload = function (payload, linearFactor) {
6002 if (linearFactor === void 0) { linearFactor = 1; }
6003 if (!payload || payload.length === 0) {
6004 return;
6005 }
6006 this._buffer.clearSent(payload);
6007 this._consecutiveErrors++;
6008 for (var _i = 0, payload_1 = payload; _i < payload_1.length; _i++) {
6009 var item = payload_1[_i];
6010 this._buffer.enqueue(item);
6011 }
6012 // setup timer
6013 this._setRetryTime(linearFactor);
6014 this._setupTimer();
6015 };
6016 /**
6017 * Calculates the time to wait before retrying in case of an error based on
6018 * http://en.wikipedia.org/wiki/Exponential_backoff
6019 */
6020 Sender.prototype._setRetryTime = function (linearFactor) {
6021 var SlotDelayInSeconds = 10;
6022 var delayInSeconds;
6023 if (this._consecutiveErrors <= 1) {
6024 delayInSeconds = SlotDelayInSeconds;
6025 }
6026 else {
6027 var backOffSlot = (Math.pow(2, this._consecutiveErrors) - 1) / 2;
6028 // tslint:disable-next-line:insecure-random
6029 var backOffDelay = Math.floor(Math.random() * backOffSlot * SlotDelayInSeconds) + 1;
6030 backOffDelay = linearFactor * backOffDelay;
6031 delayInSeconds = Math.max(Math.min(backOffDelay, 3600), SlotDelayInSeconds);
6032 }
6033 // TODO: Log the backoff time like the C# version does.
6034 var retryAfterTimeSpan = Date.now() + (delayInSeconds * 1000);
6035 // TODO: Log the retry at time like the C# version does.
6036 this._retryAt = retryAfterTimeSpan;
6037 };
6038 /**
6039 * Sets up the timer which triggers actually sending the data.
6040 */
6041 Sender.prototype._setupTimer = function () {
6042 var _this = this;
6043 if (!this._timeoutHandle) {
6044 var retryInterval = this._retryAt ? Math.max(0, this._retryAt - Date.now()) : 0;
6045 var timerValue = Math.max(this._senderConfig.maxBatchInterval(), retryInterval);
6046 this._timeoutHandle = setTimeout(function () {
6047 _this.triggerSend();
6048 }, timerValue);
6049 }
6050 };
6051 /**
6052 * Checks if the SDK should resend the payload after receiving this status code from the backend.
6053 * @param statusCode
6054 */
6055 Sender.prototype._isRetriable = function (statusCode) {
6056 return statusCode === 408 // Timeout
6057 || statusCode === 429 // Too many requests.
6058 || statusCode === 500 // Internal server error.
6059 || statusCode === 503; // Service unavailable.
6060 };
6061 Sender.prototype._formatErrorMessageXhr = function (xhr, message) {
6062 if (xhr) {
6063 return "XMLHttpRequest,Status:" + xhr.status + ",Response:" + xhr.responseText || xhr.response || "";
6064 }
6065 return message;
6066 };
6067 /**
6068 * Send XDomainRequest
6069 * @param payload {string} - The data payload to be sent.
6070 * @param isAsync {boolean} - Indicates if the request should be sent asynchronously
6071 *
6072 * Note: XDomainRequest does not support sync requests. This 'isAsync' parameter is added
6073 * to maintain consistency with the xhrSender's contract
6074 * Note: XDomainRequest does not support custom headers and we are not able to get
6075 * appId from the backend for the correct correlation.
6076 */
6077 Sender.prototype._xdrSender = function (payload, isAsync) {
6078 var _this = this;
6079 var _window = getWindow();
6080 var xdr = new XDomainRequest();
6081 xdr.onload = function () { return _this._xdrOnLoad(xdr, payload); };
6082 xdr.onerror = function (event) { return _this._onError(payload, _this._formatErrorMessageXdr(xdr), event); };
6083 // XDomainRequest requires the same protocol as the hosting page.
6084 // If the protocol doesn't match, we can't send the telemetry :(.
6085 var hostingProtocol = _window && _window.location && _window.location.protocol || "";
6086 if (this._senderConfig.endpointUrl().lastIndexOf(hostingProtocol, 0) !== 0) {
6087 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, ". " +
6088 "Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.");
6089 this._buffer.clear();
6090 return;
6091 }
6092 var endpointUrl = this._senderConfig.endpointUrl().replace(/^(https?:)/, "");
6093 xdr.open('POST', endpointUrl);
6094 // compose an array of payloads
6095 var batch = this._buffer.batchPayloads(payload);
6096 xdr.send(batch);
6097 this._buffer.markAsSent(payload);
6098 };
6099 Sender.prototype._formatErrorMessageXdr = function (xdr, message) {
6100 if (xdr) {
6101 return "XDomainRequest,Response:" + xdr.responseText || "";
6102 }
6103 return message;
6104 };
6105 return Sender;
6106 }(BaseTelemetryPlugin));
6107
6108 var Session = /** @class */ (function () {
6109 function Session() {
6110 }
6111 return Session;
6112 }());
6113 var _SessionManager = /** @class */ (function () {
6114 function _SessionManager(config, logger) {
6115 var _this = this;
6116 if (CoreUtils.isNullOrUndefined(logger)) {
6117 this._logger = new DiagnosticLogger();
6118 }
6119 else {
6120 this._logger = logger;
6121 }
6122 if (!config) {
6123 config = {};
6124 }
6125 if (!(typeof config.sessionExpirationMs === "function")) {
6126 config.sessionExpirationMs = function () { return _SessionManager.acquisitionSpan; };
6127 }
6128 if (!(typeof config.sessionRenewalMs === "function")) {
6129 config.sessionRenewalMs = function () { return _SessionManager.renewalSpan; };
6130 }
6131 this.config = config;
6132 this._storageNamePrefix = function () { return _this.config.namePrefix && _this.config.namePrefix() ? _SessionManager.cookieNameConst + _this.config.namePrefix() : _SessionManager.cookieNameConst; };
6133 this.automaticSession = new Session();
6134 }
6135 _SessionManager.prototype.update = function () {
6136 if (!this.automaticSession.id) {
6137 this.initializeAutomaticSession();
6138 }
6139 var now = DateTimeUtils.Now();
6140 var acquisitionExpired = this.config.sessionExpirationMs() === 0 ? false : now - this.automaticSession.acquisitionDate > this.config.sessionExpirationMs();
6141 var renewalExpired = this.config.sessionExpirationMs() === 0 ? false : now - this.automaticSession.renewalDate > this.config.sessionRenewalMs();
6142 // renew if acquisitionSpan or renewalSpan has ellapsed
6143 if (acquisitionExpired || renewalExpired) {
6144 // update automaticSession so session state has correct id
6145 this.renew();
6146 }
6147 else {
6148 // do not update the cookie more often than cookieUpdateInterval
6149 if (!this.cookieUpdatedTimestamp || now - this.cookieUpdatedTimestamp > _SessionManager.cookieUpdateInterval) {
6150 this.automaticSession.renewalDate = now;
6151 this.setCookie(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate);
6152 }
6153 }
6154 };
6155 /**
6156 * Record the current state of the automatic session and store it in our cookie string format
6157 * into the browser's local storage. This is used to restore the session data when the cookie
6158 * expires.
6159 */
6160 _SessionManager.prototype.backup = function () {
6161 this.setStorage(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate);
6162 };
6163 /**
6164 * Use config.namePrefix + ai_session cookie data or local storage data (when the cookie is unavailable) to
6165 * initialize the automatic session.
6166 */
6167 _SessionManager.prototype.initializeAutomaticSession = function () {
6168 var cookie = Util.getCookie(this._logger, this._storageNamePrefix());
6169 if (cookie && typeof cookie.split === "function") {
6170 this.initializeAutomaticSessionWithData(cookie);
6171 }
6172 else {
6173 // There's no cookie, but we might have session data in local storage
6174 // This can happen if the session expired or the user actively deleted the cookie
6175 // We only want to recover data if the cookie is missing from expiry. We should respect the user's wishes if the cookie was deleted actively.
6176 // The User class handles this for us and deletes our local storage object if the persistent user cookie was removed.
6177 var storage = Util.getStorage(this._logger, this._storageNamePrefix());
6178 if (storage) {
6179 this.initializeAutomaticSessionWithData(storage);
6180 }
6181 }
6182 if (!this.automaticSession.id) {
6183 this.renew();
6184 }
6185 };
6186 /**
6187 * Extract id, aquisitionDate, and renewalDate from an ai_session payload string and
6188 * use this data to initialize automaticSession.
6189 *
6190 * @param {string} sessionData - The string stored in an ai_session cookie or local storage backup
6191 */
6192 _SessionManager.prototype.initializeAutomaticSessionWithData = function (sessionData) {
6193 var params = sessionData.split("|");
6194 if (params.length > 0) {
6195 this.automaticSession.id = params[0];
6196 }
6197 try {
6198 if (params.length > 1) {
6199 var acq = +params[1];
6200 this.automaticSession.acquisitionDate = +new Date(acq);
6201 this.automaticSession.acquisitionDate = this.automaticSession.acquisitionDate > 0 ? this.automaticSession.acquisitionDate : 0;
6202 }
6203 if (params.length > 2) {
6204 var renewal = +params[2];
6205 this.automaticSession.renewalDate = +new Date(renewal);
6206 this.automaticSession.renewalDate = this.automaticSession.renewalDate > 0 ? this.automaticSession.renewalDate : 0;
6207 }
6208 }
6209 catch (e) {
6210 this._logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.ErrorParsingAISessionCookie, "Error parsing ai_session cookie, session will be reset: " + Util.getExceptionName(e), { exception: Util.dump(e) });
6211 }
6212 if (this.automaticSession.renewalDate === 0) {
6213 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.SessionRenewalDateIsZero, "AI session renewal date is 0, session will be reset.");
6214 }
6215 };
6216 _SessionManager.prototype.renew = function () {
6217 var now = DateTimeUtils.Now();
6218 this.automaticSession.id = Util.newId();
6219 this.automaticSession.acquisitionDate = now;
6220 this.automaticSession.renewalDate = now;
6221 this.setCookie(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate);
6222 // If this browser does not support local storage, fire an internal log to keep track of it at this point
6223 if (!Util.canUseLocalStorage()) {
6224 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserDoesNotSupportLocalStorage, "Browser does not support local storage. Session durations will be inaccurate.");
6225 }
6226 };
6227 _SessionManager.prototype.setCookie = function (guid, acq, renewal) {
6228 // Set cookie to expire after the session expiry time passes or the session renewal deadline, whichever is sooner
6229 // Expiring the cookie will cause the session to expire even if the user isn't on the page
6230 var acquisitionExpiry = acq + this.config.sessionExpirationMs();
6231 var renewalExpiry = renewal + this.config.sessionRenewalMs();
6232 var cookieExpiry = new Date();
6233 var cookie = [guid, acq, renewal];
6234 if (acquisitionExpiry < renewalExpiry) {
6235 cookieExpiry.setTime(acquisitionExpiry);
6236 }
6237 else {
6238 cookieExpiry.setTime(renewalExpiry);
6239 }
6240 var cookieDomnain = this.config.cookieDomain ? this.config.cookieDomain() : null;
6241 // if sessionExpirationMs is set to 0, it means the expiry is set to 0 for this session cookie
6242 // A cookie with 0 expiry in the session cookie will never expire for that browser session. If the browser is closed the cookie expires.
6243 // Another browser instance does not inherit this cookie.
6244 var UTCString = this.config.sessionExpirationMs() === 0 ? '0' : cookieExpiry.toUTCString();
6245 Util.setCookie(this._logger, this._storageNamePrefix(), cookie.join('|') + ';expires=' + UTCString, cookieDomnain);
6246 this.cookieUpdatedTimestamp = DateTimeUtils.Now();
6247 };
6248 _SessionManager.prototype.setStorage = function (guid, acq, renewal) {
6249 // Keep data in local storage to retain the last session id, allowing us to cleanly end the session when it expires
6250 // Browsers that don't support local storage won't be able to end sessions cleanly from the client
6251 // The server will notice this and end the sessions itself, with loss of accurate session duration
6252 Util.setStorage(this._logger, this._storageNamePrefix(), [guid, acq, renewal].join('|'));
6253 };
6254 _SessionManager.acquisitionSpan = 86400000; // 24 hours in ms
6255 _SessionManager.renewalSpan = 1800000; // 30 minutes in ms
6256 _SessionManager.cookieUpdateInterval = 60000; // 1 minute in ms
6257 _SessionManager.cookieNameConst = 'ai_session';
6258 return _SessionManager;
6259 }());
6260
6261 var Application = /** @class */ (function () {
6262 function Application() {
6263 }
6264 return Application;
6265 }());
6266
6267 var Device = /** @class */ (function () {
6268 /**
6269 * Constructs a new instance of the Device class
6270 */
6271 function Device() {
6272 // don't attempt to fingerprint browsers
6273 this.id = "browser";
6274 // Device type is a dimension in our data platform
6275 // Setting it to 'Browser' allows to separate client and server dependencies/exceptions
6276 this.deviceClass = "Browser";
6277 }
6278 return Device;
6279 }());
6280
6281 var Version = "2.4.4";
6282 var Internal = /** @class */ (function () {
6283 /**
6284 * Constructs a new instance of the internal telemetry data class.
6285 */
6286 function Internal(config) {
6287 this.sdkVersion = (config.sdkExtension && config.sdkExtension() ? config.sdkExtension() + "_" : "") + "javascript:" + Version;
6288 }
6289 return Internal;
6290 }());
6291
6292 var User = /** @class */ (function () {
6293 function User(config, logger) {
6294 this.isNewUser = false;
6295 this._logger = logger;
6296 // get userId or create new one if none exists
6297 var cookie = Util.getCookie(this._logger, User.userCookieName);
6298 if (cookie) {
6299 this.isNewUser = false;
6300 var params = cookie.split(User.cookieSeparator);
6301 if (params.length > 0) {
6302 this.id = params[0];
6303 }
6304 }
6305 this.config = config;
6306 if (!this.id) {
6307 this.id = Util.newId();
6308 var date = new Date();
6309 var acqStr = CoreUtils.toISOString(date);
6310 this.accountAcquisitionDate = acqStr;
6311 this.isNewUser = true;
6312 // without expiration, cookies expire at the end of the session
6313 // set it to 365 days from now
6314 // 365 * 24 * 60 * 60 * 1000 = 31536000000
6315 date.setTime(date.getTime() + 31536000000);
6316 var newCookie = [this.id, acqStr];
6317 var cookieDomain = this.config.cookieDomain ? this.config.cookieDomain() : undefined;
6318 Util.setCookie(this._logger, User.userCookieName, newCookie.join(User.cookieSeparator) + ';expires=' + date.toUTCString(), cookieDomain);
6319 // If we have an config.namePrefix() + ai_session in local storage this means the user actively removed our cookies.
6320 // We should respect their wishes and clear ourselves from local storage
6321 var name_1 = config.namePrefix && config.namePrefix() ? config.namePrefix() + 'ai_session' : 'ai_session';
6322 Util.removeStorage(this._logger, name_1);
6323 }
6324 // We still take the account id from the ctor param for backward compatibility.
6325 // But if the the customer set the accountId through the newer setAuthenticatedUserContext API, we will override it.
6326 this.accountId = config.accountId ? config.accountId() : undefined;
6327 // Get the auth user id and account id from the cookie if exists
6328 // Cookie is in the pattern: <authenticatedId>|<accountId>
6329 var authCookie = Util.getCookie(this._logger, User.authUserCookieName);
6330 if (authCookie) {
6331 authCookie = decodeURI(authCookie);
6332 var authCookieString = authCookie.split(User.cookieSeparator);
6333 if (authCookieString[0]) {
6334 this.authenticatedId = authCookieString[0];
6335 }
6336 if (authCookieString.length > 1 && authCookieString[1]) {
6337 this.accountId = authCookieString[1];
6338 }
6339 }
6340 }
6341 /**
6342 * Sets the authenticated user id and the account id in this session.
6343 *
6344 * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.
6345 * @param accountId {string} - An optional string to represent the account associated with the authenticated user.
6346 */
6347 User.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {
6348 if (storeInCookie === void 0) { storeInCookie = false; }
6349 // Validate inputs to ensure no cookie control characters.
6350 var isInvalidInput = !this.validateUserInput(authenticatedUserId) || (accountId && !this.validateUserInput(accountId));
6351 if (isInvalidInput) {
6352 this._logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.SetAuthContextFailedAccountName, "Setting auth user context failed. " +
6353 "User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.", true);
6354 return;
6355 }
6356 // Create cookie string.
6357 this.authenticatedId = authenticatedUserId;
6358 var authCookie = this.authenticatedId;
6359 if (accountId) {
6360 this.accountId = accountId;
6361 authCookie = [this.authenticatedId, this.accountId].join(User.cookieSeparator);
6362 }
6363 if (storeInCookie) {
6364 // Set the cookie. No expiration date because this is a session cookie (expires when browser closed).
6365 // Encoding the cookie to handle unexpected unicode characters.
6366 Util.setCookie(this._logger, User.authUserCookieName, encodeURI(authCookie), this.config.cookieDomain());
6367 }
6368 };
6369 /**
6370 * Clears the authenticated user id and the account id from the user context.
6371 * @returns {}
6372 */
6373 User.prototype.clearAuthenticatedUserContext = function () {
6374 this.authenticatedId = null;
6375 this.accountId = null;
6376 Util.deleteCookie(this._logger, User.authUserCookieName);
6377 };
6378 User.prototype.validateUserInput = function (id) {
6379 // Validate:
6380 // 1. Id is a non-empty string.
6381 // 2. It does not contain special characters for cookies.
6382 if (typeof id !== 'string' ||
6383 !id ||
6384 id.match(/,|;|=| |\|/)) {
6385 return false;
6386 }
6387 return true;
6388 };
6389 User.cookieSeparator = '|';
6390 User.userCookieName = 'ai_user';
6391 User.authUserCookieName = 'ai_authUser';
6392 return User;
6393 }());
6394
6395 var Location = /** @class */ (function () {
6396 function Location() {
6397 }
6398 return Location;
6399 }());
6400
6401 var TelemetryTrace = /** @class */ (function () {
6402 function TelemetryTrace(id, parentId, name, logger) {
6403 this.traceID = id || Util.generateW3CId();
6404 this.parentID = parentId;
6405 this.name = name;
6406 var location = getLocation();
6407 if (!name && location && location.pathname) {
6408 this.name = location.pathname;
6409 }
6410 this.name = DataSanitizer.sanitizeString(logger, this.name);
6411 }
6412 return TelemetryTrace;
6413 }());
6414
6415 /**
6416 * PropertiesPlugin.ts
6417 * @copyright Microsoft 2018
6418 */
6419 var TelemetryContext = /** @class */ (function () {
6420 function TelemetryContext(logger, defaultConfig) {
6421 if (hasWindow()) {
6422 this.sessionManager = new _SessionManager(defaultConfig, logger);
6423 this.application = new Application();
6424 this.device = new Device();
6425 this.internal = new Internal(defaultConfig);
6426 this.location = new Location();
6427 this.user = new User(defaultConfig, logger);
6428 this.telemetryTrace = new TelemetryTrace(undefined, undefined, undefined, logger);
6429 this.session = new Session();
6430 }
6431 this.appId = function () { return null; };
6432 }
6433 TelemetryContext.prototype.applySessionContext = function (event, itemCtx) {
6434 var sessionContext = this.session || (this.sessionManager && this.sessionManager.automaticSession);
6435 if (sessionContext) {
6436 if (typeof sessionContext.id === "string") {
6437 event.ext.app.sesId = sessionContext.id;
6438 }
6439 }
6440 if (this.session) {
6441 // If customer set session info, apply his context; otherwise apply context automatically generated
6442 if (typeof this.session.id === "string") {
6443 event.ext.app.sesId = this.session.id;
6444 }
6445 else {
6446 event.ext.app.sesId = this.sessionManager.automaticSession.id;
6447 }
6448 }
6449 };
6450 TelemetryContext.prototype.applyOperatingSystemContxt = function (event, itemCtx) {
6451 if (this.os && this.os.name) {
6452 event.ext.os = this.os;
6453 }
6454 };
6455 TelemetryContext.prototype.applyApplicationContext = function (event, itemCtx) {
6456 if (this.application) {
6457 if (typeof this.application.ver === "string") {
6458 event.tags[CtxTagKeys.applicationVersion] = this.application.ver;
6459 }
6460 if (typeof this.application.build === "string") {
6461 event.tags[CtxTagKeys.applicationBuild] = this.application.build;
6462 }
6463 }
6464 };
6465 TelemetryContext.prototype.applyDeviceContext = function (event, itemCtx) {
6466 if (this.device) {
6467 if (typeof this.device.id === "string") {
6468 event.ext.device.localId = this.device.id;
6469 }
6470 if (typeof this.device.ip === "string") {
6471 event.ext.device.ip = this.device.ip;
6472 }
6473 if (typeof this.device.model === "string") {
6474 event.ext.device.model = this.device.model;
6475 }
6476 if (typeof this.device.deviceClass === "string") {
6477 event.ext.device.deviceClass = this.device.deviceClass;
6478 }
6479 }
6480 };
6481 TelemetryContext.prototype.applyInternalContext = function (event, itemCtx) {
6482 if (this.internal) {
6483 if (typeof this.internal.agentVersion === "string") {
6484 event.tags[CtxTagKeys.internalAgentVersion] = this.internal.agentVersion; // not mapped in CS 4.0
6485 }
6486 if (typeof this.internal.sdkVersion === "string") {
6487 event.tags[CtxTagKeys.internalSdkVersion] = this.internal.sdkVersion;
6488 }
6489 }
6490 };
6491 TelemetryContext.prototype.applyLocationContext = function (event, itemCtx) {
6492 if (this.location) {
6493 if (typeof this.location.ip === "string") {
6494 event.tags[CtxTagKeys.locationIp] = this.location.ip;
6495 }
6496 }
6497 };
6498 TelemetryContext.prototype.applyOperationContext = function (event, itemCtx) {
6499 if (this.telemetryTrace) {
6500 var trace = event.ext.trace || { traceID: undefined, parentID: undefined };
6501 if (typeof this.telemetryTrace.traceID === "string") {
6502 trace.traceID = this.telemetryTrace.traceID;
6503 }
6504 if (typeof this.telemetryTrace.name === "string") {
6505 trace.name = this.telemetryTrace.name;
6506 }
6507 if (typeof this.telemetryTrace.parentID === "string") {
6508 trace.parentID = this.telemetryTrace.parentID;
6509 }
6510 event.ext.trace = trace;
6511 }
6512 };
6513 TelemetryContext.prototype.applyWebContext = function (event, itemCtx) {
6514 if (this.web) {
6515 event.ext.web = event.ext.web || {};
6516 event.ext.web = this.web;
6517 }
6518 };
6519 TelemetryContext.prototype.applyUserContext = function (event, itemCtx) {
6520 if (this.user) {
6521 if (!event.tags) {
6522 event.tags = [];
6523 }
6524 // stays in tags
6525 if (typeof this.user.accountId === "string") {
6526 event.tags[CtxTagKeys.userAccountId] = this.user.accountId;
6527 }
6528 // CS 4.0
6529 if (typeof this.user.id === "string") {
6530 event.ext.user.id = this.user.id;
6531 }
6532 if (typeof this.user.authenticatedId === "string") {
6533 event.ext.user.authId = this.user.authenticatedId;
6534 }
6535 }
6536 };
6537 TelemetryContext.prototype.cleanUp = function (event, itemCtx) {
6538 if (event.ext[Extensions.DeviceExt] && CoreUtils.objKeys(event.ext[Extensions.DeviceExt]).length === 0) {
6539 delete event.ext[Extensions.DeviceExt];
6540 }
6541 if (event.ext[Extensions.UserExt] && CoreUtils.objKeys(event.ext[Extensions.UserExt]).length === 0) {
6542 delete event.ext[Extensions.UserExt];
6543 }
6544 if (event.ext[Extensions.WebExt] && CoreUtils.objKeys(event.ext[Extensions.WebExt]).length === 0) {
6545 delete event.ext[Extensions.WebExt];
6546 }
6547 if (event.ext[Extensions.OSExt] && CoreUtils.objKeys(event.ext[Extensions.OSExt]).length === 0) {
6548 delete event.ext[Extensions.OSExt];
6549 }
6550 if (event.ext[Extensions.AppExt] && CoreUtils.objKeys(event.ext[Extensions.AppExt]).length === 0) {
6551 delete event.ext[Extensions.AppExt];
6552 }
6553 if (event.ext[Extensions.TraceExt] && CoreUtils.objKeys(event.ext[Extensions.TraceExt]).length === 0) {
6554 delete event.ext[Extensions.TraceExt];
6555 }
6556 };
6557 return TelemetryContext;
6558 }());
6559
6560 /**
6561 * PropertiesPlugin.ts
6562 * @copyright Microsoft 2018
6563 */
6564 var PropertiesPlugin = /** @class */ (function (_super) {
6565 __extends(PropertiesPlugin, _super);
6566 function PropertiesPlugin() {
6567 var _this = _super !== null && _super.apply(this, arguments) || this;
6568 _this.priority = 110;
6569 _this.identifier = PropertiesPluginIdentifier;
6570 return _this;
6571 }
6572 PropertiesPlugin.getDefaultConfig = function () {
6573 var defaultConfig = {
6574 instrumentationKey: function () { return undefined; },
6575 accountId: function () { return null; },
6576 sessionRenewalMs: function () { return 30 * 60 * 1000; },
6577 samplingPercentage: function () { return 100; },
6578 sessionExpirationMs: function () { return 24 * 60 * 60 * 1000; },
6579 cookieDomain: function () { return null; },
6580 sdkExtension: function () { return null; },
6581 isBrowserLinkTrackingEnabled: function () { return false; },
6582 appId: function () { return null; },
6583 namePrefix: function () { return undefined; }
6584 };
6585 return defaultConfig;
6586 };
6587 PropertiesPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {
6588 var _this = this;
6589 _super.prototype.initialize.call(this, config, core, extensions, pluginChain);
6590 var ctx = this._getTelCtx();
6591 var identifier = this.identifier;
6592 var defaultConfig = PropertiesPlugin.getDefaultConfig();
6593 this._extensionConfig = this._extensionConfig || PropertiesPlugin.getDefaultConfig();
6594 var _loop_1 = function (field) {
6595 this_1._extensionConfig[field] = function () { return ctx.getConfig(identifier, field, defaultConfig[field]()); };
6596 };
6597 var this_1 = this;
6598 for (var field in defaultConfig) {
6599 _loop_1(field);
6600 }
6601 this.context = new TelemetryContext(core.logger, this._extensionConfig);
6602 this._breezeChannel = Util.getExtension(extensions, BreezeChannelIdentifier);
6603 this.context.appId = function () { return _this._breezeChannel ? _this._breezeChannel["_appId"] : null; };
6604 };
6605 /**
6606 * Add Part A fields to the event
6607 * @param event The event that needs to be processed
6608 */
6609 PropertiesPlugin.prototype.processTelemetry = function (event, itemCtx) {
6610 if (CoreUtils.isNullOrUndefined(event)) ;
6611 else {
6612 itemCtx = this._getTelCtx(itemCtx);
6613 // If the envelope is PageView, reset the internal message count so that we can send internal telemetry for the new page.
6614 if (event.name === PageView.envelopeType) {
6615 itemCtx.diagLog().resetInternalMessageCount();
6616 }
6617 if (this.context.session) {
6618 // If customer did not provide custom session id update the session manager
6619 if (typeof this.context.session.id !== "string") {
6620 this.context.sessionManager.update();
6621 }
6622 }
6623 this._processTelemetryInternal(event, itemCtx);
6624 if (this.context && this.context.user && this.context.user.isNewUser) {
6625 this.context.user.isNewUser = false;
6626 var message = new _InternalLogMessage(_InternalMessageId.SendBrowserInfoOnUserInit, ((getNavigator() || {}).userAgent || ""));
6627 itemCtx.diagLog().logInternalMessage(LoggingSeverity.CRITICAL, message);
6628 }
6629 this.processNext(event, itemCtx);
6630 }
6631 };
6632 PropertiesPlugin.prototype._processTelemetryInternal = function (event, itemCtx) {
6633 // set part A fields
6634 if (!event.tags) {
6635 event.tags = [];
6636 }
6637 if (!event.ext) {
6638 event.ext = {};
6639 }
6640 var ext = event.ext;
6641 ext[Extensions.DeviceExt] = ext[Extensions.DeviceExt] || {};
6642 ext[Extensions.WebExt] = ext[Extensions.WebExt] || {};
6643 ext[Extensions.UserExt] = ext[Extensions.UserExt] || {};
6644 ext[Extensions.OSExt] = ext[Extensions.OSExt] || {};
6645 ext[Extensions.AppExt] = ext[Extensions.AppExt] || {};
6646 ext[Extensions.TraceExt] = ext[Extensions.TraceExt] || {};
6647 var context = this.context;
6648 context.applySessionContext(event, itemCtx);
6649 context.applyApplicationContext(event, itemCtx);
6650 context.applyDeviceContext(event, itemCtx);
6651 context.applyOperationContext(event, itemCtx);
6652 context.applyUserContext(event, itemCtx);
6653 context.applyOperatingSystemContxt(event, itemCtx);
6654 context.applyWebContext(event, itemCtx);
6655 context.applyLocationContext(event, itemCtx); // legacy tags
6656 context.applyInternalContext(event, itemCtx); // legacy tags
6657 context.cleanUp(event, itemCtx);
6658 };
6659 return PropertiesPlugin;
6660 }(BaseTelemetryPlugin));
6661
6662 var XHRMonitoringState = /** @class */ (function () {
6663 function XHRMonitoringState() {
6664 this.openDone = false;
6665 this.setRequestHeaderDone = false;
6666 this.sendDone = false;
6667 this.abortDone = false;
6668 // <summary>True, if onreadyStateChangeCallback function attached to xhr, otherwise false</summary>
6669 this.onreadystatechangeCallbackAttached = false;
6670 }
6671 return XHRMonitoringState;
6672 }());
6673 var ajaxRecord = /** @class */ (function () {
6674 function ajaxRecord(traceID, spanID, logger) {
6675 this.completed = false;
6676 this.requestHeadersSize = null;
6677 this.requestHeaders = null;
6678 this.ttfb = null;
6679 this.responseReceivingDuration = null;
6680 this.callbackDuration = null;
6681 this.ajaxTotalDuration = null;
6682 this.aborted = null;
6683 this.pageUrl = null;
6684 this.requestUrl = null;
6685 this.requestSize = 0;
6686 this.method = null;
6687 /// <summary>Returns the HTTP status code.</summary>
6688 this.status = null;
6689 // <summary>The timestamp when open method was invoked</summary>
6690 this.requestSentTime = null;
6691 // <summary>The timestamps when first byte was received</summary>
6692 this.responseStartedTime = null;
6693 // <summary>The timestamp when last byte was received</summary>
6694 this.responseFinishedTime = null;
6695 // <summary>The timestamp when onreadystatechange callback in readyState 4 finished</summary>
6696 this.callbackFinishedTime = null;
6697 // <summary>The timestamp at which ajax was ended</summary>
6698 this.endTime = null;
6699 // <summary>The original xhr onreadystatechange event</summary>
6700 this.originalOnreadystatechage = null;
6701 this.xhrMonitoringState = new XHRMonitoringState();
6702 // <summary>Determines whether or not JavaScript exception occured in xhr.onreadystatechange code. 1 if occured, otherwise 0.</summary>
6703 this.clientFailure = 0;
6704 this.CalculateMetrics = function () {
6705 var self = this;
6706 // round to 3 decimal points
6707 self.ajaxTotalDuration = Math.round(DateTimeUtils.GetDuration(self.requestSentTime, self.responseFinishedTime) * 1000) / 1000;
6708 };
6709 this.traceID = traceID;
6710 this.spanID = spanID;
6711 this._logger = logger;
6712 }
6713 ajaxRecord.prototype.getAbsoluteUrl = function () {
6714 return this.requestUrl ? UrlHelper.getAbsoluteUrl(this.requestUrl) : null;
6715 };
6716 ajaxRecord.prototype.getPathName = function () {
6717 return this.requestUrl ? DataSanitizer.sanitizeUrl(this._logger, UrlHelper.getCompleteUrl(this.method, this.requestUrl)) : null;
6718 };
6719 return ajaxRecord;
6720 }());
6721
6722 var Traceparent = /** @class */ (function () {
6723 function Traceparent(traceId, spanId) {
6724 this.traceFlag = Traceparent.DEFAULT_TRACE_FLAG;
6725 this.version = Traceparent.DEFAULT_VERSION;
6726 if (traceId && Traceparent.isValidTraceId(traceId)) {
6727 this.traceId = traceId;
6728 }
6729 else {
6730 this.traceId = Util.generateW3CId();
6731 }
6732 if (spanId && Traceparent.isValidSpanId(spanId)) {
6733 this.spanId = spanId;
6734 }
6735 else {
6736 this.spanId = Util.generateW3CId().substr(0, 16);
6737 }
6738 }
6739 Traceparent.isValidTraceId = function (id) {
6740 return id.match(/^[0-9a-f]{32}$/) && id !== "00000000000000000000000000000000";
6741 };
6742 Traceparent.isValidSpanId = function (id) {
6743 return id.match(/^[0-9a-f]{16}$/) && id !== "0000000000000000";
6744 };
6745 Traceparent.prototype.toString = function () {
6746 return this.version + "-" + this.traceId + "-" + this.spanId + "-" + this.traceFlag;
6747 };
6748 Traceparent.DEFAULT_TRACE_FLAG = "01";
6749 Traceparent.DEFAULT_VERSION = "00";
6750 return Traceparent;
6751 }());
6752
6753 var _isNullOrUndefined$3 = CoreUtils.isNullOrUndefined;
6754 var AjaxMonitor = /** @class */ (function (_super) {
6755 __extends(AjaxMonitor, _super);
6756 function AjaxMonitor() {
6757 var _this = _super.call(this) || this;
6758 _this.identifier = AjaxMonitor.identifier;
6759 _this.priority = 120;
6760 _this._config = AjaxMonitor.getEmptyConfig();
6761 _this._trackAjaxAttempts = 0;
6762 var location = getLocation();
6763 _this.currentWindowHost = location && location.host && location.host.toLowerCase();
6764 _this.initialized = false;
6765 _this._fetchInitialized = false;
6766 return _this;
6767 }
6768 AjaxMonitor.getDefaultConfig = function () {
6769 var config = {
6770 maxAjaxCallsPerView: 500,
6771 disableAjaxTracking: false,
6772 disableFetchTracking: true,
6773 disableCorrelationHeaders: false,
6774 distributedTracingMode: DistributedTracingModes.AI,
6775 correlationHeaderExcludedDomains: [
6776 "*.blob.core.windows.net",
6777 "*.blob.core.chinacloudapi.cn",
6778 "*.blob.core.cloudapi.de",
6779 "*.blob.core.usgovcloudapi.net"
6780 ],
6781 correlationHeaderDomains: undefined,
6782 appId: undefined,
6783 enableCorsCorrelation: false,
6784 enableRequestHeaderTracking: false,
6785 enableResponseHeaderTracking: false,
6786 enableAjaxErrorStatusText: false
6787 };
6788 return config;
6789 };
6790 AjaxMonitor.getEmptyConfig = function () {
6791 return {
6792 maxAjaxCallsPerView: undefined,
6793 disableAjaxTracking: undefined,
6794 disableFetchTracking: undefined,
6795 disableCorrelationHeaders: undefined,
6796 distributedTracingMode: undefined,
6797 correlationHeaderExcludedDomains: undefined,
6798 appId: undefined,
6799 enableCorsCorrelation: undefined,
6800 correlationHeaderDomains: undefined,
6801 enableRequestHeaderTracking: undefined,
6802 enableResponseHeaderTracking: undefined,
6803 enableAjaxErrorStatusText: undefined
6804 };
6805 };
6806 AjaxMonitor.getFailedAjaxDiagnosticsMessage = function (xhr) {
6807 var result = "";
6808 try {
6809 if (!_isNullOrUndefined$3(xhr) &&
6810 !_isNullOrUndefined$3(xhr.ajaxData) &&
6811 !_isNullOrUndefined$3(xhr.ajaxData.requestUrl)) {
6812 result += "(url: '" + xhr.ajaxData.requestUrl + "')";
6813 }
6814 }
6815 catch (e) { }
6816 return result;
6817 };
6818 AjaxMonitor.prototype.trackDependencyData = function (dependency, properties) {
6819 this.trackDependencyDataInternal(dependency, properties);
6820 };
6821 AjaxMonitor.prototype.processTelemetry = function (item, itemCtx) {
6822 this.processNext(item, itemCtx);
6823 };
6824 AjaxMonitor.prototype.includeCorrelationHeaders = function (ajaxData, input, init, xhr) {
6825 var _self = this;
6826 if (input) {
6827 if (CorrelationIdHelper.canIncludeCorrelationHeader(_self._config, ajaxData.getAbsoluteUrl(), _self.currentWindowHost)) {
6828 if (!init) {
6829 init = {};
6830 }
6831 // init headers override original request headers
6832 // so, if they exist use only them, otherwise use request's because they should have been applied in the first place
6833 // not using original request headers will result in them being lost
6834 init.headers = new Headers(init.headers || (input instanceof Request ? (input.headers || {}) : {}));
6835 if (_self._isUsingAIHeaders) {
6836 var id = "|" + ajaxData.traceID + "." + ajaxData.spanID;
6837 init.headers.set(RequestHeaders.requestIdHeader, id);
6838 if (_self._config.enableRequestHeaderTracking) {
6839 ajaxData.requestHeaders[RequestHeaders.requestIdHeader] = id;
6840 }
6841 }
6842 var appId = _self._config.appId || (_self._context && _self._context.appId());
6843 if (appId) {
6844 init.headers.set(RequestHeaders.requestContextHeader, RequestHeaders.requestContextAppIdFormat + appId);
6845 if (_self._config.enableRequestHeaderTracking) {
6846 ajaxData.requestHeaders[RequestHeaders.requestContextHeader] = RequestHeaders.requestContextAppIdFormat + appId;
6847 }
6848 }
6849 if (_self._isUsingW3CHeaders) {
6850 var traceparent = new Traceparent(ajaxData.traceID, ajaxData.spanID);
6851 init.headers.set(RequestHeaders.traceParentHeader, traceparent.toString());
6852 if (_self._config.enableRequestHeaderTracking) {
6853 ajaxData.requestHeaders[RequestHeaders.traceParentHeader] = traceparent.toString();
6854 }
6855 }
6856 return init;
6857 }
6858 return init;
6859 }
6860 else if (xhr) {
6861 if (CorrelationIdHelper.canIncludeCorrelationHeader(_self._config, xhr.ajaxData.getAbsoluteUrl(), _self.currentWindowHost)) {
6862 if (_self._isUsingAIHeaders) {
6863 var id = "|" + xhr.ajaxData.traceID + "." + xhr.ajaxData.spanID;
6864 xhr.setRequestHeader(RequestHeaders.requestIdHeader, id);
6865 if (_self._config.enableRequestHeaderTracking) {
6866 xhr.ajaxData.requestHeaders[RequestHeaders.requestIdHeader] = id;
6867 }
6868 }
6869 var appId = _self._config.appId || (_self._context && _self._context.appId());
6870 if (appId) {
6871 xhr.setRequestHeader(RequestHeaders.requestContextHeader, RequestHeaders.requestContextAppIdFormat + appId);
6872 if (_self._config.enableRequestHeaderTracking) {
6873 xhr.ajaxData.requestHeaders[RequestHeaders.requestContextHeader] = RequestHeaders.requestContextAppIdFormat + appId;
6874 }
6875 }
6876 if (_self._isUsingW3CHeaders) {
6877 var traceparent = new Traceparent(xhr.ajaxData.traceID, xhr.ajaxData.spanID);
6878 xhr.setRequestHeader(RequestHeaders.traceParentHeader, traceparent.toString());
6879 if (_self._config.enableRequestHeaderTracking) {
6880 xhr.ajaxData.requestHeaders[RequestHeaders.traceParentHeader] = traceparent.toString();
6881 }
6882 }
6883 }
6884 return xhr;
6885 }
6886 return undefined;
6887 };
6888 AjaxMonitor.prototype.initialize = function (config, core, extensions, pluginChain) {
6889 var _self = this;
6890 _super.prototype.initialize.call(this, config, core, extensions, pluginChain);
6891 var ctx = _self._getTelCtx();
6892 if (!_self.initialized && !_self._fetchInitialized) {
6893 var defaultConfig = AjaxMonitor.getDefaultConfig();
6894 for (var field in defaultConfig) {
6895 _self._config[field] = ctx.getConfig(AjaxMonitor.identifier, field, defaultConfig[field]);
6896 }
6897 _self._isUsingAIHeaders = _self._config.distributedTracingMode === DistributedTracingModes.AI || _self._config.distributedTracingMode === DistributedTracingModes.AI_AND_W3C;
6898 _self._isUsingW3CHeaders = _self._config.distributedTracingMode === DistributedTracingModes.AI_AND_W3C || _self._config.distributedTracingMode === DistributedTracingModes.W3C;
6899 if (_self._config.disableAjaxTracking === false) {
6900 _self.instrumentXhr();
6901 }
6902 if (_self._config.disableFetchTracking === false) {
6903 _self.instrumentFetch();
6904 }
6905 if (extensions.length > 0 && extensions) {
6906 var propExt = void 0, extIx = 0;
6907 while (!propExt && extIx < extensions.length) {
6908 if (extensions[extIx] && extensions[extIx].identifier === PropertiesPluginIdentifier) {
6909 propExt = extensions[extIx];
6910 }
6911 extIx++;
6912 }
6913 if (propExt) {
6914 _self._context = propExt.context; // we could move IPropertiesPlugin to common as well
6915 }
6916 }
6917 }
6918 };
6919 /**
6920 * Logs dependency call
6921 * @param dependencyData dependency data object
6922 */
6923 AjaxMonitor.prototype.trackDependencyDataInternal = function (dependency, properties, systemProperties) {
6924 var _self = this;
6925 if (_self._config.maxAjaxCallsPerView === -1 || _self._trackAjaxAttempts < _self._config.maxAjaxCallsPerView) {
6926 var item = TelemetryItemCreator.create(dependency, RemoteDependencyData$1.dataType, RemoteDependencyData$1.envelopeType, _self.diagLog(), properties, systemProperties);
6927 _self.core.track(item);
6928 }
6929 else if (_self._trackAjaxAttempts === _self._config.maxAjaxCallsPerView) {
6930 _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.MaxAjaxPerPVExceeded, "Maximum ajax per page view limit reached, ajax monitoring is paused until the next trackPageView(). In order to increase the limit set the maxAjaxCallsPerView configuration parameter.", true);
6931 }
6932 ++_self._trackAjaxAttempts;
6933 };
6934 // Fetch Stuff
6935 AjaxMonitor.prototype.instrumentFetch = function () {
6936 var _self = this;
6937 if (!_self.supportsFetch() || _self._fetchInitialized) {
6938 return;
6939 }
6940 // Getting the global instance tp support web workers (which don't have window)
6941 var global = getGlobal();
6942 var originalFetch = global.fetch;
6943 var fetchMonitorInstance = _self;
6944 global.fetch = function fetch(input, init) {
6945 var fetchData;
6946 if (fetchMonitorInstance.isFetchInstrumented(input) && fetchMonitorInstance.isMonitoredInstance(undefined, undefined, input, init)) {
6947 try {
6948 fetchData = fetchMonitorInstance.createFetchRecord(input, init);
6949 init = fetchMonitorInstance.includeCorrelationHeaders(fetchData, input, init);
6950 }
6951 catch (e) {
6952 fetchMonitorInstance.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxOpen, "Failed to monitor Window.fetch, monitoring data for this fetch call may be incorrect.", {
6953 ajaxDiagnosticsMessage: _self.getFailedFetchDiagnosticsMessage(input),
6954 exception: Util.dump(e)
6955 });
6956 }
6957 }
6958 return originalFetch(input, init)
6959 .then(function (response) {
6960 fetchMonitorInstance.onFetchComplete(response, fetchData);
6961 return response;
6962 })["catch"](function (reason) {
6963 fetchMonitorInstance.onFetchFailed(input, fetchData, reason);
6964 throw reason;
6965 });
6966 };
6967 _self._fetchInitialized = true;
6968 };
6969 AjaxMonitor.prototype.instrumentXhr = function () {
6970 var _self = this;
6971 if (_self.supportsAjaxMonitoring() && !_self.initialized) {
6972 _self.instrumentOpen();
6973 _self.instrumentSend();
6974 _self.instrumentAbort();
6975 _self.instrumentSetRequestHeader();
6976 _self.initialized = true;
6977 }
6978 };
6979 /// <summary>Verifies that particalar instance of XMLHttpRequest needs to be monitored</summary>
6980 /// <param name="excludeAjaxDataValidation">Optional parameter. True if ajaxData must be excluded from verification</param>
6981 /// <returns type="bool">True if instance needs to be monitored, otherwise false</returns>
6982 AjaxMonitor.prototype.isMonitoredInstance = function (xhr, excludeAjaxDataValidation, request, init) {
6983 var disabledProperty = false;
6984 var ajaxValidation = true;
6985 var initialized = false;
6986 if (typeof request !== 'undefined') {
6987 initialized = this._fetchInitialized;
6988 // Look for DisabledPropertyName in either Request or RequestInit
6989 disabledProperty = (typeof request === 'object' ? request[DisabledPropertyName] === true : false) ||
6990 (init ? init[DisabledPropertyName] === true : false);
6991 }
6992 else if (typeof xhr !== 'undefined') {
6993 initialized = this.initialized;
6994 disabledProperty = xhr[DisabledPropertyName] === true;
6995 ajaxValidation = excludeAjaxDataValidation === true || !_isNullOrUndefined$3(xhr.ajaxData);
6996 }
6997 // checking to see that all interested functions on xhr were instrumented
6998 return initialized
6999 // checking on ajaxData to see that it was not removed in user code
7000 && ajaxValidation
7001 // check that this instance is not not used by ajax call performed inside client side monitoring to send data to collector
7002 && !disabledProperty;
7003 };
7004 /// <summary>Determines whether ajax monitoring can be enabled on this document</summary>
7005 /// <returns>True if Ajax monitoring is supported on this page, otherwise false</returns>
7006 AjaxMonitor.prototype.supportsAjaxMonitoring = function () {
7007 var result = true;
7008 if (typeof XMLHttpRequest === 'undefined' ||
7009 _isNullOrUndefined$3(XMLHttpRequest) ||
7010 _isNullOrUndefined$3(XMLHttpRequest.prototype) ||
7011 _isNullOrUndefined$3(XMLHttpRequest.prototype.open) ||
7012 _isNullOrUndefined$3(XMLHttpRequest.prototype.send) ||
7013 _isNullOrUndefined$3(XMLHttpRequest.prototype.abort)) {
7014 result = false;
7015 }
7016 // disable in IE8 or older (https://www.w3schools.com/jsref/jsref_trim_string.asp)
7017 try {
7018 }
7019 catch (ex) {
7020 result = false;
7021 }
7022 return result;
7023 };
7024 AjaxMonitor.prototype.instrumentOpen = function () {
7025 var originalOpen = XMLHttpRequest.prototype.open;
7026 var ajaxMonitorInstance = this;
7027 XMLHttpRequest.prototype.open = function (method, url, async) {
7028 var funcThis = this;
7029 try {
7030 if (ajaxMonitorInstance.isMonitoredInstance(funcThis, true) &&
7031 (!funcThis.ajaxData ||
7032 !funcThis.ajaxData.xhrMonitoringState.openDone)) {
7033 ajaxMonitorInstance.openHandler(funcThis, method, url, async);
7034 }
7035 }
7036 catch (e) {
7037 ajaxMonitorInstance.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxOpen, "Failed to monitor XMLHttpRequest.open, monitoring data for this ajax call may be incorrect.", {
7038 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(funcThis),
7039 exception: Util.dump(e)
7040 });
7041 }
7042 return originalOpen.apply(funcThis, arguments);
7043 };
7044 };
7045 AjaxMonitor.prototype.openHandler = function (xhr, method, url, async) {
7046 var _self = this;
7047 var traceID = (_self._context && _self._context.telemetryTrace && _self._context.telemetryTrace.traceID) || Util.generateW3CId();
7048 var spanID = Util.generateW3CId().substr(0, 16);
7049 var ajaxData = new ajaxRecord(traceID, spanID, _self.diagLog());
7050 ajaxData.method = method;
7051 ajaxData.requestUrl = url;
7052 ajaxData.xhrMonitoringState.openDone = true;
7053 ajaxData.requestHeaders = {};
7054 xhr.ajaxData = ajaxData;
7055 _self.attachToOnReadyStateChange(xhr);
7056 };
7057 AjaxMonitor.prototype.instrumentSend = function () {
7058 var originalSend = XMLHttpRequest.prototype.send;
7059 var ajaxMonitorInstance = this;
7060 XMLHttpRequest.prototype.send = function (content) {
7061 var funcThis = this;
7062 try {
7063 if (ajaxMonitorInstance.isMonitoredInstance(funcThis) && !funcThis.ajaxData.xhrMonitoringState.sendDone) {
7064 ajaxMonitorInstance.sendHandler(funcThis, content);
7065 }
7066 }
7067 catch (e) {
7068 ajaxMonitorInstance.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxSend, "Failed to monitor XMLHttpRequest, monitoring data for this ajax call may be incorrect.", {
7069 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(funcThis),
7070 exception: Util.dump(e)
7071 });
7072 }
7073 return originalSend.apply(funcThis, arguments);
7074 };
7075 };
7076 AjaxMonitor.prototype.sendHandler = function (xhr, content) {
7077 xhr.ajaxData.requestSentTime = DateTimeUtils.Now();
7078 xhr = this.includeCorrelationHeaders(xhr.ajaxData, undefined, undefined, xhr);
7079 xhr.ajaxData.xhrMonitoringState.sendDone = true;
7080 };
7081 AjaxMonitor.prototype.instrumentAbort = function () {
7082 var originalAbort = XMLHttpRequest.prototype.abort;
7083 var ajaxMonitorInstance = this;
7084 XMLHttpRequest.prototype.abort = function () {
7085 var funcThis = this;
7086 try {
7087 if (ajaxMonitorInstance.isMonitoredInstance(funcThis) && !funcThis.ajaxData.xhrMonitoringState.abortDone) {
7088 funcThis.ajaxData.aborted = 1;
7089 funcThis.ajaxData.xhrMonitoringState.abortDone = true;
7090 }
7091 }
7092 catch (e) {
7093 ajaxMonitorInstance.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxAbort, "Failed to monitor XMLHttpRequest.abort, monitoring data for this ajax call may be incorrect.", {
7094 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(funcThis),
7095 exception: Util.dump(e)
7096 });
7097 }
7098 return originalAbort.apply(funcThis, arguments);
7099 };
7100 };
7101 AjaxMonitor.prototype.instrumentSetRequestHeader = function () {
7102 if (!this._config.enableRequestHeaderTracking) {
7103 return;
7104 }
7105 var originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
7106 var ajaxMonitorInstance = this;
7107 XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
7108 var funcThis = this;
7109 try {
7110 if (ajaxMonitorInstance.isMonitoredInstance(funcThis)) {
7111 funcThis.ajaxData.requestHeaders[header] = value;
7112 }
7113 }
7114 catch (e) {
7115 ajaxMonitorInstance.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxSetRequestHeader, "Failed to monitor XMLHttpRequest.setRequestHeader, monitoring data for this ajax call may be incorrect.", {
7116 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(funcThis),
7117 exception: Util.dump(e)
7118 });
7119 }
7120 return originalSetRequestHeader.apply(funcThis, arguments);
7121 };
7122 };
7123 AjaxMonitor.prototype.attachToOnReadyStateChange = function (xhr) {
7124 var ajaxMonitorInstance = this;
7125 xhr.ajaxData.xhrMonitoringState.onreadystatechangeCallbackAttached = EventHelper.Attach(xhr, "readystatechange", function () {
7126 try {
7127 if (ajaxMonitorInstance.isMonitoredInstance(xhr)) {
7128 if (xhr.readyState === 4) {
7129 ajaxMonitorInstance.onAjaxComplete(xhr);
7130 }
7131 }
7132 }
7133 catch (e) {
7134 var exceptionText = Util.dump(e);
7135 // ignore messages with c00c023f, as this a known IE9 XHR abort issue
7136 if (!exceptionText || exceptionText.toLowerCase().indexOf("c00c023f") === -1) {
7137 ajaxMonitorInstance.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxRSC, "Failed to monitor XMLHttpRequest 'readystatechange' event handler, monitoring data for this ajax call may be incorrect.", {
7138 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr),
7139 exception: Util.dump(e)
7140 });
7141 }
7142 }
7143 });
7144 };
7145 AjaxMonitor.prototype.onAjaxComplete = function (xhr) {
7146 var _self = this;
7147 xhr.ajaxData.responseFinishedTime = DateTimeUtils.Now();
7148 xhr.ajaxData.status = xhr.status;
7149 xhr.ajaxData.CalculateMetrics();
7150 if (xhr.ajaxData.ajaxTotalDuration < 0) {
7151 _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxDur, "Failed to calculate the duration of the ajax call, monitoring data for this ajax call won't be sent.", {
7152 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr),
7153 requestSentTime: xhr.ajaxData.requestSentTime,
7154 responseFinishedTime: xhr.ajaxData.responseFinishedTime
7155 });
7156 }
7157 else {
7158 var dependency = {
7159 id: "|" + xhr.ajaxData.traceID + "." + xhr.ajaxData.spanID,
7160 target: xhr.ajaxData.getAbsoluteUrl(),
7161 name: xhr.ajaxData.getPathName(),
7162 type: "Ajax",
7163 duration: xhr.ajaxData.ajaxTotalDuration,
7164 success: (+(xhr.ajaxData.status)) >= 200 && (+(xhr.ajaxData.status)) < 400,
7165 responseCode: +xhr.ajaxData.status,
7166 method: xhr.ajaxData.method
7167 };
7168 // enrich dependency target with correlation context from the server
7169 var correlationContext = _self.getAjaxCorrelationContext(xhr);
7170 if (correlationContext) {
7171 dependency.correlationContext = /* dependency.target + " | " + */ correlationContext;
7172 }
7173 if (_self._config.enableRequestHeaderTracking) {
7174 if (CoreUtils.objKeys(xhr.ajaxData.requestHeaders).length > 0) {
7175 dependency.properties = dependency.properties || {};
7176 dependency.properties.requestHeaders = {};
7177 dependency.properties.requestHeaders = xhr.ajaxData.requestHeaders;
7178 }
7179 }
7180 if (_self._config.enableResponseHeaderTracking) {
7181 var headers = xhr.getAllResponseHeaders();
7182 if (headers) {
7183 // xhr.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string or null
7184 // the regex converts the header string into an array of individual headers
7185 var arr = headers.trim().split(/[\r\n]+/);
7186 var responseHeaderMap_1 = {};
7187 CoreUtils.arrForEach(arr, function (line) {
7188 var parts = line.split(': ');
7189 var header = parts.shift();
7190 var value = parts.join(': ');
7191 responseHeaderMap_1[header] = value;
7192 });
7193 if (CoreUtils.objKeys(responseHeaderMap_1).length > 0) {
7194 dependency.properties = dependency.properties || {};
7195 dependency.properties.responseHeaders = {};
7196 dependency.properties.responseHeaders = responseHeaderMap_1;
7197 }
7198 }
7199 }
7200 if (_self._config.enableAjaxErrorStatusText && xhr.status >= 400) {
7201 dependency.properties = dependency.properties || {};
7202 var responseType = xhr.responseType;
7203 if (responseType === "" || responseType === "text") {
7204 dependency.properties.responseText = xhr.responseText ? xhr.statusText + " - " + xhr.responseText : xhr.statusText;
7205 }
7206 if (responseType === "json") {
7207 dependency.properties.responseText = xhr.response ? xhr.statusText + " - " + JSON.stringify(xhr.response) : xhr.statusText;
7208 }
7209 }
7210 _self.trackDependencyDataInternal(dependency);
7211 xhr.ajaxData = null;
7212 }
7213 };
7214 AjaxMonitor.prototype.getAjaxCorrelationContext = function (xhr) {
7215 try {
7216 var responseHeadersString = xhr.getAllResponseHeaders();
7217 if (responseHeadersString !== null) {
7218 var index = responseHeadersString.toLowerCase().indexOf(RequestHeaders.requestContextHeaderLowerCase);
7219 if (index !== -1) {
7220 var responseHeader = xhr.getResponseHeader(RequestHeaders.requestContextHeader);
7221 return CorrelationIdHelper.getCorrelationContext(responseHeader);
7222 }
7223 }
7224 }
7225 catch (e) {
7226 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxGetCorrelationHeader, "Failed to get Request-Context correlation header as it may be not included in the response or not accessible.", {
7227 ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr),
7228 exception: Util.dump(e)
7229 });
7230 }
7231 };
7232 AjaxMonitor.prototype.isFetchInstrumented = function (input) {
7233 return this._fetchInitialized && input[DisabledPropertyName] !== true;
7234 };
7235 AjaxMonitor.prototype.supportsFetch = function () {
7236 var result = true;
7237 var _global = getGlobal();
7238 if (!_global || _isNullOrUndefined$3(_global.Request) ||
7239 _isNullOrUndefined$3(_global.Request.prototype) ||
7240 _isNullOrUndefined$3(_global.fetch)) {
7241 result = false;
7242 }
7243 return result;
7244 };
7245 AjaxMonitor.prototype.createFetchRecord = function (input, init) {
7246 var _self = this;
7247 var traceID = (_self._context && _self._context.telemetryTrace && _self._context.telemetryTrace.traceID) || Util.generateW3CId();
7248 var spanID = Util.generateW3CId().substr(0, 16);
7249 var ajaxData = new ajaxRecord(traceID, spanID, _self.diagLog());
7250 ajaxData.requestSentTime = DateTimeUtils.Now();
7251 if (input instanceof Request) {
7252 ajaxData.requestUrl = input ? input.url : "";
7253 }
7254 else {
7255 ajaxData.requestUrl = input;
7256 }
7257 if (init && init.method) {
7258 ajaxData.method = init.method;
7259 }
7260 else if (input && input instanceof Request) {
7261 ajaxData.method = input.method;
7262 }
7263 else {
7264 ajaxData.method = "GET";
7265 }
7266 if (init && init.headers && _self._config.enableRequestHeaderTracking) {
7267 ajaxData.requestHeaders = init.headers;
7268 }
7269 else {
7270 ajaxData.requestHeaders = {};
7271 }
7272 return ajaxData;
7273 };
7274 AjaxMonitor.prototype.getFailedFetchDiagnosticsMessage = function (input) {
7275 var result = "";
7276 try {
7277 if (!_isNullOrUndefined$3(input)) {
7278 if (typeof (input) === "string") {
7279 result += "(url: '" + input + "')";
7280 }
7281 else {
7282 result += "(url: '" + input.url + "')";
7283 }
7284 }
7285 }
7286 catch (e) {
7287 this.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedMonitorAjaxOpen, "Failed to grab failed fetch diagnostics message", { exception: Util.dump(e) });
7288 }
7289 return result;
7290 };
7291 AjaxMonitor.prototype.onFetchComplete = function (response, ajaxData) {
7292 var _self = this;
7293 if (!ajaxData) {
7294 return;
7295 }
7296 try {
7297 ajaxData.responseFinishedTime = DateTimeUtils.Now();
7298 ajaxData.CalculateMetrics();
7299 if (ajaxData.ajaxTotalDuration < 0) {
7300 _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxDur, "Failed to calculate the duration of the fetch call, monitoring data for this fetch call won't be sent.", {
7301 fetchDiagnosticsMessage: _self.getFailedFetchDiagnosticsMessage(response),
7302 requestSentTime: ajaxData.requestSentTime,
7303 responseFinishedTime: ajaxData.responseFinishedTime
7304 });
7305 }
7306 else {
7307 var dependency = {
7308 id: "|" + ajaxData.traceID + "." + ajaxData.spanID,
7309 target: ajaxData.getAbsoluteUrl(),
7310 name: ajaxData.getPathName(),
7311 type: "Fetch",
7312 duration: ajaxData.ajaxTotalDuration,
7313 success: response.status >= 200 && response.status < 400,
7314 responseCode: response.status,
7315 properties: { HttpMethod: ajaxData.method }
7316 };
7317 // enrich dependency target with correlation context from the server
7318 var correlationContext = _self.getFetchCorrelationContext(response);
7319 if (correlationContext) {
7320 dependency.correlationContext = correlationContext;
7321 }
7322 if (_self._config.enableRequestHeaderTracking) {
7323 if (CoreUtils.objKeys(ajaxData.requestHeaders).length > 0) {
7324 dependency.properties = dependency.properties || {};
7325 dependency.properties.requestHeaders = ajaxData.requestHeaders;
7326 }
7327 }
7328 if (_self._config.enableResponseHeaderTracking) {
7329 var responseHeaderMap_2 = {};
7330 response.headers.forEach(function (value, name) {
7331 responseHeaderMap_2[name] = value;
7332 });
7333 if (CoreUtils.objKeys(responseHeaderMap_2).length > 0) {
7334 dependency.properties = dependency.properties || {};
7335 dependency.properties.responseHeaders = responseHeaderMap_2;
7336 }
7337 }
7338 _self.trackDependencyDataInternal(dependency);
7339 }
7340 }
7341 catch (e) {
7342 _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxGetCorrelationHeader, "Failed to calculate the duration of the fetch call, monitoring data for this fetch call won't be sent.", {
7343 fetchDiagnosticsMessage: _self.getFailedFetchDiagnosticsMessage(response),
7344 exception: Util.dump(e)
7345 });
7346 }
7347 };
7348 AjaxMonitor.prototype.onFetchFailed = function (input, ajaxData, reason) {
7349 var _self = this;
7350 if (!ajaxData) {
7351 return;
7352 }
7353 try {
7354 ajaxData.responseFinishedTime = DateTimeUtils.Now();
7355 ajaxData.CalculateMetrics();
7356 if (ajaxData.ajaxTotalDuration < 0) {
7357 _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxDur, "Failed to calculate the duration of the failed fetch call, monitoring data for this fetch call won't be sent.", {
7358 fetchDiagnosticsMessage: _self.getFailedFetchDiagnosticsMessage(input),
7359 requestSentTime: ajaxData.requestSentTime,
7360 responseFinishedTime: ajaxData.responseFinishedTime
7361 });
7362 }
7363 else {
7364 var dependency = {
7365 id: "|" + ajaxData.traceID + "." + ajaxData.spanID,
7366 target: ajaxData.getAbsoluteUrl(),
7367 name: ajaxData.getPathName(),
7368 type: "Fetch",
7369 duration: ajaxData.ajaxTotalDuration,
7370 success: false,
7371 responseCode: 0,
7372 properties: { HttpMethod: ajaxData.method }
7373 };
7374 _self.trackDependencyDataInternal(dependency, { error: reason.message });
7375 }
7376 }
7377 catch (e) {
7378 _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxGetCorrelationHeader, "Failed to calculate the duration of the failed fetch call, monitoring data for this fetch call won't be sent.", {
7379 fetchDiagnosticsMessage: _self.getFailedFetchDiagnosticsMessage(input),
7380 exception: Util.dump(e)
7381 });
7382 }
7383 };
7384 AjaxMonitor.prototype.getFetchCorrelationContext = function (response) {
7385 try {
7386 var responseHeader = response.headers.get(RequestHeaders.requestContextHeader);
7387 return CorrelationIdHelper.getCorrelationContext(responseHeader);
7388 }
7389 catch (e) {
7390 this.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.FailedMonitorAjaxGetCorrelationHeader, "Failed to get Request-Context correlation header as it may be not included in the response or not accessible.", {
7391 fetchDiagnosticsMessage: this.getFailedFetchDiagnosticsMessage(response),
7392 exception: Util.dump(e)
7393 });
7394 }
7395 };
7396 AjaxMonitor.identifier = "AjaxDependencyPlugin";
7397 return AjaxMonitor;
7398 }(BaseTelemetryPlugin));
7399
7400 /**
7401 * Telemetry type classes, e.g. PageView, Exception, etc
7402 */
7403 var Telemetry = Common;
7404 /**
7405 * Application Insights API
7406 * @class Initialization
7407 * @implements {IApplicationInsights}
7408 */
7409 var Initialization = /** @class */ (function () {
7410 function Initialization(snippet) {
7411 // initialize the queue and config in case they are undefined
7412 snippet.queue = snippet.queue || [];
7413 snippet.version = snippet.version || 2.0; // Default to new version
7414 var config = snippet.config || {};
7415 if (config.connectionString) {
7416 var cs = ConnectionStringParser.parse(config.connectionString);
7417 var ingest = cs.ingestionendpoint;
7418 config.endpointUrl = ingest ? ingest + "/v2/track" : config.endpointUrl; // only add /v2/track when from connectionstring
7419 config.instrumentationKey = cs.instrumentationkey || config.instrumentationKey;
7420 }
7421 this.appInsights = new ApplicationInsights();
7422 this.properties = new PropertiesPlugin();
7423 this.dependencies = new AjaxMonitor();
7424 this.core = new AppInsightsCore();
7425 this.snippet = snippet;
7426 this.config = config;
7427 this.getSKUDefaults();
7428 }
7429 // Analytics Plugin
7430 /**
7431 * Log a user action or other occurrence.
7432 * @param {IEventTelemetry} event
7433 * @param {ICustomProperties} [customProperties]
7434 * @memberof Initialization
7435 */
7436 Initialization.prototype.trackEvent = function (event, customProperties) {
7437 this.appInsights.trackEvent(event, customProperties);
7438 };
7439 /**
7440 * Logs that a page, or similar container was displayed to the user.
7441 * @param {IPageViewTelemetry} pageView
7442 * @memberof Initialization
7443 */
7444 Initialization.prototype.trackPageView = function (pageView) {
7445 var inPv = pageView || {};
7446 this.appInsights.trackPageView(inPv);
7447 };
7448 /**
7449 * Log a bag of performance information via the customProperties field.
7450 * @param {IPageViewPerformanceTelemetry} pageViewPerformance
7451 * @memberof Initialization
7452 */
7453 Initialization.prototype.trackPageViewPerformance = function (pageViewPerformance) {
7454 var inPvp = pageViewPerformance || {};
7455 this.appInsights.trackPageViewPerformance(inPvp);
7456 };
7457 /**
7458 * Log an exception that you have caught.
7459 * @param {IExceptionTelemetry} exception
7460 * @memberof Initialization
7461 */
7462 Initialization.prototype.trackException = function (exception) {
7463 if (!exception.exception && exception.error) {
7464 exception.exception = exception.error;
7465 }
7466 this.appInsights.trackException(exception);
7467 };
7468 /**
7469 * Manually send uncaught exception telemetry. This method is automatically triggered
7470 * on a window.onerror event.
7471 * @param {IAutoExceptionTelemetry} exception
7472 * @memberof Initialization
7473 */
7474 Initialization.prototype._onerror = function (exception) {
7475 this.appInsights._onerror(exception);
7476 };
7477 /**
7478 * Log a diagnostic scenario such entering or leaving a function.
7479 * @param {ITraceTelemetry} trace
7480 * @param {ICustomProperties} [customProperties]
7481 * @memberof Initialization
7482 */
7483 Initialization.prototype.trackTrace = function (trace, customProperties) {
7484 this.appInsights.trackTrace(trace, customProperties);
7485 };
7486 /**
7487 * Log a numeric value that is not associated with a specific event. Typically used
7488 * to send regular reports of performance indicators.
7489 *
7490 * To send a single measurement, just use the `name` and `average` fields
7491 * of {@link IMetricTelemetry}.
7492 *
7493 * If you take measurements frequently, you can reduce the telemetry bandwidth by
7494 * aggregating multiple measurements and sending the resulting average and modifying
7495 * the `sampleCount` field of {@link IMetricTelemetry}.
7496 * @param {IMetricTelemetry} metric input object argument. Only `name` and `average` are mandatory.
7497 * @param {ICustomProperties} [customProperties]
7498 * @memberof Initialization
7499 */
7500 Initialization.prototype.trackMetric = function (metric, customProperties) {
7501 this.appInsights.trackMetric(metric, customProperties);
7502 };
7503 /**
7504 * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,
7505 * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view
7506 * and send the event.
7507 * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
7508 */
7509 Initialization.prototype.startTrackPage = function (name) {
7510 this.appInsights.startTrackPage(name);
7511 };
7512 /**
7513 * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
7514 * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
7515 * @param name The string you used as the name in startTrackPage. Defaults to the document title.
7516 * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
7517 * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
7518 * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
7519 */
7520 Initialization.prototype.stopTrackPage = function (name, url, customProperties, measurements) {
7521 this.appInsights.stopTrackPage(name, url, customProperties, measurements);
7522 };
7523 Initialization.prototype.startTrackEvent = function (name) {
7524 this.appInsights.startTrackEvent(name);
7525 };
7526 /**
7527 * Log an extended event that you started timing with `startTrackEvent`.
7528 * @param name The string you used to identify this event in `startTrackEvent`.
7529 * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
7530 * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
7531 */
7532 Initialization.prototype.stopTrackEvent = function (name, properties, measurements) {
7533 this.appInsights.stopTrackEvent(name, properties, measurements); // Todo: Fix to pass measurements once type is updated
7534 };
7535 Initialization.prototype.addTelemetryInitializer = function (telemetryInitializer) {
7536 return this.appInsights.addTelemetryInitializer(telemetryInitializer);
7537 };
7538 // Properties Plugin
7539 /**
7540 * Set the authenticated user id and the account id. Used for identifying a specific signed-in user. Parameters must not contain whitespace or ,;=|
7541 *
7542 * The method will only set the `authenticatedUserId` and `accountId` in the current page view. To set them for the whole session, you should set `storeInCookie = true`
7543 * @param {string} authenticatedUserId
7544 * @param {string} [accountId]
7545 * @param {boolean} [storeInCookie=false]
7546 * @memberof Initialization
7547 */
7548 Initialization.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {
7549 if (storeInCookie === void 0) { storeInCookie = false; }
7550 this.properties.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId, storeInCookie);
7551 };
7552 /**
7553 * Clears the authenticated user id and account id. The associated cookie is cleared, if present.
7554 * @memberof Initialization
7555 */
7556 Initialization.prototype.clearAuthenticatedUserContext = function () {
7557 this.properties.context.user.clearAuthenticatedUserContext();
7558 };
7559 // Dependencies Plugin
7560 /**
7561 * Log a dependency call (e.g. ajax)
7562 * @param {IDependencyTelemetry} dependency
7563 * @memberof Initialization
7564 */
7565 Initialization.prototype.trackDependencyData = function (dependency) {
7566 this.dependencies.trackDependencyData(dependency);
7567 };
7568 // Misc
7569 /**
7570 * Manually trigger an immediate send of all telemetry still in the buffer.
7571 * @param {boolean} [async=true]
7572 * @memberof Initialization
7573 */
7574 Initialization.prototype.flush = function (async) {
7575 if (async === void 0) { async = true; }
7576 CoreUtils.arrForEach(this.core.getTransmissionControls(), function (channels) {
7577 CoreUtils.arrForEach(channels, function (channel) {
7578 channel.flush(async);
7579 });
7580 });
7581 };
7582 /**
7583 * Manually trigger an immediate send of all telemetry still in the buffer using beacon Sender.
7584 * Fall back to xhr sender if beacon is not supported.
7585 * @param {boolean} [async=true]
7586 * @memberof Initialization
7587 */
7588 Initialization.prototype.onunloadFlush = function (async) {
7589 if (async === void 0) { async = true; }
7590 CoreUtils.arrForEach(this.core.getTransmissionControls(), function (channels) {
7591 CoreUtils.arrForEach(channels, function (channel) {
7592 if (channel.onunloadFlush) {
7593 channel.onunloadFlush();
7594 }
7595 else {
7596 channel.flush(async);
7597 }
7598 });
7599 });
7600 };
7601 /**
7602 * Initialize this instance of ApplicationInsights
7603 * @returns {IApplicationInsights}
7604 * @memberof Initialization
7605 */
7606 Initialization.prototype.loadAppInsights = function (legacyMode) {
7607 if (legacyMode === void 0) { legacyMode = false; }
7608 var _this = this;
7609 // dont allow additional channels/other extensions for legacy mode; legacy mode is only to allow users to switch with no code changes!
7610 if (legacyMode && _this.config.extensions && _this.config.extensions.length > 0) {
7611 throw new Error("Extensions not allowed in legacy mode");
7612 }
7613 var extensions = [];
7614 var appInsightsChannel = new Sender();
7615 extensions.push(appInsightsChannel);
7616 extensions.push(_this.properties);
7617 extensions.push(_this.dependencies);
7618 extensions.push(_this.appInsights);
7619 // initialize core
7620 _this.core.initialize(_this.config, extensions);
7621 // Empty queue of all api calls logged prior to sdk download
7622 _this.emptyQueue();
7623 _this.pollInternalLogs();
7624 _this.addHousekeepingBeforeUnload(this);
7625 _this.context = _this.properties.context;
7626 return _this;
7627 };
7628 /**
7629 * Overwrite the lazy loaded fields of global window snippet to contain the
7630 * actual initialized API methods
7631 * @param {Snippet} snippet
7632 * @memberof Initialization
7633 */
7634 Initialization.prototype.updateSnippetDefinitions = function (snippet) {
7635 // apply full appInsights to the global instance
7636 // Note: This must be called before loadAppInsights is called
7637 for (var field in this) {
7638 if (CoreUtils.isString(field)) {
7639 snippet[field] = this[field];
7640 }
7641 }
7642 };
7643 /**
7644 * Call any functions that were queued before the main script was loaded
7645 * @memberof Initialization
7646 */
7647 Initialization.prototype.emptyQueue = function () {
7648 var _this = this;
7649 // call functions that were queued before the main script was loaded
7650 try {
7651 if (Util.isArray(_this.snippet.queue)) {
7652 // note: do not check length in the for-loop conditional in case something goes wrong and the stub methods are not overridden.
7653 var length_1 = _this.snippet.queue.length;
7654 for (var i = 0; i < length_1; i++) {
7655 var call = _this.snippet.queue[i];
7656 call();
7657 }
7658 _this.snippet.queue = undefined;
7659 delete _this.snippet.queue;
7660 }
7661 }
7662 catch (exception) {
7663 var properties = {};
7664 if (exception && CoreUtils.isFunction(exception.toString)) {
7665 properties.exception = exception.toString();
7666 }
7667 // need from core
7668 // Microsoft.ApplicationInsights._InternalLogging.throwInternal(
7669 // LoggingSeverity.WARNING,
7670 // _InternalMessageId.FailedToSendQueuedTelemetry,
7671 // "Failed to send queued telemetry",
7672 // properties);
7673 }
7674 };
7675 Initialization.prototype.pollInternalLogs = function () {
7676 this.core.pollInternalLogs();
7677 };
7678 Initialization.prototype.addHousekeepingBeforeUnload = function (appInsightsInstance) {
7679 // Add callback to push events when the user navigates away
7680 if (hasWindow() || hasDocument()) {
7681 var performHousekeeping = function () {
7682 // Adds the ability to flush all data before the page unloads.
7683 // Note: This approach tries to push a sync request with all the pending events onbeforeunload.
7684 // Firefox does not respect this.Other browsers DO push out the call with < 100% hit rate.
7685 // Telemetry here will help us analyze how effective this approach is.
7686 // Another approach would be to make this call sync with a acceptable timeout to reduce the
7687 // impact on user experience.
7688 // appInsightsInstance.context._sender.triggerSend();
7689 appInsightsInstance.onunloadFlush(false);
7690 // Back up the current session to local storage
7691 // This lets us close expired sessions after the cookies themselves expire
7692 var ext = appInsightsInstance.appInsights.core['_extensions'][PropertiesPluginIdentifier];
7693 if (ext && ext.context && ext.context._sessionManager) {
7694 ext.context._sessionManager.backup();
7695 }
7696 };
7697 if (!appInsightsInstance.appInsights.config.disableFlushOnBeforeUnload) {
7698 // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server
7699 // As just hooking the window does not always fire (on chrome) for page navigations.
7700 var added = CoreUtils.addEventHandler('beforeunload', performHousekeeping);
7701 added = CoreUtils.addEventHandler('pagehide', performHousekeeping) || added;
7702 if (!added) {
7703 appInsightsInstance.appInsights.core.logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.FailedToAddHandlerForOnBeforeUnload, 'Could not add handler for beforeunload and pagehide');
7704 }
7705 }
7706 // We also need to hook the pagehide event as not all versions of Safari support load/unload events.
7707 if (!appInsightsInstance.appInsights.config.disableFlushOnUnload) {
7708 // Not adding any telemetry as pagehide as it's not supported on all browsers
7709 CoreUtils.addEventHandler('pagehide', performHousekeeping);
7710 }
7711 }
7712 };
7713 Initialization.prototype.getSKUDefaults = function () {
7714 var _this = this;
7715 _this.config.diagnosticLogInterval =
7716 _this.config.diagnosticLogInterval && _this.config.diagnosticLogInterval > 0 ? _this.config.diagnosticLogInterval : 10000;
7717 };
7718 return Initialization;
7719 }());
7720
7721 var ApplicationInsightsContainer = /** @class */ (function () {
7722 function ApplicationInsightsContainer() {
7723 }
7724 ApplicationInsightsContainer.getAppInsights = function (snippet, version) {
7725 var initialization = new Initialization(snippet);
7726 var legacyMode = version !== 2.0 ? true : false;
7727 // Two target scenarios:
7728 // 1. Customer runs v1 snippet + runtime. If customer updates just cdn location to new SDK, it will run in compat mode so old apis work
7729 // 2. Customer updates to new snippet (that uses cdn location to new SDK. This is same as a new customer onboarding
7730 // and all api signatures are expected to map to new SDK. Note new snippet specifies version
7731 if (version === 2.0) {
7732 initialization.updateSnippetDefinitions(snippet);
7733 initialization.loadAppInsights(legacyMode);
7734 return initialization; // default behavior with new snippet
7735 }
7736 else {
7737 var legacy = new AppInsightsDeprecated(snippet, initialization); // target scenario old snippet + updated endpoint
7738 legacy.updateSnippetDefinitions(snippet);
7739 initialization.loadAppInsights(legacyMode);
7740 return legacy;
7741 }
7742 };
7743 return ApplicationInsightsContainer;
7744 }());
7745
7746 var Undefined$1 = "undefined";
7747 function _logWarn(aiName, message) {
7748 // TODO: Find better place to warn to console when SDK initialization fails
7749 var _console = typeof console !== Undefined$1 ? console : null;
7750 if (_console && _console.warn) {
7751 _console.warn('Failed to initialize AppInsights JS SDK for instance ' + (aiName || '<unknown>') + ' - ' + message);
7752 }
7753 }
7754 // should be global function that should load as soon as SDK loads
7755 try {
7756 // E2E sku on load initializes core and pipeline using snippet as input for configuration
7757 // tslint:disable-next-line: no-var-keyword
7758 var aiName;
7759 if (typeof window !== Undefined$1) {
7760 var _window = window;
7761 aiName = _window["appInsightsSDK"] || "appInsights";
7762 if (typeof JSON !== Undefined$1) {
7763 // get snippet or initialize to an empty object
7764 if (_window[aiName] !== undefined) {
7765 // this is the typical case for browser+snippet
7766 var snippet = _window[aiName] || { version: 2.0 };
7767 // overwrite snippet with full appInsights
7768 // for 2.0 initialize only if required
7769 if ((snippet.version === 2.0 && _window[aiName].initialize) || snippet.version === undefined) {
7770 ApplicationInsightsContainer.getAppInsights(snippet, snippet.version);
7771 }
7772 }
7773 }
7774 else {
7775 _logWarn(aiName, "Missing JSON - you must supply a JSON polyfill!");
7776 }
7777 }
7778 else {
7779 _logWarn(aiName, "Missing window");
7780 }
7781 // Hack: If legacy SDK exists, skip this step (Microsoft.ApplicationInsights exists).
7782 // else write what was there for v2 SDK prior to rollup bundle output name change.
7783 // e.g Microsoft.ApplicationInsights.ApplicationInsights, Microsoft.ApplicationInsights.Telemetry
7784 // @todo uncomment once integration tests for this can be added
7785 // if (typeof window !== Undefined && window && ((window as any).Microsoft && !(window as any).Microsoft.ApplicationInsights)) {
7786 // (window as any).Microsoft = (window as any).Microsoft || {};
7787 // (window as any).Microsoft.ApplicationInsights = {
7788 // ApplicationInsights, Telemetry
7789 // };
7790 // }
7791 }
7792 catch (e) {
7793 _logWarn(aiName, e.message);
7794 }
7795
7796 exports.ApplicationInsights = Initialization;
7797 exports.Telemetry = Telemetry;
7798
7799 return exports;
7800
7801}({}));
7802//# sourceMappingURL=ai.2.4.4.js.map
7803
7804var snippet = {
7805 config: {
7806 instrumentationKey: instrumentationKey
7807 }
7808};
7809var init = new Microsoft.ApplicationInsights.ApplicationInsights(snippet);
7810var appInsights = init.loadAppInsights();
7811appInsights.trackPageView();