/* * Microsoft Application Insights JavaScript SDK Offline Channel, 0.4.3 * Copyright (c) Microsoft and contributors. All rights reserved. * * Microsoft Application Insights Team * https://github.com/microsoft/ApplicationInsights-JS#readme * * --------------------------------------------------------------------------- * This is a single combined (rollup) declaration file for the package, * if you require a namespace wrapped version it is also available. * - Namespaced version: types/applicationinsights-offlinechannel-js.namespaced.d.ts * --------------------------------------------------------------------------- */ import { BaseTelemetryPlugin } from '@microsoft/applicationinsights-core-js'; import { EnumValue } from '@microsoft/applicationinsights-core-js'; import { EventPersistence } from '@microsoft/applicationinsights-core-js'; import { IAppInsightsCore } from '@microsoft/applicationinsights-core-js'; import { IChannelControls } from '@microsoft/applicationinsights-core-js'; import { IConfig } from '@microsoft/applicationinsights-core-js'; import { IConfiguration } from '@microsoft/applicationinsights-core-js'; import { IDiagnosticLogger } from '@microsoft/applicationinsights-core-js'; import { INotificationManager } from '@microsoft/applicationinsights-core-js'; import { IOfflineListener } from '@microsoft/applicationinsights-core-js'; import { IPayloadData } from '@microsoft/applicationinsights-core-js'; import { IPlugin } from '@microsoft/applicationinsights-core-js'; import { IProcessTelemetryContext } from '@microsoft/applicationinsights-core-js'; import { IProcessTelemetryUnloadContext } from '@microsoft/applicationinsights-core-js'; import { IPromise } from '@nevware21/ts-async'; import { ITelemetryItem } from '@microsoft/applicationinsights-core-js'; import { ITelemetryPluginChain } from '@microsoft/applicationinsights-core-js'; import { ITelemetryUnloadState } from '@microsoft/applicationinsights-core-js'; import { IUnloadHookContainer } from '@microsoft/applicationinsights-core-js'; import { IXHROverride } from '@microsoft/applicationinsights-core-js'; import { SendRequestReason } from '@microsoft/applicationinsights-core-js'; export declare const BatchSendStatus: EnumValue; export declare type BatchSendStatus = number | eBatchSendStatus; export declare const BatchStoreStatus: EnumValue; export declare type BatchStoreStatus = number | eBatchStoreStatus; export declare type createDefaultOfflineDetector = (cfg?: IOfflineDetectorCfg) => IOfflineDetector; export declare type createNoopOfflineDetector = (cfg?: IOfflineDetectorCfg) => IOfflineDetector; export declare const enum eBatchSendStatus { Complete = 1, Retry = 2, Drop = 3, Failure = 4 } export declare const enum eBatchStoreStatus { Success = 1, Failure = 2 } /** * Identifies the Storage Providers used by the LocalStorageChannel */ export declare const enum eStorageProviders { /** * Identifies that the provider that uses (window||globalThis||self).localStorage */ LocalStorage = 1, /** * Identifies that the provider that uses (window||globalThis||self).sessionStorage */ SessionStorage = 2, /** * Identifies that the provider that uses (window||globalThis||self).indexedDB */ IndexedDb = 3 } export declare const enum eStorageType { Unknown = 0, LocalStorage = 1, SessionStorage = 2, IndexDb = 3 } /** * An internal interface which defines a in memory batch */ export declare interface IInMemoryBatch { /** * Enqueue the payload */ addEvent: (evt: IPostTransmissionTelemetryItem | ITelemetryItem) => boolean; /** * Returns the number of elements in the buffer */ count: () => number; /** * Returns items stored in the buffer */ getItems: () => IPostTransmissionTelemetryItem[] | ITelemetryItem[]; /** * Split this batch into 2 with any events > fromEvent returned in the new batch and all other * events are kept in the current batch. * @param fromEvt - The first event to remove from the current batch. * @param numEvts - The number of events to be removed from the current batch and returned in the new one. Defaults to all trailing events */ split: (fromEvt: number, numEvts?: number) => IInMemoryBatch; /** * create current buffer to a new endpoint with current logger * @param endpoint - new endpoint * @param evts - new events to be added * @param evtsLimitInMem - new evtsLimitInMem */ createNew(endpoint: string, evts?: IPostTransmissionTelemetryItem[] | ITelemetryItem[], evtsLimitInMem?: number): IInMemoryBatch; } /** * An internal interface which defines a common provider context that is used to pass multiple values when initializing provider instances */ export declare interface ILocalStorageProviderContext { /** * Identifies the context for the current event */ itemCtx?: IProcessTelemetryContext; /** * Identifies the local storage config that should be used to initialize the provider */ storageConfig: IOfflineChannelConfiguration; /** * Identifies the unique identifier to be used for this provider instance, when not provided a new Guid will be generated for this instance. * This value must be unique across all instances to avoid polluting events between browser / tabs instances as they may share the same persistent storage. * The primary use case for setting this value is for unit testing. */ id?: string; /** * Identifies endpoint url. */ endpoint?: string; /** * Identifies Notification Manager */ notificationMgr?: INotificationManager; } /** * Class that implements storing of events using the WebStorage Api ((window||globalThis||self).localstorage, (window||globalThis||self).sessionStorage). */ export declare class IndexedDbProvider implements IOfflineProvider { id: string; /** * Creates a WebStorageProvider using the provider storageType */ constructor(id?: string, unloadHookContainer?: IUnloadHookContainer); /** * Initializes the provider using the config * @param providerContext - The provider context that should be used to initialize the provider * @returns True if the provider is initialized and available for use otherwise false */ initialize(providerContext: ILocalStorageProviderContext): boolean; /** * Identifies whether this storage provider support synchronous requests */ supportsSyncRequests(): boolean; /** * Get all of the currently cached events from the storage mechanism */ getNextBatch(): IStorageTelemetryItem[] | IPromise | null; /** * Get all of the currently cached events from the storage mechanism */ getAllEvents(cnt?: number): IStorageTelemetryItem[] | IPromise | null; /** * Stores the value into the storage using the specified key. * @param key - The key value to use for the value * @param evt - The actual event of the request * @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) */ addEvent(key: string, evt: any, itemCtx: IProcessTelemetryContext): IStorageTelemetryItem | IPromise | null; /** * Removes the value associated with the provided key * @param evts - The events to be removed */ removeEvents(evts: any[]): IStorageTelemetryItem[] | IPromise | null; /** * Removes all entries from the storage provider, if there are any. */ clear(disable?: boolean): IStorageTelemetryItem[] | IPromise | null; /** * Removes all entries with stroage time longer than inStorageMaxTime from the storage provider */ clean(disable?: boolean): boolean | IPromise; /** * Shuts-down the telemetry plugin. This is usually called when telemetry is shut down. */ teardown(): void; } export declare class InMemoryBatch implements IInMemoryBatch { constructor(logger: IDiagnosticLogger, endpoint: string, evts?: IPostTransmissionTelemetryItem[], evtsLimitInMem?: number); addEvent(payload: IPostTransmissionTelemetryItem | ITelemetryItem): any; endpoint(): any; count(): number; clear(): void; getItems(): IPostTransmissionTelemetryItem[] | ITelemetryItem[]; /** * Split this batch into 2 with any events > fromEvent returned in the new batch and all other * events are kept in the current batch. * @param fromEvt - The first event to remove from the current batch. * @param numEvts - The number of events to be removed from the current batch and returned in the new one. Defaults to all trailing events */ split(fromEvt: number, numEvts?: number): any; /** * create current buffer to a new endpoint * @param endpoint - if not defined, current endpoint will be used * @param evts - new events to be added * @param addCurEvts - if it is set to true, current itemss will be transferred to the new batch */ createNew(endpoint: string, evts?: IPostTransmissionTelemetryItem[] | ITelemetryItem[], evtsLimitInMem?: number): any; } export declare interface IOfflineBatchCleanResponse { batchCnt: number; } export declare interface IOfflineBatchHandler { storeBatch(batch: IPayloadData, cb?: OfflineBatchStoreCallback, sync?: boolean): undefined | IOfflineBatchStoreResponse | IPromise; sendNextBatch(cb?: OfflineBatchCallback, sync?: boolean, xhrOverride?: IXHROverride, cnt?: number): undefined | IOfflineBatchResponse | IPromise; hasStoredBatch(callback?: (hasBatches: boolean) => void): undefined | boolean | IPromise; cleanStorage(cb?: (res: IOfflineBatchCleanResponse) => void): undefined | IOfflineBatchCleanResponse | IPromise; teardown(unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState): void; } export declare interface IOfflineBatchHandlerCfg { batchMaxSize?: number; storageType?: eStorageType; offineDetector?: IOfflineDetector; autoClean?: Boolean; maxRetryCnt?: number; } export declare interface IOfflineBatchResponse { state: eBatchSendStatus; data?: any; } export declare interface IOfflineBatchStoreResponse { state: eBatchStoreStatus; item?: any; } /** * The IOfflineChannelConfiguration interface defines the configuration options for offline channel, * supports offline events storage, retrieval and re-sending. */ export declare interface IOfflineChannelConfiguration { /** * [Optional] The max size in bytes that should be used for storing events(default up to 5 Mb) in local/session storage. * The maximum size in bytes that should be used for storing events in storage If not specified, the system will use up to 5 MB * @default 5000000 */ maxStorageSizeInBytes?: number; /** * [Optional] The storage key prefix that should be used when storing events in persistent storage. * @default AIOffline */ storageKeyPrefix?: string; /** * [Optional] Identifies the minimum level that will be cached in the offline channel. Valid values of this * setting are defined by the EventPersistence enum, currently Normal (1) and Critical (2) with the default * value being Normal (1), which means all events without a persistence level set or with invalid persistence level will be marked as Normal(1) events. * @default 1 */ minPersistenceLevel?: number | EventPersistence; /** * [Optional] Identifies the StorageProviders that should be used by the system if available, the first available * provider will be used. Valid available values are defined by the eStorageProviders enum. Only the first 5 entries * are processed, so if this value contains more than 5 elements they will be ignored. * Note: LocalStorage will be used to save unload events even if it is not in the providers list * Default order is [StorageProviders.LocalStorage, StorageProviders.IndexedDB] */ providers?: number[] | eStorageProviders[]; /** * [Optional] The IndexedDb database name that should be used when storing events using (window||globalThis||self).indexedDb. */ indexedDbName?: string; /** * [Optional] Identifies the maximum number of events to store in each memory batch before sending to persistent storage. * For versions > 3.3.2, new config splitEvts is added * If splitEvts is set true, eventsLimitInMem will be applied to each persistent level batch */ eventsLimitInMem?: number; /** * [Optional] Identifies if events that have existed in storage longer than the maximum allowed time (configured in inStorageMaxTime) should be cleaned after connection with storage. * If not provided, default is false */ autoClean?: boolean; /** * [Optional] Identifies the maximum time in ms that items should be in memory before being saved into storage. * @default 15000 */ inMemoMaxTime?: number; /** * [Optional] Identifies the maximum time in ms that items should be in persistent storage. * default: 10080000 (around 2.8 hours) for versions <= 3.3.0 * default: 604800000 (around 7days) for versions > 3.3.0 */ inStorageMaxTime?: number; /** * [Optional] Identifies the maximum retry times for an event batch. * default: 1 */ maxRetry?: number; /** * Identifies online channel IDs in order. The first available one will be used. * default is [AppInsightsChannelPlugin, PostChannel] */ primaryOnlineChannelId?: string[]; /** * Identifies the maximum size per batch in bytes that is saved in persistent storage. * default 63000 */ maxBatchsize?: number; /** * Identifies offline sender properties. If not defined, settings will be the same as the online channel configured in primaryOnlineChannelId. */ senderCfg?: IOfflineSenderConfig; /** * Identifies the interval time in ms that previously stored offline event batches should be sent under online status. * default 15000 */ maxSentBatchInterval?: number; /** * Identifies the maximum event batch count when cleaning or releasing space for persistent storage per time. * default 10 */ EventsToDropPerTime?: number; /** * Identifies the maximum critical events count for an event batch to be able to drop when releasing space for persistent storage per time. * default 2 */ maxCriticalEvtsDropCnt?: number; /** * Identifies overridden for the Instrumentation key when the offline channel calls processTelemetry. */ overrideInstrumentationKey?: string; /** * Identifies when saving events into the persistent storage, events will be batched and saved separately based on persistence level * this is useful to help reduce the loss of critical events during cleaning process * but it will result in more frequest storage implementations. * If it is set to false, all events will be saved into single in memory batch * Default: false */ splitEvts?: boolean; /** * [Optional] Custom provider that can be used instead of the provided LocalStorage, SessionStorage, IndexedDB. * Default: null * @since 3.9.10 */ customProvider?: IOfflineProvider; /** * [Optional] Custom unload provider should be used for handling unload scenarios. * This provider should support synchronous operations (supportsSyncRequests should return true) * If the unload provider is not provided, the provided customProvider will be used if it supports sync requests, * otherwise localStorage will be used by default. * Default: null * @since 3.9.10 */ customUnloadProvider?: IOfflineProvider; } export declare interface IOfflineDetector { startPolling(): boolean; stopPolling(): boolean; getOfflineListener(): IOfflineListener; } export declare interface IOfflineDetectorCfg { autoStop: boolean; pollingInterval: number; pollingUrl: string; } export declare interface IOfflineProvider { /** * Initializes the provider using the config * @param providerContext - The provider context that should be used to initialize the provider * @returns True if the provider is initialized and available for use otherwise false */ initialize(providerContext: ILocalStorageProviderContext): boolean; /** * Identifies whether this storage provider support synchronious requests */ supportsSyncRequests(): boolean; /** * Stores the value into the storage using the specified key. * @param key - The key value to use for the value * @param evt - The actual event of the request * @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) * @returns Either the added element (for synchronous operation) or a Promise for an asynchronous processing */ addEvent(key: string, evt: IStorageTelemetryItem, itemCtx: IProcessTelemetryContext): IStorageTelemetryItem | IPromise | null; /** * Get Next batch from the storage */ getNextBatch(): IStorageTelemetryItem[] | IPromise | null; /** * Get all stored batches from the storage. * @param cnt - batch numbers if it is defined, it will returns given number of batches. * if cnt is not defined, it will return all available batches */ getAllEvents(cnt?: number): IStorageTelemetryItem[] | IPromise | null; /** * Removes the value associated with the provided key * @param evts - The events to be removed * @returns Either the removed item array (for synchronous operation) or a Promise for an asynchronous processing */ removeEvents(evts: IStorageTelemetryItem[]): IStorageTelemetryItem[] | IPromise | null; /** * Removes all entries from the storage provider, if there are any. * @returns Either the removed item array (for synchronous operation) or a Promise for an asynchronous processing */ clear(): IStorageTelemetryItem[] | IPromise | null; /** * Removes all entries with stroage time longer than inStorageMaxTime from the storage provider */ clean(disable?: boolean): boolean | IPromise; /** * Shuts-down the telemetry plugin. This is usually called when telemetry is shut down. */ teardown(): void; } export declare interface IOfflineSenderConfig { /** * Identifies status codes for re-sending event batches * Default: [401, 403, 408, 429, 500, 502, 503, 504] */ retryCodes?: number[]; /** * [Optional] Either an array or single value identifying the requested TransportType type(s) that should be used for sending events * If not defined, the same transports will be used in the channel with the primaryOnlineChannelId */ transports?: number | number[]; /** * [Optional] The HTTP override that should be used to send requests, as an IXHROverride object. */ httpXHROverride?: IXHROverride; /** * Identifies if provided httpXhrOverride will always be used * default false */ alwaysUseXhrOverride?: boolean; } export declare interface IPostTransmissionTelemetryItem extends ITelemetryItem { /** * [Optional] An EventPersistence value, that specifies the persistence for the event. The EventPersistence constant */ persistence?: EventPersistence; } /** * An internal interface which defines a common storage item */ export declare interface IStorageTelemetryItem extends IPayloadData { id?: string; iKey?: string; sync?: boolean; criticalCnt?: number; isArr?: boolean; attempCnt?: number; } export declare type OfflineBatchCallback = (response: IOfflineBatchResponse) => void; export declare class OfflineBatchHandler implements IOfflineBatchHandler { constructor(logger?: IDiagnosticLogger, unloadHookContainer?: IUnloadHookContainer); /** * Initializes the provider using the config * @returns True if the provider is initialized and available for use otherwise false */ initialize(providerContext: ILocalStorageProviderContext): any; storeBatch(batch: IPayloadData, cb?: OfflineBatchStoreCallback, sync?: boolean): undefined | IOfflineBatchStoreResponse | IPromise; sendNextBatch(cb?: OfflineBatchCallback, sync?: boolean, xhrOverride?: IXHROverride, cnt?: number): undefined | IOfflineBatchResponse | IPromise; hasStoredBatch(callback?: (hasBatches: boolean) => void): undefined | boolean | IPromise; cleanStorage(cb?: (res: IOfflineBatchCleanResponse) => void): undefined | IOfflineBatchCleanResponse | IPromise; teardown(unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState): any; } export declare type OfflineBatchSendCallback = (response: IOfflineBatchResponse) => void; export declare type OfflineBatchStoreCallback = (response: IOfflineBatchStoreResponse) => void; export declare class OfflineChannel extends BaseTelemetryPlugin implements IChannelControls { identifier: string; priority: number; version: string; id: string; constructor(); /** * The function does the initial set up. It adds a notification listener to determine which events to remove. * @param coreConfig - The core configuration. * @param core - The AppInsights core. * @param extensions - An array of all the plugins being used. */ initialize(coreConfig: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain): void; /** * Process an event to add it to the local storage and then pass it to the next plugin. * @param event - The event that needs to be stored. * @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(evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext): void; /** * Pauses the adding of new events to the plugin. Also calls pause on the next * plugin. */ pause(): void; /** * Resumes the adding of new events to the plugin. Also calls resume on * the next plugin. Adds all events in storage to the next plugin. */ resume(): void; /** * Get offline listener * @returns offline listener */ getOfflineListener(): any; /** *No op */ flush(sync: 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; /** * Flush the next stored event batch */ sendNextBatch(): void; } export declare class Sender { _appId: string; 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. */ 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; initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, cxt: IProcessTelemetryContext, diagLog: IDiagnosticLogger, channelId?: string, unloadHookContainer?: IUnloadHookContainer): 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 async - 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 async is true. */ triggerSend(async?: boolean, forcedSender?: SenderFunction, sendReason?: SendRequestReason): void | IPromise; /** * Check if there are no active requests being sent. * @returns True if idle, false otherwise. */ isCompletelyIdle(): boolean; /** * Get current xhr instance */ getXhrInst(sync?: boolean): any; _doTeardown(unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState): void; } declare type SenderFunction = (payload: string[], isAsync: boolean) => void | IPromise; export declare const StorageProviders: EnumValue; export declare type StorageProviders = number | eStorageProviders; export declare const StorageType: EnumValue; export declare type StorageType = number | eStorageType; /** * Class that implements storing of events using the WebStorage Api ((window||globalThis||self).localstorage, (window||globalThis||self).sessionStorage). */ export declare class WebStorageProvider implements IOfflineProvider { id: string; /** * Creates a WebStorageProvider using the provider storageType * @param storageType - The type of Storage provider, normal values are "localStorage" or "sessionStorage" */ constructor(storageType: string, id?: string, unloadHookContainer?: IUnloadHookContainer); /** * Initializes the provider using the config * @param providerContext - The provider context that should be used to initialize the provider * @returns True if the provider is initialized and available for use otherwise false */ initialize(providerContext: ILocalStorageProviderContext): boolean; /** * Identifies whether this storage provider support synchronous requests */ supportsSyncRequests(): boolean; /** * Get all of the currently cached events from the storage mechanism */ getAllEvents(cnt?: number): IStorageTelemetryItem[] | IPromise | null; /** * Get the Next one cached batch from the storage mechanism */ getNextBatch(): IStorageTelemetryItem[] | IPromise | null; /** * Stores the value into the storage using the specified key. * @param key - The key value to use for the value * @param evt - The actual event of the request * @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) */ addEvent(key: string, evt: any, itemCtx: IProcessTelemetryContext): IStorageTelemetryItem | IPromise | null; /** * Removes the value associated with the provided key * @param evts - The events to be removed */ removeEvents(evts: any[]): IStorageTelemetryItem[] | IPromise | null; /** * Removes all entries from the storage provider, if there are any. */ clear(): IStorageTelemetryItem[] | IPromise | null; /** * Removes all entries with stroage time longer than inStorageMaxTime from the storage provider */ clean(): boolean | IPromise; /** * Shuts-down the telemetry plugin. This is usually called when telemetry is shut down. */ teardown(): void; } export { }