/*
 * Application Insights JavaScript SDK - Web, 3.3.5-nightly3.2411-06
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */


"use strict";
var _a, _b, _c, _d;
import dynamicProto from "@microsoft/dynamicproto-js";
import { AnalyticsPlugin } from "@microsoft/applicationinsights-analytics-js";
import { CfgSyncPlugin } from "@microsoft/applicationinsights-cfgsync-js";
import { Sender } from "@microsoft/applicationinsights-channel-js";
import { AnalyticsPluginIdentifier, DEFAULT_BREEZE_PATH, PropertiesPluginIdentifier, ThrottleMgr, parseConnectionString } from "@microsoft/applicationinsights-common";
import { AppInsightsCore, _throwInternal, addPageHideEventListener, addPageUnloadEventListener, cfgDfMerge, cfgDfValidate, createDynamicConfig, createProcessTelemetryContext, createUniqueNamespace, doPerf, hasDocument, hasWindow, isArray, isFeatureEnabled, isFunction, isNullOrUndefined, isReactNative, isString, mergeEvtNamespace, onConfigChange, proxyAssign, proxyFunctions, removePageHideEventListener, removePageUnloadEventListener } from "@microsoft/applicationinsights-core-js";
import { AjaxPlugin as DependenciesPlugin } from "@microsoft/applicationinsights-dependencies-js";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import { createPromise, createSyncPromise, doAwaitResponse } from "@nevware21/ts-async";
import { arrForEach, arrIndexOf, isPromiseLike, objDefine, objForEachKey, strIndexOf, throwUnsupported } from "@nevware21/ts-utils";
import { CONFIG_ENDPOINT_URL, STR_ADD_TELEMETRY_INITIALIZER, STR_CLEAR_AUTHENTICATED_USER_CONTEXT, STR_EVT_NAMESPACE, STR_FLUSH, STR_GET_COOKIE_MGR, STR_GET_PLUGIN, STR_POLL_INTERNAL_LOGS, STR_SET_AUTHENTICATED_USER_CONTEXT, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE, STR_STOP_TRACK_EVENT, STR_STOP_TRACK_PAGE, STR_TRACK_DEPENDENCY_DATA, STR_TRACK_EVENT, STR_TRACK_EXCEPTION, STR_TRACK_METRIC, STR_TRACK_PAGE_VIEW, STR_TRACK_TRACE } from "./InternalConstants";
import { _DYN_ADD_HOUSEKEEPING_BEF2, _DYN_CONNECTION_STRING, _DYN_CONTEXT, _DYN_ENDPOINT_URL, _DYN_INGESTIONENDPOINT, _DYN_INSTRUMENTATIONKEY0, _DYN_INSTRUMENTATION_KEY, _DYN_ONUNLOAD_FLUSH, _DYN_QUEUE, _DYN_SEND_MESSAGE, _DYN_UPDATE_SNIPPET_DEFIN3, _DYN_USER_OVERRIDE_ENDPOI1, _DYN_VERSION } from "./__DynamicConstants";
var _internalSdkSrc;
// This is an exclude list of properties that should not be updated during initialization
// They include a combination of private and internal property names
var _ignoreUpdateSnippetProperties = [
    STR_SNIPPET, "dependencies", "properties", "_snippetVersion", "appInsightsNew", "getSKUDefaults"
];
var IKEY_USAGE = "iKeyUsage";
var CDN_USAGE = "CdnUsage";
var SDK_LOADER_VER = "SdkLoaderVer";
var UNDEFINED_VALUE = undefined;
var default_limit = {
    samplingRate: 100,
    maxSendNumber: 1
};
var default_interval = {
    monthInterval: 3,
    daysOfMonth: [28]
};
var default_throttle_config = {
    disabled: true,
    limit: cfgDfMerge(default_limit),
    interval: cfgDfMerge(default_interval)
};
// We need to include all properties that we only reference that we want to be dynamically updatable here
// So they are converted even when not specified in the passed configuration
var defaultConfigValues = (_a = {},
    _a[_DYN_CONNECTION_STRING /* @min:connectionString */] = UNDEFINED_VALUE,
    _a[_DYN_ENDPOINT_URL /* @min:endpointUrl */] = UNDEFINED_VALUE,
    _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = UNDEFINED_VALUE,
    _a[_DYN_USER_OVERRIDE_ENDPOI1 /* @min:userOverrideEndpointUrl */] = UNDEFINED_VALUE,
    _a.diagnosticLogInterval = cfgDfValidate(_chkDiagLevel, 10000),
    _a.featureOptIn = (_b = {},
        _b[IKEY_USAGE] = { mode: 3 /* FeatureOptInMode.enable */ },
        _b[CDN_USAGE] = { mode: 2 /* FeatureOptInMode.disable */ },
        _b[SDK_LOADER_VER] = { mode: 2 /* FeatureOptInMode.disable */ },
        _b),
    _a.throttleMgrCfg = cfgDfMerge((_c = {},
        _c[109 /* _eInternalMessageId.DefaultThrottleMsgKey */] = cfgDfMerge(default_throttle_config),
        _c[106 /* _eInternalMessageId.InstrumentationKeyDeprecation */] = cfgDfMerge(default_throttle_config),
        _c[111 /* _eInternalMessageId.SdkLdrUpdate */] = cfgDfMerge(default_throttle_config),
        _c[110 /* _eInternalMessageId.CdnDeprecation */] = cfgDfMerge(default_throttle_config),
        _c)),
    _a.extensionConfig = cfgDfMerge((_d = {},
        _d["AppInsightsCfgSyncPlugin"] = cfgDfMerge({
            cfgUrl: CONFIG_ENDPOINT_URL,
            syncMode: 2 /* ICfgSyncMode.Receive */
        }),
        _d)),
    _a);
function _chkDiagLevel(value) {
    // Make sure we have a value > 0
    return value && value > 0;
}
/**
 * Application Insights API
 * @group Entrypoint
 * @group Classes
 * @class Initialization
 * @implements {IApplicationInsights}
 */
var AppInsightsSku = /** @class */ (function () {
    function AppInsightsSku(snippet) {
        var _this = this;
        // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()
        var dependencies;
        var properties;
        var _sender;
        var _snippetVersion;
        var _evtNamespace;
        var _houseKeepingNamespace;
        var _core;
        var _config;
        var _analyticsPlugin;
        var _cfgSyncPlugin;
        var _throttleMgr;
        var _iKeySentMessage;
        var _cdnSentMessage;
        var _sdkVerSentMessage;
        dynamicProto(AppInsightsSku, this, function (_self) {
            _initDefaults();
            objDefine(_self, "config", {
                g: function () {
                    return _config;
                }
            });
            arrForEach(["pluginVersionStringArr", "pluginVersionString"], function (key) {
                objDefine(_self, key, {
                    g: function () {
                        if (_core) {
                            return _core[key];
                        }
                        return null;
                    }
                });
            });
            // initialize the queue and config in case they are undefined
            _snippetVersion = "" + (snippet.sv || snippet[_DYN_VERSION /* @min:%2eversion */] || "");
            snippet[_DYN_QUEUE /* @min:%2equeue */] = snippet[_DYN_QUEUE /* @min:%2equeue */] || [];
            snippet[_DYN_VERSION /* @min:%2eversion */] = snippet[_DYN_VERSION /* @min:%2eversion */] || 2.0; // Default to new version
            var cfgHandler = createDynamicConfig(snippet.config || {}, defaultConfigValues);
            _config = cfgHandler.cfg;
            _analyticsPlugin = new AnalyticsPlugin();
            objDefine(_self, "appInsights", {
                g: function () {
                    return _analyticsPlugin;
                }
            });
            properties = new PropertiesPlugin();
            dependencies = new DependenciesPlugin();
            _sender = new Sender();
            _core = new AppInsightsCore();
            objDefine(_self, "core", {
                g: function () {
                    return _core;
                }
            });
            // Will get recalled if any referenced values are changed
            _addUnloadHook(onConfigChange(cfgHandler, function () {
                var configCs = _config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */];
                function _parseCs() {
                    return createSyncPromise(function (resolve, reject) {
                        doAwaitResponse(configCs, function (res) {
                            var curCs = res && res.value;
                            var parsedCs = null;
                            if (!res.rejected && curCs) {
                                // replace cs with resolved values in case of circular promises
                                _config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */] = curCs;
                                parsedCs = parseConnectionString(curCs);
                            }
                            // if can't resolve cs promise, null will be returned
                            resolve(parsedCs);
                        });
                    });
                }
                if (isPromiseLike(configCs)) {
                    var ikeyPromise = createSyncPromise(function (resolve, reject) {
                        _parseCs().then(function (cs) {
                            var ikey = _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];
                            ikey = cs && cs[_DYN_INSTRUMENTATIONKEY0 /* @min:%2einstrumentationkey */] || ikey;
                            resolve(ikey);
                        }).catch(function (e) {
                            // parseCs will always resolve(unless timeout)
                            // return null in case any error happens
                            resolve(null);
                        });
                    });
                    var url = _config[_DYN_USER_OVERRIDE_ENDPOI1 /* @min:%2euserOverrideEndpointUrl */];
                    if (isNullOrUndefined(url)) {
                        url = createSyncPromise(function (resolve, reject) {
                            _parseCs().then(function (cs) {
                                var url = _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];
                                var ingest = cs && cs[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */];
                                url = ingest ? ingest + DEFAULT_BREEZE_PATH : url;
                                resolve(url);
                            }).catch(function (e) {
                                // parseCs will always resolve(unless timeout)
                                // return null in case any error happens
                                resolve(null);
                            });
                        });
                    }
                    _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = ikeyPromise;
                    _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */] = url;
                }
                if (isString(configCs) && configCs) {
                    // confirm if promiselike function present
                    // handle cs promise here
                    // add cases to oneNote
                    var cs = parseConnectionString(configCs);
                    var ingest = cs[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */];
                    _config.endpointUrl = _config[_DYN_USER_OVERRIDE_ENDPOI1 /* @min:%2euserOverrideEndpointUrl */] ? _config[_DYN_USER_OVERRIDE_ENDPOI1 /* @min:%2euserOverrideEndpointUrl */] : ingest + DEFAULT_BREEZE_PATH; // add /v2/track
                    _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = cs[_DYN_INSTRUMENTATIONKEY0 /* @min:%2einstrumentationkey */] || _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];
                }
                // userOverrideEndpointUrl have the highest priority
                _config.endpointUrl = _config[_DYN_USER_OVERRIDE_ENDPOI1 /* @min:%2euserOverrideEndpointUrl */] ? _config[_DYN_USER_OVERRIDE_ENDPOI1 /* @min:%2euserOverrideEndpointUrl */] : _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];
            }));
            _self[STR_SNIPPET /* @min:%2esnippet */] = snippet;
            _self[STR_FLUSH /* @min:%2eflush */] = function (async, callBack) {
                if (async === void 0) { async = true; }
                var result;
                doPerf(_core, function () { return "AISKU.flush"; }, function () {
                    if (async && !callBack) {
                        result = createPromise(function (resolve) {
                            callBack = resolve;
                        });
                    }
                    var waiting = 1;
                    var flushDone = function () {
                        waiting--;
                        if (waiting === 0) {
                            callBack();
                        }
                    };
                    arrForEach(_core.getChannels(), function (channel) {
                        if (channel) {
                            waiting++;
                            channel[STR_FLUSH /* @min:%2eflush */](async, flushDone);
                        }
                    });
                    // decrement the initial "waiting"
                    flushDone();
                }, null, async);
                return result;
            };
            _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */] = function (async) {
                if (async === void 0) { async = true; }
                arrForEach(_core.getChannels(), function (channel) {
                    if (channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]) {
                        channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]();
                    }
                    else {
                        channel[STR_FLUSH /* @min:%2eflush */](async);
                    }
                });
            };
            _self.loadAppInsights = function (legacyMode, logger, notificationManager) {
                if (legacyMode === void 0) { legacyMode = false; }
                if (legacyMode) {
                    throwUnsupported("Legacy Mode is no longer supported");
                }
                function _updateSnippetProperties(snippet) {
                    if (snippet) {
                        var snippetVer = "";
                        if (!isNullOrUndefined(_snippetVersion)) {
                            snippetVer += _snippetVersion;
                        }
                        if (_self[_DYN_CONTEXT /* @min:%2econtext */] && _self[_DYN_CONTEXT /* @min:%2econtext */].internal) {
                            _self[_DYN_CONTEXT /* @min:%2econtext */].internal.snippetVer = snippetVer || "-";
                        }
                        // apply updated properties to the global instance (snippet)
                        objForEachKey(_self, function (field, value) {
                            if (isString(field) &&
                                !isFunction(value) &&
                                field && field[0] !== "_" && // Don't copy "internal" values
                                arrIndexOf(_ignoreUpdateSnippetProperties, field) === -1) {
                                if (snippet[field] !== value) {
                                    snippet[field] = value;
                                }
                            }
                        });
                    }
                }
                doPerf(_self.core, function () { return "AISKU.loadAppInsights"; }, function () {
                    // initialize core
                    _core.initialize(_config, [_sender, properties, dependencies, _analyticsPlugin, _cfgSyncPlugin], logger, notificationManager);
                    objDefine(_self, "context", {
                        g: function () { return properties[_DYN_CONTEXT /* @min:%2econtext */]; }
                    });
                    if (!_throttleMgr) {
                        _throttleMgr = new ThrottleMgr(_core);
                    }
                    var sdkSrc = _findSdkSourceFile();
                    if (sdkSrc && _self[_DYN_CONTEXT /* @min:%2econtext */]) {
                        _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc = sdkSrc;
                    }
                    _updateSnippetProperties(_self[STR_SNIPPET /* @min:%2esnippet */]);
                    // Empty queue of all api calls logged prior to sdk download
                    _self.emptyQueue();
                    _self[STR_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */]();
                    _self[_DYN_ADD_HOUSEKEEPING_BEF2 /* @min:%2eaddHousekeepingBeforeUnload */](_self);
                    _addUnloadHook(onConfigChange(cfgHandler, function () {
                        var defaultEnable = false;
                        if (_config.throttleMgrCfg[109 /* _eInternalMessageId.DefaultThrottleMsgKey */]) {
                            defaultEnable = !_config.throttleMgrCfg[109 /* _eInternalMessageId.DefaultThrottleMsgKey */].disabled;
                        }
                        if (!_throttleMgr.isReady() && _config.extensionConfig && _config.extensionConfig[_cfgSyncPlugin.identifier] && defaultEnable) {
                            // set ready state to true will automatically trigger flush()
                            _throttleMgr.onReadyState(true);
                        }
                        var result;
                        if (!_iKeySentMessage && !_config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */] && isFeatureEnabled(IKEY_USAGE, _config)) {
                            result = _throttleMgr[_DYN_SEND_MESSAGE /* @min:%2esendMessage */](106 /* _eInternalMessageId.InstrumentationKeyDeprecation */, "See Instrumentation key support at aka.ms/IkeyMigrate");
                            _iKeySentMessage = true;
                        }
                        if (!_cdnSentMessage && _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc && _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc.indexOf("az416426") != -1 && isFeatureEnabled(CDN_USAGE, _config)) {
                            result = _throttleMgr[_DYN_SEND_MESSAGE /* @min:%2esendMessage */](110 /* _eInternalMessageId.CdnDeprecation */, "See Cdn support notice at aka.ms/JsActiveCdn");
                            _cdnSentMessage = true;
                        }
                        if (!_sdkVerSentMessage && parseInt(_snippetVersion) < 6 && isFeatureEnabled(SDK_LOADER_VER, _config)) {
                            result = _throttleMgr[_DYN_SEND_MESSAGE /* @min:%2esendMessage */](111 /* _eInternalMessageId.SdkLdrUpdate */, "An updated Sdk Loader is available, see aka.ms/SnippetVer");
                            _sdkVerSentMessage = true;
                        }
                    }));
                });
                return _self;
            };
            _self[_DYN_UPDATE_SNIPPET_DEFIN3 /* @min:%2eupdateSnippetDefinitions */] = function (snippet) {
                // apply full appInsights to the global instance
                // Note: This must be called before loadAppInsights is called
                proxyAssign(snippet, _self, function (name) {
                    // Not excluding names prefixed with "_" as we need to proxy some functions like _onError
                    return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;
                });
            };
            _self.emptyQueue = function () {
                // call functions that were queued before the main script was loaded
                try {
                    if (isArray(_self.snippet[_DYN_QUEUE /* @min:%2equeue */])) {
                        // note: do not check length in the for-loop conditional in case something goes wrong and the stub methods are not overridden.
                        var length_1 = _self.snippet[_DYN_QUEUE /* @min:%2equeue */].length;
                        for (var i = 0; i < length_1; i++) {
                            var call = _self.snippet[_DYN_QUEUE /* @min:%2equeue */][i];
                            call();
                        }
                        _self.snippet[_DYN_QUEUE /* @min:%2equeue */] = undefined;
                        delete _self.snippet[_DYN_QUEUE /* @min:%2equeue */];
                    }
                }
                catch (exception) {
                    var properties_1 = {};
                    if (exception && isFunction(exception.toString)) {
                        properties_1.exception = exception.toString();
                    }
                    // need from core
                    // Microsoft.ApplicationInsights._InternalLogging.throwInternal(
                    //     eLoggingSeverity.WARNING,
                    //     _eInternalMessageId.FailedToSendQueuedTelemetry,
                    //     "Failed to send queued telemetry",
                    //     properties);
                }
            };
            _self[_DYN_ADD_HOUSEKEEPING_BEF2 /* @min:%2eaddHousekeepingBeforeUnload */] = function (appInsightsInstance) {
                // Add callback to push events when the user navigates away
                if (hasWindow() || hasDocument()) {
                    var performHousekeeping_1 = function () {
                        // Adds the ability to flush all data before the page unloads.
                        // Note: This approach tries to push a sync request with all the pending events onbeforeunload.
                        // Firefox does not respect this.Other browsers DO push out the call with < 100% hit rate.
                        // Telemetry here will help us analyze how effective this approach is.
                        // Another approach would be to make this call sync with a acceptable timeout to reduce the
                        // impact on user experience.
                        // appInsightsInstance.context._sender.triggerSend();
                        appInsightsInstance[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](false);
                        // Back up the current session to local storage
                        // This lets us close expired sessions after the cookies themselves expire
                        if (isFunction(_self.core[STR_GET_PLUGIN /* @min:%2egetPlugin */])) {
                            var loadedPlugin = _this.core[STR_GET_PLUGIN /* @min:%2egetPlugin */](PropertiesPluginIdentifier);
                            if (loadedPlugin) {
                                var propertiesPlugin = loadedPlugin.plugin;
                                if (propertiesPlugin && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */] && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager) {
                                    propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager.backup();
                                }
                            }
                        }
                    };
                    var added_1 = false;
                    if (!_houseKeepingNamespace) {
                        _houseKeepingNamespace = mergeEvtNamespace(_evtNamespace, _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */] && _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */]());
                    }
                    // Will be recalled if any referenced config properties change
                    _addUnloadHook(onConfigChange(_config, function (details) {
                        var coreConfig = details.cfg;
                        var analyticsPlugin = appInsightsInstance.appInsights;
                        var ctx = createProcessTelemetryContext(null, coreConfig, analyticsPlugin.core);
                        var extConfig = ctx.getExtCfg(analyticsPlugin.identifier || AnalyticsPluginIdentifier);
                        // As we could get recalled, remove any previously registered event handlers first
                        _removePageEventHandlers();
                        var excludePageUnloadEvents = coreConfig.disablePageUnloadEvents;
                        if (!extConfig.disableFlushOnBeforeUnload) {
                            // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server
                            // As just hooking the window does not always fire (on chrome) for page navigation's.
                            if (addPageUnloadEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace)) {
                                added_1 = true;
                            }
                            // We also need to hook the pagehide and visibilitychange events as not all versions of Safari support load/unload events.
                            if (addPageHideEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace)) {
                                added_1 = true;
                            }
                            // A reactNative app may not have a window and therefore the beforeunload/pagehide events -- so don't
                            // log the failure in this case
                            if (!added_1 && !isReactNative()) {
                                _throwInternal(_core.logger, 1 /* eLoggingSeverity.CRITICAL */, 19 /* _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload */, "Could not add handler for beforeunload and pagehide");
                            }
                        }
                        if (!added_1 && !extConfig.disableFlushOnUnload) {
                            // If we didn't add the normal set then attempt to add the pagehide and visibilitychange only
                            addPageHideEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace);
                        }
                    }));
                }
            };
            _self.getSender = function () {
                return _sender;
            };
            _self.unload = function (isAsync, unloadComplete, cbTimeout) {
                var unloadDone = false;
                var result;
                if (isAsync && !unloadComplete) {
                    result = createPromise(function (resolve) {
                        // Set the callback to the promise resolve callback
                        unloadComplete = resolve;
                    });
                }
                function _unloadCallback(unloadState) {
                    if (!unloadDone) {
                        unloadDone = true;
                        _initDefaults();
                        unloadComplete && unloadComplete(unloadState);
                    }
                }
                _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](isAsync);
                _removePageEventHandlers();
                _core.unload && _core.unload(isAsync, _unloadCallback, cbTimeout);
                return result;
            };
            proxyFunctions(_self, _analyticsPlugin, [
                STR_GET_COOKIE_MGR,
                STR_TRACK_EVENT,
                STR_TRACK_PAGE_VIEW,
                "trackPageViewPerformance",
                STR_TRACK_EXCEPTION,
                "_onerror",
                STR_TRACK_TRACE,
                STR_TRACK_METRIC,
                STR_START_TRACK_PAGE,
                STR_STOP_TRACK_PAGE,
                STR_START_TRACK_EVENT,
                STR_STOP_TRACK_EVENT
            ]);
            proxyFunctions(_self, _getCurrentDependencies, [
                STR_TRACK_DEPENDENCY_DATA,
                "addDependencyListener",
                "addDependencyInitializer"
            ]);
            proxyFunctions(_self, _core, [
                STR_ADD_TELEMETRY_INITIALIZER,
                STR_POLL_INTERNAL_LOGS,
                "stopPollingInternalLogs",
                STR_GET_PLUGIN,
                "addPlugin",
                STR_EVT_NAMESPACE,
                "addUnloadCb",
                "getTraceCtx",
                "updateCfg",
                "onCfgChange"
            ]);
            proxyFunctions(_self, function () {
                var context = properties[_DYN_CONTEXT /* @min:%2econtext */];
                return context ? context.user : null;
            }, [
                STR_SET_AUTHENTICATED_USER_CONTEXT,
                STR_CLEAR_AUTHENTICATED_USER_CONTEXT
            ]);
            // Using a function to support the dynamic adding / removal of plugins, so this will always return the current value
            function _getCurrentDependencies() {
                return dependencies;
            }
            function _initDefaults() {
                _evtNamespace = createUniqueNamespace("AISKU");
                _houseKeepingNamespace = null;
                dependencies = null;
                properties = null;
                _sender = null;
                _snippetVersion = null;
                _throttleMgr = null;
                _iKeySentMessage = false;
                _cdnSentMessage = false;
                _sdkVerSentMessage = false;
                _cfgSyncPlugin = new CfgSyncPlugin();
            }
            function _removePageEventHandlers() {
                // Remove any registered event handlers
                if (_houseKeepingNamespace) {
                    removePageUnloadEventListener(null, _houseKeepingNamespace);
                    removePageHideEventListener(null, _houseKeepingNamespace);
                }
            }
            function _addUnloadHook(hooks) {
                _core.addUnloadHook(hooks);
            }
        });
    }
    // Analytics Plugin
// Removed Stub for AppInsightsSku.prototype.getCookieMgr.
// Removed Stub for AppInsightsSku.prototype.trackEvent.
// Removed Stub for AppInsightsSku.prototype.trackPageView.
// Removed Stub for AppInsightsSku.prototype.trackPageViewPerformance.
// Removed Stub for AppInsightsSku.prototype.trackException.
// Removed Stub for AppInsightsSku.prototype._onerror.
// Removed Stub for AppInsightsSku.prototype.trackTrace.
// Removed Stub for AppInsightsSku.prototype.trackMetric.
// Removed Stub for AppInsightsSku.prototype.startTrackPage.
// Removed Stub for AppInsightsSku.prototype.stopTrackPage.
// Removed Stub for AppInsightsSku.prototype.startTrackEvent.
// Removed Stub for AppInsightsSku.prototype.stopTrackEvent.
// Removed Stub for AppInsightsSku.prototype.addTelemetryInitializer.
    // Properties Plugin
// Removed Stub for AppInsightsSku.prototype.setAuthenticatedUserContext.
// Removed Stub for AppInsightsSku.prototype.clearAuthenticatedUserContext.
    // Dependencies Plugin
// Removed Stub for AppInsightsSku.prototype.trackDependencyData.
    // Misc
// Removed Stub for AppInsightsSku.prototype.flush.
// Removed Stub for AppInsightsSku.prototype.onunloadFlush.
// Removed Stub for AppInsightsSku.prototype.loadAppInsights.
// Removed Stub for AppInsightsSku.prototype.updateSnippetDefinitions.
// Removed Stub for AppInsightsSku.prototype.emptyQueue.
// Removed Stub for AppInsightsSku.prototype.pollInternalLogs.
// Removed Stub for AppInsightsSku.prototype.stopPollingInternalLogs.
// Removed Stub for AppInsightsSku.prototype.addHousekeepingBeforeUnload.
// Removed Stub for AppInsightsSku.prototype.getSender.
// Removed Stub for AppInsightsSku.prototype.unload.
// Removed Stub for AppInsightsSku.prototype.getPlugin.
// Removed Stub for AppInsightsSku.prototype.addPlugin.
// Removed Stub for AppInsightsSku.prototype.updateCfg.
// Removed Stub for AppInsightsSku.prototype.evtNamespace.
// Removed Stub for AppInsightsSku.prototype.addUnloadCb.
// Removed Stub for AppInsightsSku.prototype.addDependencyListener.
    /**
     * Add an dependency telemetry initializer callback function to allow populating additional properties or drop the request.
     * It is called after the dependency call has completed and any available performance details are available. A dependency
     * initializer is similar to the TelemetryInitializer function but it allows you to block the reporting of the dependency
     * request so that it doesn't count against the `maxAjaxCallsPerView`.
     * @param dependencyInitializer - The Dependency Telemetry Initializer function
     * @returns - A IDependencyInitializerHandler to enable the initializer to be removed
     */
    AppInsightsSku.prototype.addDependencyInitializer = function (dependencyInitializer) {
        return null;
    };
// Removed Stub for AppInsightsSku.prototype.getTraceCtx.
// Removed Stub for AppInsightsSku.prototype.onCfgChange.
    return AppInsightsSku;
}());
export { AppInsightsSku };
// tslint:disable-next-line
export function _findSdkSourceFile() {
    if (_internalSdkSrc) {
        // Use the cached value
        return _internalSdkSrc;
    }
    var sdkSrc = null;
    var isModule = false;
    var cdns = [
        "://js.monitor.azure.com/",
        "://az416426.vo.msecnd.net/"
    ];
    try {
        // Try and determine whether the sdk is being loaded from the CDN
        // currentScript is only valid during initial processing
        var scrpt = (document || {}).currentScript;
        if (scrpt) {
            sdkSrc = scrpt.src;
            // } else {
            //     // We need to update to at least typescript 2.9 for this to work :-(
            //     // Leaving as a stub for now so after we upgrade this breadcrumb is available
            //     let meta = import.meta;
            //     sdkSrc = (meta || {}).url;
            //     isModule = true;
        }
    }
    catch (e) {
        // eslint-disable-next-line no-empty
    }
    if (sdkSrc) {
        try {
            var url_1 = sdkSrc.toLowerCase();
            if (url_1) {
                var src_1 = "";
                arrForEach(cdns, function (value, idx) {
                    if (strIndexOf(url_1, value) !== -1) {
                        src_1 = "cdn" + (idx + 1);
                        if (strIndexOf(url_1, "/scripts/") === -1) {
                            if (strIndexOf(url_1, "/next/") !== -1) {
                                src_1 += "-next";
                            }
                            else if (strIndexOf(url_1, "/beta/") !== -1) {
                                src_1 += "-beta";
                            }
                        }
                        _internalSdkSrc = src_1 + (isModule ? ".mod" : "");
                        return -1;
                    }
                });
            }
        }
        catch (e) {
            // eslint-disable-next-line no-empty
        }
        // Cache the found value so we don't have to look it up again
        _internalSdkSrc = sdkSrc;
    }
    return _internalSdkSrc;
}
//# sourceMappingURL=AISku.js.map