UNPKG

@microsoft/1ds-post-js

Version:

Microsoft Application Insights JavaScript SDK - 1ds-post-channel-js

938 lines (916 loc) 134 kB
/* * 1DS JS SDK Post Channel, 4.3.9 * Copyright (c) Microsoft and contributors. All rights reserved. * * Microsoft Application Insights Team * https://github.com/microsoft/ApplicationInsights-JS#readme */ declare namespace oneDS { /** * BaseTelemetryPlugin provides a basic implementation of the ITelemetryPlugin interface so that plugins * can avoid implementation the same set of boiler plate code as well as provide a base * implementation so that new default implementations can be added without breaking all plugins. */ abstract class BaseTelemetryPlugin implements ITelemetryPlugin { identifier: string; version?: string; /** * Holds the core instance that was used during initialization */ core: IAppInsightsCore; priority: number; /** * 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) */ processNext: (env: ITelemetryItem, itemCtx: IProcessTelemetryContext) => void; /** * Set next extension for telemetry processing */ setNextPlugin: (next: ITelemetryPlugin | ITelemetryPluginChain) => void; /** * Returns the current diagnostic logger that can be used to log issues, if no logger is currently * assigned a new default one will be created and returned. */ diagLog: (itemCtx?: IProcessTelemetryContext) => IDiagnosticLogger; /** * Returns whether the plugin has been initialized */ isInitialized: () => boolean; /** * Helper to return the current IProcessTelemetryContext, if the passed argument exists this just * returns that value (helps with minification for callers), otherwise it will return the configured * context or a temporary one. * @param currentCtx - [Optional] The current execution context */ protected _getTelCtx: (currentCtx?: IProcessTelemetryContext) => IProcessTelemetryContext; /** * Internal helper to allow setting of the internal initialized setting for inherited instances and unit testing */ protected setInitialized: (isInitialized: boolean) => void; /** * Teardown / Unload hook to allow implementations to perform some additional unload operations before the BaseTelemetryPlugin * finishes it's removal. * @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. * @param asyncCallback - An optional callback that the plugin must call if it returns true to inform the caller that it has completed any async unload/teardown operations. * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations. */ protected _doTeardown?: (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState, asyncCallback?: () => void) => void | boolean; /** * Extension hook to allow implementations to perform some additional update operations before the BaseTelemetryPlugin finishes it's removal * @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. * @param asyncCallback - An optional callback that the plugin must call if it returns true to inform the caller that it has completed any async update operations. * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations. */ protected _doUpdate?: (updateCtx?: IProcessTelemetryUpdateContext, updateState?: ITelemetryUpdateState, asyncCallback?: () => void) => void | boolean; /** * Exposes the underlying unload hook container instance for this extension to allow it to be passed down to any sub components of the class. * This should NEVER be exposed or called publically as it's scope is for internal use by BaseTelemetryPlugin and any derived class (which is why * it's scoped as protected) */ protected readonly _unloadHooks: IUnloadHookContainer; constructor(); initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain): 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; abstract processTelemetry(env: ITelemetryItem, itemCtx?: IProcessTelemetryContext): void; /** * The the plugin should re-evaluate configuration and update any cached configuration settings. * @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; /** * Add an unload handler that will be called when the SDK is being unloaded * @param handler - the handler */ protected _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 */ protected _addHook(hooks: IUnloadHook | IUnloadHook[] | Iterator<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>): void; } /** * Best Effort. RealTime Latency events are sent every 9 sec and * Normal Latency events are sent every 18 sec. */ const BE_PROFILE = "BEST_EFFORT"; 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 _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<E = any> = { 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<E = any> = EnumCls<E>; 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 } type FieldValueSanitizerFunc = (details: IFieldSanitizerDetails) => IEventProperty | null; const enum FieldValueSanitizerType { NotSet = 0, String = 1, Number = 2, Boolean = 3, Object = 4, Array = 4096, EventProperty = 8192 } type FieldValueSanitizerTypes = string | number | boolean | object | string[] | number[] | boolean[] | IEventProperty; /** * This defines the handler function that is called via the finally when the promise is resolved or rejected */ type FinallyPromiseHandler = (() => void) | undefined | null; interface IAppInsightsCore<CfgType extends IConfiguration = IConfiguration> 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<ITelemetryUnloadState>; /** * Find and return the (first) plugin with the specified identifier if present */ getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T>; /** * 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<T extends IPlugin = ITelemetryPlugin>(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<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>): 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<CfgType>): 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 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: <T>(identifier: string, defaultValue?: IConfigDefaults<T>) => 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: <T extends ITelemetryPlugin = ITelemetryPlugin>(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; } /** * The IChannelConfiguration interface holds the configuration details passed to Post module. */ interface IChannelConfiguration { /** * [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] Sets the maximum number of immediate latency events that will be cached in memory before the SDK starts to drop other * immediate events only, does not drop normal and real time latency events as immediate events have their own internal queue. Under * normal situations immediate events are scheduled to be sent in the next Javascript execution cycle, so the typically number of * immediate events is small (~1), the only time more than one event may be present is when the channel is paused or immediate send * is disabled (via manual transmit profile). By default max number of events is 500 and the default transmit time is 0ms. */ immediateEventLimit?: number; /** * [Optional] If defined, when the number of queued events reaches or exceeded this limit this will cause the queue to be immediately * flushed rather than waiting for the normal timers. Defaults to undefined. */ autoFlushEventsLimit?: number; /** * [Optional] If defined allows you to disable the auto batch (iKey set of requests) flushing logic. This is in addition to the * default transmission profile timers, autoFlushEventsLimit and eventsLimitInMem config values. */ disableAutoBatchFlushLimit?: boolean; /** * [Optional] Sets the record and request size limit in bytes for serializer. * Default for record size (sync) is 65000, record size (async) is 2000000. * Default for request size (sync) is 65000, request size (async) is 3145728. * @since 3.3.7 */ requestLimit?: IRequestSizeLimit; /** * [Optional] Sets the limit number of events per batch. * Default is 500 * @since 3.3.7 */ maxEvtPerBatch?: number; /** * [Optional] The HTTP override that should be used to send requests, as an IXHROverride object. * By default during the unload of a page or if the event specifies that it wants to use sendBeacon() or sync fetch (with keep-alive), * this override will NOT be called. You can now change this behavior by enabling the 'alwaysUseXhrOverride' configuration value. * The payload data (first argument) now also includes any configured 'timeout' (defaults to undefined) and whether you should avoid * creating any synchronous XHR requests 'disableXhrSync' (defaults to false/undefined) */ httpXHROverride?: IXHROverride; /** * Override for Instrumentation key */ overrideInstrumentationKey?: string; /** * Override for Endpoint where telemetry data is sent */ overrideEndpointUrl?: string; /** * The master off switch. Do not send any data if set to TRUE */ disableTelemetry?: boolean; /** * MC1 and MS0 cookies will not be returned from Collector endpoint. */ ignoreMc1Ms0CookieProcessing?: boolean; /** * Override for setTimeout */ setTimeoutOverride?: typeof setTimeout; /** * Override for clearTimeout */ clearTimeoutOverride?: typeof clearTimeout; /** * [Optional] POST channel preprocessing function. Can be used to gzip the payload before transmission and to set the appropriate * Content-Encoding header. The preprocessor is explicitly not called during teardown when using the sendBeacon() API. */ payloadPreprocessor?: PayloadPreprocessorFunction; /** * [Optional] POST channel listener function, used for enabling logging or reporting (RemoteDDVChannel) of the payload that is being sent. */ payloadListener?: PayloadListenerFunction; /** * [Optional] By default additional timing metrics details are added to each event after they are sent to allow you to review how long it took * to create serialized request. As not all implementations require this level of detail and it's now possible to get the same metrics via * the IPerfManager and IPerfEvent we are enabling these details to be disabled. Default value is false to retain the previous behavior, * if you are not using these metrics and performance is a concern then it is recommended to set this value to true. */ disableEventTimings?: boolean; /** * [Optional] The value sanitizer to use while constructing the envelope. */ valueSanitizer?: IValueSanitizer; /** * [Optional] During serialization, when an object is identified, should the object be serialized by JSON.stringify(theObject); (when true) otherwise by theObject.toString(). * Defaults to false */ stringifyObjects?: boolean; /** * [Optional] Enables support for objects with compound keys which indirectly represent an object where the "key" of the object contains a "." as part of it's name. * @example * ```typescript * event: { "somedata.embeddedvalue": 123 } * ``` */ enableCompoundKey?: boolean; /** * [Optional] Switch to disable the v8 optimizeObject() calls used to provide better serialization performance. Defaults to false. */ disableOptimizeObj?: boolean; /** * [Optional] By default a "Cache-Control" header will be added to the outbound payloads with the value "no-cache, no-store", this is to * avoid instances where Chrome can "Stall" requests which use the same outbound URL. */ /** * [Optional] Either an array or single value identifying the requested TransportType type that should be used. * This is used during initialization to identify the requested send transport, it will be ignored if a httpXHROverride is provided. */ transports?: number | number[]; /** * [Optional] Either an array or single value identifying the requested TransportType type(s) that should be used during unload or events * marked as sendBeacon. This is used during initialization to identify the requested send transport, it will be ignored if a httpXHROverride * is provided and alwaysUseXhrOverride is true. */ unloadTransports?: number | number[]; /** * [Optional] A flag to enable or disable the usage of the sendBeacon() API (if available). If running on ReactNative this defaults * to `false` for all other cases it defaults to `true`. */ useSendBeacon?: boolean; /** * [Optional] A flag to disable the usage of the [fetch with keep-alive](https://javascript.info/fetch-api#keepalive) support. */ disableFetchKeepAlive?: boolean; /** * [Optional] Avoid adding request headers to the outgoing request that would cause a pre-flight (OPTIONS) request to be sent for each request. * This currently defaults to false. This is changed as the collector enables Access-Control-Max-Age to allow the browser to better cache any * previous OPTIONS response. Hence, we moved some of the current dynamic values sent on the query string to a header. */ avoidOptions?: boolean; /** * [Optional] Specify a timeout (in ms) to apply to requests when sending requests using XHR, XDR or fetch requests. Defaults to undefined * and therefore the runtime defaults (normally zero for browser environments) */ xhrTimeout?: number; /** * [Optional] When using Xhr for sending requests disable sending as synchronous during unload or synchronous flush. * You should enable this feature for IE (when there is no sendBeacon() or fetch (with keep-alive)) and you have clients * that end up blocking the UI during page unloading. This will cause ALL XHR requests to be sent asynchronously which * during page unload may result in the lose of telemetry. */ disableXhrSync?: boolean; /** * [Optional] By default during unload (or when you specify to use sendBeacon() or sync fetch (with keep-alive) for an event) the SDK * ignores any provided httpXhrOverride and attempts to use sendBeacon() or fetch(with keep-alive) when they are available. * When this configuration option is true any provided httpXhrOverride will always be used, so any provided httpXhrOverride will * also need to "handle" the synchronous unload scenario. */ alwaysUseXhrOverride?: boolean; /** * [Optional] Identifies the number of times any single event will be retried if it receives a failed (retirable) response, this * causes the event to be internally "requeued" and resent in the next batch. As each normal batched send request is retried at * least once before starting to increase the internal backoff send interval, normally batched events will generally be attempted * the next nearest even number of times. This means that the total number of actual send attempts will almost always be even * (setting to 5 will cause 6 requests), unless using manual synchronous flushing (calling flush(false)) which is not subject to * request level retry attempts. * Defaults to 6 times. */ maxEventRetryAttempts?: number; /** * [Optional] Identifies the number of times any single event will be retried if it receives a failed (retriable) response as part * of processing / flushing events once a page unload state has been detected, this causes the event to be internally "requeued" * and resent in the next batch, which during page unload. Unlike the normal batching process, send requests are never retried, * so the value listed here is always the maximum number of attempts for any single event. * Defaults to 2 times. * Notes: * The SDK by default will use the sendBeacon() API if it exists which is treated as a fire and forget successful response, so for * environments that support or supply this API the events won't be retried (because they will be deeded to be successfully sent). * When an environment (IE) doesn't support sendBeacon(), this will cause multiple synchronous (by default) XMLHttpRequests to be sent, * which will block the UI until a response is received. You can disable ALL synchronous XHR requests by setting the 'disableXhrSync' * configuration setting and/or changing this value to 0 or 1. */ maxUnloadEventRetryAttempts?: number; /** * [Optional] flag to indicate whether the sendBeacon and fetch (with keep-alive flag) should add the "NoResponseBody" query string * value to indicate that the server should return a 204 for successful requests. Defaults to true */ addNoResponse?: boolean; /** * :warning: DO NOT USE THIS FLAG UNLESS YOU KNOW THAT PII DATA WILL NEVER BE INCLUDED IN THE EVENT! * * [Optional] Flag to indicate whether the SDK should include the common schema metadata in the payload. Defaults to true. * This flag is only applicable to the POST channel and will cause the SDK to exclude the common schema metadata from the payload, * while this will reduce the size of the payload, also means that the data marked as PII will not be processed as PII by the backend * and will not be included in the PII data purge process. * @since 4.1.0 */ excludeCsMetaData?: boolean; /** * [Optional] Specify whether cross-site Access-Control fetch requests should include credentials such as cookies, * authentication headers, or TLS client certificates. * * Possible values: * - "omit": never send credentials in the request or include credentials in the response. * - "include": always include credentials, even cross-origin. * - "same-origin": only send and include credentials for same-origin requests. * * If not set, the default value will be "include". * * For more information, refer to: * - [Fetch API - Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#including_credentials) * @since 3.3.1 */ fetchCredentials?: RequestCredentials; } /** * 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 async - 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 async is true. */ flush?(async: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason): boolean | void | IPromise<boolean>; /** * Get offline support * @returns IInternalOfflineSupport */ getOfflineSupport?: () => IInternalOfflineSupport; } /** * The type to identify whether the default value should be applied in preference to the provided value. */ type IConfigCheckFn<V> = (value: V) => boolean; /** * The default values with a check function */ interface IConfigDefaultCheck<T, V, C = IConfiguration> { /** * Callback function to check if the user-supplied value is valid, if not the default will be applied */ isVal?: IConfigCheckFn<V>; /** * Optional function to allow converting and setting of the default value */ set?: IConfigSetFn<T, V>; /** * The default value to apply if the user-supplied value is not valid */ v?: V | IConfigDefaults<V, T>; /** * 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<keyof T | keyof C>; /** * 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<T, C = IConfiguration> = { [key in keyof T]: T[key] | IConfigDefaultCheck<T, T[key], C>; }; /** * The type which identifies the function use to validate the user supplied value */ type IConfigSetFn<T, V> = (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<string>; /** * Connection string of resource. Either this or instrumentationKey must be specified. */ connectionString?: string | IPromise<string>; /** * 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<string>; /** * 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;