a||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var h=require(\"react\"),n=require(\"use-sync-external-store/shim\");function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q=\"function\"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);\nu(function(){f.hasValue=!0;f.value=d},[d]);w(d);return d};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","/**\n * This file automatically generated from `pre-publish.js`.\n * Do not manually edit.\n */\n\nmodule.exports = {\n \"area\": true,\n \"base\": true,\n \"br\": true,\n \"col\": true,\n \"embed\": true,\n \"hr\": true,\n \"img\": true,\n \"input\": true,\n \"link\": true,\n \"meta\": true,\n \"param\": true,\n \"source\": true,\n \"track\": true,\n \"wbr\": true\n};\n","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\nmodule.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t\r\n *
\r\n */\r\nexport var createAsyncAllPromise = /*#__PURE__*/ _createAllPromise(createAsyncPromise);\r\n/**\r\n * Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).\r\n * @group Async\r\n * @group Promise\r\n * @group Resolved\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createAsyncResolvedPromise = /*#__PURE__*/ _createResolvedPromise(createAsyncPromise);\r\n/**\r\n * Returns a single asynchronous Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the optional timeout value to schedule\r\n * when then chained items will be executed. (eg. `catch()`; `finally()`).\r\n * @group Async\r\n * @group Promise\r\n * @group Rejected\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createAsyncRejectedPromise = /*#__PURE__*/ _createRejectedPromise(createAsyncPromise);\r\n/**\r\n * Returns a single Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations based on the\r\n * {@link createAsyncPromise Aasynchronous} promise implementation. Any chained operations will execute\r\n * __asynchronously__ when the final operation pending promises have resolved, or if the input contains\r\n * no promises. It will resolve only after all of the input promises have either resolved or rejected,\r\n * and will resolve with an array of {@link IPromiseResult } objects that each describe the outcome of\r\n * each promise.\r\n * @since 0.5.0\r\n * @group Async\r\n * @group Promise\r\n * @group AllSettled\r\n * @param input - An array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.\r\n *\r\n * @example\r\n * ```ts\r\n * const promises = [\r\n * createResolvedPromise(1),\r\n * createResolvedPromise(2),\r\n * createResolvedPromise(3),\r\n * createRejectedPromise(\"error\"),\r\n * ];\r\n *\r\n * const results = await createAllSettledPromise(promises);\r\n *\r\n * // results is:\r\n * // [\r\n * // { status: \"fulfilled\", value: 1 },\r\n * // { status: \"fulfilled\", value: 2 },\r\n * // { status: \"fulfilled\", value: 3 },\r\n * // { status: \"rejected\", reason: \"error\" }\r\n * // ]\r\n * ```\r\n */\r\nexport function createAsyncAllSettledPromise(input, timeout) {\r\n !_allAsyncSettledCreator && (_allAsyncSettledCreator = _createAllSettledPromise(createAsyncPromise));\r\n return _allAsyncSettledCreator.v(input, timeout);\r\n}\r\n/**\r\n * The `createAsyncRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise\r\n * settles with the eventual state of the first promise that settles.\r\n * @description The `createAsyncRacePromise` method is one of the promise concurrency methods. It's useful when you want the first\r\n * async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).\r\n * If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to\r\n * the first of these values found in the iterable.\r\n * @since 0.5.0\r\n * @group Async\r\n * @group Promise\r\n * @group Race\r\n * @param values - An the array of promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the\r\n * first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever\r\n * if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise is still\r\n * asynchronously settled.\r\n */\r\nexport function createAsyncRacePromise(values, timeout) {\r\n !_raceAsyncCreator && (_raceAsyncCreator = _createRacePromise(createAsyncPromise));\r\n return _raceAsyncCreator.v(values, timeout);\r\n}\r\n/**\r\n * The `createAsyncAnyPromise` method takes an array of promises as input and returns a single Promise.\r\n * This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.\r\n * It rejects when all of the input's promises reject (including when an empty iterable is passed), with an\r\n * AggregateError containing an array of rejection reasons.\r\n * @since 0.5.0\r\n * @group Async\r\n * @group Promise\r\n * @group Any\r\n * @param values - An Array promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A new Promise that is:\r\n * - Already rejected, if the iterable passed is empty.\r\n * - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value\r\n * is the fulfillment value of the first promise that was fulfilled.\r\n * - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is\r\n * an AggregateError containing an array of rejection reasons in its errors property. The errors are in the\r\n * order of the promises passed, regardless of completion order. If the iterable passed is non-empty but\r\n * contains no pending promises, the returned promise is still asynchronously (instead of synchronously)\r\n * rejected.\r\n */\r\nexport function createAsyncAnyPromise(values, timeout) {\r\n !_anyAsyncCreator && (_anyAsyncCreator = _createAnyPromise(createAsyncPromise));\r\n return _anyAsyncCreator.v(values, timeout);\r\n}\r\n//# sourceMappingURL=asyncPromise.js.map","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 NevWare21 Solutions LLC\r\n * Licensed under the MIT license.\r\n */\r\nimport { createAsyncPromise } from \"./asyncPromise\";\r\nimport { _createAllPromise, _createAllSettledPromise, _createAnyPromise, _createRacePromise, _createRejectedPromise, _createResolvedPromise } from \"./base\";\r\nimport { STRING_STATES } from \"../internal/state\";\r\nimport { dumpObj, isFunction, objDefineProp, throwTypeError, getInst, createCachedValue, safe } from \"@nevware21/ts-utils\";\r\nimport { STR_PROMISE } from \"../internal/constants\";\r\n/**\r\n * @internal\r\n * @ignore\r\n * Flag to determine if the native Promise class should be used if available, used for testing purposes.\r\n */\r\nvar _useNative = true;\r\n/**\r\n * @internal\r\n * @ignore\r\n * Cached value for the native Promise class\r\n */\r\nvar _promiseCls;\r\n/**\r\n * @internal\r\n * @ignore\r\n * Cached value for the `Promise.all` method\r\n */\r\nvar _allCreator;\r\n/**\r\n * @internal\r\n * @ignore\r\n * Cached value for the `Promise.allSettled` method\r\n */\r\nvar _allNativeSettledCreator;\r\n/**\r\n * @internal\r\n * @ignore\r\n * Cached value for the `Promise.race` method\r\n */\r\nvar _raceNativeCreator;\r\n/**\r\n * @internal\r\n * @ignore\r\n * Cached value for the `Promise.any` method\r\n */\r\nvar _anyNativeCreator;\r\n/**\r\n * @internal\r\n * @ignore\r\n * Test Hook function to clear the cached values and set whether to use the native Promise class\r\n * @param useNative\r\n */\r\nexport function _clearPromiseCache(useNative) {\r\n //#ifdef _DEBUG\r\n //#:(!_DEBUG) _useNative = !!useNative;\r\n //#:(!_DEBUG) _promiseCls = null as any;\r\n //#:(!_DEBUG) _allCreator = null as any;\r\n //#:(!_DEBUG) _allNativeSettledCreator = null as any;\r\n //#:(!_DEBUG) _raceNativeCreator = null as any;\r\n //#:(!_DEBUG) _anyNativeCreator = null as any;\r\n //#endif\r\n}\r\n/*#__NO_SIDE_EFFECTS__*/\r\nexport function _createNativePromiseHelper(name, func) {\r\n !_promiseCls && (_promiseCls = createCachedValue((_useNative && safe(getInst, [STR_PROMISE]).v) || null));\r\n if (_promiseCls.v && _promiseCls.v[name]) {\r\n return createCachedValue(function (input, timeout) {\r\n return createNativePromise(function (resolve, reject) {\r\n _promiseCls.v[name](input).then(resolve, reject);\r\n });\r\n });\r\n }\r\n return func();\r\n}\r\n/**\r\n * Creates a Promise instance that when resolved or rejected will execute it's pending chained operations using the\r\n * available native Promise implementation.\r\n * If runtime does not support native `Promise` class (or no polyfill is available) this function will fallback to using\r\n * `createAsyncPromise` which will resolve them __asynchronously__ using the optional provided timeout value to\r\n * schedule when the chained items will be executed.\r\n * @group Alias\r\n * @group Promise\r\n * @group Native\r\n * @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will\r\n * cause the promise to be rejected. The return value of the executor is always ignored\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport function createNativePromise(executor, timeout) {\r\n !_promiseCls && (_promiseCls = createCachedValue((_useNative && safe(getInst, [STR_PROMISE]).v) || null));\r\n var PrmCls = _promiseCls.v;\r\n if (!PrmCls) {\r\n return createAsyncPromise(executor);\r\n }\r\n if (!isFunction(executor)) {\r\n throwTypeError(STR_PROMISE + \": executor is not a function - \" + dumpObj(executor));\r\n }\r\n var _state = 0 /* ePromiseState.Pending */;\r\n function _strState() {\r\n return STRING_STATES[_state];\r\n }\r\n var thePromise = new PrmCls(function (resolve, reject) {\r\n function _resolve(value) {\r\n _state = 2 /* ePromiseState.Resolved */;\r\n resolve(value);\r\n }\r\n function _reject(reason) {\r\n _state = 3 /* ePromiseState.Rejected */;\r\n reject(reason);\r\n }\r\n executor(_resolve, _reject);\r\n });\r\n objDefineProp(thePromise, \"state\", {\r\n get: _strState\r\n });\r\n return thePromise;\r\n}\r\n/**\r\n * Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional\r\n * provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.\r\n * It rejects immediately upon any of the input promises rejected or non-promises throwing an error,\r\n * and will reject with this first rejection message / error.\r\n * If the runtime doesn't support the Promise.all it will fallback back to an asynchronous Promise implementation.\r\n * @group Alias\r\n * @group Promise\r\n * @group All\r\n * @group Native\r\n * @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout\r\n * @returns\r\n * \r\n *
\r\n */\r\nexport function createNativeAllPromise(input, timeout) {\r\n !_allCreator && (_allCreator = _createNativePromiseHelper(\"all\", function () { return createCachedValue(_createAllPromise(createNativePromise)); }));\r\n return _allCreator.v(input, timeout);\r\n}\r\n/**\r\n * Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).\r\n * @group Alias\r\n * @group Promise\r\n * @group Resolved\r\n * @group Native\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createNativeResolvedPromise = /*#__PURE__*/ _createResolvedPromise(createNativePromise);\r\n/**\r\n * Returns a single asynchronous Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the optional timeout value to schedule\r\n * when then chained items will be executed. (eg. `catch()`; `finally()`).\r\n * @group Alias\r\n * @group Promise\r\n * @group Rejected\r\n * @group Native\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createNativeRejectedPromise = /*#__PURE__*/ _createRejectedPromise(createNativePromise);\r\n/**\r\n * Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations using {@link createNativePromise native}\r\n * environment promise implementation, if the runtime does not provide any native then the optional provided\r\n * timeout value will be used to schedule when the chained items will be executed or if the input contains no promises.\r\n * It will resolve only after all of the input promises have either resolved or rejected, and will resolve with an array\r\n * of {@link IPromiseResult } objects that each describe the outcome of each promise.\r\n * @since 0.5.0\r\n * @group Alias\r\n * @group Promise\r\n * @group AllSettled\r\n * @group Native\r\n * @param input - An array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.\r\n *\r\n * @example\r\n * ```ts\r\n * const promises = [\r\n * createNativeResolvedPromise(1),\r\n * createNativeResolvedPromise(2),\r\n * createNativeResolvedPromise(3),\r\n * createNativeRejectedPromise(\"error\"),\r\n * ];\r\n *\r\n * const results = await createNativeAllSettledPromise(promises);\r\n *\r\n * // results is:\r\n * // [\r\n * // { status: \"fulfilled\", value: 1 },\r\n * // { status: \"fulfilled\", value: 2 },\r\n * // { status: \"fulfilled\", value: 3 },\r\n * // { status: \"rejected\", reason: \"error\" }\r\n * // ]\r\n * ```\r\n */\r\nexport function createNativeAllSettledPromise(input, timeout) {\r\n !_allNativeSettledCreator && (_allNativeSettledCreator = _createNativePromiseHelper(\"allSettled\", function () { return _createAllSettledPromise(createNativePromise); }));\r\n return _allNativeSettledCreator.v(input, timeout);\r\n}\r\n/**\r\n * The `createNativeRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise\r\n * settles with the eventual state of the first promise that settles.\r\n * @description The `createNativeRacePromise` method is one of the promise concurrency methods. It's useful when you want the first\r\n * async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).\r\n * If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to\r\n * the first of these values found in the iterable.\r\n * @since 0.5.0\r\n * @group Alias\r\n * @group Promise\r\n * @group Race\r\n * @group Native\r\n * @param values - An the array of promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the\r\n * first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever\r\n * if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle\r\n * asynchronously.\r\n */\r\nexport function createNativeRacePromise(values, timeout) {\r\n !_raceNativeCreator && (_raceNativeCreator = _createNativePromiseHelper(\"race\", function () { return _createRacePromise(createNativePromise); }));\r\n return _raceNativeCreator.v(values, timeout);\r\n}\r\n/**\r\n * The `createNativeAnyPromise` method takes an array of promises as input and returns a single Promise.\r\n * This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.\r\n * It rejects when all of the input's promises reject (including when an empty iterable is passed), with an\r\n * AggregateError containing an array of rejection reasons.\r\n * @since 0.5.0\r\n * @group Alias\r\n * @group Promise\r\n * @group Any\r\n * @group Native\r\n * @param values - An Array promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A new Promise that is:\r\n * - Already rejected, if the iterable passed is empty.\r\n * - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value\r\n * is the fulfillment value of the first promise that was fulfilled.\r\n * - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is\r\n * an AggregateError containing an array of rejection reasons in its errors property. The errors are in the\r\n * order of the promises passed, regardless of completion order. If the iterable passed is non-empty but\r\n * contains no pending promises, the returned promise is still asynchronously (instead of synchronously)\r\n * rejected.\r\n */\r\nexport function createNativeAnyPromise(values, timeout) {\r\n !_anyNativeCreator && (_anyNativeCreator = _createNativePromiseHelper(\"any\", function () { return _createAnyPromise(createNativePromise); }));\r\n return _anyNativeCreator.v(values, timeout);\r\n}\r\n//# sourceMappingURL=nativePromise.js.map","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 NevWare21 Solutions LLC\r\n * Licensed under the MIT license.\r\n */\r\nimport { isUndefined } from \"@nevware21/ts-utils\";\r\nimport { _createAllPromise, _createAllSettledPromise, _createAnyPromise, _createPromise, _createRacePromise, _createRejectedPromise, _createResolvedPromise } from \"./base\";\r\nimport { idleItemProcessor } from \"./itemProcessor\";\r\nvar _defaultIdleTimeout;\r\nvar _allIdleSettledCreator;\r\nvar _raceIdleCreator;\r\nvar _anyIdleCreator;\r\n/**\r\n * Sets the global default idle timeout / deadline to use when no timeout is passed during promise creation.\r\n * @param idleDeadline - Specifies the time in milliseconds to use as the idle timeout / deadline by when any\r\n * outstanding chained items should be executed.\r\n * @group Idle\r\n */\r\nexport function setDefaultIdlePromiseTimeout(idleDeadline) {\r\n _defaultIdleTimeout = idleDeadline;\r\n}\r\n/**\r\n * @deprecated Use `setDefaultIdlePromiseTimeout` instead\r\n * Sets the global default idle timeout / deadline to use when no timeout is passed during promise creation.\r\n * @param idleDeadline - Specifies the time in milliseconds to use as the idle timeout / deadline by when any\r\n * outstanding chained items should be executed.\r\n * @group Idle\r\n */\r\nexport var setDefaultIdleTimeout = ( /*#__PURE__*/setDefaultIdlePromiseTimeout);\r\n/**\r\n * Creates an idle Promise instance that when resolved or rejected will execute it's pending chained operations\r\n * __asynchronously__ using the `requestIdleCallback` API (if available) with the optional provided timeout value to\r\n * schedule when the chained items will be executed. When `requestIdleCallback` is not available this becomes the same as\r\n * `createAsyncPromise` which uses `setTimeout` to schedule executions.\r\n * @group Idle\r\n * @group Promise\r\n * @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will\r\n * cause the promise to be rejected. The return value of the executor is always ignored\r\n * @param timeout - Optional deadline timeout to wait before processing the items, defaults to undefined. If the number of\r\n * milliseconds represented by this parameter has elapsed and the callback has not already been called, then a task to execute\r\n * the callback is queued in the event loop (even if doing so risks causing a negative performance impact). timeout must be a\r\n * positive value or it is ignored.\r\n */\r\nexport function createIdlePromise(executor, timeout) {\r\n var theTimeout = isUndefined(timeout) ? _defaultIdleTimeout : timeout;\r\n return _createPromise(createIdlePromise, idleItemProcessor(theTimeout), executor, theTimeout);\r\n}\r\n/**\r\n * Returns an idle Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations __asynchronously__\r\n * using the `requestIdleCallback` API (if available) with the optional provided timeout value to\r\n * schedule when the chained items will be executed.\r\n * It rejects immediately upon any of the input promises rejected or non-promises throwing an error,\r\n * and will reject with this first rejection message / error.\r\n * When resolved or rejected any additional chained operations will execute __asynchronously__ using\r\n * the `requestIdleCallback` API (if available) with the optional provided timeout value to schedule\r\n * when the chained items will be executed. (eg. `then()`; `catch()`; `finally()`).\r\n * @group Idle\r\n * @group Promise\r\n * @group All\r\n * @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout\r\n * @returns\r\n * \r\n *
\r\n */\r\nexport var createIdleAllPromise = /*#__PURE__*/ _createAllPromise(createIdlePromise);\r\n/**\r\n * Returns an idle Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the\r\n * `requestIdleCallback` API (if available) with the optional provided timeout value to schedule when\r\n * the chained items will be executed. (eg. `then()`; `finally()`).\r\n * @group Idle\r\n * @group Promise\r\n * @group Resolved\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createIdleResolvedPromise = /*#__PURE__*/ _createResolvedPromise(createIdlePromise);\r\n/**\r\n * Returns an idle Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the o`requestIdleCallback` API\r\n * (if available) with the optional provided timeout value to schedule when the chained items will\r\n * be executed. (eg. `catch()`; `finally()`).\r\n * @group Idle\r\n * @group Promise\r\n * @group Rejected\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createIdleRejectedPromise = /*#__PURE__*/ _createRejectedPromise(createIdlePromise);\r\n/**\r\n * Returns a single Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations based on the\r\n * {@link createIdlePromise idle} promise implementation. Any chained operations will execute\r\n * __asynchronously__ when the environment is idle as the final operation pending promises have resolved,\r\n * or if the input contains no promises. It will resolve only after all of the input promises have either\r\n * resolved or rejected, and will resolve with an array of {@link IPromiseResult } objects that each describe\r\n * the outcome of each promise.\r\n * @since 0.5.0\r\n * @group Idle\r\n * @group Promise\r\n * @group AllSettled\r\n * @param input - An array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.\r\n *\r\n * @example\r\n * ```ts\r\n * const promises = [\r\n * createResolvedPromise(1),\r\n * createResolvedPromise(2),\r\n * createResolvedPromise(3),\r\n * createRejectedPromise(\"error\"),\r\n * ];\r\n *\r\n * const results = await createAllSettledPromise(promises);\r\n *\r\n * // results is:\r\n * // [\r\n * // { status: \"fulfilled\", value: 1 },\r\n * // { status: \"fulfilled\", value: 2 },\r\n * // { status: \"fulfilled\", value: 3 },\r\n * // { status: \"rejected\", reason: \"error\" }\r\n * // ]\r\n * ```\r\n */\r\nexport function createIdleAllSettledPromise(input, timeout) {\r\n !_allIdleSettledCreator && (_allIdleSettledCreator = _createAllSettledPromise(createIdlePromise));\r\n return _allIdleSettledCreator.v(input, timeout);\r\n}\r\n/**\r\n * The `createIdleRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise\r\n * settles with the eventual state of the first promise that settles.\r\n * @description The `createIdleRacePromise` method is one of the promise concurrency methods. It's useful when you want the first\r\n * async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).\r\n * If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to\r\n * the first of these values found in the iterable.\r\n * @since 0.5.0\r\n * @group Idle\r\n * @group Promise\r\n * @group Race\r\n * @param values - An the array of promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the\r\n * first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever\r\n * if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle\r\n * asynchronously when the system detects that the runtime is idle.\r\n */\r\nexport function createIdleRacePromise(values, timeout) {\r\n !_raceIdleCreator && (_raceIdleCreator = _createRacePromise(createIdlePromise));\r\n return _raceIdleCreator.v(values, timeout);\r\n}\r\n/**\r\n * The `createIdleAnyPromise` method takes an array of promises as input and returns a single Promise.\r\n * This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.\r\n * It rejects when all of the input's promises reject (including when an empty iterable is passed), with an\r\n * AggregateError containing an array of rejection reasons.\r\n * @since 0.5.0\r\n * @group Idle\r\n * @group Promise\r\n * @group Any\r\n * @param values - An Array promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A new Promise that is:\r\n * - Already rejected, if the iterable passed is empty.\r\n * - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value\r\n * is the fulfillment value of the first promise that was fulfilled.\r\n * - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is\r\n * an AggregateError containing an array of rejection reasons in its errors property. The errors are in the\r\n * order of the promises passed, regardless of completion order. If the iterable passed is non-empty but\r\n * contains no pending promises, the returned promise is still asynchronously (instead of synchronously)\r\n * rejected.\r\n */\r\nexport function createIdleAnyPromise(values, timeout) {\r\n !_anyIdleCreator && (_anyIdleCreator = _createAnyPromise(createIdlePromise));\r\n return _anyIdleCreator.v(values, timeout);\r\n}\r\n//# sourceMappingURL=idlePromise.js.map","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 NevWare21 Solutions LLC\r\n * Licensed under the MIT license.\r\n */\r\nimport { createCachedValue } from \"@nevware21/ts-utils\";\r\nimport { _createAllPromise, _createAllSettledPromise, _createAnyPromise, _createRacePromise, _createRejectedPromise, _createResolvedPromise } from \"./base\";\r\nimport { createNativePromise } from \"./nativePromise\";\r\nvar _promiseCreator;\r\nvar _allSettledCreator;\r\nvar _raceCreator;\r\nvar _anyCreator;\r\n/**\r\n * Set the default promise implementation to use when calling `createPromise`; `createAllPromise`; `createResolvedPromise`\r\n * and `createRejectedPromise`. This is effective a global value and changing this will affect ALL callers of these\r\n * functions, as such these functions should only be used when switching implementations would have not unexpected\r\n * consequences like switching from a `createSyncPromise` to `createIdlePromise` where idle promises have a possibility\r\n * of never getting called during application shutdown or during an expected timeframe.\r\n * @group Alias\r\n * @group Promise\r\n * @param creator - The creator function to call when a new promise is required.\r\n */\r\nexport function setCreatePromiseImpl(creator) {\r\n _promiseCreator = creator ? createCachedValue(creator) : null;\r\n}\r\n/**\r\n * Creates a Promise instance using the current default promise creator that when resolved or rejected will execute\r\n * it's pending chained operations.\r\n * @group Alias\r\n * @group Promise\r\n * @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will\r\n * cause the promise to be rejected. The return value of the executor is always ignored\r\n * @param timeout - [Optional] timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport function createPromise(executor, timeout) {\r\n !_promiseCreator && (_promiseCreator = createCachedValue(createNativePromise));\r\n return _promiseCreator.v.call(this, executor, timeout);\r\n}\r\n/**\r\n * Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional\r\n * provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.\r\n * It rejects immediately upon any of the input promises rejected or non-promises throwing an error,\r\n * and will reject with this first rejection message / error.\r\n * If the runtime doesn't support the Promise.all it will fallback back to an asynchronous Promise implementation.\r\n * @group Alias\r\n * @group Promise\r\n * @group All\r\n * @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout\r\n * @returns\r\n * \r\n *
\r\n */\r\nexport var createAllPromise = /*#__PURE__*/ _createAllPromise(createPromise);\r\n/**\r\n * Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).\r\n * @group Alias\r\n * @group Promise\r\n * @group Resolved\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createResolvedPromise = /*#__PURE__*/ _createResolvedPromise(createPromise);\r\n/**\r\n * Returns a single asynchronous Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the optional timeout value to schedule\r\n * when then chained items will be executed. (eg. `catch()`; `finally()`).\r\n * @group Alias\r\n * @group Promise\r\n * @group Rejected\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport var createRejectedPromise = /*#__PURE__*/ _createRejectedPromise(createPromise);\r\n/**\r\n * Returns a single Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations based on the current\r\n * promise implementation. If the current implementation is synchronous then the chained operations will\r\n * execute __synchronously__ in the same execution cycle as the final operation pending promises have resolved,\r\n * or if the input contains no promises. If the current implementation is asynchronous then the chained\r\n * operations will execute __asynchronously__ using the optional provided timeout value to schedule when the\r\n * chained items will be executed or if the input contains no promises.\r\n * It will resolve only after all of the input promises have either resolved or rejected, and will resolve with an array\r\n * of {@link IPromiseResult } objects that each describe the outcome of each promise.\r\n * @since 0.5.0\r\n * @group Alias\r\n * @group Promise\r\n * @group AllSettled\r\n * @param input - An array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.\r\n *\r\n * @example\r\n * ```ts\r\n * const promises = [\r\n * createResolvedPromise(1),\r\n * createResolvedPromise(2),\r\n * createResolvedPromise(3),\r\n * createRejectedPromise(\"error\"),\r\n * ];\r\n *\r\n * const results = await createAllSettledPromise(promises);\r\n *\r\n * // results is:\r\n * // [\r\n * // { status: \"fulfilled\", value: 1 },\r\n * // { status: \"fulfilled\", value: 2 },\r\n * // { status: \"fulfilled\", value: 3 },\r\n * // { status: \"rejected\", reason: \"error\" }\r\n * // ]\r\n * ```\r\n */\r\nexport function createAllSettledPromise(input, timeout) {\r\n !_allSettledCreator && (_allSettledCreator = _createAllSettledPromise(createPromise));\r\n return _allSettledCreator.v(input, timeout);\r\n}\r\n/**\r\n * The `createRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise\r\n * settles with the eventual state of the first promise that settles.\r\n * @description The `createRacePromise` method is one of the promise concurrency methods. It's useful when you want the first\r\n * async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).\r\n * If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to\r\n * the first of these values found in the iterable.\r\n * @since 0.5.0\r\n * @group Alias\r\n * @group Promise\r\n * @group Race\r\n * @param values - An the array of promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the\r\n * first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever\r\n * if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle\r\n * based on the current promise implementation.\r\n */\r\nexport function createRacePromise(values, timeout) {\r\n !_raceCreator && (_raceCreator = _createRacePromise(createPromise));\r\n return _raceCreator.v(values, timeout);\r\n}\r\n/**\r\n * The `createAnyPromise` method takes an array of promises as input and returns a single Promise.\r\n * This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.\r\n * It rejects when all of the input's promises reject (including when an empty iterable is passed), with an\r\n * AggregateError containing an array of rejection reasons.\r\n * @since 0.5.0\r\n * @group Alias\r\n * @group Promise\r\n * @group Any\r\n * @param values - An Array promises.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.\r\n * @returns A new Promise that is:\r\n * - Already rejected, if the iterable passed is empty.\r\n * - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value\r\n * is the fulfillment value of the first promise that was fulfilled.\r\n * - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is\r\n * an AggregateError containing an array of rejection reasons in its errors property. The errors are in the\r\n * order of the promises passed, regardless of completion order. If the iterable passed is non-empty but\r\n * contains no pending promises, the returned promise is still asynchronously (instead of synchronously)\r\n * rejected.\r\n */\r\nexport function createAnyPromise(values, timeout) {\r\n !_anyCreator && (_anyCreator = _createAnyPromise(createPromise));\r\n return _anyCreator.v(values, timeout);\r\n}\r\n//# sourceMappingURL=promise.js.map","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 NevWare21 Solutions LLC\r\n * Licensed under the MIT license.\r\n */\r\nimport { getKnownSymbol, objDefineProp } from \"@nevware21/ts-utils\";\r\nimport { createAsyncAllPromise, createAsyncAllSettledPromise, createAsyncAnyPromise, createAsyncPromise, createAsyncRacePromise, createAsyncRejectedPromise, createAsyncResolvedPromise } from \"../promise/asyncPromise\";\r\nvar toStringTagSymbol = getKnownSymbol(11 /* WellKnownSymbols.toStringTag */);\r\n/**\r\n * A full polyfill for the Promise class.\r\n * Represents the completion of an asynchronous operation, and its resulting value.\r\n * @since 0.5.0\r\n * @class\r\n * @group Polyfill\r\n * @group Promise\r\n */\r\nexport var PolyPromise = /*#__PURE__*/ (function () {\r\n /**\r\n * Creates a new Promise.\r\n * @constructor\r\n * @param executor A callback used to initialize the promise. This callback is passed two arguments:\r\n * a resolve callback used to resolve the promise with a value or the result of another promise,\r\n * and a reject callback used to reject the promise with a provided reason or error.\r\n */\r\n function PolyPromiseImpl(executor) {\r\n this._$ = createAsyncPromise(executor);\r\n if (toStringTagSymbol) {\r\n this[toStringTagSymbol] = \"Promise\";\r\n }\r\n // Re-Expose the state of the underlying promise\r\n objDefineProp(this, \"state\", {\r\n get: function () {\r\n return this._$.state;\r\n }\r\n });\r\n }\r\n /**\r\n */\r\n PolyPromiseImpl.all = createAsyncAllPromise;\r\n PolyPromiseImpl.race = createAsyncRacePromise;\r\n PolyPromiseImpl.any = createAsyncAnyPromise;\r\n PolyPromiseImpl.reject = createAsyncRejectedPromise;\r\n PolyPromiseImpl.resolve = createAsyncResolvedPromise;\r\n PolyPromiseImpl.allSettled = createAsyncAllSettledPromise;\r\n var theProto = PolyPromiseImpl.prototype;\r\n theProto.then = function (onResolved, onRejected) {\r\n return this._$.then(onResolved, onRejected);\r\n };\r\n theProto.catch = function (onRejected) {\r\n return this._$.catch(onRejected);\r\n };\r\n theProto.finally = function (onfinally) {\r\n return this._$.finally(onfinally);\r\n };\r\n return PolyPromiseImpl;\r\n}());\r\n//# sourceMappingURL=promise.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_FEATURE_OPT_IN = \"featureOptIn\"; // Count: 4\r\nexport var _DYN_ON_CFG_CHANGE_RECEIV0 = \"onCfgChangeReceive\"; // Count: 2\r\nexport var _DYN_NON_OVERRIDE_CONFIGS = \"nonOverrideConfigs\"; // Count: 2\r\nexport var _DYN_SCHEDULE_FETCH_TIMEO1 = \"scheduleFetchTimeout\"; // Count: 2\r\n//# sourceMappingURL=__DynamicConstants.js.map","import { isNullOrUndefined, isObject, objExtend, objForEachKey, setValueByKey } from \"@nevware21/ts-utils\";\r\nimport { _DYN_FEATURE_OPT_IN } from \"./__DynamicConstants\";\r\n/**\r\n * Delete a config key in the given cfg, if the config key exists in nonOverrideConfigs and its value is set to true\r\n * @param cfg cfg to modify\r\n * @param nonOverrideConfigs nonOverrideConfigs\r\n * @param curLevel cur config level, starting at 0\r\n * @param maxLevel max config level\r\n * @returns new copy of modified configs\r\n */\r\nexport function replaceByNonOverrideCfg(cfg, nonOverrideConfigs, curLevel, maxLevel) {\r\n try {\r\n var exceedMaxLevel = curLevel > maxLevel;\r\n if (exceedMaxLevel) {\r\n cfg = null;\r\n }\r\n var curCfg_1 = curLevel == 0 ? objExtend({}, cfg) : cfg; // only copy cfg at the begining level\r\n if (curCfg_1 && nonOverrideConfigs && !exceedMaxLevel) {\r\n objForEachKey(curCfg_1, function (key) {\r\n var nonOverrideVal = nonOverrideConfigs[key];\r\n if (!!nonOverrideVal) {\r\n if (isObject(curCfg_1[key]) && isObject(nonOverrideVal)) {\r\n curCfg_1[key] = replaceByNonOverrideCfg(curCfg_1[key], nonOverrideVal, ++curLevel, maxLevel);\r\n }\r\n else {\r\n delete curCfg_1[key];\r\n }\r\n }\r\n });\r\n }\r\n return curCfg_1;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n // if errors happen, do nothing\r\n return cfg;\r\n}\r\n// CDN Mode, value = B (CDN value = B)\r\n// |--------------------------------------------------------------------------|-----------|\r\n// | | none | disabled | enabled | forceOn | forceOff |\r\n// | ------------------ | ----------- | ----------- | ----------- | --------- | --------- |\r\n// | User Mode, value = A | none | none | disabled | enabled | enabled | disabled |\r\n// (user Value = A) | disabled | disabled | disabled | disabled | enabled | disabled |\r\n// | enabled | enabled | disabled | enabled | enabled | disabled |\r\n// | none(blockCdn) | none | none | none | none | none |\r\n// | disabled(blockCdn) | disabled | disabled | disabled | disabled | disabled |\r\n// | enabled(blockCdn) | enabled | enabled | enabled | enabled | enabled |\r\n// This matrix identifies how feature based overrides are selected (if present)\r\n// cdn Mode (cdn Value = B)\r\n// |---------------------------------------------------------------------------|\r\n// | | none | disabled | enabled | forceOn | forceOff |\r\n// | ------------------ | ---------| ---------| ---------| ---------|----------|\r\n// | User Mode | none | A | A | A || B | B || A | B || A |\r\n// (user Value = A) | disabled | A | A | A | B || A | B || A |\r\n// | enabled | A | A | A || B | B || A | B || A |\r\n// | none(blockCdn) | A | A | A | A | A |\r\n// | disabled(blockCdn) | A | A | A | A | A |\r\n// | enabled(blockCdn) | A | A | A | A | A |\r\n// Note:\r\n// Where the \"value\" is an object (map) of encoded key/values which will be used to override the real configuration\r\n// A = either the user supplied enable/disable value (via the `config.featureOptIn[name]`) or if not defined by the user the SDK defaults of the same.\r\n// B = The enable/disable value obtained from the CDN for the named feature\r\n// These are evaluated based on the above matrix to either\r\n// - A (Always the user/sdk value)\r\n// - B (Always the value from the CDN)\r\n// - A || B (If A is null or undefined use the value from the CDN (B) otherwise A)\r\n// - B || A (If B is null or undefined use the user/SDK value otherwise use the value from the CDN)\r\n//\r\n// The result of the value may also be null / undefined, which means there are no overrides to apply when the feature is enabled\r\nvar F = \"featureOptIn.\";\r\nvar M = \".mode\";\r\nvar ON = \".onCfg\";\r\nvar OFF = \".offCfg\";\r\nexport function resolveCdnFeatureCfg(field, cdnCfg, userOptInDetails) {\r\n var _a;\r\n // cdn conifg value\r\n if (!cdnCfg || !cdnCfg.enabled) {\r\n return null;\r\n }\r\n var cdnFt = (cdnCfg[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */] || {})[field] || { mode: 1 /* CdnFeatureMode.none */ };\r\n var cdnM = cdnFt.mode;\r\n var cdnOnV = cdnFt.onCfg;\r\n var cdnOffV = cdnFt.offCfg;\r\n var userFt = (userOptInDetails || {})[field] || { mode: 2 /* FeatureOptInMode.disable */ }; // default user mode is disable\r\n var userM = userFt.mode;\r\n var userOnV = userFt.onCfg;\r\n var userOffV = userFt.offCfg;\r\n var blockCdn = !!userFt.blockCdnCfg;\r\n var mFld = F + field + M;\r\n var onFld = F + field + ON;\r\n var offFld = F + field + OFF;\r\n var mode = userM;\r\n var onV = userOnV;\r\n var offV = userOffV;\r\n if (!blockCdn) {\r\n if (cdnM === 4 /* CdnFeatureMode.forceOn */ || cdnM === 5 /* CdnFeatureMode.forceOff */) {\r\n mode = (cdnM == 4 /* CdnFeatureMode.forceOn */ ? 3 /* FeatureOptInMode.enable */ : 2 /* FeatureOptInMode.disable */);\r\n onV = cdnOnV || userOnV;\r\n offV = cdnOffV || userOffV;\r\n }\r\n else if (cdnM === 2 /* CdnFeatureMode.disable */ || userM === 2 /* FeatureOptInMode.disable */) {\r\n mode = 2 /* FeatureOptInMode.disable */;\r\n onV = userOnV || cdnOnV;\r\n offV = userOffV || cdnOffV;\r\n }\r\n else if (cdnM === 3 /* CdnFeatureMode.enable */) {\r\n mode = 3 /* FeatureOptInMode.enable */;\r\n onV = userOnV || cdnOnV;\r\n offV = userOffV || cdnOffV;\r\n }\r\n else if (cdnM === 1 /* CdnFeatureMode.none */ && userM === 1 /* FeatureOptInMode.none */) {\r\n mode = 1 /* FeatureOptInMode.none */;\r\n }\r\n }\r\n return _a = {},\r\n _a[mFld] = mode,\r\n _a[onFld] = onV,\r\n _a[offFld] = offV,\r\n _a;\r\n}\r\n// helper function to get cdn config with opt-in features\r\nexport function applyCdnfeatureCfg(cdnCfg, core) {\r\n try {\r\n if (!cdnCfg || !cdnCfg.enabled) {\r\n return null;\r\n }\r\n if (!cdnCfg[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */]) {\r\n return cdnCfg.config;\r\n }\r\n var optInMap = cdnCfg[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */];\r\n var cdnConfig_1 = cdnCfg.config || {};\r\n objForEachKey(optInMap, function (key) {\r\n var featureVal = resolveCdnFeatureCfg(key, cdnCfg, core.config[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */]);\r\n if (!isNullOrUndefined(featureVal)) {\r\n objForEachKey(featureVal, function (config, val) {\r\n setValueByKey(cdnConfig_1, config, val);\r\n });\r\n _overrideCdnCfgByFeature(key, featureVal, cdnConfig_1);\r\n }\r\n });\r\n return cdnConfig_1;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n}\r\nfunction _overrideCdnCfgByFeature(field, ftVal, config) {\r\n var mode = ftVal[F + field + M];\r\n var val = ftVal[F + field + ON];\r\n var dVal = ftVal[F + field + OFF];\r\n var target = null;\r\n if (mode === 3 /* FeatureOptInMode.enable */) {\r\n target = val;\r\n }\r\n if (mode === 2 /* FeatureOptInMode.disable */) {\r\n target = dVal;\r\n }\r\n if (target) {\r\n objForEachKey(target, function (key, cfg) {\r\n setValueByKey(config, key, cfg);\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=CfgSyncHelperFuncs.js.map","/**\r\n* CfgSyncPlugin.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nvar _a;\r\nimport { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { BaseTelemetryPlugin, createProcessTelemetryContext, createUniqueNamespace, eventOff, eventOn, getGlobal, getJSON, isFetchSupported, isXhrSupported, mergeEvtNamespace, onConfigChange, sendCustomEvent } from \"@microsoft/applicationinsights-core-js\";\r\nimport { doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { isFunction, isNullOrUndefined, isPlainObject, objDeepFreeze, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { applyCdnfeatureCfg, replaceByNonOverrideCfg } from \"./CfgSyncHelperFuncs\";\r\nimport { _DYN_NON_OVERRIDE_CONFIGS, _DYN_ON_CFG_CHANGE_RECEIV0, _DYN_SCHEDULE_FETCH_TIMEO1 } from \"./__DynamicConstants\";\r\nvar EVENT_NAME = \"ai_cfgsync\";\r\nvar STR_GET_METHOD = \"GET\";\r\nvar FETCH_TIMEOUT = 1800000; // 30 minutes\r\nvar udfVal = undefined;\r\nvar defaultNonOverrideCfg = { instrumentationKey: true, connectionString: true, endpointUrl: true };\r\nvar _defaultConfig = objDeepFreeze((_a = {\r\n syncMode: 1 /* ICfgSyncMode.Broadcast */,\r\n blkCdnCfg: udfVal,\r\n customEvtName: udfVal,\r\n cfgUrl: udfVal,\r\n overrideSyncFn: udfVal,\r\n overrideFetchFn: udfVal\r\n },\r\n _a[_DYN_ON_CFG_CHANGE_RECEIV0 /* @min:onCfgChangeReceive */] = udfVal,\r\n _a[_DYN_SCHEDULE_FETCH_TIMEO1 /* @min:scheduleFetchTimeout */] = FETCH_TIMEOUT,\r\n _a[_DYN_NON_OVERRIDE_CONFIGS /* @min:nonOverrideConfigs */] = defaultNonOverrideCfg,\r\n _a));\r\nvar CfgSyncPlugin = /** @class */ (function (_super) {\r\n __extends(CfgSyncPlugin, _super);\r\n function CfgSyncPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 198;\r\n _this.identifier = \"AppInsightsCfgSyncPlugin\";\r\n var _extensionConfig;\r\n var _mainConfig; // throttle config should be wrapped in IConfiguration\r\n var _evtName;\r\n var _evtNamespace;\r\n var _cfgUrl;\r\n var _timeoutHandle;\r\n var _receiveChanges;\r\n var _broadcastChanges;\r\n var _blkCdnCfg;\r\n var _fetchTimeout;\r\n var _retryCnt;\r\n var _onCfgChangeReceive;\r\n var _nonOverrideConfigs;\r\n var _fetchFn;\r\n var _overrideFetchFn;\r\n var _overrideSyncFn;\r\n var _paused = false;\r\n dynamicProto(CfgSyncPlugin, _this, function (_self, _base) {\r\n _initDefaults();\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n _base.initialize(config, core, extensions, pluginChain);\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());\r\n _populateDefaults(config);\r\n };\r\n _self.getCfg = function () {\r\n return _mainConfig;\r\n };\r\n _self.pause = function () {\r\n _paused = true;\r\n _clearScheduledTimer();\r\n };\r\n _self.resume = function () {\r\n _paused = false;\r\n _setupTimer();\r\n };\r\n // used for V2 to manaully trigger config udpate\r\n _self.setCfg = function (config) {\r\n return _setCfg(config);\r\n };\r\n _self.sync = function (customDetails) {\r\n return _sendCfgsyncEvents(customDetails);\r\n };\r\n _self.updateEventListenerName = function (eventName) {\r\n return _updateEventListenerName(eventName);\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n _eventOff();\r\n _clearScheduledTimer();\r\n _initDefaults();\r\n };\r\n _self[\"_getDbgPlgTargets\"] = function () {\r\n return [_broadcastChanges, _receiveChanges, _evtName, _blkCdnCfg, _nonOverrideConfigs];\r\n };\r\n function _initDefaults() {\r\n _mainConfig = null;\r\n _evtName = null;\r\n _evtNamespace = null;\r\n _cfgUrl = null;\r\n _receiveChanges = null;\r\n _broadcastChanges = null;\r\n _nonOverrideConfigs = null;\r\n _timeoutHandle = null;\r\n _fetchTimeout = null;\r\n _retryCnt = null;\r\n _blkCdnCfg = null;\r\n _overrideFetchFn = null;\r\n _overrideSyncFn = null;\r\n _onCfgChangeReceive = null;\r\n }\r\n function _populateDefaults(config) {\r\n var identifier = _self.identifier;\r\n var core = _self.core;\r\n _self._addHook(onConfigChange(config, function () {\r\n var ctx = createProcessTelemetryContext(null, config, core);\r\n _extensionConfig = ctx.getExtCfg(identifier, _defaultConfig);\r\n var preBlkCdn = _blkCdnCfg;\r\n _blkCdnCfg = !!_extensionConfig.blkCdnCfg;\r\n // avoid initial call\r\n if (!isNullOrUndefined(preBlkCdn) && preBlkCdn !== _blkCdnCfg) {\r\n if (!_blkCdnCfg && _cfgUrl) {\r\n _fetchFn && _fetchFn(_cfgUrl, _onFetchComplete, _broadcastChanges);\r\n }\r\n else {\r\n _clearScheduledTimer();\r\n }\r\n }\r\n if (isNullOrUndefined(_receiveChanges)) {\r\n _receiveChanges = _extensionConfig.syncMode === 2 /* ICfgSyncMode.Receive */;\r\n }\r\n if (isNullOrUndefined(_broadcastChanges)) {\r\n _broadcastChanges = _extensionConfig.syncMode === 1 /* ICfgSyncMode.Broadcast */;\r\n }\r\n var newEvtName = _extensionConfig.customEvtName || EVENT_NAME;\r\n if (_evtName !== newEvtName) {\r\n if (_receiveChanges) {\r\n _updateEventListenerName(newEvtName);\r\n }\r\n else {\r\n _eventOff();\r\n _evtName = newEvtName;\r\n }\r\n }\r\n if (isNullOrUndefined(_cfgUrl)) {\r\n _cfgUrl = _extensionConfig.cfgUrl;\r\n }\r\n // if cfgUrl is set, we will ignore core config change\r\n if (!_cfgUrl) {\r\n _mainConfig = config;\r\n if (_broadcastChanges) {\r\n _sendCfgsyncEvents();\r\n }\r\n }\r\n }));\r\n _overrideSyncFn = _extensionConfig.overrideSyncFn;\r\n _overrideFetchFn = _extensionConfig.overrideFetchFn;\r\n _onCfgChangeReceive = _extensionConfig[_DYN_ON_CFG_CHANGE_RECEIV0 /* @min:%2eonCfgChangeReceive */];\r\n _nonOverrideConfigs = _extensionConfig[_DYN_NON_OVERRIDE_CONFIGS /* @min:%2enonOverrideConfigs */]; // override values should not be changed\r\n _fetchTimeout = _extensionConfig[_DYN_SCHEDULE_FETCH_TIMEO1 /* @min:%2escheduleFetchTimeout */];\r\n _fetchFn = _getFetchFnInterface();\r\n _retryCnt = 0;\r\n // NOT support cfgURL change to avoid mutiple fetch calls\r\n if (_cfgUrl && !_blkCdnCfg) {\r\n _fetchFn && _fetchFn(_cfgUrl, _onFetchComplete, _broadcastChanges);\r\n }\r\n }\r\n function _setCfg(config, isAutoSync) {\r\n if (config) {\r\n _mainConfig = config;\r\n if (!!isAutoSync && !_paused) {\r\n return _sendCfgsyncEvents();\r\n }\r\n if (_receiveChanges && !_paused) {\r\n _self.core.updateCfg(config);\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n function _eventOff() {\r\n try {\r\n var global_1 = getGlobal();\r\n if (global_1) {\r\n eventOff(global_1, null, null, _evtNamespace);\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n function _sendCfgsyncEvents(customDetails) {\r\n try {\r\n if (!!_overrideSyncFn && isFunction(_overrideSyncFn)) {\r\n return _overrideSyncFn(_mainConfig, customDetails);\r\n }\r\n return sendCustomEvent(_evtName, _mainConfig, customDetails);\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n function _updateEventListenerName(name) {\r\n try {\r\n _eventOff();\r\n if (name) {\r\n _evtName = name;\r\n _addEventListener();\r\n }\r\n return true;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n function _getFetchFnInterface() {\r\n var _fetchFn = _overrideFetchFn;\r\n if (isNullOrUndefined(_fetchFn)) {\r\n if (isFetchSupported()) {\r\n _fetchFn = _fetchSender;\r\n }\r\n else if (isXhrSupported()) {\r\n _fetchFn = _xhrSender;\r\n }\r\n }\r\n return _fetchFn;\r\n }\r\n function _fetchSender(url, oncomplete, isAutoSync) {\r\n var global = getGlobal();\r\n var fetchFn = (global && global.fetch) || null;\r\n if (url && fetchFn && isFunction(fetchFn)) {\r\n try {\r\n var init = {\r\n method: STR_GET_METHOD\r\n };\r\n var request = new Request(url, init);\r\n doAwaitResponse(fetch(request), function (result) {\r\n var response = result.value;\r\n if (!result.rejected) {\r\n if (response.ok) {\r\n doAwaitResponse(response.text(), function (res) {\r\n _doOnComplete(oncomplete, response.status, res.value, isAutoSync);\r\n });\r\n }\r\n else {\r\n _doOnComplete(oncomplete, response.status, null, isAutoSync);\r\n }\r\n }\r\n else {\r\n _doOnComplete(oncomplete, 400);\r\n }\r\n });\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n }\r\n function _xhrSender(url, oncomplete, isAutoSync) {\r\n try {\r\n var xhr_1 = new XMLHttpRequest();\r\n xhr_1.open(STR_GET_METHOD, url);\r\n xhr_1.onreadystatechange = function () {\r\n if (xhr_1.readyState === XMLHttpRequest.DONE) {\r\n _doOnComplete(oncomplete, xhr_1.status, xhr_1.responseText, isAutoSync);\r\n }\r\n };\r\n xhr_1.onerror = function () {\r\n _doOnComplete(oncomplete, 400);\r\n };\r\n xhr_1.ontimeout = function () {\r\n _doOnComplete(oncomplete, 400);\r\n };\r\n xhr_1.send();\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n function _onFetchComplete(status, response, isAutoSync) {\r\n try {\r\n if (status >= 200 && status < 400 && response) {\r\n _retryCnt = 0; // any successful response will reset retry count to 0\r\n var JSON_1 = getJSON();\r\n if (JSON_1) {\r\n var cdnCfg = JSON_1.parse(response); //comments are not allowed\r\n var cfg = applyCdnfeatureCfg(cdnCfg, _self.core);\r\n var newCfg = cfg && isPlainObject(cfg) && _replaceTartgetByKeys(cfg);\r\n newCfg && _setCfg(newCfg, isAutoSync);\r\n //cfg && _setCfg(cfg, isAutoSync);\r\n }\r\n }\r\n else {\r\n _retryCnt++;\r\n }\r\n if (_retryCnt < 3) {\r\n _setupTimer();\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n function _doOnComplete(oncomplete, status, response, isAutoSync) {\r\n try {\r\n oncomplete(status, response, isAutoSync);\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n function _addEventListener() {\r\n if (_receiveChanges) {\r\n var global_2 = getGlobal();\r\n if (global_2) {\r\n try {\r\n eventOn(global_2, _evtName, function (event) {\r\n // TODO: add more validation here\r\n // may include a \"name\" or some other features to check\r\n var cfgEvent = event && event.detail;\r\n if (_onCfgChangeReceive && cfgEvent) {\r\n _onCfgChangeReceive(cfgEvent);\r\n }\r\n else {\r\n var cfg = cfgEvent && cfgEvent.cfg;\r\n var newCfg = cfg && isPlainObject(cfg) && _replaceTartgetByKeys(cfg);\r\n newCfg && _setCfg(newCfg);\r\n }\r\n }, _evtNamespace, true);\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n }\r\n }\r\n // 4 levels\r\n function _replaceTartgetByKeys(cfg, level) {\r\n var _cfg = null;\r\n try {\r\n if (cfg) {\r\n _cfg = replaceByNonOverrideCfg(cfg, _nonOverrideConfigs, 0, 5);\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return _cfg;\r\n }\r\n /**\r\n * Sets up the timer which triggers fetching cdn every 30mins after inital call\r\n */\r\n function _setupTimer() {\r\n if (!_timeoutHandle && _fetchTimeout) {\r\n _timeoutHandle = scheduleTimeout(function () {\r\n _timeoutHandle = null;\r\n _fetchFn(_cfgUrl, _onFetchComplete, _broadcastChanges);\r\n }, _fetchTimeout);\r\n _timeoutHandle.unref();\r\n }\r\n }\r\n function _clearScheduledTimer() {\r\n _timeoutHandle && _timeoutHandle.cancel();\r\n _timeoutHandle = null;\r\n _retryCnt = 0;\r\n }\r\n _self.processTelemetry = function (env, itemCtx) {\r\n _self.processNext(env, itemCtx);\r\n };\r\n });\r\n return _this;\r\n }\r\n CfgSyncPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Get current configs of current instance.\r\n * @param config current configs\r\n */\r\n CfgSyncPlugin.prototype.getCfg = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Manually set configs of current instance.\r\n * @param config new configs\r\n */\r\n CfgSyncPlugin.prototype.setCfg = function (config) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Manually broadcast configs of current instance to all other instances.\r\n * @param customDetails additional details should also be sent out to other instances\r\n */\r\n CfgSyncPlugin.prototype.sync = function (customDetails) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Manually update event name.\r\n * If current instance is the main instance, then following config changes will be sent out under this new event name.\r\n * If current instance is listener instances, it will listen to event details under this new name.\r\n * @param eventName new event name\r\n */\r\n CfgSyncPlugin.prototype.updateEventListenerName = function (eventName) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Pause the sending/receiving of events\r\n */\r\n CfgSyncPlugin.prototype.pause = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Resume the sending/receiving of events\r\n */\r\n CfgSyncPlugin.prototype.resume = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n // /**\r\n // * Add Part A fields to the event\r\n // * @param event - The event that needs to be processed\r\n // */\r\n CfgSyncPlugin.prototype.processTelemetry = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return CfgSyncPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport { CfgSyncPlugin };\r\n//# sourceMappingURL=CfgSyncPlugin.js.map","import { arrForEach, createUniqueNamespace, eventOff, eventOn, getDocument, getNavigator, getWindow, isNullOrUndefined, isUndefined, mergeEvtNamespace } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_PUSH } from \"./__DynamicConstants\";\r\nfunction _disableEvents(target, evtNamespace) {\r\n eventOff(target, null, null, evtNamespace);\r\n}\r\n/**\r\n * Create a new OfflineListener instance to monitor browser online / offline events\r\n * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance\r\n */\r\nexport function createOfflineListener(parentEvtNamespace) {\r\n var _document = getDocument();\r\n var _navigator = getNavigator(); // Gets the window.navigator or workerNavigator depending on the global\r\n var _isListening = false;\r\n var listenerList = [];\r\n // Set the initial state\r\n // rState is changed by the browser, both via events and when we check the navigator.onLine property\r\n var rState = 1 /* eOfflineValue.Online */;\r\n if (_navigator && !isNullOrUndefined(_navigator.onLine) && !_navigator.onLine) { // navigator.onLine is undefined in react-native\r\n rState = 2 /* eOfflineValue.Offline */;\r\n }\r\n // ustate is changed by the user calling setOnlineState\r\n var uState = 0 /* eOfflineValue.Unknown */;\r\n // current state would be updated each time rState or uState is changed\r\n // it is a resolved value of rState and uState\r\n var _currentState = calCurrentState();\r\n var _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"OfflineListener\"), parentEvtNamespace);\r\n try {\r\n if (_enableEvents(getWindow())) {\r\n _isListening = true;\r\n }\r\n if (_document) {\r\n // Also attach to the document.body or document\r\n var target = _document.body || _document;\r\n if (target.ononline) {\r\n if (_enableEvents(target)) {\r\n _isListening = true;\r\n }\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // this makes react-native less angry\r\n _isListening = false;\r\n }\r\n function _enableEvents(target) {\r\n var enabled = false;\r\n if (target) {\r\n enabled = eventOn(target, \"online\", _setOnline, _evtNamespace);\r\n if (enabled) {\r\n eventOn(target, \"offline\", _setOffline, _evtNamespace);\r\n }\r\n }\r\n return enabled;\r\n }\r\n function _isOnline() {\r\n return _currentState;\r\n }\r\n function calCurrentState() {\r\n if (uState === 2 /* eOfflineValue.Offline */ || rState === 2 /* eOfflineValue.Offline */) {\r\n return false;\r\n }\r\n return true; // if both unknown, then we assume the network is good\r\n }\r\n function listnerNoticeCheck() {\r\n // we were offline and are now online or we were online and now offline\r\n var newState = calCurrentState();\r\n if (_currentState !== newState) {\r\n _currentState = newState; // use the resolved state to update\r\n // send all the callbacks with the current state\r\n arrForEach(listenerList, function (callback) {\r\n var offlineState = {\r\n isOnline: _currentState,\r\n rState: rState,\r\n uState: uState\r\n };\r\n try {\r\n callback(offlineState);\r\n }\r\n catch (e) {\r\n // Do nothing, just making sure we run all of the callbacks\r\n }\r\n });\r\n }\r\n }\r\n function setOnlineState(newState) {\r\n uState = newState;\r\n listnerNoticeCheck();\r\n }\r\n function _setOnline() {\r\n rState = 1 /* eOfflineValue.Online */;\r\n listnerNoticeCheck();\r\n }\r\n function _setOffline() {\r\n rState = 2 /* eOfflineValue.Offline */;\r\n listnerNoticeCheck();\r\n }\r\n function _unload() {\r\n var win = getWindow();\r\n if (win && _isListening) {\r\n _disableEvents(win, _evtNamespace);\r\n if (_document) {\r\n // Also attach to the document.body or document\r\n var target = _document.body || _document;\r\n if (!isUndefined(target.ononline)) {\r\n _disableEvents(target, _evtNamespace);\r\n }\r\n }\r\n _isListening = false;\r\n }\r\n }\r\n function addListener(callback) {\r\n listenerList[_DYN_PUSH /* @min:%2epush */](callback);\r\n // Define rm as an instance of IUnloadHook\r\n return {\r\n rm: function () {\r\n var index = listenerList.indexOf(callback);\r\n if (index > -1) {\r\n return listenerList.splice(index, 1);\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n };\r\n }\r\n return {\r\n isOnline: _isOnline,\r\n isListening: function () { return _isListening; },\r\n unload: _unload,\r\n addListener: addListener,\r\n setOnlineState: setOnlineState\r\n };\r\n}\r\n//# sourceMappingURL=Offline.js.map","import { createEnumStyle } from \"./EnumHelperFuncs\";\r\nexport var ActiveStatus = createEnumStyle({\r\n NONE: 0 /* eActiveStatus.NONE */,\r\n PENDING: 3 /* eActiveStatus.PENDING */,\r\n INACTIVE: 1 /* eActiveStatus.INACTIVE */,\r\n ACTIVE: 2 /* eActiveStatus.ACTIVE */\r\n});\r\n//# sourceMappingURL=InitActiveStatusEnum.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nexport var ChannelControllerPriority = 500;\r\nexport var DisabledPropertyName = \"Microsoft_ApplicationInsights_BypassAjaxInstrumentation\";\r\n// export const SampleRate = \"sampleRate\";\r\n// export const ProcessLegacy = \"ProcessLegacy\";\r\n// export const HttpMethod = \"http.method\";\r\n// export const DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\r\n// export const DEFAULT_BREEZE_PATH = \"/v2/track\";\r\n// export const strNotSpecified = \"not_specified\";\r\n// export const strIkey = \"iKey\";\r\n//# sourceMappingURL=Constants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { arrForEach, dumpObj, getNavigator, getWindow, isFunction, objKeys } from \"@nevware21/ts-utils\";\r\nimport { _DYN_DATA, _DYN_HEADERS, _DYN_INITIALIZE, _DYN_LENGTH, _DYN_MESSAGE, _DYN_PROTOCOL, _DYN_REPLACE, _DYN_SEND_POST, _DYN_SET_REQUEST_HEADER, _DYN_STATUS, _DYN_TIMEOUT, _DYN_TO_LOWER_CASE, _DYN_URL_STRING, _DYN_VALUE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { DisabledPropertyName } from \"./Constants\";\r\nimport { _throwInternal, _warnToConsole } from \"./DiagnosticLogger\";\r\nimport { getLocation, isBeaconsSupported, isFetchSupported, isXhrSupported, useXDomainRequest } from \"./EnvUtils\";\r\nimport { _getAllResponseHeaders, formatErrorMessageXdr, formatErrorMessageXhr, getResponseText, openXhr } from \"./HelperFuncs\";\r\nvar STR_EMPTY = \"\";\r\nvar STR_NO_RESPONSE_BODY = \"NoResponseBody\";\r\nvar _noResponseQs = \"&\" + STR_NO_RESPONSE_BODY + \"=true\";\r\nvar STR_POST_METHOD = \"POST\";\r\n/**\r\n * This Internal component\r\n * Manager SendPost functions\r\n * SendPostManger\r\n * @internal for internal use only\r\n */\r\nvar SenderPostManager = /** @class */ (function () {\r\n function SenderPostManager() {\r\n var _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)\r\n var _enableSendPromise;\r\n var _isInitialized;\r\n var _diagLog;\r\n var _isOneDs;\r\n var _onCompleteFuncs;\r\n var _disableCredentials;\r\n var _fetchCredentials;\r\n var _fallbackInst;\r\n var _disableXhr;\r\n var _disableBeacon;\r\n var _disableBeaconSync;\r\n var _disableFetchKeepAlive;\r\n var _addNoResponse;\r\n var _timeoutWrapper;\r\n dynamicProto(SenderPostManager, this, function (_self, _base) {\r\n var _sendCredentials = true; // for 1ds\r\n _initDefaults();\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, diagLog) {\r\n _diagLog = diagLog;\r\n if (_isInitialized) {\r\n _throwInternal(_diagLog, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender is already initialized\");\r\n }\r\n _self.SetConfig(config);\r\n _isInitialized = true;\r\n };\r\n _self[\"_getDbgPlgTargets\"] = function () {\r\n return [_isInitialized, _isOneDs, _disableCredentials, _enableSendPromise];\r\n };\r\n // This componet might get its config from sender, offline sender, 1ds post\r\n // so set this function to mock dynamic changes\r\n _self.SetConfig = function (config) {\r\n try {\r\n _onCompleteFuncs = config.senderOnCompleteCallBack || {};\r\n _disableCredentials = !!config.disableCredentials;\r\n _fetchCredentials = config.fetchCredentials;\r\n _isOneDs = !!config.isOneDs;\r\n _enableSendPromise = !!config.enableSendPromise;\r\n _disableXhr = !!config.disableXhr;\r\n _disableBeacon = !!config.disableBeacon;\r\n _disableBeaconSync = !!config.disableBeaconSync;\r\n _timeoutWrapper = config.timeWrapper;\r\n _addNoResponse = !!config.addNoResponse;\r\n _disableFetchKeepAlive = !!config.disableFetchKeepAlive;\r\n _fallbackInst = { sendPOST: _xhrSender };\r\n if (!_isOneDs) {\r\n _sendCredentials = false; // for appInsights, set it to false always\r\n }\r\n if (_disableCredentials) {\r\n var location_1 = getLocation();\r\n if (location_1 && location_1.protocol && location_1.protocol[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"file:\") {\r\n // Special case where a local html file fails with a CORS error on Chromium browsers\r\n _sendCredentials = false;\r\n }\r\n }\r\n return true;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n };\r\n _self.getSyncFetchPayload = function () {\r\n return _syncFetchPayload;\r\n };\r\n _self.getSenderInst = function (transports, sync) {\r\n if (transports && transports[_DYN_LENGTH /* @min:%2elength */]) {\r\n return _getSenderInterface(transports, sync);\r\n }\r\n return null;\r\n };\r\n _self.getFallbackInst = function () {\r\n return _fallbackInst;\r\n };\r\n _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] = function (unloadCtx, unloadState) {\r\n _initDefaults();\r\n };\r\n /**\r\n * success handler\r\n */\r\n function _onSuccess(res, onComplete) {\r\n _doOnComplete(onComplete, 200, {}, res);\r\n }\r\n /**\r\n * error handler\r\n */\r\n function _onError(message, onComplete) {\r\n _throwInternal(_diagLog, 2 /* eLoggingSeverity.WARNING */, 26 /* _eInternalMessageId.OnError */, \"Failed to send telemetry.\", { message: message });\r\n _doOnComplete(onComplete, 400, {});\r\n }\r\n function _onNoPayloadUrl(onComplete) {\r\n _onError(\"No endpoint url is provided for the batch\", onComplete);\r\n }\r\n function _getSenderInterface(transports, syncSupport) {\r\n var _a;\r\n var transportType = 0 /* TransportType.NotSet */;\r\n var sendPostFunc = null;\r\n var lp = 0;\r\n while (sendPostFunc == null && lp < transports[_DYN_LENGTH /* @min:%2elength */]) {\r\n transportType = transports[lp];\r\n if (!_disableXhr && transportType === 1 /* TransportType.Xhr */) {\r\n if (useXDomainRequest()) {\r\n // IE 8 and 9\r\n sendPostFunc = _xdrSender;\r\n }\r\n else if (isXhrSupported()) {\r\n sendPostFunc = _xhrSender;\r\n }\r\n }\r\n else if (transportType === 2 /* TransportType.Fetch */ && isFetchSupported(syncSupport) && (!syncSupport || !_disableFetchKeepAlive)) {\r\n sendPostFunc = _doFetchSender;\r\n }\r\n else if (transportType === 3 /* TransportType.Beacon */ && isBeaconsSupported() && (syncSupport ? !_disableBeaconSync : !_disableBeacon)) {\r\n sendPostFunc = _beaconSender;\r\n }\r\n lp++;\r\n }\r\n if (sendPostFunc) {\r\n return _a = {\r\n _transport: transportType,\r\n _isSync: syncSupport\r\n },\r\n _a[_DYN_SEND_POST /* @min:sendPOST */] = sendPostFunc,\r\n _a;\r\n }\r\n return null;\r\n }\r\n function _doOnComplete(oncomplete, status, headers, response) {\r\n try {\r\n oncomplete && oncomplete(status, headers, response);\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n function _doBeaconSend(payload, oncomplete) {\r\n var nav = getNavigator();\r\n var url = payload[_DYN_URL_STRING /* @min:%2eurlString */];\r\n if (!url) {\r\n _onNoPayloadUrl(oncomplete);\r\n // return true here, because we don't want to retry it with fallback sender\r\n return true;\r\n }\r\n url = payload[_DYN_URL_STRING /* @min:%2eurlString */] + (_addNoResponse ? _noResponseQs : STR_EMPTY);\r\n var data = payload[_DYN_DATA /* @min:%2edata */];\r\n // Chrome only allows CORS-safelisted values for the sendBeacon data argument\r\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283\r\n // Chrome only allows CORS-safelisted values for the sendBeacon data argument\r\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283\r\n var plainTextBatch = _isOneDs ? data : new Blob([data], { type: \"text/plain;charset=UTF-8\" });\r\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\r\n var queued = nav.sendBeacon(url, plainTextBatch);\r\n return queued;\r\n }\r\n /**\r\n * Send Beacon API request\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param sync - {boolean} - not used\r\n * Note: Beacon API does not support custom headers and we are not able to get\r\n * appId from the backend for the correct correlation.\r\n */\r\n function _beaconSender(payload, oncomplete, sync) {\r\n var data = payload[_DYN_DATA /* @min:%2edata */];\r\n try {\r\n if (data) {\r\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\r\n if (!_doBeaconSend(payload, oncomplete)) {\r\n var onRetry = _onCompleteFuncs && _onCompleteFuncs.beaconOnRetry;\r\n if (onRetry && isFunction(onRetry)) {\r\n onRetry(payload, oncomplete, _doBeaconSend);\r\n }\r\n else {\r\n _fallbackInst && _fallbackInst[_DYN_SEND_POST /* @min:%2esendPOST */](payload, oncomplete, true);\r\n _throwInternal(_diagLog, 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\r\n }\r\n }\r\n else {\r\n // if can send\r\n _onSuccess(STR_EMPTY, oncomplete);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _isOneDs && _warnToConsole(_diagLog, \"Failed to send telemetry using sendBeacon API. Ex:\" + dumpObj(e));\r\n _doOnComplete(oncomplete, _isOneDs ? 0 : 400, {}, STR_EMPTY);\r\n }\r\n return;\r\n }\r\n /**\r\n * Send XMLHttpRequest\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param sync - {boolean} - Indicates if the request should be sent synchronously\r\n */\r\n function _xhrSender(payload, oncomplete, sync) {\r\n //let internalPayload = payload as IInternalPayloadData;\r\n var thePromise;\r\n var resolveFunc;\r\n var rejectFunc;\r\n var headers = payload[_DYN_HEADERS /* @min:%2eheaders */] || {};\r\n if (!sync && _enableSendPromise) {\r\n thePromise = createPromise(function (resolve, reject) {\r\n resolveFunc = resolve;\r\n rejectFunc = reject;\r\n });\r\n }\r\n if (_isOneDs && sync && payload.disableXhrSync) {\r\n sync = false;\r\n }\r\n //const xhr = new XMLHttpRequest();\r\n var endPointUrl = payload[_DYN_URL_STRING /* @min:%2eurlString */];\r\n if (!endPointUrl) {\r\n _onNoPayloadUrl(oncomplete);\r\n resolveFunc && resolveFunc(false);\r\n return;\r\n }\r\n var xhr = openXhr(STR_POST_METHOD, endPointUrl, _sendCredentials, true, sync, payload[_DYN_TIMEOUT /* @min:%2etimeout */]);\r\n if (!_isOneDs) {\r\n // application/json should NOT add to 1ds post by default\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](\"Content-type\", \"application/json\");\r\n }\r\n arrForEach(objKeys(headers), function (headerName) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](headerName, headers[headerName]);\r\n });\r\n xhr.onreadystatechange = function () {\r\n if (!_isOneDs) {\r\n _doOnReadyFunc(xhr);\r\n if (xhr.readyState === 4) {\r\n resolveFunc && resolveFunc(true);\r\n }\r\n }\r\n };\r\n xhr.onload = function () {\r\n if (_isOneDs) {\r\n _doOnReadyFunc(xhr);\r\n }\r\n };\r\n function _doOnReadyFunc(xhr) {\r\n var onReadyFunc = _onCompleteFuncs && _onCompleteFuncs.xhrOnComplete;\r\n var onReadyFuncExist = onReadyFunc && isFunction(onReadyFunc);\r\n if (onReadyFuncExist) {\r\n onReadyFunc(xhr, oncomplete, payload);\r\n }\r\n else {\r\n var response = getResponseText(xhr);\r\n _doOnComplete(oncomplete, xhr[_DYN_STATUS /* @min:%2estatus */], _getAllResponseHeaders(xhr, _isOneDs), response);\r\n }\r\n }\r\n xhr.onerror = function (event) {\r\n _doOnComplete(oncomplete, _isOneDs ? xhr[_DYN_STATUS /* @min:%2estatus */] : 400, _getAllResponseHeaders(xhr, _isOneDs), _isOneDs ? STR_EMPTY : formatErrorMessageXhr(xhr));\r\n rejectFunc && rejectFunc(event);\r\n };\r\n xhr.ontimeout = function () {\r\n _doOnComplete(oncomplete, _isOneDs ? xhr[_DYN_STATUS /* @min:%2estatus */] : 500, _getAllResponseHeaders(xhr, _isOneDs), _isOneDs ? STR_EMPTY : formatErrorMessageXhr(xhr));\r\n resolveFunc && resolveFunc(false);\r\n };\r\n xhr.send(payload[_DYN_DATA /* @min:%2edata */]);\r\n return thePromise;\r\n }\r\n /**\r\n * Send fetch API request\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param sync - {boolean} - For fetch this identifies whether we are \"unloading\" (false) or a normal request\r\n */\r\n function _doFetchSender(payload, oncomplete, sync) {\r\n var _a;\r\n var endPointUrl = payload[_DYN_URL_STRING /* @min:%2eurlString */];\r\n var batch = payload[_DYN_DATA /* @min:%2edata */];\r\n var plainTextBatch = _isOneDs ? batch : new Blob([batch], { type: \"application/json\" });\r\n var thePromise;\r\n var resolveFunc;\r\n var rejectFunc;\r\n var requestHeaders = new Headers();\r\n var batchLength = batch[_DYN_LENGTH /* @min:%2elength */];\r\n var ignoreResponse = false;\r\n var responseHandled = false;\r\n var headers = payload[_DYN_HEADERS /* @min:%2eheaders */] || {};\r\n //TODO: handle time out for 1ds\r\n var init = (_a = {\r\n method: STR_POST_METHOD,\r\n body: plainTextBatch\r\n },\r\n _a[DisabledPropertyName] = true // Mark so we don't attempt to track this request\r\n ,\r\n _a);\r\n // Only add headers if there are headers to add, due to issue with some polyfills\r\n if (payload.headers && objKeys(payload.headers)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(objKeys(headers), function (headerName) {\r\n requestHeaders.append(headerName, headers[headerName]);\r\n });\r\n init[_DYN_HEADERS /* @min:%2eheaders */] = requestHeaders;\r\n }\r\n if (_fetchCredentials) { // if user passed in this value via post channel (1ds), then use it\r\n init.credentials = _fetchCredentials;\r\n }\r\n else if (_sendCredentials && _isOneDs) {\r\n // for 1ds, Don't send credentials when URL is file://\r\n init.credentials = \"include\";\r\n }\r\n if (sync) {\r\n init.keepalive = true;\r\n _syncFetchPayload += batchLength;\r\n if (_isOneDs) {\r\n if (payload[\"_sendReason\"] === 2 /* SendRequestReason.Unload */) {\r\n // As a sync request (during unload), it is unlikely that we will get a chance to process the response so\r\n // just like beacon send assume that the events have been accepted and processed\r\n ignoreResponse = true;\r\n if (_addNoResponse) {\r\n endPointUrl += _noResponseQs;\r\n }\r\n }\r\n }\r\n else {\r\n // for appinsights, set to true for all sync request\r\n ignoreResponse = true;\r\n }\r\n }\r\n var request = new Request(endPointUrl, init);\r\n try {\r\n // Also try and tag the request (just in case the value in init is not copied over)\r\n request[DisabledPropertyName] = true;\r\n }\r\n catch (e) {\r\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\r\n // cause the request to fail and we no telemetry would be sent\r\n }\r\n if (!sync && _enableSendPromise) {\r\n thePromise = createPromise(function (resolve, reject) {\r\n resolveFunc = resolve;\r\n rejectFunc = reject;\r\n });\r\n }\r\n if (!endPointUrl) {\r\n _onNoPayloadUrl(oncomplete);\r\n resolveFunc && resolveFunc(false);\r\n return;\r\n }\r\n function _handleError(res) {\r\n // In case there is an error in the request. Set the status to 0 for 1ds and 400 for appInsights\r\n // so that the events can be retried later.\r\n _doOnComplete(oncomplete, _isOneDs ? 0 : 400, {}, _isOneDs ? STR_EMPTY : res);\r\n }\r\n function _onFetchComplete(response, payload, value) {\r\n var status = response[_DYN_STATUS /* @min:%2estatus */];\r\n var onCompleteFunc = _onCompleteFuncs.fetchOnComplete;\r\n if (onCompleteFunc && isFunction(onCompleteFunc)) {\r\n onCompleteFunc(response, oncomplete, value || STR_EMPTY, payload);\r\n }\r\n else {\r\n _doOnComplete(oncomplete, status, {}, value || STR_EMPTY);\r\n }\r\n }\r\n try {\r\n doAwaitResponse(fetch(_isOneDs ? endPointUrl : request, _isOneDs ? init : null), function (result) {\r\n if (sync) {\r\n _syncFetchPayload -= batchLength;\r\n batchLength = 0;\r\n }\r\n if (!responseHandled) {\r\n responseHandled = true;\r\n if (!result.rejected) {\r\n var response_1 = result[_DYN_VALUE /* @min:%2evalue */];\r\n try {\r\n /**\r\n * The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500.\r\n * Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure\r\n * or if anything prevented the request from completing.\r\n */\r\n if (!_isOneDs && !response_1.ok) {\r\n // this is for appInsights only\r\n _handleError(response_1.statusText);\r\n resolveFunc && resolveFunc(false);\r\n }\r\n else {\r\n if (_isOneDs && !response_1.body) {\r\n _onFetchComplete(response_1, null, STR_EMPTY);\r\n resolveFunc && resolveFunc(true);\r\n }\r\n else {\r\n doAwaitResponse(response_1.text(), function (resp) {\r\n _onFetchComplete(response_1, payload, resp[_DYN_VALUE /* @min:%2evalue */]);\r\n resolveFunc && resolveFunc(true);\r\n });\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _handleError(dumpObj(e));\r\n rejectFunc && rejectFunc(e);\r\n }\r\n }\r\n else {\r\n _handleError(result.reason && result.reason[_DYN_MESSAGE /* @min:%2emessage */]);\r\n rejectFunc && rejectFunc(result.reason);\r\n }\r\n }\r\n });\r\n }\r\n catch (e) {\r\n if (!responseHandled) {\r\n _handleError(dumpObj(e));\r\n rejectFunc && rejectFunc(e);\r\n }\r\n }\r\n if (ignoreResponse && !responseHandled) {\r\n // Assume success during unload processing as we most likely won't get the response\r\n responseHandled = true;\r\n _doOnComplete(oncomplete, 200, {});\r\n resolveFunc && resolveFunc(true);\r\n }\r\n if (_isOneDs && !responseHandled && payload[_DYN_TIMEOUT /* @min:%2etimeout */] > 0) {\r\n // Simulate timeout\r\n _timeoutWrapper && _timeoutWrapper.set(function () {\r\n if (!responseHandled) {\r\n // Assume a 500 response (which will cause a retry)\r\n responseHandled = true;\r\n _doOnComplete(oncomplete, 500, {});\r\n resolveFunc && resolveFunc(true);\r\n }\r\n }, payload[_DYN_TIMEOUT /* @min:%2etimeout */]);\r\n }\r\n return thePromise;\r\n }\r\n /**\r\n * Send XDomainRequest\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param sync - {boolean} - Indicates if the request should be sent synchronously\r\n *\r\n * Note: XDomainRequest does not support sync requests. This 'isAsync' parameter is added\r\n * to maintain consistency with the xhrSender's contract\r\n * Note: XDomainRequest does not support custom headers and we are not able to get\r\n * appId from the backend for the correct correlation.\r\n */\r\n function _xdrSender(payload, oncomplete, sync) {\r\n // It doesn't support custom headers, so no action is taken with current requestHeaders\r\n var _window = getWindow();\r\n var xdr = new XDomainRequest();\r\n var data = payload[_DYN_DATA /* @min:%2edata */];\r\n xdr.onload = function () {\r\n var response = getResponseText(xdr);\r\n var onloadFunc = _onCompleteFuncs && _onCompleteFuncs.xdrOnComplete;\r\n if (onloadFunc && isFunction(onloadFunc)) {\r\n onloadFunc(xdr, oncomplete, payload);\r\n }\r\n else {\r\n _doOnComplete(oncomplete, 200, {}, response);\r\n }\r\n };\r\n xdr.onerror = function () {\r\n _doOnComplete(oncomplete, 400, {}, _isOneDs ? STR_EMPTY : formatErrorMessageXdr(xdr));\r\n };\r\n xdr.ontimeout = function () {\r\n _doOnComplete(oncomplete, 500, {});\r\n };\r\n xdr.onprogress = function () { };\r\n // XDomainRequest requires the same protocol as the hosting page.\r\n // If the protocol doesn't match, we can't send the telemetry :(.\r\n var hostingProtocol = _window && _window.location && _window.location[_DYN_PROTOCOL /* @min:%2eprotocol */] || \"\";\r\n var endpoint = payload[_DYN_URL_STRING /* @min:%2eurlString */];\r\n if (!endpoint) {\r\n _onNoPayloadUrl(oncomplete);\r\n return;\r\n }\r\n if (!_isOneDs && endpoint.lastIndexOf(hostingProtocol, 0) !== 0) {\r\n var msg = \"Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.\";\r\n _throwInternal(_diagLog, 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + msg);\r\n _onError(msg, oncomplete);\r\n return;\r\n }\r\n var endpointUrl = _isOneDs ? endpoint : endpoint[_DYN_REPLACE /* @min:%2ereplace */](/^(https?:)/, \"\");\r\n xdr.open(STR_POST_METHOD, endpointUrl);\r\n if (payload[_DYN_TIMEOUT /* @min:%2etimeout */]) {\r\n xdr[_DYN_TIMEOUT /* @min:%2etimeout */] = payload[_DYN_TIMEOUT /* @min:%2etimeout */];\r\n }\r\n xdr.send(data);\r\n if (_isOneDs && sync) {\r\n _timeoutWrapper && _timeoutWrapper.set(function () {\r\n xdr.send(data);\r\n }, 0);\r\n }\r\n else {\r\n xdr.send(data);\r\n }\r\n }\r\n function _initDefaults() {\r\n _syncFetchPayload = 0;\r\n _isInitialized = false;\r\n _enableSendPromise = false;\r\n _diagLog = null;\r\n _isOneDs = null;\r\n _onCompleteFuncs = null;\r\n _disableCredentials = null;\r\n _fetchCredentials = null;\r\n _fallbackInst = null;\r\n _disableXhr = false;\r\n _disableBeacon = false;\r\n _disableBeaconSync = false;\r\n _disableFetchKeepAlive = false;\r\n _addNoResponse = false;\r\n _timeoutWrapper = null;\r\n }\r\n });\r\n }\r\n SenderPostManager.prototype.initialize = function (config, diagLog) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Get size of current sync fetch payload\r\n */\r\n SenderPostManager.prototype.getSyncFetchPayload = function () {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * reset Config\r\n * @returns True if set is successfully\r\n */\r\n SenderPostManager.prototype.SetConfig = function (config) {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Get current xhr instance\r\n */\r\n SenderPostManager.prototype.getSenderInst = function (transports, sync) {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Get current fallback sender instance\r\n */\r\n SenderPostManager.prototype.getFallbackInst = function () {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n SenderPostManager.prototype._doTeardown = function (unloadCtx, unloadState) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return SenderPostManager;\r\n}());\r\nexport { SenderPostManager };\r\n//# sourceMappingURL=SenderPostManager.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { arrSlice, getLength } from \"@nevware21/ts-utils\";\r\nimport { _DYN_UNLOAD } from \"../__DynamicConstants\";\r\n/**\r\n * Run the unload function of the target object if it exists\r\n * @param target - The target object that contains the unload function\r\n * @param isAsync - The caller identifies whether it is expecting the operation to complete synchronously or asynchronously. Even\r\n * if the caller is not waiting the operation may still be performed asynchronously depending on the component and the reverse is\r\n * also true.\r\n * @returns The result of the target function\r\n */\r\nexport function runTargetUnload(target, isAsync) {\r\n if (target && target[_DYN_UNLOAD /* @min:%2eunload */]) {\r\n return target[_DYN_UNLOAD /* @min:%2eunload */](isAsync);\r\n }\r\n}\r\n/**\r\n * Call the unload function on all targets handling any returned [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * / Promise before calling the next targets unload\r\n * @param targets - An array of the targets to unload\r\n * @param isAsync - The caller identifies whether it is expecting the operations to complete synchronously or asynchronously. Even\r\n * if the caller is not waiting the operation may still be performed asynchronously depending on the component and the reverse is\r\n * also true.\r\n * @param done - Optional callback function to call once all of the unload functions have been called.\r\n */\r\nexport function doUnloadAll(targets, isAsync, done) {\r\n var result;\r\n if (!done) {\r\n result = createPromise(function (resolved) {\r\n done = resolved;\r\n });\r\n }\r\n if (targets && getLength(targets) > 0) {\r\n doAwaitResponse(runTargetUnload(targets[0], isAsync), function () {\r\n doUnloadAll(arrSlice(targets, 1), isAsync, done);\r\n });\r\n }\r\n else {\r\n done();\r\n }\r\n return result;\r\n}\r\n//# sourceMappingURL=AsyncUtils.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { dumpObj } from \"@nevware21/ts-utils\";\r\nimport { _DYN_ITEMS_RECEIVED, _DYN_LENGTH, _DYN_NAME } from \"../__DynamicConstants\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { getJSON } from \"./EnvUtils\";\r\n/**\r\n * Parses the response from the backend.\r\n * @param response - XMLHttpRequest or XDomainRequest response\r\n */\r\nexport function parseResponse(response, diagLog) {\r\n try {\r\n if (response && response !== \"\") {\r\n var result = getJSON().parse(response);\r\n if (result && result[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] && result[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] >= result.itemsAccepted &&\r\n result.itemsReceived - result.itemsAccepted === result.errors[_DYN_LENGTH /* @min:%2elength */]) {\r\n return result;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(diagLog, 1 /* eLoggingSeverity.CRITICAL */, 43 /* _eInternalMessageId.InvalidBackendResponse */, \"Cannot parse the response. \" + (e[_DYN_NAME /* @min:%2ename */] || dumpObj(e)), {\r\n response: response\r\n });\r\n }\r\n return null;\r\n}\r\n//# sourceMappingURL=ResponseHelpers.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { __extends } from \"tslib\";\r\nimport { createClassFromInterface } from \"@microsoft/applicationinsights-core-js\";\r\nfunction _aiNameFunc(baseName) {\r\n var aiName = \"ai.\" + baseName + \".\";\r\n return function (name) {\r\n return aiName + name;\r\n };\r\n}\r\nvar _aiApplication = _aiNameFunc(\"application\");\r\nvar _aiDevice = _aiNameFunc(\"device\");\r\nvar _aiLocation = _aiNameFunc(\"location\");\r\nvar _aiOperation = _aiNameFunc(\"operation\");\r\nvar _aiSession = _aiNameFunc(\"session\");\r\nvar _aiUser = _aiNameFunc(\"user\");\r\nvar _aiCloud = _aiNameFunc(\"cloud\");\r\nvar _aiInternal = _aiNameFunc(\"internal\");\r\nvar ContextTagKeys = /** @class */ (function (_super) {\r\n __extends(ContextTagKeys, _super);\r\n function ContextTagKeys() {\r\n return _super.call(this) || this;\r\n }\r\n return ContextTagKeys;\r\n}(createClassFromInterface({\r\n applicationVersion: _aiApplication(\"ver\"),\r\n applicationBuild: _aiApplication(\"build\"),\r\n applicationTypeId: _aiApplication(\"typeId\"),\r\n applicationId: _aiApplication(\"applicationId\"),\r\n applicationLayer: _aiApplication(\"layer\"),\r\n deviceId: _aiDevice(\"id\"),\r\n deviceIp: _aiDevice(\"ip\"),\r\n deviceLanguage: _aiDevice(\"language\"),\r\n deviceLocale: _aiDevice(\"locale\"),\r\n deviceModel: _aiDevice(\"model\"),\r\n deviceFriendlyName: _aiDevice(\"friendlyName\"),\r\n deviceNetwork: _aiDevice(\"network\"),\r\n deviceNetworkName: _aiDevice(\"networkName\"),\r\n deviceOEMName: _aiDevice(\"oemName\"),\r\n deviceOS: _aiDevice(\"os\"),\r\n deviceOSVersion: _aiDevice(\"osVersion\"),\r\n deviceRoleInstance: _aiDevice(\"roleInstance\"),\r\n deviceRoleName: _aiDevice(\"roleName\"),\r\n deviceScreenResolution: _aiDevice(\"screenResolution\"),\r\n deviceType: _aiDevice(\"type\"),\r\n deviceMachineName: _aiDevice(\"machineName\"),\r\n deviceVMName: _aiDevice(\"vmName\"),\r\n deviceBrowser: _aiDevice(\"browser\"),\r\n deviceBrowserVersion: _aiDevice(\"browserVersion\"),\r\n locationIp: _aiLocation(\"ip\"),\r\n locationCountry: _aiLocation(\"country\"),\r\n locationProvince: _aiLocation(\"province\"),\r\n locationCity: _aiLocation(\"city\"),\r\n operationId: _aiOperation(\"id\"),\r\n operationName: _aiOperation(\"name\"),\r\n operationParentId: _aiOperation(\"parentId\"),\r\n operationRootId: _aiOperation(\"rootId\"),\r\n operationSyntheticSource: _aiOperation(\"syntheticSource\"),\r\n operationCorrelationVector: _aiOperation(\"correlationVector\"),\r\n sessionId: _aiSession(\"id\"),\r\n sessionIsFirst: _aiSession(\"isFirst\"),\r\n sessionIsNew: _aiSession(\"isNew\"),\r\n userAccountAcquisitionDate: _aiUser(\"accountAcquisitionDate\"),\r\n userAccountId: _aiUser(\"accountId\"),\r\n userAgent: _aiUser(\"userAgent\"),\r\n userId: _aiUser(\"id\"),\r\n userStoreRegion: _aiUser(\"storeRegion\"),\r\n userAuthUserId: _aiUser(\"authUserId\"),\r\n userAnonymousUserAcquisitionDate: _aiUser(\"anonUserAcquisitionDate\"),\r\n userAuthenticatedUserAcquisitionDate: _aiUser(\"authUserAcquisitionDate\"),\r\n cloudName: _aiCloud(\"name\"),\r\n cloudRole: _aiCloud(\"role\"),\r\n cloudRoleVer: _aiCloud(\"roleVer\"),\r\n cloudRoleInstance: _aiCloud(\"roleInstance\"),\r\n cloudEnvironment: _aiCloud(\"environment\"),\r\n cloudLocation: _aiCloud(\"location\"),\r\n cloudDeploymentUnit: _aiCloud(\"deploymentUnit\"),\r\n internalNodeName: _aiInternal(\"nodeName\"),\r\n internalSdkVersion: _aiInternal(\"sdkVersion\"),\r\n internalAgentVersion: _aiInternal(\"agentVersion\"),\r\n internalSnippet: _aiInternal(\"snippet\"),\r\n internalSdkSrc: _aiInternal(\"sdkSrc\")\r\n})));\r\nexport { ContextTagKeys };\r\n//# sourceMappingURL=ContextTagKeys.js.map","import { ContextTagKeys } from \"./Contracts/ContextTagKeys\";\r\nexport var Extensions = {\r\n UserExt: \"user\",\r\n DeviceExt: \"device\",\r\n TraceExt: \"trace\",\r\n WebExt: \"web\",\r\n AppExt: \"app\",\r\n OSExt: \"os\",\r\n SessionExt: \"ses\",\r\n SDKExt: \"sdk\"\r\n};\r\nexport var CtxTagKeys = new ContextTagKeys();\r\n//# sourceMappingURL=PartAExtensions.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strNotSpecified } from \"../../Constants\";\r\nimport { _DYN_NAME } from \"../../__DynamicConstants\";\r\nimport { dataSanitizeString } from \"./DataSanitizer\";\r\nvar Envelope = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\r\n function Envelope(logger, data, name) {\r\n var _this = this;\r\n var _self = this;\r\n _self.ver = 1;\r\n _self.sampleRate = 100.0;\r\n _self.tags = {};\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self.data = data;\r\n _self.time = toISOString(new Date());\r\n _self.aiDataContract = {\r\n time: 1 /* FieldType.Required */,\r\n iKey: 1 /* FieldType.Required */,\r\n name: 1 /* FieldType.Required */,\r\n sampleRate: function () {\r\n return (_this.sampleRate === 100) ? 4 /* FieldType.Hidden */ : 1 /* FieldType.Required */;\r\n },\r\n tags: 1 /* FieldType.Required */,\r\n data: 1 /* FieldType.Required */\r\n };\r\n }\r\n return Envelope;\r\n}());\r\nexport { Envelope };\r\n//# sourceMappingURL=Envelope.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar Data = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\r\n function Data(baseType, data) {\r\n /**\r\n * The data contract for serializing this object.\r\n */\r\n this.aiDataContract = {\r\n baseType: 1 /* FieldType.Required */,\r\n baseData: 1 /* FieldType.Required */\r\n };\r\n this.baseType = baseType;\r\n this.baseData = data;\r\n }\r\n return Data;\r\n}());\r\nexport { Data };\r\n//# sourceMappingURL=Data.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// ###################################################################################################################################################\r\n// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ###\r\n// ###################################################################################################################################################\r\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nexport var STR_DURATION = \"duration\";\r\n//# sourceMappingURL=InternalConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_TAGS = \"tags\"; // Count: 17\r\nexport var _DYN_DEVICE_TYPE = \"deviceType\"; // Count: 3\r\nexport var _DYN_DATA = \"data\"; // Count: 15\r\nexport var _DYN_NAME = \"name\"; // Count: 8\r\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 5\r\nexport var _DYN_LENGTH = \"length\"; // Count: 38\r\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 5\r\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 7\r\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 10\r\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 7\r\nexport var _DYN__GET = \"_get\"; // Count: 5\r\nexport var _DYN_ENQUEUE = \"enqueue\"; // Count: 7\r\nexport var _DYN_COUNT = \"count\"; // Count: 7\r\nexport var _DYN_EVENTS_LIMIT_IN_MEM = \"eventsLimitInMem\"; // Count: 2\r\nexport var _DYN_PUSH = \"push\"; // Count: 9\r\nexport var _DYN_ITEM = \"item\"; // Count: 6\r\nexport var _DYN_EMIT_LINE_DELIMITED_0 = \"emitLineDelimitedJson\"; // Count: 3\r\nexport var _DYN_CLEAR = \"clear\"; // Count: 6\r\nexport var _DYN_CREATE_NEW = \"createNew\"; // Count: 3\r\nexport var _DYN_MARK_AS_SENT = \"markAsSent\"; // Count: 4\r\nexport var _DYN_CLEAR_SENT = \"clearSent\"; // Count: 5\r\nexport var _DYN_BUFFER_OVERRIDE = \"bufferOverride\"; // Count: 3\r\nexport var _DYN__BUFFER__KEY = \"BUFFER_KEY\"; // Count: 5\r\nexport var _DYN__SENT__BUFFER__KEY = \"SENT_BUFFER_KEY\"; // Count: 8\r\nexport var _DYN_CONCAT = \"concat\"; // Count: 6\r\nexport var _DYN__MAX__BUFFER__SIZE = \"MAX_BUFFER_SIZE\"; // Count: 5\r\nexport var _DYN_TRIGGER_SEND = \"triggerSend\"; // Count: 5\r\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 16\r\nexport var _DYN_INITIALIZE = \"initialize\"; // Count: 3\r\nexport var _DYN__SENDER = \"_sender\"; // Count: 5\r\nexport var _DYN_CUSTOM_HEADERS = \"customHeaders\"; // Count: 3\r\nexport var _DYN_MAX_BATCH_SIZE_IN_BY1 = \"maxBatchSizeInBytes\"; // Count: 2\r\nexport var _DYN_ONUNLOAD_DISABLE_BEA2 = \"onunloadDisableBeacon\"; // Count: 3\r\nexport var _DYN_IS_BEACON_API_DISABL3 = \"isBeaconApiDisabled\"; // Count: 3\r\nexport var _DYN_ALWAYS_USE_XHR_OVERR4 = \"alwaysUseXhrOverride\"; // Count: 2\r\nexport var _DYN_DISABLE_XHR = \"disableXhr\"; // Count: 3\r\nexport var _DYN_ENABLE_SESSION_STORA5 = \"enableSessionStorageBuffer\"; // Count: 2\r\nexport var _DYN__BUFFER = \"_buffer\"; // Count: 9\r\nexport var _DYN_ONUNLOAD_DISABLE_FET6 = \"onunloadDisableFetch\"; // Count: 2\r\nexport var _DYN_DISABLE_SEND_BEACON_7 = \"disableSendBeaconSplit\"; // Count: 2\r\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 2\r\nexport var _DYN_ENABLE_SEND_PROMISE = \"enableSendPromise\"; // Count: 2\r\nexport var _DYN_GET_SENDER_INST = \"getSenderInst\"; // Count: 4\r\nexport var _DYN_UNLOAD_TRANSPORTS = \"unloadTransports\"; // Count: 2\r\nexport var _DYN_CONVERT_UNDEFINED = \"convertUndefined\"; // Count: 2\r\nexport var _DYN_MAX_BATCH_INTERVAL = \"maxBatchInterval\"; // Count: 2\r\nexport var _DYN_SERIALIZE = \"serialize\"; // Count: 4\r\nexport var _DYN__ON_ERROR = \"_onError\"; // Count: 7\r\nexport var _DYN__ON_PARTIAL_SUCCESS = \"_onPartialSuccess\"; // Count: 3\r\nexport var _DYN__ON_SUCCESS = \"_onSuccess\"; // Count: 6\r\nexport var _DYN_ITEMS_RECEIVED = \"itemsReceived\"; // Count: 3\r\nexport var _DYN_ITEMS_ACCEPTED = \"itemsAccepted\"; // Count: 3\r\nexport var _DYN_ORI_PAYLOAD = \"oriPayload\"; // Count: 3\r\nexport var _DYN_BASE_TYPE = \"baseType\"; // Count: 4\r\nexport var _DYN_SAMPLE_RATE = \"sampleRate\"; // Count: 4\r\nexport var _DYN_EVENTS_SEND_REQUEST = \"eventsSendRequest\"; // Count: 2\r\nexport var _DYN_GET_SAMPLING_SCORE = \"getSamplingScore\"; // Count: 2\r\nexport var _DYN_GET_HASH_CODE_SCORE = \"getHashCodeScore\"; // Count: 4\r\n//# sourceMappingURL=__DynamicConstants.js.map","import { __assign } from \"tslib\";\r\nimport { CtxTagKeys, Data, Envelope, Event, Exception, HttpMethod, Metric, PageView, PageViewPerformance, RemoteDependencyData, SampleRate, Trace, dataSanitizeString } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, _warnToConsole, getJSON, hasJSON, isNullOrUndefined, isNumber, isString, isTruthy, objForEachKey, optimizeObject, setValue, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_DURATION } from \"./InternalConstants\";\r\nimport { _DYN_DATA, _DYN_DATA_TYPE, _DYN_DEVICE_TYPE, _DYN_ENVELOPE_TYPE, _DYN_LENGTH, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_STRINGIFY, _DYN_TAGS, _DYN_TO_STRING, _DYN_TRACE_ID } from \"./__DynamicConstants\";\r\n// these two constants are used to filter out properties not needed when trying to extract custom properties and measurements from the incoming payload\r\nvar strBaseType = \"baseType\";\r\nvar strBaseData = \"baseData\";\r\nvar strProperties = \"properties\";\r\nvar strTrue = \"true\";\r\nfunction _setValueIf(target, field, value) {\r\n return setValue(target, field, value, isTruthy);\r\n}\r\n/*\r\n * Maps Part A data from CS 4.0\r\n */\r\nfunction _extractPartAExtensions(logger, item, env) {\r\n // todo: switch to keys from common in this method\r\n var envTags = env[_DYN_TAGS /* @min:%2etags */] = env[_DYN_TAGS /* @min:%2etags */] || {};\r\n var itmExt = item.ext = item.ext || {};\r\n var itmTags = item[_DYN_TAGS /* @min:%2etags */] = item[_DYN_TAGS /* @min:%2etags */] || [];\r\n var extUser = itmExt.user;\r\n if (extUser) {\r\n _setValueIf(envTags, CtxTagKeys.userAuthUserId, extUser.authId);\r\n _setValueIf(envTags, CtxTagKeys.userId, extUser.id || extUser.localId);\r\n }\r\n var extApp = itmExt.app;\r\n if (extApp) {\r\n _setValueIf(envTags, CtxTagKeys.sessionId, extApp.sesId);\r\n }\r\n var extDevice = itmExt.device;\r\n if (extDevice) {\r\n _setValueIf(envTags, CtxTagKeys.deviceId, extDevice.id || extDevice.localId);\r\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice.deviceClass);\r\n _setValueIf(envTags, CtxTagKeys.deviceIp, extDevice.ip);\r\n _setValueIf(envTags, CtxTagKeys.deviceModel, extDevice.model);\r\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice[_DYN_DEVICE_TYPE /* @min:%2edeviceType */]);\r\n }\r\n var web = item.ext.web;\r\n if (web) {\r\n _setValueIf(envTags, CtxTagKeys.deviceLanguage, web.browserLang);\r\n _setValueIf(envTags, CtxTagKeys.deviceBrowserVersion, web.browserVer);\r\n _setValueIf(envTags, CtxTagKeys.deviceBrowser, web.browser);\r\n var envData = env[_DYN_DATA /* @min:%2edata */] = env[_DYN_DATA /* @min:%2edata */] || {};\r\n var envBaseData = envData[strBaseData] = envData[strBaseData] || {};\r\n var envProps = envBaseData[strProperties] = envBaseData[strProperties] || {};\r\n _setValueIf(envProps, \"domain\", web.domain);\r\n _setValueIf(envProps, \"isManual\", web.isManual ? strTrue : null);\r\n _setValueIf(envProps, \"screenRes\", web.screenRes);\r\n _setValueIf(envProps, \"userConsent\", web.userConsent ? strTrue : null);\r\n }\r\n var extOs = itmExt.os;\r\n if (extOs) {\r\n _setValueIf(envTags, CtxTagKeys.deviceOS, extOs[_DYN_NAME /* @min:%2ename */]);\r\n _setValueIf(envTags, CtxTagKeys.deviceOSVersion, extOs.osVer);\r\n }\r\n // No support for mapping Trace.traceState to 2.0 as it is currently empty\r\n var extTrace = itmExt.trace;\r\n if (extTrace) {\r\n _setValueIf(envTags, CtxTagKeys.operationParentId, extTrace.parentID);\r\n _setValueIf(envTags, CtxTagKeys.operationName, dataSanitizeString(logger, extTrace[_DYN_NAME /* @min:%2ename */]));\r\n _setValueIf(envTags, CtxTagKeys.operationId, extTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\r\n }\r\n // Sample 4.0 schema\r\n // {\r\n // \"time\" : \"2018-09-05T22:51:22.4936Z\",\r\n // \"name\" : \"MetricWithNamespace\",\r\n // \"iKey\" : \"ABC-5a4cbd20-e601-4ef5-a3c6-5d6577e4398e\",\r\n // \"ext\": { \"cloud\": {\r\n // \"role\": \"WATSON3\",\r\n // \"roleInstance\": \"CO4AEAP00000260\"\r\n // },\r\n // \"device\": {}, \"correlation\": {} },\r\n // \"tags\": [\r\n // { \"amazon.region\" : \"east2\" },\r\n // { \"os.expid\" : \"wp:02df239\" }\r\n // ]\r\n // }\r\n var tgs = {};\r\n // deals with tags.push({object})\r\n for (var i = itmTags[_DYN_LENGTH /* @min:%2elength */] - 1; i >= 0; i--) {\r\n var tg = itmTags[i];\r\n objForEachKey(tg, function (key, value) {\r\n tgs[key] = value;\r\n });\r\n itmTags.splice(i, 1);\r\n }\r\n // deals with tags[key]=value (and handles hasOwnProperty)\r\n objForEachKey(itmTags, function (tg, value) {\r\n tgs[tg] = value;\r\n });\r\n var theTags = __assign(__assign({}, envTags), tgs);\r\n if (!theTags[CtxTagKeys.internalSdkVersion]) {\r\n // Append a version in case it is not already set\r\n theTags[CtxTagKeys.internalSdkVersion] = dataSanitizeString(logger, \"javascript:\".concat(EnvelopeCreator.Version), 64);\r\n }\r\n env[_DYN_TAGS /* @min:%2etags */] = optimizeObject(theTags);\r\n}\r\nfunction _extractPropsAndMeasurements(data, properties, measurements) {\r\n if (!isNullOrUndefined(data)) {\r\n objForEachKey(data, function (key, value) {\r\n if (isNumber(value)) {\r\n measurements[key] = value;\r\n }\r\n else if (isString(value)) {\r\n properties[key] = value;\r\n }\r\n else if (hasJSON()) {\r\n properties[key] = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n }\r\n });\r\n }\r\n}\r\nfunction _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue) {\r\n if (!isNullOrUndefined(properties)) {\r\n objForEachKey(properties, function (key, value) {\r\n properties[key] = value || customUndefinedValue;\r\n });\r\n }\r\n}\r\n// TODO: Do we want this to take logger as arg or use this._logger as nonstatic?\r\nfunction _createEnvelope(logger, envelopeType, telemetryItem, data) {\r\n var envelope = new Envelope(logger, data, envelopeType);\r\n _setValueIf(envelope, \"sampleRate\", telemetryItem[SampleRate]);\r\n if ((telemetryItem[strBaseData] || {}).startTime) {\r\n // Starting from Version 3.0.3, the time property will be assigned by the startTime value,\r\n // which records the loadEvent time for the pageView event.\r\n envelope.time = toISOString(telemetryItem[strBaseData].startTime);\r\n }\r\n envelope.iKey = telemetryItem.iKey;\r\n var iKeyNoDashes = telemetryItem.iKey.replace(/-/g, \"\");\r\n envelope[_DYN_NAME /* @min:%2ename */] = envelope[_DYN_NAME /* @min:%2ename */].replace(\"{0}\", iKeyNoDashes);\r\n // extract all extensions from ctx\r\n _extractPartAExtensions(logger, telemetryItem, envelope);\r\n // loop through the envelope tags (extension of Part A) and pick out the ones that should go in outgoing envelope tags\r\n telemetryItem[_DYN_TAGS /* @min:%2etags */] = telemetryItem[_DYN_TAGS /* @min:%2etags */] || [];\r\n return optimizeObject(envelope);\r\n}\r\nfunction EnvelopeCreatorInit(logger, telemetryItem) {\r\n if (isNullOrUndefined(telemetryItem[strBaseData])) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 46 /* _eInternalMessageId.TelemetryEnvelopeInvalid */, \"telemetryItem.baseData cannot be null.\");\r\n }\r\n}\r\nexport var EnvelopeCreator = {\r\n Version: '3.3.1'\r\n};\r\nexport function DependencyEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n if (isNullOrUndefined(bd)) {\r\n _warnToConsole(logger, \"Invalid input for dependency data\");\r\n return null;\r\n }\r\n var method = bd[strProperties] && bd[strProperties][HttpMethod] ? bd[strProperties][HttpMethod] : \"GET\";\r\n var remoteDepData = new RemoteDependencyData(logger, bd.id, bd.target, bd[_DYN_NAME /* @min:%2ename */], bd[STR_DURATION /* @min:%2eduration */], bd.success, bd.responseCode, method, bd.type, bd.correlationContext, customProperties, customMeasurements);\r\n var data = new Data(RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */], remoteDepData);\r\n return _createEnvelope(logger, RemoteDependencyData[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function EventEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var customProperties = {};\r\n var customMeasurements = {};\r\n if (telemetryItem[strBaseType] !== Event[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n customProperties[\"baseTypeSource\"] = telemetryItem[strBaseType]; // save the passed in base type as a property\r\n }\r\n if (telemetryItem[strBaseType] === Event[_DYN_DATA_TYPE /* @min:%2edataType */]) { // take collection\r\n customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n }\r\n else { // if its not a known type, convert to custom event\r\n if (telemetryItem[strBaseData]) {\r\n _extractPropsAndMeasurements(telemetryItem[strBaseData], customProperties, customMeasurements);\r\n }\r\n }\r\n // Extract root level properties from part C telemetryItem.data\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var eventName = telemetryItem[strBaseData][_DYN_NAME /* @min:%2ename */];\r\n var eventData = new Event(logger, eventName, customProperties, customMeasurements);\r\n var data = new Data(Event[_DYN_DATA_TYPE /* @min:%2edataType */], eventData);\r\n return _createEnvelope(logger, Event[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function ExceptionEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n // Extract root level properties from part C telemetryItem.data\r\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n var exData = Exception.CreateFromInterface(logger, bd, customProperties, customMeasurements);\r\n var data = new Data(Exception[_DYN_DATA_TYPE /* @min:%2edataType */], exData);\r\n return _createEnvelope(logger, Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function MetricEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var baseData = telemetryItem[strBaseData];\r\n var props = baseData[strProperties] || {};\r\n var measurements = baseData[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\r\n }\r\n var baseMetricData = new Metric(logger, baseData[_DYN_NAME /* @min:%2ename */], baseData.average, baseData.sampleCount, baseData.min, baseData.max, baseData.stdDev, props, measurements);\r\n var data = new Data(Metric[_DYN_DATA_TYPE /* @min:%2edataType */], baseMetricData);\r\n return _createEnvelope(logger, Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function PageViewEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n // Since duration is not part of the domain properties in Common Schema, extract it from part C\r\n var duration;\r\n var baseData = telemetryItem[strBaseData];\r\n if (!isNullOrUndefined(baseData) &&\r\n !isNullOrUndefined(baseData[strProperties]) &&\r\n !isNullOrUndefined(baseData[strProperties][STR_DURATION])) { // from part B properties\r\n duration = baseData[strProperties][STR_DURATION];\r\n delete baseData[strProperties][STR_DURATION];\r\n }\r\n else if (!isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */]) &&\r\n !isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION])) { // from custom properties\r\n duration = telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\r\n delete telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n // special case: pageview.id is grabbed from current operation id. Analytics plugin is decoupled from properties plugin, so this is done here instead. This can be made a default telemetry intializer instead if needed to be decoupled from channel\r\n var currentContextId;\r\n if (((telemetryItem.ext || {}).trace || {})[_DYN_TRACE_ID /* @min:%2etraceID */]) {\r\n currentContextId = telemetryItem.ext.trace[_DYN_TRACE_ID /* @min:%2etraceID */];\r\n }\r\n var id = bd.id || currentContextId;\r\n var name = bd[_DYN_NAME /* @min:%2ename */];\r\n var url = bd.uri;\r\n var properties = bd[strProperties] || {};\r\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n // refUri is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd.refUri)) {\r\n properties[\"refUri\"] = bd.refUri;\r\n }\r\n // pageType is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd.pageType)) {\r\n properties[\"pageType\"] = bd.pageType;\r\n }\r\n // isLoggedIn is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd.isLoggedIn)) {\r\n properties[\"isLoggedIn\"] = bd.isLoggedIn[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n // pageTags is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd[strProperties])) {\r\n var pageTags = bd[strProperties];\r\n objForEachKey(pageTags, function (key, value) {\r\n properties[key] = value;\r\n });\r\n }\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\r\n }\r\n var pageViewData = new PageView(logger, name, url, duration, properties, measurements, id);\r\n var data = new Data(PageView[_DYN_DATA_TYPE /* @min:%2edataType */], pageViewData);\r\n return _createEnvelope(logger, PageView[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function PageViewPerformanceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var bd = telemetryItem[strBaseData];\r\n var name = bd[_DYN_NAME /* @min:%2ename */];\r\n var url = bd.uri || bd.url;\r\n var properties = bd[strProperties] || {};\r\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\r\n }\r\n var baseData = new PageViewPerformance(logger, name, url, undefined, properties, measurements, bd);\r\n var data = new Data(PageViewPerformance[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\r\n return _createEnvelope(logger, PageViewPerformance[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function TraceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var message = telemetryItem[strBaseData].message;\r\n var severityLevel = telemetryItem[strBaseData].severityLevel;\r\n var props = telemetryItem[strBaseData][strProperties] || {};\r\n var measurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\r\n }\r\n var baseData = new Trace(logger, message, severityLevel, props, measurements);\r\n var data = new Data(Trace[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\r\n return _createEnvelope(logger, Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\n//# sourceMappingURL=EnvelopeCreator.js.map","import { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, arrForEach, arrIndexOf, dumpObj, getExceptionName, getJSON, isArray, isFunction, isNullOrUndefined, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_BUFFER_OVERRIDE, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_CONCAT, _DYN_COUNT, _DYN_CREATE_NEW, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENQUEUE, _DYN_EVENTS_LIMIT_IN_MEM, _DYN_ITEM, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_PUSH, _DYN_STRINGIFY, _DYN__BUFFER__KEY, _DYN__GET, _DYN__MAX__BUFFER__SIZE, _DYN__SENT__BUFFER__KEY } from \"./__DynamicConstants\";\r\nvar BaseSendBuffer = /** @class */ (function () {\r\n function BaseSendBuffer(logger, config) {\r\n var _buffer = [];\r\n var _bufferFullMessageSent = false;\r\n var _maxRetryCnt = config.maxRetryCnt;\r\n this[_DYN__GET /* @min:%2e_get */] = function () {\r\n return _buffer;\r\n };\r\n this._set = function (buffer) {\r\n _buffer = buffer;\r\n return _buffer;\r\n };\r\n dynamicProto(BaseSendBuffer, this, function (_self) {\r\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\r\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= config[_DYN_EVENTS_LIMIT_IN_MEM /* @min:%2eeventsLimitInMem */]) {\r\n // sent internal log only once per page view\r\n if (!_bufferFullMessageSent) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 105 /* _eInternalMessageId.InMemoryStorageBufferFull */, \"Maximum in-memory buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\r\n _bufferFullMessageSent = true;\r\n }\r\n return;\r\n }\r\n payload.cnt = payload.cnt || 0;\r\n // max retry is defined, and max retry is reached, do not add the payload to buffer\r\n if (!isNullOrUndefined(_maxRetryCnt)) {\r\n if (payload.cnt > _maxRetryCnt) {\r\n // TODO: add log here on dropping payloads\r\n return;\r\n }\r\n }\r\n _buffer[_DYN_PUSH /* @min:%2epush */](payload);\r\n return;\r\n };\r\n _self[_DYN_COUNT /* @min:%2ecount */] = function () {\r\n return _buffer[_DYN_LENGTH /* @min:%2elength */];\r\n };\r\n _self.size = function () {\r\n var size = _buffer[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < _buffer[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n size += (_buffer[lp].item)[_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n if (!config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */]) {\r\n size += 2;\r\n }\r\n return size;\r\n };\r\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\r\n _buffer = [];\r\n _bufferFullMessageSent = false;\r\n };\r\n _self.getItems = function () {\r\n return _buffer.slice(0);\r\n };\r\n _self.batchPayloads = function (payloads) {\r\n if (payloads && payloads[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var payloadStr_1 = [];\r\n arrForEach(payloads, function (payload) {\r\n payloadStr_1[_DYN_PUSH /* @min:%2epush */](payload[_DYN_ITEM /* @min:%2eitem */]);\r\n });\r\n var batch = config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */] ?\r\n payloadStr_1.join(\"\\n\") :\r\n \"[\" + payloadStr_1.join(\",\") + \"]\";\r\n return batch;\r\n }\r\n return null;\r\n };\r\n _self[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = function (newLogger, newConfig, canUseSessionStorage) {\r\n var items = _buffer.slice(0);\r\n newLogger = newLogger || logger;\r\n newConfig = newConfig || {};\r\n var newBuffer = !!canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);\r\n arrForEach(items, function (payload) {\r\n newBuffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n });\r\n return newBuffer;\r\n };\r\n });\r\n }\r\n BaseSendBuffer.prototype.enqueue = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n BaseSendBuffer.prototype.count = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\n BaseSendBuffer.prototype.size = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\n BaseSendBuffer.prototype.clear = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n BaseSendBuffer.prototype.getItems = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n BaseSendBuffer.prototype.batchPayloads = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n BaseSendBuffer.prototype.createNew = function (newLogger, newConfig, canUseSessionStorage) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return BaseSendBuffer;\r\n}());\r\n/*\r\n * An array based send buffer.\r\n */\r\nvar ArraySendBuffer = /** @class */ (function (_super) {\r\n __extends(ArraySendBuffer, _super);\r\n function ArraySendBuffer(logger, config) {\r\n var _this = _super.call(this, logger, config) || this;\r\n dynamicProto(ArraySendBuffer, _this, function (_self, _base) {\r\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\r\n _base[_DYN_CLEAR /* @min:%2eclear */]();\r\n };\r\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\r\n // not supported\r\n };\r\n });\r\n return _this;\r\n }\r\n ArraySendBuffer.prototype.markAsSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ArraySendBuffer.prototype.clearSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return ArraySendBuffer;\r\n}(BaseSendBuffer));\r\nexport { ArraySendBuffer };\r\nvar PREVIOUS_KEYS = [\"AI_buffer\", \"AI_sentBuffer\"];\r\n/*\r\n * Session storage buffer holds a copy of all unsent items in the browser session storage.\r\n */\r\nvar SessionStorageSendBuffer = /** @class */ (function (_super) {\r\n __extends(SessionStorageSendBuffer, _super);\r\n function SessionStorageSendBuffer(logger, config) {\r\n var _this = _super.call(this, logger, config) || this;\r\n var _bufferFullMessageSent = false;\r\n //Note: should not use config.namePrefix directly, because it will always refers to the latest namePrefix\r\n var _namePrefix = config === null || config === void 0 ? void 0 : config.namePrefix;\r\n // TODO: add remove buffer override as well\r\n var _b = config[_DYN_BUFFER_OVERRIDE /* @min:%2ebufferOverride */] || { getItem: utlGetSessionStorage, setItem: utlSetSessionStorage }, getItem = _b.getItem, setItem = _b.setItem;\r\n var _maxRetryCnt = config.maxRetryCnt;\r\n dynamicProto(SessionStorageSendBuffer, _this, function (_self, _base) {\r\n var bufferItems = _getBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */]);\r\n var itemsInSentBuffer = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n var previousItems = _getPreviousEvents();\r\n var notDeliveredItems = itemsInSentBuffer[_DYN_CONCAT /* @min:%2econcat */](previousItems);\r\n var buffer = _self._set(bufferItems[_DYN_CONCAT /* @min:%2econcat */](notDeliveredItems));\r\n // If the buffer has too many items, drop items from the end.\r\n if (buffer[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n buffer[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\r\n }\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], buffer);\r\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\r\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n // sent internal log only once per page view\r\n if (!_bufferFullMessageSent) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Maximum buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\r\n _bufferFullMessageSent = true;\r\n }\r\n return;\r\n }\r\n payload.cnt = payload.cnt || 0;\r\n // max retry is defined, and max retry is reached, do not add the payload to buffer\r\n if (!isNullOrUndefined(_maxRetryCnt)) {\r\n if (payload.cnt > _maxRetryCnt) {\r\n // TODO: add log here on dropping payloads\r\n return;\r\n }\r\n }\r\n _base[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n _setBuffer(SessionStorageSendBuffer.BUFFER_KEY, _self[_DYN__GET /* @min:%2e_get */]());\r\n };\r\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\r\n _base[_DYN_CLEAR /* @min:%2eclear */]();\r\n _setBuffer(SessionStorageSendBuffer.BUFFER_KEY, _self[_DYN__GET /* @min:%2e_get */]());\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\r\n _bufferFullMessageSent = false;\r\n };\r\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._set(_removePayloadsFromBuffer(payload, _self[_DYN__GET /* @min:%2e_get */]())));\r\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n if (sentElements instanceof Array && payload instanceof Array) {\r\n sentElements = sentElements[_DYN_CONCAT /* @min:%2econcat */](payload);\r\n if (sentElements[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n // We send telemetry normally. If the SENT_BUFFER is too big we don't add new elements\r\n // until we receive a response from the backend and the buffer has free space again (see clearSent method)\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Sent buffer reached its maximum size: \" + sentElements[_DYN_LENGTH /* @min:%2elength */], true);\r\n sentElements[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\r\n }\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\r\n }\r\n };\r\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\r\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n sentElements = _removePayloadsFromBuffer(payload, sentElements);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\r\n };\r\n _self[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = function (newLogger, newConfig, canUseSessionStorage) {\r\n canUseSessionStorage = !!canUseSessionStorage;\r\n var unsentItems = _self[_DYN__GET /* @min:%2e_get */]().slice(0);\r\n var sentItems = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]).slice(0);\r\n newLogger = newLogger || logger;\r\n newConfig = newConfig || {};\r\n // to make sure that we do not send duplicated payloads when it is switched back to previous one\r\n _self[_DYN_CLEAR /* @min:%2eclear */]();\r\n var newBuffer = canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);\r\n arrForEach(unsentItems, function (payload) {\r\n newBuffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n });\r\n if (canUseSessionStorage) {\r\n // arr buffer will clear all payloads if markAsSent() is called\r\n newBuffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](sentItems);\r\n }\r\n return newBuffer;\r\n };\r\n function _removePayloadsFromBuffer(payloads, buffer) {\r\n var remaining = [];\r\n var payloadStr = [];\r\n arrForEach(payloads, function (payload) {\r\n payloadStr[_DYN_PUSH /* @min:%2epush */](payload[_DYN_ITEM /* @min:%2eitem */]);\r\n });\r\n arrForEach(buffer, function (value) {\r\n if (!isFunction(value) && arrIndexOf(payloadStr, value[_DYN_ITEM /* @min:%2eitem */]) === -1) {\r\n remaining[_DYN_PUSH /* @min:%2epush */](value);\r\n }\r\n });\r\n return remaining;\r\n }\r\n function _getBuffer(key) {\r\n var prefixedKey = key;\r\n prefixedKey = _namePrefix ? _namePrefix + \"_\" + prefixedKey : prefixedKey;\r\n return _getBufferBase(prefixedKey);\r\n }\r\n function _getBufferBase(key) {\r\n try {\r\n var bufferJson = getItem(logger, key);\r\n if (bufferJson) {\r\n var buffer_1 = getJSON().parse(bufferJson);\r\n if (isString(buffer_1)) {\r\n // When using some version prototype.js the stringify / parse cycle does not decode array's correctly\r\n buffer_1 = getJSON().parse(buffer_1);\r\n }\r\n if (buffer_1 && isArray(buffer_1)) {\r\n return buffer_1;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 42 /* _eInternalMessageId.FailedToRestoreStorageBuffer */, \" storage key: \" + key + \", \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n return [];\r\n }\r\n function _setBuffer(key, buffer) {\r\n var prefixedKey = key;\r\n try {\r\n prefixedKey = _namePrefix ? _namePrefix + \"_\" + prefixedKey : prefixedKey;\r\n var bufferJson = JSON[_DYN_STRINGIFY /* @min:%2estringify */](buffer);\r\n setItem(logger, prefixedKey, bufferJson);\r\n }\r\n catch (e) {\r\n // if there was an error, clear the buffer\r\n // telemetry is stored in the _buffer array so we won't loose any items\r\n setItem(logger, prefixedKey, JSON[_DYN_STRINGIFY /* @min:%2estringify */]([]));\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 41 /* _eInternalMessageId.FailedToSetStorageBuffer */, \" storage key: \" + prefixedKey + \", \" + getExceptionName(e) + \". Buffer cleared\", { exception: dumpObj(e) });\r\n }\r\n }\r\n // this removes buffer with prefix+key\r\n function _getPreviousEvents() {\r\n var items = [];\r\n try {\r\n arrForEach(PREVIOUS_KEYS, function (key) {\r\n var events = _getItemsFromPreviousKey(key);\r\n items = items[_DYN_CONCAT /* @min:%2econcat */](events);\r\n // to make sure that we also transfer items from old prefixed + key buffer\r\n if (_namePrefix) {\r\n var prefixedKey = _namePrefix + \"_\" + key;\r\n var prefixEvents = _getItemsFromPreviousKey(prefixedKey);\r\n items = items[_DYN_CONCAT /* @min:%2econcat */](prefixEvents);\r\n }\r\n });\r\n return items;\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 41 /* _eInternalMessageId.FailedToSetStorageBuffer */, \"Transfer events from previous buffers: \" + getExceptionName(e) + \". previous Buffer items can not be removed\", { exception: dumpObj(e) });\r\n }\r\n return [];\r\n }\r\n // transform string[] to IInternalStorageItem[]\r\n function _getItemsFromPreviousKey(key) {\r\n try {\r\n var items = _getBufferBase(key);\r\n var transFormedItems_1 = [];\r\n arrForEach(items, function (item) {\r\n var internalItem = {\r\n item: item,\r\n cnt: 0 // previous events will be default to 0 count\r\n };\r\n transFormedItems_1[_DYN_PUSH /* @min:%2epush */](internalItem);\r\n });\r\n // remove the session storage if we can add events back\r\n utlRemoveSessionStorage(logger, key);\r\n return transFormedItems_1;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return [];\r\n }\r\n });\r\n return _this;\r\n }\r\n SessionStorageSendBuffer.prototype.enqueue = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.clear = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.markAsSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.clearSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.createNew = function (newLogger, newConfig, canUseSessionStorage) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n var _a;\r\n _a = SessionStorageSendBuffer;\r\n SessionStorageSendBuffer.VERSION = \"_1\";\r\n SessionStorageSendBuffer.BUFFER_KEY = \"AI_buffer\" + _a.VERSION;\r\n SessionStorageSendBuffer.SENT_BUFFER_KEY = \"AI_sentBuffer\" + _a.VERSION;\r\n // Maximum number of payloads stored in the buffer. If the buffer is full, new elements will be dropped.\r\n SessionStorageSendBuffer.MAX_BUFFER_SIZE = 2000;\r\n return SessionStorageSendBuffer;\r\n}(BaseSendBuffer));\r\nexport { SessionStorageSendBuffer };\r\n//# sourceMappingURL=SendBuffer.js.map","var _a, _b;\r\nimport { __assign, __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { BreezeChannelIdentifier, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, Event, Exception, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate, Trace, createOfflineListener, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage, utlSetStoragePrefix } from \"@microsoft/applicationinsights-common\";\r\nimport { ActiveStatus, BaseTelemetryPlugin, SenderPostManager, _throwInternal, _warnToConsole, arrForEach, cfgDfBoolean, cfgDfValidate, createProcessTelemetryContext, createUniqueNamespace, dateNow, dumpObj, formatErrorMessageXdr, formatErrorMessageXhr, getExceptionName, getIEVersion, isArray, isBeaconsSupported, isFetchSupported, isNullOrUndefined, mergeEvtNamespace, objExtend, onConfigChange, parseResponse, prependTransports, runTargetUnload } from \"@microsoft/applicationinsights-core-js\";\r\nimport { isNumber, isString, isTruthy, objDeepFreeze, objDefine, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { DependencyEnvelopeCreator, EventEnvelopeCreator, ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator, PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator } from \"./EnvelopeCreator\";\r\nimport { ArraySendBuffer, SessionStorageSendBuffer } from \"./SendBuffer\";\r\nimport { Serializer } from \"./Serializer\";\r\nimport { Sample } from \"./TelemetryProcessors/Sample\";\r\nimport { _DYN_ALWAYS_USE_XHR_OVERR4, _DYN_BASE_TYPE, _DYN_BUFFER_OVERRIDE, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_CONVERT_UNDEFINED, _DYN_COUNT, _DYN_CREATE_NEW, _DYN_CUSTOM_HEADERS, _DYN_DATA, _DYN_DIAG_LOG, _DYN_DISABLE_SEND_BEACON_7, _DYN_DISABLE_XHR, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENABLE_SEND_PROMISE, _DYN_ENABLE_SESSION_STORA5, _DYN_ENQUEUE, _DYN_EVENTS_LIMIT_IN_MEM, _DYN_EVENTS_SEND_REQUEST, _DYN_GET_SENDER_INST, _DYN_INITIALIZE, _DYN_INSTRUMENTATION_KEY, _DYN_IS_BEACON_API_DISABL3, _DYN_ITEM, _DYN_ITEMS_ACCEPTED, _DYN_ITEMS_RECEIVED, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_MAX_BATCH_INTERVAL, _DYN_MAX_BATCH_SIZE_IN_BY1, _DYN_ONUNLOAD_DISABLE_BEA2, _DYN_ONUNLOAD_DISABLE_FET6, _DYN_ORI_PAYLOAD, _DYN_PUSH, _DYN_SAMPLE_RATE, _DYN_SERIALIZE, _DYN_TAGS, _DYN_TRIGGER_SEND, _DYN_UNLOAD_TRANSPORTS, _DYN__BUFFER, _DYN__ON_ERROR, _DYN__ON_PARTIAL_SUCCESS, _DYN__ON_SUCCESS, _DYN__SENDER } from \"./__DynamicConstants\";\r\nvar UNDEFINED_VALUE = undefined;\r\nvar EMPTY_STR = \"\";\r\nvar FetchSyncRequestSizeLimitBytes = 65000; // approx 64kb (the current Edge, Firefox and Chrome max limit)\r\nfunction _getResponseText(xhr) {\r\n try {\r\n return xhr.responseText;\r\n }\r\n catch (e) {\r\n // Best effort, as XHR may throw while XDR wont so just ignore\r\n }\r\n return null;\r\n}\r\nfunction isOverrideFn(httpXHROverride) {\r\n return httpXHROverride && httpXHROverride.sendPOST;\r\n}\r\nvar defaultAppInsightsChannelConfig = objDeepFreeze((_a = {\r\n // Use the default value (handles empty string in the configuration)\r\n endpointUrl: cfgDfValidate(isTruthy, DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH)\r\n },\r\n _a[_DYN_EMIT_LINE_DELIMITED_0 /* @min:emitLineDelimitedJson */] = cfgDfBoolean(),\r\n _a[_DYN_MAX_BATCH_INTERVAL /* @min:maxBatchInterval */] = 15000,\r\n _a[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:maxBatchSizeInBytes */] = 102400,\r\n _a.disableTelemetry = cfgDfBoolean(),\r\n _a[_DYN_ENABLE_SESSION_STORA5 /* @min:enableSessionStorageBuffer */] = cfgDfBoolean(true),\r\n _a.isRetryDisabled = cfgDfBoolean(),\r\n _a[_DYN_IS_BEACON_API_DISABL3 /* @min:isBeaconApiDisabled */] = cfgDfBoolean(true),\r\n _a[_DYN_DISABLE_SEND_BEACON_7 /* @min:disableSendBeaconSplit */] = cfgDfBoolean(true),\r\n _a[_DYN_DISABLE_XHR /* @min:disableXhr */] = cfgDfBoolean(),\r\n _a[_DYN_ONUNLOAD_DISABLE_FET6 /* @min:onunloadDisableFetch */] = cfgDfBoolean(),\r\n _a[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:onunloadDisableBeacon */] = cfgDfBoolean(),\r\n _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = UNDEFINED_VALUE,\r\n _a.namePrefix = UNDEFINED_VALUE,\r\n _a.samplingPercentage = cfgDfValidate(_chkSampling, 100),\r\n _a[_DYN_CUSTOM_HEADERS /* @min:customHeaders */] = UNDEFINED_VALUE,\r\n _a[_DYN_CONVERT_UNDEFINED /* @min:convertUndefined */] = UNDEFINED_VALUE,\r\n _a[_DYN_EVENTS_LIMIT_IN_MEM /* @min:eventsLimitInMem */] = 10000,\r\n _a[_DYN_BUFFER_OVERRIDE /* @min:bufferOverride */] = false,\r\n _a.httpXHROverride = { isVal: isOverrideFn, v: UNDEFINED_VALUE },\r\n _a[_DYN_ALWAYS_USE_XHR_OVERR4 /* @min:alwaysUseXhrOverride */] = cfgDfBoolean(),\r\n _a.transports = UNDEFINED_VALUE,\r\n _a.retryCodes = UNDEFINED_VALUE,\r\n _a.maxRetryCnt = { isVal: isNumber, v: 10 },\r\n _a));\r\nfunction _chkSampling(value) {\r\n return !isNaN(value) && value > 0 && value <= 100;\r\n}\r\nvar EnvelopeTypeCreator = (_b = {},\r\n _b[Event.dataType] = EventEnvelopeCreator,\r\n _b[Trace.dataType] = TraceEnvelopeCreator,\r\n _b[PageView.dataType] = PageViewEnvelopeCreator,\r\n _b[PageViewPerformance.dataType] = PageViewPerformanceEnvelopeCreator,\r\n _b[Exception.dataType] = ExceptionEnvelopeCreator,\r\n _b[Metric.dataType] = MetricEnvelopeCreator,\r\n _b[RemoteDependencyData.dataType] = DependencyEnvelopeCreator,\r\n _b);\r\nvar Sender = /** @class */ (function (_super) {\r\n __extends(Sender, _super);\r\n function Sender() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 1001;\r\n _this.identifier = BreezeChannelIdentifier;\r\n // Don't set the defaults here, set them in the _initDefaults() as this is also called during unload\r\n var _consecutiveErrors; // How many times in a row a retryable error condition has occurred.\r\n var _retryAt; // The time to retry at in milliseconds from 1970/01/01 (this makes the timer calculation easy).\r\n var _lastSend; // The time of the last send operation.\r\n var _paused; // Flag indicating that the sending should be paused\r\n var _timeoutHandle; // Handle to the timer for delayed sending of batches of data.\r\n var _serializer;\r\n var _stamp_specific_redirects;\r\n var _headers;\r\n var _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)\r\n var _syncUnloadSender; // The identified sender to use for the synchronous unload stage\r\n var _offlineListener;\r\n var _evtNamespace;\r\n var _endpointUrl;\r\n var _orgEndpointUrl;\r\n var _maxBatchSizeInBytes;\r\n var _beaconSupported;\r\n var _beaconOnUnloadSupported;\r\n var _beaconNormalSupported;\r\n var _customHeaders;\r\n var _disableTelemetry;\r\n var _instrumentationKey;\r\n var _convertUndefined;\r\n var _isRetryDisabled;\r\n var _maxBatchInterval;\r\n var _sessionStorageUsed;\r\n var _bufferOverrideUsed;\r\n var _namePrefix;\r\n var _enableSendPromise;\r\n var _alwaysUseCustomSend;\r\n var _disableXhr;\r\n var _fetchKeepAlive;\r\n var _xhrSend;\r\n var _fallbackSend;\r\n var _disableBeaconSplit;\r\n var _sendPostMgr;\r\n var _retryCodes;\r\n dynamicProto(Sender, _this, function (_self, _base) {\r\n _initDefaults();\r\n _self.pause = function () {\r\n _clearScheduledTimer();\r\n _paused = true;\r\n };\r\n _self.resume = function () {\r\n if (_paused) {\r\n _paused = false;\r\n _retryAt = null;\r\n // flush if we have exceeded the max-size already\r\n _checkMaxSize();\r\n _setupTimer();\r\n }\r\n };\r\n _self.flush = function (isAsync, callBack, sendReason) {\r\n if (isAsync === void 0) { isAsync = true; }\r\n if (!_paused) {\r\n // Clear the normal schedule timer as we are going to try and flush ASAP\r\n _clearScheduledTimer();\r\n try {\r\n return _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](isAsync, null, sendReason || 1 /* SendRequestReason.ManualFlush */);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 22 /* _eInternalMessageId.FlushFailed */, \"flush failed, telemetry will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n };\r\n _self.onunloadFlush = function () {\r\n if (!_paused) {\r\n if (_beaconSupported || _alwaysUseCustomSend) {\r\n try {\r\n return _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, _doUnloadSend, 2 /* SendRequestReason.Unload */);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 20 /* _eInternalMessageId.FailedToSendQueuedTelemetry */, \"failed to flush with beacon sender on page unload, telemetry will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n else {\r\n _self.flush(false);\r\n }\r\n }\r\n };\r\n _self.addHeader = function (name, value) {\r\n _headers[name] = value;\r\n };\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, core, extensions, pluginChain) {\r\n if (_self.isInitialized()) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender is already initialized\");\r\n }\r\n _base[_DYN_INITIALIZE /* @min:%2einitialize */](config, core, extensions, pluginChain);\r\n var identifier = _self.identifier;\r\n _serializer = new Serializer(core.logger);\r\n _consecutiveErrors = 0;\r\n _retryAt = null;\r\n _lastSend = 0;\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\r\n _stamp_specific_redirects = 0;\r\n var diagLog = _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"Sender\"), core.evtNamespace && core.evtNamespace());\r\n _offlineListener = createOfflineListener(_evtNamespace);\r\n // This function will be re-called whenever any referenced configuration is changed\r\n _self._addHook(onConfigChange(config, function (details) {\r\n var config = details.cfg;\r\n if (config.storagePrefix) {\r\n utlSetStoragePrefix(config.storagePrefix);\r\n }\r\n var ctx = createProcessTelemetryContext(null, config, core);\r\n var senderConfig = ctx.getExtCfg(identifier, defaultAppInsightsChannelConfig);\r\n objDefine(_self, \"_senderConfig\", {\r\n g: function () {\r\n return senderConfig;\r\n }\r\n });\r\n // or is not string\r\n if (core.activeStatus() === ActiveStatus.PENDING) {\r\n // waiting for core promises to be resolved\r\n // NOTE: if active status is set to pending, stop sending, clear timer here\r\n _self.pause();\r\n }\r\n else if (core.activeStatus() === ActiveStatus.ACTIVE) {\r\n // core status changed from pending to other status\r\n _self.resume();\r\n }\r\n // Only update the endpoint if the original config !== the current config\r\n // This is so any redirect endpointUrl is not overwritten\r\n if (_orgEndpointUrl !== senderConfig.endpointUrl) {\r\n if (_orgEndpointUrl) {\r\n // TODO: add doc to remind users to flush before changing endpoint, otherwise all unsent payload will be sent to new endpoint\r\n }\r\n _endpointUrl = _orgEndpointUrl = senderConfig.endpointUrl;\r\n }\r\n if (_customHeaders && _customHeaders !== senderConfig[_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */]) {\r\n // Removing any previously defined custom headers as they have changed\r\n arrForEach(_customHeaders, function (customHeader) {\r\n delete _headers[customHeader.header];\r\n });\r\n }\r\n _maxBatchSizeInBytes = senderConfig[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:%2emaxBatchSizeInBytes */];\r\n _beaconSupported = (senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:%2eonunloadDisableBeacon */] === false || senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */] === false) && isBeaconsSupported();\r\n _beaconOnUnloadSupported = senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:%2eonunloadDisableBeacon */] === false && isBeaconsSupported();\r\n _beaconNormalSupported = senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */] === false && isBeaconsSupported();\r\n _alwaysUseCustomSend = senderConfig[_DYN_ALWAYS_USE_XHR_OVERR4 /* @min:%2ealwaysUseXhrOverride */];\r\n _disableXhr = !!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */];\r\n _retryCodes = senderConfig.retryCodes;\r\n var bufferOverride = senderConfig[_DYN_BUFFER_OVERRIDE /* @min:%2ebufferOverride */];\r\n var canUseSessionStorage = !!senderConfig[_DYN_ENABLE_SESSION_STORA5 /* @min:%2eenableSessionStorageBuffer */] &&\r\n (!!bufferOverride || utlCanUseSessionStorage());\r\n var namePrefix = senderConfig.namePrefix;\r\n //Note: emitLineDelimitedJson and eventsLimitInMem is directly accessed via config in senderBuffer\r\n //Therefore, if canUseSessionStorage is not changed, we do not need to re initialize a new one\r\n var shouldUpdate = (canUseSessionStorage !== _sessionStorageUsed)\r\n || (canUseSessionStorage && (_namePrefix !== namePrefix)) // prefixName is only used in session storage\r\n || (canUseSessionStorage && (_bufferOverrideUsed !== bufferOverride));\r\n if (_self[_DYN__BUFFER /* @min:%2e_buffer */]) {\r\n // case1 (Pre and Now enableSessionStorageBuffer settings are same)\r\n // if namePrefix changes, transfer current buffer to new buffer\r\n // else no action needed\r\n //case2 (Pre and Now enableSessionStorageBuffer settings are changed)\r\n // transfer current buffer to new buffer\r\n if (shouldUpdate) {\r\n try {\r\n _self._buffer = _self._buffer[_DYN_CREATE_NEW /* @min:%2ecreateNew */](diagLog, senderConfig, canUseSessionStorage);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 12 /* _eInternalMessageId.FailedAddingTelemetryToBuffer */, \"failed to transfer telemetry to different buffer storage, telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n _checkMaxSize();\r\n }\r\n else {\r\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = canUseSessionStorage\r\n ? new SessionStorageSendBuffer(diagLog, senderConfig) : new ArraySendBuffer(diagLog, senderConfig);\r\n }\r\n _namePrefix = namePrefix;\r\n _sessionStorageUsed = canUseSessionStorage;\r\n _bufferOverrideUsed = bufferOverride;\r\n _fetchKeepAlive = !senderConfig[_DYN_ONUNLOAD_DISABLE_FET6 /* @min:%2eonunloadDisableFetch */] && isFetchSupported(true);\r\n _disableBeaconSplit = !!senderConfig[_DYN_DISABLE_SEND_BEACON_7 /* @min:%2edisableSendBeaconSplit */];\r\n _self._sample = new Sample(senderConfig.samplingPercentage, diagLog);\r\n _instrumentationKey = senderConfig[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\r\n if (!_validateInstrumentationKey(_instrumentationKey, config)) {\r\n _throwInternal(diagLog, 1 /* eLoggingSeverity.CRITICAL */, 100 /* _eInternalMessageId.InvalidInstrumentationKey */, \"Invalid Instrumentation key \" + _instrumentationKey);\r\n }\r\n _customHeaders = senderConfig[_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */];\r\n if (isString(_endpointUrl) && !isInternalApplicationInsightsEndpoint(_endpointUrl) && _customHeaders && _customHeaders[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(_customHeaders, function (customHeader) {\r\n _this.addHeader(customHeader.header, customHeader.value);\r\n });\r\n }\r\n else {\r\n _customHeaders = null;\r\n }\r\n _enableSendPromise = senderConfig[_DYN_ENABLE_SEND_PROMISE /* @min:%2eenableSendPromise */];\r\n var sendPostConfig = _getSendPostMgrConfig();\r\n // only init it once\r\n if (!_sendPostMgr) {\r\n _sendPostMgr = new SenderPostManager();\r\n _sendPostMgr[_DYN_INITIALIZE /* @min:%2einitialize */](sendPostConfig, diagLog);\r\n }\r\n else {\r\n _sendPostMgr.SetConfig(sendPostConfig);\r\n }\r\n var customInterface = senderConfig.httpXHROverride;\r\n var httpInterface = null;\r\n var syncInterface = null;\r\n // User requested transport(s) values > Beacon > Fetch > XHR\r\n // Beacon would be filtered out if user has set disableBeaconApi to true at _getSenderInterface\r\n var theTransports = prependTransports([3 /* TransportType.Beacon */, 1 /* TransportType.Xhr */, 2 /* TransportType.Fetch */], senderConfig.transports);\r\n httpInterface = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */](theTransports, false);\r\n var xhrInterface = _sendPostMgr && _sendPostMgr.getFallbackInst();\r\n _xhrSend = function (payload, isAsync) {\r\n return _doSend(xhrInterface, payload, isAsync);\r\n };\r\n _fallbackSend = function (payload, isAsync) {\r\n return _doSend(xhrInterface, payload, isAsync, false);\r\n };\r\n httpInterface = _alwaysUseCustomSend ? customInterface : (httpInterface || customInterface || xhrInterface);\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = function (payload, isAsync) {\r\n return _doSend(httpInterface, payload, isAsync);\r\n };\r\n if (_fetchKeepAlive) {\r\n // Try and use the fetch with keepalive\r\n _syncUnloadSender = _fetchKeepAliveSender;\r\n }\r\n var syncTransports = prependTransports([3 /* TransportType.Beacon */, 1 /* TransportType.Xhr */], senderConfig[_DYN_UNLOAD_TRANSPORTS /* @min:%2eunloadTransports */]);\r\n if (!_fetchKeepAlive) {\r\n // remove fetch from theTransports\r\n syncTransports = syncTransports.filter(function (transport) { return transport !== 2 /* TransportType.Fetch */; });\r\n }\r\n syncInterface = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */](syncTransports, true);\r\n syncInterface = _alwaysUseCustomSend ? customInterface : (syncInterface || customInterface);\r\n if ((_alwaysUseCustomSend || senderConfig[_DYN_UNLOAD_TRANSPORTS /* @min:%2eunloadTransports */] || !_syncUnloadSender) && syncInterface) {\r\n _syncUnloadSender = function (payload, isAsync) {\r\n return _doSend(syncInterface, payload, isAsync);\r\n };\r\n }\r\n if (!_syncUnloadSender) {\r\n _syncUnloadSender = _xhrSend;\r\n }\r\n _disableTelemetry = senderConfig.disableTelemetry;\r\n _convertUndefined = senderConfig[_DYN_CONVERT_UNDEFINED /* @min:%2econvertUndefined */] || UNDEFINED_VALUE;\r\n _isRetryDisabled = senderConfig.isRetryDisabled;\r\n _maxBatchInterval = senderConfig[_DYN_MAX_BATCH_INTERVAL /* @min:%2emaxBatchInterval */];\r\n }));\r\n };\r\n _self.processTelemetry = function (telemetryItem, itemCtx) {\r\n var _a;\r\n itemCtx = _self._getTelCtx(itemCtx);\r\n var diagLogger = itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n try {\r\n var isValidate = _validate(telemetryItem, diagLogger);\r\n if (!isValidate) {\r\n return;\r\n }\r\n var aiEnvelope = _getEnvelope(telemetryItem, diagLogger);\r\n if (!aiEnvelope) {\r\n return;\r\n }\r\n // check if the incoming payload is too large, truncate if necessary\r\n var payload = _serializer[_DYN_SERIALIZE /* @min:%2eserialize */](aiEnvelope);\r\n // flush if we would exceed the max-size limit by adding this item\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n _checkMaxSize(payload);\r\n var payloadItem = (_a = {},\r\n _a[_DYN_ITEM /* @min:item */] = payload,\r\n _a.cnt = 0 // inital cnt will always be 0\r\n ,\r\n _a);\r\n // enqueue the payload\r\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payloadItem);\r\n // ensure an invocation timeout is set\r\n _setupTimer();\r\n }\r\n catch (e) {\r\n _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 12 /* _eInternalMessageId.FailedAddingTelemetryToBuffer */, \"Failed adding telemetry to the sender's buffer, some telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n // hand off the telemetry item to the next plugin\r\n _self.processNext(telemetryItem, itemCtx);\r\n };\r\n _self.isCompletelyIdle = function () {\r\n return !_paused && _syncFetchPayload === 0 && _self._buffer[_DYN_COUNT /* @min:%2ecount */]() === 0;\r\n };\r\n /**\r\n * xhr state changes\r\n */\r\n _self._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) {\r\n // since version 3.2.0, this function is no-op\r\n if (_isStringArr(payload)) {\r\n return;\r\n }\r\n return _xhrReadyStateChange(xhr, payload, countOfItemsInPayload);\r\n };\r\n /**\r\n * Immediately send buffered data\r\n * @param async - {boolean} - Indicates if the events should be sent asynchronously\r\n * @param forcedSender - {SenderFunction} - Indicates the forcedSender, undefined if not passed\r\n */\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */] = function (async, forcedSender, sendReason) {\r\n if (async === void 0) { async = true; }\r\n var result;\r\n if (!_paused) {\r\n try {\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n // Send data only if disableTelemetry is false\r\n if (!_disableTelemetry) {\r\n if (buffer[_DYN_COUNT /* @min:%2ecount */]() > 0) {\r\n var payload = buffer.getItems();\r\n _notifySendRequest(sendReason || 0 /* SendRequestReason.Undefined */, async);\r\n // invoke send\r\n if (forcedSender) {\r\n result = forcedSender.call(_self, payload, async);\r\n }\r\n else {\r\n result = _self[_DYN__SENDER /* @min:%2e_sender */](payload, async);\r\n }\r\n }\r\n // update lastSend time to enable throttling\r\n _lastSend = +new Date;\r\n }\r\n else {\r\n buffer[_DYN_CLEAR /* @min:%2eclear */]();\r\n }\r\n _clearScheduledTimer();\r\n }\r\n catch (e) {\r\n /* Ignore this error for IE under v10 */\r\n var ieVer = getIEVersion();\r\n if (!ieVer || ieVer > 9) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Telemetry transmission failed, some telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n }\r\n return result;\r\n };\r\n _self.getOfflineSupport = function () {\r\n var _a;\r\n return _a = {\r\n getUrl: function () {\r\n return _endpointUrl;\r\n },\r\n createPayload: _createPayload\r\n },\r\n _a[_DYN_SERIALIZE /* @min:serialize */] = _serialize,\r\n _a.batch = _batch,\r\n _a.shouldProcess = function (evt) {\r\n return !!_validate(evt);\r\n },\r\n _a;\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n _self.onunloadFlush();\r\n runTargetUnload(_offlineListener, false);\r\n _initDefaults();\r\n };\r\n /**\r\n * error handler\r\n */\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */] = function (payload, message, event) {\r\n // since version 3.1.3, string[] is no-op\r\n if (_isStringArr(payload)) {\r\n return;\r\n }\r\n return _onError(payload, message, event);\r\n };\r\n /**\r\n * partial success handler\r\n */\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */] = function (payload, results) {\r\n // since version 3.1.3, string[] is no-op\r\n if (_isStringArr(payload)) {\r\n return;\r\n }\r\n return _onPartialSuccess(payload, results);\r\n };\r\n /**\r\n * success handler\r\n */\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */] = function (payload, countOfItemsInPayload) {\r\n // since version 3.1.3, string[] is no-op\r\n if (_isStringArr(payload)) {\r\n return;\r\n }\r\n return _onSuccess(payload, countOfItemsInPayload);\r\n //_self._buffer && _self._buffer.clearSent(payload);\r\n };\r\n /**\r\n * xdr state changes\r\n */\r\n _self._xdrOnLoad = function (xdr, payload) {\r\n // since version 3.1.3, string[] is no-op\r\n if (_isStringArr(payload)) {\r\n return;\r\n }\r\n return _xdrOnLoad(xdr, payload);\r\n };\r\n function _xdrOnLoad(xdr, payload) {\r\n var responseText = _getResponseText(xdr);\r\n if (xdr && (responseText + \"\" === \"200\" || responseText === \"\")) {\r\n _consecutiveErrors = 0;\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, 0);\r\n }\r\n else {\r\n var results = parseResponse(responseText);\r\n if (results && results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] && results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] > results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]\r\n && !_isRetryDisabled) {\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, results);\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, formatErrorMessageXdr(xdr));\r\n }\r\n }\r\n }\r\n function _getSendPostMgrConfig() {\r\n var _a;\r\n try {\r\n var onCompleteFuncs = {\r\n xdrOnComplete: function (xdr, oncomplete, payload) {\r\n var data = _getPayloadArr(payload);\r\n if (!data) {\r\n return;\r\n }\r\n return _xdrOnLoad(xdr, data);\r\n },\r\n fetchOnComplete: function (response, onComplete, resValue, payload) {\r\n var data = _getPayloadArr(payload);\r\n if (!data) {\r\n return;\r\n }\r\n return _checkResponsStatus(response.status, data, response.url, data[_DYN_LENGTH /* @min:%2elength */], response.statusText, resValue || \"\");\r\n },\r\n xhrOnComplete: function (request, oncomplete, payload) {\r\n var data = _getPayloadArr(payload);\r\n if (!data) {\r\n return;\r\n }\r\n return _xhrReadyStateChange(request, data, data[_DYN_LENGTH /* @min:%2elength */]);\r\n },\r\n beaconOnRetry: function (data, onComplete, canSend) {\r\n return _onBeaconRetry(data, onComplete, canSend);\r\n }\r\n };\r\n var config = (_a = {},\r\n _a[_DYN_ENABLE_SEND_PROMISE /* @min:enableSendPromise */] = _enableSendPromise,\r\n _a.isOneDs = false,\r\n _a.disableCredentials = false,\r\n _a[_DYN_DISABLE_XHR /* @min:disableXhr */] = _disableXhr,\r\n _a.disableBeacon = !_beaconNormalSupported,\r\n _a.disableBeaconSync = !_beaconOnUnloadSupported,\r\n _a.senderOnCompleteCallBack = onCompleteFuncs,\r\n _a);\r\n return config;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n /**\r\n * xhr state changes\r\n */\r\n function _xhrReadyStateChange(xhr, payload, countOfItemsInPayload) {\r\n if (xhr.readyState === 4) {\r\n _checkResponsStatus(xhr.status, payload, xhr.responseURL, countOfItemsInPayload, formatErrorMessageXhr(xhr), _getResponseText(xhr) || xhr.response);\r\n }\r\n }\r\n /**\r\n * error handler\r\n */\r\n function _onError(payload, message, event) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 26 /* _eInternalMessageId.OnError */, \"Failed to send telemetry.\", { message: message });\r\n _self._buffer && _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n }\r\n /**\r\n * partial success handler\r\n */\r\n function _onPartialSuccess(payload, results) {\r\n var failed = [];\r\n var retry = [];\r\n // Iterate through the reversed array of errors so that splicing doesn't have invalid indexes after the first item.\r\n var errors = results.errors.reverse();\r\n for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {\r\n var error = errors_1[_i];\r\n var extracted = payload.splice(error.index, 1)[0];\r\n if (_isRetriable(error.statusCode)) {\r\n retry[_DYN_PUSH /* @min:%2epush */](extracted);\r\n }\r\n else {\r\n // All other errors, including: 402 (Monthly quota exceeded) and 439 (Too many requests and refresh cache).\r\n failed[_DYN_PUSH /* @min:%2epush */](extracted);\r\n }\r\n }\r\n if (payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]);\r\n }\r\n if (failed[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](failed, formatErrorMessageXhr(null, [\"partial success\", results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */], \"of\", results.itemsReceived].join(\" \")));\r\n }\r\n if (retry[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _resendPayload(retry);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Partial success. \" +\r\n \"Delivered: \" + payload[_DYN_LENGTH /* @min:%2elength */] + \", Failed: \" + failed[_DYN_LENGTH /* @min:%2elength */] +\r\n \". Will retry to send \" + retry[_DYN_LENGTH /* @min:%2elength */] + \" our of \" + results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] + \" items\");\r\n }\r\n }\r\n /**\r\n * success handler\r\n */\r\n function _onSuccess(payload, countOfItemsInPayload) {\r\n _self._buffer && _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n }\r\n function _getPayloadArr(payload) {\r\n try {\r\n if (payload) {\r\n var internalPayload = payload;\r\n var arr = internalPayload[_DYN_ORI_PAYLOAD /* @min:%2eoriPayload */];\r\n if (arr && arr[_DYN_LENGTH /* @min:%2elength */]) {\r\n return arr;\r\n }\r\n return null;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n function _validate(telemetryItem, diagLogger) {\r\n if (_disableTelemetry) {\r\n // Do not send/save data\r\n return false;\r\n }\r\n // validate input\r\n if (!telemetryItem) {\r\n diagLogger && _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 7 /* _eInternalMessageId.CannotSendEmptyTelemetry */, \"Cannot send empty telemetry\");\r\n return false;\r\n }\r\n // validate event\r\n if (telemetryItem.baseData && !telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\r\n diagLogger && _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 70 /* _eInternalMessageId.InvalidEvent */, \"Cannot send telemetry without baseData and baseType\");\r\n return false;\r\n }\r\n if (!telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\r\n // Default\r\n telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */] = \"EventData\";\r\n }\r\n // ensure a sender was constructed\r\n if (!_self[_DYN__SENDER /* @min:%2e_sender */]) {\r\n diagLogger && _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender was not initialized\");\r\n return false;\r\n }\r\n // check if this item should be sampled in, else add sampleRate tag\r\n if (!_isSampledIn(telemetryItem)) {\r\n // Item is sampled out, do not send it\r\n diagLogger && _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 33 /* _eInternalMessageId.TelemetrySampledAndNotSent */, \"Telemetry item was sampled out and not sent\", { SampleRate: _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] });\r\n return false;\r\n }\r\n else {\r\n telemetryItem[SampleRate] = _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */];\r\n }\r\n return true;\r\n }\r\n function _getEnvelope(telemetryItem, diagLogger) {\r\n // construct an envelope that Application Insights endpoint can understand\r\n // if ikey of telemetry is provided and not empty, envelope will use this iKey instead of senderConfig iKey\r\n var defaultEnvelopeIkey = telemetryItem.iKey || _instrumentationKey;\r\n var aiEnvelope = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, diagLogger, _convertUndefined);\r\n if (!aiEnvelope) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 47 /* _eInternalMessageId.CreateEnvelopeError */, \"Unable to create an AppInsights envelope\");\r\n return;\r\n }\r\n var doNotSendItem = false;\r\n // this is for running in legacy mode, where customer may already have a custom initializer present\r\n if (telemetryItem[_DYN_TAGS /* @min:%2etags */] && telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy]) {\r\n arrForEach(telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy], function (callBack) {\r\n try {\r\n if (callBack && callBack(aiEnvelope) === false) {\r\n doNotSendItem = true;\r\n _warnToConsole(diagLogger, \"Telemetry processor check returns false\");\r\n }\r\n }\r\n catch (e) {\r\n // log error but dont stop executing rest of the telemetry initializers\r\n // doNotSendItem = true;\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"One of telemetry initializers failed, telemetry item will not be sent: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n });\r\n delete telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy];\r\n }\r\n if (doNotSendItem) {\r\n return; // do not send, no need to execute next plugin\r\n }\r\n return aiEnvelope;\r\n }\r\n function _serialize(item) {\r\n var rlt = EMPTY_STR;\r\n var diagLogger = _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n try {\r\n var valid = _validate(item, diagLogger);\r\n var envelope = null;\r\n if (valid) {\r\n envelope = _getEnvelope(item, diagLogger);\r\n }\r\n if (envelope) {\r\n rlt = _serializer[_DYN_SERIALIZE /* @min:%2eserialize */](envelope);\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return rlt;\r\n }\r\n function _batch(arr) {\r\n var rlt = EMPTY_STR;\r\n if (arr && arr[_DYN_LENGTH /* @min:%2elength */]) {\r\n rlt = \"[\" + arr.join(\",\") + \"]\";\r\n }\r\n return rlt;\r\n }\r\n function _createPayload(data) {\r\n var _a;\r\n var headers = _getHeaders();\r\n return _a = {\r\n urlString: _endpointUrl\r\n },\r\n _a[_DYN_DATA /* @min:data */] = data,\r\n _a.headers = headers,\r\n _a;\r\n }\r\n function _isSampledIn(envelope) {\r\n return _self._sample.isSampledIn(envelope);\r\n }\r\n function _getOnComplete(payload, status, headers, response) {\r\n // ***********************************************************************************************\r\n //TODO: handle other status codes\r\n if (status === 200 && payload) {\r\n _self._onSuccess(payload, payload[_DYN_LENGTH /* @min:%2elength */]);\r\n }\r\n else {\r\n response && _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, response);\r\n }\r\n }\r\n function _doSend(sendInterface, payload, isAsync, markAsSent) {\r\n if (markAsSent === void 0) { markAsSent = true; }\r\n var onComplete = function (status, headers, response) {\r\n return _getOnComplete(payload, status, headers, response);\r\n };\r\n var payloadData = _getPayload(payload);\r\n var sendPostFunc = sendInterface && sendInterface.sendPOST;\r\n if (sendPostFunc && payloadData) {\r\n // ***********************************************************************************************\r\n // mark payload as sent at the beginning of calling each send function\r\n if (markAsSent) {\r\n _self._buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n }\r\n return sendPostFunc(payloadData, onComplete, !isAsync);\r\n }\r\n return null;\r\n }\r\n function _getPayload(payload) {\r\n var _a;\r\n if (isArray(payload) && payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var batch = _self[_DYN__BUFFER /* @min:%2e_buffer */].batchPayloads(payload);\r\n var headers = _getHeaders();\r\n var payloadData = (_a = {},\r\n _a[_DYN_DATA /* @min:data */] = batch,\r\n _a.urlString = _endpointUrl,\r\n _a.headers = headers,\r\n _a.disableXhrSync = _disableXhr,\r\n _a.disableFetchKeepAlive = !_fetchKeepAlive,\r\n _a[_DYN_ORI_PAYLOAD /* @min:oriPayload */] = payload,\r\n _a);\r\n return payloadData;\r\n }\r\n return null;\r\n }\r\n function _getHeaders() {\r\n try {\r\n var headers = _headers || {};\r\n if (isInternalApplicationInsightsEndpoint(_endpointUrl)) {\r\n headers[RequestHeaders[6 /* eRequestHeaders.sdkContextHeader */]] = RequestHeaders[7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */];\r\n }\r\n return headers;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n function _checkMaxSize(incomingPayload) {\r\n var incomingSize = incomingPayload ? incomingPayload[_DYN_LENGTH /* @min:%2elength */] : 0;\r\n if ((_self[_DYN__BUFFER /* @min:%2e_buffer */].size() + incomingSize) > _maxBatchSizeInBytes) {\r\n if (!_offlineListener || _offlineListener.isOnline()) { // only trigger send when currently online\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 10 /* SendRequestReason.MaxBatchSize */);\r\n }\r\n return true;\r\n }\r\n return false;\r\n }\r\n function _checkResponsStatus(status, payload, responseUrl, countOfItemsInPayload, errorMessage, res) {\r\n var response = null;\r\n if (!_self._appId) {\r\n response = parseResponse(res);\r\n if (response && response.appId) {\r\n _self._appId = response.appId;\r\n }\r\n }\r\n if ((status < 200 || status >= 300) && status !== 0) {\r\n // Update End Point url if permanent redirect or moved permanently\r\n // Updates the end point url before retry\r\n if (status === 301 || status === 307 || status === 308) {\r\n if (!_checkAndUpdateEndPointUrl(responseUrl)) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n return;\r\n }\r\n }\r\n if (_offlineListener && !_offlineListener.isOnline()) { // offline\r\n // Note: Don't check for status == 0, since adblock gives this code\r\n if (!_isRetryDisabled) {\r\n var offlineBackOffMultiplier = 10; // arbritrary number\r\n _resendPayload(payload, offlineBackOffMultiplier);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". Offline - Response Code: \".concat(status, \". Offline status: \").concat(!_offlineListener.isOnline(), \". Will retry to send \").concat(payload.length, \" items.\"));\r\n }\r\n return;\r\n }\r\n if (!_isRetryDisabled && _isRetriable(status)) {\r\n _resendPayload(payload);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" +\r\n \"Response code \" + status + \". Will retry to send \" + payload[_DYN_LENGTH /* @min:%2elength */] + \" items.\");\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n }\r\n }\r\n else {\r\n // check if the xhr's responseURL or fetch's response.url is same as endpoint url\r\n // TODO after 10 redirects force send telemetry with 'redirect=false' as query parameter.\r\n _checkAndUpdateEndPointUrl(responseUrl);\r\n if (status === 206) {\r\n if (!response) {\r\n response = parseResponse(res);\r\n }\r\n if (response && !_isRetryDisabled) {\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, response);\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n }\r\n }\r\n else {\r\n _consecutiveErrors = 0;\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, countOfItemsInPayload);\r\n }\r\n }\r\n }\r\n function _checkAndUpdateEndPointUrl(responseUrl) {\r\n // Maximum stamp specific redirects allowed(uncomment this when breeze is ready with not allowing redirects feature)\r\n if (_stamp_specific_redirects >= 10) {\r\n // _self._senderConfig.endpointUrl = () => Sender._getDefaultAppInsightsChannelConfig().endpointUrl()+\"/?redirect=false\";\r\n // _stamp_specific_redirects = 0;\r\n return false;\r\n }\r\n if (!isNullOrUndefined(responseUrl) && responseUrl !== \"\") {\r\n if (responseUrl !== _endpointUrl) {\r\n _endpointUrl = responseUrl;\r\n ++_stamp_specific_redirects;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n function _doUnloadSend(payload, isAsync) {\r\n if (_syncUnloadSender) {\r\n // We are unloading so always call the sender with sync set to false\r\n _syncUnloadSender(payload, false);\r\n }\r\n else {\r\n // Fallback to the previous beacon Sender (which causes a CORB warning on chrome now)\r\n var beaconInst = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */]([3 /* TransportType.Beacon */], true);\r\n return _doSend(beaconInst, payload, isAsync);\r\n }\r\n }\r\n function _onBeaconRetry(payload, onComplete, canSend) {\r\n var internalPayload = payload;\r\n var data = internalPayload && internalPayload[_DYN_ORI_PAYLOAD /* @min:%2eoriPayload */];\r\n if (!_disableBeaconSplit) {\r\n // Failed to send entire payload so try and split data and try to send as much events as possible\r\n var droppedPayload = [];\r\n for (var lp = 0; lp < data[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var thePayload = data[lp];\r\n var arr = [thePayload];\r\n var item = _getPayload(arr);\r\n if (!canSend(item, onComplete)) {\r\n // Can't send anymore, so split the batch and drop the rest\r\n droppedPayload[_DYN_PUSH /* @min:%2epush */](thePayload);\r\n }\r\n else {\r\n _self._onSuccess(arr, arr[_DYN_LENGTH /* @min:%2elength */]);\r\n }\r\n }\r\n if (droppedPayload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _fallbackSend && _fallbackSend(droppedPayload, true);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\r\n }\r\n }\r\n else {\r\n _fallbackSend && _fallbackSend(data, true);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\r\n }\r\n }\r\n function _isStringArr(arr) {\r\n try {\r\n if (arr && arr[_DYN_LENGTH /* @min:%2elength */]) {\r\n return (isString(arr[0]));\r\n }\r\n }\r\n catch (e) {\r\n //TODO: log, sender use IInternalStorageItem instead of string since 3.1.3\r\n }\r\n return null;\r\n }\r\n function _fetchKeepAliveSender(payload, isAsync) {\r\n var transport = null;\r\n if (isArray(payload)) {\r\n var payloadSize = payload[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < payload[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n payloadSize += payload[lp].item[_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n var syncFetchPayload = _sendPostMgr.getSyncFetchPayload();\r\n if ((syncFetchPayload + payloadSize) <= FetchSyncRequestSizeLimitBytes) {\r\n transport = 2 /* TransportType.Fetch */;\r\n }\r\n else if (isBeaconsSupported()) {\r\n // Fallback to beacon sender as we at least get told which events can't be scheduled\r\n transport = 3 /* TransportType.Beacon */;\r\n }\r\n else {\r\n // Payload is going to be too big so just try and send via XHR\r\n transport = 1 /* TransportType.Xhr */;\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with xhrSender.\");\r\n }\r\n var inst = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */]([transport], true);\r\n return _doSend(inst, payload, isAsync);\r\n }\r\n return null;\r\n }\r\n /**\r\n * Resend payload. Adds payload back to the send buffer and setup a send timer (with exponential backoff).\r\n * @param payload\r\n */\r\n function _resendPayload(payload, linearFactor) {\r\n if (linearFactor === void 0) { linearFactor = 1; }\r\n if (!payload || payload[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n return;\r\n }\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n _consecutiveErrors++;\r\n for (var _i = 0, payload_1 = payload; _i < payload_1.length; _i++) {\r\n var item = payload_1[_i];\r\n item.cnt = item.cnt || 0; // to make sure we have cnt for each payload\r\n item.cnt++; // when resend, increase cnt\r\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](item);\r\n }\r\n // setup timer\r\n _setRetryTime(linearFactor);\r\n _setupTimer();\r\n }\r\n /**\r\n * Calculates the time to wait before retrying in case of an error based on\r\n * http://en.wikipedia.org/wiki/Exponential_backoff\r\n */\r\n function _setRetryTime(linearFactor) {\r\n var SlotDelayInSeconds = 10;\r\n var delayInSeconds;\r\n if (_consecutiveErrors <= 1) {\r\n delayInSeconds = SlotDelayInSeconds;\r\n }\r\n else {\r\n var backOffSlot = (Math.pow(2, _consecutiveErrors) - 1) / 2;\r\n // tslint:disable-next-line:insecure-random\r\n var backOffDelay = Math.floor(Math.random() * backOffSlot * SlotDelayInSeconds) + 1;\r\n backOffDelay = linearFactor * backOffDelay;\r\n delayInSeconds = Math.max(Math.min(backOffDelay, 3600), SlotDelayInSeconds);\r\n }\r\n // TODO: Log the backoff time like the C# version does.\r\n var retryAfterTimeSpan = dateNow() + (delayInSeconds * 1000);\r\n // TODO: Log the retry at time like the C# version does.\r\n _retryAt = retryAfterTimeSpan;\r\n }\r\n /**\r\n * Sets up the timer which triggers actually sending the data.\r\n */\r\n function _setupTimer() {\r\n if (!_timeoutHandle && !_paused) {\r\n var retryInterval = _retryAt ? Math.max(0, _retryAt - dateNow()) : 0;\r\n var timerValue = Math.max(_maxBatchInterval, retryInterval);\r\n _timeoutHandle = scheduleTimeout(function () {\r\n _timeoutHandle = null;\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 1 /* SendRequestReason.NormalSchedule */);\r\n }, timerValue);\r\n }\r\n }\r\n function _clearScheduledTimer() {\r\n _timeoutHandle && _timeoutHandle.cancel();\r\n _timeoutHandle = null;\r\n _retryAt = null;\r\n }\r\n /**\r\n * Checks if the SDK should resend the payload after receiving this status code from the backend.\r\n * @param statusCode\r\n */\r\n function _isRetriable(statusCode) {\r\n // retryCodes = [] means should not retry\r\n if (!isNullOrUndefined(_retryCodes)) {\r\n return _retryCodes[_DYN_LENGTH /* @min:%2elength */] && _retryCodes.indexOf(statusCode) > -1;\r\n }\r\n return statusCode === 401 // Unauthorized\r\n // Removing as private links can return a 403 which causes excessive retries and session storage usage\r\n // || statusCode === 403 // Forbidden\r\n || statusCode === 408 // Timeout\r\n || statusCode === 429 // Too many requests.\r\n || statusCode === 500 // Internal server error.\r\n || statusCode === 502 // Bad Gateway.\r\n || statusCode === 503 // Service unavailable.\r\n || statusCode === 504; // Gateway timeout.\r\n }\r\n // Using function lookups for backward compatibility as the getNotifyMgr() did not exist until after v2.5.6\r\n function _getNotifyMgr() {\r\n var func = \"getNotifyMgr\";\r\n if (_self.core[func]) {\r\n return _self.core[func]();\r\n }\r\n // using _self.core['_notificationManager'] for backward compatibility\r\n return _self.core[\"_notificationManager\"];\r\n }\r\n function _notifySendRequest(sendRequest, isAsync) {\r\n var manager = _getNotifyMgr();\r\n if (manager && manager[_DYN_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */]) {\r\n try {\r\n manager[_DYN_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendRequest, isAsync);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 74 /* _eInternalMessageId.NotificationException */, \"send request notification failed: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n }\r\n /**\r\n * Validate UUID Format\r\n * Specs taken from https://tools.ietf.org/html/rfc4122 and breeze repo\r\n */\r\n function _validateInstrumentationKey(instrumentationKey, config) {\r\n var disableValidation = config.disableInstrumentationKeyValidation;\r\n var disableIKeyValidationFlag = isNullOrUndefined(disableValidation) ? false : disableValidation;\r\n if (disableIKeyValidationFlag) {\r\n return true;\r\n }\r\n var UUID_Regex = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\";\r\n var regexp = new RegExp(UUID_Regex);\r\n return regexp.test(instrumentationKey);\r\n }\r\n function _initDefaults() {\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\r\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = null;\r\n _self._appId = null;\r\n _self._sample = null;\r\n _headers = {};\r\n _offlineListener = null;\r\n _consecutiveErrors = 0;\r\n _retryAt = null;\r\n _lastSend = null;\r\n _paused = false;\r\n _timeoutHandle = null;\r\n _serializer = null;\r\n _stamp_specific_redirects = 0;\r\n _syncFetchPayload = 0;\r\n _syncUnloadSender = null;\r\n _evtNamespace = null;\r\n _endpointUrl = null;\r\n _orgEndpointUrl = null;\r\n _maxBatchSizeInBytes = 0;\r\n _beaconSupported = false;\r\n _customHeaders = null;\r\n _disableTelemetry = false;\r\n _instrumentationKey = null;\r\n _convertUndefined = UNDEFINED_VALUE;\r\n _isRetryDisabled = false;\r\n _sessionStorageUsed = null;\r\n _namePrefix = UNDEFINED_VALUE;\r\n _disableXhr = false;\r\n _fetchKeepAlive = false;\r\n _disableBeaconSplit = false;\r\n _xhrSend = null;\r\n _fallbackSend = null;\r\n _sendPostMgr = null;\r\n objDefine(_self, \"_senderConfig\", {\r\n g: function () {\r\n return objExtend({}, defaultAppInsightsChannelConfig);\r\n }\r\n });\r\n }\r\n });\r\n return _this;\r\n }\r\n Sender.constructEnvelope = function (orig, iKey, logger, convertUndefined) {\r\n var envelope;\r\n if (iKey !== orig.iKey && !isNullOrUndefined(iKey)) {\r\n envelope = __assign(__assign({}, orig), { iKey: iKey });\r\n }\r\n else {\r\n envelope = orig;\r\n }\r\n var creator = EnvelopeTypeCreator[envelope.baseType] || EventEnvelopeCreator;\r\n return creator(logger, envelope, convertUndefined);\r\n };\r\n /**\r\n * Pause the sending (transmission) of events, this will cause all events to be batched only until the maximum limits are\r\n * hit at which point new events are dropped. Will also cause events to NOT be sent during page unload, so if Session storage\r\n * is disabled events will be lost.\r\n * SessionStorage Limit is 2000 events, In-Memory (Array) Storage is 10,000 events (can be configured via the eventsLimitInMem).\r\n */\r\n Sender.prototype.pause = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Resume the sending (transmission) of events, this will restart the timer and any batched events will be sent using the normal\r\n * send interval.\r\n */\r\n Sender.prototype.resume = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Flush to send data immediately; channel should default to sending data asynchronously. If executing asynchronously (the default) and\r\n * you DO NOT pass a callback function then a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will be returned which will resolve once the flush is complete. The actual implementation of the `IPromise`\r\n * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param async - send data asynchronously when true\r\n * @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called.\r\n * If the caller doesn't return true the caller should assume that it may never be called.\r\n * @param sendReason - specify the reason that you are calling \"flush\" defaults to ManualFlush (1) if not specified\r\n * @returns - If a callback is provided `true` to indicate that callback will be called after the flush is complete otherwise the caller\r\n * should assume that any provided callback will never be called, Nothing or if occurring asynchronously a\r\n * [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) which will be resolved once the unload is complete,\r\n * the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) will only be returned when no callback is provided\r\n * and async is true.\r\n */\r\n Sender.prototype.flush = function (async, callBack) {\r\n if (async === void 0) { async = true; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Flush the batched events synchronously (if possible -- based on configuration).\r\n * Will not flush if the Send has been paused.\r\n */\r\n Sender.prototype.onunloadFlush = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n Sender.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n Sender.prototype.processTelemetry = function (telemetryItem, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * xhr state changes\r\n * @deprecated\r\n * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility)\r\n */\r\n Sender.prototype._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n // TODO: no-op\r\n // add note to users, this will be removed\r\n };\r\n /**\r\n * Trigger the immediate send of buffered data; If executing asynchronously (the default) this may (not required) return\r\n * an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) that will resolve once the\r\n * send is complete. The actual implementation of the `IPromise` will be a native Promise (if supported) or the default\r\n * as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param async - Indicates if the events should be sent asynchronously\r\n * @param forcedSender - {SenderFunction} - Indicates the forcedSender, undefined if not passed\r\n * @returns - Nothing or optionally, if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * which will be resolved (or reject) once the send is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * should only be returned when async is true.\r\n */\r\n Sender.prototype.triggerSend = function (async, forcedSender, sendReason) {\r\n if (async === void 0) { async = true; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * error handler\r\n * @Internal\r\n * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility)\r\n */\r\n Sender.prototype._onError = function (payload, message, event) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * partial success handler\r\n * @Internal\r\n * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility)\r\n */\r\n Sender.prototype._onPartialSuccess = function (payload, results) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * success handler\r\n * @Internal\r\n * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility)\r\n */\r\n Sender.prototype._onSuccess = function (payload, countOfItemsInPayload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * xdr state changes\r\n * @deprecated\r\n * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility)\r\n */\r\n Sender.prototype._xdrOnLoad = function (xdr, payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add header to request\r\n * @param name - Header name.\r\n * @param value - Header value.\r\n */\r\n Sender.prototype.addHeader = function (name, value) {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Check if there are no active requests being sent.\r\n * @returns True if idle, false otherwise.\r\n */\r\n Sender.prototype.isCompletelyIdle = function () {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n return false;\r\n };\r\n /**\r\n * Get Offline Serializer support\r\n * @returns internal Offline Serializer object\r\n */\r\n Sender.prototype.getOfflineSupport = function () {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return Sender;\r\n}(BaseTelemetryPlugin));\r\nexport { Sender };\r\n//# sourceMappingURL=Sender.js.map","import dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _throwInternal, getJSON, isArray, isFunction, isObject, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_PUSH, _DYN_SERIALIZE, _DYN_STRINGIFY, _DYN_TO_STRING } from \"./__DynamicConstants\";\r\nvar Serializer = /** @class */ (function () {\r\n function Serializer(logger) {\r\n dynamicProto(Serializer, this, function (_self) {\r\n /**\r\n * Serializes the current object to a JSON string.\r\n */\r\n _self[_DYN_SERIALIZE /* @min:%2eserialize */] = function (input) {\r\n var output = _serializeObject(input, \"root\");\r\n try {\r\n return getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](output);\r\n }\r\n catch (e) {\r\n // if serialization fails return an empty string\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, (e && isFunction(e[_DYN_TO_STRING /* @min:%2etoString */])) ? e[_DYN_TO_STRING /* @min:%2etoString */]() : \"Error serializing object\", null, true);\r\n }\r\n };\r\n function _serializeObject(source, name) {\r\n var circularReferenceCheck = \"__aiCircularRefCheck\";\r\n var output = {};\r\n if (!source) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, \"cannot serialize object because it is null or undefined\", { name: name }, true);\r\n return output;\r\n }\r\n if (source[circularReferenceCheck]) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 50 /* _eInternalMessageId.CircularReferenceDetected */, \"Circular reference detected while serializing object\", { name: name }, true);\r\n return output;\r\n }\r\n if (!source.aiDataContract) {\r\n // special case for measurements/properties/tags\r\n if (name === \"measurements\") {\r\n output = _serializeStringMap(source, \"number\", name);\r\n }\r\n else if (name === \"properties\") {\r\n output = _serializeStringMap(source, \"string\", name);\r\n }\r\n else if (name === \"tags\") {\r\n output = _serializeStringMap(source, \"string\", name);\r\n }\r\n else if (isArray(source)) {\r\n output = _serializeArray(source, name);\r\n }\r\n else {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"Attempting to serialize an object which does not implement ISerializable\", { name: name }, true);\r\n try {\r\n // verify that the object can be stringified\r\n getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](source);\r\n output = source;\r\n }\r\n catch (e) {\r\n // if serialization fails return an empty string\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, (e && isFunction(e[_DYN_TO_STRING /* @min:%2etoString */])) ? e[_DYN_TO_STRING /* @min:%2etoString */]() : \"Error serializing object\", null, true);\r\n }\r\n }\r\n return output;\r\n }\r\n source[circularReferenceCheck] = true;\r\n objForEachKey(source.aiDataContract, function (field, contract) {\r\n var isRequired = (isFunction(contract)) ? (contract() & 1 /* FieldType.Required */) : (contract & 1 /* FieldType.Required */);\r\n var isHidden = (isFunction(contract)) ? (contract() & 4 /* FieldType.Hidden */) : (contract & 4 /* FieldType.Hidden */);\r\n var isArray = contract & 2 /* FieldType.Array */;\r\n var isPresent = source[field] !== undefined;\r\n var isObj = isObject(source[field]) && source[field] !== null;\r\n if (isRequired && !isPresent && !isArray) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 24 /* _eInternalMessageId.MissingRequiredFieldSpecification */, \"Missing required field specification. The field is required but not present on source\", { field: field, name: name });\r\n // If not in debug mode, continue and hope the error is permissible\r\n }\r\n else if (!isHidden) { // Don't serialize hidden fields\r\n var value = void 0;\r\n if (isObj) {\r\n if (isArray) {\r\n // special case; recurse on each object in the source array\r\n value = _serializeArray(source[field], field);\r\n }\r\n else {\r\n // recurse on the source object in this field\r\n value = _serializeObject(source[field], field);\r\n }\r\n }\r\n else {\r\n // assign the source field to the output even if undefined or required\r\n value = source[field];\r\n }\r\n // only emit this field if the value is defined\r\n if (value !== undefined) {\r\n output[field] = value;\r\n }\r\n }\r\n });\r\n delete source[circularReferenceCheck];\r\n return output;\r\n }\r\n function _serializeArray(sources, name) {\r\n var output;\r\n if (!!sources) {\r\n if (!isArray(sources)) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 54 /* _eInternalMessageId.ItemNotInArray */, \"This field was specified as an array in the contract but the item is not an array.\\r\\n\", { name: name }, true);\r\n }\r\n else {\r\n output = [];\r\n for (var i = 0; i < sources[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var source = sources[i];\r\n var item = _serializeObject(source, name + \"[\" + i + \"]\");\r\n output[_DYN_PUSH /* @min:%2epush */](item);\r\n }\r\n }\r\n }\r\n return output;\r\n }\r\n function _serializeStringMap(map, expectedType, name) {\r\n var output;\r\n if (map) {\r\n output = {};\r\n objForEachKey(map, function (field, value) {\r\n if (expectedType === \"string\") {\r\n if (value === undefined) {\r\n output[field] = \"undefined\";\r\n }\r\n else if (value === null) {\r\n output[field] = \"null\";\r\n }\r\n else if (!value[_DYN_TO_STRING /* @min:%2etoString */]) {\r\n output[field] = \"invalid field: toString() is not defined.\";\r\n }\r\n else {\r\n output[field] = value[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n }\r\n else if (expectedType === \"number\") {\r\n if (value === undefined) {\r\n output[field] = \"undefined\";\r\n }\r\n else if (value === null) {\r\n output[field] = \"null\";\r\n }\r\n else {\r\n var num = parseFloat(value);\r\n output[field] = num;\r\n }\r\n }\r\n else {\r\n output[field] = \"invalid field: \" + name + \" is of unknown type.\";\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, output[field], null, true);\r\n }\r\n });\r\n }\r\n return output;\r\n }\r\n });\r\n }\r\n /**\r\n * Serializes the current object to a JSON string.\r\n */\r\n Serializer.prototype.serialize = function (input) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return Serializer;\r\n}());\r\nexport { Serializer };\r\n//# sourceMappingURL=Serializer.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { _DYN_CONCAT, _DYN_LENGTH } from \"../../__DynamicConstants\";\r\n// (Magic number) DJB algorithm can't work on shorter strings (results in poor distribution\r\nvar MIN_INPUT_LENGTH = 8;\r\nvar HashCodeScoreGenerator = /** @class */ (function () {\r\n function HashCodeScoreGenerator() {\r\n }\r\n HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) {\r\n var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE;\r\n return score * 100;\r\n };\r\n HashCodeScoreGenerator.prototype.getHashCode = function (input) {\r\n if (input === \"\") {\r\n return 0;\r\n }\r\n while (input[_DYN_LENGTH /* @min:%2elength */] < MIN_INPUT_LENGTH) {\r\n input = input[_DYN_CONCAT /* @min:%2econcat */](input);\r\n }\r\n // 5381 is a magic number: http://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function\r\n var hash = 5381;\r\n for (var i = 0; i < input[_DYN_LENGTH /* @min:%2elength */]; ++i) {\r\n hash = ((hash << 5) + hash) + input.charCodeAt(i);\r\n // 'hash' is of number type which means 53 bit integer (http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types-number-type)\r\n // 'hash & hash' will keep it 32 bit integer - just to make it clearer what the result is.\r\n hash = hash & hash;\r\n }\r\n return Math.abs(hash);\r\n };\r\n // We're using 32 bit math, hence max value is (2^31 - 1)\r\n HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;\r\n return HashCodeScoreGenerator;\r\n}());\r\nexport { HashCodeScoreGenerator };\r\n//# sourceMappingURL=HashCodeScoreGenerator.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { ContextTagKeys } from \"@microsoft/applicationinsights-common\";\r\nimport { _DYN_GET_HASH_CODE_SCORE, _DYN_GET_SAMPLING_SCORE, _DYN_TAGS, _DYN_TRACE_ID } from \"../../__DynamicConstants\";\r\nimport { HashCodeScoreGenerator } from \"./HashCodeScoreGenerator\";\r\nvar SamplingScoreGenerator = /** @class */ (function () {\r\n function SamplingScoreGenerator() {\r\n var _self = this;\r\n var hashCodeGenerator = new HashCodeScoreGenerator();\r\n var keys = new ContextTagKeys();\r\n _self[_DYN_GET_SAMPLING_SCORE /* @min:%2egetSamplingScore */] = function (item) {\r\n var score = 0;\r\n if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.userId]) { // search in tags first, then ext\r\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.userId]);\r\n }\r\n else if (item.ext && item.ext.user && item.ext.user.id) {\r\n score = hashCodeGenerator[_DYN_GET_HASH_CODE_SCORE /* @min:%2egetHashCodeScore */](item.ext.user.id);\r\n }\r\n else if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.operationId]) { // search in tags first, then ext\r\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.operationId]);\r\n }\r\n else if (item.ext && item.ext.telemetryTrace && item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]) {\r\n score = hashCodeGenerator.getHashCodeScore(item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\r\n }\r\n else {\r\n // tslint:disable-next-line:insecure-random\r\n score = (Math.random() * 100);\r\n }\r\n return score;\r\n };\r\n }\r\n return SamplingScoreGenerator;\r\n}());\r\nexport { SamplingScoreGenerator };\r\n//# sourceMappingURL=SamplingScoreGenerator.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { Metric } from \"@microsoft/applicationinsights-common\";\r\nimport { safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_DATA_TYPE, _DYN_GET_SAMPLING_SCORE, _DYN_SAMPLE_RATE } from \"../__DynamicConstants\";\r\nimport { SamplingScoreGenerator } from \"./SamplingScoreGenerators/SamplingScoreGenerator\";\r\nvar Sample = /** @class */ (function () {\r\n function Sample(sampleRate, logger) {\r\n // We're using 32 bit math, hence max value is (2^31 - 1)\r\n this.INT_MAX_VALUE = 2147483647;\r\n var _logger = logger || safeGetLogger(null);\r\n if (sampleRate > 100 || sampleRate < 0) {\r\n _logger.throwInternal(2 /* eLoggingSeverity.WARNING */, 58 /* _eInternalMessageId.SampleRateOutOfRange */, \"Sampling rate is out of range (0..100). Sampling will be disabled, you may be sending too much data which may affect your AI service level.\", { samplingRate: sampleRate }, true);\r\n sampleRate = 100;\r\n }\r\n this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] = sampleRate;\r\n this.samplingScoreGenerator = new SamplingScoreGenerator();\r\n }\r\n /**\r\n * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).\r\n */\r\n Sample.prototype.isSampledIn = function (envelope) {\r\n var samplingPercentage = this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */]; // 0 - 100\r\n var isSampledIn = false;\r\n if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {\r\n return true;\r\n }\r\n else if (envelope.baseType === Metric[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n // exclude MetricData telemetry from sampling\r\n return true;\r\n }\r\n isSampledIn = this.samplingScoreGenerator[_DYN_GET_SAMPLING_SCORE /* @min:%2egetSamplingScore */](envelope) < samplingPercentage;\r\n return isSampledIn;\r\n };\r\n return Sample;\r\n}());\r\nexport { Sample };\r\n//# sourceMappingURL=Sample.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrReduce, objKeys, strEndsWith } from \"@microsoft/applicationinsights-core-js\";\r\nimport { DEFAULT_BREEZE_ENDPOINT } from \"./Constants\";\r\nimport { _DYN_INGESTIONENDPOINT, _DYN_LENGTH, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar _FIELDS_SEPARATOR = \";\";\r\nvar _FIELD_KEY_VALUE_SEPARATOR = \"=\";\r\nexport function parseConnectionString(connectionString) {\r\n if (!connectionString) {\r\n return {};\r\n }\r\n var kvPairs = connectionString[_DYN_SPLIT /* @min:%2esplit */](_FIELDS_SEPARATOR);\r\n var result = arrReduce(kvPairs, function (fields, kv) {\r\n var kvParts = kv[_DYN_SPLIT /* @min:%2esplit */](_FIELD_KEY_VALUE_SEPARATOR);\r\n if (kvParts[_DYN_LENGTH /* @min:%2elength */] === 2) { // only save fields with valid formats\r\n var key = kvParts[0][_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n var value = kvParts[1];\r\n fields[key] = value;\r\n }\r\n return fields;\r\n }, {});\r\n if (objKeys(result)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // this is a valid connection string, so parse the results\r\n if (result.endpointsuffix) {\r\n // apply the default endpoints\r\n var locationPrefix = result.location ? result.location + \".\" : \"\";\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || (\"https://\" + locationPrefix + \"dc.\" + result.endpointsuffix);\r\n }\r\n // apply user override endpoint or the default endpoints\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || DEFAULT_BREEZE_ENDPOINT;\r\n if (strEndsWith(result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */], \"/\")) {\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */].slice(0, -1);\r\n }\r\n }\r\n return result;\r\n}\r\nexport var ConnectionStringParser = {\r\n parse: parseConnectionString\r\n};\r\n//# sourceMappingURL=ConnectionStringParser.js.map","import { _throwInternal, arrIndexOf, isNotNullOrUndefined, isNullOrUndefined, onConfigChange, randomValue, safeGetLogger, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { arrForEach, objForEachKey } from \"@nevware21/ts-utils\";\r\nimport { utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from \"./StorageHelperFuncs\";\r\nimport { _DYN_COUNT, _DYN_DATE, _DYN_DAYS_OF_MONTH, _DYN_DISABLED, _DYN_GET_UTCDATE, _DYN_INTERVAL, _DYN_LENGTH, _DYN_MESSAGE, _DYN_PRE_TRIGGER_DATE, _DYN_PUSH, _DYN_STRINGIFY } from \"./__DynamicConstants\";\r\nvar THROTTLE_STORAGE_PREFIX = \"appInsightsThrottle\";\r\nvar ThrottleMgr = /** @class */ (function () {\r\n function ThrottleMgr(core, namePrefix) {\r\n var _self = this;\r\n var _canUseLocalStorage;\r\n var _logger;\r\n var _config;\r\n var _localStorageObj;\r\n var _isTriggered; //_isTriggered is to make sure that we only trigger throttle once a day\r\n var _namePrefix;\r\n var _queue;\r\n var _isReady = false;\r\n var _isSpecificDaysGiven = false;\r\n _initConfig();\r\n // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects\r\n _self[\"_getDbgPlgTargets\"] = function () {\r\n return [_queue];\r\n };\r\n _self.getConfig = function () {\r\n return _config;\r\n };\r\n /**\r\n * Check if it is the correct day to send message.\r\n * If _isTriggered is true, even if canThrottle returns true, message will not be sent,\r\n * because we only allow triggering sendMessage() once a day.\r\n * @returns if the current date is the valid date to send message\r\n */\r\n _self.canThrottle = function (msgId) {\r\n var localObj = _getLocalStorageObjByKey(msgId);\r\n var cfg = _getCfgByKey(msgId);\r\n return _canThrottle(cfg, _canUseLocalStorage, localObj);\r\n };\r\n /**\r\n * Check if throttle is triggered on current day(UTC)\r\n * if canThrottle returns false, isTriggered will return false\r\n * @returns if throttle is triggered on current day(UTC)\r\n */\r\n _self.isTriggered = function (msgId) {\r\n return _isTrigger(msgId);\r\n };\r\n /**\r\n * Before isReady set to true, all message will be stored in queue.\r\n * Message will only be sent out after isReady set to true.\r\n * Initial and default value: false\r\n * @returns isReady state\r\n */\r\n _self.isReady = function () {\r\n return _isReady;\r\n };\r\n /**\r\n * Flush all message with given message key in queue with isReady state set to true.\r\n * @returns if message queue is flushed\r\n */\r\n _self.flush = function (msgId) {\r\n try {\r\n var queue = _getQueueByKey(msgId);\r\n if (queue && queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var items = queue.slice(0);\r\n _queue[msgId] = [];\r\n arrForEach(items, function (item) {\r\n _flushMessage(item.msgID, item[_DYN_MESSAGE /* @min:%2emessage */], item.severity, false);\r\n });\r\n return true;\r\n }\r\n }\r\n catch (err) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n };\r\n /**\r\n * Flush all message in queue with isReady state set to true.\r\n * @returns if message queue is flushed\r\n */\r\n _self.flushAll = function () {\r\n try {\r\n if (_queue) {\r\n var result_1 = true;\r\n objForEachKey(_queue, function (key) {\r\n var isFlushed = _self.flush(parseInt(key));\r\n result_1 = result_1 && isFlushed;\r\n });\r\n return result_1;\r\n }\r\n }\r\n catch (err) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n };\r\n /**\r\n * Set isReady State\r\n * if isReady set to true, message queue will be flushed automatically.\r\n * @param isReady isReady State\r\n * @pa\r\n * @returns if message queue is flushed\r\n */\r\n _self.onReadyState = function (isReady, flushAll) {\r\n if (flushAll === void 0) { flushAll = true; }\r\n _isReady = isNullOrUndefined(isReady) ? true : isReady;\r\n if (_isReady && flushAll) {\r\n return _self.flushAll();\r\n }\r\n return null;\r\n };\r\n _self.sendMessage = function (msgID, message, severity) {\r\n return _flushMessage(msgID, message, severity, true);\r\n };\r\n function _flushMessage(msgID, message, severity, saveUnsentMsg) {\r\n if (_isReady) {\r\n var isSampledIn = _canSampledIn(msgID);\r\n if (!isSampledIn) {\r\n return;\r\n }\r\n var cfg = _getCfgByKey(msgID);\r\n var localStorageObj = _getLocalStorageObjByKey(msgID);\r\n var canThrottle = _canThrottle(cfg, _canUseLocalStorage, localStorageObj);\r\n var throttled = false;\r\n var number = 0;\r\n var isTriggered = _isTrigger(msgID);\r\n try {\r\n if (canThrottle && !isTriggered) {\r\n number = Math.min(cfg.limit.maxSendNumber, localStorageObj[_DYN_COUNT /* @min:%2ecount */] + 1);\r\n localStorageObj[_DYN_COUNT /* @min:%2ecount */] = 0;\r\n throttled = true;\r\n _isTriggered[msgID] = true;\r\n localStorageObj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */] = new Date();\r\n }\r\n else {\r\n _isTriggered[msgID] = canThrottle;\r\n localStorageObj[_DYN_COUNT /* @min:%2ecount */] += 1;\r\n }\r\n var localStorageName = _getLocalStorageName(msgID);\r\n _resetLocalStorage(_logger, localStorageName, localStorageObj);\r\n for (var i = 0; i < number; i++) {\r\n _sendMessage(msgID, _logger, message, severity);\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return {\r\n isThrottled: throttled,\r\n throttleNum: number\r\n };\r\n }\r\n else {\r\n if (!!saveUnsentMsg) {\r\n var queue = _getQueueByKey(msgID);\r\n queue[_DYN_PUSH /* @min:%2epush */]({\r\n msgID: msgID,\r\n message: message,\r\n severity: severity\r\n });\r\n }\r\n }\r\n return null;\r\n }\r\n function _initConfig() {\r\n _logger = safeGetLogger(core);\r\n _isTriggered = {};\r\n _localStorageObj = {};\r\n _queue = {};\r\n _config = {};\r\n _setCfgByKey(109 /* _eInternalMessageId.DefaultThrottleMsgKey */);\r\n _namePrefix = isNotNullOrUndefined(namePrefix) ? namePrefix : \"\";\r\n core.addUnloadHook(onConfigChange(core.config, function (details) {\r\n var coreConfig = details.cfg;\r\n _canUseLocalStorage = utlCanUseLocalStorage();\r\n var configMgr = coreConfig.throttleMgrCfg || {};\r\n objForEachKey(configMgr, function (key, cfg) {\r\n _setCfgByKey(parseInt(key), cfg);\r\n });\r\n }));\r\n }\r\n function _getCfgByKey(msgID) {\r\n return _config[msgID] || _config[109 /* _eInternalMessageId.DefaultThrottleMsgKey */];\r\n }\r\n function _setCfgByKey(msgID, config) {\r\n var _a, _b;\r\n try {\r\n var cfg = config || {};\r\n var curCfg = {};\r\n curCfg[_DYN_DISABLED /* @min:%2edisabled */] = !!cfg[_DYN_DISABLED /* @min:%2edisabled */];\r\n var configInterval = cfg[_DYN_INTERVAL /* @min:%2einterval */] || {};\r\n _isSpecificDaysGiven = (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth) && (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth[_DYN_LENGTH /* @min:%2elength */]) > 0;\r\n curCfg[_DYN_INTERVAL /* @min:%2einterval */] = _getIntervalConfig(configInterval);\r\n var limit = {\r\n samplingRate: ((_a = cfg.limit) === null || _a === void 0 ? void 0 : _a.samplingRate) || 100,\r\n // dafault: every time sent only 1 event\r\n maxSendNumber: ((_b = cfg.limit) === null || _b === void 0 ? void 0 : _b.maxSendNumber) || 1\r\n };\r\n curCfg.limit = limit;\r\n _config[msgID] = curCfg;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n function _getIntervalConfig(interval) {\r\n interval = interval || {};\r\n var monthInterval = interval === null || interval === void 0 ? void 0 : interval.monthInterval;\r\n var dayInterval = interval === null || interval === void 0 ? void 0 : interval.dayInterval;\r\n // default: send data every 3 month each year\r\n if (isNullOrUndefined(monthInterval) && isNullOrUndefined(dayInterval)) {\r\n interval.monthInterval = 3;\r\n if (!_isSpecificDaysGiven) {\r\n // default: send data on 28th\r\n interval[_DYN_DAYS_OF_MONTH /* @min:%2edaysOfMonth */] = [28];\r\n _isSpecificDaysGiven = true;\r\n }\r\n }\r\n interval = {\r\n // dafault: sent every three months\r\n monthInterval: interval === null || interval === void 0 ? void 0 : interval.monthInterval,\r\n dayInterval: interval === null || interval === void 0 ? void 0 : interval.dayInterval,\r\n daysOfMonth: interval === null || interval === void 0 ? void 0 : interval.daysOfMonth\r\n };\r\n return interval;\r\n }\r\n function _canThrottle(config, canUseLocalStorage, localStorageObj) {\r\n if (config && !config[_DYN_DISABLED /* @min:%2edisabled */] && canUseLocalStorage && isNotNullOrUndefined(localStorageObj)) {\r\n var curDate = _getThrottleDate();\r\n var date = localStorageObj[_DYN_DATE /* @min:%2edate */];\r\n var interval = config[_DYN_INTERVAL /* @min:%2einterval */];\r\n var monthCheck = 1;\r\n if (interval === null || interval === void 0 ? void 0 : interval.monthInterval) {\r\n var monthExpand = (curDate.getUTCFullYear() - date.getUTCFullYear()) * 12 + curDate.getUTCMonth() - date.getUTCMonth();\r\n monthCheck = _checkInterval(interval.monthInterval, 0, monthExpand);\r\n }\r\n var dayCheck = 1;\r\n if (_isSpecificDaysGiven) {\r\n dayCheck = arrIndexOf(interval[_DYN_DAYS_OF_MONTH /* @min:%2edaysOfMonth */], curDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]());\r\n }\r\n else if (interval === null || interval === void 0 ? void 0 : interval.dayInterval) {\r\n var daySpan = Math.floor((curDate.getTime() - date.getTime()) / 86400000);\r\n dayCheck = _checkInterval(interval.dayInterval, 0, daySpan);\r\n }\r\n return monthCheck >= 0 && dayCheck >= 0;\r\n }\r\n return false;\r\n }\r\n function _getLocalStorageName(msgKey, prefix) {\r\n var fix = isNotNullOrUndefined(prefix) ? prefix : \"\";\r\n if (msgKey) {\r\n return THROTTLE_STORAGE_PREFIX + fix + \"-\" + msgKey;\r\n }\r\n return null;\r\n }\r\n // returns if throttle is triggered on current Date\r\n function _isTriggeredOnCurDate(preTriggerDate) {\r\n try {\r\n if (preTriggerDate) {\r\n var curDate = new Date();\r\n return preTriggerDate.getUTCFullYear() === curDate.getUTCFullYear() &&\r\n preTriggerDate.getUTCMonth() === curDate.getUTCMonth() &&\r\n preTriggerDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]() === curDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]();\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n // transfer local storage string value to object that identifies start date, current count and preTriggerDate\r\n function _getLocalStorageObj(value, logger, storageName) {\r\n try {\r\n var storageObj = {\r\n date: _getThrottleDate(),\r\n count: 0\r\n };\r\n if (value) {\r\n var obj = JSON.parse(value);\r\n var curObj = {\r\n date: _getThrottleDate(obj[_DYN_DATE /* @min:%2edate */]) || storageObj[_DYN_DATE /* @min:%2edate */],\r\n count: obj[_DYN_COUNT /* @min:%2ecount */] || storageObj[_DYN_COUNT /* @min:%2ecount */],\r\n preTriggerDate: obj.preTriggerDate ? _getThrottleDate(obj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */]) : undefined\r\n };\r\n return curObj;\r\n }\r\n else {\r\n _resetLocalStorage(logger, storageName, storageObj);\r\n return storageObj;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n // if datestr is not defined, current date will be returned\r\n function _getThrottleDate(dateStr) {\r\n // if new Date() can't be created through the provided dateStr, null will be returned.\r\n try {\r\n if (dateStr) {\r\n var date = new Date(dateStr);\r\n //make sure it is a valid Date Object\r\n if (!isNaN(date.getDate())) {\r\n return date;\r\n }\r\n }\r\n else {\r\n return new Date();\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n function _resetLocalStorage(logger, storageName, obj) {\r\n try {\r\n return utlSetLocalStorage(logger, storageName, strTrim(JSON[_DYN_STRINGIFY /* @min:%2estringify */](obj)));\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n function _checkInterval(interval, start, current) {\r\n if (interval <= 0) {\r\n return 1;\r\n }\r\n // count from start year\r\n return (current >= start) && (current - start) % interval == 0 ? Math.floor((current - start) / interval) + 1 : -1;\r\n }\r\n function _sendMessage(msgID, logger, message, severity) {\r\n _throwInternal(logger, severity || 1 /* eLoggingSeverity.CRITICAL */, msgID, message);\r\n }\r\n // NOTE: config.limit.samplingRate is set to 4 decimal places,\r\n // so config.limit.samplingRate = 1 means 0.0001%\r\n function _canSampledIn(msgID) {\r\n try {\r\n var cfg = _getCfgByKey(msgID);\r\n return randomValue(1000000) <= cfg.limit.samplingRate;\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n function _getLocalStorageObjByKey(key) {\r\n try {\r\n var curObj = _localStorageObj[key];\r\n if (!curObj) {\r\n var localStorageName = _getLocalStorageName(key, _namePrefix);\r\n curObj = _getLocalStorageObj(utlGetLocalStorage(_logger, localStorageName), _logger, localStorageName);\r\n _localStorageObj[key] = curObj;\r\n }\r\n return _localStorageObj[key];\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n function _isTrigger(key) {\r\n var isTrigger = _isTriggered[key];\r\n if (isNullOrUndefined(isTrigger)) {\r\n isTrigger = false;\r\n var localStorageObj = _getLocalStorageObjByKey(key);\r\n if (localStorageObj) {\r\n isTrigger = _isTriggeredOnCurDate(localStorageObj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */]);\r\n }\r\n _isTriggered[key] = isTrigger;\r\n }\r\n return _isTriggered[key];\r\n }\r\n function _getQueueByKey(key) {\r\n _queue = _queue || {};\r\n if (isNullOrUndefined(_queue[key])) {\r\n _queue[key] = [];\r\n }\r\n return _queue[key];\r\n }\r\n }\r\n return ThrottleMgr;\r\n}());\r\nexport { ThrottleMgr };\r\n//# sourceMappingURL=ThrottleMgr.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { createAllPromise, createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { arrForEach, arrIndexOf, objDefine, safe, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\r\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_CANCEL, _DYN_DATA, _DYN_IS_ASYNC, _DYN_IS_CHILD_EVT, _DYN_LENGTH, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_0, _DYN_SPLICE, _DYN_UNLOAD, _DYN_WATCH } from \"../__DynamicConstants\";\r\nimport { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_OFFLINE_DROP, STR_OFFLINE_SENT, STR_OFFLINE_STORE, STR_PERF_EVENT } from \"./InternalConstants\";\r\nvar defaultValues = {\r\n perfEvtsSendAll: false\r\n};\r\nfunction _runScheduledListeners(asyncNotifications) {\r\n asyncNotifications.h = null;\r\n var callbacks = asyncNotifications.cb;\r\n asyncNotifications.cb = [];\r\n arrForEach(callbacks, function (cb) {\r\n // Run the listener in a try-catch to ensure that a single listener failing doesn't prevent the others from running\r\n safe(cb.fn, [cb.arg]);\r\n });\r\n}\r\n// This function is used to combine the logic of running the listeners and handling the async notifications so that they don't\r\n// create multiple timers if there are multiple async listeners.\r\nfunction _runListeners(listeners, name, asyncNotifications, callback) {\r\n arrForEach(listeners, function (listener) {\r\n if (listener && listener[name]) {\r\n if (asyncNotifications) {\r\n // Schedule the callback to be called after the current call stack has cleared.\r\n asyncNotifications.cb[_DYN_PUSH /* @min:%2epush */]({\r\n fn: callback,\r\n arg: listener\r\n });\r\n asyncNotifications.h = asyncNotifications.h || scheduleTimeout(_runScheduledListeners, 0, asyncNotifications);\r\n }\r\n else {\r\n // Run the listener in a try-catch to ensure that a single listener failing doesn't prevent the others from running\r\n safe(callback, [listener]);\r\n }\r\n }\r\n });\r\n}\r\n/**\r\n * Class to manage sending notifications to all the listeners.\r\n */\r\nvar NotificationManager = /** @class */ (function () {\r\n function NotificationManager(config) {\r\n this.listeners = [];\r\n var perfEvtsSendAll;\r\n var unloadHandler;\r\n var _listeners = [];\r\n var _asyncNotifications = {\r\n h: null,\r\n cb: []\r\n };\r\n var cfgHandler = createDynamicConfig(config, defaultValues);\r\n unloadHandler = cfgHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n perfEvtsSendAll = !!details.cfg.perfEvtsSendAll;\r\n });\r\n dynamicProto(NotificationManager, this, function (_self) {\r\n objDefine(_self, \"listeners\", {\r\n g: function () { return _listeners; }\r\n });\r\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\r\n _listeners[_DYN_PUSH /* @min:%2epush */](listener);\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - AWTNotificationListener to remove.\r\n */\r\n _self[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */] = function (listener) {\r\n var index = arrIndexOf(_listeners, listener);\r\n while (index > -1) {\r\n _listeners[_DYN_SPLICE /* @min:%2esplice */](index, 1);\r\n index = arrIndexOf(_listeners, listener);\r\n }\r\n };\r\n /**\r\n * Notification for events sent.\r\n * @param events - The array of events that have been sent.\r\n */\r\n _self[STR_EVENTS_SENT /* @min:%2eeventsSent */] = function (events) {\r\n _runListeners(_listeners, STR_EVENTS_SENT, _asyncNotifications, function (listener) {\r\n listener[STR_EVENTS_SENT /* @min:%2eeventsSent */](events);\r\n });\r\n };\r\n /**\r\n * Notification for events being discarded.\r\n * @param events - The array of events that have been discarded by the SDK.\r\n * @param reason - The reason for which the SDK discarded the events. The EventsDiscardedReason\r\n * constant should be used to check the different values.\r\n */\r\n _self[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */] = function (events, reason) {\r\n _runListeners(_listeners, STR_EVENTS_DISCARDED, _asyncNotifications, function (listener) {\r\n listener[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */](events, reason);\r\n });\r\n };\r\n /**\r\n * [Optional] A function called when the events have been requested to be sent to the sever.\r\n * @param sendReason - The reason why the event batch is being sent.\r\n * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.\r\n */\r\n _self[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */] = function (sendReason, isAsync) {\r\n _runListeners(_listeners, STR_EVENTS_SEND_REQUEST, isAsync ? _asyncNotifications : null, function (listener) {\r\n listener[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendReason, isAsync);\r\n });\r\n };\r\n _self[STR_PERF_EVENT /* @min:%2eperfEvent */] = function (perfEvent) {\r\n if (perfEvent) {\r\n // Send all events or only parent events\r\n if (perfEvtsSendAll || !perfEvent[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */]()) {\r\n _runListeners(_listeners, STR_PERF_EVENT, null, function (listener) {\r\n if (perfEvent[_DYN_IS_ASYNC /* @min:%2eisAsync */]) {\r\n scheduleTimeout(function () { return listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent); }, 0);\r\n }\r\n else {\r\n listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\r\n }\r\n });\r\n }\r\n }\r\n };\r\n _self[STR_OFFLINE_STORE /* @min:%2eofflineEventsStored */] = function (events) {\r\n if (events && events[_DYN_LENGTH /* @min:%2elength */]) {\r\n _runListeners(_listeners, STR_OFFLINE_STORE, _asyncNotifications, function (listener) {\r\n listener[STR_OFFLINE_STORE /* @min:%2eofflineEventsStored */](events);\r\n });\r\n }\r\n };\r\n _self[STR_OFFLINE_SENT /* @min:%2eofflineBatchSent */] = function (batch) {\r\n if (batch && batch[_DYN_DATA /* @min:%2edata */]) {\r\n _runListeners(_listeners, STR_OFFLINE_SENT, _asyncNotifications, function (listener) {\r\n listener[STR_OFFLINE_SENT /* @min:%2eofflineBatchSent */](batch);\r\n });\r\n }\r\n };\r\n _self[STR_OFFLINE_DROP /* @min:%2eofflineBatchDrop */] = function (cnt, reason) {\r\n if (cnt > 0) {\r\n var rn_1 = reason || 0; // default is unknown\r\n _runListeners(_listeners, STR_OFFLINE_DROP, _asyncNotifications, function (listener) {\r\n listener[STR_OFFLINE_DROP /* @min:%2eofflineBatchDrop */](cnt, rn_1);\r\n });\r\n }\r\n };\r\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync) {\r\n var _finishUnload = function () {\r\n unloadHandler && unloadHandler.rm();\r\n unloadHandler = null;\r\n _listeners = [];\r\n // Clear any async listener\r\n _asyncNotifications.h && _asyncNotifications.h[_DYN_CANCEL /* @min:%2ecancel */]();\r\n _asyncNotifications.h = null;\r\n _asyncNotifications.cb = [];\r\n };\r\n var waiting;\r\n _runListeners(_listeners, \"unload\", null, function (listener) {\r\n var asyncUnload = listener[_DYN_UNLOAD /* @min:%2eunload */](isAsync);\r\n if (asyncUnload) {\r\n if (!waiting) {\r\n waiting = [];\r\n }\r\n waiting[_DYN_PUSH /* @min:%2epush */](asyncUnload);\r\n }\r\n });\r\n if (waiting) {\r\n return createPromise(function (resolve) {\r\n return doAwaitResponse(createAllPromise(waiting), function () {\r\n _finishUnload();\r\n resolve();\r\n });\r\n });\r\n }\r\n else {\r\n _finishUnload();\r\n }\r\n };\r\n });\r\n }\r\n /**\r\n * Adds a notification listener.\r\n * @param listener - The notification listener to be added.\r\n */\r\n NotificationManager.prototype.addNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - AWTNotificationListener to remove.\r\n */\r\n NotificationManager.prototype.removeNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Notification for events sent.\r\n * @param events - The array of events that have been sent.\r\n */\r\n NotificationManager.prototype.eventsSent = function (events) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Notification for events being discarded.\r\n * @param events - The array of events that have been discarded by the SDK.\r\n * @param reason - The reason for which the SDK discarded the events. The EventsDiscardedReason\r\n * constant should be used to check the different values.\r\n */\r\n NotificationManager.prototype.eventsDiscarded = function (events, reason) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * [Optional] A function called when the events have been requested to be sent to the sever.\r\n * @param sendReason - The reason why the event batch is being sent.\r\n * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.\r\n */\r\n NotificationManager.prototype.eventsSendRequest = function (sendReason, isAsync) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging\r\n * the event can be displayed via the debug plugin extension.\r\n * @param perfEvent\r\n */\r\n NotificationManager.prototype.perfEvent = function (perfEvent) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Unload and remove any state that this INotificationManager may be holding, this is generally called when the\r\n * owning SDK is being unloaded.\r\n * @param isAsync - Can the unload be performed asynchronously (default)\r\n * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then\r\n * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * / Promise to allow any listeners to wait for the operation to complete.\r\n */\r\n NotificationManager.prototype.unload = function (isAsync) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * [Optional] A function called when the offline events have been stored to the persistent storage\r\n * @param events - events that are stored in the persistent storage\r\n */\r\n NotificationManager.prototype.offlineEventsStored = function (events) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * [Optional] A function called when the offline events have been sent from the persistent storage\r\n * @param batch - payload data that is sent from the persistent storage\r\n */\r\n NotificationManager.prototype.offlineBatchSent = function (batch) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * [Optional] A function called when the offline events have been dropped from the persistent storage\r\n * @param cnt - count of batches dropped\r\n * @param reason - the reason why the batches is dropped\r\n * @since v3.1.1\r\n */\r\n NotificationManager.prototype.offlineBatchDrop = function (cnt, reason) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return NotificationManager;\r\n}());\r\nexport { NotificationManager };\r\n//# sourceMappingURL=NotificationManager.js.map","// // Copyright (c) Microsoft Corporation. All rights reserved.\r\n// // Licensed under the MIT License.\r\nimport { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { arrAppend, arrForEach, dumpObj } from \"@nevware21/ts-utils\";\r\nimport { _DYN_APPLY, _DYN_DIAG_LOG, _DYN_LENGTH, _DYN_PROCESS_NEXT, _DYN_SPLICE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { BaseTelemetryPlugin } from \"./BaseTelemetryPlugin\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { getExceptionName } from \"./HelperFuncs\";\r\nimport { STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nfunction _addInitializer(_initializers, id, telemetryInitializer) {\r\n var theInitializer = {\r\n id: id,\r\n fn: telemetryInitializer\r\n };\r\n arrAppend(_initializers, theInitializer);\r\n var handler = {\r\n remove: function () {\r\n arrForEach(_initializers, function (initializer, idx) {\r\n if (initializer.id === theInitializer.id) {\r\n _initializers[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n return -1;\r\n }\r\n });\r\n }\r\n };\r\n return handler;\r\n}\r\nfunction _runInitializers(_initializers, item, logger) {\r\n var doNotSendItem = false;\r\n var telemetryInitializersCount = _initializers[_DYN_LENGTH /* @min:%2elength */];\r\n for (var i = 0; i < telemetryInitializersCount; ++i) {\r\n var telemetryInitializer = _initializers[i];\r\n if (telemetryInitializer) {\r\n try {\r\n if (telemetryInitializer.fn[_DYN_APPLY /* @min:%2eapply */](null, [item]) === false) {\r\n doNotSendItem = true;\r\n break;\r\n }\r\n }\r\n catch (e) {\r\n // log error but dont stop executing rest of the telemetry initializers\r\n // doNotSendItem = true;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Telemetry initializer failed: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n }\r\n }\r\n return !doNotSendItem;\r\n}\r\nvar TelemetryInitializerPlugin = /** @class */ (function (_super) {\r\n __extends(TelemetryInitializerPlugin, _super);\r\n function TelemetryInitializerPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = \"TelemetryInitializerPlugin\";\r\n _this.priority = 199;\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _id;\r\n var _initializers;\r\n _initDefaults();\r\n dynamicProto(TelemetryInitializerPlugin, _this, function (_self, _base) {\r\n _self.addTelemetryInitializer = function (telemetryInitializer) {\r\n return _addInitializer(_initializers, _id++, telemetryInitializer);\r\n };\r\n _self[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */] = function (item, itemCtx) {\r\n if (_runInitializers(_initializers, item, itemCtx ? itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]() : _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]())) {\r\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](item, itemCtx);\r\n }\r\n };\r\n _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] = function () {\r\n _initDefaults();\r\n };\r\n });\r\n function _initDefaults() {\r\n _id = 0;\r\n _initializers = [];\r\n }\r\n return _this;\r\n }\r\n /**\r\n * Add a telemetry processor to decorate or drop telemetry events.\r\n * @param telemetryInitializer - The Telemetry Initializer function\r\n * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed\r\n */\r\n TelemetryInitializerPlugin.prototype.addTelemetryInitializer = function (telemetryInitializer) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n TelemetryInitializerPlugin.prototype.processTelemetry = function (env, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return TelemetryInitializerPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport { TelemetryInitializerPlugin };\r\n//# sourceMappingURL=TelemetryInitializerPlugin.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nvar _a;\r\nimport { __spreadArray } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { createAllSettledPromise, createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { arrAppend, arrForEach, arrIndexOf, createTimeout, deepExtend, hasDocument, isFunction, isNullOrUndefined, isPlainObject, isPromiseLike, objDeepFreeze, objDefine, objForEachKey, objFreeze, objHasOwn, scheduleTimeout, throwError } from \"@nevware21/ts-utils\";\r\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\r\nimport { ActiveStatus } from \"../JavaScriptSDK.Enums/InitActiveStatusEnum\";\r\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_CANCEL, _DYN_CREATE_NEW, _DYN_ENABLED, _DYN_GET_NOTIFY_MGR, _DYN_GET_PLUGIN, _DYN_GET_PROCESS_TEL_CONT2, _DYN_IDENTIFIER, _DYN_INITIALIZE, _DYN_INSTRUMENTATION_KEY, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_I_KEY, _DYN_LENGTH, _DYN_LOGGER, _DYN_LOGGING_LEVEL_CONSOL4, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_NAME, _DYN_NOTIFY, _DYN_ON_COMPLETE, _DYN_POLL_INTERNAL_LOGS, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_0, _DYN_SET_DF, _DYN_SPLICE, _DYN_STOP_POLLING_INTERNA3, _DYN_TEARDOWN, _DYN_TIME, _DYN_UNLOAD, _DYN_VALUE, _DYN_VERSION, _DYN_WATCH, _DYN__INACTIVE } from \"../__DynamicConstants\";\r\nimport { doUnloadAll, runTargetUnload } from \"./AsyncUtils\";\r\nimport { ChannelControllerPriority } from \"./Constants\";\r\nimport { createCookieMgr } from \"./CookieMgr\";\r\nimport { createUniqueNamespace } from \"./DataCacheHelper\";\r\nimport { getDebugListener } from \"./DbgExtensionUtils\";\r\nimport { DiagnosticLogger, _InternalLogMessage, _throwInternal, _warnToConsole } from \"./DiagnosticLogger\";\r\nimport { getSetValue, isNotNullOrUndefined, proxyFunctionAs, proxyFunctions, toISOString } from \"./HelperFuncs\";\r\nimport { STR_CHANNELS, STR_CORE, STR_CREATE_PERF_MGR, STR_DISABLED, STR_EMPTY, STR_EVENTS_DISCARDED, STR_EXTENSIONS, STR_EXTENSION_CONFIG, STR_GET_PERF_MGR, STR_PRIORITY, UNDEFINED_VALUE } from \"./InternalConstants\";\r\nimport { NotificationManager } from \"./NotificationManager\";\r\nimport { PerfManager, doPerf, getGblPerfMgr } from \"./PerfManager\";\r\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext, createTelemetryProxyChain } from \"./ProcessTelemetryContext\";\r\nimport { _getPluginState, createDistributedTraceContext, initializePlugins, sortPlugins } from \"./TelemetryHelpers\";\r\nimport { TelemetryInitializerPlugin } from \"./TelemetryInitializerPlugin\";\r\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\r\nimport { createUnloadHookContainer } from \"./UnloadHookContainer\";\r\nvar strValidationError = \"Plugins must provide initialize method\";\r\nvar strNotificationManager = \"_notificationManager\";\r\nvar strSdkUnloadingError = \"SDK is still unloading...\";\r\nvar strSdkNotInitialized = \"SDK is not initialized\";\r\nvar maxInitQueueSize = 100;\r\nvar maxInitTimeout = 50000;\r\n// const strPluginUnloadFailed = \"Failed to unload plugin\";\r\n/**\r\n * The default settings for the config.\r\n * WE MUST include all defaults here to ensure that the config is created with all of the properties\r\n * defined as dynamic.\r\n */\r\nvar defaultConfig = objDeepFreeze((_a = {\r\n cookieCfg: {}\r\n },\r\n _a[STR_EXTENSIONS] = { rdOnly: true, ref: true, v: [] },\r\n _a[STR_CHANNELS] = { rdOnly: true, ref: true, v: [] },\r\n _a[STR_EXTENSION_CONFIG] = { ref: true, v: {} },\r\n _a[STR_CREATE_PERF_MGR] = UNDEFINED_VALUE,\r\n _a.loggingLevelConsole = 0 /* eLoggingSeverity.DISABLED */,\r\n _a.diagnosticLogInterval = UNDEFINED_VALUE,\r\n _a));\r\n/**\r\n * Helper to create the default performance manager\r\n * @param core\r\n * @param notificationMgr\r\n */\r\nfunction _createPerfManager(core, notificationMgr) {\r\n return new PerfManager(notificationMgr);\r\n}\r\nfunction _validateExtensions(logger, channelPriority, allExtensions) {\r\n var _a;\r\n // Concat all available extensions\r\n var coreExtensions = [];\r\n var channels = [];\r\n // Check if any two extensions have the same priority, then warn to console\r\n // And extract the local extensions from the\r\n var extPriorities = {};\r\n // Extension validation\r\n arrForEach(allExtensions, function (ext) {\r\n // Check for ext.initialize\r\n if (isNullOrUndefined(ext) || isNullOrUndefined(ext[_DYN_INITIALIZE /* @min:%2einitialize */])) {\r\n throwError(strValidationError);\r\n }\r\n var extPriority = ext[STR_PRIORITY /* @min:%2epriority */];\r\n var identifier = ext[_DYN_IDENTIFIER /* @min:%2eidentifier */];\r\n if (ext && extPriority) {\r\n if (!isNullOrUndefined(extPriorities[extPriority])) {\r\n _warnToConsole(logger, \"Two extensions have same priority #\" + extPriority + \" - \" + extPriorities[extPriority] + \", \" + identifier);\r\n }\r\n else {\r\n // set a value\r\n extPriorities[extPriority] = identifier;\r\n }\r\n }\r\n // Split extensions to core and channels\r\n if (!extPriority || extPriority < channelPriority) {\r\n // Add to core extension that will be managed by AppInsightsCore\r\n coreExtensions[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n else {\r\n channels[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n });\r\n return _a = {},\r\n _a[STR_CORE /* @min:core */] = coreExtensions,\r\n _a[STR_CHANNELS /* @min:channels */] = channels,\r\n _a;\r\n}\r\nfunction _isPluginPresent(thePlugin, plugins) {\r\n var exists = false;\r\n arrForEach(plugins, function (plugin) {\r\n if (plugin === thePlugin) {\r\n exists = true;\r\n return -1;\r\n }\r\n });\r\n return exists;\r\n}\r\nfunction _deepMergeConfig(details, target, newValues, merge) {\r\n // Lets assign the new values to the existing config\r\n if (newValues) {\r\n objForEachKey(newValues, function (key, value) {\r\n if (merge) {\r\n if (isPlainObject(value) && isPlainObject(target[key])) {\r\n // The target is an object and it has a value\r\n _deepMergeConfig(details, target[key], value, merge);\r\n }\r\n }\r\n if (merge && isPlainObject(value) && isPlainObject(target[key])) {\r\n // The target is an object and it has a value\r\n _deepMergeConfig(details, target[key], value, merge);\r\n }\r\n else {\r\n // Just Assign (replace) and/or make the property dynamic\r\n details.set(target, key, value);\r\n }\r\n });\r\n }\r\n}\r\nfunction _findWatcher(listeners, newWatcher) {\r\n var theListener = null;\r\n var idx = -1;\r\n arrForEach(listeners, function (listener, lp) {\r\n if (listener.w === newWatcher) {\r\n theListener = listener;\r\n idx = lp;\r\n return -1;\r\n }\r\n });\r\n return { i: idx, l: theListener };\r\n}\r\nfunction _addDelayedCfgListener(listeners, newWatcher) {\r\n var theListener = _findWatcher(listeners, newWatcher).l;\r\n if (!theListener) {\r\n theListener = {\r\n w: newWatcher,\r\n rm: function () {\r\n var fnd = _findWatcher(listeners, newWatcher);\r\n if (fnd.i !== -1) {\r\n listeners[_DYN_SPLICE /* @min:%2esplice */](fnd.i, 1);\r\n }\r\n }\r\n };\r\n listeners[_DYN_PUSH /* @min:%2epush */](theListener);\r\n }\r\n return theListener;\r\n}\r\nfunction _registerDelayedCfgListener(config, listeners, logger) {\r\n arrForEach(listeners, function (listener) {\r\n var unloadHdl = onConfigChange(config, listener.w, logger);\r\n delete listener.w; // Clear the listener reference so it will get garbage collected.\r\n // replace the remove function\r\n listener.rm = function () {\r\n unloadHdl.rm();\r\n };\r\n });\r\n}\r\n// Moved this outside of the closure to reduce the retained memory footprint\r\nfunction _initDebugListener(configHandler, unloadContainer, notificationManager, debugListener) {\r\n // Will get recalled if any referenced config values are changed\r\n unloadContainer.add(configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var disableDbgExt = details.cfg.disableDbgExt;\r\n if (disableDbgExt === true && debugListener) {\r\n // Remove any previously loaded debug listener\r\n notificationManager[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */](debugListener);\r\n debugListener = null;\r\n }\r\n if (notificationManager && !debugListener && disableDbgExt !== true) {\r\n debugListener = getDebugListener(details.cfg);\r\n notificationManager[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](debugListener);\r\n }\r\n }));\r\n return debugListener;\r\n}\r\n// Moved this outside of the closure to reduce the retained memory footprint\r\nfunction _createUnloadHook(unloadHook) {\r\n return objDefine({\r\n rm: function () {\r\n unloadHook.rm();\r\n }\r\n }, \"toJSON\", { v: function () { return \"aicore::onCfgChange<\" + JSON.stringify(unloadHook) + \">\"; } });\r\n}\r\n/**\r\n * @group Classes\r\n * @group Entrypoint\r\n */\r\nvar AppInsightsCore = /** @class */ (function () {\r\n function AppInsightsCore() {\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _configHandler;\r\n var _isInitialized;\r\n var _logger;\r\n var _eventQueue;\r\n var _notificationManager;\r\n var _perfManager;\r\n var _cfgPerfManager;\r\n var _cookieManager;\r\n var _pluginChain;\r\n var _configExtensions;\r\n var _channelConfig;\r\n var _channels;\r\n var _isUnloading;\r\n var _telemetryInitializerPlugin;\r\n var _internalLogsEventName;\r\n var _evtNamespace;\r\n var _unloadHandlers;\r\n var _hookContainer;\r\n var _debugListener;\r\n var _traceCtx;\r\n var _instrumentationKey;\r\n var _cfgListeners;\r\n var _extensions;\r\n var _pluginVersionStringArr;\r\n var _pluginVersionString;\r\n var _activeStatus; // to indicate if ikey or endpoint url promised is resolved or not\r\n var _endpoint;\r\n var _initInMemoMaxSize; // max event count limit during wait for init promises to be resolved\r\n var _isStatusSet; // track if active status is set in case of init timeout and init promises setting the status twice\r\n var _initTimer;\r\n /**\r\n * Internal log poller\r\n */\r\n var _internalLogPoller;\r\n var _internalLogPollerListening;\r\n var _forceStopInternalLogPoller;\r\n dynamicProto(AppInsightsCore, this, function (_self) {\r\n // Set the default values (also called during teardown)\r\n _initDefaults();\r\n // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects\r\n _self[\"_getDbgPlgTargets\"] = function () {\r\n return [_extensions, _eventQueue];\r\n };\r\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () { return _isInitialized; };\r\n // since version 3.3.0\r\n _self.activeStatus = function () { return _activeStatus; };\r\n // since version 3.3.0\r\n // internal\r\n _self._setPendingStatus = function () {\r\n _activeStatus = 3 /* eActiveStatus.PENDING */;\r\n };\r\n // Creating the self.initialize = ()\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, extensions, logger, notificationManager) {\r\n if (_isUnloading) {\r\n throwError(strSdkUnloadingError);\r\n }\r\n // Make sure core is only initialized once\r\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n throwError(\"Core cannot be initialized more than once\");\r\n }\r\n _configHandler = createDynamicConfig(config, defaultConfig, logger || _self[_DYN_LOGGER /* @min:%2elogger */], false);\r\n // Re-assigning the local config property so we don't have any references to the passed value and it can be garbage collected\r\n config = _configHandler.cfg;\r\n // This will be \"re-run\" if the referenced config properties are changed\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var rootCfg = details.cfg;\r\n var isPending = _activeStatus === 3 /* eActiveStatus.PENDING */;\r\n if (isPending) {\r\n // means waiting for previous promises to be resolved, won't apply new changes\r\n return;\r\n }\r\n _initInMemoMaxSize = rootCfg.initInMemoMaxSize || maxInitQueueSize;\r\n // app Insights core only handle ikey and endpointurl, aisku will handle cs\r\n var ikey = rootCfg[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\r\n var endpointUrl = rootCfg.endpointUrl; // do not need to validate endpoint url, if it is null, default one will be set by sender\r\n if (isNullOrUndefined(ikey)) {\r\n _instrumentationKey = null;\r\n // if new ikey is null, set status to be inactive, all new events will be saved in memory or dropped\r\n _activeStatus = ActiveStatus[_DYN__INACTIVE /* @min:%2eINACTIVE */];\r\n var msg = \"Please provide instrumentation key\";\r\n if (!_isInitialized) {\r\n // only throw error during initialization\r\n throwError(msg);\r\n }\r\n else {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 100 /* _eInternalMessageId.InvalidInstrumentationKey */, msg);\r\n _releaseQueues();\r\n }\r\n return;\r\n }\r\n var promises = [];\r\n if (isPromiseLike(ikey)) {\r\n promises[_DYN_PUSH /* @min:%2epush */](ikey);\r\n _instrumentationKey = null; // reset current local ikey variable (otherwise it will always be the previous ikeys if timeout is called before promise cb)\r\n }\r\n else {\r\n // string\r\n _instrumentationKey = ikey;\r\n }\r\n if (isPromiseLike(endpointUrl)) {\r\n promises[_DYN_PUSH /* @min:%2epush */](endpointUrl);\r\n _endpoint = null; // reset current local endpoint variable (otherwise it will always be the previous urls if timeout is called before promise cb)\r\n }\r\n else {\r\n // string or null\r\n _endpoint = endpointUrl;\r\n }\r\n // at least have one promise\r\n if (promises[_DYN_LENGTH /* @min:%2elength */]) {\r\n // reset to false for new dynamic changes\r\n _isStatusSet = false;\r\n _activeStatus = 3 /* eActiveStatus.PENDING */;\r\n var initTimeout = isNotNullOrUndefined(rootCfg.initTimeOut) ? rootCfg.initTimeOut : maxInitTimeout; // rootCfg.initTimeOut could be 0\r\n var allPromises = createAllSettledPromise(promises);\r\n _initTimer = scheduleTimeout(function () {\r\n // set _isStatusSet to true\r\n // set active status\r\n // release queues\r\n _initTimer = null;\r\n if (!_isStatusSet) {\r\n _setStatus();\r\n }\r\n }, initTimeout);\r\n doAwaitResponse(allPromises, function (response) {\r\n try {\r\n if (_isStatusSet) {\r\n // promises take too long to resolve, ignore them\r\n // active status should be set by timeout already\r\n return;\r\n }\r\n if (!response.rejected) {\r\n var values = response[_DYN_VALUE /* @min:%2evalue */];\r\n if (values && values[_DYN_LENGTH /* @min:%2elength */]) {\r\n // ikey\r\n var ikeyRes = values[0];\r\n _instrumentationKey = ikeyRes && ikeyRes[_DYN_VALUE /* @min:%2evalue */];\r\n // endpoint\r\n if (values[_DYN_LENGTH /* @min:%2elength */] > 1) {\r\n var endpointRes = values[1];\r\n _endpoint = endpointRes && endpointRes[_DYN_VALUE /* @min:%2evalue */];\r\n }\r\n }\r\n if (_instrumentationKey) {\r\n // if ikey is null, no need to trigger extra dynamic changes for extensions\r\n config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = _instrumentationKey; // set config.instrumentationKey for extensions to consume\r\n config.endpointUrl = _endpoint; // set config.endpointUrl for extensions to consume\r\n }\r\n }\r\n // set _isStatusSet to true\r\n // set active status\r\n // release queues\r\n _setStatus();\r\n }\r\n catch (e) {\r\n if (!_isStatusSet) {\r\n _setStatus();\r\n }\r\n }\r\n });\r\n }\r\n else {\r\n // means no promises\r\n _setStatus();\r\n }\r\n //_instrumentationKey = details.cfg.instrumentationKey;\r\n // Mark the extensionConfig and all first level keys as referenced\r\n // This is so that calls to getExtCfg() will always return the same object\r\n // Even when a user may \"re-assign\" the plugin properties (or it's unloaded/reloaded)\r\n var extCfg = details.ref(details.cfg, STR_EXTENSION_CONFIG);\r\n objForEachKey(extCfg, function (key) {\r\n details.ref(extCfg, key);\r\n });\r\n }));\r\n _notificationManager = notificationManager;\r\n // Initialize the debug listener outside of the closure to reduce the retained memory footprint\r\n _debugListener = _initDebugListener(_configHandler, _hookContainer, _notificationManager && _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */](), _debugListener);\r\n _initPerfManager();\r\n _self[_DYN_LOGGER /* @min:%2elogger */] = logger;\r\n var cfgExtensions = config[STR_EXTENSIONS /* @min:%2eextensions */];\r\n // Extension validation\r\n _configExtensions = [];\r\n _configExtensions[_DYN_PUSH /* @min:%2epush */].apply(_configExtensions, __spreadArray(__spreadArray([], extensions, false), cfgExtensions, false));\r\n _channelConfig = config[STR_CHANNELS /* @min:%2echannels */];\r\n _initPluginChain(null);\r\n if (!_channels || _channels[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n throwError(\"No \" + STR_CHANNELS + \" available\");\r\n }\r\n if (_channelConfig && _channelConfig[_DYN_LENGTH /* @min:%2elength */] > 1) {\r\n var teeController = _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */](\"TeeChannelController\");\r\n if (!teeController || !teeController.plugin) {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"TeeChannel required\");\r\n }\r\n }\r\n _registerDelayedCfgListener(config, _cfgListeners, _logger);\r\n _cfgListeners = null;\r\n _isInitialized = true;\r\n if (_activeStatus === ActiveStatus.ACTIVE) {\r\n _releaseQueues();\r\n }\r\n };\r\n _self.getChannels = function () {\r\n var controls = [];\r\n if (_channels) {\r\n arrForEach(_channels, function (channel) {\r\n controls[_DYN_PUSH /* @min:%2epush */](channel);\r\n });\r\n }\r\n return objFreeze(controls);\r\n };\r\n _self.track = function (telemetryItem) {\r\n doPerf(_self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */](), function () { return \"AppInsightsCore:track\"; }, function () {\r\n if (telemetryItem === null) {\r\n _notifyInvalidEvent(telemetryItem);\r\n // throw error\r\n throwError(\"Invalid telemetry item\");\r\n }\r\n // do basic validation before sending it through the pipeline\r\n if (!telemetryItem[_DYN_NAME /* @min:%2ename */] && isNullOrUndefined(telemetryItem[_DYN_NAME /* @min:%2ename */])) {\r\n _notifyInvalidEvent(telemetryItem);\r\n throwError(\"telemetry name required\");\r\n }\r\n // setup default iKey if not passed in\r\n telemetryItem[_DYN_I_KEY /* @min:%2eiKey */] = telemetryItem[_DYN_I_KEY /* @min:%2eiKey */] || _instrumentationKey;\r\n // add default timestamp if not passed in\r\n telemetryItem[_DYN_TIME /* @min:%2etime */] = telemetryItem[_DYN_TIME /* @min:%2etime */] || toISOString(new Date());\r\n // Common Schema 4.0\r\n telemetryItem.ver = telemetryItem.ver || \"4.0\";\r\n if (!_isUnloading && _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]() && _activeStatus === ActiveStatus.ACTIVE) {\r\n // Process the telemetry plugin chain\r\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](telemetryItem);\r\n }\r\n else if (_activeStatus !== ActiveStatus[_DYN__INACTIVE /* @min:%2eINACTIVE */]) {\r\n // Queue events until all extensions are initialized\r\n if (_eventQueue[_DYN_LENGTH /* @min:%2elength */] <= _initInMemoMaxSize) {\r\n // set limit, if full, stop adding new events\r\n _eventQueue[_DYN_PUSH /* @min:%2epush */](telemetryItem);\r\n }\r\n }\r\n }, function () { return ({ item: telemetryItem }); }, !(telemetryItem.sync));\r\n };\r\n _self[_DYN_GET_PROCESS_TEL_CONT2 /* @min:%2egetProcessTelContext */] = _createTelCtx;\r\n _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */] = function () {\r\n if (!_notificationManager) {\r\n _notificationManager = new NotificationManager(_configHandler.cfg);\r\n // For backward compatibility only\r\n _self[strNotificationManager] = _notificationManager;\r\n }\r\n return _notificationManager;\r\n };\r\n /**\r\n * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.\r\n * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be\r\n * called.\r\n * @param listener - An INotificationListener object.\r\n */\r\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\r\n _self.getNotifyMgr()[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](listener);\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - INotificationListener to remove.\r\n */\r\n _self[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */] = function (listener) {\r\n if (_notificationManager) {\r\n _notificationManager[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */](listener);\r\n }\r\n };\r\n _self.getCookieMgr = function () {\r\n if (!_cookieManager) {\r\n _cookieManager = createCookieMgr(_configHandler.cfg, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return _cookieManager;\r\n };\r\n _self.setCookieMgr = function (cookieMgr) {\r\n if (_cookieManager !== cookieMgr) {\r\n runTargetUnload(_cookieManager, false);\r\n _cookieManager = cookieMgr;\r\n }\r\n };\r\n _self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */] = function () {\r\n return _perfManager || _cfgPerfManager || getGblPerfMgr();\r\n };\r\n _self.setPerfMgr = function (perfMgr) {\r\n _perfManager = perfMgr;\r\n };\r\n _self.eventCnt = function () {\r\n return _eventQueue[_DYN_LENGTH /* @min:%2elength */];\r\n };\r\n _self.releaseQueue = function () {\r\n if (_isInitialized && _eventQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var eventQueue = _eventQueue;\r\n _eventQueue = [];\r\n if (_activeStatus === 2 /* eActiveStatus.ACTIVE */) {\r\n arrForEach(eventQueue, function (event) {\r\n event[_DYN_I_KEY /* @min:%2eiKey */] = event[_DYN_I_KEY /* @min:%2eiKey */] || _instrumentationKey;\r\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](event);\r\n });\r\n }\r\n else {\r\n // new one for msg ikey\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 20 /* _eInternalMessageId.FailedToSendQueuedTelemetry */, \"core init status is not active\");\r\n }\r\n }\r\n };\r\n _self[_DYN_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */] = function (eventName) {\r\n _internalLogsEventName = eventName || null;\r\n _forceStopInternalLogPoller = false;\r\n _internalLogPoller && _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\r\n return _startLogPoller(true);\r\n };\r\n function _setStatus() {\r\n _isStatusSet = true;\r\n if (isNullOrUndefined(_instrumentationKey)) {\r\n _activeStatus = ActiveStatus[_DYN__INACTIVE /* @min:%2eINACTIVE */];\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 112 /* _eInternalMessageId.InitPromiseException */, \"ikey can't be resolved from promises\");\r\n }\r\n else {\r\n _activeStatus = ActiveStatus.ACTIVE;\r\n }\r\n _releaseQueues();\r\n }\r\n function _releaseQueues() {\r\n if (_isInitialized) {\r\n _self.releaseQueue();\r\n _self[_DYN_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */]();\r\n }\r\n }\r\n function _startLogPoller(alwaysStart) {\r\n if ((!_internalLogPoller || !_internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */]) && !_forceStopInternalLogPoller) {\r\n var shouldStart = alwaysStart || (_logger && _logger.queue[_DYN_LENGTH /* @min:%2elength */] > 0);\r\n if (shouldStart) {\r\n if (!_internalLogPollerListening) {\r\n _internalLogPollerListening = true;\r\n // listen for any configuration changes so that changes to the\r\n // interval will cause the timer to be re-initialized\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var interval = details.cfg.diagnosticLogInterval;\r\n if (!interval || !(interval > 0)) {\r\n interval = 10000;\r\n }\r\n var isRunning = false;\r\n if (_internalLogPoller) {\r\n // It was already created so remember it's running and cancel\r\n isRunning = _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */];\r\n _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\r\n }\r\n // Create / reconfigure\r\n _internalLogPoller = createTimeout(_flushInternalLogs, interval);\r\n _internalLogPoller.unref();\r\n // Restart if previously running\r\n _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */] = isRunning;\r\n }));\r\n }\r\n _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */] = true;\r\n }\r\n }\r\n return _internalLogPoller;\r\n }\r\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */] = function () {\r\n _forceStopInternalLogPoller = true;\r\n _internalLogPoller && _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\r\n _flushInternalLogs();\r\n };\r\n // Add addTelemetryInitializer\r\n proxyFunctions(_self, function () { return _telemetryInitializerPlugin; }, [\"addTelemetryInitializer\"]);\r\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync, unloadComplete, cbTimeout) {\r\n var _a;\r\n if (isAsync === void 0) { isAsync = true; }\r\n if (!_isInitialized) {\r\n // The SDK is not initialized\r\n throwError(strSdkNotInitialized);\r\n }\r\n // Check if the SDK still unloading so throw\r\n if (_isUnloading) {\r\n // The SDK is already unloading\r\n throwError(strSdkUnloadingError);\r\n }\r\n var unloadState = (_a = {\r\n reason: 50 /* TelemetryUnloadReason.SdkUnload */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = isAsync,\r\n _a.flushComplete = false,\r\n _a);\r\n var result;\r\n if (isAsync && !unloadComplete) {\r\n result = createPromise(function (resolve) {\r\n // Set the callback to the promise resolve callback\r\n unloadComplete = resolve;\r\n });\r\n }\r\n var processUnloadCtx = createProcessTelemetryUnloadContext(_getPluginChain(), _self);\r\n processUnloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\r\n _hookContainer.run(_self[_DYN_LOGGER /* @min:%2elogger */]);\r\n // Run any \"unload\" functions for the _cookieManager, _notificationManager and _logger\r\n doUnloadAll([_cookieManager, _notificationManager, _logger], isAsync, function () {\r\n _initDefaults();\r\n unloadComplete && unloadComplete(unloadState);\r\n });\r\n }, _self);\r\n function _doUnload(flushComplete) {\r\n unloadState.flushComplete = flushComplete;\r\n _isUnloading = true;\r\n // Run all of the unload handlers first (before unloading the plugins)\r\n _unloadHandlers.run(processUnloadCtx, unloadState);\r\n // Stop polling the internal logs\r\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */]();\r\n // Start unloading the components, from this point onwards the SDK should be considered to be in an unstable state\r\n processUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n _flushInternalLogs();\r\n if (!_flushChannels(isAsync, _doUnload, 6 /* SendRequestReason.SdkUnload */, cbTimeout)) {\r\n _doUnload(false);\r\n }\r\n return result;\r\n };\r\n _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */] = _getPlugin;\r\n _self.addPlugin = function (plugin, replaceExisting, isAsync, addCb) {\r\n if (!plugin) {\r\n addCb && addCb(false);\r\n _logOrThrowError(strValidationError);\r\n return;\r\n }\r\n var existingPlugin = _getPlugin(plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */]);\r\n if (existingPlugin && !replaceExisting) {\r\n addCb && addCb(false);\r\n _logOrThrowError(\"Plugin [\" + plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"] is already loaded!\");\r\n return;\r\n }\r\n var updateState = {\r\n reason: 16 /* TelemetryUpdateReason.PluginAdded */\r\n };\r\n function _addPlugin(removed) {\r\n _configExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\r\n updateState.added = [plugin];\r\n // Re-Initialize the plugin chain\r\n _initPluginChain(updateState);\r\n addCb && addCb(true);\r\n }\r\n if (existingPlugin) {\r\n var removedPlugins_1 = [existingPlugin.plugin];\r\n var unloadState = {\r\n reason: 2 /* TelemetryUnloadReason.PluginReplace */,\r\n isAsync: !!isAsync\r\n };\r\n _removePlugins(removedPlugins_1, unloadState, function (removed) {\r\n if (!removed) {\r\n // Previous plugin was successfully removed or was not installed\r\n addCb && addCb(false);\r\n }\r\n else {\r\n updateState.removed = removedPlugins_1;\r\n updateState.reason |= 32 /* TelemetryUpdateReason.PluginRemoved */;\r\n _addPlugin(true);\r\n }\r\n });\r\n }\r\n else {\r\n _addPlugin(false);\r\n }\r\n };\r\n _self.updateCfg = function (newConfig, mergeExisting) {\r\n if (mergeExisting === void 0) { mergeExisting = true; }\r\n var updateState;\r\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n updateState = {\r\n reason: 1 /* TelemetryUpdateReason.ConfigurationChanged */,\r\n cfg: _configHandler.cfg,\r\n oldCfg: deepExtend({}, _configHandler.cfg),\r\n newConfig: deepExtend({}, newConfig),\r\n merge: mergeExisting\r\n };\r\n newConfig = updateState.newConfig;\r\n var cfg = _configHandler.cfg;\r\n // replace the immutable (if initialized) values\r\n // We don't currently allow updating the extensions and channels via the update config\r\n // So overwriting any user provided values to reuse the existing values\r\n newConfig[STR_EXTENSIONS /* @min:%2eextensions */] = cfg[STR_EXTENSIONS /* @min:%2eextensions */];\r\n newConfig[STR_CHANNELS /* @min:%2echannels */] = cfg[STR_CHANNELS /* @min:%2echannels */];\r\n }\r\n // Explicitly blocking any previous config watchers so that they don't get called because\r\n // of this bulk update (Probably not necessary)\r\n _configHandler._block(function (details) {\r\n // Lets assign the new values to the existing config either overwriting or re-assigning\r\n var theConfig = details.cfg;\r\n _deepMergeConfig(details, theConfig, newConfig, mergeExisting);\r\n if (!mergeExisting) {\r\n // Remove (unassign) the values \"missing\" from the newConfig and also not in the default config\r\n objForEachKey(theConfig, function (key) {\r\n if (!objHasOwn(newConfig, key)) {\r\n // Set the value to undefined\r\n details.set(theConfig, key, UNDEFINED_VALUE);\r\n }\r\n });\r\n }\r\n // Apply defaults to the new config\r\n details[_DYN_SET_DF /* @min:%2esetDf */](theConfig, defaultConfig);\r\n }, true);\r\n // Now execute all of the listeners (synchronously) so they update their values immediately\r\n _configHandler[_DYN_NOTIFY /* @min:%2enotify */]();\r\n if (updateState) {\r\n _doUpdate(updateState);\r\n }\r\n };\r\n _self.evtNamespace = function () {\r\n return _evtNamespace;\r\n };\r\n _self.flush = _flushChannels;\r\n _self.getTraceCtx = function (createNew) {\r\n if (!_traceCtx) {\r\n _traceCtx = createDistributedTraceContext();\r\n }\r\n return _traceCtx;\r\n };\r\n _self.setTraceCtx = function (traceCtx) {\r\n _traceCtx = traceCtx || null;\r\n };\r\n _self.addUnloadHook = _addUnloadHook;\r\n // Create the addUnloadCb\r\n proxyFunctionAs(_self, \"addUnloadCb\", function () { return _unloadHandlers; }, \"add\");\r\n _self.onCfgChange = function (handler) {\r\n var unloadHook;\r\n if (!_isInitialized) {\r\n unloadHook = _addDelayedCfgListener(_cfgListeners, handler);\r\n }\r\n else {\r\n unloadHook = onConfigChange(_configHandler.cfg, handler, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return _createUnloadHook(unloadHook);\r\n };\r\n _self.getWParam = function () {\r\n return (hasDocument() || !!_configHandler.cfg.enableWParam) ? 0 : -1;\r\n };\r\n function _setPluginVersions() {\r\n var thePlugins = {};\r\n _pluginVersionStringArr = [];\r\n var _addPluginVersions = function (plugins) {\r\n if (plugins) {\r\n arrForEach(plugins, function (plugin) {\r\n if (plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] && plugin[_DYN_VERSION /* @min:%2eversion */] && !thePlugins[plugin.identifier]) {\r\n var ver = plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"=\" + plugin[_DYN_VERSION /* @min:%2eversion */];\r\n _pluginVersionStringArr[_DYN_PUSH /* @min:%2epush */](ver);\r\n thePlugins[plugin.identifier] = plugin;\r\n }\r\n });\r\n }\r\n };\r\n _addPluginVersions(_channels);\r\n if (_channelConfig) {\r\n arrForEach(_channelConfig, function (channels) {\r\n _addPluginVersions(channels);\r\n });\r\n }\r\n _addPluginVersions(_configExtensions);\r\n }\r\n function _initDefaults() {\r\n _isInitialized = false;\r\n // Use a default logger so initialization errors are not dropped on the floor with full logging\r\n _configHandler = createDynamicConfig({}, defaultConfig, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n // Set the logging level to critical so that any critical initialization failures are displayed on the console\r\n _configHandler.cfg[_DYN_LOGGING_LEVEL_CONSOL4 /* @min:%2eloggingLevelConsole */] = 1 /* eLoggingSeverity.CRITICAL */;\r\n // Define _self.config\r\n objDefine(_self, \"config\", {\r\n g: function () { return _configHandler.cfg; },\r\n s: function (newValue) {\r\n _self.updateCfg(newValue, false);\r\n }\r\n });\r\n objDefine(_self, \"pluginVersionStringArr\", {\r\n g: function () {\r\n if (!_pluginVersionStringArr) {\r\n _setPluginVersions();\r\n }\r\n return _pluginVersionStringArr;\r\n }\r\n });\r\n objDefine(_self, \"pluginVersionString\", {\r\n g: function () {\r\n if (!_pluginVersionString) {\r\n if (!_pluginVersionStringArr) {\r\n _setPluginVersions();\r\n }\r\n _pluginVersionString = _pluginVersionStringArr.join(\";\");\r\n }\r\n return _pluginVersionString || STR_EMPTY;\r\n }\r\n });\r\n objDefine(_self, \"logger\", {\r\n g: function () {\r\n if (!_logger) {\r\n _logger = new DiagnosticLogger(_configHandler.cfg);\r\n _configHandler[_DYN_LOGGER /* @min:%2elogger */] = _logger;\r\n }\r\n return _logger;\r\n },\r\n s: function (newLogger) {\r\n _configHandler[_DYN_LOGGER /* @min:%2elogger */] = newLogger;\r\n if (_logger !== newLogger) {\r\n runTargetUnload(_logger, false);\r\n _logger = newLogger;\r\n }\r\n }\r\n });\r\n _self[_DYN_LOGGER /* @min:%2elogger */] = new DiagnosticLogger(_configHandler.cfg);\r\n _extensions = [];\r\n var cfgExtensions = _self.config[STR_EXTENSIONS /* @min:%2eextensions */] || [];\r\n cfgExtensions.splice(0, cfgExtensions[_DYN_LENGTH /* @min:%2elength */]);\r\n arrAppend(cfgExtensions, _extensions);\r\n _telemetryInitializerPlugin = new TelemetryInitializerPlugin();\r\n _eventQueue = [];\r\n runTargetUnload(_notificationManager, false);\r\n _notificationManager = null;\r\n _perfManager = null;\r\n _cfgPerfManager = null;\r\n runTargetUnload(_cookieManager, false);\r\n _cookieManager = null;\r\n _pluginChain = null;\r\n _configExtensions = [];\r\n _channelConfig = null;\r\n _channels = null;\r\n _isUnloading = false;\r\n _internalLogsEventName = null;\r\n _evtNamespace = createUniqueNamespace(\"AIBaseCore\", true);\r\n _unloadHandlers = createUnloadHandlerContainer();\r\n _traceCtx = null;\r\n _instrumentationKey = null;\r\n _hookContainer = createUnloadHookContainer();\r\n _cfgListeners = [];\r\n _pluginVersionString = null;\r\n _pluginVersionStringArr = null;\r\n _forceStopInternalLogPoller = false;\r\n _internalLogPoller = null;\r\n _internalLogPollerListening = false;\r\n _activeStatus = 0 /* eActiveStatus.NONE */; // default is None\r\n _endpoint = null;\r\n _initInMemoMaxSize = null;\r\n _isStatusSet = false;\r\n _initTimer = null;\r\n }\r\n function _createTelCtx() {\r\n var theCtx = createProcessTelemetryContext(_getPluginChain(), _configHandler.cfg, _self);\r\n theCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_startLogPoller);\r\n return theCtx;\r\n }\r\n // Initialize or Re-initialize the plugins\r\n function _initPluginChain(updateState) {\r\n // Extension validation\r\n var theExtensions = _validateExtensions(_self[_DYN_LOGGER /* @min:%2elogger */], ChannelControllerPriority, _configExtensions);\r\n _pluginChain = null;\r\n _pluginVersionString = null;\r\n _pluginVersionStringArr = null;\r\n // Get the primary channel queue and include as part of the normal extensions\r\n _channels = (_channelConfig || [])[0] || [];\r\n // Add any channels provided in the extensions and sort them\r\n _channels = sortPlugins(arrAppend(_channels, theExtensions[STR_CHANNELS /* @min:%2echannels */]));\r\n // Create an array of all extensions, including the _channels\r\n var allExtensions = arrAppend(sortPlugins(theExtensions[STR_CORE /* @min:%2ecore */]), _channels);\r\n // Required to allow plugins to call core.getPlugin() during their own initialization\r\n _extensions = objFreeze(allExtensions);\r\n // This has a side effect of adding the extensions passed during initialization\r\n // into the config.extensions, so you can see all of the extensions loaded.\r\n // This will also get updated by the addPlugin() and remove plugin code.\r\n var cfgExtensions = _self.config[STR_EXTENSIONS /* @min:%2eextensions */] || [];\r\n cfgExtensions.splice(0, cfgExtensions[_DYN_LENGTH /* @min:%2elength */]);\r\n arrAppend(cfgExtensions, _extensions);\r\n var rootCtx = _createTelCtx();\r\n // Initializing the channels first\r\n if (_channels && _channels[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n initializePlugins(rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](_channels), allExtensions);\r\n }\r\n // Now initialize the normal extensions (explicitly not including the _channels as this can cause duplicate initialization)\r\n initializePlugins(rootCtx, allExtensions);\r\n if (updateState) {\r\n _doUpdate(updateState);\r\n }\r\n }\r\n function _getPlugin(pluginIdentifier) {\r\n var theExt = null;\r\n var thePlugin = null;\r\n var channelHosts = [];\r\n arrForEach(_extensions, function (ext) {\r\n if (ext[_DYN_IDENTIFIER /* @min:%2eidentifier */] === pluginIdentifier && ext !== _telemetryInitializerPlugin) {\r\n thePlugin = ext;\r\n return -1;\r\n }\r\n if (ext.getChannel) {\r\n channelHosts[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n });\r\n if (!thePlugin && channelHosts[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(channelHosts, function (host) {\r\n thePlugin = host.getChannel(pluginIdentifier);\r\n if (!thePlugin) {\r\n return -1;\r\n }\r\n });\r\n }\r\n if (thePlugin) {\r\n theExt = {\r\n plugin: thePlugin,\r\n setEnabled: function (enabled) {\r\n _getPluginState(thePlugin)[STR_DISABLED] = !enabled;\r\n },\r\n isEnabled: function () {\r\n var pluginState = _getPluginState(thePlugin);\r\n return !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] && !pluginState[STR_DISABLED];\r\n },\r\n remove: function (isAsync, removeCb) {\r\n var _a;\r\n if (isAsync === void 0) { isAsync = true; }\r\n var pluginsToRemove = [thePlugin];\r\n var unloadState = (_a = {\r\n reason: 1 /* TelemetryUnloadReason.PluginUnload */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = isAsync,\r\n _a);\r\n _removePlugins(pluginsToRemove, unloadState, function (removed) {\r\n if (removed) {\r\n // Re-Initialize the plugin chain\r\n _initPluginChain({\r\n reason: 32 /* TelemetryUpdateReason.PluginRemoved */,\r\n removed: pluginsToRemove\r\n });\r\n }\r\n removeCb && removeCb(removed);\r\n });\r\n }\r\n };\r\n }\r\n return theExt;\r\n }\r\n function _getPluginChain() {\r\n if (!_pluginChain) {\r\n // copy the collection of extensions\r\n var extensions = (_extensions || []).slice();\r\n // During add / remove this may get called again, so don't read if already present\r\n if (arrIndexOf(extensions, _telemetryInitializerPlugin) === -1) {\r\n extensions[_DYN_PUSH /* @min:%2epush */](_telemetryInitializerPlugin);\r\n }\r\n _pluginChain = createTelemetryProxyChain(sortPlugins(extensions), _configHandler.cfg, _self);\r\n }\r\n return _pluginChain;\r\n }\r\n function _removePlugins(thePlugins, unloadState, removeComplete) {\r\n if (thePlugins && thePlugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var unloadChain = createTelemetryProxyChain(thePlugins, _configHandler.cfg, _self);\r\n var unloadCtx = createProcessTelemetryUnloadContext(unloadChain, _self);\r\n unloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\r\n var removed = false;\r\n // Remove the listed config extensions\r\n var newConfigExtensions = [];\r\n arrForEach(_configExtensions, function (plugin, idx) {\r\n if (!_isPluginPresent(plugin, thePlugins)) {\r\n newConfigExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\r\n }\r\n else {\r\n removed = true;\r\n }\r\n });\r\n _configExtensions = newConfigExtensions;\r\n _pluginVersionString = null;\r\n _pluginVersionStringArr = null;\r\n // Re-Create the channel config\r\n var newChannelConfig = [];\r\n if (_channelConfig) {\r\n arrForEach(_channelConfig, function (queue, idx) {\r\n var newQueue = [];\r\n arrForEach(queue, function (channel) {\r\n if (!_isPluginPresent(channel, thePlugins)) {\r\n newQueue[_DYN_PUSH /* @min:%2epush */](channel);\r\n }\r\n else {\r\n removed = true;\r\n }\r\n });\r\n newChannelConfig[_DYN_PUSH /* @min:%2epush */](newQueue);\r\n });\r\n _channelConfig = newChannelConfig;\r\n }\r\n removeComplete && removeComplete(removed);\r\n _startLogPoller();\r\n });\r\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n else {\r\n removeComplete(false);\r\n }\r\n }\r\n function _flushInternalLogs() {\r\n if (_logger && _logger.queue) {\r\n var queue = _logger.queue.slice(0);\r\n _logger.queue[_DYN_LENGTH /* @min:%2elength */] = 0;\r\n arrForEach(queue, function (logMessage) {\r\n var _a;\r\n var item = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = _internalLogsEventName ? _internalLogsEventName : \"InternalMessageId: \" + logMessage[_DYN_MESSAGE_ID /* @min:%2emessageId */],\r\n _a[_DYN_I_KEY /* @min:iKey */] = _instrumentationKey,\r\n _a[_DYN_TIME /* @min:time */] = toISOString(new Date()),\r\n _a.baseType = _InternalLogMessage.dataType,\r\n _a.baseData = { message: logMessage[_DYN_MESSAGE /* @min:%2emessage */] },\r\n _a);\r\n _self.track(item);\r\n });\r\n }\r\n }\r\n function _flushChannels(isAsync, callBack, sendReason, cbTimeout) {\r\n // Setting waiting to one so that we don't call the callBack until we finish iterating\r\n var waiting = 1;\r\n var doneIterating = false;\r\n var cbTimer = null;\r\n cbTimeout = cbTimeout || 5000;\r\n function doCallback() {\r\n waiting--;\r\n if (doneIterating && waiting === 0) {\r\n cbTimer && cbTimer[_DYN_CANCEL /* @min:%2ecancel */]();\r\n cbTimer = null;\r\n callBack && callBack(doneIterating);\r\n callBack = null;\r\n }\r\n }\r\n if (_channels && _channels[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var flushCtx = _createTelCtx()[_DYN_CREATE_NEW /* @min:%2ecreateNew */](_channels);\r\n flushCtx.iterate(function (plugin) {\r\n if (plugin.flush) {\r\n waiting++;\r\n var handled_1 = false;\r\n // Not all channels will call this callback for every scenario\r\n if (!plugin.flush(isAsync, function () {\r\n handled_1 = true;\r\n doCallback();\r\n }, sendReason)) {\r\n if (!handled_1) {\r\n // If any channel doesn't return true and it didn't call the callback, then we should assume that the callback\r\n // will never be called, so use a timeout to allow the channel(s) some time to \"finish\" before triggering any\r\n // followup function (such as unloading)\r\n if (isAsync && cbTimer == null) {\r\n cbTimer = scheduleTimeout(function () {\r\n cbTimer = null;\r\n doCallback();\r\n }, cbTimeout);\r\n }\r\n else {\r\n doCallback();\r\n }\r\n }\r\n }\r\n }\r\n });\r\n }\r\n doneIterating = true;\r\n doCallback();\r\n return true;\r\n }\r\n function _initPerfManager() {\r\n // Save the previous config based performance manager creator to avoid creating new perf manager instances if unchanged\r\n var prevCfgPerfMgr;\r\n // Will get recalled if any referenced config values are changed\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var enablePerfMgr = details.cfg.enablePerfMgr;\r\n if (enablePerfMgr) {\r\n var createPerfMgr = details.cfg[STR_CREATE_PERF_MGR /* @min:%2ecreatePerfMgr */];\r\n if (prevCfgPerfMgr !== createPerfMgr) {\r\n if (!createPerfMgr) {\r\n createPerfMgr = _createPerfManager;\r\n }\r\n // Set the performance manager creation function if not defined\r\n getSetValue(details.cfg, STR_CREATE_PERF_MGR, createPerfMgr);\r\n prevCfgPerfMgr = createPerfMgr;\r\n // Remove any existing config based performance manager\r\n _cfgPerfManager = null;\r\n }\r\n // Only create the performance manager if it's not already created or manually set\r\n if (!_perfManager && !_cfgPerfManager && isFunction(createPerfMgr)) {\r\n // Create a new config based performance manager\r\n _cfgPerfManager = createPerfMgr(_self, _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]());\r\n }\r\n }\r\n else {\r\n // Remove any existing config based performance manager\r\n _cfgPerfManager = null;\r\n // Clear the previous cached value so it can be GC'd\r\n prevCfgPerfMgr = null;\r\n }\r\n }));\r\n }\r\n function _doUpdate(updateState) {\r\n var updateCtx = createProcessTelemetryUpdateContext(_getPluginChain(), _self);\r\n updateCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_startLogPoller);\r\n if (!_self._updateHook || _self._updateHook(updateCtx, updateState) !== true) {\r\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\r\n }\r\n }\r\n function _logOrThrowError(message) {\r\n var logger = _self[_DYN_LOGGER /* @min:%2elogger */];\r\n if (logger) {\r\n // there should always be a logger\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, message);\r\n _startLogPoller();\r\n }\r\n else {\r\n throwError(message);\r\n }\r\n }\r\n function _notifyInvalidEvent(telemetryItem) {\r\n var manager = _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]();\r\n if (manager) {\r\n manager[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */]([telemetryItem], 2 /* eEventsDiscardedReason.InvalidEvent */);\r\n }\r\n }\r\n function _addUnloadHook(hooks) {\r\n _hookContainer.add(hooks);\r\n }\r\n });\r\n }\r\n AppInsightsCore.prototype.initialize = function (config, extensions, logger, notificationManager) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getChannels = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.track = function (telemetryItem) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getProcessTelContext = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.getNotifyMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.\r\n * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be\r\n * called.\r\n * @param listener - An INotificationListener object.\r\n */\r\n AppInsightsCore.prototype.addNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - INotificationListener to remove.\r\n */\r\n AppInsightsCore.prototype.removeNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Get the current cookie manager for this instance\r\n */\r\n AppInsightsCore.prototype.getCookieMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Set the current cookie manager for this instance\r\n * @param cookieMgr - The manager, if set to null/undefined will cause the default to be created\r\n */\r\n AppInsightsCore.prototype.setCookieMgr = function (cookieMgr) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getPerfMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.setPerfMgr = function (perfMgr) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.eventCnt = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\n /**\r\n * Enable the timer that checks the logger.queue for log messages to be flushed.\r\n * Note: Since 3.0.1 and 2.8.13 this is no longer an interval timer but is a normal\r\n * timer that is only started when this function is called and then subsequently\r\n * only _if_ there are any logger.queue messages to be sent.\r\n */\r\n AppInsightsCore.prototype.pollInternalLogs = function (eventName) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Stop the timer that log messages from logger.queue when available\r\n */\r\n AppInsightsCore.prototype.stopPollingInternalLogs = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add a telemetry processor to decorate or drop telemetry events.\r\n * @param telemetryInitializer - The Telemetry Initializer function\r\n * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed\r\n */\r\n AppInsightsCore.prototype.addTelemetryInitializer = function (telemetryInitializer) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered\r\n * to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous\r\n * unload call return `true` stating that all plugins reported that they also unloaded, the recommended\r\n * approach is to create a new instance and initialize that instance.\r\n * This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable\r\n * to successfully remove any global references or they may just be completing the unload process asynchronously.\r\n * If you pass isAsync as `true` (also the default) and DO NOT pass a callback function then an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will be returned which will resolve once the unload is complete. The actual implementation of the `IPromise`\r\n * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param isAsync - Can the unload be performed asynchronously (default)\r\n * @param unloadComplete - An optional callback that will be called once the unload has completed\r\n * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the\r\n * unload. Defaults to 5 seconds.\r\n * @return Nothing or if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * which will be resolved once the unload is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will only be returned when no callback is provided and isAsync is true\r\n */\r\n AppInsightsCore.prototype.unload = function (isAsync, unloadComplete, cbTimeout) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getPlugin = function (pluginIdentifier) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add a new plugin to the installation\r\n * @param plugin - The new plugin to add\r\n * @param replaceExisting - should any existing plugin be replaced, default is false\r\n * @param doAsync - Should the add be performed asynchronously\r\n * @param addCb - [Optional] callback to call after the plugin has been added\r\n */\r\n AppInsightsCore.prototype.addPlugin = function (plugin, replaceExisting, doAsync, addCb) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Update the configuration used and broadcast the changes to all loaded plugins\r\n * @param newConfig - The new configuration is apply\r\n * @param mergeExisting - Should the new configuration merge with the existing or just replace it. Default is to true.\r\n */\r\n AppInsightsCore.prototype.updateCfg = function (newConfig, mergeExisting) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Returns the unique event namespace that should be used\r\n */\r\n AppInsightsCore.prototype.evtNamespace = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add an unload handler that will be called when the SDK is being unloaded\r\n * @param handler - the handler\r\n */\r\n AppInsightsCore.prototype.addUnloadCb = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Flush and send any batched / cached data immediately\r\n * @param async - send data asynchronously when true (defaults to true)\r\n * @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called.\r\n * If the caller doesn't return true the caller should assume that it may never be called.\r\n * @param sendReason - specify the reason that you are calling \"flush\" defaults to ManualFlush (1) if not specified\r\n * @returns - true if the callback will be return after the flush is complete otherwise the caller should assume that any provided callback will never be called\r\n */\r\n AppInsightsCore.prototype.flush = function (isAsync, callBack, sendReason) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Gets the current distributed trace context for this instance if available\r\n * @param createNew - Optional flag to create a new instance if one doesn't currently exist, defaults to true\r\n */\r\n AppInsightsCore.prototype.getTraceCtx = function (createNew) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Sets the current distributed trace context for this instance if available\r\n */\r\n AppInsightsCore.prototype.setTraceCtx = function (newTracectx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add this hook so that it is automatically removed during unloading\r\n * @param hooks - The single hook or an array of IInstrumentHook objects\r\n */\r\n AppInsightsCore.prototype.addUnloadHook = function (hooks) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Watches and tracks changes for accesses to the current config, and if the accessed config changes the\r\n * handler will be recalled.\r\n * @param handler\r\n * @returns A watcher handler instance that can be used to remove itself when being unloaded\r\n */\r\n AppInsightsCore.prototype.onCfgChange = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Watches and tracks status of initialization process\r\n * @returns ActiveStatus\r\n * @since 3.3.0\r\n * If returned status is active, it means initialization process is completed.\r\n * If returned status is pending, it means the initialization process is waiting for promieses to be resolved.\r\n * If returned status is inactive, it means ikey is invalid or can 't get ikey or enpoint url from promsises.\r\n */\r\n AppInsightsCore.prototype.activeStatus = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Set Active Status to pending, which will block the incoming changes until internal promises are resolved\r\n * @internal Internal use\r\n * @since 3.3.0\r\n */\r\n AppInsightsCore.prototype._setPendingStatus = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.releaseQueue = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Hook for Core extensions to allow them to update their own configuration before updating all of the plugins.\r\n * @param updateCtx - The plugin update context\r\n * @param updateState - The Update State\r\n * @returns boolean - True means the extension class will call updateState otherwise the Core will\r\n */\r\n AppInsightsCore.prototype._updateHook = function (updateCtx, updateState) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return false;\r\n };\r\n return AppInsightsCore;\r\n}());\r\nexport { AppInsightsCore };\r\n//# sourceMappingURL=AppInsightsCore.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// ###################################################################################################################################################\r\n// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ###\r\n// ###################################################################################################################################################\r\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nexport var STR_DURATION = \"duration\";\r\nexport var STR_PROPERTIES = \"properties\";\r\n//# sourceMappingURL=InternalConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_REQUEST_URL = \"requestUrl\"; // Count: 11\r\nexport var _DYN_INST = \"inst\"; // Count: 5\r\nexport var _DYN_LENGTH = \"length\"; // Count: 8\r\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 9\r\nexport var _DYN_SPAN_ID = \"spanID\"; // Count: 8\r\nexport var _DYN_TRACE_FLAGS = \"traceFlags\"; // Count: 13\r\nexport var _DYN_CONTEXT = \"context\"; // Count: 7\r\nexport var _DYN_ABORTED = \"aborted\"; // Count: 7\r\nexport var _DYN_TRACE_ID0 = \"traceId\"; // Count: 5\r\nexport var _DYN_SPAN_ID1 = \"spanId\"; // Count: 5\r\nexport var _DYN__ADD_HOOK = \"_addHook\"; // Count: 4\r\nexport var _DYN_CORE = \"core\"; // Count: 8\r\nexport var _DYN_INCLUDE_CORRELATION_2 = \"includeCorrelationHeaders\"; // Count: 4\r\nexport var _DYN_GET_ABSOLUTE_URL = \"getAbsoluteUrl\"; // Count: 3\r\nexport var _DYN_HEADERS = \"headers\"; // Count: 6\r\nexport var _DYN_REQUEST_HEADERS = \"requestHeaders\"; // Count: 13\r\nexport var _DYN_SET_REQUEST_HEADER = \"setRequestHeader\"; // Count: 3\r\nexport var _DYN_TRACK_DEPENDENCY_DAT3 = \"trackDependencyDataInternal\"; // Count: 2\r\nexport var _DYN_START_TIME = \"startTime\"; // Count: 6\r\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\r\nexport var _DYN_ENABLE_REQUEST_HEADE4 = \"enableRequestHeaderTracking\"; // Count: 3\r\nexport var _DYN_ENABLE_AJAX_ERROR_ST5 = \"enableAjaxErrorStatusText\"; // Count: 2\r\nexport var _DYN_ENABLE_AJAX_PERF_TRA6 = \"enableAjaxPerfTracking\"; // Count: 2\r\nexport var _DYN_MAX_AJAX_CALLS_PER_V7 = \"maxAjaxCallsPerView\"; // Count: 2\r\nexport var _DYN_EXCLUDE_REQUEST_FROM8 = \"excludeRequestFromAutoTrackingPatterns\"; // Count: 2\r\nexport var _DYN_ADD_REQUEST_CONTEXT = \"addRequestContext\"; // Count: 2\r\nexport var _DYN_DISABLE_AJAX_TRACKIN9 = \"disableAjaxTracking\"; // Count: 3\r\nexport var _DYN_AJAX_PERF_LOOKUP_DEL10 = \"ajaxPerfLookupDelay\"; // Count: 2\r\nexport var _DYN_DISABLE_FETCH_TRACKI11 = \"disableFetchTracking\"; // Count: 2\r\nexport var _DYN_ENABLE_RESPONSE_HEAD12 = \"enableResponseHeaderTracking\"; // Count: 2\r\nexport var _DYN_STATUS = \"status\"; // Count: 11\r\nexport var _DYN_STATUS_TEXT = \"statusText\"; // Count: 9\r\nexport var _DYN_HEADER_MAP = \"headerMap\"; // Count: 8\r\nexport var _DYN_OPEN_DONE = \"openDone\"; // Count: 3\r\nexport var _DYN_SEND_DONE = \"sendDone\"; // Count: 3\r\nexport var _DYN_REQUEST_SENT_TIME = \"requestSentTime\"; // Count: 9\r\nexport var _DYN_ABORT_DONE = \"abortDone\"; // Count: 3\r\nexport var _DYN_GET_TRACE_ID = \"getTraceId\"; // Count: 3\r\nexport var _DYN_GET_TRACE_FLAGS = \"getTraceFlags\"; // Count: 3\r\nexport var _DYN_METHOD = \"method\"; // Count: 8\r\nexport var _DYN_ERROR_STATUS_TEXT = \"errorStatusText\"; // Count: 3\r\nexport var _DYN_STATE_CHANGE_ATTACHE13 = \"stateChangeAttached\"; // Count: 2\r\nexport var _DYN_RESPONSE_TEXT = \"responseText\"; // Count: 6\r\nexport var _DYN_RESPONSE_FINISHED_TI14 = \"responseFinishedTime\"; // Count: 7\r\nexport var _DYN__CREATE_TRACK_ITEM = \"CreateTrackItem\"; // Count: 3\r\nexport var _DYN_RESPONSE = \"response\"; // Count: 4\r\nexport var _DYN_GET_ALL_RESPONSE_HEA15 = \"getAllResponseHeaders\"; // Count: 2\r\nexport var _DYN_GET_PART_APROPS = \"getPartAProps\"; // Count: 3\r\nexport var _DYN_PERF_MARK = \"perfMark\"; // Count: 4\r\nexport var _DYN_NAME = \"name\"; // Count: 6\r\nexport var _DYN_PERF_TIMING = \"perfTiming\"; // Count: 3\r\nexport var _DYN_EXCEPTION = \"exception\"; // Count: 5\r\nexport var _DYN_AJAX_DIAGNOSTICS_MES16 = \"ajaxDiagnosticsMessage\"; // Count: 3\r\nexport var _DYN_CORRELATION_CONTEXT = \"correlationContext\"; // Count: 3\r\nexport var _DYN_AJAX_TOTAL_DURATION = \"ajaxTotalDuration\"; // Count: 3\r\nexport var _DYN_EVENT_TRACE_CTX = \"eventTraceCtx\"; // Count: 3\r\n//# sourceMappingURL=__DynamicConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { Extensions, dataSanitizeUrl, dateTimeUtilsDuration, msToTimeSpan, urlGetAbsoluteUrl, urlGetCompleteUrl } from \"@microsoft/applicationinsights-common\";\r\nimport { arrForEach, isNullOrUndefined, isNumber, isString, normalizeJsName, objForEachKey, objKeys } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_DURATION, STR_PROPERTIES } from \"./InternalConstants\";\r\nimport { _DYN_ABORTED, _DYN_ABORT_DONE, _DYN_AJAX_TOTAL_DURATION, _DYN_CORRELATION_CONTEXT, _DYN_ERROR_STATUS_TEXT, _DYN_EVENT_TRACE_CTX, _DYN_GET_ABSOLUTE_URL, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADER_MAP, _DYN_LENGTH, _DYN_METHOD, _DYN_NAME, _DYN_OPEN_DONE, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE, _DYN_RESPONSE_FINISHED_TI14, _DYN_SEND_DONE, _DYN_SPAN_ID, _DYN_SPAN_ID1, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE13, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACE_ID0, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\r\n/** @ignore */\r\nfunction _calcPerfDuration(resourceEntry, start, end) {\r\n var result = 0;\r\n var from = resourceEntry[start];\r\n var to = resourceEntry[end];\r\n if (from && to) {\r\n result = dateTimeUtilsDuration(from, to);\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _setPerfDuration(props, name, resourceEntry, start, end) {\r\n var result = 0;\r\n var value = _calcPerfDuration(resourceEntry, start, end);\r\n if (value) {\r\n result = _setPerfValue(props, name, msToTimeSpan(value));\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _setPerfValue(props, name, value) {\r\n var strPerf = \"ajaxPerf\";\r\n var result = 0;\r\n if (props && name && value) {\r\n var perfData = props[strPerf] = (props[strPerf] || {});\r\n perfData[name] = value;\r\n result = 1;\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _populatePerfData(ajaxData, dependency) {\r\n /*\r\n * https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API\r\n * | -startTime\r\n * | -redirectStart\r\n * | | -redirectEnd\r\n * | | | -fetchStart\r\n * | | | | -domainLookupStart\r\n * | | | | |- domainLookupEnd\r\n * | | | | | | -connectStart\r\n * | | | | | | | -secureConnectionStart\r\n * | | | | | | | | -connectEnd\r\n * | | | | | | | | | -requestStart\r\n * | | | | | | | | | | | -responseStart\r\n * | | | | | | | | | | | | | -responseEnd\r\n * +------------+-+---+----------------+-+--+--------+-+-----------+-+------------+-+\r\n * |--redirect--| |---|--domainLookup--| |--connect--| |--request--| |--response--| |\r\n * |-------------------networkConnect----------------|\r\n * | |---------sentRequest--------|\r\n * |------------------------------------perfTotal-----------------------------------|\r\n */\r\n var resourceEntry = ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */];\r\n var props = dependency[STR_PROPERTIES /* @min:%2eproperties */] || {};\r\n var propsSet = 0;\r\n var strName = \"name\";\r\n var strStart = \"Start\";\r\n var strEnd = \"End\";\r\n var strDomainLookup = \"domainLookup\";\r\n var strConnect = \"connect\";\r\n var strRedirect = \"redirect\";\r\n var strRequest = \"request\";\r\n var strResponse = \"response\";\r\n var strStartTime = \"startTime\";\r\n var strDomainLookupStart = strDomainLookup + strStart;\r\n var strDomainLookupEnd = strDomainLookup + strEnd;\r\n var strConnectStart = strConnect + strStart;\r\n var strConnectEnd = strConnect + strEnd;\r\n var strRequestStart = strRequest + strStart;\r\n var strRequestEnd = strRequest + strEnd;\r\n var strResponseStart = strResponse + strStart;\r\n var strResponseEnd = strResponse + strEnd;\r\n var strRedirectStart = strRedirect + strStart;\r\n var strRedirectEnd = strRedirect = strEnd;\r\n var strTransferSize = \"transferSize\";\r\n var strEncodedBodySize = \"encodedBodySize\";\r\n var strDecodedBodySize = \"decodedBodySize\";\r\n var strServerTiming = \"serverTiming\";\r\n if (resourceEntry) {\r\n // redirect\r\n propsSet |= _setPerfDuration(props, strRedirect, resourceEntry, strRedirectStart, strRedirectEnd);\r\n // domainLookup\r\n propsSet |= _setPerfDuration(props, strDomainLookup, resourceEntry, strDomainLookupStart, strDomainLookupEnd);\r\n // connect\r\n propsSet |= _setPerfDuration(props, strConnect, resourceEntry, strConnectStart, strConnectEnd);\r\n // request\r\n propsSet |= _setPerfDuration(props, strRequest, resourceEntry, strRequestStart, strRequestEnd);\r\n // response\r\n propsSet |= _setPerfDuration(props, strResponse, resourceEntry, strResponseStart, strResponseEnd);\r\n // Network connection time\r\n propsSet |= _setPerfDuration(props, \"networkConnect\", resourceEntry, strStartTime, strConnectEnd);\r\n // Sent Request\r\n propsSet |= _setPerfDuration(props, \"sentRequest\", resourceEntry, strRequestStart, strResponseEnd);\r\n // PerfTotal / Duration\r\n var duration = resourceEntry[STR_DURATION /* @min:%2eduration */];\r\n if (!duration) {\r\n duration = _calcPerfDuration(resourceEntry, strStartTime, strResponseEnd) || 0;\r\n }\r\n propsSet |= _setPerfValue(props, STR_DURATION, duration);\r\n propsSet |= _setPerfValue(props, \"perfTotal\", duration);\r\n var serverTiming = resourceEntry[strServerTiming];\r\n if (serverTiming) {\r\n var server_1 = {};\r\n arrForEach(serverTiming, function (value, idx) {\r\n var name = normalizeJsName(value[strName] || \"\" + idx);\r\n var newValue = server_1[name] || {};\r\n objForEachKey(value, function (key, val) {\r\n if (key !== strName && isString(val) || isNumber(val)) {\r\n if (newValue[key]) {\r\n val = newValue[key] + \";\" + val;\r\n }\r\n if (val || !isString(val)) {\r\n // Only set the value if it has a value and it's not an empty string\r\n newValue[key] = val;\r\n }\r\n }\r\n });\r\n server_1[name] = newValue;\r\n });\r\n propsSet |= _setPerfValue(props, strServerTiming, server_1);\r\n }\r\n propsSet |= _setPerfValue(props, strTransferSize, resourceEntry[strTransferSize]);\r\n propsSet |= _setPerfValue(props, strEncodedBodySize, resourceEntry[strEncodedBodySize]);\r\n propsSet |= _setPerfValue(props, strDecodedBodySize, resourceEntry[strDecodedBodySize]);\r\n }\r\n else {\r\n if (ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */]) {\r\n propsSet |= _setPerfValue(props, \"missing\", ajaxData.perfAttempts);\r\n }\r\n }\r\n if (propsSet) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = props;\r\n }\r\n}\r\nvar XHRMonitoringState = /** @class */ (function () {\r\n function XHRMonitoringState() {\r\n var self = this;\r\n self[_DYN_OPEN_DONE /* @min:%2eopenDone */] = false;\r\n self.setRequestHeaderDone = false;\r\n self[_DYN_SEND_DONE /* @min:%2esendDone */] = false;\r\n self[_DYN_ABORT_DONE /* @min:%2eabortDone */] = false;\r\n //