@microsoft/applicationinsights-analytics-js 2.7.5-nightly.2204-03 → 2.7.6

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