@microsoft/applicationinsights-channel-js 3.0.7 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/browser/es5/{applicationinsights-channel-js.3.0.7.cjs.js → applicationinsights-channel-js.3.0.9.cjs.js} +273 -239
  2. package/browser/es5/applicationinsights-channel-js.3.0.9.cjs.js.map +1 -0
  3. package/browser/es5/applicationinsights-channel-js.3.0.9.cjs.min.js +6 -0
  4. package/browser/es5/applicationinsights-channel-js.3.0.9.cjs.min.js.map +1 -0
  5. package/browser/es5/{applicationinsights-channel-js.3.0.7.gbl.js → applicationinsights-channel-js.3.0.9.gbl.js} +275 -241
  6. package/browser/es5/applicationinsights-channel-js.3.0.9.gbl.js.map +1 -0
  7. package/browser/es5/applicationinsights-channel-js.3.0.9.gbl.min.js +6 -0
  8. package/browser/es5/applicationinsights-channel-js.3.0.9.gbl.min.js.map +1 -0
  9. package/browser/es5/applicationinsights-channel-js.3.0.9.integrity.json +66 -0
  10. package/browser/es5/{applicationinsights-channel-js.3.0.7.js → applicationinsights-channel-js.3.0.9.js} +275 -241
  11. package/browser/es5/applicationinsights-channel-js.3.0.9.js.map +1 -0
  12. package/browser/es5/applicationinsights-channel-js.3.0.9.min.js +6 -0
  13. package/browser/es5/applicationinsights-channel-js.3.0.9.min.js.map +1 -0
  14. package/browser/es5/applicationinsights-channel-js.3.cjs.js +272 -238
  15. package/browser/es5/applicationinsights-channel-js.3.cjs.js.map +1 -1
  16. package/browser/es5/applicationinsights-channel-js.3.cjs.min.js +2 -2
  17. package/browser/es5/applicationinsights-channel-js.3.cjs.min.js.map +1 -1
  18. package/browser/es5/applicationinsights-channel-js.3.gbl.js +274 -240
  19. package/browser/es5/applicationinsights-channel-js.3.gbl.js.map +1 -1
  20. package/browser/es5/applicationinsights-channel-js.3.gbl.min.js +2 -2
  21. package/browser/es5/applicationinsights-channel-js.3.gbl.min.js.map +1 -1
  22. package/browser/es5/applicationinsights-channel-js.3.integrity.json +25 -25
  23. package/browser/es5/applicationinsights-channel-js.3.js +274 -240
  24. package/browser/es5/applicationinsights-channel-js.3.js.map +1 -1
  25. package/browser/es5/applicationinsights-channel-js.3.min.js +2 -2
  26. package/browser/es5/applicationinsights-channel-js.3.min.js.map +1 -1
  27. package/dist/es5/applicationinsights-channel-js.js +272 -238
  28. package/dist/es5/applicationinsights-channel-js.js.map +1 -1
  29. package/dist/es5/applicationinsights-channel-js.min.js +2 -2
  30. package/dist/es5/applicationinsights-channel-js.min.js.map +1 -1
  31. package/dist-es5/EnvelopeCreator.js +2 -2
  32. package/dist-es5/EnvelopeCreator.js.map +1 -1
  33. package/dist-es5/Interfaces.js +1 -1
  34. package/dist-es5/InternalConstants.js +1 -1
  35. package/dist-es5/Offline.js +1 -1
  36. package/dist-es5/SendBuffer.js +1 -1
  37. package/dist-es5/Sender.js +14 -5
  38. package/dist-es5/Sender.js.map +1 -1
  39. package/dist-es5/Serializer.js +1 -1
  40. package/dist-es5/TelemetryProcessors/Sample.js +1 -1
  41. package/dist-es5/TelemetryProcessors/SamplingScoreGenerators/HashCodeScoreGenerator.js +1 -1
  42. package/dist-es5/TelemetryProcessors/SamplingScoreGenerators/SamplingScoreGenerator.js +1 -1
  43. package/dist-es5/__DynamicConstants.js +3 -3
  44. package/dist-es5/__DynamicConstants.js.map +1 -1
  45. package/dist-es5/applicationinsights-channel-js.js +1 -1
  46. package/package.json +65 -62
  47. package/types/applicationinsights-channel-js.d.ts +7 -2
  48. package/types/applicationinsights-channel-js.namespaced.d.ts +2477 -42
  49. package/browser/es5/applicationinsights-channel-js.3.0.7.cjs.js.map +0 -1
  50. package/browser/es5/applicationinsights-channel-js.3.0.7.cjs.min.js +0 -6
  51. package/browser/es5/applicationinsights-channel-js.3.0.7.cjs.min.js.map +0 -1
  52. package/browser/es5/applicationinsights-channel-js.3.0.7.gbl.js.map +0 -1
  53. package/browser/es5/applicationinsights-channel-js.3.0.7.gbl.min.js +0 -6
  54. package/browser/es5/applicationinsights-channel-js.3.0.7.gbl.min.js.map +0 -1
  55. package/browser/es5/applicationinsights-channel-js.3.0.7.integrity.json +0 -66
  56. package/browser/es5/applicationinsights-channel-js.3.0.7.js.map +0 -1
  57. package/browser/es5/applicationinsights-channel-js.3.0.7.min.js +0 -6
  58. package/browser/es5/applicationinsights-channel-js.3.0.7.min.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /*
2
- * Microsoft Application Insights JavaScript SDK Channel, 3.0.7
2
+ * Microsoft Application Insights JavaScript SDK Channel, 3.0.9
3
3
  * Copyright (c) Microsoft and contributors. All rights reserved.
4
4
  *
5
5
  * Microsoft Application Insights Team
@@ -7,59 +7,1946 @@
7
7
  */
8
8
 
9
9
  declare namespace ApplicationInsights {
10
- import { BaseTelemetryPlugin } from '@microsoft/applicationinsights-core-js';
11
- import { IAppInsightsCore } from '@microsoft/applicationinsights-core-js';
12
- import { IChannelControls } from '@microsoft/applicationinsights-core-js';
13
- import { IConfig } from '@microsoft/applicationinsights-common';
14
- import { IConfiguration } from '@microsoft/applicationinsights-core-js';
15
- import { IDiagnosticLogger } from '@microsoft/applicationinsights-core-js';
16
- import { IEnvelope } from '@microsoft/applicationinsights-common';
17
- import { IPlugin } from '@microsoft/applicationinsights-core-js';
18
- import { IProcessTelemetryContext } from '@microsoft/applicationinsights-core-js';
19
- import { IPromise } from '@nevware21/ts-async';
20
- import { ISample } from '@microsoft/applicationinsights-common';
21
- import { IStorageBuffer } from '@microsoft/applicationinsights-common';
22
- import { ITelemetryItem } from '@microsoft/applicationinsights-core-js';
23
- import { ITelemetryPluginChain } from '@microsoft/applicationinsights-core-js';
24
- import { IXHROverride } from '@microsoft/applicationinsights-core-js';
25
- import { SendRequestReason } from '@microsoft/applicationinsights-core-js';
10
+ class ArraySendBuffer extends BaseSendBuffer implements ISendBuffer {
11
+ constructor(logger: IDiagnosticLogger, config: ISenderConfig);
12
+ markAsSent(payload: string[]): void;
13
+ clearSent(payload: string[]): void;
14
+ }
15
+
16
+ abstract class BaseSendBuffer {
17
+ protected _get: () => string[];
18
+ protected _set: (buffer: string[]) => string[];
19
+ constructor(logger: IDiagnosticLogger, config: ISenderConfig);
20
+ enqueue(payload: string): void;
21
+ count(): number;
22
+ size(): number;
23
+ clear(): void;
24
+ getItems(): string[];
25
+ batchPayloads(payload: string[]): string;
26
+ createNew(newLogger?: IDiagnosticLogger, newConfig?: ISenderConfig, canUseSessionStorage?: boolean): ArraySendBuffer | SessionStorageSendBuffer;
27
+ }
28
+
29
+ /**
30
+ * BaseTelemetryPlugin provides a basic implementation of the ITelemetryPlugin interface so that plugins
31
+ * can avoid implementation the same set of boiler plate code as well as provide a base
32
+ * implementation so that new default implementations can be added without breaking all plugins.
33
+ */
34
+ abstract class BaseTelemetryPlugin implements ITelemetryPlugin {
35
+ identifier: string;
36
+ version?: string;
37
+ /**
38
+ * Holds the core instance that was used during initialization
39
+ */
40
+ core: IAppInsightsCore;
41
+ priority: number;
42
+ /**
43
+ * Call back for telemetry processing before it it is sent
44
+ * @param env - This is the current event being reported
45
+ * @param itemCtx - This is the context for the current request, ITelemetryPlugin instances
46
+ * can optionally use this to access the current core instance or define / pass additional information
47
+ * to later plugins (vs appending items to the telemetry item)
48
+ */
49
+ processNext: (env: ITelemetryItem, itemCtx: IProcessTelemetryContext) => void;
50
+ /**
51
+ * Set next extension for telemetry processing
52
+ */
53
+ setNextPlugin: (next: ITelemetryPlugin | ITelemetryPluginChain) => void;
54
+ /**
55
+ * Returns the current diagnostic logger that can be used to log issues, if no logger is currently
56
+ * assigned a new default one will be created and returned.
57
+ */
58
+ diagLog: (itemCtx?: IProcessTelemetryContext) => IDiagnosticLogger;
59
+ /**
60
+ * Returns whether the plugin has been initialized
61
+ */
62
+ isInitialized: () => boolean;
63
+ /**
64
+ * Helper to return the current IProcessTelemetryContext, if the passed argument exists this just
65
+ * returns that value (helps with minification for callers), otherwise it will return the configured
66
+ * context or a temporary one.
67
+ * @param currentCtx - [Optional] The current execution context
68
+ */
69
+ protected _getTelCtx: (currentCtx?: IProcessTelemetryContext) => IProcessTelemetryContext;
70
+ /**
71
+ * Internal helper to allow setting of the internal initialized setting for inherited instances and unit testing
72
+ */
73
+ protected setInitialized: (isInitialized: boolean) => void;
74
+ /**
75
+ * Teardown / Unload hook to allow implementations to perform some additional unload operations before the BaseTelemetryPlugin
76
+ * finishes it's removal.
77
+ * @param unloadCtx - This is the context that should be used during unloading.
78
+ * @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.
79
+ * @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.
80
+ * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations.
81
+ */
82
+ protected _doTeardown?: (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState, asyncCallback?: () => void) => void | boolean;
83
+ /**
84
+ * Extension hook to allow implementations to perform some additional update operations before the BaseTelemetryPlugin finishes it's removal
85
+ * @param updateCtx - This is the context that should be used during updating.
86
+ * @param updateState - The details / state of the update process, it holds details like the current and previous configuration.
87
+ * @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.
88
+ * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations.
89
+ */
90
+ protected _doUpdate?: (updateCtx?: IProcessTelemetryUpdateContext, updateState?: ITelemetryUpdateState, asyncCallback?: () => void) => void | boolean;
91
+ /**
92
+ * Exposes the underlying unload hook container instance for this extension to allow it to be passed down to any sub components of the class.
93
+ * 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
94
+ * it's scoped as protected)
95
+ */
96
+ protected readonly _unloadHooks: IUnloadHookContainer;
97
+ constructor();
98
+ initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain): void;
99
+ /**
100
+ * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and
101
+ * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further
102
+ * processTelemetry calls are ignored and it just calls the processNext() with the provided context.
103
+ * @param unloadCtx - This is the context that should be used during unloading.
104
+ * @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.
105
+ * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing.
106
+ */
107
+ teardown(unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState): void | boolean;
108
+ abstract processTelemetry(env: ITelemetryItem, itemCtx?: IProcessTelemetryContext): void;
109
+ /**
110
+ * The the plugin should re-evaluate configuration and update any cached configuration settings.
111
+ * @param updateCtx - This is the context that should be used during updating.
112
+ * @param updateState - The details / state of the update process, it holds details like the current and previous configuration.
113
+ * @returns boolean - true if the plugin has or will call updateCtx.processNext(), this allows the plugin to perform any asynchronous operations.
114
+ */
115
+ update(updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState): void | boolean;
116
+ /**
117
+ * Add an unload handler that will be called when the SDK is being unloaded
118
+ * @param handler - the handler
119
+ */
120
+ protected _addUnloadCb(handler: UnloadHandler): void;
121
+ /**
122
+ * Add this hook so that it is automatically removed during unloading
123
+ * @param hooks - The single hook or an array of IInstrumentHook objects
124
+ */
125
+ protected _addHook(hooks: IUnloadHook | IUnloadHook[] | Iterator<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>): void;
126
+ }
127
+
128
+ const DistributedTracingModes: EnumValue<typeof eDistributedTracingModes>;
129
+
130
+ type DistributedTracingModes = number | eDistributedTracingModes;
131
+
132
+ const enum eDistributedTracingModes {
133
+ /**
134
+ * (Default) Send Application Insights correlation headers
135
+ */
136
+ AI = 0,
137
+ /**
138
+ * Send both W3C Trace Context headers and back-compatibility Application Insights headers
139
+ */
140
+ AI_AND_W3C = 1,
141
+ /**
142
+ * Send W3C Trace Context headers
143
+ */
144
+ W3C = 2
145
+ }
146
+
147
+ const enum _eInternalMessageId {
148
+ BrowserDoesNotSupportLocalStorage = 0,
149
+ BrowserCannotReadLocalStorage = 1,
150
+ BrowserCannotReadSessionStorage = 2,
151
+ BrowserCannotWriteLocalStorage = 3,
152
+ BrowserCannotWriteSessionStorage = 4,
153
+ BrowserFailedRemovalFromLocalStorage = 5,
154
+ BrowserFailedRemovalFromSessionStorage = 6,
155
+ CannotSendEmptyTelemetry = 7,
156
+ ClientPerformanceMathError = 8,
157
+ ErrorParsingAISessionCookie = 9,
158
+ ErrorPVCalc = 10,
159
+ ExceptionWhileLoggingError = 11,
160
+ FailedAddingTelemetryToBuffer = 12,
161
+ FailedMonitorAjaxAbort = 13,
162
+ FailedMonitorAjaxDur = 14,
163
+ FailedMonitorAjaxOpen = 15,
164
+ FailedMonitorAjaxRSC = 16,
165
+ FailedMonitorAjaxSend = 17,
166
+ FailedMonitorAjaxGetCorrelationHeader = 18,
167
+ FailedToAddHandlerForOnBeforeUnload = 19,
168
+ FailedToSendQueuedTelemetry = 20,
169
+ FailedToReportDataLoss = 21,
170
+ FlushFailed = 22,
171
+ MessageLimitPerPVExceeded = 23,
172
+ MissingRequiredFieldSpecification = 24,
173
+ NavigationTimingNotSupported = 25,
174
+ OnError = 26,
175
+ SessionRenewalDateIsZero = 27,
176
+ SenderNotInitialized = 28,
177
+ StartTrackEventFailed = 29,
178
+ StopTrackEventFailed = 30,
179
+ StartTrackFailed = 31,
180
+ StopTrackFailed = 32,
181
+ TelemetrySampledAndNotSent = 33,
182
+ TrackEventFailed = 34,
183
+ TrackExceptionFailed = 35,
184
+ TrackMetricFailed = 36,
185
+ TrackPVFailed = 37,
186
+ TrackPVFailedCalc = 38,
187
+ TrackTraceFailed = 39,
188
+ TransmissionFailed = 40,
189
+ FailedToSetStorageBuffer = 41,
190
+ FailedToRestoreStorageBuffer = 42,
191
+ InvalidBackendResponse = 43,
192
+ FailedToFixDepricatedValues = 44,
193
+ InvalidDurationValue = 45,
194
+ TelemetryEnvelopeInvalid = 46,
195
+ CreateEnvelopeError = 47,
196
+ MaxUnloadHookExceeded = 48,
197
+ CannotSerializeObject = 48,
198
+ CannotSerializeObjectNonSerializable = 49,
199
+ CircularReferenceDetected = 50,
200
+ ClearAuthContextFailed = 51,
201
+ ExceptionTruncated = 52,
202
+ IllegalCharsInName = 53,
203
+ ItemNotInArray = 54,
204
+ MaxAjaxPerPVExceeded = 55,
205
+ MessageTruncated = 56,
206
+ NameTooLong = 57,
207
+ SampleRateOutOfRange = 58,
208
+ SetAuthContextFailed = 59,
209
+ SetAuthContextFailedAccountName = 60,
210
+ StringValueTooLong = 61,
211
+ StartCalledMoreThanOnce = 62,
212
+ StopCalledWithoutStart = 63,
213
+ TelemetryInitializerFailed = 64,
214
+ TrackArgumentsNotSpecified = 65,
215
+ UrlTooLong = 66,
216
+ SessionStorageBufferFull = 67,
217
+ CannotAccessCookie = 68,
218
+ IdTooLong = 69,
219
+ InvalidEvent = 70,
220
+ FailedMonitorAjaxSetRequestHeader = 71,
221
+ SendBrowserInfoOnUserInit = 72,
222
+ PluginException = 73,
223
+ NotificationException = 74,
224
+ SnippetScriptLoadFailure = 99,
225
+ InvalidInstrumentationKey = 100,
226
+ CannotParseAiBlobValue = 101,
227
+ InvalidContentBlob = 102,
228
+ TrackPageActionEventFailed = 103,
229
+ FailedAddingCustomDefinedRequestContext = 104,
230
+ InMemoryStorageBufferFull = 105,
231
+ InstrumentationKeyDeprecation = 106,
232
+ ConfigWatcherException = 107,
233
+ DynamicConfigException = 108,
234
+ DefaultThrottleMsgKey = 109,
235
+ CdnDeprecation = 110,
236
+ SdkLdrUpdate = 111
237
+ }
238
+
239
+ const enum eLoggingSeverity {
240
+ /**
241
+ * No Logging will be enabled
242
+ */
243
+ DISABLED = 0,
244
+ /**
245
+ * Error will be sent as internal telemetry
246
+ */
247
+ CRITICAL = 1,
248
+ /**
249
+ * Error will NOT be sent as internal telemetry, and will only be shown in browser console
250
+ */
251
+ WARNING = 2,
252
+ /**
253
+ * The Error will NOT be sent as an internal telemetry, and will only be shown in the browser
254
+ * console if the logging level allows it.
255
+ */
256
+ DEBUG = 3
257
+ }
258
+
259
+ /**
260
+ * A type that identifies an enum class generated from a constant enum.
261
+ * @group Enum
262
+ * @typeParam E - The constant enum type
263
+ *
264
+ * Returned from {@link createEnum}
265
+ */
266
+ type EnumCls<E = any> = {
267
+ readonly [key in keyof E extends string | number | symbol ? keyof E : never]: key extends string ? E[key] : key;
268
+ } & {
269
+ readonly [key in keyof E]: E[key];
270
+ };
271
+
272
+ type EnumValue<E = any> = EnumCls<E>;
273
+
274
+ const enum FeatureOptInMode {
275
+ /**
276
+ * not set, completely depends on cdn cfg
277
+ */
278
+ none = 1,
279
+ /**
280
+ * try to not apply config from cdn
281
+ */
282
+ disable = 2,
283
+ /**
284
+ * try to apply config from cdn
285
+ */
286
+ enable = 3
287
+ }
288
+
289
+ /**
290
+ * This defines the handler function that is called via the finally when the promise is resolved or rejected
291
+ */
292
+ type FinallyPromiseHandler = (() => void) | undefined | null;
293
+
294
+ interface IAppInsightsCore<CfgType extends IConfiguration = IConfiguration> extends IPerfManagerProvider {
295
+ readonly config: CfgType;
296
+ /**
297
+ * The current logger instance for this instance.
298
+ */
299
+ readonly logger: IDiagnosticLogger;
300
+ /**
301
+ * An array of the installed plugins that provide a version
302
+ */
303
+ readonly pluginVersionStringArr: string[];
304
+ /**
305
+ * The formatted string of the installed plugins that contain a version number
306
+ */
307
+ readonly pluginVersionString: string;
308
+ /**
309
+ * Returns a value that indicates whether the instance has already been previously initialized.
310
+ */
311
+ isInitialized?: () => boolean;
312
+ initialize(config: CfgType, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void;
313
+ getChannels(): IChannelControls[];
314
+ track(telemetryItem: ITelemetryItem): void;
315
+ /**
316
+ * Get the current notification manager
317
+ */
318
+ getNotifyMgr(): INotificationManager;
319
+ /**
320
+ * Get the current cookie manager for this instance
321
+ */
322
+ getCookieMgr(): ICookieMgr;
323
+ /**
324
+ * Set the current cookie manager for this instance
325
+ * @param cookieMgr - The manager, if set to null/undefined will cause the default to be created
326
+ */
327
+ setCookieMgr(cookieMgr: ICookieMgr): void;
328
+ /**
329
+ * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.
330
+ * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be
331
+ * called.
332
+ * @param listener - An INotificationListener object.
333
+ */
334
+ addNotificationListener?(listener: INotificationListener): void;
335
+ /**
336
+ * Removes all instances of the listener.
337
+ * @param listener - INotificationListener to remove.
338
+ */
339
+ removeNotificationListener?(listener: INotificationListener): void;
340
+ /**
341
+ * Add a telemetry processor to decorate or drop telemetry events.
342
+ * @param telemetryInitializer - The Telemetry Initializer function
343
+ * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed
344
+ */
345
+ addTelemetryInitializer(telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler;
346
+ pollInternalLogs?(eventName?: string): ITimerHandler;
347
+ stopPollingInternalLogs?(): void;
348
+ /**
349
+ * Return a new instance of the IProcessTelemetryContext for processing events
350
+ */
351
+ getProcessTelContext(): IProcessTelemetryContext;
352
+ /**
353
+ * Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered
354
+ * to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous
355
+ * unload call return `true` stating that all plugins reported that they also unloaded, the recommended
356
+ * approach is to create a new instance and initialize that instance.
357
+ * This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable
358
+ * to successfully remove any global references or they may just be completing the unload process asynchronously.
359
+ * 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)
360
+ * will be returned which will resolve once the unload is complete. The actual implementation of the `IPromise`
361
+ * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)
362
+ * @param isAsync - Can the unload be performed asynchronously (default)
363
+ * @param unloadComplete - An optional callback that will be called once the unload has completed
364
+ * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the
365
+ * unload. Defaults to 5 seconds.
366
+ * @return Nothing or if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
367
+ * which will be resolved once the unload is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
368
+ * will only be returned when no callback is provided and isAsync is true
369
+ */
370
+ unload(isAsync?: boolean, unloadComplete?: (unloadState: ITelemetryUnloadState) => void, cbTimeout?: number): void | IPromise<ITelemetryUnloadState>;
371
+ /**
372
+ * Find and return the (first) plugin with the specified identifier if present
373
+ * @param pluginIdentifier
374
+ */
375
+ getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T>;
376
+ /**
377
+ * Add a new plugin to the installation
378
+ * @param plugin - The new plugin to add
379
+ * @param replaceExisting - should any existing plugin be replaced, default is false
380
+ * @param doAsync - Should the add be performed asynchronously
381
+ * @param addCb - [Optional] callback to call after the plugin has been added
382
+ */
383
+ addPlugin<T extends IPlugin = ITelemetryPlugin>(plugin: T, replaceExisting?: boolean, doAsync?: boolean, addCb?: (added?: boolean) => void): void;
384
+ /**
385
+ * Update the configuration used and broadcast the changes to all loaded plugins, this does NOT support updating, adding or removing
386
+ * any the plugins (extensions or channels). It will notify each plugin (if supported) that the configuration has changed but it will
387
+ * not remove or add any new plugins, you need to call addPlugin or getPlugin(identifier).remove();
388
+ * @param newConfig - The new configuration is apply
389
+ * @param mergeExisting - Should the new configuration merge with the existing or just replace it. Default is to merge.
390
+ */
391
+ updateCfg(newConfig: CfgType, mergeExisting?: boolean): void;
392
+ /**
393
+ * Returns the unique event namespace that should be used when registering events
394
+ */
395
+ evtNamespace(): string;
396
+ /**
397
+ * Add a handler that will be called when the SDK is being unloaded
398
+ * @param handler - the handler
399
+ */
400
+ addUnloadCb(handler: UnloadHandler): void;
401
+ /**
402
+ * Add this hook so that it is automatically removed during unloading
403
+ * @param hooks - The single hook or an array of IInstrumentHook objects
404
+ */
405
+ addUnloadHook(hooks: IUnloadHook | IUnloadHook[] | Iterator<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>): void;
406
+ /**
407
+ * Flush and send any batched / cached data immediately
408
+ * @param async - send data asynchronously when true (defaults to true)
409
+ * @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.
410
+ * If the caller doesn't return true the caller should assume that it may never be called.
411
+ * @param sendReason - specify the reason that you are calling "flush" defaults to ManualFlush (1) if not specified
412
+ * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the unload. Defaults to 5 seconds.
413
+ * @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
414
+ */
415
+ flush(isAsync?: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason, cbTimeout?: number): boolean | void;
416
+ /**
417
+ * Gets the current distributed trace context for this instance if available
418
+ * @param createNew - Optional flag to create a new instance if one doesn't currently exist, defaults to true
419
+ */
420
+ getTraceCtx(createNew?: boolean): IDistributedTraceContext | null;
421
+ /**
422
+ * Sets the current distributed trace context for this instance if available
423
+ */
424
+ setTraceCtx(newTraceCtx: IDistributedTraceContext | null | undefined): void;
425
+ /**
426
+ * Watches and tracks changes for accesses to the current config, and if the accessed config changes the
427
+ * handler will be recalled.
428
+ * @param handler
429
+ * @returns A watcher handler instance that can be used to remove itself when being unloaded
430
+ */
431
+ onCfgChange(handler: WatcherFunction<CfgType>): IUnloadHook;
432
+ /**
433
+ * Function used to identify the get w parameter used to identify status bit to some channels
434
+ */
435
+ getWParam: () => number;
436
+ }
437
+
438
+ interface IBackendResponse {
439
+ /**
440
+ * Number of items received by the backend
441
+ */
442
+ readonly itemsReceived: number;
443
+ /**
444
+ * Number of items succesfuly accepted by the backend
445
+ */
446
+ readonly itemsAccepted: number;
447
+ /**
448
+ * List of errors for items which were not accepted
449
+ */
450
+ readonly errors: IResponseError[];
451
+ /**
452
+ * App id returned by the backend - not necessary returned, but we don't need it with each response.
453
+ */
454
+ readonly appId?: string;
455
+ }
456
+
457
+ interface IBaseProcessingContext {
458
+ /**
459
+ * The current core instance for the request
460
+ */
461
+ core: () => IAppInsightsCore;
462
+ /**
463
+ * THe current diagnostic logger for the request
464
+ */
465
+ diagLog: () => IDiagnosticLogger;
466
+ /**
467
+ * Gets the current core config instance
468
+ */
469
+ getCfg: () => IConfiguration;
470
+ /**
471
+ * Gets the named extension config
472
+ */
473
+ getExtCfg: <T>(identifier: string, defaultValue?: IConfigDefaults<T>) => T;
474
+ /**
475
+ * Gets the named config from either the named identifier extension or core config if neither exist then the
476
+ * default value is returned
477
+ * @param identifier - The named extension identifier
478
+ * @param field - The config field name
479
+ * @param defaultValue - The default value to return if no defined config exists
480
+ */
481
+ getConfig: (identifier: string, field: string, defaultValue?: number | string | boolean | string[] | RegExp[] | Function) => number | string | boolean | string[] | RegExp[] | Function;
482
+ /**
483
+ * Helper to allow plugins to check and possibly shortcut executing code only
484
+ * required if there is a nextPlugin
485
+ */
486
+ hasNext: () => boolean;
487
+ /**
488
+ * Returns the next configured plugin proxy
489
+ */
490
+ getNext: () => ITelemetryPluginChain;
491
+ /**
492
+ * Helper to set the next plugin proxy
493
+ */
494
+ setNext: (nextCtx: ITelemetryPluginChain) => void;
495
+ /**
496
+ * Synchronously iterate over the context chain running the callback for each plugin, once
497
+ * every plugin has been executed via the callback, any associated onComplete will be called.
498
+ * @param callback - The function call for each plugin in the context chain
499
+ */
500
+ iterate: <T extends ITelemetryPlugin = ITelemetryPlugin>(callback: (plugin: T) => void) => void;
501
+ /**
502
+ * Set the function to call when the current chain has executed all processNext or unloadNext items.
503
+ * @param onComplete - The onComplete to call
504
+ * @param that - The "this" value to use for the onComplete call, if not provided or undefined defaults to the current context
505
+ * @param args - Any additional arguments to pass to the onComplete function
506
+ */
507
+ onComplete: (onComplete: () => void, that?: any, ...args: any[]) => void;
508
+ /**
509
+ * Create a new context using the core and config from the current instance, returns a new instance of the same type
510
+ * @param plugins - The execution order to process the plugins, if null or not supplied
511
+ * then the current execution order will be copied.
512
+ * @param startAt - The plugin to start processing from, if missing from the execution
513
+ * order then the next plugin will be NOT set.
514
+ */
515
+ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IBaseProcessingContext;
516
+ }
517
+
518
+ /**
519
+ * Provides data transmission capabilities
520
+ */
521
+ interface IChannelControls extends ITelemetryPlugin {
522
+ /**
523
+ * Pause sending data
524
+ */
525
+ pause?(): void;
526
+ /**
527
+ * Resume sending data
528
+ */
529
+ resume?(): void;
530
+ /**
531
+ * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and
532
+ * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further
533
+ * processTelemetry calls are ignored and it just calls the processNext() with the provided context.
534
+ * @param unloadCtx - This is the context that should be used during unloading.
535
+ * @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.
536
+ * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing.
537
+ */
538
+ teardown?: (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => void | boolean;
539
+ /**
540
+ * Flush to send data immediately; channel should default to sending data asynchronously. If executing asynchronously and
541
+ * you DO NOT pass a callback function then a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
542
+ * will be returned which will resolve once the flush is complete. The actual implementation of the `IPromise`
543
+ * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)
544
+ * @param async - send data asynchronously when true
545
+ * @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.
546
+ * If the caller doesn't return true the caller should assume that it may never be called.
547
+ * @param sendReason - specify the reason that you are calling "flush" defaults to ManualFlush (1) if not specified
548
+ * @returns - If a callback is provided `true` to indicate that callback will be called after the flush is complete otherwise the caller
549
+ * should assume that any provided callback will never be called, Nothing or if occurring asynchronously a
550
+ * [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) which will be resolved once the unload is complete,
551
+ * the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) will only be returned when no callback is provided
552
+ * and async is true.
553
+ */
554
+ flush?(async: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason): boolean | void | IPromise<boolean>;
555
+ }
556
+
557
+ /**
558
+ * Configuration settings for how telemetry is sent
559
+ * @export
560
+ * @interface IConfig
561
+ */
562
+ interface IConfig {
563
+ /**
564
+ * The JSON format (normal vs line delimited). True means line delimited JSON.
565
+ */
566
+ emitLineDelimitedJson?: boolean;
567
+ /**
568
+ * An optional account id, if your app groups users into accounts. No spaces, commas, semicolons, equals, or vertical bars.
569
+ */
570
+ accountId?: string;
571
+ /**
572
+ * A session is logged if the user is inactive for this amount of time in milliseconds. Default 30 mins.
573
+ * @default 30*60*1000
574
+ */
575
+ sessionRenewalMs?: number;
576
+ /**
577
+ * A session is logged if it has continued for this amount of time in milliseconds. Default 24h.
578
+ * @default 24*60*60*1000
579
+ */
580
+ sessionExpirationMs?: number;
581
+ /**
582
+ * Max size of telemetry batch. If batch exceeds limit, it is sent and a new batch is started
583
+ * @default 100000
584
+ */
585
+ maxBatchSizeInBytes?: number;
586
+ /**
587
+ * How long to batch telemetry for before sending (milliseconds)
588
+ * @default 15 seconds
589
+ */
590
+ maxBatchInterval?: number;
591
+ /**
592
+ * If true, debugging data is thrown as an exception by the logger. Default false
593
+ * @defaultValue false
594
+ */
595
+ enableDebug?: boolean;
596
+ /**
597
+ * If true, exceptions are not autocollected. Default is false
598
+ * @defaultValue false
599
+ */
600
+ disableExceptionTracking?: boolean;
601
+ /**
602
+ * If true, telemetry is not collected or sent. Default is false
603
+ * @defaultValue false
604
+ */
605
+ disableTelemetry?: boolean;
606
+ /**
607
+ * Percentage of events that will be sent. Default is 100, meaning all events are sent.
608
+ * @defaultValue 100
609
+ */
610
+ samplingPercentage?: number;
611
+ /**
612
+ * 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.
613
+ */
614
+ autoTrackPageVisitTime?: boolean;
615
+ /**
616
+ * Automatically track route changes in Single Page Applications (SPA). If true, each route change will send a new Pageview to Application Insights.
617
+ */
618
+ enableAutoRouteTracking?: boolean;
619
+ /**
620
+ * If true, Ajax calls are not autocollected. Default is false
621
+ * @defaultValue false
622
+ */
623
+ disableAjaxTracking?: boolean;
624
+ /**
625
+ * If true, Fetch requests are not autocollected. Default is false (Since 2.8.0, previously true).
626
+ * @defaultValue false
627
+ */
628
+ disableFetchTracking?: boolean;
629
+ /**
630
+ * 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.
631
+ * @defaultValue undefined.
632
+ */
633
+ excludeRequestFromAutoTrackingPatterns?: string[] | RegExp[];
634
+ /**
635
+ * Provide a way to enrich dependencies logs with context at the beginning of api call.
636
+ * Default is undefined.
637
+ */
638
+ addRequestContext?: (requestContext?: IRequestContext) => ICustomProperties;
639
+ /**
640
+ * 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
641
+ * @defaultValue false
642
+ */
643
+ overridePageViewDuration?: boolean;
644
+ /**
645
+ * 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.
646
+ */
647
+ maxAjaxCallsPerView?: number;
648
+ /**
649
+ * @ignore
650
+ * If false, internal telemetry sender buffers will be checked at startup for items not yet sent. Default is true
651
+ * @defaultValue true
652
+ */
653
+ disableDataLossAnalysis?: boolean;
654
+ /**
655
+ * 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.
656
+ * @defaultValue false
657
+ */
658
+ disableCorrelationHeaders?: boolean;
659
+ /**
660
+ * 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.
661
+ * AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services
662
+ * @defaultValue AI_AND_W3C
663
+ */
664
+ distributedTracingMode?: DistributedTracingModes;
665
+ /**
666
+ * Disable correlation headers for specific domain
667
+ */
668
+ correlationHeaderExcludedDomains?: string[];
669
+ /**
670
+ * Default false. If true, flush method will not be called when onBeforeUnload, onUnload, onPageHide or onVisibilityChange (hidden state) event(s) trigger.
671
+ */
672
+ disableFlushOnBeforeUnload?: boolean;
673
+ /**
674
+ * Default value of {@link #disableFlushOnBeforeUnload}. If true, flush method will not be called when onPageHide or onVisibilityChange (hidden state) event(s) trigger.
675
+ */
676
+ disableFlushOnUnload?: boolean;
677
+ /**
678
+ * If true, the buffer with all unsent telemetry is stored in session storage. The buffer is restored on page load. Default is true.
679
+ * @defaultValue true
680
+ */
681
+ enableSessionStorageBuffer?: boolean;
682
+ /**
683
+ * If specified, overrides the storage & retrieval mechanism that is used to manage unsent telemetry.
684
+ */
685
+ bufferOverride?: IStorageBuffer;
686
+ /**
687
+ * @deprecated Use either disableCookiesUsage or specify a cookieCfg with the enabled value set.
688
+ * If true, the SDK will not store or read any data from cookies. Default is false. As this field is being deprecated, when both
689
+ * isCookieUseDisabled and disableCookiesUsage are used disableCookiesUsage will take precedent.
690
+ * @defaultValue false
691
+ */
692
+ isCookieUseDisabled?: boolean;
693
+ /**
694
+ * If true, the SDK will not store or read any data from cookies. Default is false.
695
+ * If you have also specified a cookieCfg then enabled property (if specified) will take precedent over this value.
696
+ * @defaultValue false
697
+ */
698
+ disableCookiesUsage?: boolean;
699
+ /**
700
+ * Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains.
701
+ * @defaultValue ""
702
+ */
703
+ cookieDomain?: string;
704
+ /**
705
+ * Custom cookie path. This is helpful if you want to share Application Insights cookies behind an application gateway.
706
+ * @defaultValue ""
707
+ */
708
+ cookiePath?: string;
709
+ /**
710
+ * 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)
711
+ * @description
712
+ * @defaultValue false
713
+ */
714
+ isRetryDisabled?: boolean;
715
+ /**
716
+ * @deprecated Used when initizialing from snippet only.
717
+ * The url from where the JS SDK will be downloaded.
718
+ */
719
+ url?: string;
720
+ /**
721
+ * If true, the SDK will not store or read any data from local and session storage. Default is false.
722
+ * @defaultValue false
723
+ */
724
+ isStorageUseDisabled?: boolean;
725
+ /**
726
+ * If false, the SDK will send all telemetry using the [Beacon API](https://www.w3.org/TR/beacon)
727
+ * @defaultValue true
728
+ */
729
+ isBeaconApiDisabled?: boolean;
730
+ /**
731
+ * Don't use XMLHttpRequest or XDomainRequest (for IE < 9) by default instead attempt to use fetch() or sendBeacon.
732
+ * If no other transport is available it will still use XMLHttpRequest
733
+ */
734
+ disableXhr?: boolean;
735
+ /**
736
+ * If fetch keepalive is supported do not use it for sending events during unload, it may still fallback to fetch() without keepalive
737
+ */
738
+ onunloadDisableFetch?: boolean;
739
+ /**
740
+ * 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.
741
+ * @defaultValue null
742
+ */
743
+ sdkExtension?: string;
744
+ /**
745
+ * 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.
746
+ * @defaultValue false
747
+ */
748
+ isBrowserLinkTrackingEnabled?: boolean;
749
+ /**
750
+ * 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
751
+ * @defaultValue null
752
+ */
753
+ appId?: string;
754
+ /**
755
+ * 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
756
+ * @defaultValue false
757
+ */
758
+ enableCorsCorrelation?: boolean;
759
+ /**
760
+ * An optional value that will be used as name postfix for localStorage and session cookie name.
761
+ * @defaultValue null
762
+ */
763
+ namePrefix?: string;
764
+ /**
765
+ * 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.
766
+ * @defaultValue null
767
+ */
768
+ sessionCookiePostfix?: string;
769
+ /**
770
+ * An optional value that will be used as name postfix for user cookie name. If undefined, no postfix is added on user cookie name.
771
+ * @defaultValue null
772
+ */
773
+ userCookiePostfix?: string;
774
+ /**
775
+ * An optional value that will track Request Header through trackDependency function.
776
+ * @defaultValue false
777
+ */
778
+ enableRequestHeaderTracking?: boolean;
779
+ /**
780
+ * An optional value that will track Response Header through trackDependency function.
781
+ * @defaultValue false
782
+ */
783
+ enableResponseHeaderTracking?: boolean;
784
+ /**
785
+ * An optional value that will track Response Error data through trackDependency function.
786
+ * @defaultValue false
787
+ */
788
+ enableAjaxErrorStatusText?: boolean;
789
+ /**
790
+ * Flag to enable looking up and including additional browser window.performance timings
791
+ * in the reported ajax (XHR and fetch) reported metrics.
792
+ * Defaults to false.
793
+ */
794
+ enableAjaxPerfTracking?: boolean;
795
+ /**
796
+ * The maximum number of times to look for the window.performance timings (if available), this
797
+ * is required as not all browsers populate the window.performance before reporting the
798
+ * end of the XHR request and for fetch requests this is added after its complete
799
+ * Defaults to 3
800
+ */
801
+ maxAjaxPerfLookupAttempts?: number;
802
+ /**
803
+ * The amount of time to wait before re-attempting to find the windows.performance timings
804
+ * for an ajax request, time is in milliseconds and is passed directly to setTimeout()
805
+ * Defaults to 25.
806
+ */
807
+ ajaxPerfLookupDelay?: number;
808
+ /**
809
+ * Default false. when tab is closed, the SDK will send all remaining telemetry using the [Beacon API](https://www.w3.org/TR/beacon)
810
+ * @defaultValue false
811
+ */
812
+ onunloadDisableBeacon?: boolean;
813
+ /**
814
+ * @ignore
815
+ * Internal only
816
+ */
817
+ autoExceptionInstrumented?: boolean;
818
+ /**
819
+ *
820
+ */
821
+ correlationHeaderDomains?: string[];
822
+ /**
823
+ * @ignore
824
+ * Internal only
825
+ */
826
+ autoUnhandledPromiseInstrumented?: boolean;
827
+ /**
828
+ * Default false. Define whether to track unhandled promise rejections and report as JS errors.
829
+ * When disableExceptionTracking is enabled (dont track exceptions) this value will be false.
830
+ * @defaultValue false
831
+ */
832
+ enableUnhandledPromiseRejectionTracking?: boolean;
833
+ /**
834
+ * Disable correlation headers using regular expressions
835
+ */
836
+ correlationHeaderExcludePatterns?: RegExp[];
837
+ /**
838
+ * The ability for the user to provide extra headers
839
+ */
840
+ customHeaders?: [{
841
+ header: string;
842
+ value: string;
843
+ }];
844
+ /**
845
+ * Provide user an option to convert undefined field to user defined value.
846
+ */
847
+ convertUndefined?: any;
848
+ /**
849
+ * [Optional] The number of events that can be kept in memory before the SDK starts to drop events. By default, this is 10,000.
850
+ */
851
+ eventsLimitInMem?: number;
852
+ /**
853
+ * [Optional] Disable iKey deprecation error message.
854
+ * @defaultValue true
855
+ */
856
+ disableIkeyDeprecationMessage?: boolean;
857
+ /**
858
+ * [Optional] Flag to indicate whether the internal looking endpoints should be automatically
859
+ * added to the `excludeRequestFromAutoTrackingPatterns` collection. (defaults to true).
860
+ * This flag exists as the provided regex is generic and may unexpectedly match a domain that
861
+ * should not be excluded.
862
+ */
863
+ addIntEndpoints?: boolean;
864
+ /**
865
+ * [Optional] Sets throttle mgr configuration by key
866
+ */
867
+ throttleMgrCfg?: {
868
+ [key: number]: IThrottleMgrConfig;
869
+ };
870
+ }
871
+
872
+ /**
873
+ * The type to identify whether the default value should be applied in preference to the provided value.
874
+ */
875
+ type IConfigCheckFn<V> = (value: V) => boolean;
876
+
877
+ /**
878
+ * The default values with a check function
879
+ */
880
+ interface IConfigDefaultCheck<T, V, C = IConfiguration> {
881
+ /**
882
+ * Callback function to check if the user-supplied value is valid, if not the default will be applied
883
+ */
884
+ isVal?: IConfigCheckFn<V>;
885
+ /**
886
+ * Optional function to allow converting and setting of the default value
887
+ */
888
+ set?: IConfigSetFn<T, V>;
889
+ /**
890
+ * The default value to apply if the user-supplied value is not valid
891
+ */
892
+ v?: V | IConfigDefaults<V, T>;
893
+ /**
894
+ * The default fallback key if the main key is not present, this is the key value from the config
895
+ */
896
+ fb?: keyof T | keyof C | Array<keyof T | keyof C>;
897
+ /**
898
+ * Use this check to determine the default fallback, default only checked whether the property isDefined,
899
+ * therefore `null`; `""` are considered to be valid values.
900
+ */
901
+ dfVal?: (value: any) => boolean;
902
+ /**
903
+ * Specify that any provided value should have the default value(s) merged into the value rather than
904
+ * just using either the default of user provided values. Mergeed objects will automatically be marked
905
+ * as referenced.
906
+ */
907
+ mrg?: boolean;
908
+ /**
909
+ * Set this field of the target as referenced, which will cause any object or array instance
910
+ * to be updated in-place rather than being entirely replaced. All other values will continue to be replaced.
911
+ * This is required for nested default objects to avoid multiple repetitive updates to listeners
912
+ * @returns The referenced properties current value
913
+ */
914
+ ref?: boolean;
915
+ /**
916
+ * Set this field of the target as read-only, which will block this single named property from
917
+ * ever being changed for the target instance.
918
+ * This does NOT freeze or seal the instance, it just stops the direct re-assignment of the named property,
919
+ * if the value is a non-primitive (ie. an object or array) it's properties will still be mutable.
920
+ * @returns The referenced properties current value
921
+ */
922
+ rdOnly?: boolean;
923
+ /**
924
+ * Block the value associated with this property from having it's properties / values converted into
925
+ * dynamic properties, this is generally used to block objects or arrays provided by external libraries
926
+ * which may be a plain object with readonly (non-configurable) or const properties.
927
+ */
928
+ blkVal?: boolean;
929
+ }
930
+
931
+ /**
932
+ * The Type definition to define default values to be applied to the config
933
+ * The value may be either the direct value or a ConfigDefaultCheck definition
934
+ */
935
+ type IConfigDefaults<T, C = IConfiguration> = {
936
+ [key in keyof T]: T[key] | IConfigDefaultCheck<T, T[key], C>;
937
+ };
938
+
939
+ /**
940
+ * The type which identifies the function use to validate the user supplied value
941
+ */
942
+ type IConfigSetFn<T, V> = (value: any, defValue: V, theConfig: T) => V;
943
+
944
+ /**
945
+ * Configuration provided to SDK core
946
+ */
947
+ interface IConfiguration {
948
+ /**
949
+ * Instrumentation key of resource. Either this or connectionString must be specified.
950
+ */
951
+ instrumentationKey?: string;
952
+ /**
953
+ * Connection string of resource. Either this or instrumentationKey must be specified.
954
+ */
955
+ connectionString?: string;
956
+ /**
957
+ * Set the timer interval (in ms) for internal logging queue, this is the
958
+ * amount of time to wait after logger.queue messages are detected to be sent.
959
+ * Note: since 3.0.1 and 2.8.13 the diagnostic logger timer is a normal timeout timer
960
+ * and not an interval timer. So this now represents the timer "delay" and not
961
+ * the frequency at which the events are sent.
962
+ */
963
+ diagnosticLogInterval?: number;
964
+ /**
965
+ * Maximum number of iKey transmitted logging telemetry per page view
966
+ */
967
+ maxMessageLimit?: number;
968
+ /**
969
+ * Console logging level. All logs with a severity level higher
970
+ * than the configured level will be printed to console. Otherwise
971
+ * they are suppressed. ie Level 2 will print both CRITICAL and
972
+ * WARNING logs to console, level 1 prints only CRITICAL.
973
+ *
974
+ * Note: Logs sent as telemetry to instrumentation key will also
975
+ * be logged to console if their severity meets the configured loggingConsoleLevel
976
+ *
977
+ * 0: ALL console logging off
978
+ * 1: logs to console: severity >= CRITICAL
979
+ * 2: logs to console: severity >= WARNING
980
+ */
981
+ loggingLevelConsole?: number;
982
+ /**
983
+ * Telemtry logging level to instrumentation key. All logs with a severity
984
+ * level higher than the configured level will sent as telemetry data to
985
+ * the configured instrumentation key.
986
+ *
987
+ * 0: ALL iKey logging off
988
+ * 1: logs to iKey: severity >= CRITICAL
989
+ * 2: logs to iKey: severity >= WARNING
990
+ */
991
+ loggingLevelTelemetry?: number;
992
+ /**
993
+ * If enabled, uncaught exceptions will be thrown to help with debugging
994
+ */
995
+ enableDebug?: boolean;
996
+ /**
997
+ * Endpoint where telemetry data is sent
998
+ */
999
+ endpointUrl?: string;
1000
+ /**
1001
+ * Extension configs loaded in SDK
1002
+ */
1003
+ extensionConfig?: {
1004
+ [key: string]: any;
1005
+ };
1006
+ /**
1007
+ * Additional plugins that should be loaded by core at runtime
1008
+ */
1009
+ readonly extensions?: ITelemetryPlugin[];
1010
+ /**
1011
+ * Channel queues that is setup by caller in desired order.
1012
+ * If channels are provided here, core will ignore any channels that are already setup, example if there is a SKU with an initialized channel
1013
+ */
1014
+ readonly channels?: IChannelControls[][];
1015
+ /**
1016
+ * @type {boolean}
1017
+ * Flag that disables the Instrumentation Key validation.
1018
+ */
1019
+ disableInstrumentationKeyValidation?: boolean;
1020
+ /**
1021
+ * [Optional] When enabled this will create local perfEvents based on sections of the code that have been instrumented
1022
+ * to emit perfEvents (via the doPerf()) when this is enabled. This can be used to identify performance issues within
1023
+ * the SDK, the way you are using it or optionally your own instrumented code.
1024
+ * The provided IPerfManager implementation does NOT send any additional telemetry events to the server it will only fire
1025
+ * the new perfEvent() on the INotificationManager which you can listen to.
1026
+ * This also does not use the window.performance API, so it will work in environments where this API is not supported.
1027
+ */
1028
+ enablePerfMgr?: boolean;
1029
+ /**
1030
+ * [Optional] Callback function that will be called to create a the IPerfManager instance when required and ```enablePerfMgr```
1031
+ * is enabled, this enables you to override the default creation of a PerfManager() without needing to ```setPerfMgr()```
1032
+ * after initialization.
1033
+ */
1034
+ createPerfMgr?: (core: IAppInsightsCore, notificationManager: INotificationManager) => IPerfManager;
1035
+ /**
1036
+ * [Optional] Fire every single performance event not just the top level root performance event. Defaults to false.
1037
+ */
1038
+ perfEvtsSendAll?: boolean;
1039
+ /**
1040
+ * [Optional] Identifies the default length used to generate random session and user id's if non currently exists for the user / session.
1041
+ * Defaults to 22, previous default value was 5, if you need to keep the previous maximum length you should set this value to 5.
1042
+ */
1043
+ idLength?: number;
1044
+ /**
1045
+ * @description Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. It
1046
+ * can be set here or as part of the cookieCfg.domain, the cookieCfg takes precedence if both are specified.
1047
+ * @type {string}
1048
+ * @defaultValue ""
1049
+ */
1050
+ cookieDomain?: string;
1051
+ /**
1052
+ * @description Custom cookie path. This is helpful if you want to share Application Insights cookies behind an application
1053
+ * gateway. It can be set here or as part of the cookieCfg.domain, the cookieCfg takes precedence if both are specified.
1054
+ * @type {string}
1055
+ * @defaultValue ""
1056
+ */
1057
+ cookiePath?: string;
1058
+ /**
1059
+ * [Optional] A boolean that indicated whether to disable the use of cookies by the SDK. If true, the SDK will not store or
1060
+ * read any data from cookies. Cookie usage can be re-enabled after initialization via the core.getCookieMgr().enable().
1061
+ */
1062
+ disableCookiesUsage?: boolean;
1063
+ /**
1064
+ * [Optional] A Cookie Manager configuration which includes hooks to allow interception of the get, set and delete cookie
1065
+ * operations. If this configuration is specified any specified enabled and domain properties will take precedence over the
1066
+ * cookieDomain and disableCookiesUsage values.
1067
+ */
1068
+ cookieCfg?: ICookieMgrConfig;
1069
+ /**
1070
+ * [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
1071
+ * 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.
1072
+ * Unload events include "beforeunload", "unload", "visibilitychange" (with 'hidden' state) and "pagehide"
1073
+ */
1074
+ disablePageUnloadEvents?: string[];
1075
+ /**
1076
+ * [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
1077
+ * 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.
1078
+ * Page Show events include "pageshow" and "visibilitychange" (with 'visible' state)
1079
+ */
1080
+ disablePageShowEvents?: string[];
1081
+ /**
1082
+ * [Optional] A flag for performance optimization to disable attempting to use the Chrome Debug Extension, if disabled and the extension is installed
1083
+ * this will not send any notifications.
1084
+ */
1085
+ disableDbgExt?: boolean;
1086
+ /**
1087
+ * Add "&w=0" parameter to support UA Parsing when web-workers don't have access to Document.
1088
+ * Default is false
1089
+ */
1090
+ enableWParam?: boolean;
1091
+ /**
1092
+ * Custom optional value that will be added as a prefix for storage name.
1093
+ * @defaultValue undefined
1094
+ */
1095
+ storagePrefix?: string;
1096
+ /**
1097
+ * Custom optional value to opt in features
1098
+ * @defaultValue undefined
1099
+ */
1100
+ featureOptIn?: IFeatureOptIn;
1101
+ }
1102
+
1103
+ interface ICookieMgr {
1104
+ /**
1105
+ * Enable or Disable the usage of cookies
1106
+ */
1107
+ setEnabled(value: boolean): void;
1108
+ /**
1109
+ * Can the system use cookies, if this returns false then all cookie setting and access functions will return nothing
1110
+ */
1111
+ isEnabled(): boolean;
1112
+ /**
1113
+ * Set the named cookie with the value and optional domain and optional
1114
+ * @param name - The name of the cookie
1115
+ * @param value - The value of the cookie (Must already be encoded)
1116
+ * @param maxAgeSec - [optional] The maximum number of SECONDS that this cookie should survive
1117
+ * @param domain - [optional] The domain to set for the cookie
1118
+ * @param path - [optional] Path to set for the cookie, if not supplied will default to "/"
1119
+ * @returns - True if the cookie was set otherwise false (Because cookie usage is not enabled or available)
1120
+ */
1121
+ set(name: string, value: string, maxAgeSec?: number, domain?: string, path?: string): boolean;
1122
+ /**
1123
+ * Get the value of the named cookie
1124
+ * @param name - The name of the cookie
1125
+ */
1126
+ get(name: string): string;
1127
+ /**
1128
+ * Delete/Remove the named cookie if cookie support is available and enabled.
1129
+ * Note: Not using "delete" as the name because it's a reserved word which would cause issues on older browsers
1130
+ * @param name - The name of the cookie
1131
+ * @param path - [optional] Path to set for the cookie, if not supplied will default to "/"
1132
+ * @returns - True if the cookie was marked for deletion otherwise false (Because cookie usage is not enabled or available)
1133
+ */
1134
+ del(name: string, path?: string): boolean;
1135
+ /**
1136
+ * Purge the cookie from the system if cookie support is available, this function ignores the enabled setting of the manager
1137
+ * so any cookie will be removed.
1138
+ * Note: Not using "delete" as the name because it's a reserved word which would cause issues on older browsers
1139
+ * @param name - The name of the cookie
1140
+ * @param path - [optional] Path to set for the cookie, if not supplied will default to "/"
1141
+ * @returns - True if the cookie was marked for deletion otherwise false (Because cookie usage is not available)
1142
+ */
1143
+ purge(name: string, path?: string): boolean;
1144
+ /**
1145
+ * Optional Callback hook to allow the cookie manager to update it's configuration, not generally implemented now that
1146
+ * dynamic configuration is supported
1147
+ * @param updateState
1148
+ */
1149
+ update?(updateState: ITelemetryUpdateState): void;
1150
+ /**
1151
+ * Unload and remove any state that this ICookieMgr may be holding, this is generally called when the
1152
+ * owning SDK is being unloaded.
1153
+ * @param isAsync - Can the unload be performed asynchronously (default)
1154
+ * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then
1155
+ * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
1156
+ * / Promise to allow any listeners to wait for the operation to complete.
1157
+ */
1158
+ unload?(isAsync?: boolean): void | IPromise<void>;
1159
+ }
1160
+
1161
+ /**
1162
+ * Configuration definition for instance based cookie management configuration
1163
+ */
1164
+ interface ICookieMgrConfig {
1165
+ /**
1166
+ * Defaults to true, A boolean that indicates whether the use of cookies by the SDK is enabled by the current instance.
1167
+ * If false, the instance of the SDK initialized by this configuration will not store or read any data from cookies
1168
+ */
1169
+ enabled?: boolean;
1170
+ /**
1171
+ * Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains.
1172
+ */
1173
+ domain?: string;
1174
+ /**
1175
+ * Specifies the path to use for the cookie, defaults to '/'
1176
+ */
1177
+ path?: string;
1178
+ /**
1179
+ * Specify the cookie name(s) to be ignored, this will cause any matching cookie name to never be read or written.
1180
+ * They may still be explicitly purged or deleted. You do not need to repeat the name in the `blockedCookies`
1181
+ * configuration.(Since v2.8.8)
1182
+ */
1183
+ ignoreCookies?: string[];
1184
+ /**
1185
+ * Specify the cookie name(s) to never be written, this will cause any cookie name to never be created or updated,
1186
+ * they will still be read unless also included in the ignoreCookies and may still be explicitly purged or deleted.
1187
+ * If not provided defaults to the same list provided in ignoreCookies. (Since v2.8.8)
1188
+ */
1189
+ blockedCookies?: string[];
1190
+ /**
1191
+ * Hook function to fetch the named cookie value.
1192
+ * @param name - The name of the cookie
1193
+ */
1194
+ getCookie?: (name: string) => string;
1195
+ /**
1196
+ * Hook function to set the named cookie with the specified value.
1197
+ * @param name - The name of the cookie
1198
+ * @param value - The value to set for the cookie
1199
+ */
1200
+ setCookie?: (name: string, value: string) => void;
1201
+ /**
1202
+ * Hook function to delete the named cookie with the specified value, separated from
1203
+ * setCookie to avoid the need to parse the value to determine whether the cookie is being
1204
+ * added or removed.
1205
+ * @param name - The name of the cookie
1206
+ * @param cookieValue - The value to set to expire the cookie
1207
+ */
1208
+ delCookie?: (name: string, cookieValue: string) => void;
1209
+ }
1210
+
1211
+ interface ICustomProperties {
1212
+ [key: string]: any;
1213
+ }
1214
+
1215
+ interface IDiagnosticLogger {
1216
+ /**
1217
+ * 0: OFF
1218
+ * 1: only critical (default)
1219
+ * 2: critical + info
1220
+ */
1221
+ consoleLoggingLevel: () => number;
1222
+ /**
1223
+ * The internal logging queue
1224
+ */
1225
+ queue: _InternalLogMessage[];
1226
+ /**
1227
+ * This method will throw exceptions in debug mode or attempt to log the error as a console warning.
1228
+ * @param severity - The severity of the log message
1229
+ * @param message - The log message.
1230
+ */
1231
+ throwInternal(severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct?: boolean): void;
1232
+ /**
1233
+ * This will write a debug message to the console if possible
1234
+ * @param message - {string} - The debug message
1235
+ */
1236
+ debugToConsole?(message: string): void;
1237
+ /**
1238
+ * This will write a warning to the console if possible
1239
+ * @param message - The warning message
1240
+ */
1241
+ warnToConsole(message: string): void;
1242
+ /**
1243
+ * This will write an error to the console if possible.
1244
+ * Provided by the default DiagnosticLogger instance, and internally the SDK will fall back to warnToConsole, however,
1245
+ * direct callers MUST check for its existence on the logger as you can provide your own IDiagnosticLogger instance.
1246
+ * @param message - The error message
1247
+ */
1248
+ errorToConsole?(message: string): void;
1249
+ /**
1250
+ * Resets the internal message count
1251
+ */
1252
+ resetInternalMessageCount(): void;
1253
+ /**
1254
+ * Logs a message to the internal queue.
1255
+ * @param severity - The severity of the log message
1256
+ * @param message - The message to log.
1257
+ */
1258
+ logInternalMessage?(severity: LoggingSeverity, message: _InternalLogMessage): void;
1259
+ /**
1260
+ * Optional Callback hook to allow the diagnostic logger to update it's configuration
1261
+ * @param updateState
1262
+ */
1263
+ update?(updateState: ITelemetryUpdateState): void;
1264
+ /**
1265
+ * Unload and remove any state that this IDiagnosticLogger may be holding, this is generally called when the
1266
+ * owning SDK is being unloaded.
1267
+ * @param isAsync - Can the unload be performed asynchronously (default)
1268
+ * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then
1269
+ * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
1270
+ * / Promise to allow any listeners to wait for the operation to complete.
1271
+ */
1272
+ unload?(isAsync?: boolean): void | IPromise<void>;
1273
+ }
1274
+
1275
+ interface IDistributedTraceContext {
1276
+ /**
1277
+ * Returns the current name of the page
1278
+ */
1279
+ getName(): string;
1280
+ /**
1281
+ * Sets the current name of the page
1282
+ * @param pageName
1283
+ */
1284
+ setName(pageName: string): void;
1285
+ /**
1286
+ * Returns the unique identifier for a trace. All requests / spans from the same trace share the same traceId.
1287
+ * Must be read from incoming headers or generated according to the W3C TraceContext specification,
1288
+ * in a hex representation of 16-byte array. A.k.a. trace-id, TraceID or Distributed TraceID
1289
+ */
1290
+ getTraceId(): string;
1291
+ /**
1292
+ * Set the unique identifier for a trace. All requests / spans from the same trace share the same traceId.
1293
+ * Must be conform to the W3C TraceContext specification, in a hex representation of 16-byte array.
1294
+ * A.k.a. trace-id, TraceID or Distributed TraceID https://www.w3.org/TR/trace-context/#trace-id
1295
+ */
1296
+ setTraceId(newValue: string): void;
1297
+ /**
1298
+ * Self-generated 8-bytes identifier of the incoming request. Must be a hex representation of 8-byte array.
1299
+ * Also know as the parentId, used to link requests together
1300
+ */
1301
+ getSpanId(): string;
1302
+ /**
1303
+ * Self-generated 8-bytes identifier of the incoming request. Must be a hex representation of 8-byte array.
1304
+ * Also know as the parentId, used to link requests together
1305
+ * https://www.w3.org/TR/trace-context/#parent-id
1306
+ */
1307
+ setSpanId(newValue: string): void;
1308
+ /**
1309
+ * An integer representation of the W3C TraceContext trace-flags.
1310
+ */
1311
+ getTraceFlags(): number | undefined;
1312
+ /**
1313
+ * https://www.w3.org/TR/trace-context/#trace-flags
1314
+ * @param newValue
1315
+ */
1316
+ setTraceFlags(newValue?: number): void;
1317
+ }
1318
+
1319
+ interface IEnvelope extends ISerializable {
1320
+ /**
1321
+ * 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.
1322
+ */
1323
+ ver: number;
1324
+ /**
1325
+ * Type name of telemetry data item.
1326
+ */
1327
+ name: string;
1328
+ /**
1329
+ * 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.
1330
+ */
1331
+ time: string;
1332
+ /**
1333
+ * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items.
1334
+ */
1335
+ sampleRate: number;
1336
+ /**
1337
+ * Sequence field used to track absolute order of uploaded events.
1338
+ */
1339
+ seq: string;
1340
+ /**
1341
+ * 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.
1342
+ */
1343
+ iKey: string;
1344
+ /**
1345
+ * Key/value collection of context properties. See ContextTagKeys for information on available properties.
1346
+ */
1347
+ tags: {
1348
+ [name: string]: any;
1349
+ };
1350
+ /**
1351
+ * Telemetry data item.
1352
+ */
1353
+ data: any;
1354
+ }
1355
+
1356
+ interface IFeatureOptIn {
1357
+ [feature: string]: IFeatureOptInDetails;
1358
+ }
1359
+
1360
+ interface IFeatureOptInDetails {
1361
+ /**
1362
+ * sets feature opt-in mode
1363
+ * @default undefined
1364
+ */
1365
+ mode?: FeatureOptInMode;
1366
+ /**
1367
+ * Identifies configuration override values when given feature is enabled
1368
+ * NOTE: should use flat string for fields, for example, if you want to set value for extensionConfig.Ananlytics.disableAjaxTrackig in configurations,
1369
+ * you should use "extensionConfig.Ananlytics.disableAjaxTrackig" as field name: {["extensionConfig.Analytics.disableAjaxTrackig"]:1}
1370
+ * Default: undefined
1371
+ */
1372
+ onCfg?: {
1373
+ [field: string]: any;
1374
+ };
1375
+ /**
1376
+ * Identifies configuration override values when given feature is disabled
1377
+ * NOTE: should use flat string for fields, for example, if you want to set value for extensionConfig.Ananlytics.disableAjaxTrackig in configurations,
1378
+ * you should use "extensionConfig.Ananlytics.disableAjaxTrackig" as field name: {["extensionConfig.Analytics.disableAjaxTrackig"]:1}
1379
+ * Default: undefined
1380
+ */
1381
+ offCfg?: {
1382
+ [field: string]: any;
1383
+ };
1384
+ /**
1385
+ * define if should block any changes from cdn cfg, if set to true, cfgValue will be applied under all scenarios
1386
+ * @default false
1387
+ */
1388
+ blockCdnCfg?: boolean;
1389
+ }
1390
+
1391
+ /**
1392
+ * An alternate interface which provides automatic removal during unloading of the component
1393
+ */
1394
+ interface ILegacyUnloadHook {
1395
+ /**
1396
+ * Legacy Self remove the referenced component
1397
+ */
1398
+ remove: () => void;
1399
+ }
1400
+
1401
+ interface ILoadedPlugin<T extends IPlugin> {
1402
+ plugin: T;
1403
+ /**
1404
+ * Identifies whether the plugin is enabled and can process events. This is slightly different from isInitialized as the plugin may be initialized but disabled
1405
+ * via the setEnabled() or it may be a shared plugin which has had it's teardown function called from another instance..
1406
+ * @returns boolean = true if the plugin is in a state where it is operational.
1407
+ */
1408
+ isEnabled: () => boolean;
1409
+ /**
1410
+ * You can optionally enable / disable a plugin from processing events.
1411
+ * Setting enabled to true will not necessarily cause the `isEnabled()` to also return true
1412
+ * as the plugin must also have been successfully initialized and not had it's `teardown` method called
1413
+ * (unless it's also been re-initialized)
1414
+ */
1415
+ setEnabled: (isEnabled: boolean) => void;
1416
+ remove: (isAsync?: boolean, removeCb?: (removed?: boolean) => void) => void;
1417
+ }
1418
+
1419
+ /**
1420
+ * An interface used for the notification listener.
1421
+ * @interface
1422
+ */
1423
+ interface INotificationListener {
1424
+ /**
1425
+ * [Optional] A function called when events are sent.
1426
+ * @param events - The array of events that have been sent.
1427
+ */
1428
+ eventsSent?: (events: ITelemetryItem[]) => void;
1429
+ /**
1430
+ * [Optional] A function called when events are discarded.
1431
+ * @param events - The array of events that have been discarded.
1432
+ * @param reason - The reason for discarding the events. The EventsDiscardedReason
1433
+ * constant should be used to check the different values.
1434
+ */
1435
+ eventsDiscarded?: (events: ITelemetryItem[], reason: number) => void;
1436
+ /**
1437
+ * [Optional] A function called when the events have been requested to be sent to the sever.
1438
+ * @param sendReason - The reason why the event batch is being sent.
1439
+ * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.
1440
+ */
1441
+ eventsSendRequest?: (sendReason: number, isAsync?: boolean) => void;
1442
+ /**
1443
+ * [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
1444
+ * the event can be displayed via the debug plugin extension.
1445
+ * @param perfEvent
1446
+ */
1447
+ perfEvent?: (perfEvent: IPerfEvent) => void;
1448
+ /**
1449
+ * Unload and remove any state that this INotificationListener may be holding, this is generally called when the
1450
+ * owning Manager is being unloaded.
1451
+ * @param isAsync - Can the unload be performed asynchronously (default)
1452
+ * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then
1453
+ * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
1454
+ * / Promise to allow any listeners to wait for the operation to complete.
1455
+ */
1456
+ unload?(isAsync?: boolean): void | IPromise<void>;
1457
+ }
1458
+
1459
+ /**
1460
+ * Class to manage sending notifications to all the listeners.
1461
+ */
1462
+ interface INotificationManager {
1463
+ listeners: INotificationListener[];
1464
+ /**
1465
+ * Adds a notification listener.
1466
+ * @param listener - The notification listener to be added.
1467
+ */
1468
+ addNotificationListener(listener: INotificationListener): void;
1469
+ /**
1470
+ * Removes all instances of the listener.
1471
+ * @param listener - AWTNotificationListener to remove.
1472
+ */
1473
+ removeNotificationListener(listener: INotificationListener): void;
1474
+ /**
1475
+ * Notification for events sent.
1476
+ * @param events - The array of events that have been sent.
1477
+ */
1478
+ eventsSent(events: ITelemetryItem[]): void;
1479
+ /**
1480
+ * Notification for events being discarded.
1481
+ * @param events - The array of events that have been discarded by the SDK.
1482
+ * @param reason - The reason for which the SDK discarded the events. The EventsDiscardedReason
1483
+ * constant should be used to check the different values.
1484
+ */
1485
+ eventsDiscarded(events: ITelemetryItem[], reason: number): void;
1486
+ /**
1487
+ * [Optional] A function called when the events have been requested to be sent to the sever.
1488
+ * @param sendReason - The reason why the event batch is being sent.
1489
+ * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.
1490
+ */
1491
+ eventsSendRequest?(sendReason: number, isAsync: boolean): void;
1492
+ /**
1493
+ * [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
1494
+ * the event can be displayed via the debug plugin extension.
1495
+ * @param perfEvent - The perf event details
1496
+ */
1497
+ perfEvent?(perfEvent: IPerfEvent): void;
1498
+ /**
1499
+ * Unload and remove any state that this INotificationManager may be holding, this is generally called when the
1500
+ * owning SDK is being unloaded.
1501
+ * @param isAsync - Can the unload be performed asynchronously (default)
1502
+ * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then
1503
+ * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)
1504
+ * / Promise to allow any listeners to wait for the operation to complete.
1505
+ */
1506
+ unload?(isAsync?: boolean): void | IPromise<void>;
1507
+ }
1508
+
1509
+ class _InternalLogMessage {
1510
+ static dataType: string;
1511
+ message: string;
1512
+ messageId: _InternalMessageId;
1513
+ constructor(msgId: _InternalMessageId, msg: string, isUserAct?: boolean, properties?: Object);
1514
+ }
1515
+
1516
+ type _InternalMessageId = number | _eInternalMessageId;
1517
+
1518
+ /** IPayloadData describes interface of payload sent via POST channel */
1519
+ interface IPayloadData {
1520
+ urlString: string;
1521
+ data: Uint8Array | string;
1522
+ headers?: {
1523
+ [name: string]: string;
1524
+ };
1525
+ timeout?: number;
1526
+ disableXhrSync?: boolean;
1527
+ disableFetchKeepAlive?: boolean;
1528
+ sendReason?: SendRequestReason;
1529
+ }
1530
+
1531
+ /**
1532
+ * This interface identifies the details of an internal performance event - it does not represent an outgoing reported event
1533
+ */
1534
+ interface IPerfEvent {
1535
+ /**
1536
+ * The name of the performance event
1537
+ */
1538
+ name: string;
1539
+ /**
1540
+ * The start time of the performance event
1541
+ */
1542
+ start: number;
1543
+ /**
1544
+ * The payload (contents) of the perfEvent, may be null or only set after the event has completed depending on
1545
+ * the runtime environment.
1546
+ */
1547
+ payload: any;
1548
+ /**
1549
+ * Is this occurring from an asynchronous event
1550
+ */
1551
+ isAsync: boolean;
1552
+ /**
1553
+ * Identifies the total inclusive time spent for this event, including the time spent for child events,
1554
+ * this will be undefined until the event is completed
1555
+ */
1556
+ time?: number;
1557
+ /**
1558
+ * Identifies the exclusive time spent in for this event (not including child events),
1559
+ * this will be undefined until the event is completed.
1560
+ */
1561
+ exTime?: number;
1562
+ /**
1563
+ * The Parent event that was started before this event was created
1564
+ */
1565
+ parent?: IPerfEvent;
1566
+ /**
1567
+ * The child perf events that are contained within the total time of this event.
1568
+ */
1569
+ childEvts?: IPerfEvent[];
1570
+ /**
1571
+ * Identifies whether this event is a child event of a parent
1572
+ */
1573
+ isChildEvt: () => boolean;
1574
+ /**
1575
+ * Get the names additional context associated with this perf event
1576
+ */
1577
+ getCtx?: (key: string) => any;
1578
+ /**
1579
+ * Set the named additional context to be associated with this perf event, this will replace any existing value
1580
+ */
1581
+ setCtx?: (key: string, value: any) => void;
1582
+ /**
1583
+ * Mark this event as completed, calculating the total execution time.
1584
+ */
1585
+ complete: () => void;
1586
+ }
1587
+
1588
+ /**
1589
+ * This defines an internal performance manager for tracking and reporting the internal performance of the SDK -- It does
1590
+ * not represent or report any event to the server.
1591
+ */
1592
+ interface IPerfManager {
1593
+ /**
1594
+ * Create a new event and start timing, the manager may return null/undefined to indicate that it does not
1595
+ * want to monitor this source event.
1596
+ * @param src - The source name of the event
1597
+ * @param payloadDetails - An optional callback function to fetch the payload details for the event.
1598
+ * @param isAsync - Is the event occurring from a async event
1599
+ */
1600
+ create(src: string, payloadDetails?: () => any, isAsync?: boolean): IPerfEvent | null | undefined;
1601
+ /**
1602
+ * Complete the perfEvent and fire any notifications.
1603
+ * @param perfEvent - Fire the event which will also complete the passed event
1604
+ */
1605
+ fire(perfEvent: IPerfEvent): void;
1606
+ /**
1607
+ * Set an execution context value
1608
+ * @param key - The context key name
1609
+ * @param value - The value
1610
+ */
1611
+ setCtx(key: string, value: any): void;
1612
+ /**
1613
+ * Get the execution context value
1614
+ * @param key - The context key
1615
+ */
1616
+ getCtx(key: string): any;
1617
+ }
1618
+
1619
+ /**
1620
+ * Identifies an interface to a host that can provide an IPerfManager implementation
1621
+ */
1622
+ interface IPerfManagerProvider {
1623
+ /**
1624
+ * Get the current performance manager
1625
+ */
1626
+ getPerfMgr(): IPerfManager;
1627
+ /**
1628
+ * Set the current performance manager
1629
+ * @param perfMgr - The performance manager
1630
+ */
1631
+ setPerfMgr(perfMgr: IPerfManager): void;
1632
+ }
26
1633
 
27
- class ArraySendBuffer extends BaseSendBuffer implements ISendBuffer {
28
- constructor(logger: IDiagnosticLogger, config: ISenderConfig);
29
- markAsSent(payload: string[]): void;
30
- clearSent(payload: string[]): void;
1634
+ interface IPlugin {
1635
+ /**
1636
+ * Initialize plugin loaded by SDK
1637
+ * @param config - The config for the plugin to use
1638
+ * @param core - The current App Insights core to use for initializing this plugin instance
1639
+ * @param extensions - The complete set of extensions to be used for initializing the plugin
1640
+ * @param pluginChain - [Optional] specifies the current plugin chain which identifies the
1641
+ * set of plugins and the order they should be executed for the current request.
1642
+ */
1643
+ initialize: (config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain) => void;
1644
+ /**
1645
+ * Returns a value that indicates whether the plugin has already been previously initialized.
1646
+ * New plugins should implement this method to avoid being initialized more than once.
1647
+ */
1648
+ isInitialized?: () => boolean;
1649
+ /**
1650
+ * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and
1651
+ * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further
1652
+ * processTelemetry calls are ignored and it just calls the processNext() with the provided context.
1653
+ * @param unloadCtx - This is the context that should be used during unloading.
1654
+ * @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.
1655
+ * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing.
1656
+ */
1657
+ teardown?: (unloadCtx: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => void | boolean;
1658
+ /**
1659
+ * Extension name
1660
+ */
1661
+ readonly identifier: string;
1662
+ /**
1663
+ * Plugin version (available in data.properties.version in common schema)
1664
+ */
1665
+ readonly version?: string;
1666
+ /**
1667
+ * The App Insights core to use for backward compatibility.
1668
+ * Therefore the interface will be able to access the core without needing to cast to "any".
1669
+ * [optional] any 3rd party plugins which are already implementing this interface don't fail to compile.
1670
+ */
1671
+ core?: IAppInsightsCore;
31
1672
  }
32
1673
 
33
- abstract class BaseSendBuffer {
34
- protected _get: () => string[];
35
- protected _set: (buffer: string[]) => string[];
36
- constructor(logger: IDiagnosticLogger, config: ISenderConfig);
37
- enqueue(payload: string): void;
38
- count(): number;
39
- size(): number;
40
- clear(): void;
41
- getItems(): string[];
42
- batchPayloads(payload: string[]): string;
43
- createNew(newLogger?: IDiagnosticLogger, newConfig?: ISenderConfig, canUseSessionStorage?: boolean): ArraySendBuffer | SessionStorageSendBuffer;
1674
+ /**
1675
+ * The current context for the current call to processTelemetry(), used to support sharing the same plugin instance
1676
+ * between multiple AppInsights instances
1677
+ */
1678
+ interface IProcessTelemetryContext extends IBaseProcessingContext {
1679
+ /**
1680
+ * Call back for telemetry processing before it it is sent
1681
+ * @param env - This is the current event being reported
1682
+ * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void)
1683
+ */
1684
+ processNext: (env: ITelemetryItem) => boolean | void;
1685
+ /**
1686
+ * Create a new context using the core and config from the current instance, returns a new instance of the same type
1687
+ * @param plugins - The execution order to process the plugins, if null or not supplied
1688
+ * then the current execution order will be copied.
1689
+ * @param startAt - The plugin to start processing from, if missing from the execution
1690
+ * order then the next plugin will be NOT set.
1691
+ */
1692
+ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryContext;
44
1693
  }
45
1694
 
46
- interface IBackendResponse {
1695
+ /**
1696
+ * The current context for the current call to teardown() implementations, used to support when plugins are being removed
1697
+ * or the SDK is being unloaded.
1698
+ */
1699
+ interface IProcessTelemetryUnloadContext extends IBaseProcessingContext {
47
1700
  /**
48
- * Number of items received by the backend
1701
+ * This Plugin has finished unloading, so unload the next one
1702
+ * @param uploadState - The state of the unload process
1703
+ * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void)
49
1704
  */
50
- readonly itemsReceived: number;
1705
+ processNext: (unloadState: ITelemetryUnloadState) => boolean | void;
51
1706
  /**
52
- * Number of items succesfuly accepted by the backend
1707
+ * Create a new context using the core and config from the current instance, returns a new instance of the same type
1708
+ * @param plugins - The execution order to process the plugins, if null or not supplied
1709
+ * then the current execution order will be copied.
1710
+ * @param startAt - The plugin to start processing from, if missing from the execution
1711
+ * order then the next plugin will be NOT set.
53
1712
  */
54
- readonly itemsAccepted: number;
1713
+ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryUnloadContext;
1714
+ }
1715
+
1716
+ /**
1717
+ * The current context for the current call to the plugin update() implementations, used to support the notifications
1718
+ * for when plugins are added, removed or the configuration was changed.
1719
+ */
1720
+ interface IProcessTelemetryUpdateContext extends IBaseProcessingContext {
55
1721
  /**
56
- * List of errors for items which were not accepted
1722
+ * This Plugin has finished unloading, so unload the next one
1723
+ * @param updateState - The update State
1724
+ * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void)
57
1725
  */
58
- readonly errors: IResponseError[];
1726
+ processNext: (updateState: ITelemetryUpdateState) => boolean | void;
59
1727
  /**
60
- * App id returned by the backend - not necessary returned, but we don't need it with each response.
1728
+ * Create a new context using the core and config from the current instance, returns a new instance of the same type
1729
+ * @param plugins - The execution order to process the plugins, if null or not supplied
1730
+ * then the current execution order will be copied.
1731
+ * @param startAt - The plugin to start processing from, if missing from the execution
1732
+ * order then the next plugin will be NOT set.
61
1733
  */
62
- readonly appId?: string;
1734
+ createNew: (plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryUpdateContext;
1735
+ }
1736
+
1737
+ /**
1738
+ * Create a Promise object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
1739
+ * This interface definition, closely mirrors the typescript / javascript PromiseLike<T> and Promise<T> definitions as well as providing
1740
+ * simular functions as that provided by jQuery deferred objects.
1741
+ *
1742
+ * The returned Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers
1743
+ * with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous
1744
+ * methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point
1745
+ * in the future.
1746
+ *
1747
+ * A Promise is in one of these states:
1748
+ * <ul>
1749
+ * <li> pending: initial state, neither fulfilled nor rejected.
1750
+ * <li> fulfilled: meaning that the operation was completed successfully.
1751
+ * <li> rejected: meaning that the operation failed.
1752
+ * </ul>
1753
+ *
1754
+ * A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the
1755
+ * associated handlers queued up by a promise's then method are called synchronously. If the promise has already been fulfilled or rejected
1756
+ * when a corresponding handler is attached, the handler will be called synchronously, so there is no race condition between an asynchronous
1757
+ * operation completing and its handlers being attached.
1758
+ *
1759
+ * As the `then()` and `catch()` methods return promises, they can be chained.
1760
+ * @typeParam T - Identifies the expected return type from the promise
1761
+ */
1762
+ interface IPromise<T> extends PromiseLike<T>, Promise<T> {
1763
+ /**
1764
+ * Returns a string representation of the current state of the promise. The promise can be in one of four states.
1765
+ * <ul>
1766
+ * <li> <b>"pending"</b>: The promise is not yet in a completed state (neither "rejected"; or "resolved").</li>
1767
+ * <li> <b>"resolved"</b>: The promise is in the resolved state.</li>
1768
+ * <li> <b>"rejected"</b>: The promise is in the rejected state.</li>
1769
+ * </ul>
1770
+ * @example
1771
+ * ```ts
1772
+ * let doResolve;
1773
+ * let promise: IPromise<any> = createSyncPromise((resolve) => {
1774
+ * doResolve = resolve;
1775
+ * });
1776
+ *
1777
+ * let state: string = promise.state();
1778
+ * console.log("State: " + state); // State: pending
1779
+ * doResolve(true); // Promise will resolve synchronously as it's a synchronous promise
1780
+ * console.log("State: " + state); // State: resolved
1781
+ * ```
1782
+ */
1783
+ state?: string;
1784
+ /**
1785
+ * Attaches callbacks for the resolution and/or rejection of the Promise.
1786
+ * @param onResolved The callback to execute when the Promise is resolved.
1787
+ * @param onRejected The callback to execute when the Promise is rejected.
1788
+ * @returns A Promise for the completion of which ever callback is executed.
1789
+ * @example
1790
+ * ```ts
1791
+ * const promise1 = createPromise((resolve, reject) => {
1792
+ * resolve('Success!');
1793
+ * });
1794
+ *
1795
+ * promise1.then((value) => {
1796
+ * console.log(value);
1797
+ * // expected output: "Success!"
1798
+ * });
1799
+ * ```
1800
+ */
1801
+ then<TResult1 = T, TResult2 = never>(onResolved?: ResolvedPromiseHandler<T, TResult1>, onRejected?: RejectedPromiseHandler<TResult2>): IPromise<TResult1 | TResult2>;
1802
+ /**
1803
+ * Attaches callbacks for the resolution and/or rejection of the Promise.
1804
+ * @param onResolved The callback to execute when the Promise is resolved.
1805
+ * @param onRejected The callback to execute when the Promise is rejected.
1806
+ * @returns A Promise for the completion of which ever callback is executed.
1807
+ * @example
1808
+ * ```ts
1809
+ * const promise1 = createPromise((resolve, reject) => {
1810
+ * resolve('Success!');
1811
+ * });
1812
+ *
1813
+ * promise1.then((value) => {
1814
+ * console.log(value);
1815
+ * // expected output: "Success!"
1816
+ * });
1817
+ * ```
1818
+ */
1819
+ then<TResult1 = T, TResult2 = never>(onResolved?: ResolvedPromiseHandler<T, TResult1>, onRejected?: RejectedPromiseHandler<TResult2>): PromiseLike<TResult1 | TResult2>;
1820
+ /**
1821
+ * Attaches callbacks for the resolution and/or rejection of the Promise.
1822
+ * @param onResolved The callback to execute when the Promise is resolved.
1823
+ * @param onRejected The callback to execute when the Promise is rejected.
1824
+ * @returns A Promise for the completion of which ever callback is executed.
1825
+ * @example
1826
+ * ```ts
1827
+ * const promise1 = createPromise((resolve, reject) => {
1828
+ * resolve('Success!');
1829
+ * });
1830
+ *
1831
+ * promise1.then((value) => {
1832
+ * console.log(value);
1833
+ * // expected output: "Success!"
1834
+ * });
1835
+ * ```
1836
+ */
1837
+ then<TResult1 = T, TResult2 = never>(onResolved?: ResolvedPromiseHandler<T, TResult1>, onRejected?: RejectedPromiseHandler<TResult2>): Promise<TResult1 | TResult2>;
1838
+ /**
1839
+ * Attaches a callback for only the rejection of the Promise.
1840
+ * @param onRejected The callback to execute when the Promise is rejected.
1841
+ * @returns A Promise for the completion of the callback.
1842
+ * @example
1843
+ * ```ts
1844
+ * const promise1 = createPromise((resolve, reject) => {
1845
+ * throw 'Uh-oh!';
1846
+ * });
1847
+ *
1848
+ * promise1.catch((error) => {
1849
+ * console.error(error);
1850
+ * });
1851
+ * // expected output: Uh-oh!
1852
+ * ```
1853
+ */
1854
+ catch<TResult = never>(onRejected?: ((reason: any) => TResult | IPromise<TResult>) | undefined | null): IPromise<T | TResult>;
1855
+ /**
1856
+ * Attaches a callback for only the rejection of the Promise.
1857
+ * @param onRejected The callback to execute when the Promise is rejected.
1858
+ * @returns A Promise for the completion of the callback.
1859
+ * @example
1860
+ * ```ts
1861
+ * const promise1 = createPromise((resolve, reject) => {
1862
+ * throw 'Uh-oh!';
1863
+ * });
1864
+ *
1865
+ * promise1.catch((error) => {
1866
+ * console.error(error);
1867
+ * });
1868
+ * // expected output: Uh-oh!
1869
+ * ```
1870
+ */
1871
+ catch<TResult = never>(onRejected?: ((reason: any) => TResult | IPromise<TResult>) | undefined | null): PromiseLike<T | TResult>;
1872
+ /**
1873
+ * Attaches a callback for only the rejection of the Promise.
1874
+ * @param onRejected The callback to execute when the Promise is rejected.
1875
+ * @returns A Promise for the completion of the callback.
1876
+ * @example
1877
+ * ```ts
1878
+ * const promise1 = createPromise((resolve, reject) => {
1879
+ * throw 'Uh-oh!';
1880
+ * });
1881
+ *
1882
+ * promise1.catch((error) => {
1883
+ * console.error(error);
1884
+ * });
1885
+ * // expected output: Uh-oh!
1886
+ * ```
1887
+ */
1888
+ catch<TResult = never>(onRejected?: ((reason: any) => TResult | IPromise<TResult>) | undefined | null): Promise<T | TResult>;
1889
+ /**
1890
+ * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
1891
+ * resolved value cannot be modified from the callback.
1892
+ * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected).
1893
+ * @returns A Promise for the completion of the callback.
1894
+ * @example
1895
+ * ```ts
1896
+ * function doFunction() {
1897
+ * return createPromise((resolve, reject) => {
1898
+ * if (Math.random() > 0.5) {
1899
+ * resolve('Function has completed');
1900
+ * } else {
1901
+ * reject(new Error('Function failed to process'));
1902
+ * }
1903
+ * });
1904
+ * }
1905
+ *
1906
+ * doFunction().then((data) => {
1907
+ * console.log(data);
1908
+ * }).catch((err) => {
1909
+ * console.error(err);
1910
+ * }).finally(() => {
1911
+ * console.log('Function processing completed');
1912
+ * });
1913
+ * ```
1914
+ */
1915
+ finally(onfinally?: FinallyPromiseHandler): IPromise<T>;
1916
+ /**
1917
+ * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
1918
+ * resolved value cannot be modified from the callback.
1919
+ * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected).
1920
+ * @returns A Promise for the completion of the callback.
1921
+ * @example
1922
+ * ```ts
1923
+ * function doFunction() {
1924
+ * return createPromise((resolve, reject) => {
1925
+ * if (Math.random() > 0.5) {
1926
+ * resolve('Function has completed');
1927
+ * } else {
1928
+ * reject(new Error('Function failed to process'));
1929
+ * }
1930
+ * });
1931
+ * }
1932
+ *
1933
+ * doFunction().then((data) => {
1934
+ * console.log(data);
1935
+ * }).catch((err) => {
1936
+ * console.error(err);
1937
+ * }).finally(() => {
1938
+ * console.log('Function processing completed');
1939
+ * });
1940
+ * ```
1941
+ */
1942
+ finally(onFinally?: FinallyPromiseHandler): Promise<T>;
1943
+ }
1944
+
1945
+ interface IRequestContext {
1946
+ status?: number;
1947
+ xhr?: XMLHttpRequest;
1948
+ request?: Request;
1949
+ response?: Response | string;
63
1950
  }
64
1951
 
65
1952
  interface IResponseError {
@@ -68,6 +1955,14 @@ declare namespace ApplicationInsights {
68
1955
  readonly message: string;
69
1956
  }
70
1957
 
1958
+ interface ISample {
1959
+ /**
1960
+ * Sample rate
1961
+ */
1962
+ sampleRate: number;
1963
+ isSampledIn(envelope: ITelemetryItem): boolean;
1964
+ }
1965
+
71
1966
  interface ISendBuffer {
72
1967
  /**
73
1968
  * Enqueue the payload
@@ -214,8 +2109,441 @@ declare namespace ApplicationInsights {
214
2109
  * @since 3.0.6
215
2110
  */
216
2111
  disableSendBeaconSplit?: boolean;
2112
+ /**
2113
+ * (Optional) The specific error codes that will cause a retry of sending data to the backend.
2114
+ * @since 3.1.1
2115
+ */
2116
+ retryCodes?: number[];
2117
+ }
2118
+
2119
+ interface ISerializable {
2120
+ /**
2121
+ * The set of fields for a serializable object.
2122
+ * This defines the serialization order and a value of true/false
2123
+ * for each field defines whether the field is required or not.
2124
+ */
2125
+ aiDataContract: any;
2126
+ }
2127
+
2128
+ /**
2129
+ * Identifies a simple interface to allow you to override the storage mechanism used
2130
+ * to track unsent and unacknowledged events. When provided it must provide both
2131
+ * the get and set item functions.
2132
+ * @since 2.8.12
2133
+ */
2134
+ interface IStorageBuffer {
2135
+ /**
2136
+ * Retrieves the stored value for a given key
2137
+ */
2138
+ getItem(logger: IDiagnosticLogger, name: string): string;
2139
+ /**
2140
+ * Sets the stored value for a given key
2141
+ */
2142
+ setItem(logger: IDiagnosticLogger, name: string, data: string): boolean;
2143
+ }
2144
+
2145
+ interface ITelemetryInitializerHandler extends ILegacyUnloadHook {
2146
+ remove(): void;
2147
+ }
2148
+
2149
+ /**
2150
+ * Telemety item supported in Core
2151
+ */
2152
+ interface ITelemetryItem {
2153
+ /**
2154
+ * CommonSchema Version of this SDK
2155
+ */
2156
+ ver?: string;
2157
+ /**
2158
+ * Unique name of the telemetry item
2159
+ */
2160
+ name: string;
2161
+ /**
2162
+ * Timestamp when item was sent
2163
+ */
2164
+ time?: string;
2165
+ /**
2166
+ * Identifier of the resource that uniquely identifies which resource data is sent to
2167
+ */
2168
+ iKey?: string;
2169
+ /**
2170
+ * System context properties of the telemetry item, example: ip address, city etc
2171
+ */
2172
+ ext?: {
2173
+ [key: string]: any;
2174
+ };
2175
+ /**
2176
+ * System context property extensions that are not global (not in ctx)
2177
+ */
2178
+ tags?: Tags & Tags[];
2179
+ /**
2180
+ * Custom data
2181
+ */
2182
+ data?: ICustomProperties;
2183
+ /**
2184
+ * Telemetry type used for part B
2185
+ */
2186
+ baseType?: string;
2187
+ /**
2188
+ * Based on schema for part B
2189
+ */
2190
+ baseData?: {
2191
+ [key: string]: any;
2192
+ };
2193
+ }
2194
+
2195
+ /**
2196
+ * Configuration provided to SDK core
2197
+ */
2198
+ interface ITelemetryPlugin extends ITelemetryProcessor, IPlugin {
2199
+ /**
2200
+ * Set next extension for telemetry processing, this is not optional as plugins should use the
2201
+ * processNext() function of the passed IProcessTelemetryContext instead. It is being kept for
2202
+ * now for backward compatibility only.
2203
+ */
2204
+ setNextPlugin?: (next: ITelemetryPlugin | ITelemetryPluginChain) => void;
2205
+ /**
2206
+ * Priority of the extension
2207
+ */
2208
+ readonly priority: number;
2209
+ }
2210
+
2211
+ /**
2212
+ * Configuration provided to SDK core
2213
+ */
2214
+ interface ITelemetryPluginChain extends ITelemetryProcessor {
2215
+ /**
2216
+ * Returns the underlying plugin that is being proxied for the processTelemetry call
2217
+ */
2218
+ getPlugin: () => ITelemetryPlugin;
2219
+ /**
2220
+ * Returns the next plugin
2221
+ */
2222
+ getNext: () => ITelemetryPluginChain;
2223
+ /**
2224
+ * This plugin is being unloaded and should remove any hooked events and cleanup any global/scoped values, after this
2225
+ * call the plugin will be removed from the telemetry processing chain and will no longer receive any events..
2226
+ * @param unloadCtx - The unload context to use for this call.
2227
+ * @param unloadState - The details of the unload operation
2228
+ */
2229
+ unload?: (unloadCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) => void;
2230
+ }
2231
+
2232
+ interface ITelemetryProcessor {
2233
+ /**
2234
+ * Call back for telemetry processing before it it is sent
2235
+ * @param env - This is the current event being reported
2236
+ * @param itemCtx - This is the context for the current request, ITelemetryPlugin instances
2237
+ * can optionally use this to access the current core instance or define / pass additional information
2238
+ * to later plugins (vs appending items to the telemetry item)
2239
+ */
2240
+ processTelemetry: (env: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => void;
2241
+ /**
2242
+ * The the plugin should re-evaluate configuration and update any cached configuration settings or
2243
+ * plugins. If implemented this method will be called whenever a plugin is added or removed and if
2244
+ * the configuration has bee updated.
2245
+ * @param updateCtx - This is the context that should be used during updating.
2246
+ * @param updateState - The details / state of the update process, it holds details like the current and previous configuration.
2247
+ * @returns boolean - true if the plugin has or will call updateCtx.processNext(), this allows the plugin to perform any asynchronous operations.
2248
+ */
2249
+ update?: (updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState) => void | boolean;
217
2250
  }
218
2251
 
2252
+ interface ITelemetryUnloadState {
2253
+ reason: TelemetryUnloadReason;
2254
+ isAsync: boolean;
2255
+ flushComplete?: boolean;
2256
+ }
2257
+
2258
+ interface ITelemetryUpdateState {
2259
+ /**
2260
+ * Identifies the reason for the update notification, this is a bitwise numeric value
2261
+ */
2262
+ reason: TelemetryUpdateReason;
2263
+ /**
2264
+ * This is a new active configuration that should be used
2265
+ */
2266
+ cfg?: IConfiguration;
2267
+ /**
2268
+ * The detected changes
2269
+ */
2270
+ oldCfg?: IConfiguration;
2271
+ /**
2272
+ * If this is a configuration update this was the previous configuration that was used
2273
+ */
2274
+ newConfig?: IConfiguration;
2275
+ /**
2276
+ * Was the new config requested to be merged with the existing config
2277
+ */
2278
+ merge?: boolean;
2279
+ /**
2280
+ * This holds a collection of plugins that have been added (if the reason identifies that one or more plugins have been added)
2281
+ */
2282
+ added?: IPlugin[];
2283
+ /**
2284
+ * This holds a collection of plugins that have been removed (if the reason identifies that one or more plugins have been removed)
2285
+ */
2286
+ removed?: IPlugin[];
2287
+ }
2288
+
2289
+ /**
2290
+ * Identifies frequency of items sent
2291
+ * Default: send data on 28th every 3 month each year
2292
+ */
2293
+ interface IThrottleInterval {
2294
+ /**
2295
+ * Identifies month interval that items can be sent
2296
+ * 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.)
2297
+ * If both monthInterval and dayInterval are undefined, it will be set to 3
2298
+ */
2299
+ monthInterval?: number;
2300
+ /**
2301
+ * Identifies days Interval from start date that items can be sent
2302
+ * Default: undefined
2303
+ */
2304
+ dayInterval?: number;
2305
+ /**
2306
+ * Identifies days within each month that items can be sent
2307
+ * If both monthInterval and dayInterval are undefined, it will be default to [28]
2308
+ */
2309
+ daysOfMonth?: number[];
2310
+ }
2311
+
2312
+ /**
2313
+ * Identifies limit number/percentage of items sent per time
2314
+ * If both are provided, minimum number between the two will be used
2315
+ */
2316
+ interface IThrottleLimit {
2317
+ /**
2318
+ * Identifies sampling percentage of items per time
2319
+ * The percentage is set to 4 decimal places, for example: 1 means 0.0001%
2320
+ * Default: 100 (0.01%)
2321
+ */
2322
+ samplingRate?: number;
2323
+ /**
2324
+ * Identifies limit number of items per time
2325
+ * Default: 1
2326
+ */
2327
+ maxSendNumber?: number;
2328
+ }
2329
+
2330
+ /**
2331
+ * Identifies basic config
2332
+ */
2333
+ interface IThrottleMgrConfig {
2334
+ /**
2335
+ * Identifies if throttle is disabled
2336
+ * Default: false
2337
+ */
2338
+ disabled?: boolean;
2339
+ /**
2340
+ * Identifies limit number/percentage of items sent per time
2341
+ * Default: sampling percentage 0.01% with one item sent per time
2342
+ */
2343
+ limit?: IThrottleLimit;
2344
+ /**
2345
+ * Identifies frequency of items sent
2346
+ * Default: send data on 28th every 3 month each year
2347
+ */
2348
+ interval?: IThrottleInterval;
2349
+ }
2350
+
2351
+ /**
2352
+ * A Timer handler which is returned from {@link scheduleTimeout} which contains functions to
2353
+ * cancel or restart (refresh) the timeout function.
2354
+ *
2355
+ * @since 0.4.4
2356
+ * @group Timer
2357
+ */
2358
+ interface ITimerHandler {
2359
+ /**
2360
+ * Cancels a timeout that was previously scheduled, after calling this function any previously
2361
+ * scheduled timer will not execute.
2362
+ * @example
2363
+ * ```ts
2364
+ * let theTimer = scheduleTimeout(...);
2365
+ * theTimer.cancel();
2366
+ * ```
2367
+ */
2368
+ cancel(): void;
2369
+ /**
2370
+ * Reschedules the timer to call its callback at the previously specified duration
2371
+ * adjusted to the current time. This is useful for refreshing a timer without allocating
2372
+ * a new JavaScript object.
2373
+ *
2374
+ * Using this on a timer that has already called its callback will reactivate the timer.
2375
+ * Calling on a timer that has not yet executed will just reschedule the current timer.
2376
+ * @example
2377
+ * ```ts
2378
+ * let theTimer = scheduleTimeout(...);
2379
+ * // The timer will be restarted (if already executed) or rescheduled (if it has not yet executed)
2380
+ * theTimer.refresh();
2381
+ * ```
2382
+ */
2383
+ refresh(): ITimerHandler;
2384
+ /**
2385
+ * When called, requests that the event loop not exit so long when the ITimerHandler is active.
2386
+ * Calling timer.ref() multiple times will have no effect. By default, all ITimerHandler objects
2387
+ * will create "ref'ed" instances, making it normally unnecessary to call timer.ref() unless
2388
+ * timer.unref() had been called previously.
2389
+ * @since 0.7.0
2390
+ * @returns the ITimerHandler instance
2391
+ * @example
2392
+ * ```ts
2393
+ * let theTimer = createTimeout(...);
2394
+ *
2395
+ * // Make sure the timer is referenced (the default) so that the runtime (Node) does not terminate
2396
+ * // if there is a waiting referenced timer.
2397
+ * theTimer.ref();
2398
+ * ```
2399
+ */
2400
+ ref(): this;
2401
+ /**
2402
+ * When called, the any active ITimerHandler instance will not require the event loop to remain
2403
+ * active (Node.js). If there is no other activity keeping the event loop running, the process may
2404
+ * exit before the ITimerHandler instance callback is invoked. Calling timer.unref() multiple times
2405
+ * will have no effect.
2406
+ * @since 0.7.0
2407
+ * @returns the ITimerHandler instance
2408
+ * @example
2409
+ * ```ts
2410
+ * let theTimer = createTimeout(...);
2411
+ *
2412
+ * // Unreference the timer so that the runtime (Node) may terminate if nothing else is running.
2413
+ * theTimer.unref();
2414
+ * ```
2415
+ */
2416
+ unref(): this;
2417
+ /**
2418
+ * If true, any running referenced `ITimerHandler` instance will keep the Node.js event loop active.
2419
+ * @since 0.7.0
2420
+ * @example
2421
+ * ```ts
2422
+ * let theTimer = createTimeout(...);
2423
+ *
2424
+ * // Unreference the timer so that the runtime (Node) may terminate if nothing else is running.
2425
+ * theTimer.unref();
2426
+ * let hasRef = theTimer.hasRef(); // false
2427
+ *
2428
+ * theTimer.ref();
2429
+ * hasRef = theTimer.hasRef(); // true
2430
+ * ```
2431
+ */
2432
+ hasRef(): boolean;
2433
+ /**
2434
+ * Gets or Sets a flag indicating if the underlying timer is currently enabled and running.
2435
+ * Setting the enabled flag to the same as it's current value has no effect, setting to `true`
2436
+ * when already `true` will not {@link ITimerHandler.refresh | refresh}() the timer.
2437
+ * And setting to 'false` will {@link ITimerHandler.cancel | cancel}() the timer.
2438
+ * @since 0.8.1
2439
+ * @example
2440
+ * ```ts
2441
+ * let theTimer = createTimeout(...);
2442
+ *
2443
+ * // Check if enabled
2444
+ * theTimer.enabled; // false
2445
+ *
2446
+ * // Start the timer
2447
+ * theTimer.enabled = true; // Same as calling refresh()
2448
+ * theTimer.enabled; //true
2449
+ *
2450
+ * // Has no effect as it's already running
2451
+ * theTimer.enabled = true;
2452
+ *
2453
+ * // Will refresh / restart the time
2454
+ * theTimer.refresh()
2455
+ *
2456
+ * let theTimer = scheduleTimeout(...);
2457
+ *
2458
+ * // Check if enabled
2459
+ * theTimer.enabled; // true
2460
+ * ```
2461
+ */
2462
+ enabled: boolean;
2463
+ }
2464
+
2465
+ /**
2466
+ * An interface which provides automatic removal during unloading of the component
2467
+ */
2468
+ interface IUnloadHook {
2469
+ /**
2470
+ * Self remove the referenced component
2471
+ */
2472
+ rm: () => void;
2473
+ }
2474
+
2475
+ /**
2476
+ * Interface which identifiesAdd this hook so that it is automatically removed during unloading
2477
+ * @param hooks - The single hook or an array of IInstrumentHook objects
2478
+ */
2479
+ interface IUnloadHookContainer {
2480
+ add: (hooks: IUnloadHook | IUnloadHook[] | Iterator<IUnloadHook> | ILegacyUnloadHook | ILegacyUnloadHook[] | Iterator<ILegacyUnloadHook>) => void;
2481
+ run: (logger?: IDiagnosticLogger) => void;
2482
+ }
2483
+
2484
+ interface IWatchDetails<T = IConfiguration> {
2485
+ /**
2486
+ * The current config object
2487
+ */
2488
+ cfg: T;
2489
+ /**
2490
+ * Set the value against the provided config/name with the value, the property
2491
+ * will be converted to be dynamic (if not already) as long as the provided config
2492
+ * is already a tracked dynamic object.
2493
+ * @throws TypeError if the provided config is not a monitored dynamic config
2494
+ */
2495
+ set: <C, V>(theConfig: C, name: string, value: V) => V;
2496
+ /**
2497
+ * Set default values for the config if not present.
2498
+ * @param theConfig - The configuration object to set default on (if missing)
2499
+ * @param defaultValues - The default values to apply to the config
2500
+ */
2501
+ setDf: <C>(theConfig: C, defaultValues: IConfigDefaults<C>) => C;
2502
+ /**
2503
+ * Set this named property of the target as referenced, which will cause any object or array instance
2504
+ * to be updated in-place rather than being entirely replaced. All other values will continue to be replaced.
2505
+ * @returns The referenced properties current value
2506
+ */
2507
+ ref: <C, V = any>(target: C, name: string) => V;
2508
+ /**
2509
+ * Set this named property of the target as read-only, which will block this single named property from
2510
+ * ever being changed for the target instance.
2511
+ * This does NOT freeze or seal the instance, it just stops the direct re-assignment of the named property,
2512
+ * if the value is a non-primitive (ie. an object or array) it's properties will still be mutable.
2513
+ * @returns The referenced properties current value
2514
+ */
2515
+ rdOnly: <C, V = any>(target: C, name: string) => V;
2516
+ }
2517
+
2518
+ /**
2519
+ * The IXHROverride interface overrides the way HTTP requests are sent.
2520
+ */
2521
+ interface IXHROverride {
2522
+ sendPOST: SendPOSTFunction;
2523
+ }
2524
+
2525
+ const LoggingSeverity: EnumValue<typeof eLoggingSeverity>;
2526
+
2527
+ type LoggingSeverity = number | eLoggingSeverity;
2528
+
2529
+ type OnCompleteCallback = (status: number, headers: {
2530
+ [headerName: string]: string;
2531
+ }, response?: string) => void;
2532
+
2533
+ /**
2534
+ * This defines the handler function for when a promise is rejected.
2535
+ * @param value This is the value passed as part of resolving the Promise
2536
+ * @return This may return a value, another Promise or void. @see {@link IPromise.then} for how the value is handled.
2537
+ */
2538
+ type RejectedPromiseHandler<T = never> = (((reason: any) => T | IPromise<T> | PromiseLike<T>) | undefined | null);
2539
+
2540
+ /**
2541
+ * This defines the handler function for when a promise is resolved.
2542
+ * @param value This is the value passed as part of resolving the Promise
2543
+ * @return This may return a value, another Promise or void. @see {@link IPromise.then} for how the value is handled.
2544
+ */
2545
+ type ResolvedPromiseHandler<T, TResult1 = T> = (((value: T) => TResult1 | IPromise<TResult1> | PromiseLike<TResult1>) | undefined | null);
2546
+
219
2547
  class Sender extends BaseTelemetryPlugin implements IChannelControls {
220
2548
  static constructEnvelope(orig: ITelemetryItem, iKey: string, logger: IDiagnosticLogger, convertUndefined?: any): IEnvelope;
221
2549
  readonly priority: number;
@@ -317,6 +2645,60 @@ declare namespace ApplicationInsights {
317
2645
 
318
2646
  type SenderFunction = (payload: string[], isAsync: boolean) => void | IPromise<boolean>;
319
2647
 
2648
+ /**
2649
+ * SendPOSTFunction type defines how an HTTP POST request is sent to an ingestion server
2650
+ * @param payload - The payload object that should be sent, contains the url, bytes/string and headers for the request
2651
+ * @param oncomplete - The function to call once the request has completed whether a success, failure or timeout
2652
+ * @param sync - A boolean flag indicating whether the request should be sent as a synchronous request.
2653
+ */
2654
+ type SendPOSTFunction = (payload: IPayloadData, oncomplete: OnCompleteCallback, sync?: boolean) => void | IPromise<boolean>;
2655
+
2656
+ /**
2657
+ * The EventsDiscardedReason enumeration contains a set of values that specify the reason for discarding an event.
2658
+ */
2659
+ const enum SendRequestReason {
2660
+ /**
2661
+ * No specific reason was specified
2662
+ */
2663
+ Undefined = 0,
2664
+ /**
2665
+ * Events are being sent based on the normal event schedule / timer.
2666
+ */
2667
+ NormalSchedule = 1,
2668
+ /**
2669
+ * A manual flush request was received
2670
+ */
2671
+ ManualFlush = 1,
2672
+ /**
2673
+ * Unload event is being processed
2674
+ */
2675
+ Unload = 2,
2676
+ /**
2677
+ * The event(s) being sent are sync events
2678
+ */
2679
+ SyncEvent = 3,
2680
+ /**
2681
+ * The Channel was resumed
2682
+ */
2683
+ Resumed = 4,
2684
+ /**
2685
+ * The event(s) being sent as a retry
2686
+ */
2687
+ Retry = 5,
2688
+ /**
2689
+ * The SDK is unloading
2690
+ */
2691
+ SdkUnload = 6,
2692
+ /**
2693
+ * Maximum batch size would be exceeded
2694
+ */
2695
+ MaxBatchSize = 10,
2696
+ /**
2697
+ * The Maximum number of events have already been queued
2698
+ */
2699
+ MaxQueuedEvents = 20
2700
+ }
2701
+
320
2702
  class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuffer {
321
2703
  static BUFFER_KEY: string;
322
2704
  static SENT_BUFFER_KEY: string;
@@ -329,11 +2711,64 @@ declare namespace ApplicationInsights {
329
2711
  createNew(newLogger?: IDiagnosticLogger, newConfig?: ISenderConfig, canUseSessionStorage?: boolean): ArraySendBuffer | SessionStorageSendBuffer;
330
2712
  }
331
2713
 
2714
+ interface Tags {
2715
+ [key: string]: any;
2716
+ }
2717
+
2718
+ type TelemetryInitializerFunction = <T extends ITelemetryItem>(item: T) => boolean | void;
2719
+
2720
+ /**
2721
+ * The TelemetryUnloadReason enumeration contains the possible reasons for why a plugin is being unloaded / torndown().
2722
+ */
2723
+ const enum TelemetryUnloadReason {
2724
+ /**
2725
+ * Teardown has been called without any context.
2726
+ */
2727
+ ManualTeardown = 0,
2728
+ /**
2729
+ * Just this plugin is being removed
2730
+ */
2731
+ PluginUnload = 1,
2732
+ /**
2733
+ * This instance of the plugin is being removed and replaced
2734
+ */
2735
+ PluginReplace = 2,
2736
+ /**
2737
+ * The entire SDK is being unloaded
2738
+ */
2739
+ SdkUnload = 50
2740
+ }
2741
+
2742
+ /**
2743
+ * The TelemetryUpdateReason enumeration contains a set of bit-wise values that specify the reason for update request.
2744
+ */
2745
+ const enum TelemetryUpdateReason {
2746
+ /**
2747
+ * Unknown.
2748
+ */
2749
+ Unknown = 0,
2750
+ /**
2751
+ * The configuration has ben updated or changed
2752
+ */
2753
+ ConfigurationChanged = 1,
2754
+ /**
2755
+ * One or more plugins have been added
2756
+ */
2757
+ PluginAdded = 16,
2758
+ /**
2759
+ * One or more plugins have been removed
2760
+ */
2761
+ PluginRemoved = 32
2762
+ }
2763
+
2764
+ type UnloadHandler = (itemCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) => void;
2765
+
2766
+ type WatcherFunction<T = IConfiguration> = (details: IWatchDetails<T>) => void;
2767
+
332
2768
  interface XDomainRequest extends XMLHttpRequestEventTarget {
333
2769
  readonly responseText: string;
334
2770
  send(payload: string): void;
335
2771
  open(method: string, url: string): void;
336
2772
  }
337
2773
 
338
-
339
2774
  }