@microsoft/applicationinsights-analytics-js 2.8.0-beta.2203-02 → 2.8.0-beta.2203-05

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 (32) hide show
  1. package/browser/applicationinsights-analytics-js.integrity.json +9 -9
  2. package/browser/applicationinsights-analytics-js.js +813 -252
  3. package/browser/applicationinsights-analytics-js.js.map +1 -1
  4. package/browser/applicationinsights-analytics-js.min.js +2 -2
  5. package/browser/applicationinsights-analytics-js.min.js.map +1 -1
  6. package/dist/applicationinsights-analytics-js.api.json +48 -183
  7. package/dist/applicationinsights-analytics-js.api.md +8 -18
  8. package/dist/applicationinsights-analytics-js.d.ts +9 -104
  9. package/dist/applicationinsights-analytics-js.js +813 -252
  10. package/dist/applicationinsights-analytics-js.js.map +1 -1
  11. package/dist/applicationinsights-analytics-js.min.js +2 -2
  12. package/dist/applicationinsights-analytics-js.min.js.map +1 -1
  13. package/dist/applicationinsights-analytics-js.rollup.d.ts +9 -104
  14. package/dist-esm/JavaScriptSDK/AnalyticsPlugin.js +673 -0
  15. package/dist-esm/JavaScriptSDK/AnalyticsPlugin.js.map +1 -0
  16. package/dist-esm/JavaScriptSDK/Telemetry/PageViewManager.js +1 -1
  17. package/dist-esm/JavaScriptSDK/Telemetry/PageViewPerformanceManager.js +1 -1
  18. package/dist-esm/JavaScriptSDK/Telemetry/PageVisitTimeManager.js +1 -1
  19. package/dist-esm/JavaScriptSDK/Timing.js +39 -0
  20. package/dist-esm/JavaScriptSDK/Timing.js.map +1 -0
  21. package/dist-esm/JavaScriptSDK.Interfaces/ITelemetryConfig.js +1 -1
  22. package/dist-esm/applicationinsights-analytics-js.js +2 -2
  23. package/dist-esm/applicationinsights-analytics-js.js.map +1 -1
  24. package/package.json +5 -5
  25. package/src/JavaScriptSDK/{ApplicationInsights.ts → AnalyticsPlugin.ts} +401 -324
  26. package/src/JavaScriptSDK/Timing.ts +46 -0
  27. package/src/applicationinsights-analytics-js.ts +1 -1
  28. package/types/JavaScriptSDK/{ApplicationInsights.d.ts → AnalyticsPlugin.d.ts} +7 -11
  29. package/types/JavaScriptSDK/Timing.d.ts +18 -0
  30. package/types/applicationinsights-analytics-js.d.ts +1 -1
  31. package/dist-esm/JavaScriptSDK/ApplicationInsights.js +0 -606
  32. package/dist-esm/JavaScriptSDK/ApplicationInsights.js.map +0 -1
@@ -3,30 +3,34 @@
3
3
  * @copyright Microsoft 2018
4
4
  */
5
5
 
6
- import {
6
+ import {
7
7
  IConfig, PageViewPerformance, IAppInsights, PageView, RemoteDependencyData, Event as EventTelemetry, IEventTelemetry,
8
8
  TelemetryItemCreator, Metric, Exception, SeverityLevel, Trace, IDependencyTelemetry,
9
9
  IExceptionTelemetry, ITraceTelemetry, IMetricTelemetry, IAutoExceptionTelemetry,
10
10
  IPageViewTelemetryInternal, IPageViewTelemetry, IPageViewPerformanceTelemetry, IPageViewPerformanceTelemetryInternal,
11
- dateTimeUtilsDuration, IExceptionInternal, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent,
12
- strNotSpecified, isCrossOriginError, utlDisableStorage, dataSanitizeString
11
+ IExceptionInternal, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent,
12
+ strNotSpecified, isCrossOriginError, utlDisableStorage, utlEnableStorage, dataSanitizeString
13
13
  } from "@microsoft/applicationinsights-common";
14
14
 
15
15
  import {
16
16
  IPlugin, IConfiguration, IAppInsightsCore,
17
17
  BaseTelemetryPlugin, ITelemetryItem, IProcessTelemetryContext, ITelemetryPluginChain,
18
- IDiagnosticLogger, LoggingSeverity, _InternalMessageId, ICustomProperties,
19
- getWindow, getDocument, getHistory, getLocation, doPerf, objForEachKey,
20
- isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, ICookieMgr, safeGetCookieMgr
18
+ LoggingSeverity, _InternalMessageId, ICustomProperties,
19
+ getWindow, getDocument, getHistory, getLocation, objForEachKey,
20
+ isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, ICookieMgr, safeGetCookieMgr,
21
+ TelemetryInitializerFunction, hasHistory, strUndefined, objDefineAccessors, InstrumentFunc, IInstrumentCallDetails, eventOn, eventOff,
22
+ mergeEvtNamespace, createUniqueNamespace, ITelemetryInitializerHandler, throwError, isUndefined, hasWindow, createProcessTelemetryContext,
23
+ ITelemetryUnloadState
21
24
  } from "@microsoft/applicationinsights-core-js";
22
25
  import { PageViewManager, IAppInsightsInternal } from "./Telemetry/PageViewManager";
23
26
  import { PageVisitTimeManager } from "./Telemetry/PageVisitTimeManager";
24
27
  import { PageViewPerformanceManager } from "./Telemetry/PageViewPerformanceManager";
25
- import { ITelemetryConfig } from "../JavaScriptSDK.Interfaces/ITelemetryConfig";
26
28
  import dynamicProto from "@microsoft/dynamicproto-js";
27
29
 
28
30
  // For types only
29
31
  import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
32
+ import { Timing } from "./Timing";
33
+ import { IProcessTelemetryUnloadContext, IProcessTelemetryUpdateContext } from "@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext";
30
34
 
31
35
  "use strict";
32
36
 
@@ -53,55 +57,86 @@ function _getReason(error: any) {
53
57
  return error || "";
54
58
  }
55
59
 
56
- export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal {
57
- public static Version = "2.8.0-beta.2203-02"; // Not currently used anywhere
60
+ const MinMilliSeconds = 60000;
58
61
 
59
- public static getDefaultConfig(config?: IConfig): IConfig {
60
- if (!config) {
61
- config = {};
62
- }
62
+ function _configMilliseconds(value: number, defValue: number) {
63
+ value = value || defValue;
64
+ if (value < MinMilliSeconds) {
65
+ value = MinMilliSeconds;
66
+ }
63
67
 
64
- // set default values
65
- config.sessionRenewalMs = 30 * 60 * 1000;
66
- config.sessionExpirationMs = 24 * 60 * 60 * 1000;
67
- config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
68
- config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
69
- config.overridePageViewDuration = stringToBoolOrDefault(config.overridePageViewDuration);
70
- config.enableUnhandledPromiseRejectionTracking = stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
71
-
72
- if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
73
- config.samplingPercentage = 100;
74
- }
68
+ return value;
69
+ }
75
70
 
76
- config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
77
- config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
78
- config.enableAutoRouteTracking = stringToBoolOrDefault(config.enableAutoRouteTracking);
79
- config.namePrefix = config.namePrefix || "";
71
+ function _getDefaultConfig(config?: IConfig): IConfig {
72
+ if (!config) {
73
+ config = {};
74
+ }
80
75
 
81
- config.enableDebug = stringToBoolOrDefault(config.enableDebug);
82
- config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
83
- config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
76
+ // set default values
77
+ config.sessionRenewalMs = _configMilliseconds(config.sessionRenewalMs, 30 * 60 * 1000);
78
+ config.sessionExpirationMs = _configMilliseconds(config.sessionExpirationMs, 24 * 60 * 60 * 1000);
79
+ config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
80
+ config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
81
+ config.overridePageViewDuration = stringToBoolOrDefault(config.overridePageViewDuration);
82
+ config.enableUnhandledPromiseRejectionTracking = stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
84
83
 
85
- return config;
84
+ if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
85
+ config.samplingPercentage = 100;
86
86
  }
87
87
 
88
+ config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
89
+ config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
90
+ config.enableAutoRouteTracking = stringToBoolOrDefault(config.enableAutoRouteTracking);
91
+ config.namePrefix = config.namePrefix || "";
92
+
93
+ config.enableDebug = stringToBoolOrDefault(config.enableDebug);
94
+ config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
95
+ config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
96
+
97
+ return config;
98
+ }
99
+
100
+ function _updateStorageUsage(extConfig: IConfig) {
101
+ // Not resetting the storage usage as someone may have manually called utlDisableStorage, so this will only
102
+ // reset based if the configuration option is provided
103
+ if (!isUndefined(extConfig.isStorageUseDisabled)) {
104
+ if (extConfig.isStorageUseDisabled) {
105
+ utlDisableStorage();
106
+ } else {
107
+ utlEnableStorage();
108
+ }
109
+ }
110
+ }
111
+
112
+ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal {
113
+ public static Version = "2.8.0-beta.2203-05"; // Not currently used anywhere
114
+
115
+ public static getDefaultConfig = _getDefaultConfig;
116
+
88
117
  public identifier: string = AnalyticsPluginIdentifier; // do not change name or priority
89
118
  public priority: number = 180; // take from reserved priority range 100- 200
90
119
  public config: IConfig;
91
120
  public queue: Array<() => void>;
92
121
  public autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place
93
122
 
94
- protected _telemetryInitializers: Array<(envelope: ITelemetryItem) => boolean | void>; // Internal telemetry initializers.
95
- protected _pageViewManager: PageViewManager;
96
- protected _pageViewPerformanceManager: PageViewPerformanceManager;
97
- protected _pageVisitTimeManager: PageVisitTimeManager;
98
-
99
123
  constructor() {
100
124
  super();
101
125
  let _eventTracking: Timing;
102
126
  let _pageTracking: Timing;
103
- let _properties: PropertiesPlugin;
104
-
127
+ let _pageViewManager: PageViewManager;
128
+ let _pageViewPerformanceManager: PageViewPerformanceManager;
129
+ let _pageVisitTimeManager: PageVisitTimeManager;
130
+ let _preInitTelemetryInitializers: TelemetryInitializerFunction[];
131
+ let _isBrowserLinkTrackingEnabled: boolean;
132
+ let _browserLinkInitializerAdded: boolean;
133
+ let _enableAutoRouteTracking: boolean;
134
+ let _historyListenerAdded: boolean;
135
+ let _disableExceptionTracking: boolean;
136
+ let _autoExceptionInstrumented: boolean;
137
+ let _enableUnhandledPromiseRejectionTracking: boolean;
138
+ let _autoUnhandledPromiseInstrumented: boolean;
139
+
105
140
  // Counts number of trackAjax invocations.
106
141
  // By default we only monitor X ajax call per view to avoid too much load.
107
142
  // Default value is set in config.
@@ -111,48 +146,24 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
111
146
  // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
112
147
  let _prevUri: string; // Assigned in the constructor
113
148
  let _currUri: string;
114
-
149
+ let _evtNamespace: string | string[];
150
+
151
+ dynamicProto(AnalyticsPlugin, this, (_self, _base) => {
152
+ let _addHook = _base._addHook;
115
153
 
116
- dynamicProto(ApplicationInsights, this, (_self, _base) => {
117
- let location = getLocation(true);
118
- _prevUri = location && location.href || "";
154
+ _initDefaults();
119
155
 
120
156
  _self.getCookieMgr = () => {
121
157
  return safeGetCookieMgr(_self.core);
122
158
  };
123
159
 
124
160
  _self.processTelemetry = (env: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
125
- doPerf(_self.core, () => _self.identifier + ":processTelemetry", () => {
126
- let doNotSendItem = false;
127
- const telemetryInitializersCount = _self._telemetryInitializers.length;
128
- itemCtx = _self._getTelCtx(itemCtx);
129
- for (let i = 0; i < telemetryInitializersCount; ++i) {
130
- const telemetryInitializer = _self._telemetryInitializers[i];
131
- if (telemetryInitializer) {
132
- try {
133
- if (telemetryInitializer.apply(null, [env]) === false) {
134
- doNotSendItem = true;
135
- break;
136
- }
137
- } catch (e) {
138
- // log error but dont stop executing rest of the telemetry initializers
139
- // doNotSendItem = true;
140
- itemCtx.diagLog().throwInternal(
141
- LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e),
142
- { exception: dumpObj(e) }, true);
143
- }
144
- }
145
- }
146
-
147
- if (!doNotSendItem) {
148
- _self.processNext(env, itemCtx);
149
- }
150
- }, () => ({ item: env }), !((env as any).sync));
161
+ _self.processNext(env, itemCtx);
151
162
  };
152
163
 
153
164
  _self.trackEvent = (event: IEventTelemetry, customProperties?: ICustomProperties): void => {
154
165
  try {
155
- const telemetryItem = TelemetryItemCreator.create<IEventTelemetry>(
166
+ let telemetryItem = TelemetryItemCreator.create<IEventTelemetry>(
156
167
  event,
157
168
  EventTelemetry.dataType,
158
169
  EventTelemetry.envelopeType,
@@ -162,7 +173,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
162
173
 
163
174
  _self.core.track(telemetryItem);
164
175
  } catch (e) {
165
- _self.diagLog().throwInternal(LoggingSeverity.WARNING,
176
+ _throwInternal(LoggingSeverity.WARNING,
166
177
  _InternalMessageId.TrackTraceFailed,
167
178
  "trackTrace failed, trace will not be collected: " + getExceptionName(e),
168
179
  { exception: dumpObj(e) });
@@ -177,7 +188,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
177
188
  try {
178
189
  _eventTracking.start(name);
179
190
  } catch (e) {
180
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
191
+ _throwInternal(LoggingSeverity.CRITICAL,
181
192
  _InternalMessageId.StartTrackEventFailed,
182
193
  "startTrackEvent failed, event will not be collected: " + getExceptionName(e),
183
194
  { exception: dumpObj(e) });
@@ -194,7 +205,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
194
205
  try {
195
206
  _eventTracking.stop(name, undefined, properties); // Todo: Fix to pass measurements once type is updated
196
207
  } catch (e) {
197
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
208
+ _throwInternal(LoggingSeverity.CRITICAL,
198
209
  _InternalMessageId.StopTrackEventFailed,
199
210
  "stopTrackEvent failed, event will not be collected: " + getExceptionName(e),
200
211
  { exception: dumpObj(e) });
@@ -209,7 +220,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
209
220
  */
210
221
  _self.trackTrace = (trace: ITraceTelemetry, customProperties?: ICustomProperties): void => {
211
222
  try {
212
- const telemetryItem = TelemetryItemCreator.create<ITraceTelemetry>(
223
+ let telemetryItem = TelemetryItemCreator.create<ITraceTelemetry>(
213
224
  trace,
214
225
  Trace.dataType,
215
226
  Trace.envelopeType,
@@ -218,7 +229,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
218
229
 
219
230
  _self.core.track(telemetryItem);
220
231
  } catch (e) {
221
- _self.diagLog().throwInternal(LoggingSeverity.WARNING,
232
+ _throwInternal(LoggingSeverity.WARNING,
222
233
  _InternalMessageId.TrackTraceFailed,
223
234
  "trackTrace failed, trace will not be collected: " + getExceptionName(e),
224
235
  { exception: dumpObj(e) });
@@ -238,7 +249,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
238
249
  */
239
250
  _self.trackMetric = (metric: IMetricTelemetry, customProperties?: ICustomProperties): void => {
240
251
  try {
241
- const telemetryItem = TelemetryItemCreator.create<IMetricTelemetry>(
252
+ let telemetryItem = TelemetryItemCreator.create<IMetricTelemetry>(
242
253
  metric,
243
254
  Metric.dataType,
244
255
  Metric.envelopeType,
@@ -248,7 +259,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
248
259
 
249
260
  _self.core.track(telemetryItem);
250
261
  } catch (e) {
251
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
262
+ _throwInternal(LoggingSeverity.CRITICAL,
252
263
  _InternalMessageId.TrackMetricFailed,
253
264
  "trackMetric failed, metric will not be collected: " + getExceptionName(e),
254
265
  { exception: dumpObj(e) });
@@ -263,14 +274,14 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
263
274
  */
264
275
  _self.trackPageView = (pageView?: IPageViewTelemetry, customProperties?: ICustomProperties) => {
265
276
  try {
266
- const inPv = pageView || {};
267
- _self._pageViewManager.trackPageView(inPv, {...inPv.properties, ...inPv.measurements, ...customProperties});
277
+ let inPv = pageView || {};
278
+ _pageViewManager.trackPageView(inPv, {...inPv.properties, ...inPv.measurements, ...customProperties});
268
279
 
269
280
  if (_self.config.autoTrackPageVisitTime) {
270
- _self._pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
281
+ _pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
271
282
  }
272
283
  } catch (e) {
273
- _self.diagLog().throwInternal(
284
+ _throwInternal(
274
285
  LoggingSeverity.CRITICAL,
275
286
  _InternalMessageId.TrackPVFailed,
276
287
  "trackPageView failed, page view will not be collected: " + getExceptionName(e),
@@ -290,7 +301,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
290
301
  pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;
291
302
  }
292
303
 
293
- const telemetryItem = TelemetryItemCreator.create<IPageViewTelemetryInternal>(
304
+ let telemetryItem = TelemetryItemCreator.create<IPageViewTelemetryInternal>(
294
305
  pageView,
295
306
  PageView.dataType,
296
307
  PageView.envelopeType,
@@ -310,7 +321,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
310
321
  * @param properties
311
322
  */
312
323
  _self.sendPageViewPerformanceInternal = (pageViewPerformance: IPageViewPerformanceTelemetryInternal, properties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
313
- const telemetryItem = TelemetryItemCreator.create<IPageViewPerformanceTelemetryInternal>(
324
+ let telemetryItem = TelemetryItemCreator.create<IPageViewPerformanceTelemetryInternal>(
314
325
  pageViewPerformance,
315
326
  PageViewPerformance.dataType,
316
327
  PageViewPerformance.envelopeType,
@@ -327,11 +338,12 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
327
338
  * @param customProperties
328
339
  */
329
340
  _self.trackPageViewPerformance = (pageViewPerformance: IPageViewPerformanceTelemetry, customProperties?: ICustomProperties): void => {
341
+ let inPvp = pageViewPerformance || {};
330
342
  try {
331
- _self._pageViewPerformanceManager.populatePageViewPerformanceEvent(pageViewPerformance);
332
- _self.sendPageViewPerformanceInternal(pageViewPerformance, customProperties);
343
+ _pageViewPerformanceManager.populatePageViewPerformanceEvent(inPvp);
344
+ _self.sendPageViewPerformanceInternal(inPvp, customProperties);
333
345
  } catch (e) {
334
- _self.diagLog().throwInternal(
346
+ _throwInternal(
335
347
  LoggingSeverity.CRITICAL,
336
348
  _InternalMessageId.TrackPVFailed,
337
349
  "trackPageViewPerformance failed, page view will not be collected: " + getExceptionName(e),
@@ -354,7 +366,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
354
366
 
355
367
  _pageTracking.start(name);
356
368
  } catch (e) {
357
- _self.diagLog().throwInternal(
369
+ _throwInternal(
358
370
  LoggingSeverity.CRITICAL,
359
371
  _InternalMessageId.StartTrackFailed,
360
372
  "startTrackPage failed, page view may not be collected: " + getExceptionName(e),
@@ -385,10 +397,10 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
385
397
  _pageTracking.stop(name, url, properties, measurement);
386
398
 
387
399
  if (_self.config.autoTrackPageVisitTime) {
388
- _self._pageVisitTimeManager.trackPreviousPageVisit(name, url);
400
+ _pageVisitTimeManager.trackPreviousPageVisit(name, url);
389
401
  }
390
402
  } catch (e) {
391
- _self.diagLog().throwInternal(
403
+ _throwInternal(
392
404
  LoggingSeverity.CRITICAL,
393
405
  _InternalMessageId.StopTrackFailed,
394
406
  "stopTrackPage failed, page view will not be collected: " + getExceptionName(e),
@@ -404,7 +416,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
404
416
  */
405
417
  _self.sendExceptionInternal = (exception: IExceptionTelemetry, customProperties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
406
418
  const theError = exception.exception || exception.error || new Error(strNotSpecified);
407
- const exceptionPartB = new Exception(
419
+ let exceptionPartB = new Exception(
408
420
  _self.diagLog(),
409
421
  theError,
410
422
  exception.properties || customProperties,
@@ -413,7 +425,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
413
425
  exception.id
414
426
  ).toInterface();
415
427
 
416
- const telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IExceptionInternal>(
428
+ let telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IExceptionInternal>(
417
429
  exceptionPartB,
418
430
  Exception.dataType,
419
431
  Exception.envelopeType,
@@ -434,10 +446,14 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
434
446
  * @memberof ApplicationInsights
435
447
  */
436
448
  _self.trackException = (exception: IExceptionTelemetry, customProperties?: ICustomProperties): void => {
449
+ if (exception && !exception.exception && (exception as any).error) {
450
+ exception.exception = (exception as any).error;
451
+ }
452
+
437
453
  try {
438
454
  _self.sendExceptionInternal(exception, customProperties);
439
455
  } catch (e) {
440
- _self.diagLog().throwInternal(
456
+ _throwInternal(
441
457
  LoggingSeverity.CRITICAL,
442
458
  _InternalMessageId.TrackExceptionFailed,
443
459
  "trackException failed, exception will not be collected: " + getExceptionName(e),
@@ -464,7 +480,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
464
480
  const url = (exception && exception.url) || (getDocument() || {} as any).URL;
465
481
  // If no error source is provided assume the default window.onerror handler
466
482
  const errorSrc = exception.errorSrc || "window.onerror@" + url + ":" + (exception.lineNumber || 0) + ":" + (exception.columnNumber || 0);
467
- const properties = {
483
+ let properties = {
468
484
  errorSrc,
469
485
  url,
470
486
  lineNumber: exception.lineNumber || 0,
@@ -492,7 +508,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
492
508
  } catch (e) {
493
509
  const errorString = error ? (error.name + ", " + error.message) : "null";
494
510
 
495
- _self.diagLog().throwInternal(
511
+ _throwInternal(
496
512
  LoggingSeverity.CRITICAL,
497
513
  _InternalMessageId.ExceptionWhileLoggingError,
498
514
  "_onError threw exception while logging error, error will not be collected: "
@@ -502,8 +518,18 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
502
518
  }
503
519
  };
504
520
 
505
- _self.addTelemetryInitializer = (telemetryInitializer: (item: ITelemetryItem) => boolean | void) => {
506
- _self._telemetryInitializers.push(telemetryInitializer);
521
+ _self.addTelemetryInitializer = (telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler | void => {
522
+ if (_self.core) {
523
+ // Just add to the core
524
+ return _self.core.addTelemetryInitializer(telemetryInitializer);
525
+ }
526
+
527
+ // Handle "pre-initialization" telemetry initializers (for backward compatibility)
528
+ if (!_preInitTelemetryInitializers) {
529
+ _preInitTelemetryInitializers = [];
530
+ }
531
+
532
+ _preInitTelemetryInitializers.push(telemetryInitializer);
507
533
  };
508
534
 
509
535
  _self.initialize = (config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) => {
@@ -512,197 +538,103 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
512
538
  }
513
539
 
514
540
  if (isNullOrUndefined(core)) {
515
- throw Error("Error initializing");
541
+ throwError("Error initializing");
516
542
  }
517
543
 
518
544
  _base.initialize(config, core, extensions, pluginChain);
519
- _self.setInitialized(false); // resetting the initialized state, just in case the following fails
520
- let ctx = _self._getTelCtx();
521
- let identifier = _self.identifier;
522
-
523
- _self.config = ctx.getExtCfg<IConfig>(identifier);
524
-
525
- // load default values if specified
526
- const defaults: IConfig = ApplicationInsights.getDefaultConfig(config);
527
- if (defaults !== undefined) {
528
- objForEachKey(defaults, (field, value) => {
529
- // for each unspecified field, set the default value
530
- _self.config[field] = ctx.getConfig(identifier, field, value);
531
- if (_self.config[field] === undefined) {
532
- _self.config[field] = value;
545
+ try {
546
+ _evtNamespace = mergeEvtNamespace(createUniqueNamespace("AnalyticsPlugin"), core.evtNamespace && core.evtNamespace());
547
+ if (_preInitTelemetryInitializers) {
548
+ arrForEach(_preInitTelemetryInitializers, (initializer) => {
549
+ core.addTelemetryInitializer(initializer);
550
+ });
551
+
552
+ _preInitTelemetryInitializers = null;
553
+ }
554
+
555
+ let extConfig = _populateDefaults(config);
556
+ _updateStorageUsage(extConfig);
557
+
558
+ _pageViewPerformanceManager = new PageViewPerformanceManager(_self.core);
559
+ _pageViewManager = new PageViewManager(this, extConfig.overridePageViewDuration, _self.core, _pageViewPerformanceManager);
560
+ _pageVisitTimeManager = new PageVisitTimeManager(_self.diagLog(), (pageName, pageUrl, pageVisitTime) => trackPageVisitTime(pageName, pageUrl, pageVisitTime))
561
+
562
+ _updateBrowserLinkTracking(extConfig, config);
563
+
564
+ _eventTracking = new Timing(_self.diagLog(), "trackEvent");
565
+ _eventTracking.action =
566
+ (name?: string, url?: string, duration?: number, properties?: { [key: string]: string }) => {
567
+ if (!properties) {
568
+ properties = {};
569
+ }
570
+
571
+ properties[durationProperty] = duration.toString();
572
+ _self.trackEvent({ name, properties } as IEventTelemetry);
533
573
  }
534
- });
535
- }
536
-
537
- // Todo: move this out of static state
538
- if (_self.config.isStorageUseDisabled) {
539
- utlDisableStorage();
540
- }
541
-
542
- const configGetters: ITelemetryConfig = {
543
- instrumentationKey: () => config.instrumentationKey,
544
- accountId: () => _self.config.accountId || config.accountId,
545
- sessionRenewalMs: () => _self.config.sessionRenewalMs || config.sessionRenewalMs,
546
- sessionExpirationMs: () => _self.config.sessionExpirationMs || config.sessionExpirationMs,
547
- sampleRate: () => _self.config.samplingPercentage || config.samplingPercentage,
548
- sdkExtension: () => _self.config.sdkExtension || config.sdkExtension,
549
- isBrowserLinkTrackingEnabled: () => _self.config.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled,
550
- appId: () => _self.config.appId || config.appId
551
- }
552
-
553
- _self._pageViewPerformanceManager = new PageViewPerformanceManager(_self.core);
554
- _self._pageViewManager = new PageViewManager(this, _self.config.overridePageViewDuration, _self.core, _self._pageViewPerformanceManager);
555
- _self._pageVisitTimeManager = new PageVisitTimeManager(_self.diagLog(), (pageName, pageUrl, pageVisitTime) => trackPageVisitTime(pageName, pageUrl, pageVisitTime))
556
-
557
- _self._telemetryInitializers = _self._telemetryInitializers || [];
558
- _addDefaultTelemetryInitializers(configGetters);
559
-
560
- _eventTracking = new Timing(_self.diagLog(), "trackEvent");
561
- _eventTracking.action =
562
- (name?: string, url?: string, duration?: number, properties?: { [key: string]: string }) => {
563
- if (!properties) {
574
+
575
+ // initialize page view timing
576
+ _pageTracking = new Timing(_self.diagLog(), "trackPageView");
577
+ _pageTracking.action = (name, url, duration, properties, measurements) => {
578
+
579
+ // duration must be a custom property in order for the collector to extract it
580
+ if (isNullOrUndefined(properties)) {
564
581
  properties = {};
565
582
  }
566
-
567
583
  properties[durationProperty] = duration.toString();
568
- _self.trackEvent({ name, properties } as IEventTelemetry);
569
- }
570
-
571
- // initialize page view timing
572
- _pageTracking = new Timing(_self.diagLog(), "trackPageView");
573
- _pageTracking.action = (name, url, duration, properties, measurements) => {
574
-
575
- // duration must be a custom property in order for the collector to extract it
576
- if (isNullOrUndefined(properties)) {
577
- properties = {};
584
+
585
+ let pageViewItem: IPageViewTelemetry = {
586
+ name,
587
+ uri: url,
588
+ properties,
589
+ measurements
590
+ };
591
+
592
+ _self.sendPageViewInternal(pageViewItem, properties);
578
593
  }
579
- properties[durationProperty] = duration.toString();
580
-
581
- const pageViewItem: IPageViewTelemetry = {
582
- name,
583
- uri: url,
584
- properties,
585
- measurements
586
- };
587
-
588
- _self.sendPageViewInternal(pageViewItem, properties);
589
- }
590
-
591
- let _window = getWindow();
592
- let _history = getHistory();
593
- let _location = getLocation(true);
594
-
595
- const instance: IAppInsights = this;
596
- if (_self.config.disableExceptionTracking === false &&
597
- !_self.config.autoExceptionInstrumented && _window) {
598
- // We want to enable exception auto collection and it has not been done so yet
599
- const onerror = "onerror";
600
- const originalOnError = _window[onerror];
601
- _window.onerror = (message, url, lineNumber, columnNumber, error) => {
602
- const evt = _window[strEvent];
603
- const handled = originalOnError && (originalOnError(message, url, lineNumber, columnNumber, error) as any);
604
- if (handled !== true) { // handled could be typeof function
605
- instance._onerror(Exception.CreateAutoException(
606
- message,
607
- url,
608
- lineNumber,
609
- columnNumber,
610
- error,
611
- evt
612
- ));
613
- }
614
-
615
- return handled;
594
+
595
+ if (hasWindow()) {
596
+ _updateExceptionTracking(extConfig);
597
+ _updateLocationChange(extConfig);
616
598
  }
617
- _self.config.autoExceptionInstrumented = true;
599
+
600
+ } catch (e) {
601
+ // resetting the initialized state because of failure
602
+ _self.setInitialized(false);
603
+ throw e;
618
604
  }
605
+ };
619
606
 
620
- if (_self.config.disableExceptionTracking === false &&
621
- _self.config.enableUnhandledPromiseRejectionTracking === true &&
622
- !_self.config.autoUnhandledPromiseInstrumented && _window) {
623
- // We want to enable exception auto collection and it has not been done so yet
624
- const onunhandledrejection = "onunhandledrejection";
625
- const originalOnUnhandledRejection = _window[onunhandledrejection];
626
- _window[onunhandledrejection] = (error: PromiseRejectionEvent) => {
627
- const evt = _window[strEvent];
628
- const handled = originalOnUnhandledRejection && (originalOnUnhandledRejection.call(_window, error) as any);
629
- if (handled !== true) { // handled could be typeof function
630
- instance._onerror(Exception.CreateAutoException(
631
- _getReason(error),
632
- _location ? _location.href : "",
633
- 0,
634
- 0,
635
- error,
636
- evt
637
- ));
638
- }
607
+ _self._doTeardown = (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => {
608
+ // Just register to remove all events associated with this namespace
609
+ eventOff(window, null, null, _evtNamespace);
610
+ _initDefaults();
611
+ };
612
+
613
+ function _populateDefaults(config: IConfiguration) {
614
+ let ctx = createProcessTelemetryContext(null, config, _self.core);
615
+ let identifier = _self.identifier;
639
616
 
640
- return handled;
641
- }
642
- _self.config.autoUnhandledPromiseInstrumented = true;
643
- }
617
+ // load default values if specified
618
+ const defaults: IConfig = _getDefaultConfig(config);
619
+ let extConfig = _self.config = ctx.getExtCfg<IConfig>(identifier);
644
620
 
645
- /**
646
- * Create a custom "locationchange" event which is triggered each time the history object is changed
647
- */
648
- if (_self.config.enableAutoRouteTracking === true
649
- && _history && isFunction(_history.pushState) && isFunction(_history.replaceState)
650
- && _window
651
- && typeof Event !== "undefined") {
652
- const _self = this;
653
- // Find the properties plugin
654
- arrForEach(extensions, extension => {
655
- if (extension.identifier === PropertiesPluginIdentifier) {
656
- _properties = extension as PropertiesPlugin;
621
+ if (defaults !== undefined) {
622
+ objForEachKey(defaults, (field, value) => {
623
+ // for each unspecified field, set the default value
624
+ extConfig[field] = ctx.getConfig(identifier, field, value);
625
+ if (extConfig[field] === undefined) {
626
+ extConfig = value;
657
627
  }
658
628
  });
659
-
660
- _history.pushState = ( f => function pushState() {
661
- const ret = f.apply(this, arguments);
662
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "pushState"));
663
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "locationchange"));
664
- return ret;
665
- })(_history.pushState);
666
-
667
- _history.replaceState = ( f => function replaceState(){
668
- const ret = f.apply(this, arguments);
669
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "replaceState"));
670
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "locationchange"));
671
- return ret;
672
- })(_history.replaceState);
673
-
674
- if (_window.addEventListener) {
675
- _window.addEventListener(_self.config.namePrefix + "popstate",()=>{
676
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "locationchange"));
677
- });
678
-
679
- _window.addEventListener(_self.config.namePrefix + "locationchange", () => {
680
- if (_properties && _properties.context && _properties.context.telemetryTrace) {
681
- _properties.context.telemetryTrace.traceID = generateW3CId();
682
- let traceLocationName = "_unknown_";
683
- if (_location && _location.pathname) {
684
- traceLocationName = _location.pathname + (_location.hash || "");
685
- }
686
-
687
- // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it
688
- _properties.context.telemetryTrace.name = dataSanitizeString(_self.diagLog(), traceLocationName);
689
- }
690
- if (_currUri) {
691
- _prevUri = _currUri;
692
- _currUri = _location && _location.href || "";
693
- } else {
694
- _currUri = _location && _location.href || "";
695
- }
696
- setTimeout(((uri: string) => {
697
- // todo: override start time so that it is not affected by autoRoutePVDelay
698
- _self.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
699
- }).bind(this, _prevUri), _self.autoRoutePVDelay);
700
- });
701
- }
702
629
  }
703
630
 
704
- _self.setInitialized(true);
705
- };
631
+ return extConfig;
632
+ }
633
+
634
+ function _updateBrowserLinkTracking(extConfig: IConfig, config: IConfig) {
635
+ _isBrowserLinkTrackingEnabled = extConfig.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled;
636
+ _addDefaultTelemetryInitializers();
637
+ }
706
638
 
707
639
  /**
708
640
  * Log a page visit time
@@ -710,7 +642,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
710
642
  * @param pageVisitDuration Duration of visit to the page in milleseconds
711
643
  */
712
644
  function trackPageVisitTime(pageName: string, pageUrl: string, pageVisitTime: number) {
713
- const properties = { PageName: pageName, PageUrl: pageUrl };
645
+ let properties = { PageName: pageName, PageUrl: pageUrl };
714
646
  _self.trackMetric({
715
647
  name: "PageVisitTime",
716
648
  average: pageVisitTime,
@@ -720,12 +652,12 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
720
652
  }, properties);
721
653
  }
722
654
 
723
- function _addDefaultTelemetryInitializers(configGetters: ITelemetryConfig) {
724
- if (!configGetters.isBrowserLinkTrackingEnabled()) {
655
+ function _addDefaultTelemetryInitializers() {
656
+ if (!_browserLinkInitializerAdded && _isBrowserLinkTrackingEnabled) {
725
657
  const browserLinkPaths = ["/browserLinkSignalR/", "/__browserLink/"];
726
658
  const dropBrowserLinkRequests = (envelope: ITelemetryItem) => {
727
- if (envelope.baseType === RemoteDependencyData.dataType) {
728
- const remoteData = envelope.baseData as IDependencyTelemetry;
659
+ if (_isBrowserLinkTrackingEnabled && envelope.baseType === RemoteDependencyData.dataType) {
660
+ let remoteData = envelope.baseData as IDependencyTelemetry;
729
661
  if (remoteData) {
730
662
  for (let i = 0; i < browserLinkPaths.length; i++) {
731
663
  if (remoteData.target && remoteData.target.indexOf(browserLinkPaths[i]) >= 0) {
@@ -738,16 +670,13 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
738
670
  return true;
739
671
  }
740
672
 
741
- _addTelemetryInitializer(dropBrowserLinkRequests)
673
+ _self.addTelemetryInitializer(dropBrowserLinkRequests);
674
+ _browserLinkInitializerAdded = true;
742
675
  }
743
676
  }
744
677
 
745
- function _addTelemetryInitializer(telemetryInitializer: (envelope: ITelemetryItem) => boolean | void) {
746
- _self._telemetryInitializers.push(telemetryInitializer);
747
- }
748
-
749
678
  function _sendCORSException(exception: IAutoExceptionTelemetry, properties?: ICustomProperties) {
750
- const telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IAutoExceptionTelemetry>(
679
+ let telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IAutoExceptionTelemetry>(
751
680
  exception,
752
681
  Exception.dataType,
753
682
  Exception.envelopeType,
@@ -757,6 +686,196 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
757
686
 
758
687
  _self.core.track(telemetryItem);
759
688
  }
689
+
690
+ function _updateExceptionTracking(extConfig: IConfig) {
691
+ let _window = getWindow();
692
+ let locn = getLocation(true);
693
+
694
+ _disableExceptionTracking = extConfig.disableExceptionTracking;
695
+
696
+ if (!_disableExceptionTracking && !_autoExceptionInstrumented && !extConfig.autoExceptionInstrumented) {
697
+ // We want to enable exception auto collection and it has not been done so yet
698
+ _addHook(InstrumentFunc(_window, "onerror", {
699
+ ns: _evtNamespace,
700
+ rsp: (callDetails: IInstrumentCallDetails, message, url, lineNumber, columnNumber, error) => {
701
+ if (!_disableExceptionTracking && callDetails.rslt !== true) {
702
+ _self._onerror(Exception.CreateAutoException(
703
+ message,
704
+ url,
705
+ lineNumber,
706
+ columnNumber,
707
+ error,
708
+ callDetails.evt
709
+ ));
710
+ }
711
+ }
712
+ }));
713
+
714
+ _autoExceptionInstrumented = true;
715
+ }
716
+
717
+ _addUnhandledPromiseRejectionTracking(extConfig, _window, locn);
718
+ }
719
+
720
+ function _updateLocationChange(extConfig: IConfig) {
721
+ let win = getWindow();
722
+ let locn = getLocation(true);
723
+
724
+ _enableAutoRouteTracking = extConfig.enableAutoRouteTracking === true;
725
+
726
+ /**
727
+ * Create a custom "locationchange" event which is triggered each time the history object is changed
728
+ */
729
+ if (win && _enableAutoRouteTracking && hasHistory()) {
730
+ let _history = getHistory();
731
+
732
+ if (isFunction(_history.pushState) && isFunction(_history.replaceState) && typeof Event !== strUndefined) {
733
+ _addHistoryListener(extConfig, win, _history, locn);
734
+ }
735
+ }
736
+ }
737
+
738
+ /**
739
+ * Create a custom "locationchange" event which is triggered each time the history object is changed
740
+ */
741
+ function _addHistoryListener(extConfig: IConfig, win: Window, history: History, locn: Location) {
742
+
743
+ function _popstateHandler() {
744
+ if (_enableAutoRouteTracking) {
745
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
746
+ }
747
+ }
748
+
749
+ function _locationChangeHandler() {
750
+ // We always track the changes (if the handler is installed) to handle the feature being disabled between location changes
751
+ if (_currUri) {
752
+ _prevUri = _currUri;
753
+ _currUri = locn && locn.href || "";
754
+ } else {
755
+ _currUri = locn && locn.href || "";
756
+ }
757
+
758
+ if (_enableAutoRouteTracking) {
759
+ let properties = _self.core.getPlugin<PropertiesPlugin>(PropertiesPluginIdentifier);
760
+
761
+ if (properties) {
762
+ let context = properties.plugin.context;
763
+ if (context && context.telemetryTrace) {
764
+ context.telemetryTrace.traceID = generateW3CId();
765
+ let traceLocationName = "_unknown_";
766
+ if (locn && locn.pathname) {
767
+ traceLocationName = locn.pathname + (locn.hash || "");
768
+ }
769
+
770
+ // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it
771
+ context.telemetryTrace.name = dataSanitizeString(_self.diagLog(), traceLocationName);
772
+ }
773
+ }
774
+
775
+ setTimeout(((uri: string) => {
776
+ // todo: override start time so that it is not affected by autoRoutePVDelay
777
+ _self.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
778
+ }).bind(this, _prevUri), _self.autoRoutePVDelay);
779
+ }
780
+ }
781
+
782
+ if (!_historyListenerAdded) {
783
+ _addHook(InstrumentFunc(history, "pushState", {
784
+ ns: _evtNamespace,
785
+ rsp: () => {
786
+ if (_enableAutoRouteTracking) {
787
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "pushState"));
788
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
789
+ }
790
+ }
791
+ }));
792
+
793
+ _addHook(InstrumentFunc(history, "replaceState", {
794
+ ns: _evtNamespace,
795
+ rsp: () => {
796
+ if (_enableAutoRouteTracking) {
797
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "replaceState"));
798
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
799
+ }
800
+ }
801
+ }));
802
+
803
+ eventOn(win, extConfig.namePrefix + "popstate", _popstateHandler, _evtNamespace);
804
+ eventOn(win, extConfig.namePrefix + "locationchange", _locationChangeHandler, _evtNamespace);
805
+
806
+ _historyListenerAdded = true;
807
+ }
808
+ }
809
+
810
+ function _addUnhandledPromiseRejectionTracking(extConfig: IConfig, _window: Window, _location: Location) {
811
+ _enableUnhandledPromiseRejectionTracking = extConfig.enableUnhandledPromiseRejectionTracking === true;
812
+
813
+ if (_enableUnhandledPromiseRejectionTracking && !_autoUnhandledPromiseInstrumented) {
814
+ // We want to enable exception auto collection and it has not been done so yet
815
+ _addHook(InstrumentFunc(_window, "onunhandledrejection", {
816
+ ns: _evtNamespace,
817
+ rsp: (callDetails: IInstrumentCallDetails, error: PromiseRejectionEvent) => {
818
+ if (_enableUnhandledPromiseRejectionTracking && callDetails.rslt !== true) { // handled could be typeof function
819
+ _self._onerror(Exception.CreateAutoException(
820
+ _getReason(error),
821
+ _location ? _location.href : "",
822
+ 0,
823
+ 0,
824
+ error,
825
+ callDetails.evt
826
+ ));
827
+ }
828
+ }
829
+ }));
830
+
831
+ _autoUnhandledPromiseInstrumented = true;
832
+ extConfig.autoUnhandledPromiseInstrumented = _autoUnhandledPromiseInstrumented;
833
+ }
834
+ }
835
+
836
+ /**
837
+ * This method will throw exceptions in debug mode or attempt to log the error as a console warning.
838
+ * @param severity {LoggingSeverity} - The severity of the log message
839
+ * @param message {_InternalLogMessage} - The log message.
840
+ */
841
+ function _throwInternal(severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct?: boolean): void {
842
+ _self.diagLog().throwInternal(severity, msgId, msg, properties, isUserAct);
843
+ }
844
+
845
+ function _initDefaults() {
846
+ _eventTracking = null;
847
+ _pageTracking = null;
848
+ _pageViewManager = null;
849
+ _pageViewPerformanceManager = null;
850
+ _pageVisitTimeManager = null;
851
+ _preInitTelemetryInitializers = null;
852
+ _isBrowserLinkTrackingEnabled = false;
853
+ _browserLinkInitializerAdded = false;
854
+ _enableAutoRouteTracking = false;
855
+ _historyListenerAdded = false;
856
+ _disableExceptionTracking = false;
857
+ _autoExceptionInstrumented = false;
858
+ _enableUnhandledPromiseRejectionTracking = false;
859
+ _autoUnhandledPromiseInstrumented = false;
860
+
861
+ // Counts number of trackAjax invocations.
862
+ // By default we only monitor X ajax call per view to avoid too much load.
863
+ // Default value is set in config.
864
+ // This counter keeps increasing even after the limit is reached.
865
+ _trackAjaxAttempts = 0;
866
+
867
+ // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
868
+ let location = getLocation(true);
869
+ _prevUri = location && location.href || "";
870
+ _currUri = null;
871
+ _evtNamespace = null;
872
+ }
873
+
874
+ // For backward compatibility
875
+ objDefineAccessors(_self, "_pageViewManager", () => _pageViewManager);
876
+ objDefineAccessors(_self, "_pageViewPerformanceManager", () => _pageViewPerformanceManager);
877
+ objDefineAccessors(_self, "_pageVisitTimeManager", () => _pageVisitTimeManager);
878
+ objDefineAccessors(_self, "_evtNamespace", () => "." + _evtNamespace);
760
879
  });
761
880
  }
762
881
 
@@ -867,7 +986,6 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
867
986
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
868
987
  }
869
988
 
870
-
871
989
  /**
872
990
  * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
873
991
  * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
@@ -912,52 +1030,11 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
912
1030
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
913
1031
  }
914
1032
 
915
- public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void) {
1033
+ public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void): ITelemetryInitializerHandler | void {
916
1034
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
917
1035
  }
918
1036
 
919
1037
  public initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) {
920
1038
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
921
1039
  }
922
- }
923
-
924
- /**
925
- * Used to record timed events and page views.
926
- */
927
- class Timing {
928
-
929
- public action: (name?: string, url?: string, duration?: number, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => void;
930
- public start: (name: string) => void;
931
- public stop: (name: string, url: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => void;
932
-
933
- constructor(logger: IDiagnosticLogger, name: string) {
934
- let _self = this;
935
- let _events: { [key: string]: number; } = {}
936
-
937
- _self.start = (name: string) => {
938
- if (typeof _events[name] !== "undefined") {
939
- logger.throwInternal(
940
- LoggingSeverity.WARNING, _InternalMessageId.StartCalledMoreThanOnce, "start was called more than once for this event without calling stop.",
941
- { name, key: name }, true);
942
- }
943
-
944
- _events[name] = +new Date;
945
- }
946
-
947
- _self.stop = (name: string, url: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => {
948
- const start = _events[name];
949
- if (isNaN(start)) {
950
- logger.throwInternal(
951
- LoggingSeverity.WARNING, _InternalMessageId.StopCalledWithoutStart, "stop was called without a corresponding start.",
952
- { name, key: name }, true);
953
- } else {
954
- const end = +new Date;
955
- const duration = dateTimeUtilsDuration(start, end);
956
- _self.action(name, url, duration, properties, measurements);
957
- }
958
-
959
- delete _events[name];
960
- _events[name] = undefined;
961
- }
962
- }
963
1040
  }