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

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 +668 -1624
  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 +668 -1624
  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 +7 -7
  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
@@ -0,0 +1,606 @@
1
+ /*
2
+ * Application Insights JavaScript SDK - Web Analytics, 2.7.5-nightly.2204-23
3
+ * Copyright (c) Microsoft and contributors. All rights reserved.
4
+ */
5
+ /**
6
+ * ApplicationInsights.ts
7
+ * @copyright Microsoft 2018
8
+ */
9
+ import { __assignFn as __assign, __extendsFn as __extends } from "@microsoft/applicationinsights-shims";
10
+ import { PageViewPerformance, PageView, RemoteDependencyData, Event as EventTelemetry, TelemetryItemCreator, Metric, Exception, SeverityLevel, Trace, dateTimeUtilsDuration, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent, strNotSpecified, isCrossOriginError, utlDisableStorage, dataSanitizeString } from "@microsoft/applicationinsights-common";
11
+ import { BaseTelemetryPlugin, LoggingSeverity, _InternalMessageId, getWindow, getDocument, getHistory, getLocation, doPerf, objForEachKey, isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, safeGetCookieMgr } from "@microsoft/applicationinsights-core-js";
12
+ import { PageViewManager } from "./Telemetry/PageViewManager";
13
+ import { PageVisitTimeManager } from "./Telemetry/PageVisitTimeManager";
14
+ import { PageViewPerformanceManager } from "./Telemetry/PageViewPerformanceManager";
15
+ import dynamicProto from "@microsoft/dynamicproto-js";
16
+ "use strict";
17
+ var durationProperty = "duration";
18
+ var strEvent = "event";
19
+ function _dispatchEvent(target, evnt) {
20
+ if (target && target.dispatchEvent && evnt) {
21
+ target.dispatchEvent(evnt);
22
+ }
23
+ }
24
+ function _getReason(error) {
25
+ if (error && error.reason) {
26
+ var reason = error.reason;
27
+ if (!isString(reason) && isFunction(reason.toString)) {
28
+ return reason.toString();
29
+ }
30
+ return dumpObj(reason);
31
+ }
32
+ // Pass the original object down which will eventually get evaluated for any message or description
33
+ return error || "";
34
+ }
35
+ var ApplicationInsights = /** @class */ (function (_super) {
36
+ __extends(ApplicationInsights, _super);
37
+ function ApplicationInsights() {
38
+ var _this = _super.call(this) || this;
39
+ _this.identifier = AnalyticsPluginIdentifier; // do not change name or priority
40
+ _this.priority = 180; // take from reserved priority range 100- 200
41
+ _this.autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place
42
+ var _eventTracking;
43
+ var _pageTracking;
44
+ var _properties;
45
+ // Counts number of trackAjax invocations.
46
+ // By default we only monitor X ajax call per view to avoid too much load.
47
+ // Default value is set in config.
48
+ // This counter keeps increasing even after the limit is reached.
49
+ var _trackAjaxAttempts = 0;
50
+ // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
51
+ var _prevUri; // Assigned in the constructor
52
+ var _currUri;
53
+ dynamicProto(ApplicationInsights, _this, function (_self, _base) {
54
+ var location = getLocation(true);
55
+ _prevUri = location && location.href || "";
56
+ _self.getCookieMgr = function () {
57
+ return safeGetCookieMgr(_self.core);
58
+ };
59
+ _self.processTelemetry = function (env, itemCtx) {
60
+ doPerf(_self.core, function () { return _self.identifier + ":processTelemetry"; }, function () {
61
+ var doNotSendItem = false;
62
+ var telemetryInitializersCount = _self._telemetryInitializers.length;
63
+ itemCtx = _self._getTelCtx(itemCtx);
64
+ for (var i = 0; i < telemetryInitializersCount; ++i) {
65
+ var telemetryInitializer = _self._telemetryInitializers[i];
66
+ if (telemetryInitializer) {
67
+ try {
68
+ if (telemetryInitializer.apply(null, [env]) === false) {
69
+ doNotSendItem = true;
70
+ break;
71
+ }
72
+ }
73
+ catch (e) {
74
+ // log error but dont stop executing rest of the telemetry initializers
75
+ // doNotSendItem = true;
76
+ itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e), { exception: dumpObj(e) }, true);
77
+ }
78
+ }
79
+ }
80
+ if (!doNotSendItem) {
81
+ _self.processNext(env, itemCtx);
82
+ }
83
+ }, function () { return ({ item: env }); }, !(env.sync));
84
+ };
85
+ _self.trackEvent = function (event, customProperties) {
86
+ try {
87
+ var telemetryItem = TelemetryItemCreator.create(event, EventTelemetry.dataType, EventTelemetry.envelopeType, _self.diagLog(), customProperties);
88
+ _self.core.track(telemetryItem);
89
+ }
90
+ catch (e) {
91
+ _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TrackTraceFailed, "trackTrace failed, trace will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
92
+ }
93
+ };
94
+ /**
95
+ * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.
96
+ * @param name A string that identifies this event uniquely within the document.
97
+ */
98
+ _self.startTrackEvent = function (name) {
99
+ try {
100
+ _eventTracking.start(name);
101
+ }
102
+ catch (e) {
103
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StartTrackEventFailed, "startTrackEvent failed, event will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
104
+ }
105
+ };
106
+ /**
107
+ * Log an extended event that you started timing with `startTrackEvent`.
108
+ * @param name The string you used to identify this event in `startTrackEvent`.
109
+ * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
110
+ * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
111
+ */
112
+ _self.stopTrackEvent = function (name, properties, measurements) {
113
+ try {
114
+ _eventTracking.stop(name, undefined, properties); // Todo: Fix to pass measurements once type is updated
115
+ }
116
+ catch (e) {
117
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StopTrackEventFailed, "stopTrackEvent failed, event will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
118
+ }
119
+ };
120
+ /**
121
+ * @description Log a diagnostic message
122
+ * @param {ITraceTelemetry} trace
123
+ * @param ICustomProperties.
124
+ * @memberof ApplicationInsights
125
+ */
126
+ _self.trackTrace = function (trace, customProperties) {
127
+ try {
128
+ var telemetryItem = TelemetryItemCreator.create(trace, Trace.dataType, Trace.envelopeType, _self.diagLog(), customProperties);
129
+ _self.core.track(telemetryItem);
130
+ }
131
+ catch (e) {
132
+ _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TrackTraceFailed, "trackTrace failed, trace will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
133
+ }
134
+ };
135
+ /**
136
+ * @description Log a numeric value that is not associated with a specific event. Typically
137
+ * used to send regular reports of performance indicators. To send single measurement, just
138
+ * use the name and average fields of {@link IMetricTelemetry}. If you take measurements
139
+ * frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements
140
+ * and sending the resulting average at intervals
141
+ * @param {IMetricTelemetry} metric input object argument. Only name and average are mandatory.
142
+ * @param {{[key: string]: any}} customProperties additional data used to filter metrics in the
143
+ * portal. Defaults to empty.
144
+ * @memberof ApplicationInsights
145
+ */
146
+ _self.trackMetric = function (metric, customProperties) {
147
+ try {
148
+ var telemetryItem = TelemetryItemCreator.create(metric, Metric.dataType, Metric.envelopeType, _self.diagLog(), customProperties);
149
+ _self.core.track(telemetryItem);
150
+ }
151
+ catch (e) {
152
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackMetricFailed, "trackMetric failed, metric will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
153
+ }
154
+ };
155
+ /**
156
+ * Logs that a page or other item was viewed.
157
+ * @param IPageViewTelemetry The string you used as the name in startTrackPage. Defaults to the document title.
158
+ * @param customProperties Additional data used to filter events and metrics. Defaults to empty.
159
+ * If a user wants to provide duration for pageLoad, it'll have to be in pageView.properties.duration
160
+ */
161
+ _self.trackPageView = function (pageView, customProperties) {
162
+ try {
163
+ var inPv = pageView || {};
164
+ _self._pageViewManager.trackPageView(inPv, __assign(__assign(__assign({}, inPv.properties), inPv.measurements), customProperties));
165
+ if (_self.config.autoTrackPageVisitTime) {
166
+ _self._pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
167
+ }
168
+ }
169
+ catch (e) {
170
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackPVFailed, "trackPageView failed, page view will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
171
+ }
172
+ };
173
+ /**
174
+ * Create a page view telemetry item and send it to the SDK pipeline through the core.track API
175
+ * @param pageView Page view item to be sent
176
+ * @param properties Custom properties (Part C) that a user can add to the telemetry item
177
+ * @param systemProperties System level properties (Part A) that a user can add to the telemetry item
178
+ */
179
+ _self.sendPageViewInternal = function (pageView, properties, systemProperties) {
180
+ var doc = getDocument();
181
+ if (doc) {
182
+ pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;
183
+ }
184
+ var telemetryItem = TelemetryItemCreator.create(pageView, PageView.dataType, PageView.envelopeType, _self.diagLog(), properties, systemProperties);
185
+ _self.core.track(telemetryItem);
186
+ // reset ajaxes counter
187
+ _trackAjaxAttempts = 0;
188
+ };
189
+ /**
190
+ * @ignore INTERNAL ONLY
191
+ * @param pageViewPerformance
192
+ * @param properties
193
+ */
194
+ _self.sendPageViewPerformanceInternal = function (pageViewPerformance, properties, systemProperties) {
195
+ var telemetryItem = TelemetryItemCreator.create(pageViewPerformance, PageViewPerformance.dataType, PageViewPerformance.envelopeType, _self.diagLog(), properties, systemProperties);
196
+ _self.core.track(telemetryItem);
197
+ };
198
+ /**
199
+ * Send browser performance metrics.
200
+ * @param pageViewPerformance
201
+ * @param customProperties
202
+ */
203
+ _self.trackPageViewPerformance = function (pageViewPerformance, customProperties) {
204
+ try {
205
+ _self._pageViewPerformanceManager.populatePageViewPerformanceEvent(pageViewPerformance);
206
+ _self.sendPageViewPerformanceInternal(pageViewPerformance, customProperties);
207
+ }
208
+ catch (e) {
209
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackPVFailed, "trackPageViewPerformance failed, page view will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
210
+ }
211
+ };
212
+ /**
213
+ * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,
214
+ * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view
215
+ * and send the event.
216
+ * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
217
+ */
218
+ _self.startTrackPage = function (name) {
219
+ try {
220
+ if (typeof name !== "string") {
221
+ var doc = getDocument();
222
+ name = doc && doc.title || "";
223
+ }
224
+ _pageTracking.start(name);
225
+ }
226
+ catch (e) {
227
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StartTrackFailed, "startTrackPage failed, page view may not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
228
+ }
229
+ };
230
+ /**
231
+ * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
232
+ * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
233
+ * @param name The string you used as the name in startTrackPage. Defaults to the document title.
234
+ * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
235
+ * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
236
+ * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
237
+ */
238
+ _self.stopTrackPage = function (name, url, properties, measurement) {
239
+ try {
240
+ if (typeof name !== "string") {
241
+ var doc = getDocument();
242
+ name = doc && doc.title || "";
243
+ }
244
+ if (typeof url !== "string") {
245
+ var loc = getLocation();
246
+ url = loc && loc.href || "";
247
+ }
248
+ _pageTracking.stop(name, url, properties, measurement);
249
+ if (_self.config.autoTrackPageVisitTime) {
250
+ _self._pageVisitTimeManager.trackPreviousPageVisit(name, url);
251
+ }
252
+ }
253
+ catch (e) {
254
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.StopTrackFailed, "stopTrackPage failed, page view will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
255
+ }
256
+ };
257
+ /**
258
+ * @ignore INTERNAL ONLY
259
+ * @param exception
260
+ * @param properties
261
+ * @param systemProperties
262
+ */
263
+ _self.sendExceptionInternal = function (exception, customProperties, systemProperties) {
264
+ var theError = exception.exception || exception.error || new Error(strNotSpecified);
265
+ var exceptionPartB = new Exception(_self.diagLog(), theError, exception.properties || customProperties, exception.measurements, exception.severityLevel, exception.id).toInterface();
266
+ var telemetryItem = TelemetryItemCreator.create(exceptionPartB, Exception.dataType, Exception.envelopeType, _self.diagLog(), customProperties, systemProperties);
267
+ _self.core.track(telemetryItem);
268
+ };
269
+ /**
270
+ * Log an exception you have caught.
271
+ *
272
+ * @param {IExceptionTelemetry} exception Object which contains exception to be sent
273
+ * @param {{[key: string]: any}} customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.
274
+ *
275
+ * Any property of type double will be considered a measurement, and will be treated by Application Insights as a metric.
276
+ * @memberof ApplicationInsights
277
+ */
278
+ _self.trackException = function (exception, customProperties) {
279
+ try {
280
+ _self.sendExceptionInternal(exception, customProperties);
281
+ }
282
+ catch (e) {
283
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.TrackExceptionFailed, "trackException failed, exception will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
284
+ }
285
+ };
286
+ /**
287
+ * @description Custom error handler for Application Insights Analytics
288
+ * @param {IAutoExceptionTelemetry} exception
289
+ * @memberof ApplicationInsights
290
+ */
291
+ _self._onerror = function (exception) {
292
+ var error = exception && exception.error;
293
+ var evt = exception && exception.evt;
294
+ try {
295
+ if (!evt) {
296
+ var _window = getWindow();
297
+ if (_window) {
298
+ evt = _window[strEvent];
299
+ }
300
+ }
301
+ var url = (exception && exception.url) || (getDocument() || {}).URL;
302
+ // If no error source is provided assume the default window.onerror handler
303
+ var errorSrc = exception.errorSrc || "window.onerror@" + url + ":" + (exception.lineNumber || 0) + ":" + (exception.columnNumber || 0);
304
+ var properties = {
305
+ errorSrc: errorSrc,
306
+ url: url,
307
+ lineNumber: exception.lineNumber || 0,
308
+ columnNumber: exception.columnNumber || 0,
309
+ message: exception.message
310
+ };
311
+ if (isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception.error)) {
312
+ _sendCORSException(Exception.CreateAutoException("Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.", url, exception.lineNumber || 0, exception.columnNumber || 0, error, evt, null, errorSrc), properties);
313
+ }
314
+ else {
315
+ if (!exception.errorSrc) {
316
+ exception.errorSrc = errorSrc;
317
+ }
318
+ _self.trackException({ exception: exception, severityLevel: SeverityLevel.Error }, properties);
319
+ }
320
+ }
321
+ catch (e) {
322
+ var errorString = error ? (error.name + ", " + error.message) : "null";
323
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.ExceptionWhileLoggingError, "_onError threw exception while logging error, error will not be collected: "
324
+ + getExceptionName(e), { exception: dumpObj(e), errorString: errorString });
325
+ }
326
+ };
327
+ _self.addTelemetryInitializer = function (telemetryInitializer) {
328
+ _self._telemetryInitializers.push(telemetryInitializer);
329
+ };
330
+ _self.initialize = function (config, core, extensions, pluginChain) {
331
+ if (_self.isInitialized()) {
332
+ return;
333
+ }
334
+ if (isNullOrUndefined(core)) {
335
+ throw Error("Error initializing");
336
+ }
337
+ _base.initialize(config, core, extensions, pluginChain);
338
+ _self.setInitialized(false); // resetting the initialized state, just in case the following fails
339
+ var ctx = _self._getTelCtx();
340
+ var identifier = _self.identifier;
341
+ _self.config = ctx.getExtCfg(identifier);
342
+ // load default values if specified
343
+ var defaults = ApplicationInsights.getDefaultConfig(config);
344
+ if (defaults !== undefined) {
345
+ objForEachKey(defaults, function (field, value) {
346
+ // for each unspecified field, set the default value
347
+ _self.config[field] = ctx.getConfig(identifier, field, value);
348
+ if (_self.config[field] === undefined) {
349
+ _self.config[field] = value;
350
+ }
351
+ });
352
+ }
353
+ // Todo: move this out of static state
354
+ if (_self.config.isStorageUseDisabled) {
355
+ utlDisableStorage();
356
+ }
357
+ var configGetters = {
358
+ instrumentationKey: function () { return config.instrumentationKey; },
359
+ accountId: function () { return _self.config.accountId || config.accountId; },
360
+ sessionRenewalMs: function () { return _self.config.sessionRenewalMs || config.sessionRenewalMs; },
361
+ sessionExpirationMs: function () { return _self.config.sessionExpirationMs || config.sessionExpirationMs; },
362
+ sampleRate: function () { return _self.config.samplingPercentage || config.samplingPercentage; },
363
+ sdkExtension: function () { return _self.config.sdkExtension || config.sdkExtension; },
364
+ isBrowserLinkTrackingEnabled: function () { return _self.config.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled; },
365
+ appId: function () { return _self.config.appId || config.appId; }
366
+ };
367
+ _self._pageViewPerformanceManager = new PageViewPerformanceManager(_self.core);
368
+ _self._pageViewManager = new PageViewManager(_this, _self.config.overridePageViewDuration, _self.core, _self._pageViewPerformanceManager);
369
+ _self._pageVisitTimeManager = new PageVisitTimeManager(_self.diagLog(), function (pageName, pageUrl, pageVisitTime) { return trackPageVisitTime(pageName, pageUrl, pageVisitTime); });
370
+ _self._telemetryInitializers = _self._telemetryInitializers || [];
371
+ _addDefaultTelemetryInitializers(configGetters);
372
+ _eventTracking = new Timing(_self.diagLog(), "trackEvent");
373
+ _eventTracking.action =
374
+ function (name, url, duration, properties) {
375
+ if (!properties) {
376
+ properties = {};
377
+ }
378
+ properties[durationProperty] = duration.toString();
379
+ _self.trackEvent({ name: name, properties: properties });
380
+ };
381
+ // initialize page view timing
382
+ _pageTracking = new Timing(_self.diagLog(), "trackPageView");
383
+ _pageTracking.action = function (name, url, duration, properties, measurements) {
384
+ // duration must be a custom property in order for the collector to extract it
385
+ if (isNullOrUndefined(properties)) {
386
+ properties = {};
387
+ }
388
+ properties[durationProperty] = duration.toString();
389
+ var pageViewItem = {
390
+ name: name,
391
+ uri: url,
392
+ properties: properties,
393
+ measurements: measurements
394
+ };
395
+ _self.sendPageViewInternal(pageViewItem, properties);
396
+ };
397
+ var _window = getWindow();
398
+ var _history = getHistory();
399
+ var _location = getLocation(true);
400
+ var instance = _this;
401
+ if (_self.config.disableExceptionTracking === false &&
402
+ !_self.config.autoExceptionInstrumented && _window) {
403
+ // We want to enable exception auto collection and it has not been done so yet
404
+ var onerror_1 = "onerror";
405
+ var originalOnError_1 = _window[onerror_1];
406
+ _window.onerror = function (message, url, lineNumber, columnNumber, error) {
407
+ var evt = _window[strEvent];
408
+ var handled = originalOnError_1 && originalOnError_1(message, url, lineNumber, columnNumber, error);
409
+ if (handled !== true) { // handled could be typeof function
410
+ instance._onerror(Exception.CreateAutoException(message, url, lineNumber, columnNumber, error, evt));
411
+ }
412
+ return handled;
413
+ };
414
+ _self.config.autoExceptionInstrumented = true;
415
+ }
416
+ if (_self.config.disableExceptionTracking === false &&
417
+ _self.config.enableUnhandledPromiseRejectionTracking === true &&
418
+ !_self.config.autoUnhandledPromiseInstrumented && _window) {
419
+ // We want to enable exception auto collection and it has not been done so yet
420
+ var onunhandledrejection_1 = "onunhandledrejection";
421
+ var originalOnUnhandledRejection_1 = _window[onunhandledrejection_1];
422
+ _window[onunhandledrejection_1] = function (error) {
423
+ var evt = _window[strEvent];
424
+ var handled = originalOnUnhandledRejection_1 && originalOnUnhandledRejection_1.call(_window, error);
425
+ if (handled !== true) { // handled could be typeof function
426
+ instance._onerror(Exception.CreateAutoException(_getReason(error), _location ? _location.href : "", 0, 0, error, evt));
427
+ }
428
+ return handled;
429
+ };
430
+ _self.config.autoUnhandledPromiseInstrumented = true;
431
+ }
432
+ /**
433
+ * Create a custom "locationchange" event which is triggered each time the history object is changed
434
+ */
435
+ if (_self.config.enableAutoRouteTracking === true
436
+ && _history && isFunction(_history.pushState) && isFunction(_history.replaceState)
437
+ && _window
438
+ && typeof Event !== "undefined") {
439
+ var _self_1 = _this;
440
+ // Find the properties plugin
441
+ arrForEach(extensions, function (extension) {
442
+ if (extension.identifier === PropertiesPluginIdentifier) {
443
+ _properties = extension;
444
+ }
445
+ });
446
+ _history.pushState = (function (f) { return function pushState() {
447
+ var ret = f.apply(this, arguments);
448
+ _dispatchEvent(_window, createDomEvent(_self_1.config.namePrefix + "pushState"));
449
+ _dispatchEvent(_window, createDomEvent(_self_1.config.namePrefix + "locationchange"));
450
+ return ret;
451
+ }; })(_history.pushState);
452
+ _history.replaceState = (function (f) { return function replaceState() {
453
+ var ret = f.apply(this, arguments);
454
+ _dispatchEvent(_window, createDomEvent(_self_1.config.namePrefix + "replaceState"));
455
+ _dispatchEvent(_window, createDomEvent(_self_1.config.namePrefix + "locationchange"));
456
+ return ret;
457
+ }; })(_history.replaceState);
458
+ if (_window.addEventListener) {
459
+ _window.addEventListener(_self_1.config.namePrefix + "popstate", function () {
460
+ _dispatchEvent(_window, createDomEvent(_self_1.config.namePrefix + "locationchange"));
461
+ });
462
+ _window.addEventListener(_self_1.config.namePrefix + "locationchange", function () {
463
+ if (_properties && _properties.context && _properties.context.telemetryTrace) {
464
+ _properties.context.telemetryTrace.traceID = generateW3CId();
465
+ var traceLocationName = "_unknown_";
466
+ if (_location && _location.pathname) {
467
+ traceLocationName = _location.pathname + (_location.hash || "");
468
+ }
469
+ // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it
470
+ _properties.context.telemetryTrace.name = dataSanitizeString(_self_1.diagLog(), traceLocationName);
471
+ }
472
+ if (_currUri) {
473
+ _prevUri = _currUri;
474
+ _currUri = _location && _location.href || "";
475
+ }
476
+ else {
477
+ _currUri = _location && _location.href || "";
478
+ }
479
+ setTimeout((function (uri) {
480
+ // todo: override start time so that it is not affected by autoRoutePVDelay
481
+ _self_1.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
482
+ }).bind(_this, _prevUri), _self_1.autoRoutePVDelay);
483
+ });
484
+ }
485
+ }
486
+ _self.setInitialized(true);
487
+ };
488
+ /**
489
+ * Log a page visit time
490
+ * @param pageName Name of page
491
+ * @param pageVisitDuration Duration of visit to the page in milleseconds
492
+ */
493
+ function trackPageVisitTime(pageName, pageUrl, pageVisitTime) {
494
+ var properties = { PageName: pageName, PageUrl: pageUrl };
495
+ _self.trackMetric({
496
+ name: "PageVisitTime",
497
+ average: pageVisitTime,
498
+ max: pageVisitTime,
499
+ min: pageVisitTime,
500
+ sampleCount: 1
501
+ }, properties);
502
+ }
503
+ function _addDefaultTelemetryInitializers(configGetters) {
504
+ if (!configGetters.isBrowserLinkTrackingEnabled()) {
505
+ var browserLinkPaths_1 = ["/browserLinkSignalR/", "/__browserLink/"];
506
+ var dropBrowserLinkRequests = function (envelope) {
507
+ if (envelope.baseType === RemoteDependencyData.dataType) {
508
+ var remoteData = envelope.baseData;
509
+ if (remoteData) {
510
+ for (var i = 0; i < browserLinkPaths_1.length; i++) {
511
+ if (remoteData.target && remoteData.target.indexOf(browserLinkPaths_1[i]) >= 0) {
512
+ return false;
513
+ }
514
+ }
515
+ }
516
+ }
517
+ return true;
518
+ };
519
+ _addTelemetryInitializer(dropBrowserLinkRequests);
520
+ }
521
+ }
522
+ function _addTelemetryInitializer(telemetryInitializer) {
523
+ _self._telemetryInitializers.push(telemetryInitializer);
524
+ }
525
+ function _sendCORSException(exception, properties) {
526
+ var telemetryItem = TelemetryItemCreator.create(exception, Exception.dataType, Exception.envelopeType, _self.diagLog(), properties);
527
+ _self.core.track(telemetryItem);
528
+ }
529
+ });
530
+ return _this;
531
+ }
532
+ ApplicationInsights.getDefaultConfig = function (config) {
533
+ if (!config) {
534
+ config = {};
535
+ }
536
+ // set default values
537
+ config.sessionRenewalMs = 30 * 60 * 1000;
538
+ config.sessionExpirationMs = 24 * 60 * 60 * 1000;
539
+ config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
540
+ config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
541
+ config.overridePageViewDuration = stringToBoolOrDefault(config.overridePageViewDuration);
542
+ config.enableUnhandledPromiseRejectionTracking = stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
543
+ if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
544
+ config.samplingPercentage = 100;
545
+ }
546
+ config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
547
+ config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
548
+ config.enableAutoRouteTracking = stringToBoolOrDefault(config.enableAutoRouteTracking);
549
+ config.namePrefix = config.namePrefix || "";
550
+ config.enableDebug = stringToBoolOrDefault(config.enableDebug);
551
+ config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
552
+ config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
553
+ return config;
554
+ };
555
+ // Removed Stub for ApplicationInsights.prototype.getCookieMgr.
556
+ // Removed Stub for ApplicationInsights.prototype.processTelemetry.
557
+ // Removed Stub for ApplicationInsights.prototype.trackEvent.
558
+ // Removed Stub for ApplicationInsights.prototype.startTrackEvent.
559
+ // Removed Stub for ApplicationInsights.prototype.stopTrackEvent.
560
+ // Removed Stub for ApplicationInsights.prototype.trackTrace.
561
+ // Removed Stub for ApplicationInsights.prototype.trackMetric.
562
+ // Removed Stub for ApplicationInsights.prototype.trackPageView.
563
+ // Removed Stub for ApplicationInsights.prototype.sendPageViewInternal.
564
+ // Removed Stub for ApplicationInsights.prototype.sendPageViewPerformanceInternal.
565
+ // Removed Stub for ApplicationInsights.prototype.trackPageViewPerformance.
566
+ // Removed Stub for ApplicationInsights.prototype.startTrackPage.
567
+ // Removed Stub for ApplicationInsights.prototype.stopTrackPage.
568
+ // Removed Stub for ApplicationInsights.prototype.sendExceptionInternal.
569
+ // Removed Stub for ApplicationInsights.prototype.trackException.
570
+ // Removed Stub for ApplicationInsights.prototype._onerror.
571
+ // Removed Stub for ApplicationInsights.prototype.addTelemetryInitializer.
572
+ // Removed Stub for ApplicationInsights.prototype.initialize.
573
+ ApplicationInsights.Version = "2.7.5-nightly.2204-23"; // Not currently used anywhere
574
+ return ApplicationInsights;
575
+ }(BaseTelemetryPlugin));
576
+ export { ApplicationInsights };
577
+ /**
578
+ * Used to record timed events and page views.
579
+ */
580
+ var Timing = /** @class */ (function () {
581
+ function Timing(logger, name) {
582
+ var _self = this;
583
+ var _events = {};
584
+ _self.start = function (name) {
585
+ if (typeof _events[name] !== "undefined") {
586
+ logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.StartCalledMoreThanOnce, "start was called more than once for this event without calling stop.", { name: name, key: name }, true);
587
+ }
588
+ _events[name] = +new Date;
589
+ };
590
+ _self.stop = function (name, url, properties, measurements) {
591
+ var start = _events[name];
592
+ if (isNaN(start)) {
593
+ logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.StopCalledWithoutStart, "stop was called without a corresponding start.", { name: name, key: name }, true);
594
+ }
595
+ else {
596
+ var end = +new Date;
597
+ var duration = dateTimeUtilsDuration(start, end);
598
+ _self.action(name, url, duration, properties, measurements);
599
+ }
600
+ delete _events[name];
601
+ _events[name] = undefined;
602
+ };
603
+ }
604
+ return Timing;
605
+ }());
606
+ //# sourceMappingURL=ApplicationInsights.js.map