@microsoft/1ds-post-js
Version:
Microsoft Application Insights JavaScript SDK - 1ds-post-channel-js
1,013 lines (987 loc) • 226 kB
TypeScript
/*
* 1DS JS SDK Post Channel, 4.4.3
* Copyright (c) Microsoft and contributors. All rights reserved.
*
* Microsoft Application Insights Team
* https://github.com/microsoft/ApplicationInsights-JS#readme
*/
declare namespace oneDS {
/// <reference lib="es2015" />
/**
* 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<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>): void;
}
/**
* Best Effort. RealTime Latency events are sent every 9 sec and
* Normal Latency events are sent every 18 sec.
*/
const BE_PROFILE = "BEST_EFFORT";
const enum eActiveStatus {
NONE = 0,
/**
* inactive status means there might be rejected ikey/endpoint promises or ikey/endpoint resolved is not valid
*/
INACTIVE = 1,
/**
* active mean ikey/endpoint promises is resolved and initializing with ikey/endpoint is successful
*/
ACTIVE = 2,
/**
* Waiting for promises to be resolved
* NOTE: if status is set to be pending, incoming changes will be dropped until pending status is removed
*/
PENDING = 3
}
/**
* Const enum 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 _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,
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,
MaxUnloadHookExceeded = 9948
}
const enum eLoggingSeverity {
/**
* No Logging will be enabled
*/
DISABLED = 0,
/**
* Error will be sent as internal telemetry
*/
CRITICAL = 1,
/**
* Error will NOT be sent as internal telemetry, and will only be shown in browser console
*/
WARNING = 2,
/**
* The Error will NOT be sent as an internal telemetry, and will only be shown in the browser
* console if the logging level allows it.
*/
DEBUG = 3
}
/**
* A type that identifies an enum class generated from a constant enum.
* @group Enum
* @typeParam E - The constant enum type
*
* Returned from {@link createEnum}
*/
type EnumCls<E = any> = {
readonly [key in keyof E extends string | number | symbol ? keyof E : never]: key extends string ? E[key] : key;
} & {
readonly [key in keyof E]: E[key];
};
type EnumValue<E = any> = EnumCls<E>;
/**
* 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
}
type FieldValueSanitizerFunc = (details: IFieldSanitizerDetails) => IEventProperty | null;
const enum FieldValueSanitizerType {
NotSet = 0,
String = 1,
Number = 2,
Boolean = 3,
Object = 4,
Array = 4096,
EventProperty = 8192
}
type FieldValueSanitizerTypes = string | number | boolean | object | string[] | number[] | boolean[] | IEventProperty;
/**
* This defines the handler function that is called via the finally when the promise is resolved or rejected
*/
type FinallyPromiseHandler = (() => void) | undefined | null;
interface IAppInsightsCore<CfgType extends IConfiguration = IConfiguration> extends IPerfManagerProvider, ITraceHost<CfgType> {
/**
* The current logger instance for this instance.
*/
readonly logger: IDiagnosticLogger;
/**
* An array of the installed plugins that provide a version
*/
readonly pluginVersionStringArr: string[];
/**
* The formatted string of the installed plugins that contain a version number
*/
readonly pluginVersionString: string;
/**
* Returns a value that indicates whether the instance has already been previously initialized.
*/
isInitialized?: () => boolean;
initialize(config: CfgType, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void;
getChannels(): IChannelControls[];
track(telemetryItem: ITelemetryItem): void;
/**
* Get the current notification manager
*/
getNotifyMgr(): INotificationManager;
/**
* Get the current cookie manager for this instance
*/
getCookieMgr(): ICookieMgr;
/**
* Set the current cookie manager for this instance
* @param cookieMgr - The manager, if set to null/undefined will cause the default to be created
*/
setCookieMgr(cookieMgr: ICookieMgr): void;
/**
* Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.
* The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be
* called.
* @param listener - An INotificationListener object.
*/
addNotificationListener?(listener: INotificationListener): void;
/**
* Removes all instances of the listener.
* @param listener - INotificationListener to remove.
*/
removeNotificationListener?(listener: INotificationListener): void;
/**
* Add a telemetry processor to decorate or drop telemetry events.
* @param telemetryInitializer - The Telemetry Initializer function
* @returns - A ITelemetryInitializerHandler to enable the initializer to be removed
*/
addTelemetryInitializer(telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler;
pollInternalLogs?(eventName?: string): ITimerHandler;
stopPollingInternalLogs?(): void;
/**
* Return a new instance of the IProcessTelemetryContext for processing events
*/
getProcessTelContext(): IProcessTelemetryContext;
/**
* Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered
* to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous
* unload call return `true` stating that all plugins reported that they also unloaded, the recommended
* approach is to create a new instance and initialize that instance.
* This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable
* to successfully remove any global references or they may just be completing the unload process asynchronously.
* If you pass isAsync as `true` (also the default) and DO NOT pass a callback function then an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
* will be returned which will resolve once the unload is complete. The actual implementation of the `IPromise`
* will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)
* @param isAsync - Can the unload be performed asynchronously (default)
* @param unloadComplete - An optional callback that will be called once the unload has completed
* @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the
* unload. Defaults to 5 seconds.
* @returns Nothing or if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
* which will be resolved once the unload is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
* will only be returned when no callback is provided and isAsync is true
*/
unload(isAsync?: boolean, unloadComplete?: (unloadState: ITelemetryUnloadState) => void, cbTimeout?: number): void | IPromise<ITelemetryUnloadState>;
/**
* Find and return the (first) plugin with the specified identifier if present
*/
getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T>;
/**
* Add a new plugin to the installation
* @param plugin - The new plugin to add
* @param replaceExisting - should any existing plugin be replaced, default is false
* @param doAsync - Should the add be performed asynchronously
* @param addCb - [Optional] callback to call after the plugin has been added
*/
addPlugin<T extends IPlugin = ITelemetryPlugin>(plugin: T, replaceExisting?: boolean, doAsync?: boolean, addCb?: (added?: boolean) => void): void;
/**
* Update the configuration used and broadcast the changes to all loaded plugins, this does NOT support updating, adding or removing
* any the plugins (extensions or channels). It will notify each plugin (if supported) that the configuration has changed but it will
* not remove or add any new plugins, you need to call addPlugin or getPlugin(identifier).remove();
* @param newConfig - The new configuration is apply
* @param mergeExisting - Should the new configuration merge with the existing or just replace it. Default is to merge.
*/
updateCfg(newConfig: CfgType, mergeExisting?: boolean): void;
/**
* Returns the unique event namespace that should be used when registering events
*/
evtNamespace(): string;
/**
* Add a handler that will be called when the SDK is being unloaded
* @param handler - the handler
*/
addUnloadCb(handler: UnloadHandler): void;
/**
* Add this hook so that it is automatically removed during unloading
* @param hooks - The single hook or an array of IInstrumentHook objects
*/
addUnloadHook(hooks: IUnloadHook | IUnloadHook[] | Iterator<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>): void;
/**
* Flush and send any batched / cached data immediately
* @param async - send data asynchronously when true (defaults to true)
* @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called.
* If the caller doesn't return true the caller should assume that it may never be called.
* @param sendReason - specify the reason that you are calling "flush" defaults to ManualFlush (1) if not specified
* @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the unload. Defaults to 5 seconds.
* @returns - true if the callback will be return after the flush is complete otherwise the caller should assume that any provided callback will never be called
*/
flush(isAsync?: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason, cbTimeout?: number): boolean | void;
/**
* 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<ITraceProvider>): void;
/**
* Watches and tracks changes for accesses to the current config, and if the accessed config changes the
* handler will be recalled.
* @returns A watcher handler instance that can be used to remove itself when being unloaded
*/
onCfgChange(handler: WatcherFunction<CfgType>): IUnloadHook;
/**
* Function used to identify the get w parameter used to identify status bit to some channels
*/
getWParam: () => number;
/**
* Watches and tracks status of initialization process
* @returns ActiveStatus
* @since 3.3.0
* If returned status is active, it means initialization process is completed.
* If returned status is pending, it means the initialization process is waiting for promieses to be resolved.
* If returned status is inactive, it means ikey is invalid or can 't get ikey or enpoint url from promsises.
*/
activeStatus?: () => eActiveStatus | number;
/**
* Set Active Status to pending, which will block the incoming changes until internal promises are resolved
* @internal Internal use
* @since 3.3.0
*/
_setPendingStatus?: () => void;
}
/**
* Information about what changed in an attribute container
*/
interface IAttributeChangeInfo<V extends OTelAttributeValue = OTelAttributeValue> {
/**
* 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<V extends OTelAttributeValue = OTelAttributeValue> {
/**
* 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<string>;
/**
* 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<V>;
/**
* 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<V>) => 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 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: <T>(identifier: string, defaultValue?: IConfigDefaults<T>, 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: <T extends ITelemetryPlugin = ITelemetryPlugin>(callback: (plugin: T) => void) => void;
/**
* Set the function to call when the current chain has executed all processNext or unloadNext items.
* @param onComplete - The onComplete to call
* @param that - The "this" value to use for the onComplete call, if not provided or undefined defaults to the current context
* @param args - Any additional arguments to pass to the onComplete function
*/
onComplete: (onComplete: () => void, that?: any, ...args: any[]) => void;
/**
* Create a new context using the core and config from the current instance, returns a new instance of the same type
* @param plugins - The execution order to process the plugins, if null or not supplied
* then the current execution order will be copied.
* @param startAt - The plugin to start processing from, if missing from the execution
* order then the next plugin will be NOT set.
*/
createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IBaseProcessingContext;
}
/**
* 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<string> = {
* v: "some value"
* };
* ```
*/
interface ICachedValue<T> {
/**
* Returns the current cached value
*/
v: T;
/**
* Returns the current cached value
*/
toJSON(): T;
}
/**
* The IChannelConfiguration interface holds the configuration details passed to Post module.
*/
interface IChannelConfiguration {
/**
* [Optional] The number of events that can be kept in memory before the SDK starts to drop events. By default, this is 10,000.
*/
eventsLimitInMem?: number;
/**
* [Optional] Sets the maximum number of immediate latency events that will be cached in memory before the SDK starts to drop other
* immediate events only, does not drop normal and real time latency events as immediate events have their own internal queue. Under
* normal situations immediate events are scheduled to be sent in the next Javascript execution cycle, so the typically number of
* immediate events is small (~1), the only time more than one event may be present is when the channel is paused or immediate send
* is disabled (via manual transmit profile). By default max number of events is 500 and the default transmit time is 0ms.
*/
immediateEventLimit?: number;
/**
* [Optional] If defined, when the number of queued events reaches or exceeded this limit this will cause the queue to be immediately
* flushed rather than waiting for the normal timers. Defaults to undefined.
*/
autoFlushEventsLimit?: number;
/**
* [Optional] If defined allows you to disable the auto batch (iKey set of requests) flushing logic. This is in addition to the
* default transmission profile timers, autoFlushEventsLimit and eventsLimitInMem config values.
*/
disableAutoBatchFlushLimit?: boolean;
/**
* [Optional] Sets the record and request size limit in bytes for serializer.
* Default for record size (sync) is 65000, record size (async) is 2000000.
* Default for request size (sync) is 65000, request size (async) is 3145728.
* @since 3.3.7
*/
requestLimit?: IRequestSizeLimit;
/**
* [Optional] Sets the limit number of events per batch.
* Default is 500
* @since 3.3.7
*/
maxEvtPerBatch?: number;
/**
* [Optional] The HTTP override that should be used to send requests, as an IXHROverride object.
* By default during the unload of a page or if the event specifies that it wants to use sendBeacon() or sync fetch (with keep-alive),
* this override will NOT be called. You can now change this behavior by enabling the 'alwaysUseXhrOverride' configuration value.
* The payload data (first argument) now also includes any configured 'timeout' (defaults to undefined) and whether you should avoid
* creating any synchronous XHR requests 'disableXhrSync' (defaults to false/undefined)
*/
httpXHROverride?: IXHROverride;
/**
* Override for Instrumentation key
*/
overrideInstrumentationKey?: string;
/**
* Override for Endpoint where telemetry data is sent
*/
overrideEndpointUrl?: string;
/**
* The master off switch. Do not send any data if set to TRUE
*/
disableTelemetry?: boolean;
/**
* MC1 and MS0 cookies will not be returned from Collector endpoint.
*/
ignoreMc1Ms0CookieProcessing?: boolean;
/**
* Override for setTimeout
*/
setTimeoutOverride?: typeof setTimeout;
/**
* Override for clearTimeout
*/
clearTimeoutOverride?: typeof clearTimeout;
/**
* [Optional] POST channel preprocessing function. Can be used to gzip the payload before transmission and to set the appropriate
* Content-Encoding header. The preprocessor is explicitly not called during teardown when using the sendBeacon() API.
*/
payloadPreprocessor?: PayloadPreprocessorFunction;
/**
* [Optional] POST channel listener function, used for enabling logging or reporting (RemoteDDVChannel) of the payload that is being sent.
*/
payloadListener?: PayloadListenerFunction;
/**
* [Optional] By default additional timing metrics details are added to each event after they are sent to allow you to review how long it took
* to create serialized request. As not all implementations require this level of detail and it's now possible to get the same metrics via
* the IPerfManager and IPerfEvent we are enabling these details to be disabled. Default value is false to retain the previous behavior,
* if you are not using these metrics and performance is a concern then it is recommended to set this value to true.
*/
disableEventTimings?: boolean;
/**
* [Optional] The value sanitizer to use while constructing the envelope.
*/
valueSanitizer?: IValueSanitizer;
/**
* [Optional] During serialization, when an object is identified, should the object be serialized by JSON.stringify(theObject); (when true) otherwise by theObject.toString().
* Defaults to false
*/
stringifyObjects?: boolean;
/**
* [Optional] Enables support for objects with compound keys which indirectly represent an object where the "key" of the object contains a "." as part of it's name.
* @example
* ```typescript
* event: { "somedata.embeddedvalue": 123 }
* ```
*/
enableCompoundKey?: boolean;
/**
* [Optional] Switch to disable the v8 optimizeObject() calls used to provide better serialization performance. Defaults to false.
*/
disableOptimizeObj?: boolean;
/**
* [Optional] By default a "Cache-Control" header will be added to the outbound payloads with the value "no-cache, no-store", this is to
* avoid instances where Chrome can "Stall" requests which use the same outbound URL.
*/
/**
* [Optional] Either an array or single value identifying the requested TransportType type that should be used.
* This is used during initialization to identify the requested send transport, it will be ignored if a httpXHROverride is provided.
*/
transports?: number | number[];
/**
* [Optional] Either an array or single value identifying the requested TransportType type(s) that should be used during unload or events
* marked as sendBeacon. This is used during initialization to identify the requested send transport, it will be ignored if a httpXHROverride
* is provided and alwaysUseXhrOverride is true.
*/
unloadTransports?: number | number[];
/**
* [Optional] A flag to enable or disable the usage of the sendBeacon() API (if available). If running on ReactNative this defaults
* to `false` for all other cases it defaults to `true`.
*/
useSendBeacon?: boolean;
/**
* [Optional] A flag to disable the usage of the [fetch with keep-alive](https://javascript.info/fetch-api#keepalive) support.
*/
disableFetchKeepAlive?: boolean;
/**
* [Optional] Avoid adding request headers to the outgoing request that would cause a pre-flight (OPTIONS) request to be sent for each request.
* This currently defaults to false. This is changed as the collector enables Access-Control-Max-Age to allow the browser to better cache any
* previous OPTIONS response. Hence, we moved some of the current dynamic values sent on the query string to a header.
*/
avoidOptions?: boolean;
/**
* [Optional] Specify a timeout (in ms) to apply to requests when sending requests using XHR, XDR or fetch requests. Defaults to undefined
* and therefore the runtime defaults (normally zero for browser environments)
*/
xhrTimeout?: number;
/**
* [Optional] When using Xhr for sending requests disable sending as synchronous during unload or synchronous flush.
* You should enable this feature for IE (when there is no sendBeacon() or fetch (with keep-alive)) and you have clients
* that end up blocking the UI during page unloading. This will cause ALL XHR requests to be sent asynchronously which
* during page unload may result in the lose of telemetry.
*/
disableXhrSync?: boolean;
/**
* [Optional] By default during unload (or when you specify to use sendBeacon() or sync fetch (with keep-alive) for an event) the SDK
* ignores any provided httpXhrOverride and attempts to use sendBeacon() or fetch(with keep-alive) when they are available.
* When this configuration option is true any provided httpXhrOverride will always be used, so any provided httpXhrOverride will
* also need to "handle" the synchronous unload scenario.
*/
alwaysUseXhrOverride?: boolean;
/**
* [Optional] Identifies the number of times any single event will be retried if it receives a failed (retirable) response, this
* causes the event to be internally "requeued" and resent in the next batch. As each normal batched send request is retried at
* least once before starting to increase the internal backoff send interval, normally batched events will generally be attempted
* the next nearest even number of times. This means that the total number of actual send attempts will almost always be even
* (setting to 5 will cause 6 requests), unless using manual synchronous flushing (calling flush(false)) which is not subject to
* request level retry attempts.
* Defaults to 6 times.
*/
maxEventRetryAttempts?: number;
/**