/*!
 * Application Insights JavaScript SDK - Core, 2.8.15
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.Microsoft = global.Microsoft || {}, global.Microsoft.ApplicationInsights = global.Microsoft.ApplicationInsights || {})));
})(this, (function (exports) { 'use strict';

    var MinChannelPriorty = 100;

    var strShimFunction = "function";
    var strShimObject = "object";
    var strShimUndefined = "undefined";
    var strShimPrototype = "prototype";
    var strShimHasOwnProperty = "hasOwnProperty";
    var ObjClass = Object;
    var ObjProto = ObjClass[strShimPrototype];
    var ObjAssign = ObjClass["assign"];
    var ObjCreate = ObjClass["create"];
    var ObjDefineProperty = ObjClass["defineProperty"];
    var ObjHasOwnProperty = ObjProto[strShimHasOwnProperty];

    var _cachedGlobal = null;
    function getGlobal(useCached) {
        if (useCached === void 0) { useCached = true; }
        var result = useCached === false ? null : _cachedGlobal;
        if (!result) {
            if (typeof globalThis !== strShimUndefined) {
                result = globalThis;
            }
            if (!result && typeof self !== strShimUndefined) {
                result = self;
            }
            if (!result && typeof window !== strShimUndefined) {
                result = window;
            }
            if (!result && typeof global !== strShimUndefined) {
                result = global;
            }
            _cachedGlobal = result;
        }
        return result;
    }
    function throwTypeError(message) {
        throw new TypeError(message);
    }
    function objCreateFn(obj) {
        var func = ObjCreate;
        if (func) {
            return func(obj);
        }
        if (obj == null) {
            return {};
        }
        var type = typeof obj;
        if (type !== strShimObject && type !== strShimFunction) {
            throwTypeError("Object prototype may only be an Object:" + obj);
        }
        function tmpFunc() { }
        tmpFunc[strShimPrototype] = obj;
        return new tmpFunc();
    }

    (getGlobal() || {})["Symbol"];
    (getGlobal() || {})["Reflect"];
    var extendStaticsFn = function (d, b) {
        extendStaticsFn = ObjClass["setPrototypeOf"] ||
            ({ __proto__: [] } instanceof Array && function (d, b) {
                d.__proto__ = b;
            }) ||
            function (d, b) {
                for (var p in b) {
                    if (b[strShimHasOwnProperty](p)) {
                        d[p] = b[p];
                    }
                }
            };
        return extendStaticsFn(d, b);
    };
    function __extendsFn(d, b) {
        if (typeof b !== strShimFunction && b !== null) {
            throwTypeError("Class extends value " + String(b) + " is not a constructor or null");
        }
        extendStaticsFn(d, b);
        function __() {
            this.constructor = d;
        }
        d[strShimPrototype] = b === null ? objCreateFn(b) : (__[strShimPrototype] = b[strShimPrototype], new __());
    }
    function __spreadArrayFn(to, from) {
        for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) {
            to[j] = from[i];
        }
        return to;
    }

    var _DYN_INITIALIZE = "initialize";
    var _DYN_NAME = "name";
    var _DYN_GET_NOTIFY_MGR = "getNotifyMgr";
    var _DYN_IDENTIFIER = "identifier";
    var _DYN_PUSH = "push";
    var _DYN_IS_INITIALIZED = "isInitialized";
    var _DYN_CONFIG = "config";
    var _DYN_INSTRUMENTATION_KEY = "instrumentationKey";
    var _DYN_LOGGER = "logger";
    var _DYN_LENGTH = "length";
    var _DYN_TIME = "time";
    var _DYN_PROCESS_NEXT = "processNext";
    var _DYN_GET_PROCESS_TEL_CONT0 = "getProcessTelContext";
    var _DYN_ADD_NOTIFICATION_LIS1 = "addNotificationListener";
    var _DYN_REMOVE_NOTIFICATION_2 = "removeNotificationListener";
    var _DYN_STOP_POLLING_INTERNA3 = "stopPollingInternalLogs";
    var _DYN_ON_COMPLETE = "onComplete";
    var _DYN_GET_PLUGIN = "getPlugin";
    var _DYN_FLUSH = "flush";
    var _DYN__EXTENSIONS = "_extensions";
    var _DYN_SPLICE = "splice";
    var _DYN_TEARDOWN = "teardown";
    var _DYN_MESSAGE_ID = "messageId";
    var _DYN_MESSAGE = "message";
    var _DYN_IS_ASYNC = "isAsync";
    var _DYN__DO_TEARDOWN = "_doTeardown";
    var _DYN_UPDATE = "update";
    var _DYN_GET_NEXT = "getNext";
    var _DYN_DIAG_LOG = "diagLog";
    var _DYN_SET_NEXT_PLUGIN = "setNextPlugin";
    var _DYN_CREATE_NEW = "createNew";
    var _DYN_COOKIE_CFG = "cookieCfg";
    var _DYN_INDEX_OF = "indexOf";
    var _DYN_SUBSTRING = "substring";
    var _DYN_USER_AGENT = "userAgent";
    var _DYN_SPLIT = "split";
    var _DYN_SET_ENABLED = "setEnabled";
    var _DYN_SUBSTR = "substr";
    var _DYN_NODE_TYPE = "nodeType";
    var _DYN_APPLY = "apply";
    var _DYN_REPLACE = "replace";
    var _DYN_ENABLE_DEBUG_EXCEPTI4 = "enableDebugExceptions";
    var _DYN_LOG_INTERNAL_MESSAGE = "logInternalMessage";
    var _DYN_TO_LOWER_CASE = "toLowerCase";
    var _DYN_CALL = "call";
    var _DYN_TYPE = "type";
    var _DYN_HANDLER = "handler";
    var _DYN_LISTENERS = "listeners";
    var _DYN_IS_CHILD_EVT = "isChildEvt";
    var _DYN_GET_CTX = "getCtx";
    var _DYN_SET_CTX = "setCtx";
    var _DYN_COMPLETE = "complete";
    var _DYN_TRACE_ID = "traceId";
    var _DYN_SPAN_ID = "spanId";
    var _DYN_TRACE_FLAGS = "traceFlags";
    var _DYN_VERSION = "version";

    var STR_EMPTY = "";
    var STR_CHANNELS = "channels";
    var STR_CORE = "core";
    var STR_CREATE_PERF_MGR = "createPerfMgr";
    var STR_DISABLED = "disabled";
    var STR_EXTENSION_CONFIG = "extensionConfig";
    var STR_EXTENSIONS = "extensions";
    var STR_PROCESS_TELEMETRY = "processTelemetry";
    var STR_PRIORITY = "priority";
    var STR_EVENTS_SENT = "eventsSent";
    var STR_EVENTS_DISCARDED = "eventsDiscarded";
    var STR_EVENTS_SEND_REQUEST = "eventsSendRequest";
    var STR_PERF_EVENT = "perfEvent";
    var STR_ERROR_TO_CONSOLE = "errorToConsole";
    var STR_WARN_TO_CONSOLE = "warnToConsole";
    var STR_GET_PERF_MGR = "getPerfMgr";

    var strToISOString = "toISOString";
    var cStrEndsWith = "endsWith";
    var cStrStartsWith = "startsWith";
    var strIndexOf = "indexOf";
    var strMap = "map";
    var strReduce = "reduce";
    var cStrTrim = "trim";
    var strToString = "toString";
    var str__Proto$1 = "__proto__";
    var strConstructor = "constructor";
    var _objDefineProperty$1 = ObjDefineProperty;
    var _objFreeze = ObjClass.freeze;
    var _objSeal = ObjClass.seal;
    var _objKeys = ObjClass.keys;
    var StringProto = String[strShimPrototype];
    var _strTrim = StringProto[cStrTrim];
    var _strEndsWith = StringProto[cStrEndsWith];
    var _strStartsWith = StringProto[cStrStartsWith];
    var DateProto = Date[strShimPrototype];
    var _dataToISOString = DateProto[strToISOString];
    var _isArray = Array.isArray;
    var _objToString = ObjProto[strToString];
    var _fnToString = ObjHasOwnProperty[strToString];
    var _objFunctionString = _fnToString[_DYN_CALL ](ObjClass);
    var rCamelCase = /-([a-z])/g;
    var rNormalizeInvalid = /([^\w\d_$])/g;
    var rLeadingNumeric = /^(\d+[\w\d_$])/;
    var _objGetPrototypeOf$1 = Object["getPrototypeOf"];
    function _getObjProto$1(target) {
        if (target) {
            if (_objGetPrototypeOf$1) {
                return _objGetPrototypeOf$1(target);
            }
            var newProto = target[str__Proto$1] || target[strShimPrototype] || target[strConstructor];
            if (newProto) {
                return newProto;
            }
        }
        return null;
    }
    function objToString(obj) {
        return _objToString[_DYN_CALL ](obj);
    }
    function isTypeof(value, theType) {
        return typeof value === theType;
    }
    function isUndefined(value) {
        return value === undefined || typeof value === strShimUndefined;
    }
    function isNotUndefined(value) {
        return !isUndefined(value);
    }
    function isNullOrUndefined(value) {
        return (value === null || isUndefined(value));
    }
    function isNotNullOrUndefined(value) {
        return !isNullOrUndefined(value);
    }
    function hasOwnProperty(obj, prop) {
        return !!(obj && ObjHasOwnProperty[_DYN_CALL ](obj, prop));
    }
    function isObject(value) {
        return !!(value && typeof value === strShimObject);
    }
    function isFunction(value) {
        return !!(value && typeof value === strShimFunction);
    }
    function normalizeJsName(name) {
        var value = name;
        if (value && isString(value)) {
            value = value[_DYN_REPLACE ](rCamelCase, function (_all, letter) {
                return letter.toUpperCase();
            });
            value = value[_DYN_REPLACE ](rNormalizeInvalid, "_");
            value = value[_DYN_REPLACE ](rLeadingNumeric, function (_all, match) {
                return "_" + match;
            });
        }
        return value;
    }
    function objForEachKey(target, callbackfn) {
        if (target) {
            for (var prop in target) {
                if (ObjHasOwnProperty[_DYN_CALL ](target, prop)) {
                    callbackfn[_DYN_CALL ](target, prop, target[prop]);
                }
            }
        }
    }
    function strEndsWith(value, search) {
        var result = false;
        if (value && search && !(result = value === search)) {
            result = _strEndsWith ? value[cStrEndsWith](search) : _strEndsWithPoly(value, search);
        }
        return result;
    }
    function _strEndsWithPoly(value, search) {
        var result = false;
        var searchLen = search ? search[_DYN_LENGTH ] : 0;
        var valLen = value ? value[_DYN_LENGTH ] : 0;
        if (searchLen && valLen && valLen >= searchLen && !(result = value === search)) {
            var pos = valLen - 1;
            for (var lp = searchLen - 1; lp >= 0; lp--) {
                if (value[pos] != search[lp]) {
                    return false;
                }
                pos--;
            }
            result = true;
        }
        return result;
    }
    function strStartsWith(value, checkValue) {
        var result = false;
        if (value && checkValue && !(result = value === checkValue)) {
            result = _strStartsWith ? value[cStrStartsWith](checkValue) : _strStartsWithPoly(value, checkValue);
        }
        return result;
    }
    function _strStartsWithPoly(value, checkValue) {
        var result = false;
        var chkLen = checkValue ? checkValue[_DYN_LENGTH ] : 0;
        if (value && chkLen && value[_DYN_LENGTH ] >= chkLen && !(result = value === checkValue)) {
            for (var lp = 0; lp < chkLen; lp++) {
                if (value[lp] !== checkValue[lp]) {
                    return false;
                }
            }
            result = true;
        }
        return result;
    }
    function strContains(value, search) {
        if (value && search) {
            return value[_DYN_INDEX_OF ](search) !== -1;
        }
        return false;
    }
    function isDate(obj) {
        return !!(obj && _objToString[_DYN_CALL ](obj) === "[object Date]");
    }
    var isArray = _isArray || _isArrayPoly;
    function _isArrayPoly(obj) {
        return !!(obj && _objToString[_DYN_CALL ](obj) === "[object Array]");
    }
    function isError(obj) {
        return !!(obj && _objToString[_DYN_CALL ](obj) === "[object Error]");
    }
    function isString(value) {
        return typeof value === "string";
    }
    function isNumber(value) {
        return typeof value === "number";
    }
    function isBoolean(value) {
        return typeof value === "boolean";
    }
    function isSymbol(value) {
        return typeof value === "symbol";
    }
    function isPlainObject(value) {
        var result = false;
        if (value && typeof value === "object") {
            var proto = _objGetPrototypeOf$1 ? _objGetPrototypeOf$1(value) : _getObjProto$1(value);
            if (!proto) {
                result = true;
            }
            else {
                if (proto[strConstructor] && ObjHasOwnProperty[_DYN_CALL ](proto, strConstructor)) {
                    proto = proto[strConstructor];
                }
                result = typeof proto === strShimFunction && _fnToString[_DYN_CALL ](proto) === _objFunctionString;
            }
        }
        return result;
    }
    function toISOString(date) {
        if (date) {
            return _dataToISOString ? date[strToISOString]() : _toISOStringPoly(date);
        }
    }
    function _toISOStringPoly(date) {
        if (date && date.getUTCFullYear) {
            var pad = function (num) {
                var r = String(num);
                if (r[_DYN_LENGTH ] === 1) {
                    r = "0" + r;
                }
                return r;
            };
            return date.getUTCFullYear()
                + "-" + pad(date.getUTCMonth() + 1)
                + "-" + pad(date.getUTCDate())
                + "T" + pad(date.getUTCHours())
                + ":" + pad(date.getUTCMinutes())
                + ":" + pad(date.getUTCSeconds())
                + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
                + "Z";
        }
    }
    function arrForEach(arr, callbackfn, thisArg) {
        var len = arr[_DYN_LENGTH ];
        try {
            for (var idx = 0; idx < len; idx++) {
                if (idx in arr) {
                    if (callbackfn[_DYN_CALL ](thisArg || arr, arr[idx], idx, arr) === -1) {
                        break;
                    }
                }
            }
        }
        catch (e) {
        }
    }
    function arrIndexOf(arr, searchElement, fromIndex) {
        if (arr) {
            if (arr[strIndexOf]) {
                return arr[strIndexOf](searchElement, fromIndex);
            }
            var len = arr[_DYN_LENGTH ];
            var from = fromIndex || 0;
            try {
                for (var lp = Math.max(from >= 0 ? from : len - Math.abs(from), 0); lp < len; lp++) {
                    if (lp in arr && arr[lp] === searchElement) {
                        return lp;
                    }
                }
            }
            catch (e) {
            }
        }
        return -1;
    }
    function arrMap(arr, callbackfn, thisArg) {
        var results;
        if (arr) {
            if (arr[strMap]) {
                return arr[strMap](callbackfn, thisArg);
            }
            var len = arr[_DYN_LENGTH ];
            var _this = thisArg || arr;
            results = new Array(len);
            try {
                for (var lp = 0; lp < len; lp++) {
                    if (lp in arr) {
                        results[lp] = callbackfn[_DYN_CALL ](_this, arr[lp], arr);
                    }
                }
            }
            catch (e) {
            }
        }
        return results;
    }
    function arrReduce(arr, callbackfn, initialValue) {
        var value;
        if (arr) {
            if (arr[strReduce]) {
                return arr[strReduce](callbackfn, initialValue);
            }
            var len = arr[_DYN_LENGTH ];
            var lp = 0;
            if (arguments[_DYN_LENGTH ] >= 3) {
                value = arguments[2];
            }
            else {
                while (lp < len && !(lp in arr)) {
                    lp++;
                }
                value = arr[lp++];
            }
            while (lp < len) {
                if (lp in arr) {
                    value = callbackfn(value, arr[lp], lp, arr);
                }
                lp++;
            }
        }
        return value;
    }
    function strTrim(str) {
        if (str) {
            str = (_strTrim && str[cStrTrim]) ? str[cStrTrim]() : (str[_DYN_REPLACE ] ? str[_DYN_REPLACE ](/^\s+|(?=\s)\s+$/g, STR_EMPTY) : str);
        }
        return str;
    }
    var _objKeysHasDontEnumBug = !({ toString: null }).propertyIsEnumerable("toString");
    var _objKeysDontEnums = [
        "toString",
        "toLocaleString",
        "valueOf",
        "hasOwnProperty",
        "isPrototypeOf",
        "propertyIsEnumerable",
        "constructor"
    ];
    function objKeys(obj) {
        var objType = typeof obj;
        if (objType !== strShimFunction && (objType !== strShimObject || obj === null)) {
            throwTypeError("objKeys called on non-object");
        }
        if (!_objKeysHasDontEnumBug && _objKeys) {
            return _objKeys(obj);
        }
        var result = [];
        for (var prop in obj) {
            if (obj && ObjHasOwnProperty[_DYN_CALL ](obj, prop)) {
                result[_DYN_PUSH ](prop);
            }
        }
        if (_objKeysHasDontEnumBug) {
            var dontEnumsLength = _objKeysDontEnums[_DYN_LENGTH ];
            for (var lp = 0; lp < dontEnumsLength; lp++) {
                if (obj && ObjHasOwnProperty[_DYN_CALL ](obj, _objKeysDontEnums[lp])) {
                    result[_DYN_PUSH ](_objKeysDontEnums[lp]);
                }
            }
        }
        return result;
    }
    function objDefineAccessors(target, prop, getProp, setProp) {
        if (_objDefineProperty$1) {
            try {
                var descriptor = {
                    enumerable: true,
                    configurable: true
                };
                if (getProp) {
                    descriptor.get = getProp;
                }
                if (setProp) {
                    descriptor.set = setProp;
                }
                _objDefineProperty$1(target, prop, descriptor);
                return true;
            }
            catch (e) {
            }
        }
        return false;
    }
    function _doNothing(value) {
        return value;
    }
    function deepFreeze(obj) {
        if (_objFreeze) {
            objForEachKey(obj, function (name, value) {
                if (isArray(value) || isObject(value)) {
                    _objFreeze(value);
                }
            });
        }
        return objFreeze(obj);
    }
    var objFreeze = _objFreeze || _doNothing;
    var objSeal = _objSeal || _doNothing;
    function dateNow() {
        var dt = Date;
        return dt.now ? dt.now() : new dt().getTime();
    }
    function getExceptionName(object) {
        if (isError(object)) {
            return object[_DYN_NAME ];
        }
        return STR_EMPTY;
    }
    function setValue(target, field, value, valChk, srcChk) {
        var theValue = value;
        if (target) {
            theValue = target[field];
            if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) {
                theValue = value;
                target[field] = theValue;
            }
        }
        return theValue;
    }
    function getSetValue(target, field, defValue) {
        var theValue;
        if (target) {
            theValue = target[field];
            if (!theValue && isNullOrUndefined(theValue)) {
                theValue = !isUndefined(defValue) ? defValue : {};
                target[field] = theValue;
            }
        }
        else {
            theValue = !isUndefined(defValue) ? defValue : {};
        }
        return theValue;
    }
    function getCfgValue(theValue, defaultValue) {
        return !isNullOrUndefined(theValue) ? theValue : defaultValue;
    }
    function isNotTruthy(value) {
        return !value;
    }
    function isTruthy(value) {
        return !!value;
    }
    function throwError(message) {
        throw new Error(message);
    }
    function _createProxyFunction(source, funcName) {
        var srcFunc = null;
        var src = null;
        if (isFunction(source)) {
            srcFunc = source;
        }
        else {
            src = source;
        }
        return function () {
            var originalArguments = arguments;
            if (srcFunc) {
                src = srcFunc();
            }
            if (src) {
                return src[funcName][_DYN_APPLY ](src, originalArguments);
            }
        };
    }
    function proxyAssign(target, source, chkSet) {
        if (target && source && isObject(target) && isObject(source)) {
            var _loop_1 = function (field) {
                if (isString(field)) {
                    var value = source[field];
                    if (isFunction(value)) {
                        if (!chkSet || chkSet(field, true, source, target)) {
                            target[field] = _createProxyFunction(source, field);
                        }
                    }
                    else if (!chkSet || chkSet(field, false, source, target)) {
                        if (hasOwnProperty(target, field)) {
                            delete target[field];
                        }
                        if (!objDefineAccessors(target, field, function () {
                            return source[field];
                        }, function (theValue) {
                            source[field] = theValue;
                        })) {
                            target[field] = value;
                        }
                    }
                }
            };
            for (var field in source) {
                _loop_1(field);
            }
        }
        return target;
    }
    function proxyFunctionAs(target, name, source, theFunc, overwriteTarget) {
        if (target && name && source) {
            if (overwriteTarget !== false || isUndefined(target[name])) {
                target[name] = _createProxyFunction(source, theFunc);
            }
        }
    }
    function proxyFunctions(target, source, functionsToProxy, overwriteTarget) {
        if (target && source && isObject(target) && isArray(functionsToProxy)) {
            arrForEach(functionsToProxy, function (theFuncName) {
                if (isString(theFuncName)) {
                    proxyFunctionAs(target, theFuncName, source, theFuncName, overwriteTarget);
                }
            });
        }
        return target;
    }
    function createClassFromInterface(defaults) {
        return /** @class */ (function () {
            function class_1() {
                var _this_1 = this;
                if (defaults) {
                    objForEachKey(defaults, function (field, value) {
                        _this_1[field] = value;
                    });
                }
            }
            return class_1;
        }());
    }
    function optimizeObject(theObject) {
        if (theObject && ObjAssign) {
            theObject = ObjClass(ObjAssign({}, theObject));
        }
        return theObject;
    }
    function objExtend(obj1, obj2, obj3, obj4, obj5, obj6) {
        var theArgs = arguments;
        var extended = theArgs[0] || {};
        var argLen = theArgs[_DYN_LENGTH ];
        var deep = false;
        var idx = 1;
        if (argLen > 0 && isBoolean(extended)) {
            deep = extended;
            extended = theArgs[idx] || {};
            idx++;
        }
        if (!isObject(extended)) {
            extended = {};
        }
        for (; idx < argLen; idx++) {
            var arg = theArgs[idx];
            var isArgArray = isArray(arg);
            var isArgObj = isObject(arg);
            for (var prop in arg) {
                var propOk = (isArgArray && (prop in arg)) || (isArgObj && (ObjHasOwnProperty[_DYN_CALL ](arg, prop)));
                if (!propOk) {
                    continue;
                }
                var newValue = arg[prop];
                var isNewArray = void 0;
                if (deep && newValue && ((isNewArray = isArray(newValue)) || isPlainObject(newValue))) {
                    var clone = extended[prop];
                    if (isNewArray) {
                        if (!isArray(clone)) {
                            clone = [];
                        }
                    }
                    else if (!isPlainObject(clone)) {
                        clone = {};
                    }
                    newValue = objExtend(deep, clone, newValue);
                }
                if (newValue !== undefined) {
                    extended[prop] = newValue;
                }
            }
        }
        return extended;
    }

    function createEnumStyle(values) {
        var enumClass = {};
        objForEachKey(values, function (field, value) {
            enumClass[field] = value;
            enumClass[value] = field;
        });
        return deepFreeze(enumClass);
    }
    function createEnumMap(values) {
        var mapClass = {};
        objForEachKey(values, function (field, value) {
            mapClass[field] = field;
            mapClass[value] = field;
        });
        return deepFreeze(mapClass);
    }
    function createValueMap(values) {
        var mapClass = {};
        objForEachKey(values, function (field, value) {
            mapClass[field] = value[1];
            mapClass[value[0]] = value[1];
        });
        return deepFreeze(mapClass);
    }

    var EventsDiscardedReason = createEnumStyle({
        Unknown: 0 ,
        NonRetryableStatus: 1 ,
        InvalidEvent: 2 ,
        SizeLimitExceeded: 3 ,
        KillSwitch: 4 ,
        QueueFull: 5
    });

    /*!
     * Microsoft Dynamic Proto Utility, 1.1.9
     * Copyright (c) Microsoft and contributors. All rights reserved.
     */
    var _a$1;
    var UNDEFINED = "undefined";
    var Constructor = 'constructor';
    var Prototype = 'prototype';
    var strFunction = 'function';
    var DynInstFuncTable = '_dynInstFuncs';
    var DynProxyTag = '_isDynProxy';
    var DynClassName = '_dynClass';
    var DynClassNamePrefix = '_dynCls$';
    var DynInstChkTag = '_dynInstChk';
    var DynAllowInstChkTag = DynInstChkTag;
    var DynProtoDefaultOptions = '_dfOpts';
    var UnknownValue = '_unknown_';
    var str__Proto = "__proto__";
    var DynProtoBaseProto = "_dyn" + str__Proto;
    var DynProtoGlobalSettings = "__dynProto$Gbl";
    var DynProtoCurrent = "_dynInstProto";
    var strUseBaseInst = 'useBaseInst';
    var strSetInstFuncs = 'setInstFuncs';
    var Obj = Object;
    var _objGetPrototypeOf = Obj["getPrototypeOf"];
    var _objGetOwnProps = Obj["getOwnPropertyNames"];
    function _getGlobal() {
        var result;
        if (typeof globalThis !== UNDEFINED) {
            result = globalThis;
        }
        if (!result && typeof self !== UNDEFINED) {
            result = self;
        }
        if (!result && typeof window !== UNDEFINED) {
            result = window;
        }
        if (!result && typeof global !== UNDEFINED) {
            result = global;
        }
        return result || {};
    }
    var _gbl = _getGlobal();
    var _gblInst = _gbl[DynProtoGlobalSettings] || (_gbl[DynProtoGlobalSettings] = {
        o: (_a$1 = {},
            _a$1[strSetInstFuncs] = true,
            _a$1[strUseBaseInst] = true,
            _a$1),
        n: 1000
    });
    function _hasOwnProperty(obj, prop) {
        return obj && Obj[Prototype].hasOwnProperty.call(obj, prop);
    }
    function _isObjectOrArrayPrototype(target) {
        return target && (target === Obj[Prototype] || target === Array[Prototype]);
    }
    function _isObjectArrayOrFunctionPrototype(target) {
        return _isObjectOrArrayPrototype(target) || target === Function[Prototype];
    }
    function _getObjProto(target) {
        var newProto;
        if (target) {
            if (_objGetPrototypeOf) {
                return _objGetPrototypeOf(target);
            }
            var curProto = target[str__Proto] || target[Prototype] || (target[Constructor] ? target[Constructor][Prototype] : null);
            newProto = target[DynProtoBaseProto] || curProto;
            if (!_hasOwnProperty(target, DynProtoBaseProto)) {
                delete target[DynProtoCurrent];
                newProto = target[DynProtoBaseProto] = target[DynProtoCurrent] || target[DynProtoBaseProto];
                target[DynProtoCurrent] = curProto;
            }
        }
        return newProto;
    }
    function _forEachProp(target, func) {
        var props = [];
        if (_objGetOwnProps) {
            props = _objGetOwnProps(target);
        }
        else {
            for (var name_1 in target) {
                if (typeof name_1 === "string" && _hasOwnProperty(target, name_1)) {
                    props.push(name_1);
                }
            }
        }
        if (props && props.length > 0) {
            for (var lp = 0; lp < props.length; lp++) {
                func(props[lp]);
            }
        }
    }
    function _isDynamicCandidate(target, funcName, skipOwn) {
        return (funcName !== Constructor && typeof target[funcName] === strFunction && (skipOwn || _hasOwnProperty(target, funcName)));
    }
    function _throwTypeError(message) {
        throw new TypeError("DynamicProto: " + message);
    }
    function _getInstanceFuncs(thisTarget) {
        var instFuncs = {};
        _forEachProp(thisTarget, function (name) {
            if (!instFuncs[name] && _isDynamicCandidate(thisTarget, name, false)) {
                instFuncs[name] = thisTarget[name];
            }
        });
        return instFuncs;
    }
    function _hasVisited(values, value) {
        for (var lp = values.length - 1; lp >= 0; lp--) {
            if (values[lp] === value) {
                return true;
            }
        }
        return false;
    }
    function _getBaseFuncs(classProto, thisTarget, instFuncs, useBaseInst) {
        function _instFuncProxy(target, funcHost, funcName) {
            var theFunc = funcHost[funcName];
            if (theFunc[DynProxyTag] && useBaseInst) {
                var instFuncTable = target[DynInstFuncTable] || {};
                if (instFuncTable[DynAllowInstChkTag] !== false) {
                    theFunc = (instFuncTable[funcHost[DynClassName]] || {})[funcName] || theFunc;
                }
            }
            return function () {
                return theFunc.apply(target, arguments);
            };
        }
        var baseFuncs = {};
        _forEachProp(instFuncs, function (name) {
            baseFuncs[name] = _instFuncProxy(thisTarget, instFuncs, name);
        });
        var baseProto = _getObjProto(classProto);
        var visited = [];
        while (baseProto && !_isObjectArrayOrFunctionPrototype(baseProto) && !_hasVisited(visited, baseProto)) {
            _forEachProp(baseProto, function (name) {
                if (!baseFuncs[name] && _isDynamicCandidate(baseProto, name, !_objGetPrototypeOf)) {
                    baseFuncs[name] = _instFuncProxy(thisTarget, baseProto, name);
                }
            });
            visited.push(baseProto);
            baseProto = _getObjProto(baseProto);
        }
        return baseFuncs;
    }
    function _getInstFunc(target, funcName, proto, currentDynProtoProxy) {
        var instFunc = null;
        if (target && _hasOwnProperty(proto, DynClassName)) {
            var instFuncTable = target[DynInstFuncTable] || {};
            instFunc = (instFuncTable[proto[DynClassName]] || {})[funcName];
            if (!instFunc) {
                _throwTypeError("Missing [" + funcName + "] " + strFunction);
            }
            if (!instFunc[DynInstChkTag] && instFuncTable[DynAllowInstChkTag] !== false) {
                var canAddInst = !_hasOwnProperty(target, funcName);
                var objProto = _getObjProto(target);
                var visited = [];
                while (canAddInst && objProto && !_isObjectArrayOrFunctionPrototype(objProto) && !_hasVisited(visited, objProto)) {
                    var protoFunc = objProto[funcName];
                    if (protoFunc) {
                        canAddInst = (protoFunc === currentDynProtoProxy);
                        break;
                    }
                    visited.push(objProto);
                    objProto = _getObjProto(objProto);
                }
                try {
                    if (canAddInst) {
                        target[funcName] = instFunc;
                    }
                    instFunc[DynInstChkTag] = 1;
                }
                catch (e) {
                    instFuncTable[DynAllowInstChkTag] = false;
                }
            }
        }
        return instFunc;
    }
    function _getProtoFunc(funcName, proto, currentDynProtoProxy) {
        var protoFunc = proto[funcName];
        if (protoFunc === currentDynProtoProxy) {
            protoFunc = _getObjProto(proto)[funcName];
        }
        if (typeof protoFunc !== strFunction) {
            _throwTypeError("[" + funcName + "] is not a " + strFunction);
        }
        return protoFunc;
    }
    function _populatePrototype(proto, className, target, baseInstFuncs, setInstanceFunc) {
        function _createDynamicPrototype(proto, funcName) {
            var dynProtoProxy = function () {
                var instFunc = _getInstFunc(this, funcName, proto, dynProtoProxy) || _getProtoFunc(funcName, proto, dynProtoProxy);
                return instFunc.apply(this, arguments);
            };
            dynProtoProxy[DynProxyTag] = 1;
            return dynProtoProxy;
        }
        if (!_isObjectOrArrayPrototype(proto)) {
            var instFuncTable = target[DynInstFuncTable] = target[DynInstFuncTable] || {};
            var instFuncs_1 = instFuncTable[className] = (instFuncTable[className] || {});
            if (instFuncTable[DynAllowInstChkTag] !== false) {
                instFuncTable[DynAllowInstChkTag] = !!setInstanceFunc;
            }
            _forEachProp(target, function (name) {
                if (_isDynamicCandidate(target, name, false) && target[name] !== baseInstFuncs[name]) {
                    instFuncs_1[name] = target[name];
                    delete target[name];
                    if (!_hasOwnProperty(proto, name) || (proto[name] && !proto[name][DynProxyTag])) {
                        proto[name] = _createDynamicPrototype(proto, name);
                    }
                }
            });
        }
    }
    function _checkPrototype(classProto, thisTarget) {
        if (_objGetPrototypeOf) {
            var visited = [];
            var thisProto = _getObjProto(thisTarget);
            while (thisProto && !_isObjectArrayOrFunctionPrototype(thisProto) && !_hasVisited(visited, thisProto)) {
                if (thisProto === classProto) {
                    return true;
                }
                visited.push(thisProto);
                thisProto = _getObjProto(thisProto);
            }
            return false;
        }
        return true;
    }
    function _getObjName(target, unknownValue) {
        if (_hasOwnProperty(target, Prototype)) {
            return target.name || unknownValue || UnknownValue;
        }
        return (((target || {})[Constructor]) || {}).name || unknownValue || UnknownValue;
    }
    function dynamicProto(theClass, target, delegateFunc, options) {
        if (!_hasOwnProperty(theClass, Prototype)) {
            _throwTypeError("theClass is an invalid class definition.");
        }
        var classProto = theClass[Prototype];
        if (!_checkPrototype(classProto, target)) {
            _throwTypeError("[" + _getObjName(theClass) + "] not in hierarchy of [" + _getObjName(target) + "]");
        }
        var className = null;
        if (_hasOwnProperty(classProto, DynClassName)) {
            className = classProto[DynClassName];
        }
        else {
            className = DynClassNamePrefix + _getObjName(theClass, "_") + "$" + _gblInst.n;
            _gblInst.n++;
            classProto[DynClassName] = className;
        }
        var perfOptions = dynamicProto[DynProtoDefaultOptions];
        var useBaseInst = !!perfOptions[strUseBaseInst];
        if (useBaseInst && options && options[strUseBaseInst] !== undefined) {
            useBaseInst = !!options[strUseBaseInst];
        }
        var instFuncs = _getInstanceFuncs(target);
        var baseFuncs = _getBaseFuncs(classProto, target, instFuncs, useBaseInst);
        delegateFunc(target, baseFuncs);
        var setInstanceFunc = !!_objGetPrototypeOf && !!perfOptions[strSetInstFuncs];
        if (setInstanceFunc && options) {
            setInstanceFunc = !!options[strSetInstFuncs];
        }
        _populatePrototype(classProto, className, target, instFuncs, setInstanceFunc !== false);
    }
    dynamicProto[DynProtoDefaultOptions] = _gblInst.o;

    var strWindow = "window";
    var strDocument = "document";
    var strDocumentMode = "documentMode";
    var strNavigator = "navigator";
    var strHistory = "history";
    var strLocation = "location";
    var strConsole = "console";
    var strPerformance = "performance";
    var strJSON = "JSON";
    var strCrypto = "crypto";
    var strMsCrypto = "msCrypto";
    var strReactNative = "ReactNative";
    var strMsie = "msie";
    var strTrident = "trident/";
    var strXMLHttpRequest = "XMLHttpRequest";
    var _isTrident = null;
    var _navUserAgentCheck = null;
    var _enableMocks = false;
    var _useXDomainRequest = null;
    var _beaconsSupported = null;
    function _hasProperty(theClass, property) {
        var supported = false;
        if (theClass) {
            try {
                supported = property in theClass;
                if (!supported) {
                    var proto = theClass[strShimPrototype];
                    if (proto) {
                        supported = property in proto;
                    }
                }
            }
            catch (e) {
            }
            if (!supported) {
                try {
                    var tmp = new theClass();
                    supported = !isUndefined(tmp[property]);
                }
                catch (e) {
                }
            }
        }
        return supported;
    }
    function setEnableEnvMocks(enabled) {
        _enableMocks = enabled;
    }
    function getGlobalInst(name) {
        var gbl = getGlobal();
        if (gbl && gbl[name]) {
            return gbl[name];
        }
        if (name === strWindow && hasWindow()) {
            return window;
        }
        return null;
    }
    function hasWindow() {
        return Boolean(typeof window === strShimObject && window);
    }
    function getWindow() {
        if (hasWindow()) {
            return window;
        }
        return getGlobalInst(strWindow);
    }
    function hasDocument() {
        return Boolean(typeof document === strShimObject && document);
    }
    function getDocument() {
        if (hasDocument()) {
            return document;
        }
        return getGlobalInst(strDocument);
    }
    function hasNavigator() {
        return Boolean(typeof navigator === strShimObject && navigator);
    }
    function getNavigator() {
        if (hasNavigator()) {
            return navigator;
        }
        return getGlobalInst(strNavigator);
    }
    function hasHistory() {
        return Boolean(typeof history === strShimObject && history);
    }
    function getHistory() {
        if (hasHistory()) {
            return history;
        }
        return getGlobalInst(strHistory);
    }
    function getLocation(checkForMock) {
        if (checkForMock && _enableMocks) {
            var mockLocation = getGlobalInst("__mockLocation");
            if (mockLocation) {
                return mockLocation;
            }
        }
        if (typeof location === strShimObject && location) {
            return location;
        }
        return getGlobalInst(strLocation);
    }
    function getConsole() {
        if (typeof console !== strShimUndefined) {
            return console;
        }
        return getGlobalInst(strConsole);
    }
    function getPerformance() {
        return getGlobalInst(strPerformance);
    }
    function hasJSON() {
        return Boolean((typeof JSON === strShimObject && JSON) || getGlobalInst(strJSON) !== null);
    }
    function getJSON() {
        if (hasJSON()) {
            return JSON || getGlobalInst(strJSON);
        }
        return null;
    }
    function getCrypto() {
        return getGlobalInst(strCrypto);
    }
    function getMsCrypto() {
        return getGlobalInst(strMsCrypto);
    }
    function isReactNative() {
        var nav = getNavigator();
        if (nav && nav.product) {
            return nav.product === strReactNative;
        }
        return false;
    }
    function isIE() {
        var nav = getNavigator();
        if (nav && (nav[_DYN_USER_AGENT ] !== _navUserAgentCheck || _isTrident === null)) {
            _navUserAgentCheck = nav[_DYN_USER_AGENT ];
            var userAgent = (_navUserAgentCheck || STR_EMPTY)[_DYN_TO_LOWER_CASE ]();
            _isTrident = (strContains(userAgent, strMsie) || strContains(userAgent, strTrident));
        }
        return _isTrident;
    }
    function getIEVersion(userAgentStr) {
        if (userAgentStr === void 0) { userAgentStr = null; }
        if (!userAgentStr) {
            var navigator_1 = getNavigator() || {};
            userAgentStr = navigator_1 ? (navigator_1[_DYN_USER_AGENT ] || STR_EMPTY)[_DYN_TO_LOWER_CASE ]() : STR_EMPTY;
        }
        var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE ]();
        if (strContains(ua, strMsie)) {
            var doc = getDocument() || {};
            return Math.max(parseInt(ua[_DYN_SPLIT ](strMsie)[1]), (doc[strDocumentMode] || 0));
        }
        else if (strContains(ua, strTrident)) {
            var tridentVer = parseInt(ua[_DYN_SPLIT ](strTrident)[1]);
            if (tridentVer) {
                return tridentVer + 4;
            }
        }
        return null;
    }
    function dumpObj(object) {
        var objectTypeDump = Object[strShimPrototype].toString[_DYN_CALL ](object);
        var propertyValueDump = STR_EMPTY;
        if (objectTypeDump === "[object Error]") {
            propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object[_DYN_NAME ] + "'";
        }
        else if (hasJSON()) {
            propertyValueDump = getJSON().stringify(object);
        }
        return objectTypeDump + propertyValueDump;
    }
    function isSafari(userAgentStr) {
        if (!userAgentStr || !isString(userAgentStr)) {
            var navigator_2 = getNavigator() || {};
            userAgentStr = navigator_2 ? (navigator_2[_DYN_USER_AGENT ] || STR_EMPTY)[_DYN_TO_LOWER_CASE ]() : STR_EMPTY;
        }
        var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE ]();
        return (ua[_DYN_INDEX_OF ]("safari") >= 0);
    }
    function isBeaconsSupported() {
        if (_beaconsSupported === null) {
            _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon);
        }
        return _beaconsSupported;
    }
    function isFetchSupported(withKeepAlive) {
        var isSupported = false;
        try {
            isSupported = !!getGlobalInst("fetch");
            var request = getGlobalInst("Request");
            if (isSupported && withKeepAlive && request) {
                isSupported = _hasProperty(request, "keepalive");
            }
        }
        catch (e) {
        }
        return isSupported;
    }
    function useXDomainRequest() {
        if (_useXDomainRequest === null) {
            _useXDomainRequest = (typeof XDomainRequest !== strShimUndefined);
            if (_useXDomainRequest && isXhrSupported()) {
                _useXDomainRequest = _useXDomainRequest && !_hasProperty(getGlobalInst(strXMLHttpRequest), "withCredentials");
            }
        }
        return _useXDomainRequest;
    }
    function isXhrSupported() {
        var isSupported = false;
        try {
            var xmlHttpRequest = getGlobalInst(strXMLHttpRequest);
            isSupported = !!xmlHttpRequest;
        }
        catch (e) {
        }
        return isSupported;
    }
    function _getNamedValue(values, name) {
        if (values) {
            for (var i = 0; i < values[_DYN_LENGTH ]; i++) {
                var value = values[i];
                if (value[_DYN_NAME ]) {
                    if (value[_DYN_NAME ] === name) {
                        return value;
                    }
                }
            }
        }
        return {};
    }
    function findMetaTag(name) {
        var doc = getDocument();
        if (doc && name) {
            return _getNamedValue(doc.querySelectorAll("meta"), name).content;
        }
        return null;
    }
    function findNamedServerTiming(name) {
        var value;
        var perf = getPerformance();
        if (perf) {
            var navPerf = perf.getEntriesByType("navigation") || [];
            value = _getNamedValue((navPerf[_DYN_LENGTH ] > 0 ? navPerf[0] : {}).serverTiming, name).description;
        }
        return value;
    }
    function dispatchEvent(target, evnt) {
        if (target && target.dispatchEvent && evnt) {
            target.dispatchEvent(evnt);
            return true;
        }
        return false;
    }
    function createCustomDomEvent(eventName, details) {
        var event = null;
        var detail = { detail: details || null };
        if (isFunction(CustomEvent)) {
            event = new CustomEvent(eventName, detail);
        }
        else {
            var doc = getDocument();
            if (doc && doc.createEvent) {
                event = doc.createEvent("CustomEvent");
                event.initCustomEvent(eventName, true, true, detail);
            }
        }
        return event;
    }
    function sendCustomEvent(evtName, cfg, customDetails) {
        var global = getGlobal();
        if (global && global.CustomEvent) {
            try {
                var details = { cfg: cfg || null, customDetails: customDetails || null };
                return dispatchEvent(global, createCustomDomEvent(evtName, details));
            }
            catch (e) {
            }
        }
        return false;
    }

    var listenerFuncs = ["eventsSent", "eventsDiscarded", "eventsSendRequest", "perfEvent"];
    var _aiNamespace = null;
    var _debugListener;
    function _listenerProxyFunc(name, config) {
        return function () {
            var args = arguments;
            var dbgExt = getDebugExt(config);
            if (dbgExt) {
                var listener = dbgExt.listener;
                if (listener && listener[name]) {
                    listener[name][_DYN_APPLY ](listener, args);
                }
            }
        };
    }
    function _getExtensionNamespace() {
        var target = getGlobalInst("Microsoft");
        if (target) {
            _aiNamespace = target["ApplicationInsights"];
        }
        return _aiNamespace;
    }
    function getDebugExt(config) {
        var ns = _aiNamespace;
        if (!ns && config.disableDbgExt !== true) {
            ns = _aiNamespace || _getExtensionNamespace();
        }
        return ns ? ns["ChromeDbgExt"] : null;
    }
    function getDebugListener(config) {
        if (!_debugListener) {
            _debugListener = {};
            for (var lp = 0; lp < listenerFuncs[_DYN_LENGTH ]; lp++) {
                _debugListener[listenerFuncs[lp]] = _listenerProxyFunc(listenerFuncs[lp], config);
            }
        }
        return _debugListener;
    }

    var AiNonUserActionablePrefix = "AI (Internal): ";
    var AiUserActionablePrefix = "AI: ";
    var AIInternalMessagePrefix = "AITR_";
    function _sanitizeDiagnosticText(text) {
        if (text) {
            return "\"" + text[_DYN_REPLACE ](/\"/g, STR_EMPTY) + "\"";
        }
        return STR_EMPTY;
    }
    function _logToConsole(func, message) {
        var theConsole = getConsole();
        if (!!theConsole) {
            var logFunc = "log";
            if (theConsole[func]) {
                logFunc = func;
            }
            if (isFunction(theConsole[logFunc])) {
                theConsole[logFunc](message);
            }
        }
    }
    var _InternalLogMessage = /** @class */ (function () {
        function _InternalLogMessage(msgId, msg, isUserAct, properties) {
            if (isUserAct === void 0) { isUserAct = false; }
            var _self = this;
            _self[_DYN_MESSAGE_ID ] = msgId;
            _self[_DYN_MESSAGE ] =
                (isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +
                    msgId;
            var strProps = STR_EMPTY;
            if (hasJSON()) {
                strProps = getJSON().stringify(properties);
            }
            var diagnosticText = (msg ? " message:" + _sanitizeDiagnosticText(msg) : STR_EMPTY) +
                (properties ? " props:" + _sanitizeDiagnosticText(strProps) : STR_EMPTY);
            _self[_DYN_MESSAGE ] += diagnosticText;
        }
        _InternalLogMessage.dataType = "MessageData";
        return _InternalLogMessage;
    }());
    function safeGetLogger(core, config) {
        return (core || {})[_DYN_LOGGER ] || new DiagnosticLogger(config);
    }
    var DiagnosticLogger = /** @class */ (function () {
        function DiagnosticLogger(config) {
            this.identifier = "DiagnosticLogger";
            this.queue = [];
            var _messageCount = 0;
            var _messageLogged = {};
            var _loggingLevelConsole;
            var _loggingLevelTelemetry;
            var _maxInternalMessageLimit;
            var _enableDebug;
            dynamicProto(DiagnosticLogger, this, function (_self) {
                _setDefaultsFromConfig(config || {});
                _self.consoleLoggingLevel = function () { return _loggingLevelConsole; };
                _self.telemetryLoggingLevel = function () { return _loggingLevelTelemetry; };
                _self.maxInternalMessageLimit = function () { return _maxInternalMessageLimit; };
                _self[_DYN_ENABLE_DEBUG_EXCEPTI4 ] = function () { return _enableDebug; };
                _self.throwInternal = function (severity, msgId, msg, properties, isUserAct) {
                    if (isUserAct === void 0) { isUserAct = false; }
                    var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
                    if (_enableDebug) {
                        throw dumpObj(message);
                    }
                    else {
                        var logFunc = severity === 1  ? STR_ERROR_TO_CONSOLE : STR_WARN_TO_CONSOLE;
                        if (!isUndefined(message[_DYN_MESSAGE ])) {
                            if (isUserAct) {
                                var messageKey = +message[_DYN_MESSAGE_ID ];
                                if (!_messageLogged[messageKey] && _loggingLevelConsole >= severity) {
                                    _self[logFunc](message[_DYN_MESSAGE ]);
                                    _messageLogged[messageKey] = true;
                                }
                            }
                            else {
                                if (_loggingLevelConsole >= severity) {
                                    _self[logFunc](message[_DYN_MESSAGE ]);
                                }
                            }
                            _logInternalMessage(severity, message);
                        }
                        else {
                            _debugExtMsg("throw" + (severity === 1  ? "Critical" : "Warning"), message);
                        }
                    }
                };
                _self[STR_WARN_TO_CONSOLE ] = function (message) {
                    _logToConsole("warn", message);
                    _debugExtMsg("warning", message);
                };
                _self[STR_ERROR_TO_CONSOLE ] = function (message) {
                    _logToConsole("error", message);
                    _debugExtMsg("error", message);
                };
                _self.resetInternalMessageCount = function () {
                    _messageCount = 0;
                    _messageLogged = {};
                };
                _self[_DYN_LOG_INTERNAL_MESSAGE ] = _logInternalMessage;
                function _logInternalMessage(severity, message) {
                    if (_areInternalMessagesThrottled()) {
                        return;
                    }
                    var logMessage = true;
                    var messageKey = AIInternalMessagePrefix + message[_DYN_MESSAGE_ID ];
                    if (_messageLogged[messageKey]) {
                        logMessage = false;
                    }
                    else {
                        _messageLogged[messageKey] = true;
                    }
                    if (logMessage) {
                        if (severity <= _loggingLevelTelemetry) {
                            _self.queue[_DYN_PUSH ](message);
                            _messageCount++;
                            _debugExtMsg((severity === 1  ? "error" : "warn"), message);
                        }
                        if (_messageCount === _maxInternalMessageLimit) {
                            var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
                            var throttleMessage = new _InternalLogMessage(23 , throttleLimitMessage, false);
                            _self.queue[_DYN_PUSH ](throttleMessage);
                            if (severity === 1 ) {
                                _self[STR_ERROR_TO_CONSOLE ](throttleLimitMessage);
                            }
                            else {
                                _self[STR_WARN_TO_CONSOLE ](throttleLimitMessage);
                            }
                        }
                    }
                }
                function _setDefaultsFromConfig(config) {
                    _loggingLevelConsole = getCfgValue(config.loggingLevelConsole, 0);
                    _loggingLevelTelemetry = getCfgValue(config.loggingLevelTelemetry, 1);
                    _maxInternalMessageLimit = getCfgValue(config.maxMessageLimit, 25);
                    _enableDebug = getCfgValue(config.enableDebug, getCfgValue(config[_DYN_ENABLE_DEBUG_EXCEPTI4 ], false));
                }
                function _areInternalMessagesThrottled() {
                    return _messageCount >= _maxInternalMessageLimit;
                }
                function _debugExtMsg(name, data) {
                    var dbgExt = getDebugExt(config || {});
                    if (dbgExt && dbgExt[_DYN_DIAG_LOG ]) {
                        dbgExt[_DYN_DIAG_LOG ](name, data);
                    }
                }
            });
        }
        DiagnosticLogger.__ieDyn=1;
        return DiagnosticLogger;
    }());
    function _getLogger(logger) {
        return (logger || new DiagnosticLogger());
    }
    function _throwInternal(logger, severity, msgId, msg, properties, isUserAct) {
        if (isUserAct === void 0) { isUserAct = false; }
        _getLogger(logger).throwInternal(severity, msgId, msg, properties, isUserAct);
    }
    function _warnToConsole(logger, message) {
        _getLogger(logger)[STR_WARN_TO_CONSOLE ](message);
    }
    function _logInternalMessage(logger, severity, message) {
        _getLogger(logger)[_DYN_LOG_INTERNAL_MESSAGE ](severity, message);
    }

    var strExecutionContextKey = "ctx";
    var strParentContextKey = "ParentContextKey";
    var strChildrenContextKey = "ChildrenContextKey";
    var _defaultPerfManager = null;
    var PerfEvent = /** @class */ (function () {
        function PerfEvent(name, payloadDetails, isAsync) {
            var _self = this;
            var accessorDefined = false;
            _self.start = dateNow();
            _self[_DYN_NAME ] = name;
            _self[_DYN_IS_ASYNC ] = isAsync;
            _self[_DYN_IS_CHILD_EVT ] = function () { return false; };
            if (isFunction(payloadDetails)) {
                var theDetails_1;
                accessorDefined = objDefineAccessors(_self, "payload", function () {
                    if (!theDetails_1 && isFunction(payloadDetails)) {
                        theDetails_1 = payloadDetails();
                        payloadDetails = null;
                    }
                    return theDetails_1;
                });
            }
            _self[_DYN_GET_CTX ] = function (key) {
                if (key) {
                    if (key === PerfEvent[strParentContextKey] || key === PerfEvent[strChildrenContextKey]) {
                        return _self[key];
                    }
                    return (_self[strExecutionContextKey] || {})[key];
                }
                return null;
            };
            _self[_DYN_SET_CTX ] = function (key, value) {
                if (key) {
                    if (key === PerfEvent[strParentContextKey]) {
                        if (!_self[key]) {
                            _self[_DYN_IS_CHILD_EVT ] = function () { return true; };
                        }
                        _self[key] = value;
                    }
                    else if (key === PerfEvent[strChildrenContextKey]) {
                        _self[key] = value;
                    }
                    else {
                        var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};
                        ctx[key] = value;
                    }
                }
            };
            _self[_DYN_COMPLETE ] = function () {
                var childTime = 0;
                var childEvts = _self[_DYN_GET_CTX ](PerfEvent[strChildrenContextKey]);
                if (isArray(childEvts)) {
                    for (var lp = 0; lp < childEvts[_DYN_LENGTH ]; lp++) {
                        var childEvt = childEvts[lp];
                        if (childEvt) {
                            childTime += childEvt[_DYN_TIME ];
                        }
                    }
                }
                _self[_DYN_TIME ] = dateNow() - _self.start;
                _self.exTime = _self[_DYN_TIME ] - childTime;
                _self[_DYN_COMPLETE ] = function () { };
                if (!accessorDefined && isFunction(payloadDetails)) {
                    _self.payload = payloadDetails();
                }
            };
        }
        PerfEvent.ParentContextKey = "parent";
        PerfEvent.ChildrenContextKey = "childEvts";
        return PerfEvent;
    }());
    var PerfManager = /** @class */ (function () {
        function PerfManager(manager) {
            this.ctx = {};
            dynamicProto(PerfManager, this, function (_self) {
                _self.create = function (src, payloadDetails, isAsync) {
                    return new PerfEvent(src, payloadDetails, isAsync);
                };
                _self.fire = function (perfEvent) {
                    if (perfEvent) {
                        perfEvent[_DYN_COMPLETE ]();
                        if (manager && isFunction(manager[STR_PERF_EVENT ])) {
                            manager[STR_PERF_EVENT ](perfEvent);
                        }
                    }
                };
                _self[_DYN_SET_CTX ] = function (key, value) {
                    if (key) {
                        var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};
                        ctx[key] = value;
                    }
                };
                _self[_DYN_GET_CTX ] = function (key) {
                    return (_self[strExecutionContextKey] || {})[key];
                };
            });
        }
        PerfManager.__ieDyn=1;
        return PerfManager;
    }());
    var doPerfActiveKey = "CoreUtils.doPerf";
    function doPerf(mgrSource, getSource, func, details, isAsync) {
        if (mgrSource) {
            var perfMgr = mgrSource;
            if (perfMgr[STR_GET_PERF_MGR]) {
                perfMgr = perfMgr[STR_GET_PERF_MGR]();
            }
            if (perfMgr) {
                var perfEvt = void 0;
                var currentActive = perfMgr[_DYN_GET_CTX ](doPerfActiveKey);
                try {
                    perfEvt = perfMgr.create(getSource(), details, isAsync);
                    if (perfEvt) {
                        if (currentActive && perfEvt[_DYN_SET_CTX ]) {
                            perfEvt[_DYN_SET_CTX ](PerfEvent[strParentContextKey], currentActive);
                            if (currentActive[_DYN_GET_CTX ] && currentActive[_DYN_SET_CTX ]) {
                                var children = currentActive[_DYN_GET_CTX ](PerfEvent[strChildrenContextKey]);
                                if (!children) {
                                    children = [];
                                    currentActive[_DYN_SET_CTX ](PerfEvent[strChildrenContextKey], children);
                                }
                                children[_DYN_PUSH ](perfEvt);
                            }
                        }
                        perfMgr[_DYN_SET_CTX ](doPerfActiveKey, perfEvt);
                        return func(perfEvt);
                    }
                }
                catch (ex) {
                    if (perfEvt && perfEvt[_DYN_SET_CTX ]) {
                        perfEvt[_DYN_SET_CTX ]("exception", ex);
                    }
                }
                finally {
                    if (perfEvt) {
                        perfMgr.fire(perfEvt);
                    }
                    perfMgr[_DYN_SET_CTX ](doPerfActiveKey, currentActive);
                }
            }
        }
        return func();
    }
    function setGblPerfMgr(perfManager) {
        _defaultPerfManager = perfManager;
    }
    function getGblPerfMgr() {
        return _defaultPerfManager;
    }

    var UInt32Mask = 0x100000000;
    var MaxUInt32 = 0xffffffff;
    var _mwcSeeded = false;
    var _mwcW = 123456789;
    var _mwcZ = 987654321;
    function _mwcSeed(seedValue) {
        if (seedValue < 0) {
            seedValue >>>= 0;
        }
        _mwcW = (123456789 + seedValue) & MaxUInt32;
        _mwcZ = (987654321 - seedValue) & MaxUInt32;
        _mwcSeeded = true;
    }
    function _autoSeedMwc() {
        try {
            var now = dateNow() & 0x7fffffff;
            _mwcSeed(((Math.random() * UInt32Mask) ^ now) + now);
        }
        catch (e) {
        }
    }
    function randomValue(maxValue) {
        if (maxValue > 0) {
            return Math.floor((random32() / MaxUInt32) * (maxValue + 1)) >>> 0;
        }
        return 0;
    }
    function random32(signed) {
        var value = 0;
        var c = getCrypto() || getMsCrypto();
        if (c && c.getRandomValues) {
            value = c.getRandomValues(new Uint32Array(1))[0] & MaxUInt32;
        }
        if (value === 0 && isIE()) {
            if (!_mwcSeeded) {
                _autoSeedMwc();
            }
            value = mwcRandom32() & MaxUInt32;
        }
        if (value === 0) {
            value = Math.floor((UInt32Mask * Math.random()) | 0);
        }
        if (!signed) {
            value >>>= 0;
        }
        return value;
    }
    function mwcRandomSeed(value) {
        if (!value) {
            _autoSeedMwc();
        }
        else {
            _mwcSeed(value);
        }
    }
    function mwcRandom32(signed) {
        _mwcZ = (36969 * (_mwcZ & 0xFFFF) + (_mwcZ >> 16)) & MaxUInt32;
        _mwcW = (18000 * (_mwcW & 0xFFFF) + (_mwcW >> 16)) & MaxUInt32;
        var value = (((_mwcZ << 16) + (_mwcW & 0xFFFF)) >>> 0) & MaxUInt32 | 0;
        if (!signed) {
            value >>>= 0;
        }
        return value;
    }
    function newId(maxLength) {
        if (maxLength === void 0) { maxLength = 22; }
        var base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var number = random32() >>> 0;
        var chars = 0;
        var result = STR_EMPTY;
        while (result[_DYN_LENGTH ] < maxLength) {
            chars++;
            result += base64chars.charAt(number & 0x3F);
            number >>>= 6;
            if (chars === 5) {
                number = (((random32() << 2) & 0xFFFFFFFF) | (number & 0x03)) >>> 0;
                chars = 0;
            }
        }
        return result;
    }

    var _objDefineProperty = ObjDefineProperty;
    var version = '2.8.15';
    var instanceName = "." + newId(6);
    var _dataUid = 0;
    function _createAccessor(target, prop, value) {
        if (_objDefineProperty) {
            try {
                _objDefineProperty(target, prop, {
                    value: value,
                    enumerable: false,
                    configurable: true
                });
                return true;
            }
            catch (e) {
            }
        }
        return false;
    }
    function _canAcceptData(target) {
        return target[_DYN_NODE_TYPE ] === 1 || target[_DYN_NODE_TYPE ] === 9 || !(+target[_DYN_NODE_TYPE ]);
    }
    function _getCache(data, target) {
        var theCache = target[data.id];
        if (!theCache) {
            theCache = {};
            try {
                if (_canAcceptData(target)) {
                    if (!_createAccessor(target, data.id, theCache)) {
                        target[data.id] = theCache;
                    }
                }
            }
            catch (e) {
            }
        }
        return theCache;
    }
    function createUniqueNamespace(name, includeVersion) {
        if (includeVersion === void 0) { includeVersion = false; }
        return normalizeJsName(name + (_dataUid++) + (includeVersion ? "." + version : STR_EMPTY) + instanceName);
    }
    function createElmNodeData(name) {
        var data = {
            id: createUniqueNamespace("_aiData-" + (name || STR_EMPTY) + "." + version),
            accept: function (target) {
                return _canAcceptData(target);
            },
            get: function (target, name, defValue, addDefault) {
                var theCache = target[data.id];
                if (!theCache) {
                    if (addDefault) {
                        theCache = _getCache(data, target);
                        theCache[normalizeJsName(name)] = defValue;
                    }
                    return defValue;
                }
                return theCache[normalizeJsName(name)];
            },
            kill: function (target, name) {
                if (target && target[name]) {
                    try {
                        delete target[name];
                    }
                    catch (e) {
                    }
                }
            }
        };
        return data;
    }

    var strToGMTString = "toGMTString";
    var strToUTCString = "toUTCString";
    var strCookie = "cookie";
    var strExpires = "expires";
    var strEnabled = "enabled";
    var strIsCookieUseDisabled = "isCookieUseDisabled";
    var strDisableCookiesUsage = "disableCookiesUsage";
    var strConfigCookieMgr = "_ckMgr";
    var _supportsCookies = null;
    var _allowUaSameSite = null;
    var _parsedCookieValue = null;
    var _doc = getDocument();
    var _cookieCache = {};
    var _globalCookieConfig = {};
    function _gblCookieMgr(config, logger) {
        var inst = createCookieMgr[strConfigCookieMgr] || _globalCookieConfig[strConfigCookieMgr];
        if (!inst) {
            inst = createCookieMgr[strConfigCookieMgr] = createCookieMgr(config, logger);
            _globalCookieConfig[strConfigCookieMgr] = inst;
        }
        return inst;
    }
    function _isMgrEnabled(cookieMgr) {
        if (cookieMgr) {
            return cookieMgr.isEnabled();
        }
        return true;
    }
    function _createCookieMgrConfig(rootConfig) {
        var cookieMgrCfg = rootConfig[_DYN_COOKIE_CFG ] = rootConfig[_DYN_COOKIE_CFG ] || {};
        setValue(cookieMgrCfg, "domain", rootConfig.cookieDomain, isNotNullOrUndefined, isNullOrUndefined);
        setValue(cookieMgrCfg, "path", rootConfig.cookiePath || "/", null, isNullOrUndefined);
        if (isNullOrUndefined(cookieMgrCfg[strEnabled])) {
            var cookieEnabled = void 0;
            if (!isUndefined(rootConfig[strIsCookieUseDisabled])) {
                cookieEnabled = !rootConfig[strIsCookieUseDisabled];
            }
            if (!isUndefined(rootConfig[strDisableCookiesUsage])) {
                cookieEnabled = !rootConfig[strDisableCookiesUsage];
            }
            cookieMgrCfg[strEnabled] = cookieEnabled;
        }
        return cookieMgrCfg;
    }
    function _isIgnoredCookie(cookieMgrCfg, name) {
        if (name && cookieMgrCfg && isArray(cookieMgrCfg.ignoreCookies)) {
            return cookieMgrCfg.ignoreCookies[_DYN_INDEX_OF ](name) !== -1;
        }
        return false;
    }
    function _isBlockedCookie(cookieMgrCfg, name) {
        if (name && cookieMgrCfg && isArray(cookieMgrCfg.blockedCookies)) {
            if (cookieMgrCfg.blockedCookies[_DYN_INDEX_OF ](name) !== -1) {
                return true;
            }
        }
        return _isIgnoredCookie(cookieMgrCfg, name);
    }
    function safeGetCookieMgr(core, config) {
        var cookieMgr;
        if (core) {
            cookieMgr = core.getCookieMgr();
        }
        else if (config) {
            var cookieCfg = config[_DYN_COOKIE_CFG ];
            if (cookieCfg[strConfigCookieMgr]) {
                cookieMgr = cookieCfg[strConfigCookieMgr];
            }
            else {
                cookieMgr = createCookieMgr(config);
            }
        }
        if (!cookieMgr) {
            cookieMgr = _gblCookieMgr(config, (core || {})[_DYN_LOGGER ]);
        }
        return cookieMgr;
    }
    function createCookieMgr(rootConfig, logger) {
        var _a;
        var cookieMgrConfig = _createCookieMgrConfig(rootConfig || _globalCookieConfig);
        var _path = cookieMgrConfig.path || "/";
        var _domain = cookieMgrConfig.domain;
        var _enabled = cookieMgrConfig[strEnabled] !== false;
        var cookieMgr = (_a = {
                isEnabled: function () {
                    var enabled = _enabled && areCookiesSupported(logger);
                    var gblManager = _globalCookieConfig[strConfigCookieMgr];
                    if (enabled && gblManager && cookieMgr !== gblManager) {
                        enabled = _isMgrEnabled(gblManager);
                    }
                    return enabled;
                }
            },
            _a[_DYN_SET_ENABLED ] = function (value) {
                _enabled = value !== false;
            },
            _a.set = function (name, value, maxAgeSec, domain, path) {
                var result = false;
                if (_isMgrEnabled(cookieMgr) && !_isBlockedCookie(cookieMgrConfig, name)) {
                    var values = {};
                    var theValue = strTrim(value || STR_EMPTY);
                    var idx = theValue[_DYN_INDEX_OF ](";");
                    if (idx !== -1) {
                        theValue = strTrim(value[_DYN_SUBSTRING ](0, idx));
                        values = _extractParts(value[_DYN_SUBSTRING ](idx + 1));
                    }
                    setValue(values, "domain", domain || _domain, isTruthy, isUndefined);
                    if (!isNullOrUndefined(maxAgeSec)) {
                        var _isIE = isIE();
                        if (isUndefined(values[strExpires])) {
                            var nowMs = dateNow();
                            var expireMs = nowMs + (maxAgeSec * 1000);
                            if (expireMs > 0) {
                                var expiry = new Date();
                                expiry.setTime(expireMs);
                                setValue(values, strExpires, _formatDate(expiry, !_isIE ? strToUTCString : strToGMTString) || _formatDate(expiry, _isIE ? strToGMTString : strToUTCString) || STR_EMPTY, isTruthy);
                            }
                        }
                        if (!_isIE) {
                            setValue(values, "max-age", STR_EMPTY + maxAgeSec, null, isUndefined);
                        }
                    }
                    var location_1 = getLocation();
                    if (location_1 && location_1.protocol === "https:") {
                        setValue(values, "secure", null, null, isUndefined);
                        if (_allowUaSameSite === null) {
                            _allowUaSameSite = !uaDisallowsSameSiteNone((getNavigator() || {})[_DYN_USER_AGENT ]);
                        }
                        if (_allowUaSameSite) {
                            setValue(values, "SameSite", "None", null, isUndefined);
                        }
                    }
                    setValue(values, "path", path || _path, null, isUndefined);
                    var setCookieFn = cookieMgrConfig.setCookie || _setCookieValue;
                    setCookieFn(name, _formatCookieValue(theValue, values));
                    result = true;
                }
                return result;
            },
            _a.get = function (name) {
                var value = STR_EMPTY;
                if (_isMgrEnabled(cookieMgr) && !_isIgnoredCookie(cookieMgrConfig, name)) {
                    value = (cookieMgrConfig.getCookie || _getCookieValue)(name);
                }
                return value;
            },
            _a.del = function (name, path) {
                var result = false;
                if (_isMgrEnabled(cookieMgr)) {
                    result = cookieMgr.purge(name, path);
                }
                return result;
            },
            _a.purge = function (name, path) {
                var _a;
                var result = false;
                if (areCookiesSupported(logger)) {
                    var values = (_a = {},
                        _a["path"] = path ? path : "/",
                        _a[strExpires] = "Thu, 01 Jan 1970 00:00:01 GMT",
                        _a);
                    if (!isIE()) {
                        values["max-age"] = "0";
                    }
                    var delCookie = cookieMgrConfig.delCookie || _setCookieValue;
                    delCookie(name, _formatCookieValue(STR_EMPTY, values));
                    result = true;
                }
                return result;
            },
            _a);
        cookieMgr[strConfigCookieMgr] = cookieMgr;
        return cookieMgr;
    }
    function areCookiesSupported(logger) {
        if (_supportsCookies === null) {
            _supportsCookies = false;
            try {
                var doc = _doc || {};
                _supportsCookies = doc[strCookie] !== undefined;
            }
            catch (e) {
                _throwInternal(logger, 2 , 68 , "Cannot access document.cookie - " + getExceptionName(e), { exception: dumpObj(e) });
            }
        }
        return _supportsCookies;
    }
    function _extractParts(theValue) {
        var values = {};
        if (theValue && theValue[_DYN_LENGTH ]) {
            var parts = strTrim(theValue)[_DYN_SPLIT ](";");
            arrForEach(parts, function (thePart) {
                thePart = strTrim(thePart || STR_EMPTY);
                if (thePart) {
                    var idx = thePart[_DYN_INDEX_OF ]("=");
                    if (idx === -1) {
                        values[thePart] = null;
                    }
                    else {
                        values[strTrim(thePart[_DYN_SUBSTRING ](0, idx))] = strTrim(thePart[_DYN_SUBSTRING ](idx + 1));
                    }
                }
            });
        }
        return values;
    }
    function _formatDate(theDate, func) {
        if (isFunction(theDate[func])) {
            return theDate[func]();
        }
        return null;
    }
    function _formatCookieValue(value, values) {
        var cookieValue = value || STR_EMPTY;
        objForEachKey(values, function (name, theValue) {
            cookieValue += "; " + name + (!isNullOrUndefined(theValue) ? "=" + theValue : STR_EMPTY);
        });
        return cookieValue;
    }
    function _getCookieValue(name) {
        var cookieValue = STR_EMPTY;
        if (_doc) {
            var theCookie = _doc[strCookie] || STR_EMPTY;
            if (_parsedCookieValue !== theCookie) {
                _cookieCache = _extractParts(theCookie);
                _parsedCookieValue = theCookie;
            }
            cookieValue = strTrim(_cookieCache[name] || STR_EMPTY);
        }
        return cookieValue;
    }
    function _setCookieValue(name, cookieValue) {
        if (_doc) {
            _doc[strCookie] = name + "=" + cookieValue;
        }
    }
    function uaDisallowsSameSiteNone(userAgent) {
        if (!isString(userAgent)) {
            return false;
        }
        if (strContains(userAgent, "CPU iPhone OS 12") || strContains(userAgent, "iPad; CPU OS 12")) {
            return true;
        }
        if (strContains(userAgent, "Macintosh; Intel Mac OS X 10_14") && strContains(userAgent, "Version/") && strContains(userAgent, "Safari")) {
            return true;
        }
        if (strContains(userAgent, "Macintosh; Intel Mac OS X 10_14") && strEndsWith(userAgent, "AppleWebKit/605.1.15 (KHTML, like Gecko)")) {
            return true;
        }
        if (strContains(userAgent, "Chrome/5") || strContains(userAgent, "Chrome/6")) {
            return true;
        }
        if (strContains(userAgent, "UnrealEngine") && !strContains(userAgent, "Chrome")) {
            return true;
        }
        if (strContains(userAgent, "UCBrowser/12") || strContains(userAgent, "UCBrowser/11")) {
            return true;
        }
        return false;
    }

    var strOnPrefix = "on";
    var strAttachEvent = "attachEvent";
    var strAddEventHelper = "addEventListener";
    var strDetachEvent = "detachEvent";
    var strRemoveEventListener = "removeEventListener";
    var strEvents = "events";
    var strVisibilityChangeEvt = "visibilitychange";
    var strPageHide = "pagehide";
    var strPageShow = "pageshow";
    var strUnload = "unload";
    var strBeforeUnload = "beforeunload";
    var strPageHideNamespace = createUniqueNamespace("aiEvtPageHide");
    var strPageShowNamespace = createUniqueNamespace("aiEvtPageShow");
    var rRemoveEmptyNs = /\.[\.]+/g;
    var rRemoveTrailingEmptyNs = /[\.]+$/;
    var _guid = 1;
    var elmNodeData = createElmNodeData("events");
    var eventNamespace = /^([^.]*)(?:\.(.+)|)/;
    function _normalizeNamespace(name) {
        if (name && name[_DYN_REPLACE ]) {
            return name[_DYN_REPLACE ](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g, STR_EMPTY);
        }
        return name;
    }
    function _getEvtNamespace(eventName, evtNamespace) {
        var _a;
        if (evtNamespace) {
            var theNamespace_1 = STR_EMPTY;
            if (isArray(evtNamespace)) {
                theNamespace_1 = STR_EMPTY;
                arrForEach(evtNamespace, function (name) {
                    name = _normalizeNamespace(name);
                    if (name) {
                        if (name[0] !== ".") {
                            name = "." + name;
                        }
                        theNamespace_1 += name;
                    }
                });
            }
            else {
                theNamespace_1 = _normalizeNamespace(evtNamespace);
            }
            if (theNamespace_1) {
                if (theNamespace_1[0] !== ".") {
                    theNamespace_1 = "." + theNamespace_1;
                }
                eventName = (eventName || STR_EMPTY) + theNamespace_1;
            }
        }
        var parsedEvent = (eventNamespace.exec(eventName || STR_EMPTY) || []);
        return _a = {},
            _a[_DYN_TYPE ] = parsedEvent[1],
            _a.ns = ((parsedEvent[2] || STR_EMPTY).replace(rRemoveEmptyNs, ".").replace(rRemoveTrailingEmptyNs, STR_EMPTY)[_DYN_SPLIT ](".").sort()).join("."),
            _a;
    }
    function __getRegisteredEvents(target, eventName, evtNamespace) {
        var theEvents = [];
        var eventCache = elmNodeData.get(target, strEvents, {}, false);
        var evtName = _getEvtNamespace(eventName, evtNamespace);
        objForEachKey(eventCache, function (evtType, registeredEvents) {
            arrForEach(registeredEvents, function (value) {
                var _a;
                if (!evtName[_DYN_TYPE ] || evtName[_DYN_TYPE ] === value.evtName[_DYN_TYPE ]) {
                    if (!evtName.ns || evtName.ns === evtName.ns) {
                        theEvents[_DYN_PUSH ]((_a = {},
                            _a[_DYN_NAME ] = value.evtName[_DYN_TYPE ] + (value.evtName.ns ? "." + value.evtName.ns : STR_EMPTY),
                            _a.handler = value[_DYN_HANDLER ],
                            _a));
                    }
                }
            });
        });
        return theEvents;
    }
    function _getRegisteredEvents(target, evtName, addDefault) {
        if (addDefault === void 0) { addDefault = true; }
        var aiEvts = elmNodeData.get(target, strEvents, {}, addDefault);
        var registeredEvents = aiEvts[evtName];
        if (!registeredEvents) {
            registeredEvents = aiEvts[evtName] = [];
        }
        return registeredEvents;
    }
    function _doDetach(obj, evtName, handlerRef, useCapture) {
        if (obj && evtName && evtName[_DYN_TYPE ]) {
            if (obj[strRemoveEventListener]) {
                obj[strRemoveEventListener](evtName[_DYN_TYPE ], handlerRef, useCapture);
            }
            else if (obj[strDetachEvent]) {
                obj[strDetachEvent](strOnPrefix + evtName[_DYN_TYPE ], handlerRef);
            }
        }
    }
    function _doAttach(obj, evtName, handlerRef, useCapture) {
        var result = false;
        if (obj && evtName && evtName[_DYN_TYPE ] && handlerRef) {
            if (obj[strAddEventHelper]) {
                obj[strAddEventHelper](evtName[_DYN_TYPE ], handlerRef, useCapture);
                result = true;
            }
            else if (obj[strAttachEvent]) {
                obj[strAttachEvent](strOnPrefix + evtName[_DYN_TYPE ], handlerRef);
                result = true;
            }
        }
        return result;
    }
    function _doUnregister(target, events, evtName, unRegFn) {
        var idx = events[_DYN_LENGTH ];
        while (idx--) {
            var theEvent = events[idx];
            if (theEvent) {
                if (!evtName.ns || evtName.ns === theEvent.evtName.ns) {
                    if (!unRegFn || unRegFn(theEvent)) {
                        _doDetach(target, theEvent.evtName, theEvent[_DYN_HANDLER ], theEvent.capture);
                        events[_DYN_SPLICE ](idx, 1);
                    }
                }
            }
        }
    }
    function _unregisterEvents(target, evtName, unRegFn) {
        if (evtName[_DYN_TYPE ]) {
            _doUnregister(target, _getRegisteredEvents(target, evtName[_DYN_TYPE ]), evtName, unRegFn);
        }
        else {
            var eventCache = elmNodeData.get(target, strEvents, {});
            objForEachKey(eventCache, function (evtType, events) {
                _doUnregister(target, events, evtName, unRegFn);
            });
            if (objKeys(eventCache)[_DYN_LENGTH ] === 0) {
                elmNodeData.kill(target, strEvents);
            }
        }
    }
    function mergeEvtNamespace(theNamespace, namespaces) {
        var newNamespaces;
        if (namespaces) {
            if (isArray(namespaces)) {
                newNamespaces = [theNamespace].concat(namespaces);
            }
            else {
                newNamespaces = [theNamespace, namespaces];
            }
            newNamespaces = (_getEvtNamespace("xx", newNamespaces).ns)[_DYN_SPLIT ](".");
        }
        else {
            newNamespaces = theNamespace;
        }
        return newNamespaces;
    }
    function eventOn(target, eventName, handlerRef, evtNamespace, useCapture) {
        var _a;
        if (useCapture === void 0) { useCapture = false; }
        var result = false;
        if (target) {
            try {
                var evtName = _getEvtNamespace(eventName, evtNamespace);
                result = _doAttach(target, evtName, handlerRef, useCapture);
                if (result && elmNodeData.accept(target)) {
                    var registeredEvent = (_a = {
                            guid: _guid++,
                            evtName: evtName
                        },
                        _a[_DYN_HANDLER ] = handlerRef,
                        _a.capture = useCapture,
                        _a);
                    _getRegisteredEvents(target, evtName.type)[_DYN_PUSH ](registeredEvent);
                }
            }
            catch (e) {
            }
        }
        return result;
    }
    function eventOff(target, eventName, handlerRef, evtNamespace, useCapture) {
        if (useCapture === void 0) { useCapture = false; }
        if (target) {
            try {
                var evtName_1 = _getEvtNamespace(eventName, evtNamespace);
                var found_1 = false;
                _unregisterEvents(target, evtName_1, function (regEvent) {
                    if ((evtName_1.ns && !handlerRef) || regEvent[_DYN_HANDLER ] === handlerRef) {
                        found_1 = true;
                        return true;
                    }
                    return false;
                });
                if (!found_1) {
                    _doDetach(target, evtName_1, handlerRef, useCapture);
                }
            }
            catch (e) {
            }
        }
    }
    function attachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {
        if (useCapture === void 0) { useCapture = false; }
        return eventOn(obj, eventNameWithoutOn, handlerRef, null, useCapture);
    }
    function detachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {
        if (useCapture === void 0) { useCapture = false; }
        eventOff(obj, eventNameWithoutOn, handlerRef, null, useCapture);
    }
    function addEventHandler(eventName, callback, evtNamespace) {
        var result = false;
        var w = getWindow();
        if (w) {
            result = eventOn(w, eventName, callback, evtNamespace);
            result = eventOn(w["body"], eventName, callback, evtNamespace) || result;
        }
        var doc = getDocument();
        if (doc) {
            result = eventOn(doc, eventName, callback, evtNamespace) || result;
        }
        return result;
    }
    function removeEventHandler(eventName, callback, evtNamespace) {
        var w = getWindow();
        if (w) {
            eventOff(w, eventName, callback, evtNamespace);
            eventOff(w["body"], eventName, callback, evtNamespace);
        }
        var doc = getDocument();
        if (doc) {
            eventOff(doc, eventName, callback, evtNamespace);
        }
    }
    function _addEventListeners(events, listener, excludeEvents, evtNamespace) {
        var added = false;
        if (listener && events && events[_DYN_LENGTH ] > 0) {
            arrForEach(events, function (name) {
                if (name) {
                    if (!excludeEvents || arrIndexOf(excludeEvents, name) === -1) {
                        added = addEventHandler(name, listener, evtNamespace) || added;
                    }
                }
            });
        }
        return added;
    }
    function addEventListeners(events, listener, excludeEvents, evtNamespace) {
        var added = false;
        if (listener && events && isArray(events)) {
            added = _addEventListeners(events, listener, excludeEvents, evtNamespace);
            if (!added && excludeEvents && excludeEvents[_DYN_LENGTH ] > 0) {
                added = _addEventListeners(events, listener, null, evtNamespace);
            }
        }
        return added;
    }
    function removeEventListeners(events, listener, evtNamespace) {
        if (events && isArray(events)) {
            arrForEach(events, function (name) {
                if (name) {
                    removeEventHandler(name, listener, evtNamespace);
                }
            });
        }
    }
    function addPageUnloadEventListener(listener, excludeEvents, evtNamespace) {
        return addEventListeners([strBeforeUnload, strUnload, strPageHide], listener, excludeEvents, evtNamespace);
    }
    function removePageUnloadEventListener(listener, evtNamespace) {
        removeEventListeners([strBeforeUnload, strUnload, strPageHide], listener, evtNamespace);
    }
    function addPageHideEventListener(listener, excludeEvents, evtNamespace) {
        function _handlePageVisibility(evt) {
            var doc = getDocument();
            if (listener && doc && doc.visibilityState === "hidden") {
                listener(evt);
            }
        }
        var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);
        var pageUnloadAdded = _addEventListeners([strPageHide], listener, excludeEvents, newNamespaces);
        if (!excludeEvents || arrIndexOf(excludeEvents, strVisibilityChangeEvt) === -1) {
            pageUnloadAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageUnloadAdded;
        }
        if (!pageUnloadAdded && excludeEvents) {
            pageUnloadAdded = addPageHideEventListener(listener, null, evtNamespace);
        }
        return pageUnloadAdded;
    }
    function removePageHideEventListener(listener, evtNamespace) {
        var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);
        removeEventListeners([strPageHide], listener, newNamespaces);
        removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);
    }
    function addPageShowEventListener(listener, excludeEvents, evtNamespace) {
        function _handlePageVisibility(evt) {
            var doc = getDocument();
            if (listener && doc && doc.visibilityState === "visible") {
                listener(evt);
            }
        }
        var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);
        var pageShowAdded = _addEventListeners([strPageShow], listener, excludeEvents, newNamespaces);
        pageShowAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageShowAdded;
        if (!pageShowAdded && excludeEvents) {
            pageShowAdded = addPageShowEventListener(listener, null, evtNamespace);
        }
        return pageShowAdded;
    }
    function removePageShowEventListener(listener, evtNamespace) {
        var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);
        removeEventListeners([strPageShow], listener, newNamespaces);
        removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);
    }

    var _cookieMgrs = null;
    var _canUseCookies;
    var Undefined = strShimUndefined;
    function newGuid() {
        var uuid = generateW3CId();
        return uuid[_DYN_SUBSTRING ](0, 8) + "-" + uuid[_DYN_SUBSTRING ](8, 12) + "-" + uuid[_DYN_SUBSTRING ](12, 16) + "-" + uuid[_DYN_SUBSTRING ](16, 20) + "-" + uuid[_DYN_SUBSTRING ](20);
    }
    function perfNow() {
        var perf = getPerformance();
        if (perf && perf.now) {
            return perf.now();
        }
        return dateNow();
    }
    function generateW3CId() {
        var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
        var oct = STR_EMPTY, tmp;
        for (var a = 0; a < 4; a++) {
            tmp = random32();
            oct +=
                hexValues[tmp & 0xF] +
                    hexValues[tmp >> 4 & 0xF] +
                    hexValues[tmp >> 8 & 0xF] +
                    hexValues[tmp >> 12 & 0xF] +
                    hexValues[tmp >> 16 & 0xF] +
                    hexValues[tmp >> 20 & 0xF] +
                    hexValues[tmp >> 24 & 0xF] +
                    hexValues[tmp >> 28 & 0xF];
        }
        var clockSequenceHi = hexValues[8 + (random32() & 0x03) | 0];
        return oct[_DYN_SUBSTR ](0, 8) + oct[_DYN_SUBSTR ](9, 4) + "4" + oct[_DYN_SUBSTR ](13, 3) + clockSequenceHi + oct[_DYN_SUBSTR ](16, 3) + oct[_DYN_SUBSTR ](19, 12);
    }
    var CoreUtils = {
        _canUseCookies: undefined,
        isTypeof: isTypeof,
        isUndefined: isUndefined,
        isNullOrUndefined: isNullOrUndefined,
        hasOwnProperty: hasOwnProperty,
        isFunction: isFunction,
        isObject: isObject,
        isDate: isDate,
        isArray: isArray,
        isError: isError,
        isString: isString,
        isNumber: isNumber,
        isBoolean: isBoolean,
        toISOString: toISOString,
        arrForEach: arrForEach,
        arrIndexOf: arrIndexOf,
        arrMap: arrMap,
        arrReduce: arrReduce,
        strTrim: strTrim,
        objCreate: objCreateFn,
        objKeys: objKeys,
        objDefineAccessors: objDefineAccessors,
        addEventHandler: addEventHandler,
        dateNow: dateNow,
        isIE: isIE,
        disableCookies: disableCookies,
        newGuid: newGuid,
        perfNow: perfNow,
        newId: newId,
        randomValue: randomValue,
        random32: random32,
        mwcRandomSeed: mwcRandomSeed,
        mwcRandom32: mwcRandom32,
        generateW3CId: generateW3CId
    };
    var EventHelper = {
        Attach: attachEvent,
        AttachEvent: attachEvent,
        Detach: detachEvent,
        DetachEvent: detachEvent
    };
    function _legacyCookieMgr(config, logger) {
        var cookieMgr = _gblCookieMgr(config, logger);
        var legacyCanUseCookies = CoreUtils._canUseCookies;
        if (_cookieMgrs === null) {
            _cookieMgrs = [];
            _canUseCookies = legacyCanUseCookies;
            objDefineAccessors(CoreUtils, "_canUseCookies", function () {
                return _canUseCookies;
            }, function (value) {
                _canUseCookies = value;
                arrForEach(_cookieMgrs, function (mgr) {
                    mgr[_DYN_SET_ENABLED ](value);
                });
            });
        }
        if (arrIndexOf(_cookieMgrs, cookieMgr) === -1) {
            _cookieMgrs[_DYN_PUSH ](cookieMgr);
        }
        if (isBoolean(legacyCanUseCookies)) {
            cookieMgr[_DYN_SET_ENABLED ](legacyCanUseCookies);
        }
        if (isBoolean(_canUseCookies)) {
            cookieMgr[_DYN_SET_ENABLED ](_canUseCookies);
        }
        return cookieMgr;
    }
    function disableCookies() {
        _legacyCookieMgr()[_DYN_SET_ENABLED ](false);
    }
    function canUseCookies(logger) {
        return _legacyCookieMgr(null, logger).isEnabled();
    }
    function getCookie(logger, name) {
        return _legacyCookieMgr(null, logger).get(name);
    }
    function setCookie(logger, name, value, domain) {
        _legacyCookieMgr(null, logger).set(name, value, null, domain);
    }
    function deleteCookie(logger, name) {
        return _legacyCookieMgr(null, logger).del(name);
    }

    var TRACE_PARENT_REGEX = /^([\da-f]{2})-([\da-f]{32})-([\da-f]{16})-([\da-f]{2})(-[^\s]*)?$/;
    var DEFAULT_VERSION = "00";
    var INVALID_VERSION = "ff";
    var INVALID_TRACE_ID = "00000000000000000000000000000000";
    var INVALID_SPAN_ID = "0000000000000000";
    var SAMPLED_FLAG = 0x01;
    function _isValid(value, len, invalidValue) {
        if (value && value[_DYN_LENGTH ] === len && value !== invalidValue) {
            return !!value.match(/^[\da-f]*$/);
        }
        return false;
    }
    function _formatValue(value, len, defValue) {
        if (_isValid(value, len)) {
            return value;
        }
        return defValue;
    }
    function _formatFlags(value) {
        if (isNaN(value) || value < 0 || value > 255) {
            value = 0x01;
        }
        var result = value.toString(16);
        while (result[_DYN_LENGTH ] < 2) {
            result = "0" + result;
        }
        return result;
    }
    function createTraceParent(traceId, spanId, flags, version) {
        var _a;
        return _a = {},
            _a[_DYN_VERSION ] = _isValid(version, 2, INVALID_VERSION) ? version : DEFAULT_VERSION,
            _a[_DYN_TRACE_ID ] = isValidTraceId(traceId) ? traceId : generateW3CId(),
            _a.spanId = isValidSpanId(spanId) ? spanId : generateW3CId()[_DYN_SUBSTR ](0, 16),
            _a.traceFlags = flags >= 0 && flags <= 0xFF ? flags : 1,
            _a;
    }
    function parseTraceParent(value) {
        var _a;
        if (!value) {
            return null;
        }
        if (isArray(value)) {
            value = value[0] || "";
        }
        if (!value || !isString(value) || value[_DYN_LENGTH ] > 8192) {
            return null;
        }
        var match = TRACE_PARENT_REGEX.exec(strTrim(value));
        if (!match ||
            match[1] === INVALID_VERSION ||
            match[2] === INVALID_TRACE_ID ||
            match[3] === INVALID_SPAN_ID) {
            return null;
        }
        return _a = {},
            _a[_DYN_VERSION ] = match[1],
            _a[_DYN_TRACE_ID ] = match[2],
            _a[_DYN_SPAN_ID ] = match[3],
            _a[_DYN_TRACE_FLAGS ] = parseInt(match[4], 16),
            _a;
    }
    function isValidTraceId(value) {
        return _isValid(value, 32, INVALID_TRACE_ID);
    }
    function isValidSpanId(value) {
        return _isValid(value, 16, INVALID_SPAN_ID);
    }
    function isValidTraceParent(value) {
        if (!value ||
            !_isValid(value[_DYN_VERSION ], 2, INVALID_VERSION) ||
            !_isValid(value[_DYN_TRACE_ID ], 32, INVALID_TRACE_ID) ||
            !_isValid(value[_DYN_SPAN_ID ], 16, INVALID_SPAN_ID) ||
            !_isValid(_formatFlags(value[_DYN_TRACE_FLAGS ]), 2)) {
            return false;
        }
        return true;
    }
    function isSampledFlag(value) {
        if (isValidTraceParent(value)) {
            return (value[_DYN_TRACE_FLAGS ] & SAMPLED_FLAG) === SAMPLED_FLAG;
        }
        return false;
    }
    function formatTraceParent(value) {
        if (value) {
            var flags = _formatFlags(value[_DYN_TRACE_FLAGS ]);
            if (!_isValid(flags, 2)) {
                flags = "01";
            }
            var version = value[_DYN_VERSION ] || DEFAULT_VERSION;
            if (version !== "00" && version !== "ff") {
                version = DEFAULT_VERSION;
            }
            return "".concat(version, "-").concat(_formatValue(value.traceId, 32, INVALID_TRACE_ID), "-").concat(_formatValue(value.spanId, 16, INVALID_SPAN_ID), "-").concat(flags);
        }
        return "";
    }
    function findW3cTraceParent() {
        var name = "traceparent";
        var traceParent = parseTraceParent(findMetaTag(name));
        if (!traceParent) {
            traceParent = parseTraceParent(findNamedServerTiming(name));
        }
        return traceParent;
    }

    var pluginStateData = createElmNodeData("plugin");
    function _getPluginState(plugin) {
        return pluginStateData.get(plugin, "state", {}, true);
    }
    function initializePlugins(processContext, extensions) {
        var initPlugins = [];
        var lastPlugin = null;
        var proxy = processContext[_DYN_GET_NEXT ]();
        var pluginState;
        while (proxy) {
            var thePlugin = proxy[_DYN_GET_PLUGIN ]();
            if (thePlugin) {
                if (lastPlugin &&
                    isFunction(lastPlugin[_DYN_SET_NEXT_PLUGIN ]) &&
                    isFunction(thePlugin[STR_PROCESS_TELEMETRY ])) {
                    lastPlugin[_DYN_SET_NEXT_PLUGIN ](thePlugin);
                }
                var isInitialized = false;
                if (isFunction(thePlugin[_DYN_IS_INITIALIZED ])) {
                    isInitialized = thePlugin[_DYN_IS_INITIALIZED ]();
                }
                else {
                    pluginState = _getPluginState(thePlugin);
                    isInitialized = pluginState[_DYN_IS_INITIALIZED ];
                }
                if (!isInitialized) {
                    initPlugins[_DYN_PUSH ](thePlugin);
                }
                lastPlugin = thePlugin;
                proxy = proxy[_DYN_GET_NEXT ]();
            }
        }
        arrForEach(initPlugins, function (thePlugin) {
            var core = processContext[STR_CORE]();
            thePlugin[_DYN_INITIALIZE ](processContext.getCfg(), core, extensions, processContext[_DYN_GET_NEXT ]());
            pluginState = _getPluginState(thePlugin);
            if (!thePlugin[STR_CORE] && !pluginState[STR_CORE]) {
                pluginState[STR_CORE] = core;
            }
            pluginState[_DYN_IS_INITIALIZED ] = true;
            delete pluginState[_DYN_TEARDOWN ];
        });
    }
    function sortPlugins(plugins) {
        return plugins.sort(function (extA, extB) {
            var result = 0;
            if (extB) {
                var bHasProcess = isFunction(extB[STR_PROCESS_TELEMETRY]);
                if (isFunction(extA[STR_PROCESS_TELEMETRY])) {
                    result = bHasProcess ? extA[STR_PRIORITY] - extB[STR_PRIORITY] : 1;
                }
                else if (bHasProcess) {
                    result = -1;
                }
            }
            else {
                result = extA ? 1 : -1;
            }
            return result;
        });
    }
    function unloadComponents(components, unloadCtx, unloadState, asyncCallback) {
        var idx = 0;
        function _doUnload() {
            while (idx < components[_DYN_LENGTH ]) {
                var component = components[idx++];
                if (component) {
                    var func = component._doUnload || component[_DYN__DO_TEARDOWN ];
                    if (isFunction(func)) {
                        if (func[_DYN_CALL ](component, unloadCtx, unloadState, _doUnload) === true) {
                            return true;
                        }
                    }
                }
            }
        }
        return _doUnload();
    }
    function createDistributedTraceContext(parentCtx) {
        var trace = {};
        return {
            getName: function () {
                return trace[_DYN_NAME ];
            },
            setName: function (newValue) {
                parentCtx && parentCtx.setName(newValue);
                trace[_DYN_NAME ] = newValue;
            },
            getTraceId: function () {
                return trace[_DYN_TRACE_ID ];
            },
            setTraceId: function (newValue) {
                parentCtx && parentCtx.setTraceId(newValue);
                if (isValidTraceId(newValue)) {
                    trace[_DYN_TRACE_ID ] = newValue;
                }
            },
            getSpanId: function () {
                return trace[_DYN_SPAN_ID ];
            },
            setSpanId: function (newValue) {
                parentCtx && parentCtx.setSpanId(newValue);
                if (isValidSpanId(newValue)) {
                    trace[_DYN_SPAN_ID ] = newValue;
                }
            },
            getTraceFlags: function () {
                return trace[_DYN_TRACE_FLAGS ];
            },
            setTraceFlags: function (newTraceFlags) {
                parentCtx && parentCtx.setTraceFlags(newTraceFlags);
                trace[_DYN_TRACE_FLAGS ] = newTraceFlags;
            }
        };
    }

    var strTelemetryPluginChain = "TelemetryPluginChain";
    var strHasRunFlags = "_hasRun";
    var strGetTelCtx = "_getTelCtx";
    var _chainId = 0;
    function _getNextProxyStart(proxy, core, startAt) {
        while (proxy) {
            if (proxy[_DYN_GET_PLUGIN ]() === startAt) {
                return proxy;
            }
            proxy = proxy[_DYN_GET_NEXT ]();
        }
        return createTelemetryProxyChain([startAt], core[_DYN_CONFIG ] || {}, core);
    }
    function _createInternalContext(telemetryChain, config, core, startAt) {
        var _nextProxy = null;
        var _onComplete = [];
        if (startAt !== null) {
            _nextProxy = startAt ? _getNextProxyStart(telemetryChain, core, startAt) : telemetryChain;
        }
        var context = {
            _next: _moveNext,
            ctx: {
                core: function () {
                    return core;
                },
                diagLog: function () {
                    return safeGetLogger(core, config);
                },
                getCfg: function () {
                    return config;
                },
                getExtCfg: _getExtCfg,
                getConfig: _getConfig,
                hasNext: function () {
                    return !!_nextProxy;
                },
                getNext: function () {
                    return _nextProxy;
                },
                setNext: function (nextPlugin) {
                    _nextProxy = nextPlugin;
                },
                iterate: _iterateChain,
                onComplete: _addOnComplete
            }
        };
        function _addOnComplete(onComplete, that) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            if (onComplete) {
                _onComplete[_DYN_PUSH ]({
                    func: onComplete,
                    self: !isUndefined(that) ? that : context.ctx,
                    args: args
                });
            }
        }
        function _moveNext() {
            var nextProxy = _nextProxy;
            _nextProxy = nextProxy ? nextProxy[_DYN_GET_NEXT ]() : null;
            if (!nextProxy) {
                var onComplete = _onComplete;
                if (onComplete && onComplete[_DYN_LENGTH ] > 0) {
                    arrForEach(onComplete, function (completeDetails) {
                        try {
                            completeDetails.func[_DYN_CALL ](completeDetails.self, completeDetails.args);
                        }
                        catch (e) {
                            _throwInternal(core[_DYN_LOGGER ], 2 , 73 , "Unexpected Exception during onComplete - " + dumpObj(e));
                        }
                    });
                    _onComplete = [];
                }
            }
            return nextProxy;
        }
        function _getExtCfg(identifier, defaultValue, mergeDefault) {
            if (defaultValue === void 0) { defaultValue = {}; }
            if (mergeDefault === void 0) { mergeDefault = 0 ; }
            var theConfig;
            if (config) {
                var extConfig = config[STR_EXTENSION_CONFIG ];
                if (extConfig && identifier) {
                    theConfig = extConfig[identifier];
                }
            }
            if (!theConfig) {
                theConfig = defaultValue;
            }
            else if (isObject(defaultValue)) {
                if (mergeDefault !== 0 ) {
                    var newConfig_1 = objExtend(true, defaultValue, theConfig);
                    if (config && mergeDefault === 2 ) {
                        objForEachKey(defaultValue, function (field) {
                            if (isNullOrUndefined(newConfig_1[field])) {
                                var cfgValue = config[field];
                                if (!isNullOrUndefined(cfgValue)) {
                                    newConfig_1[field] = cfgValue;
                                }
                            }
                        });
                    }
                    theConfig = newConfig_1;
                }
            }
            return theConfig;
        }
        function _getConfig(identifier, field, defaultValue) {
            if (defaultValue === void 0) { defaultValue = false; }
            var theValue;
            var extConfig = _getExtCfg(identifier, null);
            if (extConfig && !isNullOrUndefined(extConfig[field])) {
                theValue = extConfig[field];
            }
            else if (config && !isNullOrUndefined(config[field])) {
                theValue = config[field];
            }
            return !isNullOrUndefined(theValue) ? theValue : defaultValue;
        }
        function _iterateChain(cb) {
            var nextPlugin;
            while (!!(nextPlugin = context._next())) {
                var plugin = nextPlugin[_DYN_GET_PLUGIN ]();
                if (plugin) {
                    cb(plugin);
                }
            }
        }
        return context;
    }
    function createProcessTelemetryContext(telemetryChain, config, core, startAt) {
        var internalContext = _createInternalContext(telemetryChain, config, core, startAt);
        var context = internalContext.ctx;
        function _processNext(env) {
            var nextPlugin = internalContext._next();
            nextPlugin && nextPlugin[STR_PROCESS_TELEMETRY ](env, context);
            return !nextPlugin;
        }
        function _createNew(plugins, startAt) {
            if (plugins === void 0) { plugins = null; }
            if (isArray(plugins)) {
                plugins = createTelemetryProxyChain(plugins, config, core, startAt);
            }
            return createProcessTelemetryContext(plugins || context[_DYN_GET_NEXT ](), config, core, startAt);
        }
        context[_DYN_PROCESS_NEXT ] = _processNext;
        context[_DYN_CREATE_NEW ] = _createNew;
        return context;
    }
    function createProcessTelemetryUnloadContext(telemetryChain, core, startAt) {
        var config = core[_DYN_CONFIG ] || {};
        var internalContext = _createInternalContext(telemetryChain, config, core, startAt);
        var context = internalContext.ctx;
        function _processNext(unloadState) {
            var nextPlugin = internalContext._next();
            nextPlugin && nextPlugin.unload(context, unloadState);
            return !nextPlugin;
        }
        function _createNew(plugins, startAt) {
            if (plugins === void 0) { plugins = null; }
            if (isArray(plugins)) {
                plugins = createTelemetryProxyChain(plugins, config, core, startAt);
            }
            return createProcessTelemetryUnloadContext(plugins || context[_DYN_GET_NEXT ](), core, startAt);
        }
        context[_DYN_PROCESS_NEXT ] = _processNext;
        context[_DYN_CREATE_NEW ] = _createNew;
        return context;
    }
    function createProcessTelemetryUpdateContext(telemetryChain, core, startAt) {
        var config = core[_DYN_CONFIG ] || {};
        var internalContext = _createInternalContext(telemetryChain, config, core, startAt);
        var context = internalContext.ctx;
        function _processNext(updateState) {
            return context.iterate(function (plugin) {
                if (isFunction(plugin[_DYN_UPDATE ])) {
                    plugin[_DYN_UPDATE ](context, updateState);
                }
            });
        }
        function _createNew(plugins, startAt) {
            if (plugins === void 0) { plugins = null; }
            if (isArray(plugins)) {
                plugins = createTelemetryProxyChain(plugins, config, core, startAt);
            }
            return createProcessTelemetryUpdateContext(plugins || context[_DYN_GET_NEXT ](), core, startAt);
        }
        context[_DYN_PROCESS_NEXT ] = _processNext;
        context[_DYN_CREATE_NEW ] = _createNew;
        return context;
    }
    function createTelemetryProxyChain(plugins, config, core, startAt) {
        var firstProxy = null;
        var add = startAt ? false : true;
        if (isArray(plugins) && plugins[_DYN_LENGTH ] > 0) {
            var lastProxy_1 = null;
            arrForEach(plugins, function (thePlugin) {
                if (!add && startAt === thePlugin) {
                    add = true;
                }
                if (add && thePlugin && isFunction(thePlugin[STR_PROCESS_TELEMETRY ])) {
                    var newProxy = createTelemetryPluginProxy(thePlugin, config, core);
                    if (!firstProxy) {
                        firstProxy = newProxy;
                    }
                    if (lastProxy_1) {
                        lastProxy_1._setNext(newProxy);
                    }
                    lastProxy_1 = newProxy;
                }
            });
        }
        if (startAt && !firstProxy) {
            return createTelemetryProxyChain([startAt], config, core);
        }
        return firstProxy;
    }
    function createTelemetryPluginProxy(plugin, config, core) {
        var nextProxy = null;
        var hasProcessTelemetry = isFunction(plugin[STR_PROCESS_TELEMETRY ]);
        var hasSetNext = isFunction(plugin[_DYN_SET_NEXT_PLUGIN ]);
        var chainId;
        if (plugin) {
            chainId = plugin[_DYN_IDENTIFIER ] + "-" + plugin[STR_PRIORITY ] + "-" + _chainId++;
        }
        else {
            chainId = "Unknown-0-" + _chainId++;
        }
        var proxyChain = {
            getPlugin: function () {
                return plugin;
            },
            getNext: function () {
                return nextProxy;
            },
            processTelemetry: _processTelemetry,
            unload: _unloadPlugin,
            update: _updatePlugin,
            _id: chainId,
            _setNext: function (nextPlugin) {
                nextProxy = nextPlugin;
            }
        };
        function _getTelCtx() {
            var itemCtx;
            if (plugin && isFunction(plugin[strGetTelCtx])) {
                itemCtx = plugin[strGetTelCtx]();
            }
            if (!itemCtx) {
                itemCtx = createProcessTelemetryContext(proxyChain, config, core);
            }
            return itemCtx;
        }
        function _processChain(itemCtx, processPluginFn, name, details, isAsync) {
            var hasRun = false;
            var identifier = plugin ? plugin[_DYN_IDENTIFIER ] : strTelemetryPluginChain;
            var hasRunContext = itemCtx[strHasRunFlags];
            if (!hasRunContext) {
                hasRunContext = itemCtx[strHasRunFlags] = {};
            }
            itemCtx.setNext(nextProxy);
            if (plugin) {
                doPerf(itemCtx[STR_CORE ](), function () { return identifier + ":" + name; }, function () {
                    hasRunContext[chainId] = true;
                    try {
                        var nextId = nextProxy ? nextProxy._id : STR_EMPTY;
                        if (nextId) {
                            hasRunContext[nextId] = false;
                        }
                        hasRun = processPluginFn(itemCtx);
                    }
                    catch (error) {
                        var hasNextRun = nextProxy ? hasRunContext[nextProxy._id] : true;
                        if (hasNextRun) {
                            hasRun = true;
                        }
                        if (!nextProxy || !hasNextRun) {
                            _throwInternal(itemCtx[_DYN_DIAG_LOG ](), 1 , 73 , "Plugin [" + identifier + "] failed during " + name + " - " + dumpObj(error) + ", run flags: " + dumpObj(hasRunContext));
                        }
                    }
                }, details, isAsync);
            }
            return hasRun;
        }
        function _processTelemetry(env, itemCtx) {
            itemCtx = itemCtx || _getTelCtx();
            function _callProcessTelemetry(itemCtx) {
                if (!plugin || !hasProcessTelemetry) {
                    return false;
                }
                var pluginState = _getPluginState(plugin);
                if (pluginState[_DYN_TEARDOWN ] || pluginState[STR_DISABLED]) {
                    return false;
                }
                if (hasSetNext) {
                    plugin[_DYN_SET_NEXT_PLUGIN ](nextProxy);
                }
                plugin[STR_PROCESS_TELEMETRY ](env, itemCtx);
                return true;
            }
            if (!_processChain(itemCtx, _callProcessTelemetry, "processTelemetry", function () { return ({ item: env }); }, !(env.sync))) {
                itemCtx[_DYN_PROCESS_NEXT ](env);
            }
        }
        function _unloadPlugin(unloadCtx, unloadState) {
            function _callTeardown() {
                var hasRun = false;
                if (plugin) {
                    var pluginState = _getPluginState(plugin);
                    var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE ];
                    if (plugin && (!pluginCore || pluginCore === unloadCtx.core()) && !pluginState[_DYN_TEARDOWN ]) {
                        pluginState[STR_CORE ] = null;
                        pluginState[_DYN_TEARDOWN ] = true;
                        pluginState[_DYN_IS_INITIALIZED ] = false;
                        if (plugin[_DYN_TEARDOWN ] && plugin[_DYN_TEARDOWN ](unloadCtx, unloadState) === true) {
                            hasRun = true;
                        }
                    }
                }
                return hasRun;
            }
            if (!_processChain(unloadCtx, _callTeardown, "unload", function () { }, unloadState[_DYN_IS_ASYNC ])) {
                unloadCtx[_DYN_PROCESS_NEXT ](unloadState);
            }
        }
        function _updatePlugin(updateCtx, updateState) {
            function _callUpdate() {
                var hasRun = false;
                if (plugin) {
                    var pluginState = _getPluginState(plugin);
                    var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE ];
                    if (plugin && (!pluginCore || pluginCore === updateCtx.core()) && !pluginState[_DYN_TEARDOWN ]) {
                        if (plugin[_DYN_UPDATE ] && plugin[_DYN_UPDATE ](updateCtx, updateState) === true) {
                            hasRun = true;
                        }
                    }
                }
                return hasRun;
            }
            if (!_processChain(updateCtx, _callUpdate, "update", function () { }, false)) {
                updateCtx[_DYN_PROCESS_NEXT ](updateState);
            }
        }
        return objFreeze(proxyChain);
    }
    var ProcessTelemetryContext = /** @class */ (function () {
        function ProcessTelemetryContext(pluginChain, config, core, startAt) {
            var _self = this;
            var context = createProcessTelemetryContext(pluginChain, config, core, startAt);
            proxyFunctions(_self, context, objKeys(context));
        }
        return ProcessTelemetryContext;
    }());

    var ChannelControllerPriority = 500;
    var ChannelValidationMessage = "Channel has invalid priority - ";
    function _addChannelQueue(channelQueue, queue, core) {
        if (queue && isArray(queue) && queue[_DYN_LENGTH ] > 0) {
            queue = queue.sort(function (a, b) {
                return a[STR_PRIORITY ] - b[STR_PRIORITY ];
            });
            arrForEach(queue, function (queueItem) {
                if (queueItem[STR_PRIORITY ] < ChannelControllerPriority) {
                    throwError(ChannelValidationMessage + queueItem[_DYN_IDENTIFIER ]);
                }
            });
            channelQueue[_DYN_PUSH ]({
                queue: objFreeze(queue),
                chain: createTelemetryProxyChain(queue, core[_DYN_CONFIG ], core)
            });
        }
    }
    function createChannelControllerPlugin(channelQueue, core) {
        function _getTelCtx() {
            return createProcessTelemetryContext(null, core[_DYN_CONFIG ], core, null);
        }
        function _processChannelQueue(theChannels, itemCtx, processFn, onComplete) {
            var waiting = theChannels ? (theChannels[_DYN_LENGTH ] + 1) : 1;
            function _runChainOnComplete() {
                waiting--;
                if (waiting === 0) {
                    onComplete && onComplete();
                    onComplete = null;
                }
            }
            if (waiting > 0) {
                arrForEach(theChannels, function (channels) {
                    if (channels && channels.queue[_DYN_LENGTH ] > 0) {
                        var channelChain = channels.chain;
                        var chainCtx = itemCtx[_DYN_CREATE_NEW ](channelChain);
                        chainCtx[_DYN_ON_COMPLETE ](_runChainOnComplete);
                        processFn(chainCtx);
                    }
                    else {
                        waiting--;
                    }
                });
            }
            _runChainOnComplete();
        }
        function _doUpdate(updateCtx, updateState) {
            var theUpdateState = updateState || {
                reason: 0
            };
            _processChannelQueue(channelQueue, updateCtx, function (chainCtx) {
                chainCtx[_DYN_PROCESS_NEXT ](theUpdateState);
            }, function () {
                updateCtx[_DYN_PROCESS_NEXT ](theUpdateState);
            });
            return true;
        }
        function _doTeardown(unloadCtx, unloadState) {
            var theUnloadState = unloadState || {
                reason: 0 ,
                isAsync: false
            };
            _processChannelQueue(channelQueue, unloadCtx, function (chainCtx) {
                chainCtx[_DYN_PROCESS_NEXT ](theUnloadState);
            }, function () {
                unloadCtx[_DYN_PROCESS_NEXT ](theUnloadState);
                isInitialized = false;
            });
            return true;
        }
        function _getChannel(pluginIdentifier) {
            var thePlugin = null;
            if (channelQueue && channelQueue[_DYN_LENGTH ] > 0) {
                arrForEach(channelQueue, function (channels) {
                    if (channels && channels.queue[_DYN_LENGTH ] > 0) {
                        arrForEach(channels.queue, function (ext) {
                            if (ext[_DYN_IDENTIFIER ] === pluginIdentifier) {
                                thePlugin = ext;
                                return -1;
                            }
                        });
                        if (thePlugin) {
                            return -1;
                        }
                    }
                });
            }
            return thePlugin;
        }
        var isInitialized = false;
        var channelController = {
            identifier: "ChannelControllerPlugin",
            priority: ChannelControllerPriority,
            initialize: function (config, core, extensions, pluginChain) {
                isInitialized = true;
                arrForEach(channelQueue, function (channels) {
                    if (channels && channels.queue[_DYN_LENGTH ] > 0) {
                        initializePlugins(createProcessTelemetryContext(channels.chain, config, core), extensions);
                    }
                });
            },
            isInitialized: function () {
                return isInitialized;
            },
            processTelemetry: function (item, itemCtx) {
                _processChannelQueue(channelQueue, itemCtx || _getTelCtx(), function (chainCtx) {
                    chainCtx[_DYN_PROCESS_NEXT ](item);
                }, function () {
                    itemCtx[_DYN_PROCESS_NEXT ](item);
                });
            },
            update: _doUpdate,
            pause: function () {
                _processChannelQueue(channelQueue, _getTelCtx(), function (chainCtx) {
                    chainCtx.iterate(function (plugin) {
                        plugin.pause && plugin.pause();
                    });
                }, null);
            },
            resume: function () {
                _processChannelQueue(channelQueue, _getTelCtx(), function (chainCtx) {
                    chainCtx.iterate(function (plugin) {
                        plugin.resume && plugin.resume();
                    });
                }, null);
            },
            teardown: _doTeardown,
            getChannel: _getChannel,
            flush: function (isAsync, callBack, sendReason, cbTimeout) {
                var waiting = 1;
                var doneIterating = false;
                var cbTimer = null;
                cbTimeout = cbTimeout || 5000;
                function doCallback() {
                    waiting--;
                    if (doneIterating && waiting === 0) {
                        if (cbTimer) {
                            clearTimeout(cbTimer);
                            cbTimer = null;
                        }
                        callBack && callBack(doneIterating);
                        callBack = null;
                    }
                }
                _processChannelQueue(channelQueue, _getTelCtx(), function (chainCtx) {
                    chainCtx.iterate(function (plugin) {
                        if (plugin[_DYN_FLUSH ]) {
                            waiting++;
                            var handled_1 = false;
                            if (!plugin[_DYN_FLUSH ](isAsync, function () {
                                handled_1 = true;
                                doCallback();
                            }, sendReason)) {
                                if (!handled_1) {
                                    if (isAsync && cbTimer == null) {
                                        cbTimer = setTimeout(function () {
                                            cbTimer = null;
                                            doCallback();
                                        }, cbTimeout);
                                    }
                                    else {
                                        doCallback();
                                    }
                                }
                            }
                        }
                    });
                }, function () {
                    doneIterating = true;
                    doCallback();
                });
                return true;
            },
            _setQueue: function (queue) {
                channelQueue = queue;
            }
        };
        return channelController;
    }
    function createChannelQueues(channels, extensions, core) {
        var channelQueue = [];
        if (channels) {
            arrForEach(channels, function (queue) { return _addChannelQueue(channelQueue, queue, core); });
        }
        if (extensions) {
            var extensionQueue_1 = [];
            arrForEach(extensions, function (plugin) {
                if (plugin[STR_PRIORITY ] > ChannelControllerPriority) {
                    extensionQueue_1[_DYN_PUSH ](plugin);
                }
            });
            _addChannelQueue(channelQueue, extensionQueue_1, core);
        }
        return channelQueue;
    }

    function createUnloadHandlerContainer() {
        var handlers = [];
        function _addHandler(handler) {
            if (handler) {
                handlers[_DYN_PUSH ](handler);
            }
        }
        function _runHandlers(unloadCtx, unloadState) {
            arrForEach(handlers, function (handler) {
                try {
                    handler(unloadCtx, unloadState);
                }
                catch (e) {
                    _throwInternal(unloadCtx[_DYN_DIAG_LOG ](), 2 , 73 , "Unexpected error calling unload handler - " + dumpObj(e));
                }
            });
            handlers = [];
        }
        return {
            add: _addHandler,
            run: _runHandlers
        };
    }

    var strGetPlugin = "getPlugin";
    var BaseTelemetryPlugin = /** @class */ (function () {
        function BaseTelemetryPlugin() {
            var _self = this;
            var _isinitialized;
            var _rootCtx;
            var _nextPlugin;
            var _unloadHandlerContainer;
            var _hooks;
            _initDefaults();
            dynamicProto(BaseTelemetryPlugin, _self, function (_self) {
                _self[_DYN_INITIALIZE ] = function (config, core, extensions, pluginChain) {
                    _setDefaults(config, core, pluginChain);
                    _isinitialized = true;
                };
                _self[_DYN_TEARDOWN ] = function (unloadCtx, unloadState) {
                    var _a;
                    var core = _self[STR_CORE ];
                    if (!core || (unloadCtx && core !== unloadCtx[STR_CORE ]())) {
                        return;
                    }
                    var result;
                    var unloadDone = false;
                    var theUnloadCtx = unloadCtx || createProcessTelemetryUnloadContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);
                    var theUnloadState = unloadState || (_a = {
                            reason: 0
                        },
                        _a[_DYN_IS_ASYNC ] = false,
                        _a);
                    function _unloadCallback() {
                        if (!unloadDone) {
                            unloadDone = true;
                            _unloadHandlerContainer.run(theUnloadCtx, unloadState);
                            var oldHooks = _hooks;
                            _hooks = [];
                            arrForEach(oldHooks, function (fn) {
                                fn.rm();
                            });
                            if (result === true) {
                                theUnloadCtx[_DYN_PROCESS_NEXT ](theUnloadState);
                            }
                            _initDefaults();
                        }
                    }
                    if (!_self[_DYN__DO_TEARDOWN ] || _self[_DYN__DO_TEARDOWN ](theUnloadCtx, theUnloadState, _unloadCallback) !== true) {
                        _unloadCallback();
                    }
                    else {
                        result = true;
                    }
                    return result;
                };
                _self[_DYN_UPDATE ] = function (updateCtx, updateState) {
                    var core = _self[STR_CORE ];
                    if (!core || (updateCtx && core !== updateCtx[STR_CORE ]())) {
                        return;
                    }
                    var result;
                    var updateDone = false;
                    var theUpdateCtx = updateCtx || createProcessTelemetryUpdateContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);
                    var theUpdateState = updateState || {
                        reason: 0
                    };
                    function _updateCallback() {
                        if (!updateDone) {
                            updateDone = true;
                            _setDefaults(theUpdateCtx.getCfg(), theUpdateCtx.core(), theUpdateCtx[_DYN_GET_NEXT ]());
                        }
                    }
                    if (!_self._doUpdate || _self._doUpdate(theUpdateCtx, theUpdateState, _updateCallback) !== true) {
                        _updateCallback();
                    }
                    else {
                        result = true;
                    }
                    return result;
                };
                _self._addHook = function (hooks) {
                    if (hooks) {
                        if (isArray(hooks)) {
                            _hooks = _hooks.concat(hooks);
                        }
                        else {
                            _hooks[_DYN_PUSH ](hooks);
                        }
                    }
                };
                proxyFunctionAs(_self, "_addUnloadCb", function () { return _unloadHandlerContainer; }, "add");
            });
            _self[_DYN_DIAG_LOG ] = function (itemCtx) {
                return _getTelCtx(itemCtx)[_DYN_DIAG_LOG ]();
            };
            _self[_DYN_IS_INITIALIZED ] = function () {
                return _isinitialized;
            };
            _self.setInitialized = function (isInitialized) {
                _isinitialized = isInitialized;
            };
            _self[_DYN_SET_NEXT_PLUGIN ] = function (next) {
                _nextPlugin = next;
            };
            _self[_DYN_PROCESS_NEXT ] = function (env, itemCtx) {
                if (itemCtx) {
                    itemCtx[_DYN_PROCESS_NEXT ](env);
                }
                else if (_nextPlugin && isFunction(_nextPlugin[STR_PROCESS_TELEMETRY ])) {
                    _nextPlugin[STR_PROCESS_TELEMETRY ](env, null);
                }
            };
            _self._getTelCtx = _getTelCtx;
            function _getTelCtx(currentCtx) {
                if (currentCtx === void 0) { currentCtx = null; }
                var itemCtx = currentCtx;
                if (!itemCtx) {
                    var rootCtx = _rootCtx || createProcessTelemetryContext(null, {}, _self[STR_CORE ]);
                    if (_nextPlugin && _nextPlugin[strGetPlugin]) {
                        itemCtx = rootCtx[_DYN_CREATE_NEW ](null, _nextPlugin[strGetPlugin]);
                    }
                    else {
                        itemCtx = rootCtx[_DYN_CREATE_NEW ](null, _nextPlugin);
                    }
                }
                return itemCtx;
            }
            function _setDefaults(config, core, pluginChain) {
                if (config) {
                    setValue(config, STR_EXTENSION_CONFIG, [], null, isNullOrUndefined);
                }
                if (!pluginChain && core) {
                    pluginChain = core[_DYN_GET_PROCESS_TEL_CONT0 ]()[_DYN_GET_NEXT ]();
                }
                var nextPlugin = _nextPlugin;
                if (_nextPlugin && _nextPlugin[strGetPlugin]) {
                    nextPlugin = _nextPlugin[strGetPlugin]();
                }
                _self[STR_CORE ] = core;
                _rootCtx = createProcessTelemetryContext(pluginChain, config, core, nextPlugin);
            }
            function _initDefaults() {
                _isinitialized = false;
                _self[STR_CORE ] = null;
                _rootCtx = null;
                _nextPlugin = null;
                _hooks = [];
                _unloadHandlerContainer = createUnloadHandlerContainer();
            }
        }
        BaseTelemetryPlugin.__ieDyn=1;
        return BaseTelemetryPlugin;
    }());

    var TelemetryInitializerPlugin = /** @class */ (function (_super) {
        __extendsFn(TelemetryInitializerPlugin, _super);
        function TelemetryInitializerPlugin() {
            var _this = _super.call(this) || this;
            _this.identifier = "TelemetryInitializerPlugin";
            _this.priority = 199;
            var _id;
            var _initializers;
            _initDefaults();
            dynamicProto(TelemetryInitializerPlugin, _this, function (_self, _base) {
                _self.addTelemetryInitializer = function (telemetryInitializer) {
                    var theInitializer = {
                        id: _id++,
                        fn: telemetryInitializer
                    };
                    _initializers[_DYN_PUSH ](theInitializer);
                    var handler = {
                        remove: function () {
                            arrForEach(_initializers, function (initializer, idx) {
                                if (initializer.id === theInitializer.id) {
                                    _initializers[_DYN_SPLICE ](idx, 1);
                                    return -1;
                                }
                            });
                        }
                    };
                    return handler;
                };
                _self[STR_PROCESS_TELEMETRY ] = function (item, itemCtx) {
                    var doNotSendItem = false;
                    var telemetryInitializersCount = _initializers[_DYN_LENGTH ];
                    for (var i = 0; i < telemetryInitializersCount; ++i) {
                        var telemetryInitializer = _initializers[i];
                        if (telemetryInitializer) {
                            try {
                                if (telemetryInitializer.fn[_DYN_APPLY ](null, [item]) === false) {
                                    doNotSendItem = true;
                                    break;
                                }
                            }
                            catch (e) {
                                _throwInternal(itemCtx[_DYN_DIAG_LOG ](), 1 , 64 , "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e), { exception: dumpObj(e) }, true);
                            }
                        }
                    }
                    if (!doNotSendItem) {
                        _self[_DYN_PROCESS_NEXT ](item, itemCtx);
                    }
                };
                _self[_DYN__DO_TEARDOWN ] = function () {
                    _initDefaults();
                };
            });
            function _initDefaults() {
                _id = 0;
                _initializers = [];
            }
            return _this;
        }
        TelemetryInitializerPlugin.__ieDyn=1;
        return TelemetryInitializerPlugin;
    }(BaseTelemetryPlugin));

    var strValidationError = "Plugins must provide initialize method";
    var strNotificationManager = "_notificationManager";
    var strSdkUnloadingError = "SDK is still unloading...";
    var strSdkNotInitialized = "SDK is not initialized";
    var defaultInitConfig = {
        loggingLevelConsole: 1
    };
    function _createPerfManager(core, notificationMgr) {
        return new PerfManager(notificationMgr);
    }
    function _validateExtensions(logger, channelPriority, allExtensions) {
        var _a;
        var coreExtensions = [];
        var extPriorities = {};
        arrForEach(allExtensions, function (ext) {
            if (isNullOrUndefined(ext) || isNullOrUndefined(ext[_DYN_INITIALIZE ])) {
                throwError(strValidationError);
            }
            var extPriority = ext[STR_PRIORITY ];
            var identifier = ext[_DYN_IDENTIFIER ];
            if (ext && extPriority) {
                if (!isNullOrUndefined(extPriorities[extPriority])) {
                    _warnToConsole(logger, "Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier);
                }
                else {
                    extPriorities[extPriority] = identifier;
                }
            }
            if (!extPriority || extPriority < channelPriority) {
                coreExtensions[_DYN_PUSH ](ext);
            }
        });
        return _a = {
                all: allExtensions
            },
            _a[STR_CORE ] = coreExtensions,
            _a;
    }
    function _isPluginPresent(thePlugin, plugins) {
        var exists = false;
        arrForEach(plugins, function (plugin) {
            if (plugin === thePlugin) {
                exists = true;
                return -1;
            }
        });
        return exists;
    }
    function _createDummyNotificationManager() {
        var _a;
        return objCreateFn((_a = {},
            _a[_DYN_ADD_NOTIFICATION_LIS1 ] = function (listener) { },
            _a[_DYN_REMOVE_NOTIFICATION_2 ] = function (listener) { },
            _a[STR_EVENTS_SENT ] = function (events) { },
            _a[STR_EVENTS_DISCARDED ] = function (events, reason) { },
            _a[STR_EVENTS_SEND_REQUEST ] = function (sendReason, isAsync) { },
            _a));
    }
    var BaseCore = /** @class */ (function () {
        function BaseCore() {
            var _config;
            var _isInitialized;
            var _eventQueue;
            var _notificationManager;
            var _perfManager;
            var _cfgPerfManager;
            var _cookieManager;
            var _pluginChain;
            var _configExtensions;
            var _coreExtensions;
            var _channelControl;
            var _channelConfig;
            var _channelQueue;
            var _isUnloading;
            var _telemetryInitializerPlugin;
            var _internalLogsEventName;
            var _evtNamespace;
            var _unloadHandlers;
            var _debugListener;
            var _traceCtx;
            var _internalLogPoller = 0;
            var _forceStopInternalLogPoller = false;
            dynamicProto(BaseCore, this, function (_self) {
                _initDefaults();
                _self[_DYN_IS_INITIALIZED ] = function () { return _isInitialized; };
                _self[_DYN_INITIALIZE ] = function (config, extensions, logger, notificationManager) {
                    if (_isUnloading) {
                        throwError(strSdkUnloadingError);
                    }
                    if (_self[_DYN_IS_INITIALIZED ]()) {
                        throwError("Core should not be initialized more than once");
                    }
                    _config = config || {};
                    _self[_DYN_CONFIG ] = _config;
                    if (isNullOrUndefined(config[_DYN_INSTRUMENTATION_KEY ])) {
                        throwError("Please provide instrumentation key");
                    }
                    _notificationManager = notificationManager;
                    _self[strNotificationManager] = notificationManager;
                    _initDebugListener();
                    _initPerfManager();
                    _initExtConfig();
                    if (logger) {
                        _self[_DYN_LOGGER ] = logger;
                    }
                    var cfgExtensions = getSetValue(_config, STR_EXTENSIONS, []);
                    _configExtensions = [];
                    _configExtensions[_DYN_PUSH ].apply(_configExtensions, __spreadArrayFn(__spreadArrayFn([], extensions, false), cfgExtensions));
                    _channelConfig = getSetValue(_config, STR_CHANNELS, []);
                    _initPluginChain(null);
                    if (!_channelQueue || _channelQueue[_DYN_LENGTH ] === 0) {
                        throwError("No " + STR_CHANNELS + " available");
                    }
                    _isInitialized = true;
                    _self.releaseQueue();
                };
                _self.getTransmissionControls = function () {
                    var controls = [];
                    if (_channelQueue) {
                        arrForEach(_channelQueue, function (channels) {
                            controls[_DYN_PUSH ](channels.queue);
                        });
                    }
                    return objFreeze(controls);
                };
                _self.track = function (telemetryItem) {
                    telemetryItem.iKey = telemetryItem.iKey || _config[_DYN_INSTRUMENTATION_KEY ];
                    telemetryItem[_DYN_TIME ] = telemetryItem[_DYN_TIME ] || toISOString(new Date());
                    telemetryItem.ver = telemetryItem.ver || "4.0";
                    if (!_isUnloading && _self[_DYN_IS_INITIALIZED ]()) {
                        _createTelCtx()[_DYN_PROCESS_NEXT ](telemetryItem);
                    }
                    else {
                        _eventQueue[_DYN_PUSH ](telemetryItem);
                    }
                };
                _self[_DYN_GET_PROCESS_TEL_CONT0 ] = _createTelCtx;
                _self[_DYN_GET_NOTIFY_MGR ] = function () {
                    if (!_notificationManager) {
                        _notificationManager = _createDummyNotificationManager();
                        _self[strNotificationManager] = _notificationManager;
                    }
                    return _notificationManager;
                };
                _self[_DYN_ADD_NOTIFICATION_LIS1 ] = function (listener) {
                    if (_notificationManager) {
                        _notificationManager[_DYN_ADD_NOTIFICATION_LIS1 ](listener);
                    }
                };
                _self[_DYN_REMOVE_NOTIFICATION_2 ] = function (listener) {
                    if (_notificationManager) {
                        _notificationManager[_DYN_REMOVE_NOTIFICATION_2 ](listener);
                    }
                };
                _self.getCookieMgr = function () {
                    if (!_cookieManager) {
                        _cookieManager = createCookieMgr(_config, _self[_DYN_LOGGER ]);
                    }
                    return _cookieManager;
                };
                _self.setCookieMgr = function (cookieMgr) {
                    _cookieManager = cookieMgr;
                };
                _self[STR_GET_PERF_MGR ] = function () {
                    if (!_perfManager && !_cfgPerfManager) {
                        if (getCfgValue(_config.enablePerfMgr)) {
                            var createPerfMgr = getCfgValue(_config[STR_CREATE_PERF_MGR ]);
                            if (isFunction(createPerfMgr)) {
                                _cfgPerfManager = createPerfMgr(_self, _self[_DYN_GET_NOTIFY_MGR ]());
                            }
                        }
                    }
                    return _perfManager || _cfgPerfManager || getGblPerfMgr();
                };
                _self.setPerfMgr = function (perfMgr) {
                    _perfManager = perfMgr;
                };
                _self.eventCnt = function () {
                    return _eventQueue[_DYN_LENGTH ];
                };
                _self.releaseQueue = function () {
                    if (_isInitialized && _eventQueue[_DYN_LENGTH ] > 0) {
                        var eventQueue = _eventQueue;
                        _eventQueue = [];
                        arrForEach(eventQueue, function (event) {
                            _createTelCtx()[_DYN_PROCESS_NEXT ](event);
                        });
                    }
                };
                _self.pollInternalLogs = function (eventName) {
                    _internalLogsEventName = eventName || null;
                    _forceStopInternalLogPoller = false;
                    if (_internalLogPoller) {
                        clearInterval(_internalLogPoller);
                        _internalLogPoller = null;
                    }
                    return _startInternalLogTimer(true);
                };
                function _startInternalLogTimer(alwaysStart) {
                    if (!_internalLogPoller && !_forceStopInternalLogPoller) {
                        var shouldStart = alwaysStart || (_self[_DYN_LOGGER ] && _self[_DYN_LOGGER ].queue[_DYN_LENGTH ] > 0);
                        if (shouldStart) {
                            var interval = getCfgValue(_config.diagnosticLogInterval);
                            if (!interval || !(interval > 0)) {
                                interval = 10000;
                            }
                            _internalLogPoller = setInterval(function () {
                                clearInterval(_internalLogPoller);
                                _internalLogPoller = 0;
                                _flushInternalLogs();
                            }, interval);
                        }
                    }
                    return _internalLogPoller;
                }
                _self[_DYN_STOP_POLLING_INTERNA3 ] = function () {
                    _forceStopInternalLogPoller = true;
                    if (_internalLogPoller) {
                        clearInterval(_internalLogPoller);
                        _internalLogPoller = 0;
                        _flushInternalLogs();
                    }
                };
                proxyFunctions(_self, function () { return _telemetryInitializerPlugin; }, ["addTelemetryInitializer"]);
                _self.unload = function (isAsync, unloadComplete, cbTimeout) {
                    var _a;
                    if (isAsync === void 0) { isAsync = true; }
                    if (!_isInitialized) {
                        throwError(strSdkNotInitialized);
                    }
                    if (_isUnloading) {
                        throwError(strSdkUnloadingError);
                    }
                    var unloadState = (_a = {
                            reason: 50
                        },
                        _a[_DYN_IS_ASYNC ] = isAsync,
                        _a.flushComplete = false,
                        _a);
                    var processUnloadCtx = createProcessTelemetryUnloadContext(_getPluginChain(), _self);
                    processUnloadCtx[_DYN_ON_COMPLETE ](function () {
                        _initDefaults();
                        unloadComplete && unloadComplete(unloadState);
                    }, _self);
                    function _doUnload(flushComplete) {
                        unloadState.flushComplete = flushComplete;
                        _isUnloading = true;
                        _unloadHandlers.run(processUnloadCtx, unloadState);
                        _self[_DYN_STOP_POLLING_INTERNA3 ]();
                        processUnloadCtx[_DYN_PROCESS_NEXT ](unloadState);
                    }
                    _flushInternalLogs();
                    if (!_flushChannels(isAsync, _doUnload, 6 , cbTimeout)) {
                        _doUnload(false);
                    }
                };
                _self[_DYN_GET_PLUGIN ] = _getPlugin;
                _self.addPlugin = function (plugin, replaceExisting, isAsync, addCb) {
                    if (!plugin) {
                        addCb && addCb(false);
                        _logOrThrowError(strValidationError);
                        return;
                    }
                    var existingPlugin = _getPlugin(plugin[_DYN_IDENTIFIER ]);
                    if (existingPlugin && !replaceExisting) {
                        addCb && addCb(false);
                        _logOrThrowError("Plugin [" + plugin[_DYN_IDENTIFIER ] + "] is already loaded!");
                        return;
                    }
                    var updateState = {
                        reason: 16
                    };
                    function _addPlugin(removed) {
                        _configExtensions[_DYN_PUSH ](plugin);
                        updateState.added = [plugin];
                        _initPluginChain(updateState);
                        addCb && addCb(true);
                    }
                    if (existingPlugin) {
                        var removedPlugins_1 = [existingPlugin.plugin];
                        var unloadState = {
                            reason: 2 ,
                            isAsync: !!isAsync
                        };
                        _removePlugins(removedPlugins_1, unloadState, function (removed) {
                            if (!removed) {
                                addCb && addCb(false);
                            }
                            else {
                                updateState.removed = removedPlugins_1;
                                updateState.reason |= 32 ;
                                _addPlugin();
                            }
                        });
                    }
                    else {
                        _addPlugin();
                    }
                };
                _self.evtNamespace = function () {
                    return _evtNamespace;
                };
                _self[_DYN_FLUSH ] = _flushChannels;
                _self.getTraceCtx = function (createNew) {
                    if (!_traceCtx) {
                        _traceCtx = createDistributedTraceContext();
                    }
                    return _traceCtx;
                };
                _self.setTraceCtx = function (traceCtx) {
                    _traceCtx = traceCtx || null;
                };
                proxyFunctionAs(_self, "addUnloadCb", function () { return _unloadHandlers; }, "add");
                function _initDefaults() {
                    _isInitialized = false;
                    _config = objExtend(true, {}, defaultInitConfig);
                    _self[_DYN_CONFIG ] = _config;
                    _self[_DYN_LOGGER ] = new DiagnosticLogger(_config);
                    _self[_DYN__EXTENSIONS ] = [];
                    _telemetryInitializerPlugin = new TelemetryInitializerPlugin();
                    _eventQueue = [];
                    _notificationManager = null;
                    _perfManager = null;
                    _cfgPerfManager = null;
                    _cookieManager = null;
                    _pluginChain = null;
                    _coreExtensions = null;
                    _configExtensions = [];
                    _channelControl = null;
                    _channelConfig = null;
                    _channelQueue = null;
                    _isUnloading = false;
                    _internalLogsEventName = null;
                    _evtNamespace = createUniqueNamespace("AIBaseCore", true);
                    _unloadHandlers = createUnloadHandlerContainer();
                    _traceCtx = null;
                }
                function _createTelCtx() {
                    var theCtx = createProcessTelemetryContext(_getPluginChain(), _config, _self);
                    theCtx[_DYN_ON_COMPLETE ](_startInternalLogTimer);
                    return theCtx;
                }
                function _initPluginChain(updateState) {
                    var theExtensions = _validateExtensions(_self[_DYN_LOGGER ], ChannelControllerPriority, _configExtensions);
                    _coreExtensions = theExtensions[STR_CORE ];
                    _pluginChain = null;
                    var allExtensions = theExtensions.all;
                    _channelQueue = objFreeze(createChannelQueues(_channelConfig, allExtensions, _self));
                    if (_channelControl) {
                        var idx = arrIndexOf(allExtensions, _channelControl);
                        if (idx !== -1) {
                            allExtensions[_DYN_SPLICE ](idx, 1);
                        }
                        idx = arrIndexOf(_coreExtensions, _channelControl);
                        if (idx !== -1) {
                            _coreExtensions[_DYN_SPLICE ](idx, 1);
                        }
                        _channelControl._setQueue(_channelQueue);
                    }
                    else {
                        _channelControl = createChannelControllerPlugin(_channelQueue, _self);
                    }
                    allExtensions[_DYN_PUSH ](_channelControl);
                    _coreExtensions[_DYN_PUSH ](_channelControl);
                    _self[_DYN__EXTENSIONS ] = sortPlugins(allExtensions);
                    _channelControl[_DYN_INITIALIZE ](_config, _self, allExtensions);
                    var initCtx = _createTelCtx();
                    initializePlugins(initCtx, allExtensions);
                    _self[_DYN__EXTENSIONS ] = objFreeze(sortPlugins(_coreExtensions || [])).slice();
                    if (updateState) {
                        _doUpdate(updateState);
                    }
                }
                function _getPlugin(pluginIdentifier) {
                    var _a;
                    var theExt = null;
                    var thePlugin = null;
                    arrForEach(_self[_DYN__EXTENSIONS ], function (ext) {
                        if (ext[_DYN_IDENTIFIER ] === pluginIdentifier && ext !== _channelControl && ext !== _telemetryInitializerPlugin) {
                            thePlugin = ext;
                            return -1;
                        }
                    });
                    if (!thePlugin && _channelControl) {
                        thePlugin = _channelControl.getChannel(pluginIdentifier);
                    }
                    if (thePlugin) {
                        theExt = (_a = {
                                plugin: thePlugin
                            },
                            _a[_DYN_SET_ENABLED ] = function (enabled) {
                                _getPluginState(thePlugin)[STR_DISABLED] = !enabled;
                            },
                            _a.isEnabled = function () {
                                var pluginState = _getPluginState(thePlugin);
                                return !pluginState[_DYN_TEARDOWN ] && !pluginState[STR_DISABLED];
                            },
                            _a.remove = function (isAsync, removeCb) {
                                var _a;
                                if (isAsync === void 0) { isAsync = true; }
                                var pluginsToRemove = [thePlugin];
                                var unloadState = (_a = {
                                        reason: 1
                                    },
                                    _a[_DYN_IS_ASYNC ] = isAsync,
                                    _a);
                                _removePlugins(pluginsToRemove, unloadState, function (removed) {
                                    if (removed) {
                                        _initPluginChain({
                                            reason: 32 ,
                                            removed: pluginsToRemove
                                        });
                                    }
                                    removeCb && removeCb(removed);
                                });
                            },
                            _a);
                    }
                    return theExt;
                }
                function _getPluginChain() {
                    if (!_pluginChain) {
                        var extensions = (_coreExtensions || []).slice();
                        if (arrIndexOf(extensions, _telemetryInitializerPlugin) === -1) {
                            extensions[_DYN_PUSH ](_telemetryInitializerPlugin);
                        }
                        _pluginChain = createTelemetryProxyChain(sortPlugins(extensions), _config, _self);
                    }
                    return _pluginChain;
                }
                function _removePlugins(thePlugins, unloadState, removeComplete) {
                    if (thePlugins && thePlugins[_DYN_LENGTH ] > 0) {
                        var unloadChain = createTelemetryProxyChain(thePlugins, _config, _self);
                        var unloadCtx = createProcessTelemetryUnloadContext(unloadChain, _self);
                        unloadCtx[_DYN_ON_COMPLETE ](function () {
                            var removed = false;
                            var newConfigExtensions = [];
                            arrForEach(_configExtensions, function (plugin, idx) {
                                if (!_isPluginPresent(plugin, thePlugins)) {
                                    newConfigExtensions[_DYN_PUSH ](plugin);
                                }
                                else {
                                    removed = true;
                                }
                            });
                            _configExtensions = newConfigExtensions;
                            var newChannelConfig = [];
                            if (_channelConfig) {
                                arrForEach(_channelConfig, function (queue, idx) {
                                    var newQueue = [];
                                    arrForEach(queue, function (channel) {
                                        if (!_isPluginPresent(channel, thePlugins)) {
                                            newQueue[_DYN_PUSH ](channel);
                                        }
                                        else {
                                            removed = true;
                                        }
                                    });
                                    newChannelConfig[_DYN_PUSH ](newQueue);
                                });
                                _channelConfig = newChannelConfig;
                            }
                            removeComplete && removeComplete(removed);
                            _startInternalLogTimer();
                        });
                        unloadCtx[_DYN_PROCESS_NEXT ](unloadState);
                    }
                    else {
                        removeComplete(false);
                    }
                }
                function _flushInternalLogs() {
                    if (_self[_DYN_LOGGER ] && _self[_DYN_LOGGER ].queue) {
                        var queue = _self[_DYN_LOGGER ].queue.slice(0);
                        _self[_DYN_LOGGER ].queue[_DYN_LENGTH ] = 0;
                        arrForEach(queue, function (logMessage) {
                            var _a;
                            var item = (_a = {},
                                _a[_DYN_NAME ] = _internalLogsEventName ? _internalLogsEventName : "InternalMessageId: " + logMessage[_DYN_MESSAGE_ID ],
                                _a.iKey = getCfgValue(_config[_DYN_INSTRUMENTATION_KEY ]),
                                _a.time = toISOString(new Date()),
                                _a.baseType = _InternalLogMessage.dataType,
                                _a.baseData = { message: logMessage[_DYN_MESSAGE ] },
                                _a);
                            _self.track(item);
                        });
                    }
                }
                function _flushChannels(isAsync, callBack, sendReason, cbTimeout) {
                    if (_channelControl) {
                        return _channelControl[_DYN_FLUSH ](isAsync, callBack, sendReason || 6 , cbTimeout);
                    }
                    callBack && callBack(false);
                    return true;
                }
                function _initDebugListener() {
                    var disableDbgExt = getCfgValue(_config.disableDbgExt);
                    if (disableDbgExt === true && _debugListener) {
                        _notificationManager[_DYN_REMOVE_NOTIFICATION_2 ](_debugListener);
                        _debugListener = null;
                    }
                    if (_notificationManager && !_debugListener && disableDbgExt !== true) {
                        _debugListener = getDebugListener(_config);
                        _notificationManager[_DYN_ADD_NOTIFICATION_LIS1 ](_debugListener);
                    }
                }
                function _initPerfManager() {
                    var enablePerfMgr = getCfgValue(_config.enablePerfMgr);
                    if (!enablePerfMgr && _cfgPerfManager) {
                        _cfgPerfManager = null;
                    }
                    if (enablePerfMgr) {
                        getSetValue(_config, STR_CREATE_PERF_MGR, _createPerfManager);
                    }
                }
                function _initExtConfig() {
                    var extConfig = getSetValue(_config, STR_EXTENSION_CONFIG, {});
                    extConfig.NotificationManager = _notificationManager;
                }
                function _doUpdate(updateState) {
                    var updateCtx = createProcessTelemetryUpdateContext(_getPluginChain(), _self);
                    updateCtx[_DYN_ON_COMPLETE ](_startInternalLogTimer);
                    if (!_self._updateHook || _self._updateHook(updateCtx, updateState) !== true) {
                        updateCtx[_DYN_PROCESS_NEXT ](updateState);
                    }
                }
                function _logOrThrowError(message) {
                    var logger = _self[_DYN_LOGGER ];
                    if (logger) {
                        _throwInternal(logger, 2 , 73 , message);
                        _startInternalLogTimer();
                    }
                    else {
                        throwError(message);
                    }
                }
            });
        }
        BaseCore.__ieDyn=1;
        return BaseCore;
    }());

    function _runListeners(listeners, name, isAsync, callback) {
        arrForEach(listeners, function (listener) {
            if (listener && listener[name]) {
                if (isAsync) {
                    setTimeout(function () { return callback(listener); }, 0);
                }
                else {
                    try {
                        callback(listener);
                    }
                    catch (e) {
                    }
                }
            }
        });
    }
    var NotificationManager = /** @class */ (function () {
        function NotificationManager(config) {
            this.listeners = [];
            var perfEvtsSendAll = !!(config || {}).perfEvtsSendAll;
            dynamicProto(NotificationManager, this, function (_self) {
                _self[_DYN_ADD_NOTIFICATION_LIS1 ] = function (listener) {
                    _self.listeners[_DYN_PUSH ](listener);
                };
                _self[_DYN_REMOVE_NOTIFICATION_2 ] = function (listener) {
                    var index = arrIndexOf(_self[_DYN_LISTENERS ], listener);
                    while (index > -1) {
                        _self.listeners[_DYN_SPLICE ](index, 1);
                        index = arrIndexOf(_self[_DYN_LISTENERS ], listener);
                    }
                };
                _self[STR_EVENTS_SENT ] = function (events) {
                    _runListeners(_self[_DYN_LISTENERS ], STR_EVENTS_SENT, true, function (listener) {
                        listener[STR_EVENTS_SENT ](events);
                    });
                };
                _self[STR_EVENTS_DISCARDED ] = function (events, reason) {
                    _runListeners(_self[_DYN_LISTENERS ], STR_EVENTS_DISCARDED, true, function (listener) {
                        listener[STR_EVENTS_DISCARDED ](events, reason);
                    });
                };
                _self[STR_EVENTS_SEND_REQUEST ] = function (sendReason, isAsync) {
                    _runListeners(_self[_DYN_LISTENERS ], STR_EVENTS_SEND_REQUEST, isAsync, function (listener) {
                        listener[STR_EVENTS_SEND_REQUEST ](sendReason, isAsync);
                    });
                };
                _self[STR_PERF_EVENT ] = function (perfEvent) {
                    if (perfEvent) {
                        if (perfEvtsSendAll || !perfEvent[_DYN_IS_CHILD_EVT ]()) {
                            _runListeners(_self[_DYN_LISTENERS ], STR_PERF_EVENT, false, function (listener) {
                                if (perfEvent[_DYN_IS_ASYNC ]) {
                                    setTimeout(function () { return listener[STR_PERF_EVENT ](perfEvent); }, 0);
                                }
                                else {
                                    listener[STR_PERF_EVENT ](perfEvent);
                                }
                            });
                        }
                    }
                };
            });
        }
        NotificationManager.__ieDyn=1;
        return NotificationManager;
    }());

    var AppInsightsCore = /** @class */ (function (_super) {
        __extendsFn(AppInsightsCore, _super);
        function AppInsightsCore() {
            var _this = _super.call(this) || this;
            dynamicProto(AppInsightsCore, _this, function (_self, _base) {
                _self[_DYN_INITIALIZE ] = function (config, extensions, logger, notificationManager) {
                    _base[_DYN_INITIALIZE ](config, extensions, logger || new DiagnosticLogger(config), notificationManager || new NotificationManager(config));
                };
                _self.track = function (telemetryItem) {
                    doPerf(_self[STR_GET_PERF_MGR ](), function () { return "AppInsightsCore:track"; }, function () {
                        if (telemetryItem === null) {
                            _notifyInvalidEvent(telemetryItem);
                            throwError("Invalid telemetry item");
                        }
                        _validateTelemetryItem(telemetryItem);
                        _base.track(telemetryItem);
                    }, function () { return ({ item: telemetryItem }); }, !(telemetryItem.sync));
                };
                function _validateTelemetryItem(telemetryItem) {
                    if (isNullOrUndefined(telemetryItem[_DYN_NAME ])) {
                        _notifyInvalidEvent(telemetryItem);
                        throwError("telemetry name required");
                    }
                }
                function _notifyInvalidEvent(telemetryItem) {
                    var manager = _self[_DYN_GET_NOTIFY_MGR ]();
                    if (manager) {
                        manager[STR_EVENTS_DISCARDED ]([telemetryItem], 2 );
                    }
                }
            });
            return _this;
        }
        AppInsightsCore.__ieDyn=1;
        return AppInsightsCore;
    }(BaseCore));

    var _a;
    var FAILED = "Failed";
    var FAILED_MONITOR_AJAX = FAILED + "MonitorAjax";
    var TRACK = "Track";
    var START = "Start";
    var STOP = "Stop";
    var EVENT = "Event";
    var AUTH_CONTEXT = "AuthContext";
    var EXCEPTION = "Exception";
    var LOCAL = "Local";
    var SESSION = "Session";
    var STORAGE = "Storage";
    var BROWSER = "Browser";
    var CANNOT = "Cannot";
    var BUFFER = "Buffer";
    var INSTRUMENTATION_KEY = "InstrumentationKey";
    var LoggingSeverity = createEnumStyle({
        CRITICAL: 1 ,
        WARNING: 2
    });
    var _InternalMessageId = createEnumStyle((_a = {},
        _a[BROWSER + "DoesNotSupport" + LOCAL + STORAGE] = 0 ,
        _a[BROWSER + CANNOT + "Read" + LOCAL + STORAGE] = 1 ,
        _a[BROWSER + CANNOT + "Read" + SESSION + STORAGE] = 2 ,
        _a[BROWSER + CANNOT + "Write" + LOCAL + STORAGE] = 3 ,
        _a[BROWSER + CANNOT + "Write" + SESSION + STORAGE] = 4 ,
        _a[BROWSER + FAILED + "RemovalFrom" + LOCAL + STORAGE] = 5 ,
        _a[BROWSER + FAILED + "RemovalFrom" + SESSION + STORAGE] = 6 ,
        _a[CANNOT + "SendEmptyTelemetry"] = 7 ,
        _a.ClientPerformanceMathError = 8 ,
        _a["ErrorParsingAI" + SESSION + "Cookie"] = 9 ,
        _a.ErrorPVCalc = 10 ,
        _a[EXCEPTION + "WhileLoggingError"] = 11 ,
        _a[FAILED + "AddingTelemetryTo" + BUFFER] = 12 ,
        _a[FAILED_MONITOR_AJAX + "Abort"] = 13 ,
        _a[FAILED_MONITOR_AJAX + "Dur"] = 14 ,
        _a[FAILED_MONITOR_AJAX + "Open"] = 15 ,
        _a[FAILED_MONITOR_AJAX + "RSC"] = 16 ,
        _a[FAILED_MONITOR_AJAX + "Send"] = 17 ,
        _a[FAILED_MONITOR_AJAX + "GetCorrelationHeader"] = 18 ,
        _a[FAILED + "ToAddHandlerForOnBeforeUnload"] = 19 ,
        _a[FAILED + "ToSendQueuedTelemetry"] = 20 ,
        _a[FAILED + "ToReportDataLoss"] = 21 ,
        _a["Flush" + FAILED] = 22 ,
        _a.MessageLimitPerPVExceeded = 23 ,
        _a.MissingRequiredFieldSpecification = 24 ,
        _a.NavigationTimingNotSupported = 25 ,
        _a.OnError = 26 ,
        _a[SESSION + "RenewalDateIsZero"] = 27 ,
        _a.SenderNotInitialized = 28 ,
        _a[START + TRACK + EVENT + FAILED] = 29 ,
        _a[STOP + TRACK + EVENT + FAILED] = 30 ,
        _a[START + TRACK + FAILED] = 31 ,
        _a[STOP + TRACK + FAILED] = 32 ,
        _a.TelemetrySampledAndNotSent = 33 ,
        _a[TRACK + EVENT + FAILED] = 34 ,
        _a[TRACK + EXCEPTION + FAILED] = 35 ,
        _a[TRACK + "Metric" + FAILED] = 36 ,
        _a[TRACK + "PV" + FAILED] = 37 ,
        _a[TRACK + "PV" + FAILED + "Calc"] = 38 ,
        _a[TRACK + "Trace" + FAILED] = 39 ,
        _a["Transmission" + FAILED] = 40 ,
        _a[FAILED + "ToSet" + STORAGE + BUFFER] = 41 ,
        _a[FAILED + "ToRestore" + STORAGE + BUFFER] = 42 ,
        _a.InvalidBackendResponse = 43 ,
        _a[FAILED + "ToFixDepricatedValues"] = 44 ,
        _a.InvalidDurationValue = 45 ,
        _a.TelemetryEnvelopeInvalid = 46 ,
        _a.CreateEnvelopeError = 47 ,
        _a[CANNOT + "SerializeObject"] = 48 ,
        _a[CANNOT + "SerializeObjectNonSerializable"] = 49 ,
        _a.CircularReferenceDetected = 50 ,
        _a["Clear" + AUTH_CONTEXT + FAILED] = 51 ,
        _a[EXCEPTION + "Truncated"] = 52 ,
        _a.IllegalCharsInName = 53 ,
        _a.ItemNotInArray = 54 ,
        _a.MaxAjaxPerPVExceeded = 55 ,
        _a.MessageTruncated = 56 ,
        _a.NameTooLong = 57 ,
        _a.SampleRateOutOfRange = 58 ,
        _a["Set" + AUTH_CONTEXT + FAILED] = 59 ,
        _a["Set" + AUTH_CONTEXT + FAILED + "AccountName"] = 60 ,
        _a.StringValueTooLong = 61 ,
        _a.StartCalledMoreThanOnce = 62 ,
        _a.StopCalledWithoutStart = 63 ,
        _a["TelemetryInitializer" + FAILED] = 64 ,
        _a.TrackArgumentsNotSpecified = 65 ,
        _a.UrlTooLong = 66 ,
        _a[SESSION + STORAGE + BUFFER + "Full"] = 67 ,
        _a[CANNOT + "AccessCookie"] = 68 ,
        _a.IdTooLong = 69 ,
        _a.InvalidEvent = 70 ,
        _a[FAILED_MONITOR_AJAX + "SetRequestHeader"] = 71 ,
        _a["Send" + BROWSER + "InfoOnUserInit"] = 72 ,
        _a["Plugin" + EXCEPTION] = 73 ,
        _a["Notification" + EXCEPTION] = 74 ,
        _a.SnippetScriptLoadFailure = 99 ,
        _a["Invalid" + INSTRUMENTATION_KEY] = 100 ,
        _a[CANNOT + "ParseAiBlobValue"] = 101 ,
        _a.InvalidContentBlob = 102 ,
        _a[TRACK + "PageAction" + EVENT + FAILED] = 103 ,
        _a[FAILED + "AddingCustomDefinedRequestContext"] = 104 ,
        _a["InMemory" + STORAGE + BUFFER + "Full"] = 105 ,
        _a[INSTRUMENTATION_KEY + "Deprecation"] = 106 ,
        _a));

    var aiInstrumentHooks = "_aiHooks";
    var cbNames = [
        "req", "rsp", "hkErr", "fnErr"
    ];
    function _arrLoop(arr, fn) {
        if (arr) {
            for (var lp = 0; lp < arr[_DYN_LENGTH ]; lp++) {
                if (fn(arr[lp], lp)) {
                    break;
                }
            }
        }
    }
    function _doCallbacks(hooks, callDetails, cbArgs, hookCtx, type) {
        if (type >= 0  && type <= 2 ) {
            _arrLoop(hooks, function (hook, idx) {
                var cbks = hook.cbks;
                var cb = cbks[cbNames[type]];
                if (cb) {
                    callDetails.ctx = function () {
                        var ctx = hookCtx[idx] = (hookCtx[idx] || {});
                        return ctx;
                    };
                    try {
                        cb[_DYN_APPLY ](callDetails.inst, cbArgs);
                    }
                    catch (err) {
                        var orgEx = callDetails.err;
                        try {
                            var hookErrorCb = cbks[cbNames[2 ]];
                            if (hookErrorCb) {
                                callDetails.err = err;
                                hookErrorCb[_DYN_APPLY ](callDetails.inst, cbArgs);
                            }
                        }
                        catch (e) {
                        }
                        finally {
                            callDetails.err = orgEx;
                        }
                    }
                }
            });
        }
    }
    function _createFunctionHook(aiHook) {
        return function () {
            var _a;
            var funcThis = this;
            var orgArgs = arguments;
            var hooks = aiHook.h;
            var funcArgs = (_a = {},
                _a[_DYN_NAME ] = aiHook.n,
                _a.inst = funcThis,
                _a.ctx = null,
                _a.set = _replaceArg,
                _a);
            var hookCtx = [];
            var cbArgs = _createArgs([funcArgs], orgArgs);
            funcArgs.evt = getGlobalInst("event");
            function _createArgs(target, theArgs) {
                _arrLoop(theArgs, function (arg) {
                    target[_DYN_PUSH ](arg);
                });
                return target;
            }
            function _replaceArg(idx, value) {
                orgArgs = _createArgs([], orgArgs);
                orgArgs[idx] = value;
                cbArgs = _createArgs([funcArgs], orgArgs);
            }
            _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 0 );
            var theFunc = aiHook.f;
            if (theFunc) {
                try {
                    funcArgs.rslt = theFunc[_DYN_APPLY ](funcThis, orgArgs);
                }
                catch (err) {
                    funcArgs.err = err;
                    _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 3 );
                    throw err;
                }
            }
            _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 1 );
            return funcArgs.rslt;
        };
    }
    function _getOwner(target, name, checkPrototype, checkParentProto) {
        var owner = null;
        if (target) {
            if (hasOwnProperty(target, name)) {
                owner = target;
            }
            else if (checkPrototype) {
                owner = _getOwner(_getObjProto$1(target), name, checkParentProto, false);
            }
        }
        return owner;
    }
    function InstrumentProto(target, funcName, callbacks) {
        if (target) {
            return InstrumentFunc(target[strShimPrototype], funcName, callbacks, false);
        }
        return null;
    }
    function InstrumentProtos(target, funcNames, callbacks) {
        if (target) {
            return InstrumentFuncs(target[strShimPrototype], funcNames, callbacks, false);
        }
        return null;
    }
    function _createInstrumentHook(owner, funcName, fn, callbacks) {
        var aiHook = fn && fn[aiInstrumentHooks];
        if (!aiHook) {
            aiHook = {
                i: 0,
                n: funcName,
                f: fn,
                h: []
            };
            var newFunc = _createFunctionHook(aiHook);
            newFunc[aiInstrumentHooks] = aiHook;
            owner[funcName] = newFunc;
        }
        var theHook = {
            id: aiHook.i,
            cbks: callbacks,
            rm: function () {
                var id = this.id;
                _arrLoop(aiHook.h, function (hook, idx) {
                    if (hook.id === id) {
                        aiHook.h[_DYN_SPLICE ](idx, 1);
                        return 1;
                    }
                });
            }
        };
        aiHook.i++;
        aiHook.h[_DYN_PUSH ](theHook);
        return theHook;
    }
    function InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto) {
        if (checkPrototype === void 0) { checkPrototype = true; }
        if (target && funcName && callbacks) {
            var owner = _getOwner(target, funcName, checkPrototype, checkParentProto);
            if (owner) {
                var fn = owner[funcName];
                if (typeof fn === strShimFunction) {
                    return _createInstrumentHook(owner, funcName, fn, callbacks);
                }
            }
        }
        return null;
    }
    function InstrumentFuncs(target, funcNames, callbacks, checkPrototype, checkParentProto) {
        if (checkPrototype === void 0) { checkPrototype = true; }
        var hooks = null;
        _arrLoop(funcNames, function (funcName) {
            var hook = InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto);
            if (hook) {
                if (!hooks) {
                    hooks = [];
                }
                hooks[_DYN_PUSH ](hook);
            }
        });
        return hooks;
    }
    function InstrumentEvent(target, evtName, callbacks, checkPrototype, checkParentProto) {
        if (target && evtName && callbacks) {
            var owner = _getOwner(target, evtName, checkPrototype, checkParentProto) || target;
            if (owner) {
                return _createInstrumentHook(owner, evtName, owner[evtName], callbacks);
            }
        }
        return null;
    }

    exports.AppInsightsCore = AppInsightsCore;
    exports.BaseCore = BaseCore;
    exports.BaseTelemetryPlugin = BaseTelemetryPlugin;
    exports.CoreUtils = CoreUtils;
    exports.DiagnosticLogger = DiagnosticLogger;
    exports.EventHelper = EventHelper;
    exports.EventsDiscardedReason = EventsDiscardedReason;
    exports.InstrumentEvent = InstrumentEvent;
    exports.InstrumentFunc = InstrumentFunc;
    exports.InstrumentFuncs = InstrumentFuncs;
    exports.InstrumentProto = InstrumentProto;
    exports.InstrumentProtos = InstrumentProtos;
    exports.LoggingSeverity = LoggingSeverity;
    exports.MinChannelPriorty = MinChannelPriorty;
    exports.NotificationManager = NotificationManager;
    exports.PerfEvent = PerfEvent;
    exports.PerfManager = PerfManager;
    exports.ProcessTelemetryContext = ProcessTelemetryContext;
    exports.Undefined = Undefined;
    exports._InternalLogMessage = _InternalLogMessage;
    exports._InternalMessageId = _InternalMessageId;
    exports.__getRegisteredEvents = __getRegisteredEvents;
    exports._legacyCookieMgr = _legacyCookieMgr;
    exports._logInternalMessage = _logInternalMessage;
    exports._throwInternal = _throwInternal;
    exports._warnToConsole = _warnToConsole;
    exports.addEventHandler = addEventHandler;
    exports.addEventListeners = addEventListeners;
    exports.addPageHideEventListener = addPageHideEventListener;
    exports.addPageShowEventListener = addPageShowEventListener;
    exports.addPageUnloadEventListener = addPageUnloadEventListener;
    exports.areCookiesSupported = areCookiesSupported;
    exports.arrForEach = arrForEach;
    exports.arrIndexOf = arrIndexOf;
    exports.arrMap = arrMap;
    exports.arrReduce = arrReduce;
    exports.attachEvent = attachEvent;
    exports.canUseCookies = canUseCookies;
    exports.createClassFromInterface = createClassFromInterface;
    exports.createCookieMgr = createCookieMgr;
    exports.createCustomDomEvent = createCustomDomEvent;
    exports.createEnumMap = createEnumMap;
    exports.createEnumStyle = createEnumStyle;
    exports.createProcessTelemetryContext = createProcessTelemetryContext;
    exports.createTraceParent = createTraceParent;
    exports.createUniqueNamespace = createUniqueNamespace;
    exports.createUnloadHandlerContainer = createUnloadHandlerContainer;
    exports.createValueMap = createValueMap;
    exports.dateNow = dateNow;
    exports.deepFreeze = deepFreeze;
    exports.deleteCookie = deleteCookie;
    exports.detachEvent = detachEvent;
    exports.disableCookies = disableCookies;
    exports.dispatchEvent = dispatchEvent;
    exports.doPerf = doPerf;
    exports.dumpObj = dumpObj;
    exports.eventOff = eventOff;
    exports.eventOn = eventOn;
    exports.findMetaTag = findMetaTag;
    exports.findNamedServerTiming = findNamedServerTiming;
    exports.findW3cTraceParent = findW3cTraceParent;
    exports.formatTraceParent = formatTraceParent;
    exports.generateW3CId = generateW3CId;
    exports.getConsole = getConsole;
    exports.getCookie = getCookie;
    exports.getCrypto = getCrypto;
    exports.getDebugExt = getDebugExt;
    exports.getDebugListener = getDebugListener;
    exports.getDocument = getDocument;
    exports.getExceptionName = getExceptionName;
    exports.getGblPerfMgr = getGblPerfMgr;
    exports.getGlobal = getGlobal;
    exports.getGlobalInst = getGlobalInst;
    exports.getHistory = getHistory;
    exports.getIEVersion = getIEVersion;
    exports.getJSON = getJSON;
    exports.getLocation = getLocation;
    exports.getMsCrypto = getMsCrypto;
    exports.getNavigator = getNavigator;
    exports.getPerformance = getPerformance;
    exports.getSetValue = getSetValue;
    exports.getWindow = getWindow;
    exports.hasDocument = hasDocument;
    exports.hasHistory = hasHistory;
    exports.hasJSON = hasJSON;
    exports.hasNavigator = hasNavigator;
    exports.hasOwnProperty = hasOwnProperty;
    exports.hasWindow = hasWindow;
    exports.initializePlugins = initializePlugins;
    exports.isArray = isArray;
    exports.isBeaconsSupported = isBeaconsSupported;
    exports.isBoolean = isBoolean;
    exports.isDate = isDate;
    exports.isError = isError;
    exports.isFetchSupported = isFetchSupported;
    exports.isFunction = isFunction;
    exports.isIE = isIE;
    exports.isNotNullOrUndefined = isNotNullOrUndefined;
    exports.isNotTruthy = isNotTruthy;
    exports.isNotUndefined = isNotUndefined;
    exports.isNullOrUndefined = isNullOrUndefined;
    exports.isNumber = isNumber;
    exports.isObject = isObject;
    exports.isPlainObject = isPlainObject;
    exports.isReactNative = isReactNative;
    exports.isSafari = isSafari;
    exports.isSampledFlag = isSampledFlag;
    exports.isString = isString;
    exports.isSymbol = isSymbol;
    exports.isTruthy = isTruthy;
    exports.isTypeof = isTypeof;
    exports.isUndefined = isUndefined;
    exports.isValidSpanId = isValidSpanId;
    exports.isValidTraceId = isValidTraceId;
    exports.isValidTraceParent = isValidTraceParent;
    exports.isXhrSupported = isXhrSupported;
    exports.mergeEvtNamespace = mergeEvtNamespace;
    exports.mwcRandom32 = mwcRandom32;
    exports.mwcRandomSeed = mwcRandomSeed;
    exports.newGuid = newGuid;
    exports.newId = newId;
    exports.normalizeJsName = normalizeJsName;
    exports.objCreate = objCreateFn;
    exports.objDefineAccessors = objDefineAccessors;
    exports.objExtend = objExtend;
    exports.objForEachKey = objForEachKey;
    exports.objFreeze = objFreeze;
    exports.objKeys = objKeys;
    exports.objSeal = objSeal;
    exports.objToString = objToString;
    exports.optimizeObject = optimizeObject;
    exports.parseTraceParent = parseTraceParent;
    exports.perfNow = perfNow;
    exports.proxyAssign = proxyAssign;
    exports.proxyFunctionAs = proxyFunctionAs;
    exports.proxyFunctions = proxyFunctions;
    exports.random32 = random32;
    exports.randomValue = randomValue;
    exports.removeEventHandler = removeEventHandler;
    exports.removeEventListeners = removeEventListeners;
    exports.removePageHideEventListener = removePageHideEventListener;
    exports.removePageShowEventListener = removePageShowEventListener;
    exports.removePageUnloadEventListener = removePageUnloadEventListener;
    exports.safeGetCookieMgr = safeGetCookieMgr;
    exports.safeGetLogger = safeGetLogger;
    exports.sendCustomEvent = sendCustomEvent;
    exports.setCookie = setCookie;
    exports.setEnableEnvMocks = setEnableEnvMocks;
    exports.setGblPerfMgr = setGblPerfMgr;
    exports.setValue = setValue;
    exports.sortPlugins = sortPlugins;
    exports.strContains = strContains;
    exports.strEndsWith = strEndsWith;
    exports.strFunction = strShimFunction;
    exports.strObject = strShimObject;
    exports.strPrototype = strShimPrototype;
    exports.strStartsWith = strStartsWith;
    exports.strTrim = strTrim;
    exports.strUndefined = strShimUndefined;
    exports.throwError = throwError;
    exports.toISOString = toISOString;
    exports.uaDisallowsSameSiteNone = uaDisallowsSameSiteNone;
    exports.unloadComponents = unloadComponents;
    exports.useXDomainRequest = useXDomainRequest;

    (function(obj, prop, descriptor) { /* ai_es3_polyfil defineProperty */ var func = Object["defineProperty"]; if (func) { try { return func(obj, prop, descriptor); } catch(e) { /* IE8 defines defineProperty, but will throw */ } } if (descriptor && typeof descriptor.value !== undefined) { obj[prop] = descriptor.value; } return obj; })(exports, '__esModule', { value: true });

}));
