/* * Microsoft Application Insights Common JavaScript Library, 3.3.11 * Copyright (c) Microsoft and contributors. All rights reserved. * * Microsoft Application Insights Team * https://github.com/microsoft/ApplicationInsights-JS#readme */ declare namespace ApplicationInsights { /** * Data struct to contain only C section with custom fields. */ interface AIBase { /** * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */ baseType: string; } /** * Data struct to contain both B and C sections. */ interface AIData extends AIBase { /** * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */ baseType: string; /** * Container for data item (B section). */ baseData: TDomain; } const AnalyticsPluginIdentifier = "ApplicationInsightsAnalytics"; const BreezeChannelIdentifier = "AppInsightsChannelPlugin"; class ConfigurationManager { static getConfig(config: IConfiguration & IConfig, field: string, identifier?: string, defaultValue?: number | string | boolean): number | string | boolean; } type ConnectionString = { [key in ConnectionStringKey]?: string; }; type ConnectionStringKey = "authorization" | "instrumentationkey" | "ingestionendpoint" | "location" | "endpointsuffix"; const ConnectionStringParser: { parse: typeof parseConnectionString; }; class ContextTagKeys extends ContextTagKeys_base { constructor(); } const ContextTagKeys_base: new () => IContextTagKeys; /** * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. * Headers are always included if the current domain matches the request domain. If they do not match (CORS), * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must * manually supply domains to include correlation headers on. Else, no headers will be included at all. */ function correlationIdCanIncludeCorrelationHeader(config: ICorrelationConfig, requestUrl: string, currentHost?: string): boolean; /** * Combines target appId and target role name from response header. */ function correlationIdGetCorrelationContext(responseHeader: string): string; /** * Gets key from correlation response header */ function correlationIdGetCorrelationContextValue(responseHeader: string, key: string): string; function correlationIdGetPrefix(): string; function correlationIdSetPrefix(prefix: string): void; /** * Creates a IDistributedTraceContext from an optional telemetryTrace * @param telemetryTrace - The telemetryTrace instance that is being wrapped * @param parentCtx - An optional parent distributed trace instance, almost always undefined as this scenario is only used in the case of multiple property handlers. * @returns A new IDistributedTraceContext instance that is backed by the telemetryTrace or temporary object */ function createDistributedTraceContextFromTrace(telemetryTrace?: ITelemetryTrace, parentCtx?: IDistributedTraceContext): IDistributedTraceContext; function createDomEvent(eventName: string): Event; /** * Create a new OfflineListener instance to monitor browser online / offline events * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance */ function createOfflineListener(parentEvtNamespace?: string | string[]): IOfflineListener; /** * Create a telemetry item that the 1DS channel understands * @param item - domain specific properties; part B * @param baseType - telemetry item type. ie PageViewData * @param envelopeName - Name of the envelope, e.g., `Microsoft.ApplicationInsights.\.PageView`. * @param customProperties - user defined custom properties; part C * @param systemProperties - system properties that are added to the context; part A * @returns ITelemetryItem that is sent to channel */ function createTelemetryItem(item: T, baseType: string, envelopeName: string, logger: IDiagnosticLogger, customProperties?: { [key: string]: any; }, systemProperties?: { [key: string]: any; }): ITelemetryItem; /** * Create a new ITraceParent instance using the provided values. * @param traceId - The traceId to use, when invalid a new random W3C id will be generated. * @param spanId - The parent/span id to use, a new random value will be generated if it is invalid. * @param flags - The traceFlags to use, defaults to zero (0) if not supplied or invalid * @param version - The version to used, defaults to version "01" if not supplied or invalid. * @returns */ function createTraceParent(traceId?: string, spanId?: string, flags?: number, version?: string): ITraceParent; let CtxTagKeys: ContextTagKeys; class Data implements AIData, ISerializable { /** * The data contract for serializing this object. */ aiDataContract: { baseType: FieldType; baseData: FieldType; }; /** * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */ baseType: string; /** * Container for data item (B section). */ baseData: TDomain; /** * Constructs a new instance of telemetry data. */ constructor(baseType: string, data: TDomain); } class DataPoint implements IDataPoint, ISerializable { /** * The data contract for serializing this object. */ aiDataContract: { name: FieldType; kind: FieldType; value: FieldType; count: FieldType; min: FieldType; max: FieldType; stdDev: FieldType; }; /** * Name of the metric. */ name: string; /** * Metric type. Single measurement or the aggregated value. */ kind: DataPointType; /** * Single value for measurement. Sum of individual measurements for the aggregation. */ value: number; /** * Metric weight of the aggregated metric. Should not be set for a measurement. */ count: number; /** * Minimum value of the aggregated metric. Should not be set for a measurement. */ min: number; /** * Maximum value of the aggregated metric. Should not be set for a measurement. */ max: number; /** * Standard deviation of the aggregated metric. Should not be set for a measurement. */ stdDev: number; } /** * Type of the metric data measurement. */ const enum DataPointType { Measurement = 0, Aggregation = 1 } function dataSanitizeException(logger: IDiagnosticLogger, exception: any): any; function dataSanitizeId(logger: IDiagnosticLogger, id: string): string; function dataSanitizeInput(logger: IDiagnosticLogger, input: any, maxLength: number, _msgId: _eInternalMessageId): any; function dataSanitizeKey(logger: IDiagnosticLogger, name: any): any; function dataSanitizeKeyAndAddUniqueness(logger: IDiagnosticLogger, key: any, map: any): any; function dataSanitizeMeasurements(logger: IDiagnosticLogger, measurements: any): any; function dataSanitizeMessage(logger: IDiagnosticLogger, message: any): any; function dataSanitizeProperties(logger: IDiagnosticLogger, properties: any): any; const enum DataSanitizerValues { /** * Max length allowed for custom names. */ MAX_NAME_LENGTH = 150, /** * Max length allowed for Id field in page views. */ MAX_ID_LENGTH = 128, /** * Max length allowed for custom values. */ MAX_PROPERTY_LENGTH = 8192, /** * Max length allowed for names */ MAX_STRING_LENGTH = 1024, /** * Max length allowed for url. */ MAX_URL_LENGTH = 2048, /** * Max length allowed for messages. */ MAX_MESSAGE_LENGTH = 32768, /** * Max length allowed for exceptions. */ MAX_EXCEPTION_LENGTH = 32768 } function dataSanitizeString(logger: IDiagnosticLogger, value: any, maxLength?: number): any; function dataSanitizeUrl(logger: IDiagnosticLogger, url: any, config?: IConfiguration): any; function dateTimeUtilsDuration(start: number, end: number): number; function dateTimeUtilsNow(): number; const DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com"; const DEFAULT_BREEZE_PATH = "/v2/track"; /** * This is an internal property used to cause internal (reporting) requests to be ignored from reporting * additional telemetry, to handle polyfil implementations ALL urls used with a disabled request will * also be ignored for future requests even when this property is not provided. * Tagging as Ignore as this is an internal value and is not expected to be used outside of the SDK * @ignore */ const DisabledPropertyName: string; const DistributedTracingModes: EnumValue; type DistributedTracingModes = number | eDistributedTracingModes; function dsPadNumber(num: number): string; const enum eActiveStatus { NONE = 0, /** * inactive status means there might be rejected ikey/endpoint promises or ikey/endpoint resolved is not valid */ INACTIVE = 1, /** * active mean ikey/endpoint promises is resolved and initializing with ikey/endpoint is successful */ ACTIVE = 2, /** * Waiting for promises to be resolved * NOTE: if status is set to be pending, incoming changes will be dropped until pending status is removed */ PENDING = 3 } const enum eDistributedTracingModes { /** * (Default) Send Application Insights correlation headers */ AI = 0, /** * Send both W3C Trace Context headers and back-compatibility Application Insights headers */ AI_AND_W3C = 1, /** * Send W3C Trace Context headers */ W3C = 2 } const enum _eInternalMessageId { BrowserDoesNotSupportLocalStorage = 0, BrowserCannotReadLocalStorage = 1, BrowserCannotReadSessionStorage = 2, BrowserCannotWriteLocalStorage = 3, BrowserCannotWriteSessionStorage = 4, BrowserFailedRemovalFromLocalStorage = 5, BrowserFailedRemovalFromSessionStorage = 6, CannotSendEmptyTelemetry = 7, ClientPerformanceMathError = 8, ErrorParsingAISessionCookie = 9, ErrorPVCalc = 10, ExceptionWhileLoggingError = 11, FailedAddingTelemetryToBuffer = 12, FailedMonitorAjaxAbort = 13, FailedMonitorAjaxDur = 14, FailedMonitorAjaxOpen = 15, FailedMonitorAjaxRSC = 16, FailedMonitorAjaxSend = 17, FailedMonitorAjaxGetCorrelationHeader = 18, FailedToAddHandlerForOnBeforeUnload = 19, FailedToSendQueuedTelemetry = 20, FailedToReportDataLoss = 21, FlushFailed = 22, MessageLimitPerPVExceeded = 23, MissingRequiredFieldSpecification = 24, NavigationTimingNotSupported = 25, OnError = 26, SessionRenewalDateIsZero = 27, SenderNotInitialized = 28, StartTrackEventFailed = 29, StopTrackEventFailed = 30, StartTrackFailed = 31, StopTrackFailed = 32, TelemetrySampledAndNotSent = 33, TrackEventFailed = 34, TrackExceptionFailed = 35, TrackMetricFailed = 36, TrackPVFailed = 37, TrackPVFailedCalc = 38, TrackTraceFailed = 39, TransmissionFailed = 40, FailedToSetStorageBuffer = 41, FailedToRestoreStorageBuffer = 42, InvalidBackendResponse = 43, FailedToFixDepricatedValues = 44, InvalidDurationValue = 45, TelemetryEnvelopeInvalid = 46, CreateEnvelopeError = 47, MaxUnloadHookExceeded = 48, CannotSerializeObject = 48, CannotSerializeObjectNonSerializable = 49, CircularReferenceDetected = 50, ClearAuthContextFailed = 51, ExceptionTruncated = 52, IllegalCharsInName = 53, ItemNotInArray = 54, MaxAjaxPerPVExceeded = 55, MessageTruncated = 56, NameTooLong = 57, SampleRateOutOfRange = 58, SetAuthContextFailed = 59, SetAuthContextFailedAccountName = 60, StringValueTooLong = 61, StartCalledMoreThanOnce = 62, StopCalledWithoutStart = 63, TelemetryInitializerFailed = 64, TrackArgumentsNotSpecified = 65, UrlTooLong = 66, SessionStorageBufferFull = 67, CannotAccessCookie = 68, IdTooLong = 69, InvalidEvent = 70, FailedMonitorAjaxSetRequestHeader = 71, SendBrowserInfoOnUserInit = 72, PluginException = 73, NotificationException = 74, SnippetScriptLoadFailure = 99, InvalidInstrumentationKey = 100, CannotParseAiBlobValue = 101, InvalidContentBlob = 102, TrackPageActionEventFailed = 103, FailedAddingCustomDefinedRequestContext = 104, InMemoryStorageBufferFull = 105, InstrumentationKeyDeprecation = 106, ConfigWatcherException = 107, DynamicConfigException = 108, DefaultThrottleMsgKey = 109, CdnDeprecation = 110, SdkLdrUpdate = 111, InitPromiseException = 112, StatsBeatManagerException = 113, StatsBeatException = 114 } const enum eLoggingSeverity { /** * No Logging will be enabled */ DISABLED = 0, /** * Error will be sent as internal telemetry */ CRITICAL = 1, /** * Error will NOT be sent as internal telemetry, and will only be shown in browser console */ WARNING = 2, /** * The Error will NOT be sent as an internal telemetry, and will only be shown in the browser * console if the logging level allows it. */ DEBUG = 3 } /** * A type that identifies an enum class generated from a constant enum. * @group Enum * @typeParam E - The constant enum type * * Returned from {@link createEnum} */ type EnumCls = { readonly [key in keyof E extends string | number | symbol ? keyof E : never]: key extends string ? E[key] : key; } & { readonly [key in keyof E]: E[key]; }; type EnumValue = EnumCls; class Envelope implements IEnvelope { /** * The data contract for serializing this object. */ aiDataContract: any; /** * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. */ ver: number; /** * Type name of telemetry data item. */ name: string; /** * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. */ time: string; /** * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. */ sampleRate: number; /** * Sequence field used to track absolute order of uploaded events. */ seq: string; /** * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive. */ iKey: string; /** * Key/value collection of context properties. See ContextTagKeys for information on available properties. */ tags: any; /** * Telemetry data item. */ data: AIBase; /** * Constructs a new instance of telemetry data. */ constructor(logger: IDiagnosticLogger, data: AIBase, name: string); } /** * This is the enum for the different network states current ai is experiencing */ const enum eOfflineValue { Unknown = 0, Online = 1, Offline = 2 } const enum eRequestHeaders { requestContextHeader = 0, requestContextTargetKey = 1, requestContextAppIdFormat = 2, requestIdHeader = 3, traceParentHeader = 4, traceStateHeader = 5, sdkContextHeader = 6, sdkContextHeaderAppIdRequest = 7, requestContextHeaderLowerCase = 8 } /** * Defines the level of severity for the event. */ const enum eSeverityLevel { Verbose = 0, Information = 1, Warning = 2, Error = 3, Critical = 4 } class Event_2 implements IEventData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { ver: FieldType; name: FieldType; properties: FieldType; measurements: FieldType; }; /** * Schema version */ ver: number; /** * Event name. Keep it low cardinality to allow proper grouping and useful metrics. */ name: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Constructs a new instance of the EventTelemetry object */ constructor(logger: IDiagnosticLogger, name: string, properties?: any, measurements?: any); } const Event: typeof Event_2; /** * The EventPersistence contains a set of values that specify the event's persistence. */ const EventPersistence: EnumValue; type EventPersistence = number | EventPersistenceValue; /** * The EventPersistence contains a set of values that specify the event's persistence. */ const enum EventPersistenceValue { /** * Normal persistence. */ Normal = 1, /** * Critical persistence. */ Critical = 2 } class Exception implements IExceptionData, ISerializable { static envelopeType: string; static dataType: string; id?: string; problemGroup?: string; isManual?: boolean; aiDataContract: { ver: FieldType; exceptions: FieldType; severityLevel: FieldType; properties: FieldType; measurements: FieldType; }; /** * Schema version */ ver: number; /** * Exception chain - list of inner exceptions. */ exceptions: IExceptionDetails[]; /** * Severity level. Mostly used to indicate exception severity level when it is reported by logging library. */ severityLevel: SeverityLevel; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Constructs a new instance of the ExceptionTelemetry object */ constructor(logger: IDiagnosticLogger, exception: Error | IExceptionInternal | IAutoExceptionTelemetry, properties?: { [key: string]: any; }, measurements?: { [key: string]: number; }, severityLevel?: SeverityLevel, id?: string); static CreateAutoException(message: string | Event, url: string, lineNumber: number, columnNumber: number, error: any, evt?: Event | string, stack?: string, errorSrc?: string): IAutoExceptionTelemetry; static CreateFromInterface(logger: IDiagnosticLogger, exception: IExceptionInternal, properties?: any, measurements?: { [key: string]: number; }): Exception; toInterface(): IExceptionInternal; /** * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. */ static CreateSimpleException(message: string, typeName: string, assembly: string, fileName: string, details: string, line: number): Exception; static formatError: typeof _formatErrorCode; } const Extensions: { UserExt: string; DeviceExt: string; TraceExt: string; WebExt: string; AppExt: string; OSExt: string; SessionExt: string; SDKExt: string; }; const enum FeatureOptInMode { /** * not set, completely depends on cdn cfg */ none = 1, /** * try to not apply config from cdn */ disable = 2, /** * try to apply config from cdn */ enable = 3 } /** * Enum is used in aiDataContract to describe how fields are serialized. * For instance: (Fieldtype.Required | FieldType.Array) will mark the field as required and indicate it's an array */ const enum FieldType { Default = 0, Required = 1, Array = 2, Hidden = 4 } /** * This defines the handler function that is called via the finally when the promise is resolved or rejected */ type FinallyPromiseHandler = (() => void) | undefined | null; /** * Find all script tags in the provided document and return the information about them. * @param doc - The document to search for script tags * @returns */ function findAllScripts(doc: any): scriptsInfo[]; /** * Helper function to fetch the passed traceparent from the page, looking for it as a meta-tag or a Server-Timing header. * @param selectIdx - If the found value is comma separated which is the preferred entry to select, defaults to the first * @returns */ function findW3cTraceParent(selectIdx?: number): ITraceParent; /** * Formats the provided errorObj for display and reporting, it may be a String, Object, integer or undefined depending on the browser. * @param errorObj - The supplied errorObj */ function _formatErrorCode(errorObj: any): any; /** * Format the ITraceParent value as a string using the supported and know version formats. * So even if the passed traceParent is a later version the string value returned from this * function will convert it to only the known version formats. * This currently only supports version "00" and invalid "ff" * @param value - The parsed traceParent value * @returns */ function formatTraceParent(value: ITraceParent): string; function getExtensionByName(extensions: IPlugin[], identifier: string): IPlugin | null; const HttpMethod = "http.method"; interface IAppInsights { /** * Get the current cookie manager for this instance */ getCookieMgr(): ICookieMgr; trackEvent(event: IEventTelemetry, customProperties?: { [key: string]: any; }): void; trackPageView(pageView: IPageViewTelemetry, customProperties?: { [key: string]: any; }): void; trackException(exception: IExceptionTelemetry, customProperties?: { [key: string]: any; }): void; _onerror(exception: IAutoExceptionTelemetry): void; trackTrace(trace: ITraceTelemetry, customProperties?: { [key: string]: any; }): void; trackMetric(metric: IMetricTelemetry, customProperties?: { [key: string]: any; }): void; startTrackPage(name?: string): void; stopTrackPage(name?: string, url?: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }): void; startTrackEvent(name: string): void; stopTrackEvent(name: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }): void; addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void): void; trackPageViewPerformance(pageViewPerformance: IPageViewPerformanceTelemetry, customProperties?: { [key: string]: any; }): void; } interface IAppInsightsCore extends IPerfManagerProvider { readonly config: CfgType; /** * The current logger instance for this instance. */ readonly logger: IDiagnosticLogger; /** * An array of the installed plugins that provide a version */ readonly pluginVersionStringArr: string[]; /** * The formatted string of the installed plugins that contain a version number */ readonly pluginVersionString: string; /** * Returns a value that indicates whether the instance has already been previously initialized. */ isInitialized?: () => boolean; initialize(config: CfgType, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void; getChannels(): IChannelControls[]; track(telemetryItem: ITelemetryItem): void; /** * Get the current notification manager */ getNotifyMgr(): INotificationManager; /** * Get the current cookie manager for this instance */ getCookieMgr(): ICookieMgr; /** * Set the current cookie manager for this instance * @param cookieMgr - The manager, if set to null/undefined will cause the default to be created */ setCookieMgr(cookieMgr: ICookieMgr): void; /** * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised. * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be * called. * @param listener - An INotificationListener object. */ addNotificationListener?(listener: INotificationListener): void; /** * Removes all instances of the listener. * @param listener - INotificationListener to remove. */ removeNotificationListener?(listener: INotificationListener): void; /** * Add a telemetry processor to decorate or drop telemetry events. * @param telemetryInitializer - The Telemetry Initializer function * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed */ addTelemetryInitializer(telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler; pollInternalLogs?(eventName?: string): ITimerHandler; stopPollingInternalLogs?(): void; /** * Return a new instance of the IProcessTelemetryContext for processing events */ getProcessTelContext(): IProcessTelemetryContext; /** * Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered * to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous * unload call return `true` stating that all plugins reported that they also unloaded, the recommended * approach is to create a new instance and initialize that instance. * This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable * to successfully remove any global references or they may just be completing the unload process asynchronously. * 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) * will be returned which will resolve once the unload is complete. The actual implementation of the `IPromise` * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async) * @param isAsync - Can the unload be performed asynchronously (default) * @param unloadComplete - An optional callback that will be called once the unload has completed * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the * unload. Defaults to 5 seconds. * @returns Nothing or if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * which will be resolved once the unload is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * will only be returned when no callback is provided and isAsync is true */ unload(isAsync?: boolean, unloadComplete?: (unloadState: ITelemetryUnloadState) => void, cbTimeout?: number): void | IPromise; /** * Find and return the (first) plugin with the specified identifier if present */ getPlugin(pluginIdentifier: string): ILoadedPlugin; /** * Add a new plugin to the installation * @param plugin - The new plugin to add * @param replaceExisting - should any existing plugin be replaced, default is false * @param doAsync - Should the add be performed asynchronously * @param addCb - [Optional] callback to call after the plugin has been added */ addPlugin(plugin: T, replaceExisting?: boolean, doAsync?: boolean, addCb?: (added?: boolean) => void): void; /** * Update the configuration used and broadcast the changes to all loaded plugins, this does NOT support updating, adding or removing * any the plugins (extensions or channels). It will notify each plugin (if supported) that the configuration has changed but it will * not remove or add any new plugins, you need to call addPlugin or getPlugin(identifier).remove(); * @param newConfig - The new configuration is apply * @param mergeExisting - Should the new configuration merge with the existing or just replace it. Default is to merge. */ updateCfg(newConfig: CfgType, mergeExisting?: boolean): void; /** * Returns the unique event namespace that should be used when registering events */ evtNamespace(): string; /** * Add a handler that will be called when the SDK is being unloaded * @param handler - the handler */ addUnloadCb(handler: UnloadHandler): void; /** * Add this hook so that it is automatically removed during unloading * @param hooks - The single hook or an array of IInstrumentHook objects */ addUnloadHook(hooks: IUnloadHook | IUnloadHook[] | Iterator | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator): void; /** * Flush and send any batched / cached data immediately * @param async - send data asynchronously when true (defaults to true) * @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. * If the caller doesn't return true the caller should assume that it may never be called. * @param sendReason - specify the reason that you are calling "flush" defaults to ManualFlush (1) if not specified * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the unload. Defaults to 5 seconds. * @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 */ flush(isAsync?: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason, cbTimeout?: number): boolean | void; /** * Gets the current distributed trace context for this instance if available * @param createNew - Optional flag to create a new instance if one doesn't currently exist, defaults to true */ getTraceCtx(createNew?: boolean): IDistributedTraceContext | null; /** * Sets the current distributed trace context for this instance if available */ setTraceCtx(newTraceCtx: IDistributedTraceContext | null | undefined): void; /** * Watches and tracks changes for accesses to the current config, and if the accessed config changes the * handler will be recalled. * @returns A watcher handler instance that can be used to remove itself when being unloaded */ onCfgChange(handler: WatcherFunction): IUnloadHook; /** * Function used to identify the get w parameter used to identify status bit to some channels */ getWParam: () => number; /** * Watches and tracks status of initialization process * @returns ActiveStatus * @since 3.3.0 * If returned status is active, it means initialization process is completed. * If returned status is pending, it means the initialization process is waiting for promieses to be resolved. * If returned status is inactive, it means ikey is invalid or can 't get ikey or enpoint url from promsises. */ activeStatus?: () => eActiveStatus | number; /** * Set Active Status to pending, which will block the incoming changes until internal promises are resolved * @internal Internal use * @since 3.3.0 */ _setPendingStatus?: () => void; } interface IApplication { /** * The application version. */ ver: string; /** * The application build version. */ build: string; } /** * @description window.onerror function parameters * @export * @interface IAutoExceptionTelemetry */ interface IAutoExceptionTelemetry { /** * @description error message. Available as event in HTML onerror="" handler */ message: string; /** * @description URL of the script where the error was raised */ url: string; /** * @description Line number where error was raised */ lineNumber: number; /** * @description Column number for the line where the error occurred */ columnNumber: number; /** * @description Error Object (object) */ error: any; /** * @description The event at the time of the exception (object) */ evt?: Event | string; /** * @description The provided stack for the error */ stackDetails?: IStackDetails; /** * @description The calculated type of the error */ typeName?: string; /** * @description The descriptive source of the error */ errorSrc?: string; } interface IBaseProcessingContext { /** * The current core instance for the request */ core: () => IAppInsightsCore; /** * THe current diagnostic logger for the request */ diagLog: () => IDiagnosticLogger; /** * Gets the current core config instance */ getCfg: () => IConfiguration; /** * Gets the named extension config */ getExtCfg: (identifier: string, defaultValue?: IConfigDefaults) => T; /** * Gets the named config from either the named identifier extension or core config if neither exist then the * default value is returned * @param identifier - The named extension identifier * @param field - The config field name * @param defaultValue - The default value to return if no defined config exists */ getConfig: (identifier: string, field: string, defaultValue?: number | string | boolean | string[] | RegExp[] | Function) => number | string | boolean | string[] | RegExp[] | Function; /** * Helper to allow plugins to check and possibly shortcut executing code only * required if there is a nextPlugin */ hasNext: () => boolean; /** * Returns the next configured plugin proxy */ getNext: () => ITelemetryPluginChain; /** * Helper to set the next plugin proxy */ setNext: (nextCtx: ITelemetryPluginChain) => void; /** * Synchronously iterate over the context chain running the callback for each plugin, once * every plugin has been executed via the callback, any associated onComplete will be called. * @param callback - The function call for each plugin in the context chain */ iterate: (callback: (plugin: T) => void) => void; /** * Set the function to call when the current chain has executed all processNext or unloadNext items. * @param onComplete - The onComplete to call * @param that - The "this" value to use for the onComplete call, if not provided or undefined defaults to the current context * @param args - Any additional arguments to pass to the onComplete function */ onComplete: (onComplete: () => void, that?: any, ...args: any[]) => void; /** * Create a new context using the core and config from the current instance, returns a new instance of the same type * @param plugins - The execution order to process the plugins, if null or not supplied * then the current execution order will be copied. * @param startAt - The plugin to start processing from, if missing from the execution * order then the next plugin will be NOT set. */ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IBaseProcessingContext; } /** * Provides data transmission capabilities */ interface IChannelControls extends ITelemetryPlugin { /** * Pause sending data */ pause?(): void; /** * Resume sending data */ resume?(): void; /** * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further * processTelemetry calls are ignored and it just calls the processNext() with the provided context. * @param unloadCtx - This is the context that should be used during unloading. * @param unloadState - The details / state of the unload process, it holds details like whether it should be unloaded synchronously or asynchronously and the reason for the unload. * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing. */ teardown?: (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => void | boolean; /** * Flush to send data immediately; channel should default to sending data asynchronously. If executing asynchronously and * you DO NOT pass a callback function then a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * will be returned which will resolve once the flush is complete. The actual implementation of the `IPromise` * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async) * @param isAsync - send data asynchronously when true * @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. * If the caller doesn't return true the caller should assume that it may never be called. * @param sendReason - specify the reason that you are calling "flush" defaults to ManualFlush (1) if not specified * @returns - If a callback is provided `true` to indicate that callback will be called after the flush is complete otherwise the caller * should assume that any provided callback will never be called, Nothing or if occurring asynchronously a * [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) which will be resolved once the unload is complete, * the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) will only be returned when no callback is provided * and isAsync is true. */ flush?(isAsync: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason): boolean | void | IPromise; /** * Get offline support * @returns IInternalOfflineSupport */ getOfflineSupport?: () => IInternalOfflineSupport; } /** * Configuration settings for how telemetry is sent * @export * @interface IConfig */ interface IConfig { /** * The JSON format (normal vs line delimited). True means line delimited JSON. */ emitLineDelimitedJson?: boolean; /** * An optional account id, if your app groups users into accounts. No spaces, commas, semicolons, equals, or vertical bars. */ accountId?: string; /** * A session is logged if the user is inactive for this amount of time in milliseconds. Default 30 mins. * @default 30*60*1000 */ sessionRenewalMs?: number; /** * A session is logged if it has continued for this amount of time in milliseconds. Default 24h. * @default 24*60*60*1000 */ sessionExpirationMs?: number; /** * Max size of telemetry batch. If batch exceeds limit, it is sent and a new batch is started * @default 100000 */ maxBatchSizeInBytes?: number; /** * How long to batch telemetry for before sending (milliseconds) * @default 15 seconds */ maxBatchInterval?: number; /** * If true, debugging data is thrown as an exception by the logger. Default false * @defaultValue false */ enableDebug?: boolean; /** * If true, exceptions are not autocollected. Default is false * @defaultValue false */ disableExceptionTracking?: boolean; /** * If true, telemetry is not collected or sent. Default is false * @defaultValue false */ disableTelemetry?: boolean; /** * Percentage of events that will be sent. Default is 100, meaning all events are sent. * @defaultValue 100 */ samplingPercentage?: number; /** * If true, on a pageview, the previous instrumented page's view time is tracked and sent as telemetry and a new timer is started for the current pageview. It is sent as a custom metric named PageVisitTime in milliseconds and is calculated via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less). Default is false. */ autoTrackPageVisitTime?: boolean; /** * Automatically track route changes in Single Page Applications (SPA). If true, each route change will send a new Pageview to Application Insights. */ enableAutoRouteTracking?: boolean; /** * If true, Ajax calls are not autocollected. Default is false * @defaultValue false */ disableAjaxTracking?: boolean; /** * If true, Fetch requests are not autocollected. Default is false (Since 2.8.0, previously true). * @defaultValue false */ disableFetchTracking?: boolean; /** * Provide a way to exclude specific route from automatic tracking for XMLHttpRequest or Fetch request. For an ajax / fetch request that the request url matches with the regex patterns, auto tracking is turned off. * @defaultValue undefined. */ excludeRequestFromAutoTrackingPatterns?: string[] | RegExp[]; /** * Provide a way to enrich dependencies logs with context at the beginning of api call. * Default is undefined. */ addRequestContext?: (requestContext?: IRequestContext) => ICustomProperties; /** * If true, default behavior of trackPageView is changed to record end of page view duration interval when trackPageView is called. If false and no custom duration is provided to trackPageView, the page view performance is calculated using the navigation timing API. Default is false * @defaultValue false */ overridePageViewDuration?: boolean; /** * Default 500 - controls how many ajax calls will be monitored per page view. Set to -1 to monitor all (unlimited) ajax calls on the page. */ maxAjaxCallsPerView?: number; /** * @ignore * If false, internal telemetry sender buffers will be checked at startup for items not yet sent. Default is true * @defaultValue true */ disableDataLossAnalysis?: boolean; /** * If false, the SDK will add two headers ('Request-Id' and 'Request-Context') to all dependency requests to correlate them with corresponding requests on the server side. Default is false. * @defaultValue false */ disableCorrelationHeaders?: boolean; /** * Sets the distributed tracing mode. If AI_AND_W3C mode or W3C mode is set, W3C trace context headers (traceparent/tracestate) will be generated and included in all outgoing requests. * AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services * @defaultValue AI_AND_W3C */ distributedTracingMode?: DistributedTracingModes; /** * Disable correlation headers for specific domain */ correlationHeaderExcludedDomains?: string[]; /** * Default false. If true, flush method will not be called when onBeforeUnload, onUnload, onPageHide or onVisibilityChange (hidden state) event(s) trigger. */ disableFlushOnBeforeUnload?: boolean; /** * Default value of `disableFlushOnBeforeUnload`. If true, flush method will not be called when onPageHide or onVisibilityChange (hidden state) event(s) trigger. */ disableFlushOnUnload?: boolean; /** * If true, the buffer with all unsent telemetry is stored in session storage. The buffer is restored on page load. Default is true. * @defaultValue true */ enableSessionStorageBuffer?: boolean; /** * If specified, overrides the storage & retrieval mechanism that is used to manage unsent telemetry. */ bufferOverride?: IStorageBuffer; /** * @deprecated Use either disableCookiesUsage or specify a cookieCfg with the enabled value set. * If true, the SDK will not store or read any data from cookies. Default is false. As this field is being deprecated, when both * isCookieUseDisabled and disableCookiesUsage are used disableCookiesUsage will take precedent. * @defaultValue false */ isCookieUseDisabled?: boolean; /** * If true, the SDK will not store or read any data from cookies. Default is false. * If you have also specified a cookieCfg then enabled property (if specified) will take precedent over this value. * @defaultValue false */ disableCookiesUsage?: boolean; /** * Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. * @defaultValue "" */ cookieDomain?: string; /** * Custom cookie path. This is helpful if you want to share Application Insights cookies behind an application gateway. * @defaultValue "" */ cookiePath?: string; /** * Default false. If false, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error), 503 (service unavailable), and 0 (offline, only if detected) * @description * @defaultValue false */ isRetryDisabled?: boolean; /** * @deprecated Used when initizialing from snippet only. * The url from where the JS SDK will be downloaded. */ url?: string; /** * If true, the SDK will not store or read any data from local and session storage. Default is false. * @defaultValue false */ isStorageUseDisabled?: boolean; /** * If false, the SDK will send all telemetry using the Beacon API. * @defaultValue true */ isBeaconApiDisabled?: boolean; /** * Don't use XMLHttpRequest or XDomainRequest (for IE \< 9) by default instead attempt to use fetch() or sendBeacon. * If no other transport is available it will still use XMLHttpRequest */ disableXhr?: boolean; /** * If fetch keepalive is supported do not use it for sending events during unload, it may still fallback to fetch() without keepalive */ onunloadDisableFetch?: boolean; /** * Sets the sdk extension name. Only alphabetic characters are allowed. The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (e.g. 'ext_javascript:2.0.0'). Default is null. * @defaultValue null */ sdkExtension?: string; /** * Default is false. If true, the SDK will track all [Browser Link](https://docs.microsoft.com/en-us/aspnet/core/client-side/using-browserlink) requests. * @defaultValue false */ isBrowserLinkTrackingEnabled?: boolean; /** * AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requets. When Beacon API is enabled, it cannot be used automatically, but can be set manually in the configuration. Default is null * @defaultValue null */ appId?: string; /** * If true, the SDK will add two headers ('Request-Id' and 'Request-Context') to all CORS requests to correlate outgoing AJAX dependencies with corresponding requests on the server side. Default is false * @defaultValue false */ enableCorsCorrelation?: boolean; /** * An optional value that will be used as name postfix for localStorage and session cookie name. * @defaultValue null */ namePrefix?: string; /** * An optional value that will be used as name postfix for session cookie name. If undefined, namePrefix is used as name postfix for session cookie name. * @defaultValue null */ sessionCookiePostfix?: string; /** * An optional value that will be used as name postfix for user cookie name. If undefined, no postfix is added on user cookie name. * @defaultValue null */ userCookiePostfix?: string; /** * An optional value that will track Request Header through trackDependency function. * @defaultValue false */ enableRequestHeaderTracking?: boolean; /** * An optional value that will track Response Header through trackDependency function. * @defaultValue false */ enableResponseHeaderTracking?: boolean; /** * An optional value that will track Response Error data through trackDependency function. * @defaultValue false */ enableAjaxErrorStatusText?: boolean; /** * Flag to enable looking up and including additional browser window.performance timings * in the reported ajax (XHR and fetch) reported metrics. * Defaults to false. */ enableAjaxPerfTracking?: boolean; /** * The maximum number of times to look for the window.performance timings (if available), this * is required as not all browsers populate the window.performance before reporting the * end of the XHR request and for fetch requests this is added after its complete * Defaults to 3 */ maxAjaxPerfLookupAttempts?: number; /** * The amount of time to wait before re-attempting to find the windows.performance timings * for an ajax request, time is in milliseconds and is passed directly to setTimeout() * Defaults to 25. */ ajaxPerfLookupDelay?: number; /** * Default false. when tab is closed, the SDK will send all remaining telemetry using the [Beacon API](https://www.w3.org/TR/beacon) * @defaultValue false */ onunloadDisableBeacon?: boolean; /** * @ignore * Internal only */ autoExceptionInstrumented?: boolean; /** * */ correlationHeaderDomains?: string[]; /** * @ignore * Internal only */ autoUnhandledPromiseInstrumented?: boolean; /** * Default false. Define whether to track unhandled promise rejections and report as JS errors. * When disableExceptionTracking is enabled (dont track exceptions) this value will be false. * @defaultValue false */ enableUnhandledPromiseRejectionTracking?: boolean; /** * Disable correlation headers using regular expressions */ correlationHeaderExcludePatterns?: RegExp[]; /** * The ability for the user to provide extra headers */ customHeaders?: [{ header: string; value: string; }]; /** * Provide user an option to convert undefined field to user defined value. */ convertUndefined?: any; /** * [Optional] The number of events that can be kept in memory before the SDK starts to drop events. By default, this is 10,000. */ eventsLimitInMem?: number; /** * [Optional] Disable iKey deprecation error message. * @defaultValue true */ disableIkeyDeprecationMessage?: boolean; /** * [Optional] Sets to true if user wants to disable sending internal log message 'SendBrowserInfoOnUserInit' * default to be false for versions 2.8.x and 3.0.x, true for versions 3.1.x and later */ disableUserInitMessage?: boolean; /** * [Optional] Flag to indicate whether the internal looking endpoints should be automatically * added to the `excludeRequestFromAutoTrackingPatterns` collection. (defaults to true). * This flag exists as the provided regex is generic and may unexpectedly match a domain that * should not be excluded. */ addIntEndpoints?: boolean; /** * [Optional] Sets throttle mgr configuration by key */ throttleMgrCfg?: { [key: number]: IThrottleMgrConfig; }; /** * [Optional] Specifies a Highest Priority custom endpoint URL where telemetry data will be sent. * This URL takes precedence over the 'config.endpointUrl' and any endpoint in the connection string. */ userOverrideEndpointUrl?: string; } /** * The type to identify whether the default value should be applied in preference to the provided value. */ type IConfigCheckFn = (value: V) => boolean; /** * The default values with a check function */ interface IConfigDefaultCheck { /** * Callback function to check if the user-supplied value is valid, if not the default will be applied */ isVal?: IConfigCheckFn; /** * Optional function to allow converting and setting of the default value */ set?: IConfigSetFn; /** * The default value to apply if the user-supplied value is not valid */ v?: V | IConfigDefaults; /** * The default fallback key if the main key is not present, this is the key value from the config */ fb?: keyof T | keyof C | Array; /** * Use this check to determine the default fallback, default only checked whether the property isDefined, * therefore `null`; `""` are considered to be valid values. */ dfVal?: (value: any) => boolean; /** * Specify that any provided value should have the default value(s) merged into the value rather than * just using either the default of user provided values. Mergeed objects will automatically be marked * as referenced. */ mrg?: boolean; /** * Set this field of the target as referenced, which will cause any object or array instance * to be updated in-place rather than being entirely replaced. All other values will continue to be replaced. * This is required for nested default objects to avoid multiple repetitive updates to listeners * @returns The referenced properties current value */ ref?: boolean; /** * Set this field of the target as read-only, which will block this single named property from * ever being changed for the target instance. * This does NOT freeze or seal the instance, it just stops the direct re-assignment of the named property, * if the value is a non-primitive (ie. an object or array) it's properties will still be mutable. * @returns The referenced properties current value */ rdOnly?: boolean; /** * Block the value associated with this property from having it's properties / values converted into * dynamic properties, this is generally used to block objects or arrays provided by external libraries * which may be a plain object with readonly (non-configurable) or const properties. */ blkVal?: boolean; } /** * The Type definition to define default values to be applied to the config * The value may be either the direct value or a ConfigDefaultCheck definition */ type IConfigDefaults = { [key in keyof T]: T[key] | IConfigDefaultCheck; }; /** * The type which identifies the function use to validate the user supplied value */ type IConfigSetFn = (value: any, defValue: V, theConfig: T) => V; /** * Configuration provided to SDK core */ interface IConfiguration { /** * Instrumentation key of resource. Either this or connectionString must be specified. */ instrumentationKey?: string | IPromise; /** * Connection string of resource. Either this or instrumentationKey must be specified. */ connectionString?: string | IPromise; /** * Set the timer interval (in ms) for internal logging queue, this is the * amount of time to wait after logger.queue messages are detected to be sent. * Note: since 3.0.1 and 2.8.13 the diagnostic logger timer is a normal timeout timer * and not an interval timer. So this now represents the timer "delay" and not * the frequency at which the events are sent. */ diagnosticLogInterval?: number; /** * Maximum number of iKey transmitted logging telemetry per page view */ maxMessageLimit?: number; /** * Console logging level. All logs with a severity level higher * than the configured level will be printed to console. Otherwise * they are suppressed. ie Level 2 will print both CRITICAL and * WARNING logs to console, level 1 prints only CRITICAL. * * Note: Logs sent as telemetry to instrumentation key will also * be logged to console if their severity meets the configured loggingConsoleLevel * * 0: ALL console logging off * 1: logs to console: severity \>= CRITICAL * 2: logs to console: severity \>= WARNING */ loggingLevelConsole?: number; /** * Telemtry logging level to instrumentation key. All logs with a severity * level higher than the configured level will sent as telemetry data to * the configured instrumentation key. * * 0: ALL iKey logging off * 1: logs to iKey: severity \>= CRITICAL * 2: logs to iKey: severity \>= WARNING */ loggingLevelTelemetry?: number; /** * If enabled, uncaught exceptions will be thrown to help with debugging */ enableDebug?: boolean; /** * Endpoint where telemetry data is sent */ endpointUrl?: string | IPromise; /** * Extension configs loaded in SDK */ extensionConfig?: { [key: string]: any; }; /** * Additional plugins that should be loaded by core at runtime */ readonly extensions?: ITelemetryPlugin[]; /** * Channel queues that is setup by caller in desired order. * If channels are provided here, core will ignore any channels that are already setup, example if there is a SKU with an initialized channel */ readonly channels?: IChannelControls[][]; /** * Flag that disables the Instrumentation Key validation. */ disableInstrumentationKeyValidation?: boolean; /** * [Optional] When enabled this will create local perfEvents based on sections of the code that have been instrumented * to emit perfEvents (via the doPerf()) when this is enabled. This can be used to identify performance issues within * the SDK, the way you are using it or optionally your own instrumented code. * The provided IPerfManager implementation does NOT send any additional telemetry events to the server it will only fire * the new perfEvent() on the INotificationManager which you can listen to. * This also does not use the window.performance API, so it will work in environments where this API is not supported. */ enablePerfMgr?: boolean; /** * [Optional] Callback function that will be called to create a the IPerfManager instance when required and `enablePerfMgr` * is enabled, this enables you to override the default creation of a PerfManager() without needing to `setPerfMgr()` * after initialization. */ createPerfMgr?: (core: IAppInsightsCore, notificationManager: INotificationManager) => IPerfManager; /** * [Optional] Fire every single performance event not just the top level root performance event. Defaults to false. */ perfEvtsSendAll?: boolean; /** * [Optional] Identifies the default length used to generate random session and user id's if non currently exists for the user / session. * Defaults to 22, previous default value was 5, if you need to keep the previous maximum length you should set this value to 5. */ idLength?: number; /** * @description Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. It * can be set here or as part of the cookieCfg.domain, the cookieCfg takes precedence if both are specified. * @defaultValue "" */ cookieDomain?: string; /** * @description Custom cookie path. This is helpful if you want to share Application Insights cookies behind an application * gateway. It can be set here or as part of the cookieCfg.domain, the cookieCfg takes precedence if both are specified. * @defaultValue "" */ cookiePath?: string; /** * [Optional] A boolean that indicated whether to disable the use of cookies by the SDK. If true, the SDK will not store or * read any data from cookies. Cookie usage can be re-enabled after initialization via the core.getCookieMgr().enable(). */ disableCookiesUsage?: boolean; /** * [Optional] A Cookie Manager configuration which includes hooks to allow interception of the get, set and delete cookie * operations. If this configuration is specified any specified enabled and domain properties will take precedence over the * cookieDomain and disableCookiesUsage values. */ cookieCfg?: ICookieMgrConfig; /** * [Optional] An array of the page unload events that you would like to be ignored, special note there must be at least one valid unload * event hooked, if you list all or the runtime environment only supports a listed "disabled" event it will still be hooked, if required by the SDK. * Unload events include "beforeunload", "unload", "visibilitychange" (with 'hidden' state) and "pagehide". * * This can be used to avoid jQuery 3.7.1+ deprecation warnings and Chrome warnings about the unload event: * @example * ```javascript * { * disablePageUnloadEvents: ["unload"] * } * ``` * * For more details, see the [Page Unload Events documentation](https://microsoft.github.io/ApplicationInsights-JS/PageUnloadEvents.html). */ disablePageUnloadEvents?: string[]; /** * [Optional] An array of page show events that you would like to be ignored, special note there must be at lease one valid show event * hooked, if you list all or the runtime environment only supports a listed (disabled) event it will STILL be hooked, if required by the SDK. * Page Show events include "pageshow" and "visibilitychange" (with 'visible' state). * * @example * ```javascript * { * disablePageShowEvents: ["pageshow"] * } * ``` * * For more details, see the [Page Unload Events documentation](https://microsoft.github.io/ApplicationInsights-JS/PageUnloadEvents.html). */ disablePageShowEvents?: string[]; /** * [Optional] A flag for performance optimization to disable attempting to use the Chrome Debug Extension, if disabled and the extension is installed * this will not send any notifications. */ disableDbgExt?: boolean; /** * Add "&w=0" parameter to support UA Parsing when web-workers don't have access to Document. * Default is false */ enableWParam?: boolean; /** * Custom optional value that will be added as a prefix for storage name. * @defaultValue undefined */ storagePrefix?: string; /** * Custom optional value to opt in features * @defaultValue undefined */ featureOptIn?: IFeatureOptIn; /** * If your connection string, instrumentation key and endpoint url are promises, * this config is to manually set timeout for those promises. * Default: 50000ms * @since 3.3.0 */ initTimeOut?: number; /** * If your connection string, instrumentation key and endpoint url are promises, * this config is to manually set in memory proxy track calls count limit before promises finished. * Default: 100 * @since 3.3.0 */ initInMemoMaxSize?: number; /** * [Optional] Set additional configuration for exceptions, such as more scripts to include in the exception telemetry. * @since 3.3.2 */ expCfg?: IExceptionConfig; /** * [Optional] A flag to enable or disable the use of the field redaction for urls. * @defaultValue true */ redactUrls?: boolean; /** * [Optional] Additional query parameters to redact beyond the default set. * Use this to specify custom parameters that contain sensitive information. * These will be combined with the default parameters that are redacted. * @defaultValue ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature"] * @example ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature","auth_token", "api_key", "private_data"] */ redactQueryParams?: string[]; } interface IContextTagKeys { /** * Application version. Information in the application context fields is always about the application that is sending the telemetry. */ readonly applicationVersion: string; /** * Application build. */ readonly applicationBuild: string; /** * Application type id. */ readonly applicationTypeId: string; /** * Application id. */ readonly applicationId: string; /** * Application layer. */ readonly applicationLayer: string; /** * Unique client device id. Computer name in most cases. */ readonly deviceId: string; readonly deviceIp: string; readonly deviceLanguage: string; /** * Device locale using - pattern, following RFC 5646. Example 'en-US'. */ readonly deviceLocale: string; /** * Model of the device the end user of the application is using. Used for client scenarios. If this field is empty then it is derived from the user agent. */ readonly deviceModel: string; readonly deviceFriendlyName: string; readonly deviceNetwork: string; readonly deviceNetworkName: string; /** * Client device OEM name taken from the browser. */ readonly deviceOEMName: string; readonly deviceOS: string; /** * Operating system name and version of the device the end user of the application is using. If this field is empty then it is derived from the user agent. Example 'Windows 10 Pro 10.0.10586.0' */ readonly deviceOSVersion: string; /** * Name of the instance where application is running. Computer name for on-premisis, instance name for Azure. */ readonly deviceRoleInstance: string; /** * Name of the role application is part of. Maps directly to the role name in azure. */ readonly deviceRoleName: string; readonly deviceScreenResolution: string; /** * The type of the device the end user of the application is using. Used primarily to distinguish JavaScript telemetry from server side telemetry. Examples: 'PC', 'Phone', 'Browser'. 'PC' is the default value. */ readonly deviceType: string; readonly deviceMachineName: string; readonly deviceVMName: string; readonly deviceBrowser: string; /** * The browser name and version as reported by the browser. */ readonly deviceBrowserVersion: string; /** * The IP address of the client device. IPv4 and IPv6 are supported. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service. */ readonly locationIp: string; /** * The country of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service. */ readonly locationCountry: string; /** * The province/state of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service. */ readonly locationProvince: string; /** * The city of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service. */ readonly locationCity: string; /** * A unique identifier for the operation instance. The operation.id is created by either a request or a page view. All other telemetry sets this to the value for the containing request or page view. Operation.id is used for finding all the telemetry items for a specific operation instance. */ readonly operationId: string; /** * The name (group) of the operation. The operation.name is created by either a request or a page view. All other telemetry items set this to the value for the containing request or page view. Operation.name is used for finding all the telemetry items for a group of operations (i.e. 'GET Home/Index'). */ readonly operationName: string; /** * The unique identifier of the telemetry item's immediate parent. */ readonly operationParentId: string; readonly operationRootId: string; /** * Name of synthetic source. Some telemetry from the application may represent a synthetic traffic. It may be web crawler indexing the web site, site availability tests or traces from diagnostic libraries like Application Insights SDK itself. */ readonly operationSyntheticSource: string; /** * The correlation vector is a light weight vector clock which can be used to identify and order related events across clients and services. */ readonly operationCorrelationVector: string; /** * Session ID - the instance of the user's interaction with the app. Information in the session context fields is always about the end user. When telemetry is sent from a service, the session context is about the user that initiated the operation in the service. */ readonly sessionId: string; /** * Boolean value indicating whether the session identified by ai.session.id is first for the user or not. */ readonly sessionIsFirst: string; readonly sessionIsNew: string; readonly userAccountAcquisitionDate: string; /** * In multi-tenant applications this is the account ID or name which the user is acting with. Examples may be subscription ID for Azure portal or blog name blogging platform. */ readonly userAccountId: string; /** * The browser's user agent string as reported by the browser. This property will be used to extract informaiton regarding the customer's browser but will not be stored. Use custom properties to store the original user agent. */ readonly userAgent: string; /** * Anonymous user id. Represents the end user of the application. When telemetry is sent from a service, the user context is about the user that initiated the operation in the service. */ readonly userId: string; /** * Store region for UWP applications. */ readonly userStoreRegion: string; /** * Authenticated user id. The opposite of ai.user.id, this represents the user with a friendly name. Since it's PII information it is not collected by default by most SDKs. */ readonly userAuthUserId: string; readonly userAnonymousUserAcquisitionDate: string; readonly userAuthenticatedUserAcquisitionDate: string; readonly cloudName: string; /** * Name of the role the application is a part of. Maps directly to the role name in azure. */ readonly cloudRole: string; readonly cloudRoleVer: string; /** * Name of the instance where the application is running. Computer name for on-premisis, instance name for Azure. */ readonly cloudRoleInstance: string; readonly cloudEnvironment: string; readonly cloudLocation: string; readonly cloudDeploymentUnit: string; /** * SDK version. See https://github.com/microsoft/ApplicationInsights-Home/blob/master/SDK-AUTHORING.md#sdk-version-specification for information. */ readonly internalSdkVersion: string; /** * Agent version. Used to indicate the version of StatusMonitor installed on the computer if it is used for data collection. */ readonly internalAgentVersion: string; /** * This is the node name used for billing purposes. Use it to override the standard detection of nodes. */ readonly internalNodeName: string; /** * This identifies the version of the snippet that was used to initialize the SDK */ readonly internalSnippet: string; /** * This identifies the source of the Sdk script (used to identify whether the SDK was loaded via the CDN) */ readonly internalSdkSrc: string; } interface ICookieMgr { /** * Enable or Disable the usage of cookies */ setEnabled(value: boolean): void; /** * Can the system use cookies, if this returns false then all cookie setting and access functions will return nothing */ isEnabled(): boolean; /** * Set the named cookie with the value and optional domain and optional * @param name - The name of the cookie * @param value - The value of the cookie (Must already be encoded) * @param maxAgeSec - [optional] The maximum number of SECONDS that this cookie should survive * @param domain - [optional] The domain to set for the cookie * @param path - [optional] Path to set for the cookie, if not supplied will default to "/" * @returns - True if the cookie was set otherwise false (Because cookie usage is not enabled or available) */ set(name: string, value: string, maxAgeSec?: number, domain?: string, path?: string): boolean; /** * Get the value of the named cookie * @param name - The name of the cookie */ get(name: string): string; /** * Delete/Remove the named cookie if cookie support is available and enabled. * Note: Not using "delete" as the name because it's a reserved word which would cause issues on older browsers * @param name - The name of the cookie * @param path - [optional] Path to set for the cookie, if not supplied will default to "/" * @returns - True if the cookie was marked for deletion otherwise false (Because cookie usage is not enabled or available) */ del(name: string, path?: string): boolean; /** * Purge the cookie from the system if cookie support is available, this function ignores the enabled setting of the manager * so any cookie will be removed. * Note: Not using "delete" as the name because it's a reserved word which would cause issues on older browsers * @param name - The name of the cookie * @param path - [optional] Path to set for the cookie, if not supplied will default to "/" * @returns - True if the cookie was marked for deletion otherwise false (Because cookie usage is not available) */ purge(name: string, path?: string): boolean; /** * Optional Callback hook to allow the cookie manager to update it's configuration, not generally implemented now that * dynamic configuration is supported * @param updateState - The new configuration state to apply to the cookie manager */ update?(updateState: ITelemetryUpdateState): void; /** * Unload and remove any state that this ICookieMgr may be holding, this is generally called when the * owning SDK is being unloaded. * @param isAsync - Can the unload be performed asynchronously (default) * @returns If the unload occurs synchronously then nothing should be returned, if happening asynchronously then * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * / Promise to allow any listeners to wait for the operation to complete. */ unload?(isAsync?: boolean): void | IPromise; } /** * Configuration definition for instance based cookie management configuration */ interface ICookieMgrConfig { /** * Defaults to true, A boolean that indicates whether the use of cookies by the SDK is enabled by the current instance. * If false, the instance of the SDK initialized by this configuration will not store or read any data from cookies */ enabled?: boolean; /** * Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. */ domain?: string; /** * Specifies the path to use for the cookie, defaults to '/' */ path?: string; /** * Specify the cookie name(s) to be ignored, this will cause any matching cookie name to never be read or written. * They may still be explicitly purged or deleted. You do not need to repeat the name in the `blockedCookies` * configuration.(Since v2.8.8) */ ignoreCookies?: string[]; /** * Specify the cookie name(s) to never be written, this will cause any cookie name to never be created or updated, * they will still be read unless also included in the ignoreCookies and may still be explicitly purged or deleted. * If not provided defaults to the same list provided in ignoreCookies. (Since v2.8.8) */ blockedCookies?: string[]; /** * Hook function to fetch the named cookie value. * @param name - The name of the cookie */ getCookie?: (name: string) => string; /** * Hook function to set the named cookie with the specified value. * @param name - The name of the cookie * @param value - The value to set for the cookie */ setCookie?: (name: string, value: string) => void; /** * Hook function to delete the named cookie with the specified value, separated from * setCookie to avoid the need to parse the value to determine whether the cookie is being * added or removed. * @param name - The name of the cookie * @param cookieValue - The value to set to expire the cookie */ delCookie?: (name: string, cookieValue: string) => void; /** * Defaults to false, when true this will disable the deferral behavior that occurs when cookies are disabled, * reverting to the previous behavior where cookie operations would simply return false when cookies are disabled. * This is provided to maintain backward compatibility if applications depend on the previous behavior. * When false (default), cookie operations are deferred until cookies are enabled, supporting consent scenarios. * @since v3.3.10 */ disableCookieDefer?: boolean; } interface ICorrelationConfig { enableCorsCorrelation: boolean; correlationHeaderExcludedDomains: string[]; correlationHeaderExcludePatterns?: RegExp[]; disableCorrelationHeaders: boolean; distributedTracingMode: DistributedTracingModes; maxAjaxCallsPerView: number; disableAjaxTracking: boolean; disableFetchTracking: boolean; appId?: string; enableRequestHeaderTracking?: boolean; enableResponseHeaderTracking?: boolean; enableAjaxErrorStatusText?: boolean; /** * Flag to enable looking up and including additional browser window.performance timings * in the reported ajax (XHR and fetch) reported metrics. * Defaults to false. */ enableAjaxPerfTracking?: boolean; /** * The maximum number of times to look for the window.performance timings (if available), this * is required as not all browsers populate the window.performance before reporting the * end of the XHR request and for fetch requests this is added after its complete * Defaults to 3 */ maxAjaxPerfLookupAttempts?: number; /** * The amount of time to wait before re-attempting to find the windows.performance timings * for an ajax request, time is in milliseconds and is passed directly to setTimeout() * Defaults to 25. */ ajaxPerfLookupDelay?: number; correlationHeaderDomains?: string[]; /** * [Optional] Response and request headers to be excluded from AJAX & Fetch tracking data. * To override or discard the default, add an array with all headers to be excluded or * an empty array to the configuration. * * For example: `["Authorization", "X-API-Key", "WWW-Authenticate"]` * * @example * ```js * import { ApplicationInsights } from '@microsoft/applicationinsights-web'; * import { AjaxPlugin } from '@microsoft/applicationinsights-dependencies-js'; * * const dependencyPlugin = new AjaxPlugin(); * const appInsights = new ApplicationInsights({ * config: { * connectionString: 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY_GOES_HERE', * extensions: [dependencyPlugin], * extensionConfig: { * [dependencyPlugin.identifier]: { * ignoreHeaders: [ * "Authorization", * "X-API-Key", * "WWW-Authenticate" * ] * } * } * } * }); * appInsights.loadAppInsights(); * appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview * ``` */ ignoreHeaders?: string[]; /** * Provide a way to exclude specific route from automatic tracking for XMLHttpRequest or Fetch request. * For an ajax / fetch request that the request url matches with the regex patterns, auto tracking is turned off. * Default is undefined. */ excludeRequestFromAutoTrackingPatterns?: string[] | RegExp[]; /** * Provide a way to enrich dependencies logs with context at the beginning of api call. * Default is undefined. */ addRequestContext?: (requestContext?: IRequestContext) => ICustomProperties; /** * [Optional] Flag to indicate whether the internal looking endpoints should be automatically * added to the `excludeRequestFromAutoTrackingPatterns` collection. (defaults to true). * This flag exists as the provided regex is generic and may unexpectedly match a domain that * should not be excluded. */ addIntEndpoints?: boolean; } interface ICustomProperties { [key: string]: any; } /** * Metric data single measurement. */ interface IDataPoint { /** * Name of the metric. */ name: string; /** * Metric type. Single measurement or the aggregated value. */ kind: DataPointType; /** * Single value for measurement. Sum of individual measurements for the aggregation. */ value: number; /** * Metric weight of the aggregated metric. Should not be set for a measurement. */ count: number; /** * Minimum value of the aggregated metric. Should not be set for a measurement. */ min: number; /** * Maximum value of the aggregated metric. Should not be set for a measurement. */ max: number; /** * Standard deviation of the aggregated metric. Should not be set for a measurement. */ stdDev: number; } /** * DependencyTelemetry telemetry interface */ interface IDependencyTelemetry extends IPartC { id: string; name?: string; duration?: number; success?: boolean; startTime?: Date; responseCode: number; correlationContext?: string; type?: string; data?: string; target?: string; iKey?: string; } interface IDevice { /** * The type for the current device. */ deviceClass: string; /** * A device unique ID. */ id: string; /** * The device model for the current device. */ model: string; /** * The application screen resolution. */ resolution: string; /** * The IP address. */ ip: string; } interface IDiagnosticLogger { /** * 0: OFF * 1: only critical (default) * 2: critical + info */ consoleLoggingLevel: () => number; /** * The internal logging queue */ queue: _InternalLogMessage[]; /** * This method will throw exceptions in debug mode or attempt to log the error as a console warning. * @param severity - The severity of the log message * @param message - The log message. */ throwInternal(severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct?: boolean): void; /** * This will write a debug message to the console if possible * @param message - The debug message */ debugToConsole?(message: string): void; /** * This will write a warning to the console if possible * @param message - The warning message */ warnToConsole(message: string): void; /** * This will write an error to the console if possible. * Provided by the default DiagnosticLogger instance, and internally the SDK will fall back to warnToConsole, however, * direct callers MUST check for its existence on the logger as you can provide your own IDiagnosticLogger instance. * @param message - The error message */ errorToConsole?(message: string): void; /** * Resets the internal message count */ resetInternalMessageCount(): void; /** * Logs a message to the internal queue. * @param severity - The severity of the log message * @param message - The message to log. */ logInternalMessage?(severity: LoggingSeverity, message: _InternalLogMessage): void; /** * Optional Callback hook to allow the diagnostic logger to update it's configuration * @param updateState - The new configuration state to apply to the diagnostic logger */ update?(updateState: ITelemetryUpdateState): void; /** * Unload and remove any state that this IDiagnosticLogger may be holding, this is generally called when the * owning SDK is being unloaded. * @param isAsync - Can the unload be performed asynchronously (default) * @returns If the unload occurs synchronously then nothing should be returned, if happening asynchronously then * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * / Promise to allow any listeners to wait for the operation to complete. */ unload?(isAsync?: boolean): void | IPromise; } interface IDistributedTraceContext { /** * Returns the current name of the page */ getName(): string; /** * Sets the current name of the page * @param pageName - The name of the page */ setName(pageName: string): void; /** * Returns the unique identifier for a trace. All requests / spans from the same trace share the same traceId. * Must be read from incoming headers or generated according to the W3C TraceContext specification, * in a hex representation of 16-byte array. A.k.a. trace-id, TraceID or Distributed TraceID */ getTraceId(): string; /** * Set the unique identifier for a trace. All requests / spans from the same trace share the same traceId. * Must be conform to the W3C TraceContext specification, in a hex representation of 16-byte array. * A.k.a. trace-id, TraceID or Distributed TraceID https://www.w3.org/TR/trace-context/#trace-id */ setTraceId(newValue: string): void; /** * Self-generated 8-bytes identifier of the incoming request. Must be a hex representation of 8-byte array. * Also know as the parentId, used to link requests together */ getSpanId(): string; /** * Self-generated 8-bytes identifier of the incoming request. Must be a hex representation of 8-byte array. * Also know as the parentId, used to link requests together * https://www.w3.org/TR/trace-context/#parent-id */ setSpanId(newValue: string): void; /** * An integer representation of the W3C TraceContext trace-flags. */ getTraceFlags(): number | undefined; /** * https://www.w3.org/TR/trace-context/#trace-flags * @param newValue - An integer representation of the W3C TraceContext trace-flags. */ setTraceFlags(newValue?: number): void; } /** * The abstract common base of all domains. */ interface IDomain { } interface IEnvelope extends ISerializable { /** * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. */ ver: number; /** * Type name of telemetry data item. */ name: string; /** * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. */ time: string; /** * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. */ sampleRate: number; /** * Sequence field used to track absolute order of uploaded events. */ seq: string; /** * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive. */ iKey: string; /** * Key/value collection of context properties. See ContextTagKeys for information on available properties. */ tags: { [name: string]: any; }; /** * Telemetry data item. */ data: any; } /** * Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. */ interface IEventData extends IDomain { /** * Schema version */ ver: number; /** * Event name. Keep it low cardinality to allow proper grouping and useful metrics. */ name: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; } interface IEventTelemetry extends IPartC { /** * @description An event name string */ name: string; /** * @description custom defined iKey */ iKey?: string; } /** * Configuration for extra exceptions information sent with the exception telemetry. * @example * ```js * const appInsights = new ApplicationInsights({ config: { connectionString: 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY_GOES_HERE', expCfg: { inclScripts: true, expLog : () => { return {logs: ["log info 1", "log info 2"]}; }, maxLogs : 100 } } }); appInsights.trackException({error: new Error(), severityLevel: SeverityLevel.Critical}); * ``` * @interface IExceptionConfig */ interface IExceptionConfig { /** * If set to true, when exception is sent out, the SDK will also send out all scripts basic info that are loaded on the page. * Notice: This would increase the size of the exception telemetry. * @defaultvalue true */ inclScripts?: boolean; /** * Callback function for collecting logs to be included in telemetry data. * * The length of logs to generate is controlled by the `maxLogs` parameter. * * This callback is called before telemetry data is sent, allowing for dynamic customization of the logs. * * @returns An object with the following property: * - logs: An array of strings, where each string represents a log entry to be included in the telemetry. * * @property maxLogs - Specifies the maximum number of logs that can be generated. If not explicitly set, it defaults to 50. */ expLog?: () => { logs: string[]; }; /** * The maximum number of logs to include in the telemetry data. * If not explicitly set, it defaults to 50. * This is used in conjunction with the `expLog` callback. */ maxLogs?: number; } /** * An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. */ interface IExceptionData extends IDomain { /** * Schema version */ ver: number; /** * Exception chain - list of inner exceptions. */ exceptions: IExceptionDetails[]; /** * Severity level. Mostly used to indicate exception severity level when it is reported by logging library. */ severityLevel: SeverityLevel; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; } /** * Exception details of the exception in a chain. */ interface IExceptionDetails { /** * In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. */ id: number; /** * The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception */ outerId: number; /** * Exception type name. */ typeName: string; /** * Exception message. */ message: string; /** * Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. */ hasFullStack: boolean; /** * Text describing the stack. Either stack or parsedStack should have a value. */ stack: string; /** * List of stack frames. Either stack or parsedStack should have a value. */ parsedStack: IStackFrame[]; } interface IExceptionDetailsInternal { id: number; outerId: number; typeName: string; message: string; hasFullStack: boolean; stack: string; parsedStack: IExceptionStackFrameInternal[]; } interface IExceptionInternal extends IPartC { ver: string; id: string; exceptions: IExceptionDetailsInternal[]; severityLevel?: SeverityLevel | number; problemGroup: string; isManual: boolean; } interface IExceptionStackFrameInternal { level: number; method: string; assembly: string; fileName: string; line: number; pos?: number; } /** * @export * @interface IExceptionTelemetry * @description Exception interface used as primary parameter to trackException */ interface IExceptionTelemetry extends IPartC { /** * Unique guid identifying this error */ id?: string; /** * @deprecated Please use the `exception` field instead. The behavior and usage of `exception` remains the same as this field. * Unique guid identifying this error. */ error?: Error; /** * @description Error Object(s) */ exception?: Error | IAutoExceptionTelemetry; /** * @description Specified severity of exception for use with * telemetry filtering in dashboard */ severityLevel?: SeverityLevel | number; } interface IFeatureOptIn { [feature: string]: IFeatureOptInDetails; } interface IFeatureOptInDetails { /** * sets feature opt-in mode * @default undefined */ mode?: FeatureOptInMode; /** * Identifies configuration override values when given feature is enabled * NOTE: should use flat string for fields, for example, if you want to set value for extensionConfig.Ananlytics.disableAjaxTrackig in configurations, * you should use "extensionConfig.Ananlytics.disableAjaxTrackig" as field name: \{["extensionConfig.Analytics.disableAjaxTrackig"]:1\} * Default: undefined */ onCfg?: { [field: string]: any; }; /** * Identifies configuration override values when given feature is disabled * NOTE: should use flat string for fields, for example, if you want to set value for extensionConfig.Ananlytics.disableAjaxTrackig in configurations, * you should use "extensionConfig.Ananlytics.disableAjaxTrackig" as field name: \{["extensionConfig.Analytics.disableAjaxTrackig"]:1\} * Default: undefined */ offCfg?: { [field: string]: any; }; /** * define if should block any changes from cdn cfg, if set to true, cfgValue will be applied under all scenarios * @default false */ blockCdnCfg?: boolean; } interface IInternal { /** * The SDK version used to create this telemetry item. */ sdkVersion: string; /** * The SDK agent version. */ agentVersion: string; /** * The Snippet version used to initialize the sdk instance, this will contain either * undefined/null - Snippet not used * '-' - Version and legacy mode not determined * # - Version # of the snippet * #.l - Version # in legacy mode * .l - No defined version, but used legacy mode initialization */ snippetVer: string; /** * Identifies the source of the sdk script */ sdkSrc: string; } /** * Internal Interface */ interface IInternalOfflineSupport { /** * Get current endpoint url * @returns endpoint */ getUrl: () => string; /** * Create payload data * @returns IPayloadData */ createPayload: (data: string | Uint8Array) => IPayloadData; /** * Serialize an item into a string * @param input - telemetry item * @param convertUndefined - convert undefined to a custom-defined object * @returns Serialized string */ serialize?: (input: ITelemetryItem, convertUndefined?: any) => string; /** * Batch an array of strings into one string * @param arr - array of strings * @returns a string represent all items in the given array */ batch?: (arr: string[]) => string; /** * If the item should be processed by offline channel * @param evt - telemetry item * @returns should process or not */ shouldProcess?: (evt: ITelemetryItem) => boolean; /** * Create 1ds payload data * @param evts - ITelemetryItems * @returns IPayloadData */ createOneDSPayload?: (evts: ITelemetryItem[]) => IPayloadData; } /** * An alternate interface which provides automatic removal during unloading of the component */ interface ILegacyUnloadHook { /** * Legacy Self remove the referenced component */ remove: () => void; } interface ILoadedPlugin { plugin: T; /** * Identifies whether the plugin is enabled and can process events. This is slightly different from isInitialized as the plugin may be initialized but disabled * via the setEnabled() or it may be a shared plugin which has had it's teardown function called from another instance.. * @returns boolean = true if the plugin is in a state where it is operational. */ isEnabled: () => boolean; /** * You can optionally enable / disable a plugin from processing events. * Setting enabled to true will not necessarily cause the `isEnabled()` to also return true * as the plugin must also have been successfully initialized and not had it's `teardown` method called * (unless it's also been re-initialized) */ setEnabled: (isEnabled: boolean) => void; remove: (isAsync?: boolean, removeCb?: (removed?: boolean) => void) => void; } interface ILocation { /** * Client IP address for reverse lookup */ ip: string; } /** * Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements. */ interface IMessageData extends IDomain { /** * Schema version */ ver: number; /** * Trace message */ message: string; /** * Trace severity level. */ severityLevel: SeverityLevel; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; } /** * An instance of the Metric item is a list of measurements (single data points) and/or aggregations. */ interface IMetricData extends IDomain { /** * Schema version */ ver: number; /** * List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. */ metrics: IDataPoint[]; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; } interface IMetricTelemetry extends IPartC { /** * @description (required) - name of this metric */ name: string; /** * @description (required) - Recorded value/average for this metric */ average: number; /** * @description (optional) Number of samples represented by the average. * @default sampleCount=1 */ sampleCount?: number; /** * @description (optional) The smallest measurement in the sample. Defaults to the average * @default min=average */ min?: number; /** * @description (optional) The largest measurement in the sample. Defaults to the average. * @default max=average */ max?: number; /** * (optional) The standard deviation measurement in the sample, Defaults to undefined which results in zero. */ stdDev?: number; /** * @description custom defined iKey */ iKey?: string; } /** * An interface used for the notification listener. * @interface */ interface INotificationListener { /** * [Optional] A function called when events are sent. * @param events - The array of events that have been sent. */ eventsSent?: (events: ITelemetryItem[]) => void; /** * [Optional] A function called when events are discarded. * @param events - The array of events that have been discarded. * @param reason - The reason for discarding the events. The EventsDiscardedReason * constant should be used to check the different values. * @param sendType - [Optional] The send type used when the events were discarded. */ eventsDiscarded?: (events: ITelemetryItem[], reason: number, sendType?: number) => void; /** * [Optional] A function called when the events have been requested to be sent to the sever. * @param sendReason - The reason why the event batch is being sent. * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner. */ eventsSendRequest?: (sendReason: number, isAsync?: boolean) => void; /** * [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging * the event can be displayed via the debug plugin extension. * @param perfEvent - The performance event object */ perfEvent?: (perfEvent: IPerfEvent) => void; /** * Unload and remove any state that this INotificationListener may be holding, this is generally called when the * owning Manager is being unloaded. * @param isAsync - Can the unload be performed asynchronously (default) * @returns If the unload occurs synchronously then nothing should be returned, if happening asynchronously then * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * / Promise to allow any listeners to wait for the operation to complete. */ unload?(isAsync?: boolean): void | IPromise; /** * [Optional] A function called when the offline events have been stored to the persistent storage * @param events - items that are stored in the persistent storage * @since v3.1.1 */ offlineEventsStored?(events: ITelemetryItem[]): void; /** * [Optional] A function called when the offline events have been sent from the persistent storage * @param batch - payload data that is sent from the persistent storage * @since v3.1.1 */ offlineBatchSent?(batch: IPayloadData): void; /** * [Optional] A function called when the offline events have been dropped from the persistent storage * @param cnt - count of batches dropped * @param reason - the reason why the batches is dropped * @since v3.1.1 */ offlineBatchDrop?(cnt: number, reason?: number): void; } /** * Class to manage sending notifications to all the listeners. */ interface INotificationManager { listeners: INotificationListener[]; /** * Adds a notification listener. * @param listener - The notification listener to be added. */ addNotificationListener(listener: INotificationListener): void; /** * Removes all instances of the listener. * @param listener - AWTNotificationListener to remove. */ removeNotificationListener(listener: INotificationListener): void; /** * Notification for events sent. * @param events - The array of events that have been sent. */ eventsSent(events: ITelemetryItem[]): void; /** * Notification for events being discarded. * @param events - The array of events that have been discarded by the SDK. * @param reason - The reason for which the SDK discarded the events. The EventsDiscardedReason * constant should be used to check the different values. * @param sendType - [Optional] The send type used when the events were discarded. */ eventsDiscarded(events: ITelemetryItem[], reason: number, sendType?: number): void; /** * [Optional] A function called when the events have been requested to be sent to the sever. * @param sendReason - The reason why the event batch is being sent. * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner. */ eventsSendRequest?(sendReason: number, isAsync: boolean): void; /** * [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging * the event can be displayed via the debug plugin extension. * @param perfEvent - The perf event details */ perfEvent?(perfEvent: IPerfEvent): void; /** * Unload and remove any state that this INotificationManager may be holding, this is generally called when the * owning SDK is being unloaded. * @param isAsync - Can the unload be performed asynchronously (default) * @returns If the unload occurs synchronously then nothing should be returned, if happening asynchronously then * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * / Promise to allow any listeners to wait for the operation to complete. */ unload?(isAsync?: boolean): void | IPromise; /** * [Optional] A function called when the offline events have been stored to the persistent storage * @param events - items that are stored in the persistent storage * @since v3.1.1 */ offlineEventsStored?(events: ITelemetryItem[]): void; /** * [Optional] A function called when the offline events have been sent from the persistent storage * @param batch - payload data that is sent from the persistent storage * @since v3.1.1 */ offlineBatchSent?(batch: IPayloadData): void; /** * [Optional] A function called when the offline events have been dropped from the persistent storage * @param cnt - count of batches dropped * @param reason - the reason why the batches is dropped * @since v3.1.1 */ offlineBatchDrop?(cnt: number, reason?: number): void; } class _InternalLogMessage { static dataType: string; message: string; messageId: _InternalMessageId; constructor(msgId: _InternalMessageId, msg: string, isUserAct?: boolean, properties?: Object); } type _InternalMessageId = number | _eInternalMessageId; interface IOfflineListener { isOnline: () => boolean; isListening: () => boolean; unload: () => void; addListener: (callback: OfflineCallback) => IUnloadHook; setOnlineState: (uState: eOfflineValue) => void; } /** * This is the interface for the Offline state * runtime state is retrieved from the browser state * user state is set by the user */ interface IOfflineState { readonly isOnline: boolean; readonly rState: eOfflineValue; readonly uState: eOfflineValue; } interface IOperatingSystem { name: string; } /** * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */ interface IPageViewData extends IEventData { /** * Request URL with all query string parameters */ url: string; /** * Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */ duration: string; /** * Identifier of a page view instance. Used for correlation between page view and other telemetry items. */ id: string; } /** * An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request. */ interface IPageViewPerfData extends IPageViewData { /** * Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ perfTotal: string; /** * Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ networkConnect: string; /** * Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ sentRequest: string; /** * Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ receivedResponse: string; /** * DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ domProcessing: string; } interface IPageViewPerformanceTelemetry extends IPartC { /** * name String - The name of the page. Defaults to the document title. */ name?: string; /** * url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. */ uri?: string; /** * Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff". This is total duration in timespan format. */ perfTotal?: string; /** * Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff". This represents the total page load time. */ duration?: string; /** * Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ networkConnect?: string; /** * Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. */ sentRequest?: string; /** * Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff. */ receivedResponse?: string; /** * DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ domProcessing?: string; } interface IPageViewPerformanceTelemetryInternal extends IPageViewPerformanceTelemetry { /** * An identifier assigned to each distinct impression for the purposes of correlating with pageview. * A new id is automatically generated on each pageview. You can manually specify this field if you * want to use a specific value instead. */ id?: string; /** * Version of the part B schema, todo: set this value in trackpageView */ ver?: string; /** * Field indicating whether this instance of PageViewPerformance is valid and should be sent */ isValid?: boolean; /** * Duration in miliseconds */ durationMs?: number; } /** * Pageview telemetry interface */ interface IPageViewTelemetry extends IPartC { /** * name String - The string you used as the name in startTrackPage. Defaults to the document title. */ name?: string; /** * uri String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. */ uri?: string; /** * refUri String - the URL of the source page where current page is loaded from */ refUri?: string; /** * pageType String - page type */ pageType?: string; /** * isLoggedIn - boolean is user logged in */ isLoggedIn?: boolean; /** * Property bag to contain additional custom properties (Part C) */ properties?: { /** * The number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. */ duration?: number; [key: string]: any; }; /** * iKey String - custom defined iKey. */ iKey?: string; /** * Time first page view is triggered */ startTime?: Date; } interface IPageViewTelemetryInternal extends IPageViewTelemetry { /** * An identifier assigned to each distinct impression for the purposes of correlating with pageview. * A new id is automatically generated on each pageview. You can manually specify this field if you * want to use a specific value instead. */ id?: string; /** * Version of the part B schema, todo: set this value in trackpageView */ ver?: string; } /** * PartC telemetry interface */ interface IPartC { /** * Property bag to contain additional custom properties (Part C) */ properties?: { [key: string]: any; }; /** * Property bag to contain additional custom measurements (Part C) * @deprecated -- please use properties instead */ measurements?: { [key: string]: number; }; } /** IPayloadData describes interface of payload sent via POST channel */ interface IPayloadData { urlString: string; data: Uint8Array | string; headers?: { [name: string]: string; }; timeout?: number; disableXhrSync?: boolean; disableFetchKeepAlive?: boolean; sendReason?: SendRequestReason; } /** * This interface identifies the details of an internal performance event - it does not represent an outgoing reported event */ interface IPerfEvent { /** * The name of the performance event */ name: string; /** * The start time of the performance event */ start: number; /** * The payload (contents) of the perfEvent, may be null or only set after the event has completed depending on * the runtime environment. */ payload: any; /** * Is this occurring from an asynchronous event */ isAsync: boolean; /** * Identifies the total inclusive time spent for this event, including the time spent for child events, * this will be undefined until the event is completed */ time?: number; /** * Identifies the exclusive time spent in for this event (not including child events), * this will be undefined until the event is completed. */ exTime?: number; /** * The Parent event that was started before this event was created */ parent?: IPerfEvent; /** * The child perf events that are contained within the total time of this event. */ childEvts?: IPerfEvent[]; /** * Identifies whether this event is a child event of a parent */ isChildEvt: () => boolean; /** * Get the names additional context associated with this perf event */ getCtx?: (key: string) => any; /** * Set the named additional context to be associated with this perf event, this will replace any existing value */ setCtx?: (key: string, value: any) => void; /** * Mark this event as completed, calculating the total execution time. */ complete: () => void; } /** * This defines an internal performance manager for tracking and reporting the internal performance of the SDK -- It does * not represent or report any event to the server. */ interface IPerfManager { /** * Create a new event and start timing, the manager may return null/undefined to indicate that it does not * want to monitor this source event. * @param src - The source name of the event * @param payloadDetails - An optional callback function to fetch the payload details for the event. * @param isAsync - Is the event occurring from a async event */ create(src: string, payloadDetails?: () => any, isAsync?: boolean): IPerfEvent | null | undefined; /** * Complete the perfEvent and fire any notifications. * @param perfEvent - Fire the event which will also complete the passed event */ fire(perfEvent: IPerfEvent): void; /** * Set an execution context value * @param key - The context key name * @param value - The value */ setCtx(key: string, value: any): void; /** * Get the execution context value * @param key - The context key */ getCtx(key: string): any; } /** * Identifies an interface to a host that can provide an IPerfManager implementation */ interface IPerfManagerProvider { /** * Get the current performance manager */ getPerfMgr(): IPerfManager; /** * Set the current performance manager * @param perfMgr - The performance manager */ setPerfMgr(perfMgr: IPerfManager): void; } interface IPlugin { /** * Initialize plugin loaded by SDK * @param config - The config for the plugin to use * @param core - The current App Insights core to use for initializing this plugin instance * @param extensions - The complete set of extensions to be used for initializing the plugin * @param pluginChain - [Optional] specifies the current plugin chain which identifies the * set of plugins and the order they should be executed for the current request. */ initialize: (config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain) => void; /** * Returns a value that indicates whether the plugin has already been previously initialized. * New plugins should implement this method to avoid being initialized more than once. */ isInitialized?: () => boolean; /** * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further * processTelemetry calls are ignored and it just calls the processNext() with the provided context. * @param unloadCtx - This is the context that should be used during unloading. * @param unloadState - The details / state of the unload process, it holds details like whether it should be unloaded synchronously or asynchronously and the reason for the unload. * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing. */ teardown?: (unloadCtx: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => void | boolean; /** * Extension name */ readonly identifier: string; /** * Plugin version (available in data.properties.version in common schema) */ readonly version?: string; /** * The App Insights core to use for backward compatibility. * Therefore the interface will be able to access the core without needing to cast to "any". * [optional] any 3rd party plugins which are already implementing this interface don't fail to compile. */ core?: IAppInsightsCore; } /** * The current context for the current call to processTelemetry(), used to support sharing the same plugin instance * between multiple AppInsights instances */ interface IProcessTelemetryContext extends IBaseProcessingContext { /** * Call back for telemetry processing before it it is sent * @param env - This is the current event being reported * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void) */ processNext: (env: ITelemetryItem) => boolean | void; /** * Create a new context using the core and config from the current instance, returns a new instance of the same type * @param plugins - The execution order to process the plugins, if null or not supplied * then the current execution order will be copied. * @param startAt - The plugin to start processing from, if missing from the execution * order then the next plugin will be NOT set. */ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryContext; } /** * The current context for the current call to teardown() implementations, used to support when plugins are being removed * or the SDK is being unloaded. */ interface IProcessTelemetryUnloadContext extends IBaseProcessingContext { /** * This Plugin has finished unloading, so unload the next one * @param uploadState - The state of the unload process * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void) */ processNext: (unloadState: ITelemetryUnloadState) => boolean | void; /** * Create a new context using the core and config from the current instance, returns a new instance of the same type * @param plugins - The execution order to process the plugins, if null or not supplied * then the current execution order will be copied. * @param startAt - The plugin to start processing from, if missing from the execution * order then the next plugin will be NOT set. */ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryUnloadContext; } /** * The current context for the current call to the plugin update() implementations, used to support the notifications * for when plugins are added, removed or the configuration was changed. */ interface IProcessTelemetryUpdateContext extends IBaseProcessingContext { /** * This Plugin has finished unloading, so unload the next one * @param updateState - The update State * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void) */ processNext: (updateState: ITelemetryUpdateState) => boolean | void; /** * Create a new context using the core and config from the current instance, returns a new instance of the same type * @param plugins - The execution order to process the plugins, if null or not supplied * then the current execution order will be copied. * @param startAt - The plugin to start processing from, if missing from the execution * order then the next plugin will be NOT set. */ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryUpdateContext; } /** * Create a Promise object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. * This interface definition, closely mirrors the typescript / javascript PromiseLike and Promise definitions as well as providing * simular functions as that provided by jQuery deferred objects. * * The returned Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers * with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous * methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point * in the future. * * A Promise is in one of these states: *
    *
  • pending: initial state, neither fulfilled nor rejected. *
  • fulfilled: meaning that the operation was completed successfully. *
  • rejected: meaning that the operation failed. *
* * A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the * associated handlers queued up by a promise's then method are called synchronously. If the promise has already been fulfilled or rejected * when a corresponding handler is attached, the handler will be called synchronously, so there is no race condition between an asynchronous * operation completing and its handlers being attached. * * As the `then()` and `catch()` methods return promises, they can be chained. * @typeParam T - Identifies the expected return type from the promise */ interface IPromise extends PromiseLike, Promise { /** * Returns a string representation of the current state of the promise. The promise can be in one of four states. *
    *
  • "pending": The promise is not yet in a completed state (neither "rejected"; or "resolved").
  • *
  • "resolved": The promise is in the resolved state.
  • *
  • "rejected": The promise is in the rejected state.
  • *
* @example * ```ts * let doResolve; * let promise: IPromise = createSyncPromise((resolve) => { * doResolve = resolve; * }); * * let state: string = promise.state(); * console.log("State: " + state); // State: pending * doResolve(true); // Promise will resolve synchronously as it's a synchronous promise * console.log("State: " + state); // State: resolved * ``` */ state?: string; /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onResolved - The callback to execute when the Promise is resolved. * @param onRejected - The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. * @example * ```ts * const promise1 = createPromise((resolve, reject) => { * resolve('Success!'); * }); * * promise1.then((value) => { * console.log(value); * // expected output: "Success!" * }); * ``` */ then(onResolved?: ResolvedPromiseHandler, onRejected?: RejectedPromiseHandler): IPromise; /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onResolved - The callback to execute when the Promise is resolved. * @param onRejected - The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. * @example * ```ts * const promise1 = createPromise((resolve, reject) => { * resolve('Success!'); * }); * * promise1.then((value) => { * console.log(value); * // expected output: "Success!" * }); * ``` */ then(onResolved?: ResolvedPromiseHandler, onRejected?: RejectedPromiseHandler): PromiseLike; /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onResolved - The callback to execute when the Promise is resolved. * @param onRejected - The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. * @example * ```ts * const promise1 = createPromise((resolve, reject) => { * resolve('Success!'); * }); * * promise1.then((value) => { * console.log(value); * // expected output: "Success!" * }); * ``` */ then(onResolved?: ResolvedPromiseHandler, onRejected?: RejectedPromiseHandler): IPromise; /** * Attaches a callback for only the rejection of the Promise. * @param onRejected - The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. * @example * ```ts * const promise1 = createPromise((resolve, reject) => { * throw 'Uh-oh!'; * }); * * promise1.catch((error) => { * console.error(error); * }); * // expected output: Uh-oh! * ``` */ catch(onRejected?: ((reason: any) => TResult | IPromise) | undefined | null): IPromise; /** * Attaches a callback for only the rejection of the Promise. * @param onRejected - The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. * @example * ```ts * const promise1 = createPromise((resolve, reject) => { * throw 'Uh-oh!'; * }); * * promise1.catch((error) => { * console.error(error); * }); * // expected output: Uh-oh! * ``` */ catch(onRejected?: ((reason: any) => TResult | IPromise) | undefined | null): PromiseLike; /** * Attaches a callback for only the rejection of the Promise. * @param onRejected - The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. * @example * ```ts * const promise1 = createPromise((resolve, reject) => { * throw 'Uh-oh!'; * }); * * promise1.catch((error) => { * console.error(error); * }); * // expected output: Uh-oh! * ``` */ catch(onRejected?: ((reason: any) => TResult | IPromise) | undefined | null): IPromise; /** * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The * resolved value cannot be modified from the callback. * @param onfinally - The callback to execute when the Promise is settled (fulfilled or rejected). * @returns A Promise for the completion of the callback. * @example * ```ts * function doFunction() { * return createPromise((resolve, reject) => { * if (Math.random() > 0.5) { * resolve('Function has completed'); * } else { * reject(new Error('Function failed to process')); * } * }); * } * * doFunction().then((data) => { * console.log(data); * }).catch((err) => { * console.error(err); * }).finally(() => { * console.log('Function processing completed'); * }); * ``` */ finally(onfinally?: FinallyPromiseHandler): IPromise; } interface IPropertiesPlugin { readonly context: ITelemetryContext; } /** * An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. */ interface IRemoteDependencyData extends IDomain { /** * Schema version */ ver: number; /** * Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. */ name: string; /** * Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. */ id: string; /** * Result code of a dependency call. Examples are SQL error code and HTTP status code. */ resultCode: string; /** * Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */ duration: string; /** * Indication of successful or unsuccessful call. */ success: boolean; /** * Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters. */ data: string; /** * Target site of a dependency call. Examples are server name, host address. */ target: string; /** * Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. */ type: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; } interface IRequestContext { status?: number; xhr?: XMLHttpRequest; request?: Request; response?: Response | string; } interface IRequestHeaders { /** * Request-Context header */ requestContextHeader: string; /** * Target instrumentation header that is added to the response and retrieved by the * calling application when processing incoming responses. */ requestContextTargetKey: string; /** * Request-Context appId format */ requestContextAppIdFormat: string; /** * Request-Id header */ requestIdHeader: string; /** * W3C distributed tracing protocol header */ traceParentHeader: string; /** * W3C distributed tracing protocol state header */ traceStateHeader: string; /** * Sdk-Context header * If this header passed with appId in content then appId will be returned back by the backend. */ sdkContextHeader: string; /** * String to pass in header for requesting appId back from the backend. */ sdkContextHeaderAppIdRequest: string; requestContextHeaderLowerCase: string; } interface ISample { /** * Sample rate */ sampleRate: number; isSampledIn(envelope: ITelemetryItem): boolean; } /** * Checks if HTML5 Beacons are supported in the current environment. * @param useCached - [Optional] used for testing to bypass the cached lookup, when `true` this will * cause the cached global to be reset. * @returns True if supported, false otherwise. */ function isBeaconApiSupported(useCached?: boolean): boolean; function isCrossOriginError(message: string | Event, url: string, lineNumber: number, columnNumber: number, error: Error | Event): boolean; interface ISerializable { /** * The set of fields for a serializable object. * This defines the serialization order and a value of true/false * for each field defines whether the field is required or not. */ aiDataContract: any; } interface ISession { /** * The session ID. */ id?: string; /** * The date at which this guid was genereated. * Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time. */ acquisitionDate?: number; /** * The date at which this session ID was last reported. * This value should be updated whenever telemetry is sent using this ID. * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. */ renewalDate?: number; } /** * An interface that identifies the automatic session manager * @since 3.0.3 */ interface ISessionManager { /** * The automatic Session which has been initialized from the automatic SDK cookies and storage */ automaticSession: ISession; /** * Update the automatic session cookie if required * @returns */ update: () => void; /** * Record the current state of the automatic session and store it in our cookie string format * into the browser's local storage. This is used to restore the session data when the cookie * expires. */ backup: () => void; } function isInternalApplicationInsightsEndpoint(endpointUrl: string): boolean; /** * Is the parsed traceParent indicating that the trace is currently sampled. * @param value - The parsed traceParent value * @returns */ function isSampledFlag(value: ITraceParent): boolean; interface IStackDetails { src: string; obj: string[]; } /** * Stack frame information. */ interface IStackFrame { /** * Level in the call stack. For the long stacks SDK may not report every function in a call stack. */ level: number; /** * Method name. */ method: string; /** * Name of the assembly (dll, jar, etc.) containing this function. */ assembly: string; /** * File name or URL of the method implementation. */ fileName: string; /** * Line number of the code implementation. */ line: number; } /** * Identifies a simple interface to allow you to override the storage mechanism used * to track unsent and unacknowledged events. When provided it must provide both * the get and set item functions. * @since 2.8.12 */ interface IStorageBuffer { /** * Retrieves the stored value for a given key */ getItem(logger: IDiagnosticLogger, name: string): string; /** * Sets the stored value for a given key */ setItem(logger: IDiagnosticLogger, name: string, data: string): boolean; } /** * Is the provided W3c span id (aka. parent id) a valid string representation, it must be a 16-character * string of lowercase hexadecimal characters, for example, 00f067aa0ba902b7. * If all characters are zero (0000000000000000) this is considered an invalid value. * @param value - The W3c span id to be validated * @returns true if valid otherwise false */ function isValidSpanId(value: string): boolean; /** * Is the provided W3c Trace Id a valid string representation, it must be a 32-character string * of lowercase hexadecimal characters for example, 4bf92f3577b34da6a3ce929d0e0e4736. * If all characters as zero (00000000000000000000000000000000) it will be considered an invalid value. * @param value - The W3c trace Id to be validated * @returns true if valid otherwise false */ function isValidTraceId(value: string): boolean; /** * Validates that the provided ITraceParent instance conforms to the currently supported specifications * @param value - The parsed traceParent value * @returns */ function isValidTraceParent(value: ITraceParent): boolean; interface ITelemetryContext { /** * The object describing a component tracked by this object. */ readonly application: IApplication; /** * The object describing a device tracked by this object. */ readonly device: IDevice; /** * The object describing internal settings. */ readonly internal: IInternal; /** * The object describing a location tracked by this object. */ readonly location: ILocation; /** * The object describing a operation tracked by this object. */ readonly telemetryTrace: ITelemetryTrace; /** * The object describing a user tracked by this object. */ readonly user: IUserContext; /** * The object describing a session tracked by this object. */ readonly session: ISession; /** * The session manager that manages the automatic session from the cookies */ readonly sessionManager: ISessionManager; /** * The object describing os details tracked by this object. */ readonly os?: IOperatingSystem; /** * The object describing we details tracked by this object. */ readonly web?: IWeb; /** * application id obtained from breeze responses. Is used if appId is not specified by root config */ appId: () => string; /** * session id obtained from session manager. */ getSessionId: () => string; } interface ITelemetryInitializerHandler extends ILegacyUnloadHook { remove(): void; } /** * Telemety item supported in Core */ interface ITelemetryItem { /** * CommonSchema Version of this SDK */ ver?: string; /** * Unique name of the telemetry item */ name: string; /** * Timestamp when item was sent */ time?: string; /** * Identifier of the resource that uniquely identifies which resource data is sent to */ iKey?: string; /** * System context properties of the telemetry item, example: ip address, city etc */ ext?: { [key: string]: any; }; /** * System context property extensions that are not global (not in ctx) */ tags?: Tags; /** * Custom data */ data?: ICustomProperties; /** * Telemetry type used for part B */ baseType?: string; /** * Based on schema for part B */ baseData?: { [key: string]: any; }; } /** * Configuration provided to SDK core */ interface ITelemetryPlugin extends ITelemetryProcessor, IPlugin { /** * Set next extension for telemetry processing, this is now optional as plugins should use the * processNext() function of the passed IProcessTelemetryContext instead. It is being kept for * now for backward compatibility only. * @deprecated - Use processNext() function of the passed IProcessTelemetryContext instead */ setNextPlugin?: (next: ITelemetryPlugin | ITelemetryPluginChain) => void; /** * Priority of the extension */ readonly priority: number; } /** * Configuration provided to SDK core */ interface ITelemetryPluginChain extends ITelemetryProcessor { /** * Returns the underlying plugin that is being proxied for the processTelemetry call */ getPlugin: () => ITelemetryPlugin; /** * Returns the next plugin */ getNext: () => ITelemetryPluginChain; /** * This plugin is being unloaded and should remove any hooked events and cleanup any global/scoped values, after this * call the plugin will be removed from the telemetry processing chain and will no longer receive any events.. * @param unloadCtx - The unload context to use for this call. * @param unloadState - The details of the unload operation */ unload?: (unloadCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) => void; } interface ITelemetryProcessor { /** * Call back for telemetry processing before it it is sent * @param env - This is the current event being reported * @param itemCtx - This is the context for the current request, ITelemetryPlugin instances * can optionally use this to access the current core instance or define / pass additional information * to later plugins (vs appending items to the telemetry item) */ processTelemetry: (env: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => void; /** * The the plugin should re-evaluate configuration and update any cached configuration settings or * plugins. If implemented this method will be called whenever a plugin is added or removed and if * the configuration has bee updated. * @param updateCtx - This is the context that should be used during updating. * @param updateState - The details / state of the update process, it holds details like the current and previous configuration. * @returns boolean - true if the plugin has or will call updateCtx.processNext(), this allows the plugin to perform any asynchronous operations. */ update?: (updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState) => void | boolean; } interface ITelemetryTrace { /** * Trace id */ traceID?: string; /** * Parent id */ parentID?: string; /** * @deprecated Never Used * Trace state */ traceState?: ITraceState; /** * An integer representation of the W3C TraceContext trace-flags. https://www.w3.org/TR/trace-context/#trace-flags */ traceFlags?: number; /** * Name */ name?: string; } interface ITelemetryUnloadState { reason: TelemetryUnloadReason; isAsync: boolean; flushComplete?: boolean; } interface ITelemetryUpdateState { /** * Identifies the reason for the update notification, this is a bitwise numeric value */ reason: TelemetryUpdateReason; /** * This is a new active configuration that should be used */ cfg?: IConfiguration; /** * The detected changes */ oldCfg?: IConfiguration; /** * If this is a configuration update this was the previous configuration that was used */ newConfig?: IConfiguration; /** * Was the new config requested to be merged with the existing config */ merge?: boolean; /** * This holds a collection of plugins that have been added (if the reason identifies that one or more plugins have been added) */ added?: IPlugin[]; /** * This holds a collection of plugins that have been removed (if the reason identifies that one or more plugins have been removed) */ removed?: IPlugin[]; } /** * Identifies frequency of items sent * Default: send data on 28th every 3 month each year */ interface IThrottleInterval { /** * Identifies month interval that items can be sent * For example, if it is set to 2 and start date is in Jan, items will be sent out every two months (Jan, March, May etc.) * If both monthInterval and dayInterval are undefined, it will be set to 3 */ monthInterval?: number; /** * Identifies days Interval from start date that items can be sent * Default: undefined */ dayInterval?: number; /** * Identifies days within each month that items can be sent * If both monthInterval and dayInterval are undefined, it will be default to [28] */ daysOfMonth?: number[]; } /** * Identifies limit number/percentage of items sent per time * If both are provided, minimum number between the two will be used */ interface IThrottleLimit { /** * Identifies sampling percentage of items per time * The percentage is set to 4 decimal places, for example: 1 means 0.0001% * Default: 100 (0.01%) */ samplingRate?: number; /** * Identifies limit number of items per time * Default: 1 */ maxSendNumber?: number; } /** * Identifies object for local storage */ interface IThrottleLocalStorageObj { /** * Identifies start date */ date: Date; /** * Identifies current count */ count: number; /** * identifies previous triggered throttle date */ preTriggerDate?: Date; } /** * Identifies basic config */ interface IThrottleMgrConfig { /** * Identifies if throttle is disabled * Default: false */ disabled?: boolean; /** * Identifies limit number/percentage of items sent per time * Default: sampling percentage 0.01% with one item sent per time */ limit?: IThrottleLimit; /** * Identifies frequency of items sent * Default: send data on 28th every 3 month each year */ interval?: IThrottleInterval; } /** * Identifies throttle result */ interface IThrottleResult { /** * Identifies if items are sent */ isThrottled: boolean; /** * Identifies numbers of items are sent * if isThrottled is false, it will be set to 0 */ throttleNum: number; } /** * A Timer handler which is returned from {@link scheduleTimeout} which contains functions to * cancel or restart (refresh) the timeout function. * * @since 0.4.4 * @group Timer */ interface ITimerHandler { /** * Cancels a timeout that was previously scheduled, after calling this function any previously * scheduled timer will not execute. * @example * ```ts * let theTimer = scheduleTimeout(...); * theTimer.cancel(); * ``` */ cancel(): void; /** * Reschedules the timer to call its callback at the previously specified duration * adjusted to the current time. This is useful for refreshing a timer without allocating * a new JavaScript object. * * Using this on a timer that has already called its callback will reactivate the timer. * Calling on a timer that has not yet executed will just reschedule the current timer. * @example * ```ts * let theTimer = scheduleTimeout(...); * // The timer will be restarted (if already executed) or rescheduled (if it has not yet executed) * theTimer.refresh(); * ``` */ refresh(): ITimerHandler; /** * When called, requests that the event loop not exit so long when the ITimerHandler is active. * Calling timer.ref() multiple times will have no effect. By default, all ITimerHandler objects * will create "ref'ed" instances, making it normally unnecessary to call timer.ref() unless * timer.unref() had been called previously. * @since 0.7.0 * @returns the ITimerHandler instance * @example * ```ts * let theTimer = createTimeout(...); * * // Make sure the timer is referenced (the default) so that the runtime (Node) does not terminate * // if there is a waiting referenced timer. * theTimer.ref(); * ``` */ ref(): this; /** * When called, the any active ITimerHandler instance will not require the event loop to remain * active (Node.js). If there is no other activity keeping the event loop running, the process may * exit before the ITimerHandler instance callback is invoked. Calling timer.unref() multiple times * will have no effect. * @since 0.7.0 * @returns the ITimerHandler instance * @example * ```ts * let theTimer = createTimeout(...); * * // Unreference the timer so that the runtime (Node) may terminate if nothing else is running. * theTimer.unref(); * ``` */ unref(): this; /** * If true, any running referenced `ITimerHandler` instance will keep the Node.js event loop active. * @since 0.7.0 * @example * ```ts * let theTimer = createTimeout(...); * * // Unreference the timer so that the runtime (Node) may terminate if nothing else is running. * theTimer.unref(); * let hasRef = theTimer.hasRef(); // false * * theTimer.ref(); * hasRef = theTimer.hasRef(); // true * ``` */ hasRef(): boolean; /** * Gets or Sets a flag indicating if the underlying timer is currently enabled and running. * Setting the enabled flag to the same as it's current value has no effect, setting to `true` * when already `true` will not {@link ITimerHandler.refresh | refresh}() the timer. * And setting to `false` will {@link ITimerHandler.cancel | cancel}() the timer. * @since 0.8.1 * @example * ```ts * let theTimer = createTimeout(...); * * // Check if enabled * theTimer.enabled; // false * * // Start the timer * theTimer.enabled = true; // Same as calling refresh() * theTimer.enabled; //true * * // Has no effect as it's already running * theTimer.enabled = true; * * // Will refresh / restart the time * theTimer.refresh() * * let theTimer = scheduleTimeout(...); * * // Check if enabled * theTimer.enabled; // true * ``` */ enabled: boolean; } /** * This interface represents the components of a W3C traceparent header */ interface ITraceParent { /** * The version of the definition, this MUST be a string with a length of 2 and only contain lowercase * hexadecimal characters. A value of 'ff' is considered to be an invalid version. */ version: string; /** * This is the ID of the whole trace forest and is used to uniquely identify a distributed trace * through a system. It is represented as a 32-character string of lowercase hexadecimal characters, * for example, 4bf92f3577b34da6a3ce929d0e0e4736. * All characters as zero (00000000000000000000000000000000) is considered an invalid value. */ traceId: string; /** * This is the ID of the current request as known by the caller (in some tracing systems, this is also * known as the parent-id, where a span is the execution of a client request). It is represented as an * 16-character string of lowercase hexadecimal characters, for example, 00f067aa0ba902b7. * All bytes as zero (0000000000000000) is considered an invalid value. */ spanId: string; /** * An 8-bit value of flags that controls tracing such as sampling, trace level, etc. These flags are * recommendations given by the caller rather than strict rules to follow. * As this is a bit field, you cannot interpret flags by decoding the hex value and looking at the resulting * number. For example, a flag 00000001 could be encoded as 01 in hex, or 09 in hex if present with the flag * 00001000. A common mistake in bit fields is forgetting to mask when interpreting flags. */ traceFlags: number; } interface ITraceState { } interface ITraceTelemetry extends IPartC { /** * @description A message string */ message: string; /** * @description Severity level of the logging message used for filtering in the portal */ severityLevel?: SeverityLevel; /** * @description custom defiend iKey */ iKey?: string; } /** * An interface which provides automatic removal during unloading of the component */ interface IUnloadHook { /** * Self remove the referenced component */ rm: () => void; } interface IUser { /** * The telemetry configuration. */ config: any; /** * The user ID. */ id: string; /** * Authenticated user id */ authenticatedId: string; /** * The account ID. */ accountId: string; /** * The account acquisition date. */ accountAcquisitionDate: string; /** * The localId */ localId: string; /** * A flag indicating whether this represents a new user */ isNewUser?: boolean; /** * A flag indicating whether the user cookie has been set */ isUserCookieSet?: boolean; } interface IUserContext extends IUser { setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): void; clearAuthenticatedUserContext(): void; update(userId?: string): void; } interface IWatchDetails { /** * The current config object */ cfg: T; /** * Set the value against the provided config/name with the value, the property * will be converted to be dynamic (if not already) as long as the provided config * is already a tracked dynamic object. * @throws TypeError if the provided config is not a monitored dynamic config */ set: (theConfig: C, name: string, value: V) => V; /** * Set default values for the config if not present. * @param theConfig - The configuration object to set default on (if missing) * @param defaultValues - The default values to apply to the config */ setDf: (theConfig: C, defaultValues: IConfigDefaults) => C; /** * Set this named property of the target as referenced, which will cause any object or array instance * to be updated in-place rather than being entirely replaced. All other values will continue to be replaced. * @returns The referenced properties current value */ ref: (target: C, name: string) => V; /** * Set this named property of the target as read-only, which will block this single named property from * ever being changed for the target instance. * This does NOT freeze or seal the instance, it just stops the direct re-assignment of the named property, * if the value is a non-primitive (ie. an object or array) it's properties will still be mutable. * @returns The referenced properties current value */ rdOnly: (target: C, name: string) => V; } interface IWeb { /** * Browser name, set at ingestion */ browser: string; /** * Browser ver, set at ingestion. */ browserVer: string; /** * Language */ browserLang: string; /** * User consent, populated to properties bag */ userConsent: boolean; /** * Whether event was fired manually, populated to properties bag */ isManual: boolean; /** * Screen resolution, populated to properties bag */ screenRes: string; /** * Current domain. Leverages Window.location.hostname. populated to properties bag */ domain: string; } const LoggingSeverity: EnumValue; type LoggingSeverity = number | eLoggingSeverity; class Metric implements IMetricData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { ver: FieldType; metrics: FieldType; properties: FieldType; }; /** * Schema version */ ver: number; /** * List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. */ metrics: DataPoint[]; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Constructs a new instance of the MetricTelemetry object */ constructor(logger: IDiagnosticLogger, name: string, value: number, count?: number, min?: number, max?: number, stdDev?: number, properties?: any, measurements?: { [key: string]: number; }); } /** * Convert ms to c# time span format */ function msToTimeSpan(totalms: number): string; /** * this is the callback that will be called when the network status changes * @param onlineState - this is the current network running state */ type OfflineCallback = (onlineState: IOfflineState) => void; class PageView implements IPageViewData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { ver: FieldType; name: FieldType; url: FieldType; duration: FieldType; properties: FieldType; measurements: FieldType; id: FieldType; }; /** * Schema version */ ver: number; /** * Event name. Keep it low cardinality to allow proper grouping and useful metrics. */ name: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Request URL with all query string parameters */ url: string; /** * Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */ duration: string; /** * Identifier of a page view instance. Used for correlation between page view and other telemetry items. */ id: string; /** * Constructs a new instance of the PageEventTelemetry object */ constructor(logger: IDiagnosticLogger, name?: string, url?: string, durationMs?: number, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }, id?: string); } class PageViewPerformance implements IPageViewPerfData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { ver: FieldType; name: FieldType; url: FieldType; duration: FieldType; perfTotal: FieldType; networkConnect: FieldType; sentRequest: FieldType; receivedResponse: FieldType; domProcessing: FieldType; properties: FieldType; measurements: FieldType; }; /** * Schema version */ ver: number; /** * Event name. Keep it low cardinality to allow proper grouping and useful metrics. */ name: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Request URL with all query string parameters */ url: string; /** * Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */ duration: string; /** * Identifier of a page view instance. Used for correlation between page view and other telemetry items. */ id: string; /** * Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ perfTotal: string; /** * Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ networkConnect: string; /** * Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ sentRequest: string; /** * Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ receivedResponse: string; /** * DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ domProcessing: string; /** * Constructs a new instance of the PageEventTelemetry object */ constructor(logger: IDiagnosticLogger, name: string, url: string, unused: number, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }, cs4BaseData?: IPageViewPerformanceTelemetry); } function parseConnectionString(connectionString?: string): ConnectionString; /** * Attempt to parse the provided string as a W3C TraceParent header value (https://www.w3.org/TR/trace-context/#traceparent-header) * * @param value - The value to be parsed * @param selectIdx - If the found value is comma separated which is the preferred entry to select, defaults to the first * @returns */ function parseTraceParent(value: string, selectIdx?: number): ITraceParent; const ProcessLegacy = "ProcessLegacy"; const PropertiesPluginIdentifier = "AppInsightsPropertiesPlugin"; /** * This defines the handler function for when a promise is rejected. * @param value - This is the value passed as part of resolving the Promise * @return This may return a value, another Promise or void. @see {@link https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html#then | IPromise.then} for how the value is handled. */ type RejectedPromiseHandler = (((reason: any) => T | IPromise | PromiseLike) | undefined | null); class RemoteDependencyData implements IRemoteDependencyData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { id: FieldType; ver: FieldType; name: FieldType; resultCode: FieldType; duration: FieldType; success: FieldType; data: FieldType; target: FieldType; type: FieldType; properties: FieldType; measurements: FieldType; kind: FieldType; value: FieldType; count: FieldType; min: FieldType; max: FieldType; stdDev: FieldType; dependencyKind: FieldType; dependencySource: FieldType; commandName: FieldType; dependencyTypeName: FieldType; }; /** * Schema version */ ver: number; /** * Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. */ name: string; /** * Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. */ id: string; /** * Result code of a dependency call. Examples are SQL error code and HTTP status code. */ resultCode: string; /** * Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */ duration: string; /** * Indication of successful or unsuccessful call. */ success: boolean; /** * Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters. */ data: string; /** * Target site of a dependency call. Examples are server name, host address. */ target: string; /** * Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. */ type: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Constructs a new instance of the RemoteDependencyData object */ constructor(logger: IDiagnosticLogger, id: string, absoluteUrl: string, commandName: string, value: number, success: boolean, resultCode: number, method?: string, requestAPI?: string, correlationContext?: string, properties?: Object, measurements?: Object); } const RequestHeaders: IRequestHeaders & { requestContextHeader: "Request-Context"; requestContextTargetKey: "appId"; requestContextAppIdFormat: "appId=cid-v1:"; requestIdHeader: "Request-Id"; traceParentHeader: "traceparent"; traceStateHeader: "tracestate"; sdkContextHeader: "Sdk-Context"; sdkContextHeaderAppIdRequest: "appId"; requestContextHeaderLowerCase: "request-context"; 0: "Request-Context"; 1: "appId"; 2: "appId=cid-v1:"; 3: "Request-Id"; 4: "traceparent"; 5: "tracestate"; 6: "Sdk-Context"; 7: "appId"; 8: "request-context"; }; /** * This defines the handler function for when a promise is resolved. * @param value - This is the value passed as part of resolving the Promise * @return This may return a value, another Promise or void. @see {@link https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html#then | IPromise.then} for how the value is handled. */ type ResolvedPromiseHandler = (((value: T) => TResult1 | IPromise | PromiseLike) | undefined | null); const SampleRate = "sampleRate"; interface scriptsInfo { url: string; crossOrigin?: string; async?: boolean; defer?: boolean; referrerPolicy?: string; } /** * The EventsDiscardedReason enumeration contains a set of values that specify the reason for discarding an event. */ const enum SendRequestReason { /** * No specific reason was specified */ Undefined = 0, /** * Events are being sent based on the normal event schedule / timer. */ NormalSchedule = 1, /** * A manual flush request was received */ ManualFlush = 1, /** * Unload event is being processed */ Unload = 2, /** * The event(s) being sent are sync events */ SyncEvent = 3, /** * The Channel was resumed */ Resumed = 4, /** * The event(s) being sent as a retry */ Retry = 5, /** * The SDK is unloading */ SdkUnload = 6, /** * Maximum batch size would be exceeded */ MaxBatchSize = 10, /** * The Maximum number of events have already been queued */ MaxQueuedEvents = 20 } /** * Defines the level of severity for the event. */ const SeverityLevel: EnumValue; type SeverityLevel = number | eSeverityLevel; function stringToBoolOrDefault(str: any, defaultValue?: boolean): boolean; const strNotSpecified = "not_specified"; interface Tags { [key: string]: any; } type TelemetryInitializerFunction = (item: T) => boolean | void; class TelemetryItemCreator { /** * Create a telemetry item that the 1DS channel understands * @param item - domain specific properties; part B * @param baseType - telemetry item type. ie PageViewData * @param envelopeName - Name of the envelope (e.g., Microsoft.ApplicationInsights.[instrumentationKey].PageView). * @param customProperties - user defined custom properties; part C * @param systemProperties - system properties that are added to the context; part A * @returns ITelemetryItem that is sent to channel */ static create: typeof createTelemetryItem; } /** * The TelemetryUnloadReason enumeration contains the possible reasons for why a plugin is being unloaded / torndown(). */ const enum TelemetryUnloadReason { /** * Teardown has been called without any context. */ ManualTeardown = 0, /** * Just this plugin is being removed */ PluginUnload = 1, /** * This instance of the plugin is being removed and replaced */ PluginReplace = 2, /** * The entire SDK is being unloaded */ SdkUnload = 50 } /** * The TelemetryUpdateReason enumeration contains a set of bit-wise values that specify the reason for update request. */ const enum TelemetryUpdateReason { /** * Unknown. */ Unknown = 0, /** * The configuration has ben updated or changed */ ConfigurationChanged = 1, /** * One or more plugins have been added */ PluginAdded = 16, /** * One or more plugins have been removed */ PluginRemoved = 32 } class ThrottleMgr { canThrottle: (msgId: _eInternalMessageId | number) => boolean; sendMessage: (msgId: _eInternalMessageId, message: string, severity?: eLoggingSeverity) => IThrottleResult | null; getConfig: () => IThrottleMgrConfig; isTriggered: (msgId: _eInternalMessageId | number) => boolean; isReady: () => boolean; onReadyState: (isReady?: boolean, flushAll?: boolean) => boolean; flush: (msgId: _eInternalMessageId | number) => boolean; flushAll: () => boolean; config: IThrottleMgrConfig; constructor(core: IAppInsightsCore, namePrefix?: string); } class Trace implements IMessageData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { ver: FieldType; message: FieldType; severityLevel: FieldType; properties: FieldType; }; /** * Schema version */ ver: number; /** * Trace message */ message: string; /** * Trace severity level. */ severityLevel: SeverityLevel; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Constructs a new instance of the TraceTelemetry object */ constructor(logger: IDiagnosticLogger, message: string, severityLevel?: SeverityLevel, properties?: any, measurements?: { [key: string]: number; }); } type UnloadHandler = (itemCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) => void; function urlGetAbsoluteUrl(url: string): string; function urlGetCompleteUrl(method: string, absoluteUrl: string): string; function urlGetPathName(url: string): string; function urlParseFullHost(url: string, inclPort?: boolean): string; function urlParseHost(url: string, inclPort?: boolean): string; function urlParseUrl(url: string): HTMLAnchorElement; /** * Returns whether LocalStorage can be used, if the reset parameter is passed a true this will override * any previous disable calls. * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available */ function utlCanUseLocalStorage(reset?: boolean): boolean; function utlCanUseSessionStorage(reset?: boolean): boolean; /** * Disables the global SDK usage of local or session storage if available */ function utlDisableStorage(): void; /** * Re-enables the global SDK usage of local or session storage if available */ function utlEnableStorage(): void; function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string; function utlGetSessionStorage(logger: IDiagnosticLogger, name: string): string; function utlGetSessionStorageKeys(): string[]; function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string): boolean; function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boolean; function utlSetLocalStorage(logger: IDiagnosticLogger, name: string, data: string): boolean; function utlSetSessionStorage(logger: IDiagnosticLogger, name: string, data: string): boolean; function utlSetStoragePrefix(storagePrefix: string): void; type WatcherFunction = (details: IWatchDetails) => void; }