/* * Microsoft Application Insights JavaScript SDK Channel, 3.4.1 * Copyright (c) Microsoft and contributors. All rights reserved. * * Microsoft Application Insights Team * https://github.com/microsoft/ApplicationInsights-JS#readme */ declare namespace ApplicationInsights { class ArraySendBuffer extends BaseSendBuffer implements ISendBuffer { constructor(logger: IDiagnosticLogger, config: ISenderConfig); markAsSent(payload: IInternalStorageItem[]): void; clearSent(payload: IInternalStorageItem[]): void; } abstract class BaseSendBuffer { protected _get: () => IInternalStorageItem[]; protected _set: (buffer: IInternalStorageItem[]) => IInternalStorageItem[]; constructor(logger: IDiagnosticLogger, config: ISenderConfig); enqueue(payload: IInternalStorageItem): void; count(): number; size(): number; clear(): void; getItems(): IInternalStorageItem[]; batchPayloads(payload: IInternalStorageItem[]): string; createNew(newLogger?: IDiagnosticLogger, newConfig?: ISenderConfig, canUseSessionStorage?: boolean): ArraySendBuffer | SessionStorageSendBuffer; } /** * 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, 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; /** * 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 | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator): void; } const DistributedTracingModes: EnumValue; type DistributedTracingModes = number | eDistributedTracingModes; 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 for attribute change operation types */ const enum eAttributeChangeOp { /** * Clear operation - clearing all attributes */ Clear = 0, /** * Set operation - setting an attribute value (generic) */ Set = 1, /** * Add operation - adding a new attribute that didn't exist before */ Add = 2, /** * Delete operation - deleting an attribute */ Delete = 3, /** * Dropped attributes - attributes that were dropped due to size limits */ DroppedAttributes = 4 } /** * Identifies the source of an attribute value in iterator operations * @since 3.4.0 */ const enum eAttributeFilter { /** * The attribute exists local to the current container instance */ Local = 0, /** * The attribute does not exist locally and is inherited from a parent container or attributes object */ Inherited = 1, /** * The attribute exists or has been deleted locally (only) to the current container instance */ LocalOrDeleted = 2 } const enum eDistributedTracingModes { /** * Send only the legacy Application Insights correlation headers * * Headers Sent: * - `Request-Id` (Legacy Application Insights header for older Server side SDKs) * * Config Decimal Value: `0` (Zero) */ AI = 0, /** * (Default) Send both W3C Trace parent header and back-compatibility Application Insights headers * - `Request-Id` * - [`traceparent`](https://www.w3.org/TR/trace-context/#traceparent-header) * * Config Decimal Value: `1` (One) */ AI_AND_W3C = 1, /** * Send Only the W3C Trace parent header * * Headers Sent: * - [`traceparent`](https://www.w3.org/TR/trace-context/#traceparent-header) * * Config Decimal Value: `2` (Two) */ W3C = 2, /** * @internal * Bitwise mask used to separate the base distributed tracing mode from the additional optional * tracing modes. * @since 3.4.0 */ _BaseMask = 15, /** * @internal * Enabling this bit will send the W3C Trace State header, it is not intended to be used directly * or on its own. The code may assume that if this bit is set, then the W3C Trace Context headers * will also be included. * * Config Decimal Value: `16` (Sixteen in decimal) * @since 3.4.0 */ _W3CTraceState = 16, /** * Send all of the W3C Trace Context headers and the W3C Trace State headers and back-compatibility * Application Insights headers. * * Currently sent headers: * - `Request-Id` (Legacy Application Insights header for older Server side SDKs) * - [`traceparent`](https://www.w3.org/TR/trace-context/#traceparent-header) * - [`tracestate`](https://www.w3.org/TR/trace-context/#tracestate-header) * * NOTE!: Additional headers may be added as part of a future update should the W3C Trace Context specification be updated * to include additional headers. * * Config Decimal Value: `17` (Seventeen in decimal) * @since 3.4.0 */ AI_AND_W3C_TRACE = 17, /** * Send all of the W3C Trace Context headers and the W3C Trace State headers. * * Currently sent headers: * - [`traceparent`](https://www.w3.org/TR/trace-context/#traceparent-header) * - [`tracestate`](https://www.w3.org/TR/trace-context/#tracestate-header) * * NOTE!: Additional headers may be added as part of a future update should the W3C Trace Context specification be updated * to include additional headers. * * Config Decimal Value: `18` (Eighteen in decimal) * @since 3.4.0 */ W3C_TRACE = 18 } 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, AttributeError = 115, SpanError = 116, TraceError = 117, NotImplementedError = 118, VersionMismatch = 119 } 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; /** * This is the enum for the different network states current ai is experiencing */ const enum eOfflineValue { Unknown = 0, Online = 1, Offline = 2 } /** * The defined set of Span Kinds as defined by the OpenTelemetry. */ const enum eOTelSpanKind { /** Default value. Indicates that the span is used internally. */ INTERNAL = 0, /** * Indicates that the span covers server-side handling of an RPC or other * remote request. */ SERVER = 1, /** * Indicates that the span covers the client-side wrapper around an RPC or * other remote request. */ CLIENT = 2, /** * Indicates that the span describes producer sending a message to a * broker. Unlike client and server, there is no direct critical path latency * relationship between producer and consumer spans. */ PRODUCER = 3, /** * Indicates that the span describes consumer receiving a message from a * broker. Unlike client and server, there is no direct critical path latency * relationship between producer and consumer spans. */ CONSUMER = 4 } /** * An enumeration of status codes, matching the OpenTelemetry specification. * * @since 3.4.0 */ const enum eOTelSpanStatusCode { /** * The default status. */ UNSET = 0, /** * The operation has been validated by an Application developer or * Operator to have completed successfully. */ OK = 1, /** * The operation contains an error. */ ERROR = 2 } /** * Controls how the SDK should look for trace headers (traceparent/tracestate) from the initial page load * The values are bitwise OR'd together to allow for multiple values to be set at once. * @since 3.4.0 */ const enum eTraceHeadersMode { /** * Don't look for any trace headers */ None = 0, /** * Look for traceparent header/meta tag */ TraceParent = 1, /** * Look for tracestate header/meta tag */ TraceState = 2, /** * Look for both traceparent and tracestate headers/meta tags */ All = 3 } /** * Controls how the user can configure which parts of the URL should be redacted. Example, certain query parameters, username and password, etc. */ const enum eUrlRedactionOptions { /** * The default value, will redact the username and password as well as the default set of query parameters */ true = 1, /** * Does not redact username and password or any query parameters, the URL will be left as is. Note: this is not recommended as it may lead * to sensitive data being sent in clear text. */ false = 2, /** * This will append any additional queryParams that the user has provided through redactQueryParams config to the default set i.e to * @defaultValue ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature"]. */ appendToDefault = 3, /** * This will replace the default set of query parameters to redact with the query parameters defined in redactQueryParams config, if provided by the user. */ replaceDefault = 4, /** * This will redact username and password in the URL but will not redact any query parameters, even those in the default set. */ usernamePasswordOnly = 5, /** * This will only redact the query parameter in the default set of query parameters to redact. It will not redact username and password. */ queryParamsOnly = 6 } 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; interface IAppInsightsCore extends IPerfManagerProvider, ITraceHost { /** * 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; /** * Set the trace provider for creating spans. * This allows different SKUs to provide their own span implementations. * * @param provider - The trace provider to use for span creation * @since 3.4.0 */ setTraceProvider(provider: ICachedValue): 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; } /** * Information about what changed in an attribute container */ interface IAttributeChangeInfo { /** * The Id of the container that is initiated the change (not the immediate sender -- which is always the parent) * As children only receive listener notifications from their parent in reaction to both changes * they make and any changes they receive from their parent */ frm: string; /** * Operation type that occurred */ op: eAttributeChangeOp; /** * The key that was changed (only present for 'set' operations) */ k?: string; /** * The old value (only present for 'set' operations when replacing existing value) */ prev?: V; /** * The new value (only present for 'set' operations) */ val?: V; } /** * Interface for an attribute container * @since 3.4.0 */ interface IAttributeContainer { /** * Unique identifier for the attribute container */ readonly id: string; /** * The number of attributes that have been set * @returns The number of attributes that have been set */ readonly size: number; /** * The number of attributes that were dropped due to the attribute limit being reached * @returns The number of attributes that were dropped due to the attribute limit being reached */ readonly droppedAttributes: number; /** * Return a snapshot of the current attributes, including inherited ones. * This value is read-only and reflects the state of the attributes at the time of access, * and the returned instance will not change if any attributes are modified later, you will need * to access the attributes property again to get the latest state. * * Note: As this causes a snapshot to be taken, it is an expensive operation as it enumerates all * attributes, so you SHOULD use this property sparingly. * @returns A read-only snapshot of the current attributes */ readonly attributes: IOTelAttributes; /** * Clear all existing attributes from the container, this will also remove any inherited attributes * from this instance only (it will not change the inherited attributes / container(s)) */ clear: () => void; /** * Get the value of an attribute by key * @param key - The attribute key to retrieve * @param source - Optional filter to only check attributes from a specific source (Local or Inherited) * @returns The attribute value if found, undefined otherwise */ get: (key: string, source?: eAttributeFilter) => V | undefined; /** * Check if an attribute exists by key * @param key - The attribute key to check * @param source - Optional filter to only check attributes from a specific source (Local or Inherited) * @returns True if the attribute exists, false otherwise */ has: (key: string, source?: eAttributeFilter) => boolean; /** * Set the value of an attribute by key on this instance. * @param key - The attribute key to set * @param value - The value to assign to the named attribute * @returns true if the value was successfully set / replaced */ set: (key: string, value: V) => boolean; /** * Delete an existing attribute, if the key doesn't exist this will return false. If the key does * exist then it will be removed from this instance and any inherited value will be hidden (even if * the inherited value changes) * @param key - The attribute key to delete * @returns True if the attribute was deleted, false if it didn't exist (which includes if it has already been deleted) */ del: (key: string) => boolean; /** * The keys() method returns a new iterator object that contains the existing keys for each element * in this attribute container. It will return all locally set keys first and then the inherited keys. * When a key exists in both the local and inherited attributes, only the local key will be returned. * If the key has been deleted locally, it will not be included in the iterator. * @returns An iterator over the keys of the attribute container */ keys: () => Iterator; /** * The entries() method of returns a new iterator object that contains the [key, value, source?] tuples for * each attribute, it returns all existing attributes of this instance including all inherited ones. If the * same key exists in both the local and inherited attributes, only the first (non-deleted) tuple will be returned. * If the key has been deleted, it will not be included in the iterator. * * The source value of the tuple identifies the origin of the attribute (Local or Inherited). * @returns An iterator over the entries of the attribute container */ entries: () => Iterator<[string, V, eAttributeFilter]>; /** * The forEach() method of executes a provided function once per each key/value pair in this attribute container, * it will process all local attributes first, then the inherited attributes. If the same key exists in both the * local and inherited attributes, only the first (non-deleted) key/value pair will be processed. * If a key has been deleted, it will not be included in the set of processed key/value pairs. * @param callback - The function to execute for each key/value pair * @param thisArg - Optional value to use as `this` when executing `callback` */ forEach: (callback: (key: string, value: V, source?: eAttributeFilter) => void, thisArg?: any) => void; /** * The values() method returns a new iterator instance that contains the values for each element in this * attribute container. It will return all locally set values first and then the inherited values. If the * same key is present in both the local or inherited attributes only the first (non-deleted) value will be * returned. If a key has been deleted, it will not be included in the iterator. * @returns An iterator over the values of the attribute container */ values: () => Iterator; /** * Register a callback listener for any attribute changes, this will include local and inherited changes. * @param callback - Function to be called when attributes change, receives change information * @returns IUnloadHook instance with rm() function to remove this listener, once called it will never be invoked again */ listen: (callback: (changeInfo: IAttributeChangeInfo) => void) => IUnloadHook; /** * Create a child attribute container that inherits from this one, optionally taking a snapshot * so that any future changes to the parent container do not affect the child container. * The child will use all of the configuration from the parent container. * @param name - Optional name for the child container * @param snapshot - If true, the child container will be a snapshot of the current state * @returns A new attribute container instance */ child: (name?: string, snapshot?: boolean) => IAttributeContainer; } interface IBackendResponse { /** * Number of items received by the backend */ readonly itemsReceived: number; /** * Number of items succesfuly accepted by the backend */ readonly itemsAccepted: number; /** * List of errors for items which were not accepted */ readonly errors: IResponseError[]; /** * App id returned by the backend - not necessary returned, but we don't need it with each response. */ readonly appId?: 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 configuration * @param identifier - The named extension identifier * @param defaultValue - The default value(s) to return if no defined config exists * @param rootOnly - If true, only the look for the configuration in the top level and not in the "extensionConfig" */ getExtCfg: (identifier: string, defaultValue?: IConfigDefaults, rootOnly?: boolean) => 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; } /** * A generic interface for holding a cached value * @since 0.10.5 * @group Helpers * @group Cache * @typeParam T - The type of the value to be cached * @example * ```ts * let cachedValue: ICachedValue = { * v: "some value" * }; * ``` */ interface ICachedValue { /** * Returns the current cached value */ v: T; /** * Returns the current cached value */ toJSON(): T; } /** * 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 extends IOTelConfig { /** * 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 redaction for query parameters and username/password. * @defaultValue true */ redactUrls?: UrlRedactionOptions; /** * [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[]; /** * [Optional] Controls if the SDK should look for the `traceparent` and/or `tracestate` values from * the service timing headers or meta tags from the initial page load. * @defaultValue eTraceHeadersMode.All */ traceHdrMode?: eTraceHeadersMode; } 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 ICustomProperties { [key: string]: any; } interface IDiagnosticLogger { /** * 0: OFF * 1: only critical (default) * 2: critical + info */ consoleLoggingLevel: () => number; /** * The internal logging queue */ queue: IInternalLogMessage[]; /** * 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: IInternalLogMessage): 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; /** * A flag that indicates whether this logger is in debug (throw real exceptions) mode */ readonly dbgMode?: boolean; } interface IDistributedTraceContext extends IDistributedTraceInit { /** * Returns the current name of the page */ getName(): string; /** * Sets the current name of the page, also updates the name for any parent context. * This is used to identify the page in the telemetry data. * @remarks This function updates the current and ALL parent contexts with the new name, * to just update the name of the current context, use the `pageName` property. * @param pageName - The name of the page * @deprecated Use the `pageName` property to avoid the side effect of changing the page name of all * parent contexts. */ 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 * * @remarks Sets the traceId for the current context AND all parent contexts, if you want to set the traceId * for the current context only, use the `traceId` property. * @param newValue - The traceId to set * @deprecated Use the `traceId` property to avoid the side effect of changing the traceId of all * parent contexts. */ 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 * * @remarks Sets the spanId for the current context AND all parent contexts, if you want to set the spanId for * the current context only, use the `spanId` property. * @param newValue - The spanId to set * @deprecated Use the `spanId` property to avoid the side effect of changing the spanId of all * parent contexts. */ 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 * @remarks Sets the trace flags for the current context and ALL parent contexts, if you want to set the trace * flags for the current context only, use the `traceFlags` property. * @param newValue - An integer representation of the W3C TraceContext trace-flags. * @deprecated Use the `traceFlags` property to avoid the side effect of changing the traceFlags of all * parent contexts. */ setTraceFlags(newValue?: number): void; /** * Returns the current name of the page * @remarks This function updates the current context only, to update the name of the current and ALL parent contexts, * use the `setName` method. * @default undefined * @since 3.4.0 */ pageName: string; /** * The current ID of the trace that this span belongs to. It is worldwide unique * with practically sufficient probability by being made as 16 randomly * generated bytes, encoded as a 32 lowercase hex characters corresponding to * 128 bits. * @remarks It is NOT recommended that you dynamically change this value after creation and it is actively * being used as this may affect anyone accessing this context (as a parent for instance). You should logically * treat this as readonly after creation. * @remarks If you update this value, it will only update for the current context, not the parent context, * if you need to update the current and ALL parent contexts, use the `setTraceId` method which * provides the previous behavior. * @since 3.4.0 */ traceId: string; /** * The ID of the Span. It is globally unique with practically sufficient * probability by being made as 8 randomly generated bytes, encoded as a 16 * lowercase hex characters corresponding to 64 bits. * If you update this value, it will only update for the current context, not the parent context. * @remarks If you update this value, it will only update for the current context, not the parent context, * if you need to update the current and ALL parent contexts, use the `setSpanId` method. * @since 3.4.0 */ spanId: string; /** * Returns true if the current context was initialized (propagated) from a remote parent. * @since 3.4.0 * @default false * @returns True if the context was propagated from a remote parent */ readonly isRemote: boolean; /** * Trace flags to propagate. * * It is represented as 1 byte (bitmap). Bit to represent whether trace is * sampled or not. When set, the least significant bit documents that the * caller may have recorded trace data. A caller who does not record trace * data out-of-band leaves this flag unset. * * see {@link eW3CTraceFlags} for valid flag values. * * @remarks If you update this value, it will only update for the current context, not the parent context, * if you need to update the current and ALL parent contexts, use the `setTraceFlags` method. * @since 3.4.0 */ traceFlags?: number; /** * Returns the current trace state which will be used to propgate context across different services. * Updating (adding / removing keys) of the trace state will modify the current context.IOTelTraceState * @remarks Unlike the OpenTelemetry {@link IOTelTraceState}, this value is a mutable object, so you can * modify it directly you do not need to reassign the new value to this property. * @since 3.4.0 */ readonly traceState: IW3cTraceState; /** * Provides access to the parent context of the current context. * @remarks This is a read-only property, you cannot modify the parent context directly, you can only * modify the current context. If you need to modify the parent context, you need to do it through the * current context using the `setTraceId`, `setSpanId`, `setTraceFlags` and `setName` methods. * @default null * @since 3.4.0 */ readonly parentCtx?: IDistributedTraceContext | null; } /** * An object that can be used to populate a new {@link IDistributedTraceContext} instance, * the included {@link IW3cTraceState} or {@link IOTelTraceState} is used as the parent of the * created instances traceState */ interface IDistributedTraceInit { /** * The unique identifier for the trace that this span belongs to. * * The trace ID is a globally unique identifier that connects all spans within a single * distributed trace. It consists of 16 randomly generated bytes encoded as 32 lowercase * hexadecimal characters, providing 128 bits of entropy to ensure worldwide uniqueness * with practically sufficient probability. * * @remarks * - Must be exactly 32 lowercase hexadecimal characters * - Represents 128 bits (16 bytes) of random data * - Shared by all spans within the same trace * - Used for trace correlation across distributed systems * - Should never be all zeros (invalid trace ID) * * @example * ```typescript * // Example trace ID format * const traceId = "4bf92f3577b34da6a3ce929d0e0e4736"; * * // All spans in the same trace share this ID * console.log(parentSpan.spanContext().traceId === childSpan.spanContext().traceId); // true * ``` */ traceId: string; /** * The unique identifier for this specific span within the trace. * * The span ID uniquely identifies this span within the trace and is used to establish * parent-child relationships between spans. It consists of 8 randomly generated bytes * encoded as 16 lowercase hexadecimal characters, providing 64 bits of entropy to * ensure global uniqueness with practically sufficient probability. * * @remarks * - Must be exactly 16 lowercase hexadecimal characters * - Represents 64 bits (8 bytes) of random data * - Unique within the trace (different spans have different span IDs) * - Used as parent ID when creating child spans * - Should never be all zeros (invalid span ID) * * @example * ```typescript * // Example span ID format * const spanId = "00f067aa0ba902b7"; * * // Each span has a unique ID within the trace * const parentId = parentSpan.spanContext().spanId; // "00f067aa0ba902b7" * const childId = childSpan.spanContext().spanId; // "b9c7c989f97918e1" * * // Child span uses parent's span ID as its parent ID * console.log(childSpan.parentSpanId === parentId); // true * ``` */ spanId: string; /** * Indicates whether this span context was propagated from a remote parent span. * * This flag distinguishes between spans created locally within the same process * and spans that represent operations in remote services. Remote spans are typically * created when trace context is received via HTTP headers, message queues, or other * inter-process communication mechanisms. * * @defaultValue false - spans are considered local unless explicitly marked as remote * * @remarks * - True only when span context was received from another process/service * - Helps distinguish local vs. distributed trace segments * - Used by tracing systems for visualization and analysis * - Local child spans of remote parents are NOT considered remote themselves * * @example * ```typescript * // HTTP service receiving trace context * const incomingSpanContext = extractSpanContextFromHeaders(request.headers); * console.log(incomingSpanContext.isRemote); // true * * // Child span created locally * const localChild = tracer.startSpan('local-operation', { * parent: incomingSpanContext * }); * console.log(localChild.spanContext().isRemote); // false * ``` */ isRemote?: boolean; /** * Trace flags that control trace behavior and indicate sampling decisions. * * The trace flags are represented as a single byte (8-bit bitmap) that carries * trace-level information. The least significant bit (0x01) indicates whether * the trace is sampled. When this bit is set, it documents that the caller * may have recorded trace data. Additional bits are reserved for future use * and should be ignored when not understood. * * @remarks * - Represented as a number (0-255) corresponding to 8 bits * - Bit 0 (0x01): Sampled flag - indicates trace may contain recorded data * - Bits 1-7: Reserved for future use, should be preserved during propagation * - Used by sampling algorithms to make consistent decisions across services * - See {@link eW3CTraceFlags} for standard flag values * * @example * ```typescript * // Check if trace is sampled * const isSampled = (spanContext.traceFlags & 0x01) === 1; * * // Common flag values * const UNSAMPLED = 0x00; // 00000000 - not sampled * const SAMPLED = 0x01; // 00000001 - sampled * * // Preserving unknown flags during propagation * const preservedFlags = spanContext.traceFlags | 0x01; // Set sampled bit while preserving others * * // W3C traceparent header format includes these flags * const traceparent = `00-${traceId}-${spanId}-${traceFlags.toString(16).padStart(2, '0')}`; * ``` */ traceFlags?: number; /** * Vendor-specific trace state information for cross-system trace correlation. * * The trace state carries tracing-system-specific context in a standardized format * defined by the W3C Trace Context specification. It allows multiple tracing systems * to participate in the same trace by providing a mechanism for each system to add * its own metadata without interfering with others. * * The trace state is formatted as a comma-separated list of key-value pairs, where * each pair represents one tracing system's contribution. Keys should be unique * within the trace state and follow specific naming conventions. * * @remarks * - Maximum of 32 list members allowed * - Each member format: `key=value` separated by commas * - Keys should be namespaced to avoid conflicts (e.g., `vendor@system=value`) * - Total size should not exceed 512 characters for practical header limits * - Spaces around list members are ignored * - Preserves vendor-specific information during trace propagation * * @see {@link https://www.w3.org/TR/trace-context/#tracestate-field | W3C Trace Context Specification} * * @example * ```typescript * // Single tracing system * const singleVendor = { * get: (key: string) => key === 'rojo' ? '00f067aa0ba902b7' : undefined, * set: (key: string, value: string) => { ... }, * unset: (key: string) => { ... }, * serialize: () => 'rojo=00f067aa0ba902b7' * }; * * // Multiple tracing systems * const multiVendor = { * serialize: () => 'rojo=00f067aa0ba902b7,congo=t61rcWkgMzE,vendor@system=custom-value' * }; * * // Accessing trace state * const rojoValue = spanContext.traceState?.get('rojo'); * const serialized = spanContext.traceState?.serialize(); * * // HTTP header format (When the traceState is an IOTelTraceState) * headers['tracestate'] = spanContext.traceState?.serialize() || ''; * * // HTTP header format (When the traceState is an IW3cTraceState) * headers['tracestate'] = spanContext.traceState?.hdrs()[0] || ''; * ``` */ traceState?: IW3cTraceState | IOTelTraceState; } 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; } /** * 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; } 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 IInternalLogMessage { message: string; messageId: _InternalMessageId; } /** * 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; } /** * Internal interface for sendBuffer, do not export it * @internal * @since 3.1.3 */ interface IInternalStorageItem { /** * serialized telemetry to be stored. */ item: string; /** * total retry count */ cnt?: number; } /** * 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; } /** * 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; } 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; } /** * The main OpenTelemetry API interface that provides access to all OpenTelemetry functionality. * This interface extends the IOTelTracerProvider and serves as the entry point for OpenTelemetry operations. * * @example * ```typescript * // Get a tracer from the API instance * const tracer = otelApi.getTracer("my-component"); * * // Create a span * const span = tracer.startSpan("operation"); * * // Access context manager * const currentContext = otelApi.context.active(); * * // Access trace API * const activeSpan = otelApi.trace.getActiveSpan(); * ``` * * @since 3.4.0 */ interface IOTelApi extends IOTelTracerProvider { /** * The configuration object that contains all OpenTelemetry-specific settings. * This includes tracing configuration, error handlers, and other OpenTelemetry options. * * @remarks * Changes to this configuration after initialization may not take effect until * the next telemetry operation, depending on the implementation. */ cfg: IOTelConfig; /** * The current {@link ITraceHost} instance for this IOTelApi instance, this is effectively * the OpenTelemetry ContextAPI instance without the static methods. * @returns The ContextManager instance */ host: ITraceHost; /** * The current {@link ITraceApi} instance for this IOTelApi instance, this is * effectively the OpenTelemetry TraceAPI instance without the static methods. * @returns The current {@link ITraceApi} instance */ trace: ITraceApi; } /** * Configuration interface for OpenTelemetry attribute limits. * These limits help control the size and number of attributes to prevent * excessive memory usage and ensure consistent performance. * * @example * ```typescript * const limits: IOTelAttributeLimits = { * attributeCountLimit: 128, // Maximum 128 attributes * attributeValueLengthLimit: 4096 // Maximum 4KB per attribute value * }; * ``` * * @remarks * When limits are exceeded: * - Additional attributes beyond `attributeCountLimit` are dropped * - Attribute values longer than `attributeValueLengthLimit` are truncated * - The behavior may vary based on the specific implementation * * @since 3.4.0 */ interface IOTelAttributeLimits { /** * Maximum allowed length for attribute values in characters. * * @remarks * - Values longer than this limit will be truncated * - Applies to string attribute values only * - Numeric and boolean values are not affected by this limit * - Array values have this limit applied to each individual element * * @defaultValue 4096 * * @example * ```typescript * // If attributeValueLengthLimit is 100: * span.setAttribute("description", "a".repeat(200)); // Will be truncated to 100 characters * span.setAttribute("count", 12345); // Not affected (number) * span.setAttribute("enabled", true); // Not affected (boolean) * ``` */ attributeValueLengthLimit?: number; /** * Maximum number of attributes allowed per telemetry item. * * @remarks * - Attributes added beyond this limit will be dropped * - The order of attributes matters; earlier attributes take precedence * - This limit applies to the total count of attributes, regardless of their type * - Inherited or default attributes count toward this limit * * @defaultValue 128 * * @example * ```typescript * // If attributeCountLimit is 5: * span.setAttributes({ * "attr1": "value1", // Kept * "attr2": "value2", // Kept * "attr3": "value3", // Kept * "attr4": "value4", // Kept * "attr5": "value5", // Kept * "attr6": "value6" // Dropped (exceeds limit) * }); * ``` */ attributeCountLimit?: number; } /** * Attributes is a map from string to attribute values. * * Note: only the own enumerable keys are counted as valid attribute keys. * * @since 3.4.0 */ interface IOTelAttributes { [key: string]: OTelAttributeValue | undefined; } /** * OpenTelemetry configuration interface * Provides configuration specific to the OpenTelemetry extensions */ interface IOTelConfig { /** * Configuration interface for OpenTelemetry tracing functionality. * This interface contains all the settings that control how traces are created, * processed, and managed within the OpenTelemetry system. * * @example * ```typescript * const traceCfg: ITraceCfg = { * serviceName: "my-service", * generalLimits: { * attributeCountLimit: 128, * attributeValueLengthLimit: 4096 * }, * spanLimits: { * attributeCountLimit: 128, * linkCountLimit: 128, * eventCountLimit: 128 * } * }; * ``` * * @since 3.4.0 */ traceCfg?: ITraceCfg; /** * Error handlers for OpenTelemetry operations. * This interface allows you to specify custom error handling logic for various * OpenTelemetry components, enabling better control over how errors are managed * within the OpenTelemetry system. * * @see {@link IOTelErrorHandlers} * * @example * ```typescript * const errorHandlers: IOTelErrorHandlers = { * attribError: (message, key, value) => { * console.warn(`Attribute error for ${key}:`, message); * } * }; * ``` */ errorHandlers?: IOTelErrorHandlers; } /** * Configuration interface for OpenTelemetry error handling callbacks. * Provides hooks to customize how different types of errors and diagnostic * messages are handled within the OpenTelemetry system. * * @example * ```typescript * const errorHandlers: IOTelErrorHandlers = { * attribError: (message, key, value) => { * console.warn(`Attribute error for ${key}:`, message); * }, * spanError: (message, spanName) => { * logger.error(`Span ${spanName} error:`, message); * }, * warn: (message) => { * logger.warn(message); * }, * error: (message) => { * logger.error(message); * } * }; * ``` * * @remarks * If handlers are not provided, default behavior will be used: * - `attribError`: Throws an `OTelInvalidAttributeError` * - `spanError`: Logs to console or calls warn handler * - `debug`: Logs to console.log * - `warn`: Logs to console.warn * - `error`: Logs to console.error * - `notImplemented`: Logs to console.error * * @since 3.4.0 */ interface IOTelErrorHandlers { /** * Handles attribute-related errors, such as invalid attribute values or keys. * Called when an attribute operation fails validation or processing. * * @param message - Descriptive error message explaining what went wrong * @param key - The attribute key that caused the error * @param value - The attribute value that caused the error (may be of any type) * * @remarks * Common scenarios that trigger this handler: * - Invalid attribute key format * - Attribute value exceeds length limits * - Unsupported attribute value type * - Attribute count exceeds limits * * @default Throws an `OTelInvalidAttributeError` * * @example * ```typescript * attribError: (message, key, value) => { * metrics.increment('otel.attribute.errors', { key, type: typeof value }); * logger.warn(`Attribute ${key} rejected: ${message}`); * } * ``` */ attribError?: (message: string, key: string, value: any) => void; /** * Handles span-related errors that occur during span operations. * Called when a span operation fails or encounters an unexpected condition. * * @param message - Descriptive error message explaining the span error * @param spanName - The name of the span that encountered the error * * @remarks * Common scenarios that trigger this handler: * - Span operation called on an ended span * - Invalid span configuration * - Span processor errors * - Context propagation failures * * @default Logs to console or calls the warn handler * * @example * ```typescript * spanError: (message, spanName) => { * metrics.increment('otel.span.errors', { span_name: spanName }); * logger.error(`Span operation failed for "${spanName}": ${message}`); * } * ``` */ spanError?: (message: string, spanName: string) => void; /** * Handles debug-level diagnostic messages. * Used for detailed troubleshooting information that is typically * only relevant during development or when diagnosing issues. * * @param message - Debug message to be handled * * @remarks * Debug messages are typically: * - Verbose operational details * - Internal state information * - Performance metrics * - Development-time diagnostics * * @default Logs to console.log * * @example * ```typescript * debug: (message) => { * if (process.env.NODE_ENV === 'development') { * console.debug('[OTel Debug]', message); * } * } * ``` */ debug?: (message: string) => void; /** * Handles warning-level messages for non-fatal issues. * Used for conditions that are unusual but don't prevent continued operation. * * @param message - Warning message to be handled * * @remarks * Warning scenarios include: * - Configuration issues that fall back to defaults * - Performance degradation * - Deprecated API usage * - Resource limit approaches * * @default Logs to console.warn * * @example * ```typescript * warn: (message) => { * logger.warn('[OTel Warning]', message); * metrics.increment('otel.warnings'); * } * ``` */ warn?: (message: string) => void; /** * Handles general error conditions that may affect functionality. * Used for significant errors that should be investigated but may not be fatal. * * @param message - Error message to be handled * * @remarks * Error scenarios include: * - Failed network requests * - Configuration validation failures * - Resource allocation failures * - Unexpected runtime conditions * * @default Logs to console.error * * @example * ```typescript * error: (message) => { * logger.error('[OTel Error]', message); * errorReporting.captureException(new Error(message)); * } * ``` */ error?: (message: string) => void; /** * Handles errors related to unimplemented functionality. * Called when a method or feature is not yet implemented or is intentionally * disabled in the current configuration. * * @param message - Message describing the unimplemented functionality * * @remarks * Common scenarios: * - Placeholder methods that haven't been implemented * - Features disabled in the current build * - Platform-specific functionality not available * - Optional features not included in the configuration * * @default Logs to console.error * * @example * ```typescript * notImplemented: (message) => { * logger.warn(`[OTel Not Implemented] ${message}`); * if (process.env.NODE_ENV === 'development') { * console.trace('Not implemented method called'); * } * } * ``` */ notImplemented?: (message: string) => void; } interface IOTelExceptionWithCode { code: string | number; name?: string; message?: string; stack?: string; } interface IOTelExceptionWithMessage { code?: string | number; message: string; name?: string; stack?: string; } interface IOTelExceptionWithName { code?: string | number; message?: string; name: string; stack?: string; } /** * Enhanced high-resolution time interface that extends the base tuple with additional properties. * Provides a more structured way to work with high-resolution timestamps. * * @example * ```typescript * const hrTime: IOTelHrTime = { * 0: 1609459200, // seconds since Unix epoch * 1: 500000000, // nanoseconds (0-999,999,999) * }; * ``` * * @since 3.4.0 */ interface IOTelHrTime extends OTelHrTimeBase { /** * Seconds since Unix epoch (January 1, 1970 00:00:00 UTC). * Must be a non-negative integer. */ 0: number; /** * Nanoseconds within the second specified by index 0. * Must be in the range [0, 999999999]. */ 1: number; } /** * Provides an OpenTelemetry compatible interface for spans conforming to the OpenTelemetry API specification (v1.9.0). * * A span represents an operation within a trace and is the fundamental unit of work in distributed tracing. * Spans can be thought of as a grouping mechanism for a set of operations that are executed as part of * a single logical unit of work, providing timing information and contextual data about the operation. * * Spans form a tree structure within a trace, with a single root span that may have zero or more child spans, * which in turn may have their own children. This hierarchical structure allows for detailed analysis of * complex, multi-step operations across distributed systems. * * @since 3.4.0 * * @remarks * - All spans created by this library implement the ISpan interface and extend the IReadableSpan interface * - Spans should be ended by calling `end()` when the operation completes * - Once ended, spans should generally not be used for further operations * - Spans automatically track timing information from creation to end * * @example * ```typescript * // Basic span usage * const span = tracer.startSpan('user-authentication'); * span.setAttribute('user.id', '12345'); * span.setAttribute('auth.method', 'oauth2'); * * try { * const result = await authenticateUser(); * span.setStatus({ code: SpanStatusCode.OK }); * span.setAttribute('auth.success', true); * } catch (error) { * span.recordException(error); * span.setStatus({ * code: SpanStatusCode.ERROR, * message: 'Authentication failed' * }); * } finally { * span.end(); * } * ``` */ interface IOTelSpan { /** * Returns the span context object associated with this span. * * The span context is an immutable, serializable identifier that uniquely identifies * this span within a trace. It contains the trace ID, span ID, and trace flags that * can be used to create new child spans or propagate trace context across process boundaries. * * The returned span context remains valid even after the span has ended, making it * useful for asynchronous operations and cross-service communication. * * @returns The immutable span context associated with this span * * @remarks * - The span context is the primary mechanism for trace propagation * - Context can be serialized and transmitted across network boundaries * - Contains trace ID (unique to the entire trace) and span ID (unique to this span) * * @example * ```typescript * const span = tracer.startSpan('parent-operation'); * const spanContext = span.spanContext(); * * // Use context to create child spans in other parts of the system * const childSpan = tracer.startSpan('child-operation', { * parent: spanContext * }); * * // Context can be serialized for cross-service propagation * const traceId = spanContext.traceId; * const spanId = spanContext.spanId; * ``` */ spanContext(): IDistributedTraceContext; /** * Sets a single attribute on the span with the specified key and value. * * Attributes provide contextual information about the operation represented by the span. * They are key-value pairs that help with filtering, grouping, and understanding spans * in trace analysis tools. Attributes should represent meaningful properties of the operation. * * @param key - The attribute key, should be descriptive and follow naming conventions * @param value - The attribute value; null or undefined values are invalid and result in undefined behavior * * @returns This span instance for method chaining * * @remarks * - Attribute keys should follow semantic conventions when available * - Common attributes include service.name, http.method, db.statement, etc. * - Setting null or undefined values is invalid and may cause unexpected behavior * - Attributes set after span creation don't affect sampling decisions * * @example * ```typescript * const span = tracer.startSpan('http-request'); * * // Set individual attributes with descriptive keys * span.setAttribute('http.method', 'POST') * .setAttribute('http.url', 'https://api.example.com/users') * .setAttribute('http.status_code', 201) * .setAttribute('user.id', '12345') * .setAttribute('request.size', 1024); * ``` */ setAttribute(key: string, value: OTelAttributeValue): this; /** * Sets multiple attributes on the span at once using an attributes object. * * This method allows efficient batch setting of multiple attributes in a single call. * All attributes in the provided object will be added to the span, supplementing any * existing attributes (duplicate keys will be overwritten). * * @param attributes - An object containing key-value pairs to set as span attributes * * @returns This span instance for method chaining * * @remarks * - Null or undefined attribute values are invalid and will result in undefined behavior * - More efficient than multiple `setAttribute` calls for bulk operations * - Existing attributes with the same keys will be overwritten * * @example * ```typescript * const span = tracer.startSpan('database-query'); * * // Set multiple attributes efficiently * span.setAttributes({ * 'db.system': 'postgresql', * 'db.name': 'user_database', * 'db.table': 'users', * 'db.operation': 'SELECT', * 'db.rows_affected': 5, * 'query.duration_ms': 15.7 * }); * ``` */ setAttributes(attributes: IOTelAttributes): this; /** * The {@link IAttributeContainer | attribute container} associated with this span, providing * advanced attribute management capabilities. Rather than using the {@link IReadableSpan#attributes} * directly which returns a readonly {@link IOTelAttributes} map that is a snapshot of the attributes at * the time of access, the attribute container offers methods to get, set, delete, and iterate over attributes * with fine-grained control. * It is recommended that you only access the {@link IReadableSpan#attributes} property sparingly due to the * performance cost of taking a snapshot of all attributes. */ readonly attribContainer: IAttributeContainer; /** * Sets the status of the span to indicate the success or failure of the operation. * * The span status provides a standardized way to indicate whether the operation * completed successfully, encountered an error, or is in an unknown state. * This status is used by observability tools to provide meaningful insights * about system health and operation outcomes. * * @param status - The status object containing code and optional message * * @returns This span instance for method chaining * * @remarks * - Default status is UNSET until explicitly set * - Setting status overrides any previous status values * - ERROR status should be accompanied by a descriptive message when possible * - Status should reflect the final outcome of the operation * * @example * ```typescript * const span = tracer.startSpan('payment-processing'); * * try { * const result = await processPayment(paymentData); * * // Indicate successful completion * span.setStatus({ * code: SpanStatusCode.OK * }); * * } catch (error) { * // Indicate operation failed * span.setStatus({ * code: SpanStatusCode.ERROR, * message: 'Payment processing failed: ' + error.message * }); * * span.recordException(error); * } * ``` */ setStatus(status: IOTelSpanStatus): this; /** * Updates the name of the span, overriding the name provided during creation. * * Span names should be descriptive and represent the operation being performed. * Updating the name can be useful when the operation's scope becomes clearer * during execution, or when implementing generic spans that need specific naming * based on runtime conditions. * * @param name - The new name for the span, should be descriptive of the operation * * @returns This span instance for method chaining * * @remarks * - Name updates may affect sampling behavior depending on implementation * - Choose names that are meaningful but not too specific to avoid cardinality issues * - Follow naming conventions consistent with your observability strategy * - Consider the impact on existing traces and dashboards when changing names * * @example * ```typescript * const span = tracer.startSpan('generic-operation'); * * // Update name based on runtime determination * if (operationType === 'user-registration') { * span.updateName('user-registration'); * span.setAttribute('operation.type', 'registration'); * } else if (operationType === 'user-login') { * span.updateName('user-authentication'); * span.setAttribute('operation.type', 'authentication'); * } * ``` */ updateName(name: string): this; /** * Marks the end of the span's execution and records the end timestamp. * * This method finalizes the span and makes it available for export to tracing systems. * Once ended, the span should not be used for further operations. The span's duration * is calculated from its start time to the end time provided or current time. * * @param endTime - Optional end time; if not provided, current time is used * * @remarks * - This method does NOT return `this` to discourage chaining after span completion * - Ending a span has no effect on child spans, which may continue running * - Child spans can be ended independently after their parent has ended * - The span becomes eligible for export once ended * - Calling end() multiple times has no additional effect * * @example * ```typescript * const span = tracer.startSpan('file-processing'); * * try { * // Perform the operation * const result = await processFile(filePath); * * // Record success * span.setStatus({ code: SpanStatusCode.OK }); * span.setAttribute('file.size', result.size); * * } catch (error) { * span.recordException(error); * span.setStatus({ * code: SpanStatusCode.ERROR, * message: error.message * }); * } finally { * // Always end the span * span.end(); * // Don't use span after this point * } * * // Custom end time example * const customEndTime = Date.now() * 1000000; // nanoseconds * span.end(customEndTime); * ``` */ end(endTime?: OTelTimeInput): void; /** * Returns whether this span is actively recording information. * * A recording span accepts and stores attributes, events, status, and other span data. * Non-recording spans (typically due to sampling decisions) may ignore operations * like setAttribute() to optimize performance. This method allows conditional * logic to avoid expensive operations on non-recording spans. * * @returns True if the span is actively recording information, false otherwise * * @remarks * - Recording status is typically determined at span creation time * - Non-recording spans still provide valid span context for propagation * - Use this check to avoid expensive attribute calculations for non-recording spans * - Recording status remains constant throughout the span's lifetime * * @example * ```typescript * const span = tracer.startSpan('data-processing'); * * // Only perform expensive operations if span is recording * if (span.isRecording()) { * const metadata = await expensiveMetadataCalculation(); * span.setAttributes({ * 'process.metadata': JSON.stringify(metadata), * 'process.complexity': metadata.complexity, * 'process.estimated_duration': metadata.estimatedMs * }); * } * * // Always safe to set basic attributes * span.setAttribute('process.started', true); * ``` */ isRecording(): boolean; /** * Records an exception as a span event with automatic error status handling. * * This method captures exception information and automatically creates a span event * with standardized exception attributes. It's the recommended way to handle errors * within spans, providing consistent error reporting across the application. * * @param exception - The exception to record; accepts string messages or Error objects * @param time - Optional timestamp for when the exception occurred; defaults to current time * * @remarks * - Automatically extracts exception type, message, and stack trace when available * - Creates a standardized span event with exception details * - Does NOT automatically set span status to ERROR - call setStatus() explicitly if needed * - Exception events are useful for debugging and error analysis * * @example * ```typescript * const span = tracer.startSpan('risky-operation'); * * try { * await performRiskyOperation(); * span.setStatus({ code: SpanStatusCode.OK }); * * } catch (error) { * // Record the exception details * span.recordException(error); * * // Explicitly set error status * span.setStatus({ * code: SpanStatusCode.ERROR, * message: 'Operation failed due to: ' + error.message * }); * * // Re-throw if needed * throw error; * } finally { * span.end(); * } * * // Recording string exceptions * span.recordException('Custom error message occurred'); * * // Recording with custom timestamp * const errorTime = Date.now() * 1000000; // nanoseconds * span.recordException(error, errorTime); * ``` */ recordException(exception: OTelException, time?: OTelTimeInput): void; } /** * A SpanContext represents the portion of a {@link IOTelSpan} which must be * serialized and propagated along side of a {@link IOTelBaggage}. */ interface IOTelSpanContext extends IDistributedTraceInit { /** * Trace flags to propagate. * * It is represented as 1 byte (bitmap). Bit to represent whether trace is * sampled or not. When set, the least significant bit documents that the * caller may have recorded trace data. A caller who does not record trace * data out-of-band leaves this flag unset. * * see {@link eW3CTraceFlags} for valid flag values. */ traceFlags: number; } /** * Provides an OpenTelemetry like Interface for the Open Telemetry Api (1.9.0) SpanOptions * type. Where SpanOptions are options that can be used to configure a span. */ interface IOTelSpanOptions { /** * The SpanKind of a span of this span, this is used to specify * the relationship between the span and its parent span. * @see {@link eOTelSpanKind} for possible values. * @default eOTelSpanKind.INTERNAL */ kind?: OTelSpanKind; /** * A span's attributes */ attributes?: IOTelAttributes; /** A manually specified start time for the created `Span` object. */ startTime?: OTelTimeInput; /** The new span should be a root span. (Ignore parent from context). */ root?: boolean; /** Specify whether the span should be a recording span, default is true */ recording?: boolean; } interface IOTelSpanStatus { /** * The status code of this message. */ code: eOTelSpanStatusCode; /** * A developer-facing error message. */ message?: string; } /** * OpenTelemetry tracer interface for creating and managing spans within a trace. * * A tracer is responsible for creating spans that represent units of work within a distributed system. * Each tracer is typically associated with a specific instrumentation library or component, * allowing for fine-grained control over how different parts of an application generate telemetry. * * @example * ```typescript * // Get a tracer instance * const tracer = otelApi.getTracer('my-service'); * * // Create a simple span * const span = tracer.startSpan('database-query'); * span.setAttribute('db.operation', 'SELECT'); * span.end(); * * // Create an active span with automatic context management * tracer.startActiveSpan('process-request', (span) => { * span.setAttribute('request.id', '12345'); * * // Any spans created within this block will be children of this span * processRequest(); * * span.end(); * }); * ``` * * @see {@link IReadableSpan} - Interface for individual spans * @see {@link IOTelSpanOptions} - Configuration options for span creation * * @since 3.4.0 */ interface IOTelTracer { /** * Creates and starts a new span without setting it as the active span in the current context. * * This method creates a span but does NOT modify the current execution context. * The caller is responsible for managing the span's lifecycle, including calling `end()` * when the operation completes. * * @param name - The name of the span, should be descriptive of the operation being traced * @param options - Optional configuration for span creation (parent context, attributes, etc.) * * @returns The newly created span, or null if span creation failed * * @remarks * - The returned span must be manually ended by calling `span.end()` * - This span will not automatically become the parent for spans created in nested operations * - Use `startActiveSpan` if you want automatic context management * * @example * ```typescript * const span = tracer.startSpan('database-operation'); * if (span) { * try { * span.setAttribute('db.table', 'users'); * span.setAttribute('db.operation', 'SELECT'); * * // Perform database operation * const result = await db.query('SELECT * FROM users'); * * span.setAttributes({ * 'db.rows_affected': result.length, * 'operation.success': true * }); * } catch (error) { * span.setStatus({ * code: SpanStatusCode.ERROR, * message: error.message * }); * span.recordException(error); * } finally { * span.end(); // Always end the span * } * } * ``` */ startSpan(name: string, options?: IOTelSpanOptions): IReadableSpan | null; /** * Creates and starts a new span, sets it as the active span in the current context, * and executes a provided function within this context. * * This method creates a span, makes it active during the execution of the provided * function, and automatically ends the span when the function completes (or throws). * This provides automatic span lifecycle management and context propagation. * * @param name - The name of the span, should be descriptive of the operation being traced * @param options - Optional configuration for span creation (parent context, attributes, etc.) * @param fn - The function to execute within the span's active context * * @returns The result of executing the provided function * * @remarks * - The span is automatically ended when the function completes or throws an exception * - The span becomes the active parent for any spans created within the function * - If the function throws an error, the span status is automatically set to ERROR * - This is the recommended method for most tracing scenarios due to automatic lifecycle management * - Multiple overloads available for different parameter combinations * * @example * ```typescript * // Synchronous operation with just name and function * const result = tracer.startActiveSpan('user-service', (span) => { * span.setAttribute('operation', 'get-user-details'); * return { user: getUserData(), timestamp: new Date().toISOString() }; * }); * * // With options * const result2 = tracer.startActiveSpan('database-query', * { attributes: { 'db.table': 'users' } }, * (span) => { * span.setAttribute('db.operation', 'SELECT'); * return database.getUser('123'); * } * ); * * // With full context control * const result3 = tracer.startActiveSpan('external-api', * { attributes: { 'service.name': 'payment-api' } }, * currentContext, * async (span) => { * try { * const response = await fetch('/api/payment'); * span.setAttributes({ * 'http.status_code': response.status, * 'operation.success': response.ok * }); * return response.json(); * } catch (error) { * span.setAttribute('error.type', error.constructor.name); * throw error; // Error automatically recorded * } * } * ); * ``` */ startActiveSpan unknown>(name: string, fn: F): ReturnType; startActiveSpan unknown>(name: string, options: IOTelSpanOptions, fn: F): ReturnType; } interface IOTelTracerOptions { /** * The schemaUrl of the tracer or instrumentation library */ schemaUrl?: string; } /** * OpenTelemetry Trace API for getting tracers. * This provides the standard OpenTelemetry trace API entry point. */ interface IOTelTracerProvider { /** * Returns a Tracer, creating one if one with the given name and version is * not already created. This may return * - The same Tracer instance if one has already been created with the same name and version * - A new Tracer instance if one has not already been created with the same name and version * - A non-operational Tracer if the provider is not operational * * @param name - The name of the tracer or instrumentation library. * @param version - The version of the tracer or instrumentation library. * @param options - The options of the tracer or instrumentation library. * @returns Tracer A Tracer with the given name and version */ getTracer(name: string, version?: string, options?: IOTelTracerOptions): IOTelTracer; /** * Forces the tracer provider to flush any buffered data. * @returns A promise that resolves when the flush is complete. */ forceFlush?: () => IPromise | void; /** * Shuts down the tracer provider and releases any resources. * @returns A promise that resolves when the shutdown is complete. */ shutdown?: () => IPromise | void; } /** * Provides an OpenTelemetry compatible Interface for the Open Telemetry Api (1.9.0) TraceState type. * * The TraceState is a list of key/value pairs that are used to propagate * vendor-specific trace information across different distributed tracing systems. * The TraceState is used to store the state of a trace across different * distributed tracing systems, and it is used to ensure that the trace information * is consistent across different systems. * * Instances of TraceState are immutable, and the methods on this interface * return a new instance of TraceState with the updated values. */ interface IOTelTraceState { /** * Create a new TraceState which inherits from this TraceState and has the * given key set. * The new entry will always be added in the front of the list of states. * * @param key - key of the TraceState entry. * @param value - value of the TraceState entry. */ set(key: string, value: string): IOTelTraceState; /** * Return a new TraceState which inherits from this TraceState but does not * contain the given key. * * @param key - the key for the TraceState entry to be removed. */ unset(key: string): IOTelTraceState; /** * Returns the value to which the specified key is mapped, or `undefined` if * this map contains no mapping for the key. * * @param key - with which the specified value is to be associated. * @returns the value to which the specified key is mapped, or `undefined` if * this map contains no mapping for the key. */ get(key: string): string | undefined; /** * Serializes the TraceState to a `list` as defined below. The `list` is a series of `list-members` * separated by commas `,`, and a list-member is a key/value pair separated by an equals sign `=`. * Spaces and horizontal tabs surrounding `list-members` are ignored. There can be a maximum of 32 * `list-members` in a `list`. * * If the resulting serialization is limited to no longer than 512 bytes, if the combination of * keys and values exceeds this limit, the serialization will be truncated to the last key/value pair * that fits within the limit. The serialization will be returned as a string. * * This is different from the {@link IW3cTraceState} serialization which returns an array of strings where each * string is limited to 512 bytes and the array is limited to 32 strings. Thus the OpenTelemetry serialization * will only return the first single string that fits within the limie. * * @returns the serialized string. */ serialize(): string; } /** 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; } /** * Provides an OpenTelemetry compatible Interface for the Open Telemetry Sdk-Trace-Base (1.8.0 and 2.0.0) ReadableSpan type. * * The IReadableSpan interface is used to represent a span that can be read and exported, while the OpenTelemetry * specification defines a ReadableSpan as a Span that has been ended and is ready to be exported. By default all * spans created by this library implement the IReadableSpan interface which also extends the {@link IOTelSpan} interface. * * This interface is defined to provide compatibility with exporters defined by the OpenTelemetry Trace SDK. * @since 3.4.0 */ interface IReadableSpan extends IOTelSpan { /** * The span's unique identifier. */ readonly name: string; /** * Identifies the type (or kind) that this span is representing. */ readonly kind: OTelSpanKind; readonly spanContext: () => IDistributedTraceContext; readonly parentSpanId?: string; readonly parentSpanContext?: IDistributedTraceContext; readonly startTime: IOTelHrTime; readonly endTime: IOTelHrTime; readonly status: IOTelSpanStatus; /** * Provides a snapshot of the span's attributes at the time this span was ended. * @returns A read-only snapshot of the span's attributes * @remarks * It is recommended that you only access this property sparingly due to the * performance cost of taking a snapshot of all attributes. */ readonly attributes: IOTelAttributes; readonly duration: IOTelHrTime; readonly ended: boolean; readonly droppedAttributesCount: number; } interface IRequestContext { status?: number; xhr?: XMLHttpRequest; request?: Request; response?: Response | string; } interface IResponseError { readonly index: number; readonly statusCode: number; readonly message: string; } interface ISample { /** * Sample rate */ sampleRate: number; isSampledIn(envelope: ITelemetryItem): boolean; } /** * Before 3.1.2, payload only allow string * After 3.2.0, IInternalStorageItem is accepted */ interface ISendBuffer { /** * Enqueue the payload */ enqueue: (payload: IInternalStorageItem) => void; /** * Returns the number of elements in the buffer */ count: () => number; /** * Returns the current size of the serialized buffer */ size: () => number; /** * Clears the buffer */ clear: () => void; /** * Returns items stored in the buffer */ getItems: () => IInternalStorageItem[]; /** * Build a batch of all elements in the payload array */ batchPayloads: (payload: IInternalStorageItem[]) => string; /** * Moves items to the SENT_BUFFER. * The buffer holds items which were sent, but we haven't received any response from the backend yet. */ markAsSent: (payload: IInternalStorageItem[]) => void; /** * Removes items from the SENT_BUFFER. Should be called on successful response from the backend. */ clearSent: (payload: IInternalStorageItem[]) => void; /** * Copy current buffer items to a new buffer. * if canUseSessionStorage is undefined, it will set to false. * if newLogger and newConfig are undefined, current logger and empty config will be used. * if canUseSessionStorage is set to true, new SessionStorageSendBuffer will be returned otherwise ArraySendBuffer will be returned. */ createNew: (newLogger?: IDiagnosticLogger, newConfig?: ISenderConfig, canUseSessionStorage?: boolean) => ArraySendBuffer | SessionStorageSendBuffer; } interface ISenderConfig { /** * The url to which payloads will be sent */ endpointUrl: string; /** * The JSON format (normal vs line delimited). True means line delimited JSON. */ emitLineDelimitedJson: boolean; /** * The maximum size of a batch in bytes */ maxBatchSizeInBytes: number; /** * The maximum interval allowed between calls to batchInvoke */ maxBatchInterval: number; /** * The master off switch. Do not send any data if set to TRUE */ disableTelemetry: boolean; /** * Store a copy of a send buffer in the session storage */ enableSessionStorageBuffer: boolean; /** * Specify the storage buffer type implementation. * @since 2.8.12 */ bufferOverride: IStorageBuffer | false; /** * Is retry handler disabled. * If enabled, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error) and 503 (service unavailable). */ isRetryDisabled: boolean; 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; /** * Is beacon disabled on page unload. * If enabled, flush events through beaconSender. */ onunloadDisableBeacon: boolean; /** * (Optional) Override the instrumentation key that this channel instance sends to */ instrumentationKey: string; namePrefix: string; samplingPercentage: number; /** * (Optional) The ability for the user to provide extra headers */ customHeaders: [{ header: string; value: string; }]; /** * (Optional) 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) Enable the sender to return a promise so that manually flushing (and general sending) can wait for the request to finish. * Note: Enabling this may cause unhandled promise rejection errors to occur if you do not listen and handle any rejection response, * this *should* only be for manual flush attempts. * Defaults to false * @since 3.0.1 */ enableSendPromise?: boolean; /** * [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. * If alwaysUseXhrOverride configuration value is set to true, the override will always be used. * The payload data (first argument) now also includes any configured 'timeout' (defaults to undefined) and whether you should avoid * creating any synchronous XHR requests 'disableXhr' (defaults to false/undefined) * @since 3.0.4 */ httpXHROverride?: IXHROverride; /** * [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. * @since 3.0.4 */ alwaysUseXhrOverride?: boolean; /** * [Optional] Disable events splitting during sendbeacon. * Default: false * @since 3.0.6 */ disableSendBeaconSplit?: boolean; /** * [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) The specific error codes that will cause a retry of sending data to the backend. * @since 3.1.1 */ retryCodes?: number[]; /** * (Optional) The specific max retry count for each telemetry item. * Default: 10 * if it is set to 0, means no retry allowed * if it is set to undefined, means no limit for retry times * @since 3.2.0 */ maxRetryCnt?: number; /** * [Optional] Specifies the Cross-Origin Resource Policy (CORP) for the endpoint. * This value is included in the response header as `Cross-Origin-Resource-Policy`, * which helps control how resources can be shared across different origins. * * Possible values: * - `same-site`: Allows access only from the same site. * - `same-origin`: Allows access only from the same origin (protocol, host, and port). * - `cross-origin`: Allows access from any origin. * * @since 3.3.7 */ corsPolicy?: string; } 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: { [key: string]: FieldType | (() => FieldType); }; } /** * Represents the execution scope for a span, combining the trace instance and the active span. * This interface is used as the context for executing functions within a span's scope. * * @since 3.4.0 */ interface ISpanScope { /** * The trace host (core or AISKU instance). * @since 3.4.0 */ readonly host: T; /** * The active span for this execution scope. * @since 3.4.0 */ readonly span: IReadableSpan; /** * The previously active span before this scope was created, if any. * @since 3.4.0 */ readonly prvSpan?: IReadableSpan; /** * Restores the previous active span in the trace instance. * @since 3.4.0 */ restore(): void; } /** * 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; } 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 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 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; } /** * 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; } /** * ITraceApi provides an interface definition which is simular to the OpenTelemetry TraceAPI */ interface ITraceApi { /** * Returns a Tracer, creating one if one with the given name and version * if one has not already created. * * @param name - The name of the tracer or instrumentation library. * @param version - The version of the tracer or instrumentation library. * @param options - The options of the tracer or instrumentation library. * @returns Tracer A Tracer with the given name and version */ getTracer(name: string, version?: string, options?: IOTelTracerOptions): IOTelTracer; /** * Wrap the given {@link IDistributedTraceContext} in a new non-recording {@link IReadableSpan} * * @param spanContext - The {@link IDistributedTraceContext} to be wrapped * @returns a new non-recording {@link IReadableSpan} with the provided context */ wrapSpanContext(spanContext: IDistributedTraceContext | IDistributedTraceInit | IOTelSpanContext): IReadableSpan; /** * Returns true if this {@link IDistributedTraceContext} is valid. * @return true if this {@link IDistributedTraceContext} is valid. */ isSpanContextValid(spanContext: IDistributedTraceContext | IDistributedTraceInit | IOTelSpanContext): boolean; /** * Gets the span from the current context, if one exists. */ getActiveSpan(): IReadableSpan | undefined | null; /** * Set or clear the current active span. * @param span - The span to set as the active span, or null/undefined to clear the active span. * @return An ISpanScope instance returned by the host, or void if there is no defined host. */ setActiveSpan(span: IReadableSpan | undefined | null): ISpanScope | undefined | null; } /** * Configuration interface for OpenTelemetry compatible tracing functionality. * This interface contains all the settings that control how traces are created, * processed, and managed within the OpenTelemetry system. * * @example * ```typescript * const traceCfg: ITraceCfg = { * serviceName: "my-service", * generalLimits: { * attributeCountLimit: 128, * attributeValueLengthLimit: 4096 * }, * spanLimits: { * attributeCountLimit: 128, * linkCountLimit: 128, * eventCountLimit: 128 * } * }; * ``` * * @since 3.4.0 */ interface ITraceCfg { /** * Global attribute limits that apply to all telemetry items. * These limits help prevent excessive memory usage and ensure consistent * behavior across different telemetry types. * * @remarks * These limits are inherited by more specific configurations unless overridden. * For example, spans will use these limits unless `spanLimits` specifies different values. */ generalLimits?: IOTelAttributeLimits; /** * The name of the service generating telemetry data. * This name will be included in all telemetry items as a resource attribute. * * @remarks * The service name is crucial for identifying and filtering telemetry data * in observability systems. It should be consistent across all instances * of the same service. * * @example * ```typescript * serviceName: "user-authentication-service" * ``` */ serviceName?: string; /** * A flag that indicates whether the tracing (creating of a "trace" event) should be suppressed * when a {@link IOTelSpan} ends and the span {@link IOTelSpan#isRecording | isRecording} is true. * This value is also inherited by spans when they are created. */ suppressTracing?: boolean; } /** * Interface for OpenTelemetry trace operations. * This interface provides span creation, context management, and trace provider operations * that are common across different SDK implementations (Core, AISKU, etc.). * * @since 3.4.0 */ interface ITraceHost { readonly config: CfgType; /** * Gets the current distributed trace active context for this instance * @param createNew - Optional flag to create a new instance if one doesn't currently exist, defaults to true. By default this * will use any located parent as defined by the {@link IConfiguration.traceHdrMode} configuration for each new instance created. */ getTraceCtx(createNew?: boolean): IDistributedTraceContext | null; /** * Sets the current distributed trace context for this instance if available */ setTraceCtx(newTraceCtx: IDistributedTraceContext | null | undefined): void; /** * Start a new span with the given name and optional parent context. * * Note: This method only creates and returns the span. It does not automatically * set the span as the active trace context. Context management should be handled * separately using setTraceCtx() if needed. * * @param name - The name of the span * @param options - Options for creating the span (kind, attributes, startTime) * @param parent - Optional parent context. If not provided, uses the current active trace context * @returns A new span instance, or null if no trace provider is available * @since 3.4.0 * * @see {@link IReadableSpan} - Interface for individual spans * @see {@link IOTelSpanOptions} - Configuration options for span creation */ startSpan(name: string, options?: IOTelSpanOptions, parent?: IDistributedTraceContext): IReadableSpan | null; /** * Return the current active span, if no trace provider is available null will be returned * but when a trace provider is available a span instance will always be returned, even if * there is no active span (in which case a non-recording span will be returned). * @param createNew - Optional flag to create a non-recording span if no active span exists, defaults to true. * When false, returns the existing active span or null without creating a non-recording span, which can improve * performance when only checking if an active span exists. * @returns The current active span or null if no trace provider is available or if createNew is false and no active span exists * @since 3.4.0 */ getActiveSpan(createNew?: boolean): IReadableSpan | null; /** * Set the current Active Span, if no trace provider is available the span will be not be set as the active span. * @param span - The span to set as the active span * @returns An ISpanScope instance that provides the current scope, the span will always be the span passed in * even when no trace provider is available * @since 3.4.0 */ setActiveSpan(span: IReadableSpan): ISpanScope; /** * Get the current trace provider. * * @returns The current trace provider, or null if none is set * @since 3.4.0 */ getTraceProvider(): ITraceProvider | null; } /** * A trace provider interface that enables different SKUs to provide their own * span implementations while being managed by the core SDK. * * This follows the OpenTelemetry TraceProvider pattern, allowing the core to * delegate span creation to the appropriate implementation based on the SDK variant. * * @since 3.4.0 */ interface ITraceProvider { /** * The OpenTelemetry API instance associated with this trace provider. * This provides access to the tracer provider and other OpenTelemetry functionality. * @since 3.4.0 */ readonly api: IOTelApi; /** * Creates a new span with the given name and options. * * @param name - The name of the span * @param options - Options for creating the span (kind, attributes, startTime) * @param parent - Optional parent context. If not provided, uses the current active trace context * @returns A new span instance specific to this provider's implementation * @since 3.4.0 */ createSpan(name: string, options?: IOTelSpanOptions, parent?: IDistributedTraceContext): IReadableSpan; /** * Gets the provider identifier for debugging and logging purposes. * @returns A string identifying this trace provider implementation * @since 3.4.0 */ getProviderId(): string; /** * Determines if this provider is available and ready to create spans. * @returns true if the provider can create spans, false otherwise * @since 3.4.0 */ isAvailable(): boolean; } /** * An interface which provides automatic removal during unloading of the component */ interface IUnloadHook { /** * Self remove the referenced component */ rm: () => void; } /** * Interface which identifiesAdd this hook so that it is automatically removed during unloading * @param hooks - The single hook or an array of IInstrumentHook objects */ interface IUnloadHookContainer { add: (hooks: IUnloadHook | IUnloadHook[] | Iterator | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator) => void; run: (logger?: IDiagnosticLogger) => void; } /** * Represents a mutable [W3C trace state list](https://www.w3.org/TR/trace-context/#tracestate-header), this is a * list of key/value pairs that are used to pass trace state information between different tracing systems. The * list is ordered and the order is important as it determines the processing order. * * Importantly instances of this type are mutable, change made to an instance via {@link IW3cTraceState.set} or * {@link IW3cTraceState.del} will be reflected on the instance and any child instances that use it as a parent. * However, any parent instance associated with an instance will not be modified by operations on that particular * instance. * * @since 3.4.0 */ interface IW3cTraceState { /** * Returns a readonly array of the current keys associated with the trace state, keys are returned in the * required processing order and if this instance has a parent the keys from the parent will be included * unless they have been removed (deleted) from the child instance. * Once created any modifications to the parent will also be reflected in the child, this is different from * the OpenTelemetry implementation which creates a new instance for each call. * @returns A readonly array of the current keys associated with the trace state */ readonly keys: string[]; /** * Check if the trace state list is empty, meaning it has no keys or values. * This exists to allow for quick checks without needing to create a new array of keys. * @since 3.4.0 * @returns true if the trace state list is empty, false otherwise */ readonly isEmpty: boolean; /** * Get the value for the specified key that is associated with this instance, either directly or from the parent. * @param key - The key to lookup * @returns The value for the key, or undefined if not found */ get(key: string): string | undefined; /** * Set the value for the specified key for this instance, returning its new location within the list. * - 0 is the front of the list * - -1 not set because the key/value pair is invalid * If the key already exists it will be removed from its current location and added to the front of the list. And * if the key was in the parent this will override the value inherited from the parent, more importantly it will * not modify the parent value. * @param key - The key to set * @param value - The value to set * @returns 0 if successful, -1 if not */ set(key: string, value: string): number; /** * Delete the specified key from this instance, if the key was in the parent it will be removed (hidden) from * this instance but will still be available directly from the parent. * @param key - The key to delete */ del(key: string): void; /** * Format the trace state list into a strings where each string can be used as a header value. * This will return an empty array if the trace state list is empty. * @param maxHeaders - The maximum number of entries to include in the output, once the limit is reached no more entries will be included * @param maxKeys - The maximum number of keys to include in the output, once the limit is reached no more keys will be included * @param maxLen - The maximum length of each header value, once the limit is reached a new header value will be created * @returns An array of strings that can be used for the header values, if the trace state list is empty an empty array will be returned */ hdrs(maxHeaders?: number, maxKeys?: number, maxLen?: number): string[]; /** * Create a new instance of IW3cTraceState which is a child of this instance, meaning it will inherit the keys * and values from this instance but any changes made to the child will not affect this instance. * @returns A new instance of IW3cTraceState which is a child of this instance */ child(): IW3cTraceState; } 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 IXDomainRequest extends XMLHttpRequestEventTarget { readonly responseText: string; send(payload: string): void; open(method: string, url: string): void; timeout: number; contentType: string; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load" | "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; } /** * The IXHROverride interface overrides the way HTTP requests are sent. */ interface IXHROverride { sendPOST: SendPOSTFunction; } const LoggingSeverity: EnumValue; type LoggingSeverity = number | eLoggingSeverity; /** * 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; type OnCompleteCallback = (status: number, headers: { [headerName: string]: string; }, response?: string, payload?: IPayloadData) => void; /** * Attribute values may be any non-nullish primitive value except an object. * * null or undefined attribute values are invalid and will result in undefined behavior. * * @since 3.4.0 */ type OTelAttributeValue = string | number | boolean | Array | Array | Array; /** * Defines Exception. * * string or an object with one of (message or name or code) and optional stack * * @since 3.4.0 */ type OTelException = IOTelExceptionWithCode | IOTelExceptionWithMessage | IOTelExceptionWithName | string; /** * High-resolution time represented as a tuple of [seconds, nanoseconds]. * This is the base type for all OpenTelemetry high-resolution time values. * * @remarks * The first element represents seconds since Unix epoch, and the second element * represents nanoseconds (0-999,999,999) within that second. * * @example * ```typescript * const hrTime: OTelHrTimeBase = [1609459200, 500000000]; // 2021-01-01 00:00:00.5 UTC * ``` * * @since 3.4.0 */ type OTelHrTimeBase = [number, number]; /** * Creates an enum style object for the OTelSpanKind enum, providing the enum * values as properties of the object as both string and number types. * This allows for easy access to the enum values in a more readable format. */ const OTelSpanKind: EnumValue; type OTelSpanKind = number | eOTelSpanKind; /** * Union type representing all valid time input formats accepted by OpenTelemetry APIs. * * @remarks * - `IOTelHrTime`: High-resolution time with nanosecond precision * - `number`: Milliseconds since Unix epoch (JavaScript Date.now() format) * - `Date`: JavaScript Date object * * @example * ```typescript * // All of these are valid time inputs: * const hrTime: OTelTimeInput = [1609459200, 500000000]; * const msTime: OTelTimeInput = Date.now(); * const dateTime: OTelTimeInput = new Date(); * * span.addEvent("event", {}, hrTime); * span.addEvent("event", {}, msTime); * span.addEvent("event", {}, dateTime); * ``` * * @since 3.4.0 */ type OTelTimeInput = IOTelHrTime | number | Date; /** * 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); /** * 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); class Sender extends BaseTelemetryPlugin implements IChannelControls { static constructEnvelope(orig: ITelemetryItem, iKey: string, logger: IDiagnosticLogger, convertUndefined?: any): IEnvelope; readonly priority: number; readonly identifier: string; /** * The configuration for this sender instance */ readonly _senderConfig: ISenderConfig; /** * A method which will cause data to be send to the url */ _sender: SenderFunction; /** * A send buffer object */ _buffer: ISendBuffer; /** * AppId of this component parsed from some backend response. */ _appId: string; protected _sample: ISample; constructor(); /** * Pause the sending (transmission) of events, this will cause all events to be batched only until the maximum limits are * hit at which point new events are dropped. Will also cause events to NOT be sent during page unload, so if Session storage * is disabled events will be lost. * SessionStorage Limit is 2000 events, In-Memory (Array) Storage is 10,000 events (can be configured via the eventsLimitInMem). */ pause(): void; /** * Resume the sending (transmission) of events, this will restart the timer and any batched events will be sent using the normal * send interval. */ resume(): void; /** * Flush to send data immediately; channel should default to sending data asynchronously. If executing asynchronously (the default) 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; /** * Flush the batched events synchronously (if possible -- based on configuration). * Will not flush if the Send has been paused. */ onunloadFlush(): void; initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain): void; processTelemetry(telemetryItem: ITelemetryItem, itemCtx?: IProcessTelemetryContext): void; /** * xhr state changes * @deprecated * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility) */ _xhrReadyStateChange(xhr: XMLHttpRequest, payload: string[] | IInternalStorageItem[], countOfItemsInPayload: number): void; /** * Trigger the immediate send of buffered data; If executing asynchronously (the default) this may (not required) return * an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) that will resolve once the * send 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 - Indicates if the events should be sent asynchronously * @param forcedSender - Indicates the forcedSender, undefined if not passed * @returns - Nothing or optionally, if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * which will be resolved (or reject) once the send is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) * should only be returned when isAsync is true. */ triggerSend(isAsync?: boolean, forcedSender?: SenderFunction, sendReason?: SendRequestReason): void | IPromise; /** * error handler * @internal * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility) */ _onError(payload: string[] | IInternalStorageItem[], message: string, event?: ErrorEvent): void; /** * partial success handler * @internal * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility) */ _onPartialSuccess(payload: string[] | IInternalStorageItem[], results: IBackendResponse): void; /** * success handler * @internal * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility) */ _onSuccess(payload: string[] | IInternalStorageItem[], countOfItemsInPayload: number): void; /** * xdr state changes * @deprecated * since version 3.2.0, if the payload is string[], this function is no-op (string[] is only used for backwards Compatibility) */ _xdrOnLoad(xdr: IXDomainRequest, payload: string[] | IInternalStorageItem[]): void; /** * Add header to request * @param name - Header name. * @param value - Header value. */ addHeader(name: string, value: string): void; /** * Check if there are no active requests being sent. * @returns True if idle, false otherwise. */ isCompletelyIdle(): boolean; /** * Get Offline Serializer support * @returns internal Offline Serializer object */ getOfflineSupport(): IInternalOfflineSupport; /** * Get Offline listener * @returns offlineListener * @since 3.3.4 */ getOfflineListener(): IOfflineListener; } type SenderFunction = (payload: string[] | IInternalStorageItem[], isAsync: boolean) => void | IPromise; /** * SendPOSTFunction type defines how an HTTP POST request is sent to an ingestion server * @param payload - The payload object that should be sent, contains the url, bytes/string and headers for the request * @param oncomplete - The function to call once the request has completed whether a success, failure or timeout * @param sync - A boolean flag indicating whether the request should be sent as a synchronous request. */ type SendPOSTFunction = (payload: IPayloadData, oncomplete: OnCompleteCallback, sync?: boolean) => void | IPromise; /** * 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 } class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuffer { static VERSION: string; static BUFFER_KEY: string; static SENT_BUFFER_KEY: string; static MAX_BUFFER_SIZE: number; constructor(logger: IDiagnosticLogger, config: ISenderConfig); enqueue(payload: IInternalStorageItem): void; clear(): void; markAsSent(payload: IInternalStorageItem[]): void; clearSent(payload: IInternalStorageItem[]): void; createNew(newLogger?: IDiagnosticLogger, newConfig?: ISenderConfig, canUseSessionStorage?: boolean): ArraySendBuffer | SessionStorageSendBuffer; } interface Tags { [key: string]: any; } type TelemetryInitializerFunction = (item: T) => boolean | void; /** * 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 } type UnloadHandler = (itemCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) => void; const UrlRedactionOptions: EnumValue; type UrlRedactionOptions = boolean | eUrlRedactionOptions; type WatcherFunction = (details: IWatchDetails) => void; }