@microsoft/1ds-post-js 3.1.6 → 3.1.10

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 (60) hide show
  1. package/README.md +2 -1
  2. package/bundle/ms.post-3.1.10.gbl.js +3595 -0
  3. package/bundle/ms.post-3.1.10.gbl.js.map +1 -0
  4. package/bundle/ms.post-3.1.10.gbl.min.js +7 -0
  5. package/bundle/ms.post-3.1.10.gbl.min.js.map +1 -0
  6. package/bundle/ms.post-3.1.10.integrity.json +46 -0
  7. package/bundle/{ms.post-test.js → ms.post-3.1.10.js} +333 -163
  8. package/bundle/ms.post-3.1.10.js.map +1 -0
  9. package/bundle/ms.post-3.1.10.min.js +7 -0
  10. package/bundle/ms.post-3.1.10.min.js.map +1 -0
  11. package/bundle/{ms.post-3.1.6.gbl.js → ms.post.gbl.js} +332 -162
  12. package/bundle/ms.post.gbl.js.map +1 -0
  13. package/bundle/ms.post.gbl.min.js +7 -0
  14. package/bundle/ms.post.gbl.min.js.map +1 -0
  15. package/bundle/ms.post.integrity.json +46 -0
  16. package/bundle/{ms.post-3.1.6.js → ms.post.js} +333 -163
  17. package/bundle/ms.post.js.map +1 -0
  18. package/bundle/ms.post.min.js +7 -0
  19. package/bundle/ms.post.min.js.map +1 -0
  20. package/dist/ms.post.js +149 -89
  21. package/dist/ms.post.js.map +1 -1
  22. package/dist/ms.post.min.js +2 -2
  23. package/dist/ms.post.min.js.map +1 -1
  24. package/dist-esm/src/BatchNotificationActions.js +1 -1
  25. package/dist-esm/src/ClockSkewManager.js +1 -1
  26. package/dist-esm/src/Constants.d.ts +24 -0
  27. package/dist-esm/src/Constants.js +30 -0
  28. package/dist-esm/src/Constants.js.map +1 -0
  29. package/dist-esm/src/DataModels.d.ts +11 -2
  30. package/dist-esm/src/DataModels.js +1 -1
  31. package/dist-esm/src/EventBatch.d.ts +5 -2
  32. package/dist-esm/src/EventBatch.js +35 -15
  33. package/dist-esm/src/EventBatch.js.map +1 -1
  34. package/dist-esm/src/HttpManager.d.ts +1 -1
  35. package/dist-esm/src/HttpManager.js +121 -79
  36. package/dist-esm/src/HttpManager.js.map +1 -1
  37. package/dist-esm/src/Index.js +1 -1
  38. package/dist-esm/src/KillSwitch.js +1 -1
  39. package/dist-esm/src/PostChannel.js +10 -8
  40. package/dist-esm/src/PostChannel.js.map +1 -1
  41. package/dist-esm/src/RetryPolicy.js +1 -1
  42. package/dist-esm/src/Serializer.js +1 -1
  43. package/dist-esm/src/typings/XDomainRequest.js +1 -1
  44. package/package.json +3 -3
  45. package/src/Constants.ts +27 -0
  46. package/src/DataModels.ts +13 -3
  47. package/src/EventBatch.ts +47 -14
  48. package/src/HttpManager.ts +155 -85
  49. package/src/PostChannel.ts +9 -6
  50. package/bundle/ms.post-3.1.6.gbl.js.map +0 -1
  51. package/bundle/ms.post-3.1.6.gbl.min.js +0 -7
  52. package/bundle/ms.post-3.1.6.gbl.min.js.map +0 -1
  53. package/bundle/ms.post-3.1.6.integrity.json +0 -46
  54. package/bundle/ms.post-3.1.6.js.map +0 -1
  55. package/bundle/ms.post-3.1.6.min.js +0 -7
  56. package/bundle/ms.post-3.1.6.min.js.map +0 -1
  57. package/bundle/ms.post-test.integrity.json +0 -26
  58. package/bundle/ms.post-test.js.map +0 -1
  59. package/bundle/ms.post-test.min.js +0 -7
  60. package/bundle/ms.post-test.min.js.map +0 -1
@@ -0,0 +1,3595 @@
1
+ /*!
2
+ * 1DS JS SDK POST plugin, 3.1.10
3
+ * Copyright (c) Microsoft and contributors. All rights reserved.
4
+ * (Microsoft Internal Only)
5
+ */
6
+ (function (exports) {
7
+ 'use strict';
8
+
9
+ var strShimFunction = "function";
10
+ var strShimObject = "object";
11
+ var strShimUndefined = "undefined";
12
+ var strShimPrototype = "prototype";
13
+ var strShimHasOwnProperty = "hasOwnProperty";
14
+ var ObjClass = Object;
15
+ var ObjProto = ObjClass[strShimPrototype];
16
+ var ObjAssign = ObjClass["assign"];
17
+ var ObjCreate = ObjClass["create"];
18
+ var ObjDefineProperty = ObjClass["defineProperty"];
19
+ var ObjHasOwnProperty = ObjProto[strShimHasOwnProperty];
20
+
21
+ var _cachedGlobal = null;
22
+ function getGlobal(useCached) {
23
+ if (useCached === void 0) { useCached = true; }
24
+ if (!_cachedGlobal || !useCached) {
25
+ if (typeof globalThis !== strShimUndefined && globalThis) {
26
+ _cachedGlobal = globalThis;
27
+ }
28
+ if (typeof self !== strShimUndefined && self) {
29
+ _cachedGlobal = self;
30
+ }
31
+ if (typeof window !== strShimUndefined && window) {
32
+ _cachedGlobal = window;
33
+ }
34
+ if (typeof global !== strShimUndefined && global) {
35
+ _cachedGlobal = global;
36
+ }
37
+ }
38
+ return _cachedGlobal;
39
+ }
40
+ function throwTypeError(message) {
41
+ throw new TypeError(message);
42
+ }
43
+ function objCreateFn(obj) {
44
+ var func = ObjCreate;
45
+ if (func) {
46
+ return func(obj);
47
+ }
48
+ if (obj == null) {
49
+ return {};
50
+ }
51
+ var type = typeof obj;
52
+ if (type !== strShimObject && type !== strShimFunction) {
53
+ throwTypeError("Object prototype may only be an Object:" + obj);
54
+ }
55
+ function tmpFunc() { }
56
+ tmpFunc[strShimPrototype] = obj;
57
+ return new tmpFunc();
58
+ }
59
+
60
+ (getGlobal() || {})["Symbol"];
61
+ (getGlobal() || {})["Reflect"];
62
+ var __objAssignFnImpl = function (t) {
63
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
64
+ s = arguments[i];
65
+ for (var p in s) {
66
+ if (ObjProto[strShimHasOwnProperty].call(s, p)) {
67
+ t[p] = s[p];
68
+ }
69
+ }
70
+ }
71
+ return t;
72
+ };
73
+ var __assignFn = ObjAssign || __objAssignFnImpl;
74
+ var extendStaticsFn = function (d, b) {
75
+ extendStaticsFn = ObjClass["setPrototypeOf"] ||
76
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
77
+ function (d, b) {
78
+ for (var p in b) {
79
+ if (b[strShimHasOwnProperty](p)) {
80
+ d[p] = b[p];
81
+ }
82
+ }
83
+ };
84
+ return extendStaticsFn(d, b);
85
+ };
86
+ function __extendsFn(d, b) {
87
+ if (typeof b !== strShimFunction && b !== null) {
88
+ throwTypeError("Class extends value " + String(b) + " is not a constructor or null");
89
+ }
90
+ extendStaticsFn(d, b);
91
+ function __() { this.constructor = d; }
92
+ d[strShimPrototype] = b === null ? objCreateFn(b) : (__[strShimPrototype] = b[strShimPrototype], new __());
93
+ }
94
+
95
+ var EventsDiscardedReason = {
96
+ Unknown: 0,
97
+ NonRetryableStatus: 1,
98
+ InvalidEvent: 2,
99
+ SizeLimitExceeded: 3,
100
+ KillSwitch: 4,
101
+ QueueFull: 5
102
+ };
103
+
104
+ /*!
105
+ * Microsoft Dynamic Proto Utility, 1.1.4
106
+ * Copyright (c) Microsoft and contributors. All rights reserved.
107
+ */
108
+ var Constructor = 'constructor';
109
+ var Prototype = 'prototype';
110
+ var strFunction = 'function';
111
+ var DynInstFuncTable = '_dynInstFuncs';
112
+ var DynProxyTag = '_isDynProxy';
113
+ var DynClassName = '_dynClass';
114
+ var DynClassNamePrefix = '_dynCls$';
115
+ var DynInstChkTag = '_dynInstChk';
116
+ var DynAllowInstChkTag = DynInstChkTag;
117
+ var DynProtoDefaultOptions = '_dfOpts';
118
+ var UnknownValue = '_unknown_';
119
+ var str__Proto = "__proto__";
120
+ var strUseBaseInst = 'useBaseInst';
121
+ var strSetInstFuncs = 'setInstFuncs';
122
+ var Obj = Object;
123
+ var _objGetPrototypeOf = Obj["getPrototypeOf"];
124
+ var _dynamicNames = 0;
125
+ function _hasOwnProperty(obj, prop) {
126
+ return obj && Obj[Prototype].hasOwnProperty.call(obj, prop);
127
+ }
128
+ function _isObjectOrArrayPrototype(target) {
129
+ return target && (target === Obj[Prototype] || target === Array[Prototype]);
130
+ }
131
+ function _isObjectArrayOrFunctionPrototype(target) {
132
+ return _isObjectOrArrayPrototype(target) || target === Function[Prototype];
133
+ }
134
+ function _getObjProto(target) {
135
+ if (target) {
136
+ if (_objGetPrototypeOf) {
137
+ return _objGetPrototypeOf(target);
138
+ }
139
+ var newProto = target[str__Proto] || target[Prototype] || (target[Constructor] ? target[Constructor][Prototype] : null);
140
+ if (newProto) {
141
+ return newProto;
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+ function _forEachProp(target, func) {
147
+ var props = [];
148
+ var getOwnProps = Obj["getOwnPropertyNames"];
149
+ if (getOwnProps) {
150
+ props = getOwnProps(target);
151
+ }
152
+ else {
153
+ for (var name_1 in target) {
154
+ if (typeof name_1 === "string" && _hasOwnProperty(target, name_1)) {
155
+ props.push(name_1);
156
+ }
157
+ }
158
+ }
159
+ if (props && props.length > 0) {
160
+ for (var lp = 0; lp < props.length; lp++) {
161
+ func(props[lp]);
162
+ }
163
+ }
164
+ }
165
+ function _isDynamicCandidate(target, funcName, skipOwn) {
166
+ return (funcName !== Constructor && typeof target[funcName] === strFunction && (skipOwn || _hasOwnProperty(target, funcName)));
167
+ }
168
+ function _throwTypeError(message) {
169
+ throw new TypeError("DynamicProto: " + message);
170
+ }
171
+ function _getInstanceFuncs(thisTarget) {
172
+ var instFuncs = {};
173
+ _forEachProp(thisTarget, function (name) {
174
+ if (!instFuncs[name] && _isDynamicCandidate(thisTarget, name, false)) {
175
+ instFuncs[name] = thisTarget[name];
176
+ }
177
+ });
178
+ return instFuncs;
179
+ }
180
+ function _hasVisited(values, value) {
181
+ for (var lp = values.length - 1; lp >= 0; lp--) {
182
+ if (values[lp] === value) {
183
+ return true;
184
+ }
185
+ }
186
+ return false;
187
+ }
188
+ function _getBaseFuncs(classProto, thisTarget, instFuncs, useBaseInst) {
189
+ function _instFuncProxy(target, funcHost, funcName) {
190
+ var theFunc = funcHost[funcName];
191
+ if (theFunc[DynProxyTag] && useBaseInst) {
192
+ var instFuncTable = target[DynInstFuncTable] || {};
193
+ if (instFuncTable[DynAllowInstChkTag] !== false) {
194
+ theFunc = (instFuncTable[funcHost[DynClassName]] || {})[funcName] || theFunc;
195
+ }
196
+ }
197
+ return function () {
198
+ return theFunc.apply(target, arguments);
199
+ };
200
+ }
201
+ var baseFuncs = {};
202
+ _forEachProp(instFuncs, function (name) {
203
+ baseFuncs[name] = _instFuncProxy(thisTarget, instFuncs, name);
204
+ });
205
+ var baseProto = _getObjProto(classProto);
206
+ var visited = [];
207
+ while (baseProto && !_isObjectArrayOrFunctionPrototype(baseProto) && !_hasVisited(visited, baseProto)) {
208
+ _forEachProp(baseProto, function (name) {
209
+ if (!baseFuncs[name] && _isDynamicCandidate(baseProto, name, !_objGetPrototypeOf)) {
210
+ baseFuncs[name] = _instFuncProxy(thisTarget, baseProto, name);
211
+ }
212
+ });
213
+ visited.push(baseProto);
214
+ baseProto = _getObjProto(baseProto);
215
+ }
216
+ return baseFuncs;
217
+ }
218
+ function _getInstFunc(target, funcName, proto, currentDynProtoProxy) {
219
+ var instFunc = null;
220
+ if (target && _hasOwnProperty(proto, DynClassName)) {
221
+ var instFuncTable = target[DynInstFuncTable] || {};
222
+ instFunc = (instFuncTable[proto[DynClassName]] || {})[funcName];
223
+ if (!instFunc) {
224
+ _throwTypeError("Missing [" + funcName + "] " + strFunction);
225
+ }
226
+ if (!instFunc[DynInstChkTag] && instFuncTable[DynAllowInstChkTag] !== false) {
227
+ var canAddInst = !_hasOwnProperty(target, funcName);
228
+ var objProto = _getObjProto(target);
229
+ var visited = [];
230
+ while (canAddInst && objProto && !_isObjectArrayOrFunctionPrototype(objProto) && !_hasVisited(visited, objProto)) {
231
+ var protoFunc = objProto[funcName];
232
+ if (protoFunc) {
233
+ canAddInst = (protoFunc === currentDynProtoProxy);
234
+ break;
235
+ }
236
+ visited.push(objProto);
237
+ objProto = _getObjProto(objProto);
238
+ }
239
+ try {
240
+ if (canAddInst) {
241
+ target[funcName] = instFunc;
242
+ }
243
+ instFunc[DynInstChkTag] = 1;
244
+ }
245
+ catch (e) {
246
+ instFuncTable[DynAllowInstChkTag] = false;
247
+ }
248
+ }
249
+ }
250
+ return instFunc;
251
+ }
252
+ function _getProtoFunc(funcName, proto, currentDynProtoProxy) {
253
+ var protoFunc = proto[funcName];
254
+ if (protoFunc === currentDynProtoProxy) {
255
+ protoFunc = _getObjProto(proto)[funcName];
256
+ }
257
+ if (typeof protoFunc !== strFunction) {
258
+ _throwTypeError("[" + funcName + "] is not a " + strFunction);
259
+ }
260
+ return protoFunc;
261
+ }
262
+ function _populatePrototype(proto, className, target, baseInstFuncs, setInstanceFunc) {
263
+ function _createDynamicPrototype(proto, funcName) {
264
+ var dynProtoProxy = function () {
265
+ var instFunc = _getInstFunc(this, funcName, proto, dynProtoProxy) || _getProtoFunc(funcName, proto, dynProtoProxy);
266
+ return instFunc.apply(this, arguments);
267
+ };
268
+ dynProtoProxy[DynProxyTag] = 1;
269
+ return dynProtoProxy;
270
+ }
271
+ if (!_isObjectOrArrayPrototype(proto)) {
272
+ var instFuncTable = target[DynInstFuncTable] = target[DynInstFuncTable] || {};
273
+ var instFuncs_1 = instFuncTable[className] = (instFuncTable[className] || {});
274
+ if (instFuncTable[DynAllowInstChkTag] !== false) {
275
+ instFuncTable[DynAllowInstChkTag] = !!setInstanceFunc;
276
+ }
277
+ _forEachProp(target, function (name) {
278
+ if (_isDynamicCandidate(target, name, false) && target[name] !== baseInstFuncs[name]) {
279
+ instFuncs_1[name] = target[name];
280
+ delete target[name];
281
+ if (!_hasOwnProperty(proto, name) || (proto[name] && !proto[name][DynProxyTag])) {
282
+ proto[name] = _createDynamicPrototype(proto, name);
283
+ }
284
+ }
285
+ });
286
+ }
287
+ }
288
+ function _checkPrototype(classProto, thisTarget) {
289
+ if (_objGetPrototypeOf) {
290
+ var visited = [];
291
+ var thisProto = _getObjProto(thisTarget);
292
+ while (thisProto && !_isObjectArrayOrFunctionPrototype(thisProto) && !_hasVisited(visited, thisProto)) {
293
+ if (thisProto === classProto) {
294
+ return true;
295
+ }
296
+ visited.push(thisProto);
297
+ thisProto = _getObjProto(thisProto);
298
+ }
299
+ }
300
+ return false;
301
+ }
302
+ function _getObjName(target, unknownValue) {
303
+ if (_hasOwnProperty(target, Prototype)) {
304
+ return target.name || unknownValue || UnknownValue;
305
+ }
306
+ return (((target || {})[Constructor]) || {}).name || unknownValue || UnknownValue;
307
+ }
308
+ function dynamicProto(theClass, target, delegateFunc, options) {
309
+ if (!_hasOwnProperty(theClass, Prototype)) {
310
+ _throwTypeError("theClass is an invalid class definition.");
311
+ }
312
+ var classProto = theClass[Prototype];
313
+ if (!_checkPrototype(classProto, target)) {
314
+ _throwTypeError("[" + _getObjName(theClass) + "] is not in class hierarchy of [" + _getObjName(target) + "]");
315
+ }
316
+ var className = null;
317
+ if (_hasOwnProperty(classProto, DynClassName)) {
318
+ className = classProto[DynClassName];
319
+ }
320
+ else {
321
+ className = DynClassNamePrefix + _getObjName(theClass, "_") + "$" + _dynamicNames;
322
+ _dynamicNames++;
323
+ classProto[DynClassName] = className;
324
+ }
325
+ var perfOptions = dynamicProto[DynProtoDefaultOptions];
326
+ var useBaseInst = !!perfOptions[strUseBaseInst];
327
+ if (useBaseInst && options && options[strUseBaseInst] !== undefined) {
328
+ useBaseInst = !!options[strUseBaseInst];
329
+ }
330
+ var instFuncs = _getInstanceFuncs(target);
331
+ var baseFuncs = _getBaseFuncs(classProto, target, instFuncs, useBaseInst);
332
+ delegateFunc(target, baseFuncs);
333
+ var setInstanceFunc = !!_objGetPrototypeOf && !!perfOptions[strSetInstFuncs];
334
+ if (setInstanceFunc && options) {
335
+ setInstanceFunc = !!options[strSetInstFuncs];
336
+ }
337
+ _populatePrototype(classProto, className, target, instFuncs, setInstanceFunc !== false);
338
+ }
339
+ var perfDefaults = {
340
+ setInstFuncs: true,
341
+ useBaseInst: true
342
+ };
343
+ dynamicProto[DynProtoDefaultOptions] = perfDefaults;
344
+
345
+ var LoggingSeverity;
346
+ (function (LoggingSeverity) {
347
+ LoggingSeverity[LoggingSeverity["CRITICAL"] = 1] = "CRITICAL";
348
+ LoggingSeverity[LoggingSeverity["WARNING"] = 2] = "WARNING";
349
+ })(LoggingSeverity || (LoggingSeverity = {}));
350
+ var _InternalMessageId = {
351
+ BrowserDoesNotSupportLocalStorage: 0,
352
+ BrowserCannotReadLocalStorage: 1,
353
+ BrowserCannotReadSessionStorage: 2,
354
+ BrowserCannotWriteLocalStorage: 3,
355
+ BrowserCannotWriteSessionStorage: 4,
356
+ BrowserFailedRemovalFromLocalStorage: 5,
357
+ BrowserFailedRemovalFromSessionStorage: 6,
358
+ CannotSendEmptyTelemetry: 7,
359
+ ClientPerformanceMathError: 8,
360
+ ErrorParsingAISessionCookie: 9,
361
+ ErrorPVCalc: 10,
362
+ ExceptionWhileLoggingError: 11,
363
+ FailedAddingTelemetryToBuffer: 12,
364
+ FailedMonitorAjaxAbort: 13,
365
+ FailedMonitorAjaxDur: 14,
366
+ FailedMonitorAjaxOpen: 15,
367
+ FailedMonitorAjaxRSC: 16,
368
+ FailedMonitorAjaxSend: 17,
369
+ FailedMonitorAjaxGetCorrelationHeader: 18,
370
+ FailedToAddHandlerForOnBeforeUnload: 19,
371
+ FailedToSendQueuedTelemetry: 20,
372
+ FailedToReportDataLoss: 21,
373
+ FlushFailed: 22,
374
+ MessageLimitPerPVExceeded: 23,
375
+ MissingRequiredFieldSpecification: 24,
376
+ NavigationTimingNotSupported: 25,
377
+ OnError: 26,
378
+ SessionRenewalDateIsZero: 27,
379
+ SenderNotInitialized: 28,
380
+ StartTrackEventFailed: 29,
381
+ StopTrackEventFailed: 30,
382
+ StartTrackFailed: 31,
383
+ StopTrackFailed: 32,
384
+ TelemetrySampledAndNotSent: 33,
385
+ TrackEventFailed: 34,
386
+ TrackExceptionFailed: 35,
387
+ TrackMetricFailed: 36,
388
+ TrackPVFailed: 37,
389
+ TrackPVFailedCalc: 38,
390
+ TrackTraceFailed: 39,
391
+ TransmissionFailed: 40,
392
+ FailedToSetStorageBuffer: 41,
393
+ FailedToRestoreStorageBuffer: 42,
394
+ InvalidBackendResponse: 43,
395
+ FailedToFixDepricatedValues: 44,
396
+ InvalidDurationValue: 45,
397
+ TelemetryEnvelopeInvalid: 46,
398
+ CreateEnvelopeError: 47,
399
+ CannotSerializeObject: 48,
400
+ CannotSerializeObjectNonSerializable: 49,
401
+ CircularReferenceDetected: 50,
402
+ ClearAuthContextFailed: 51,
403
+ ExceptionTruncated: 52,
404
+ IllegalCharsInName: 53,
405
+ ItemNotInArray: 54,
406
+ MaxAjaxPerPVExceeded: 55,
407
+ MessageTruncated: 56,
408
+ NameTooLong: 57,
409
+ SampleRateOutOfRange: 58,
410
+ SetAuthContextFailed: 59,
411
+ SetAuthContextFailedAccountName: 60,
412
+ StringValueTooLong: 61,
413
+ StartCalledMoreThanOnce: 62,
414
+ StopCalledWithoutStart: 63,
415
+ TelemetryInitializerFailed: 64,
416
+ TrackArgumentsNotSpecified: 65,
417
+ UrlTooLong: 66,
418
+ SessionStorageBufferFull: 67,
419
+ CannotAccessCookie: 68,
420
+ IdTooLong: 69,
421
+ InvalidEvent: 70,
422
+ FailedMonitorAjaxSetRequestHeader: 71,
423
+ SendBrowserInfoOnUserInit: 72,
424
+ PluginException: 73,
425
+ NotificationException: 74,
426
+ SnippetScriptLoadFailure: 99,
427
+ InvalidInstrumentationKey: 100,
428
+ CannotParseAiBlobValue: 101,
429
+ InvalidContentBlob: 102,
430
+ TrackPageActionEventFailed: 103,
431
+ FailedAddingCustomDefinedRequestContext: 104,
432
+ InMemoryStorageBufferFull: 105
433
+ };
434
+
435
+ var strOnPrefix = "on";
436
+ var strAttachEvent = "attachEvent";
437
+ var strAddEventHelper = "addEventListener";
438
+ var _objDefineProperty = ObjDefineProperty;
439
+ function objToString(obj) {
440
+ return ObjProto.toString.call(obj);
441
+ }
442
+ function isUndefined(value) {
443
+ return value === undefined || typeof value === strShimUndefined;
444
+ }
445
+ function isNullOrUndefined(value) {
446
+ return (value === null || isUndefined(value));
447
+ }
448
+ function hasOwnProperty(obj, prop) {
449
+ return obj && ObjHasOwnProperty.call(obj, prop);
450
+ }
451
+ function isObject(value) {
452
+ return typeof value === strShimObject;
453
+ }
454
+ function isFunction(value) {
455
+ return typeof value === strShimFunction;
456
+ }
457
+ function attachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {
458
+ if (useCapture === void 0) { useCapture = false; }
459
+ var result = false;
460
+ if (!isNullOrUndefined(obj)) {
461
+ try {
462
+ if (!isNullOrUndefined(obj[strAddEventHelper])) {
463
+ obj[strAddEventHelper](eventNameWithoutOn, handlerRef, useCapture);
464
+ result = true;
465
+ }
466
+ else if (!isNullOrUndefined(obj[strAttachEvent])) {
467
+ obj[strAttachEvent](strOnPrefix + eventNameWithoutOn, handlerRef);
468
+ result = true;
469
+ }
470
+ }
471
+ catch (e) {
472
+ }
473
+ }
474
+ return result;
475
+ }
476
+ function objForEachKey(target, callbackfn) {
477
+ if (target) {
478
+ for (var prop in target) {
479
+ if (ObjHasOwnProperty.call(target, prop)) {
480
+ callbackfn.call(target, prop, target[prop]);
481
+ }
482
+ }
483
+ }
484
+ }
485
+ function strStartsWith(value, checkValue) {
486
+ var result = false;
487
+ if (value && checkValue) {
488
+ var chkLen = checkValue.length;
489
+ if (value === checkValue) {
490
+ return true;
491
+ }
492
+ else if (value.length >= chkLen) {
493
+ for (var lp = 0; lp < chkLen; lp++) {
494
+ if (value[lp] !== checkValue[lp]) {
495
+ return false;
496
+ }
497
+ }
498
+ result = true;
499
+ }
500
+ }
501
+ return result;
502
+ }
503
+ function isArray(obj) {
504
+ return objToString(obj) === "[object Array]";
505
+ }
506
+ function isString(value) {
507
+ return typeof value === "string";
508
+ }
509
+ function isNumber(value) {
510
+ return typeof value === "number";
511
+ }
512
+ function isBoolean(value) {
513
+ return typeof value === "boolean";
514
+ }
515
+ function arrForEach(arr, callbackfn, thisArg) {
516
+ var len = arr.length;
517
+ try {
518
+ for (var idx = 0; idx < len; idx++) {
519
+ if (idx in arr) {
520
+ if (callbackfn.call(thisArg || arr, arr[idx], idx, arr) === -1) {
521
+ break;
522
+ }
523
+ }
524
+ }
525
+ }
526
+ catch (e) {
527
+ }
528
+ }
529
+ function arrIndexOf(arr, searchElement, fromIndex) {
530
+ var len = arr.length;
531
+ var from = fromIndex || 0;
532
+ try {
533
+ for (var lp = Math.max(from >= 0 ? from : len - Math.abs(from), 0); lp < len; lp++) {
534
+ if (lp in arr && arr[lp] === searchElement) {
535
+ return lp;
536
+ }
537
+ }
538
+ }
539
+ catch (e) {
540
+ }
541
+ return -1;
542
+ }
543
+ function strTrim(str) {
544
+ if (typeof str !== "string") {
545
+ return str;
546
+ }
547
+ return str.replace(/^\s+|\s+$/g, "");
548
+ }
549
+ var _objKeysHasDontEnumBug = !({ toString: null }).propertyIsEnumerable("toString");
550
+ var _objKeysDontEnums = [
551
+ "toString",
552
+ "toLocaleString",
553
+ "valueOf",
554
+ "hasOwnProperty",
555
+ "isPrototypeOf",
556
+ "propertyIsEnumerable",
557
+ "constructor"
558
+ ];
559
+ function objKeys(obj) {
560
+ var objType = typeof obj;
561
+ if (objType !== strShimFunction && (objType !== strShimObject || obj === null)) {
562
+ throwTypeError("objKeys called on non-object");
563
+ }
564
+ var result = [];
565
+ for (var prop in obj) {
566
+ if (obj && ObjHasOwnProperty.call(obj, prop)) {
567
+ result.push(prop);
568
+ }
569
+ }
570
+ if (_objKeysHasDontEnumBug) {
571
+ var dontEnumsLength = _objKeysDontEnums.length;
572
+ for (var lp = 0; lp < dontEnumsLength; lp++) {
573
+ if (obj && ObjHasOwnProperty.call(obj, _objKeysDontEnums[lp])) {
574
+ result.push(_objKeysDontEnums[lp]);
575
+ }
576
+ }
577
+ }
578
+ return result;
579
+ }
580
+ function objDefineAccessors(target, prop, getProp, setProp) {
581
+ if (_objDefineProperty) {
582
+ try {
583
+ var descriptor = {
584
+ enumerable: true,
585
+ configurable: true
586
+ };
587
+ if (getProp) {
588
+ descriptor.get = getProp;
589
+ }
590
+ if (setProp) {
591
+ descriptor.set = setProp;
592
+ }
593
+ _objDefineProperty(target, prop, descriptor);
594
+ return true;
595
+ }
596
+ catch (e) {
597
+ }
598
+ }
599
+ return false;
600
+ }
601
+ function dateNow() {
602
+ var dt = Date;
603
+ if (dt.now) {
604
+ return dt.now();
605
+ }
606
+ return new dt().getTime();
607
+ }
608
+ function setValue(target, field, value, valChk, srcChk) {
609
+ var theValue = value;
610
+ if (target) {
611
+ theValue = target[field];
612
+ if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) {
613
+ theValue = value;
614
+ target[field] = theValue;
615
+ }
616
+ }
617
+ return theValue;
618
+ }
619
+ function optimizeObject(theObject) {
620
+ if (theObject) {
621
+ theObject = ObjClass(ObjAssign ? ObjAssign({}, theObject) : theObject);
622
+ }
623
+ return theObject;
624
+ }
625
+
626
+ var strWindow = "window";
627
+ var strDocument = "document";
628
+ var strNavigator = "navigator";
629
+ var strLocation = "location";
630
+ var strConsole = "console";
631
+ var strPerformance = "performance";
632
+ var strJSON = "JSON";
633
+ var strReactNative = "ReactNative";
634
+ var _enableMocks = false;
635
+ var _useXDomainRequest = null;
636
+ var _beaconsSupported = null;
637
+ function _hasProperty(theClass, property) {
638
+ var supported = false;
639
+ if (theClass) {
640
+ try {
641
+ supported = property in theClass;
642
+ if (!supported) {
643
+ var proto = theClass[strShimPrototype];
644
+ if (proto) {
645
+ supported = property in proto;
646
+ }
647
+ }
648
+ }
649
+ catch (e) {
650
+ }
651
+ if (!supported) {
652
+ try {
653
+ var tmp = new theClass();
654
+ supported = !isUndefined(tmp[property]);
655
+ }
656
+ catch (e) {
657
+ }
658
+ }
659
+ }
660
+ return supported;
661
+ }
662
+ function getGlobalInst(name) {
663
+ var gbl = getGlobal();
664
+ if (gbl && gbl[name]) {
665
+ return gbl[name];
666
+ }
667
+ if (name === strWindow && hasWindow()) {
668
+ return window;
669
+ }
670
+ return null;
671
+ }
672
+ function hasWindow() {
673
+ return Boolean(typeof window === strShimObject && window);
674
+ }
675
+ function getWindow() {
676
+ if (hasWindow()) {
677
+ return window;
678
+ }
679
+ return getGlobalInst(strWindow);
680
+ }
681
+ function hasDocument() {
682
+ return Boolean(typeof document === strShimObject && document);
683
+ }
684
+ function getDocument() {
685
+ if (hasDocument()) {
686
+ return document;
687
+ }
688
+ return getGlobalInst(strDocument);
689
+ }
690
+ function hasNavigator() {
691
+ return Boolean(typeof navigator === strShimObject && navigator);
692
+ }
693
+ function getNavigator() {
694
+ if (hasNavigator()) {
695
+ return navigator;
696
+ }
697
+ return getGlobalInst(strNavigator);
698
+ }
699
+ function getLocation(checkForMock) {
700
+ if (checkForMock && _enableMocks) {
701
+ var mockLocation = getGlobalInst("__mockLocation");
702
+ if (mockLocation) {
703
+ return mockLocation;
704
+ }
705
+ }
706
+ if (typeof location === strShimObject && location) {
707
+ return location;
708
+ }
709
+ return getGlobalInst(strLocation);
710
+ }
711
+ function getConsole() {
712
+ if (typeof console !== strShimUndefined) {
713
+ return console;
714
+ }
715
+ return getGlobalInst(strConsole);
716
+ }
717
+ function getPerformance() {
718
+ return getGlobalInst(strPerformance);
719
+ }
720
+ function hasJSON() {
721
+ return Boolean((typeof JSON === strShimObject && JSON) || getGlobalInst(strJSON) !== null);
722
+ }
723
+ function getJSON() {
724
+ if (hasJSON()) {
725
+ return JSON || getGlobalInst(strJSON);
726
+ }
727
+ return null;
728
+ }
729
+ function isReactNative() {
730
+ var nav = getNavigator();
731
+ if (nav && nav.product) {
732
+ return nav.product === strReactNative;
733
+ }
734
+ return false;
735
+ }
736
+ function dumpObj(object) {
737
+ var objectTypeDump = Object[strShimPrototype].toString.call(object);
738
+ var propertyValueDump = "";
739
+ if (objectTypeDump === "[object Error]") {
740
+ propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'";
741
+ }
742
+ else if (hasJSON()) {
743
+ propertyValueDump = getJSON().stringify(object);
744
+ }
745
+ return objectTypeDump + propertyValueDump;
746
+ }
747
+ function isBeaconsSupported() {
748
+ if (_beaconsSupported === null) {
749
+ _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon);
750
+ }
751
+ return _beaconsSupported;
752
+ }
753
+ function isFetchSupported(withKeepAlive) {
754
+ var isSupported = false;
755
+ try {
756
+ var fetchApi = getGlobalInst("fetch");
757
+ isSupported = !!fetchApi;
758
+ var request = getGlobalInst("Request");
759
+ if (isSupported && withKeepAlive && request) {
760
+ isSupported = _hasProperty(request, "keepalive");
761
+ }
762
+ }
763
+ catch (e) {
764
+ }
765
+ return isSupported;
766
+ }
767
+ function useXDomainRequest() {
768
+ if (_useXDomainRequest === null) {
769
+ _useXDomainRequest = (typeof XDomainRequest !== "undefined");
770
+ if (_useXDomainRequest && isXhrSupported()) {
771
+ _useXDomainRequest = _useXDomainRequest && !_hasProperty(getGlobalInst("XMLHttpRequest"), "withCredentials");
772
+ }
773
+ }
774
+ return _useXDomainRequest;
775
+ }
776
+ function isXhrSupported() {
777
+ var isSupported = false;
778
+ try {
779
+ var xmlHttpRequest = getGlobalInst("XMLHttpRequest");
780
+ isSupported = !!xmlHttpRequest;
781
+ }
782
+ catch (e) {
783
+ }
784
+ return isSupported;
785
+ }
786
+
787
+ var _aiNamespace = null;
788
+ function _getExtensionNamespace() {
789
+ var target = getGlobalInst("Microsoft");
790
+ if (target) {
791
+ _aiNamespace = target["ApplicationInsights"];
792
+ }
793
+ return _aiNamespace;
794
+ }
795
+ function getDebugExt(config) {
796
+ var ns = _aiNamespace;
797
+ if (!ns && config.disableDbgExt !== true) {
798
+ ns = _aiNamespace || _getExtensionNamespace();
799
+ }
800
+ return ns ? ns["ChromeDbgExt"] : null;
801
+ }
802
+
803
+ var AiNonUserActionablePrefix = "AI (Internal): ";
804
+ var AiUserActionablePrefix = "AI: ";
805
+ var AIInternalMessagePrefix = "AITR_";
806
+ var strErrorToConsole = "errorToConsole";
807
+ var strWarnToConsole = "warnToConsole";
808
+ function _sanitizeDiagnosticText(text) {
809
+ if (text) {
810
+ return "\"" + text.replace(/\"/g, "") + "\"";
811
+ }
812
+ return "";
813
+ }
814
+ function _logToConsole(func, message) {
815
+ var theConsole = getConsole();
816
+ if (!!theConsole) {
817
+ var logFunc = "log";
818
+ if (theConsole[func]) {
819
+ logFunc = func;
820
+ }
821
+ if (isFunction(theConsole[logFunc])) {
822
+ theConsole[logFunc](message);
823
+ }
824
+ }
825
+ }
826
+ var _InternalLogMessage = /** @class */ (function () {
827
+ function _InternalLogMessage(msgId, msg, isUserAct, properties) {
828
+ if (isUserAct === void 0) { isUserAct = false; }
829
+ var _self = this;
830
+ _self.messageId = msgId;
831
+ _self.message =
832
+ (isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +
833
+ msgId;
834
+ var strProps = "";
835
+ if (hasJSON()) {
836
+ strProps = getJSON().stringify(properties);
837
+ }
838
+ var diagnosticText = (msg ? " message:" + _sanitizeDiagnosticText(msg) : "") +
839
+ (properties ? " props:" + _sanitizeDiagnosticText(strProps) : "");
840
+ _self.message += diagnosticText;
841
+ }
842
+ _InternalLogMessage.dataType = "MessageData";
843
+ return _InternalLogMessage;
844
+ }());
845
+ function safeGetLogger(core, config) {
846
+ return (core || {}).logger || new DiagnosticLogger(config);
847
+ }
848
+ var DiagnosticLogger = /** @class */ (function () {
849
+ function DiagnosticLogger(config) {
850
+ this.identifier = "DiagnosticLogger";
851
+ this.queue = [];
852
+ var _messageCount = 0;
853
+ var _messageLogged = {};
854
+ dynamicProto(DiagnosticLogger, this, function (_self) {
855
+ if (isNullOrUndefined(config)) {
856
+ config = {};
857
+ }
858
+ _self.consoleLoggingLevel = function () { return _getConfigValue("loggingLevelConsole", 0); };
859
+ _self.telemetryLoggingLevel = function () { return _getConfigValue("loggingLevelTelemetry", 1); };
860
+ _self.maxInternalMessageLimit = function () { return _getConfigValue("maxMessageLimit", 25); };
861
+ _self.enableDebugExceptions = function () { return _getConfigValue("enableDebugExceptions", false); };
862
+ _self.throwInternal = function (severity, msgId, msg, properties, isUserAct) {
863
+ if (isUserAct === void 0) { isUserAct = false; }
864
+ var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
865
+ if (_self.enableDebugExceptions()) {
866
+ throw message;
867
+ }
868
+ else {
869
+ var logFunc = severity === LoggingSeverity.CRITICAL ? strErrorToConsole : strWarnToConsole;
870
+ if (!isUndefined(message.message)) {
871
+ var logLevel = _self.consoleLoggingLevel();
872
+ if (isUserAct) {
873
+ var messageKey = +message.messageId;
874
+ if (!_messageLogged[messageKey] && logLevel >= severity) {
875
+ _self[logFunc](message.message);
876
+ _messageLogged[messageKey] = true;
877
+ }
878
+ }
879
+ else {
880
+ if (logLevel >= severity) {
881
+ _self[logFunc](message.message);
882
+ }
883
+ }
884
+ _self.logInternalMessage(severity, message);
885
+ }
886
+ else {
887
+ _debugExtMsg("throw" + (severity === LoggingSeverity.CRITICAL ? "Critical" : "Warning"), message);
888
+ }
889
+ }
890
+ };
891
+ _self.warnToConsole = function (message) {
892
+ _logToConsole("warn", message);
893
+ _debugExtMsg("warning", message);
894
+ };
895
+ _self.errorToConsole = function (message) {
896
+ _logToConsole("error", message);
897
+ _debugExtMsg("error", message);
898
+ };
899
+ _self.resetInternalMessageCount = function () {
900
+ _messageCount = 0;
901
+ _messageLogged = {};
902
+ };
903
+ _self.logInternalMessage = function (severity, message) {
904
+ if (_areInternalMessagesThrottled()) {
905
+ return;
906
+ }
907
+ var logMessage = true;
908
+ var messageKey = AIInternalMessagePrefix + message.messageId;
909
+ if (_messageLogged[messageKey]) {
910
+ logMessage = false;
911
+ }
912
+ else {
913
+ _messageLogged[messageKey] = true;
914
+ }
915
+ if (logMessage) {
916
+ if (severity <= _self.telemetryLoggingLevel()) {
917
+ _self.queue.push(message);
918
+ _messageCount++;
919
+ _debugExtMsg((severity === LoggingSeverity.CRITICAL ? "error" : "warn"), message);
920
+ }
921
+ if (_messageCount === _self.maxInternalMessageLimit()) {
922
+ var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
923
+ var throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
924
+ _self.queue.push(throttleMessage);
925
+ if (severity === LoggingSeverity.CRITICAL) {
926
+ _self.errorToConsole(throttleLimitMessage);
927
+ }
928
+ else {
929
+ _self.warnToConsole(throttleLimitMessage);
930
+ }
931
+ }
932
+ }
933
+ };
934
+ function _getConfigValue(name, defValue) {
935
+ var value = config[name];
936
+ if (!isNullOrUndefined(value)) {
937
+ return value;
938
+ }
939
+ return defValue;
940
+ }
941
+ function _areInternalMessagesThrottled() {
942
+ return _messageCount >= _self.maxInternalMessageLimit();
943
+ }
944
+ function _debugExtMsg(name, data) {
945
+ var dbgExt = getDebugExt(config);
946
+ if (dbgExt && dbgExt.diagLog) {
947
+ dbgExt.diagLog(name, data);
948
+ }
949
+ }
950
+ });
951
+ }
952
+ return DiagnosticLogger;
953
+ }());
954
+
955
+ var strExecutionContextKey = "ctx";
956
+ var PerfEvent = /** @class */ (function () {
957
+ function PerfEvent(name, payloadDetails, isAsync) {
958
+ var _self = this;
959
+ var accessorDefined = false;
960
+ _self.start = dateNow();
961
+ _self.name = name;
962
+ _self.isAsync = isAsync;
963
+ _self.isChildEvt = function () { return false; };
964
+ if (isFunction(payloadDetails)) {
965
+ var theDetails_1;
966
+ accessorDefined = objDefineAccessors(_self, "payload", function () {
967
+ if (!theDetails_1 && isFunction(payloadDetails)) {
968
+ theDetails_1 = payloadDetails();
969
+ payloadDetails = null;
970
+ }
971
+ return theDetails_1;
972
+ });
973
+ }
974
+ _self.getCtx = function (key) {
975
+ if (key) {
976
+ if (key === PerfEvent.ParentContextKey || key === PerfEvent.ChildrenContextKey) {
977
+ return _self[key];
978
+ }
979
+ return (_self[strExecutionContextKey] || {})[key];
980
+ }
981
+ return null;
982
+ };
983
+ _self.setCtx = function (key, value) {
984
+ if (key) {
985
+ if (key === PerfEvent.ParentContextKey) {
986
+ if (!_self[key]) {
987
+ _self.isChildEvt = function () { return true; };
988
+ }
989
+ _self[key] = value;
990
+ }
991
+ else if (key === PerfEvent.ChildrenContextKey) {
992
+ _self[key] = value;
993
+ }
994
+ else {
995
+ var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};
996
+ ctx[key] = value;
997
+ }
998
+ }
999
+ };
1000
+ _self.complete = function () {
1001
+ var childTime = 0;
1002
+ var childEvts = _self.getCtx(PerfEvent.ChildrenContextKey);
1003
+ if (isArray(childEvts)) {
1004
+ for (var lp = 0; lp < childEvts.length; lp++) {
1005
+ var childEvt = childEvts[lp];
1006
+ if (childEvt) {
1007
+ childTime += childEvt.time;
1008
+ }
1009
+ }
1010
+ }
1011
+ _self.time = dateNow() - _self.start;
1012
+ _self.exTime = _self.time - childTime;
1013
+ _self.complete = function () { };
1014
+ if (!accessorDefined && isFunction(payloadDetails)) {
1015
+ _self.payload = payloadDetails();
1016
+ }
1017
+ };
1018
+ }
1019
+ PerfEvent.ParentContextKey = "parent";
1020
+ PerfEvent.ChildrenContextKey = "childEvts";
1021
+ return PerfEvent;
1022
+ }());
1023
+ var doPerfActiveKey = "CoreUtils.doPerf";
1024
+ function doPerf(mgrSource, getSource, func, details, isAsync) {
1025
+ if (mgrSource) {
1026
+ var perfMgr = mgrSource;
1027
+ if (isFunction(perfMgr["getPerfMgr"])) {
1028
+ perfMgr = perfMgr["getPerfMgr"]();
1029
+ }
1030
+ if (perfMgr) {
1031
+ var perfEvt = void 0;
1032
+ var currentActive = perfMgr.getCtx(doPerfActiveKey);
1033
+ try {
1034
+ perfEvt = perfMgr.create(getSource(), details, isAsync);
1035
+ if (perfEvt) {
1036
+ if (currentActive && perfEvt.setCtx) {
1037
+ perfEvt.setCtx(PerfEvent.ParentContextKey, currentActive);
1038
+ if (currentActive.getCtx && currentActive.setCtx) {
1039
+ var children = currentActive.getCtx(PerfEvent.ChildrenContextKey);
1040
+ if (!children) {
1041
+ children = [];
1042
+ currentActive.setCtx(PerfEvent.ChildrenContextKey, children);
1043
+ }
1044
+ children.push(perfEvt);
1045
+ }
1046
+ }
1047
+ perfMgr.setCtx(doPerfActiveKey, perfEvt);
1048
+ return func(perfEvt);
1049
+ }
1050
+ }
1051
+ catch (ex) {
1052
+ if (perfEvt && perfEvt.setCtx) {
1053
+ perfEvt.setCtx("exception", ex);
1054
+ }
1055
+ }
1056
+ finally {
1057
+ if (perfEvt) {
1058
+ perfMgr.fire(perfEvt);
1059
+ }
1060
+ perfMgr.setCtx(doPerfActiveKey, currentActive);
1061
+ }
1062
+ }
1063
+ }
1064
+ return func();
1065
+ }
1066
+
1067
+ var TelemetryPluginChain = /** @class */ (function () {
1068
+ function TelemetryPluginChain(plugin, defItemCtx) {
1069
+ var _self = this;
1070
+ var _nextProxy = null;
1071
+ var _hasProcessTelemetry = isFunction(plugin.processTelemetry);
1072
+ var _hasSetNext = isFunction(plugin.setNextPlugin);
1073
+ _self._hasRun = false;
1074
+ _self.getPlugin = function () {
1075
+ return plugin;
1076
+ };
1077
+ _self.getNext = function () {
1078
+ return _nextProxy;
1079
+ };
1080
+ _self.setNext = function (nextPlugin) {
1081
+ _nextProxy = nextPlugin;
1082
+ };
1083
+ _self.processTelemetry = function (env, itemCtx) {
1084
+ if (!itemCtx) {
1085
+ itemCtx = defItemCtx;
1086
+ }
1087
+ var identifier = plugin ? plugin.identifier : "TelemetryPluginChain";
1088
+ doPerf(itemCtx ? itemCtx.core() : null, function () { return identifier + ":processTelemetry"; }, function () {
1089
+ if (plugin && _hasProcessTelemetry) {
1090
+ _self._hasRun = true;
1091
+ try {
1092
+ itemCtx.setNext(_nextProxy);
1093
+ if (_hasSetNext) {
1094
+ plugin.setNextPlugin(_nextProxy);
1095
+ }
1096
+ _nextProxy && (_nextProxy._hasRun = false);
1097
+ plugin.processTelemetry(env, itemCtx);
1098
+ }
1099
+ catch (error) {
1100
+ var hasRun = _nextProxy && _nextProxy._hasRun;
1101
+ if (!_nextProxy || !hasRun) {
1102
+ itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.PluginException, "Plugin [" + plugin.identifier + "] failed during processTelemetry - " + dumpObj(error));
1103
+ }
1104
+ if (_nextProxy && !hasRun) {
1105
+ _nextProxy.processTelemetry(env, itemCtx);
1106
+ }
1107
+ }
1108
+ }
1109
+ else if (_nextProxy) {
1110
+ _self._hasRun = true;
1111
+ _nextProxy.processTelemetry(env, itemCtx);
1112
+ }
1113
+ }, function () { return ({ item: env }); }, !(env.sync));
1114
+ };
1115
+ }
1116
+ return TelemetryPluginChain;
1117
+ }());
1118
+
1119
+ function _createProxyChain(plugins, itemCtx) {
1120
+ var proxies = [];
1121
+ if (plugins && plugins.length > 0) {
1122
+ var lastProxy = null;
1123
+ for (var idx = 0; idx < plugins.length; idx++) {
1124
+ var thePlugin = plugins[idx];
1125
+ if (thePlugin && isFunction(thePlugin.processTelemetry)) {
1126
+ var newProxy = new TelemetryPluginChain(thePlugin, itemCtx);
1127
+ proxies.push(newProxy);
1128
+ if (lastProxy) {
1129
+ lastProxy.setNext(newProxy);
1130
+ }
1131
+ lastProxy = newProxy;
1132
+ }
1133
+ }
1134
+ }
1135
+ return proxies.length > 0 ? proxies[0] : null;
1136
+ }
1137
+ function _copyProxyChain(proxy, itemCtx, startAt) {
1138
+ var plugins = [];
1139
+ var add = startAt ? false : true;
1140
+ if (proxy) {
1141
+ while (proxy) {
1142
+ var thePlugin = proxy.getPlugin();
1143
+ if (add || thePlugin === startAt) {
1144
+ add = true;
1145
+ plugins.push(thePlugin);
1146
+ }
1147
+ proxy = proxy.getNext();
1148
+ }
1149
+ }
1150
+ if (!add) {
1151
+ plugins.push(startAt);
1152
+ }
1153
+ return _createProxyChain(plugins, itemCtx);
1154
+ }
1155
+ function _copyPluginChain(srcPlugins, itemCtx, startAt) {
1156
+ var plugins = srcPlugins;
1157
+ var add = false;
1158
+ if (startAt && srcPlugins) {
1159
+ plugins = [];
1160
+ arrForEach(srcPlugins, function (thePlugin) {
1161
+ if (add || thePlugin === startAt) {
1162
+ add = true;
1163
+ plugins.push(thePlugin);
1164
+ }
1165
+ });
1166
+ }
1167
+ if (startAt && !add) {
1168
+ if (!plugins) {
1169
+ plugins = [];
1170
+ }
1171
+ plugins.push(startAt);
1172
+ }
1173
+ return _createProxyChain(plugins, itemCtx);
1174
+ }
1175
+ var ProcessTelemetryContext = /** @class */ (function () {
1176
+ function ProcessTelemetryContext(plugins, config, core, startAt) {
1177
+ var _self = this;
1178
+ var _nextProxy = null;
1179
+ if (startAt !== null) {
1180
+ if (plugins && isFunction(plugins.getPlugin)) {
1181
+ _nextProxy = _copyProxyChain(plugins, _self, startAt || plugins.getPlugin());
1182
+ }
1183
+ else {
1184
+ if (startAt) {
1185
+ _nextProxy = _copyPluginChain(plugins, _self, startAt);
1186
+ }
1187
+ else if (isUndefined(startAt)) {
1188
+ _nextProxy = _createProxyChain(plugins, _self);
1189
+ }
1190
+ }
1191
+ }
1192
+ _self.core = function () {
1193
+ return core;
1194
+ };
1195
+ _self.diagLog = function () {
1196
+ return safeGetLogger(core, config);
1197
+ };
1198
+ _self.getCfg = function () {
1199
+ return config;
1200
+ };
1201
+ _self.getExtCfg = function (identifier, defaultValue) {
1202
+ if (defaultValue === void 0) { defaultValue = {}; }
1203
+ var theConfig;
1204
+ if (config) {
1205
+ var extConfig = config.extensionConfig;
1206
+ if (extConfig && identifier) {
1207
+ theConfig = extConfig[identifier];
1208
+ }
1209
+ }
1210
+ return (theConfig ? theConfig : defaultValue);
1211
+ };
1212
+ _self.getConfig = function (identifier, field, defaultValue) {
1213
+ if (defaultValue === void 0) { defaultValue = false; }
1214
+ var theValue;
1215
+ var extConfig = _self.getExtCfg(identifier, null);
1216
+ if (extConfig && !isNullOrUndefined(extConfig[field])) {
1217
+ theValue = extConfig[field];
1218
+ }
1219
+ else if (config && !isNullOrUndefined(config[field])) {
1220
+ theValue = config[field];
1221
+ }
1222
+ return !isNullOrUndefined(theValue) ? theValue : defaultValue;
1223
+ };
1224
+ _self.hasNext = function () {
1225
+ return _nextProxy != null;
1226
+ };
1227
+ _self.getNext = function () {
1228
+ return _nextProxy;
1229
+ };
1230
+ _self.setNext = function (nextPlugin) {
1231
+ _nextProxy = nextPlugin;
1232
+ };
1233
+ _self.processNext = function (env) {
1234
+ var nextPlugin = _nextProxy;
1235
+ if (nextPlugin) {
1236
+ _nextProxy = nextPlugin.getNext();
1237
+ nextPlugin.processTelemetry(env, _self);
1238
+ }
1239
+ };
1240
+ _self.createNew = function (plugins, startAt) {
1241
+ if (plugins === void 0) { plugins = null; }
1242
+ return new ProcessTelemetryContext(plugins || _nextProxy, config, core, startAt);
1243
+ };
1244
+ }
1245
+ return ProcessTelemetryContext;
1246
+ }());
1247
+
1248
+ var strExtensionConfig = "extensionConfig";
1249
+
1250
+ var strGetPlugin = "getPlugin";
1251
+ var BaseTelemetryPlugin = /** @class */ (function () {
1252
+ function BaseTelemetryPlugin() {
1253
+ var _self = this;
1254
+ var _isinitialized = false;
1255
+ var _rootCtx = null;
1256
+ var _nextPlugin = null;
1257
+ _self.core = null;
1258
+ _self.diagLog = function (itemCtx) {
1259
+ return _self._getTelCtx(itemCtx).diagLog();
1260
+ };
1261
+ _self.isInitialized = function () {
1262
+ return _isinitialized;
1263
+ };
1264
+ _self.setInitialized = function (isInitialized) {
1265
+ _isinitialized = isInitialized;
1266
+ };
1267
+ _self.setNextPlugin = function (next) {
1268
+ _nextPlugin = next;
1269
+ };
1270
+ _self.processNext = function (env, itemCtx) {
1271
+ if (itemCtx) {
1272
+ itemCtx.processNext(env);
1273
+ }
1274
+ else if (_nextPlugin && isFunction(_nextPlugin.processTelemetry)) {
1275
+ _nextPlugin.processTelemetry(env, null);
1276
+ }
1277
+ };
1278
+ _self._getTelCtx = function (currentCtx) {
1279
+ if (currentCtx === void 0) { currentCtx = null; }
1280
+ var itemCtx = currentCtx;
1281
+ if (!itemCtx) {
1282
+ var rootCtx = _rootCtx || new ProcessTelemetryContext(null, {}, _self.core);
1283
+ if (_nextPlugin && _nextPlugin[strGetPlugin]) {
1284
+ itemCtx = rootCtx.createNew(null, _nextPlugin[strGetPlugin]);
1285
+ }
1286
+ else {
1287
+ itemCtx = rootCtx.createNew(null, _nextPlugin);
1288
+ }
1289
+ }
1290
+ return itemCtx;
1291
+ };
1292
+ _self._baseTelInit = function (config, core, extensions, pluginChain) {
1293
+ if (config) {
1294
+ setValue(config, strExtensionConfig, [], null, isNullOrUndefined);
1295
+ }
1296
+ if (!pluginChain && core) {
1297
+ pluginChain = core.getProcessTelContext().getNext();
1298
+ }
1299
+ var nextPlugin = _nextPlugin;
1300
+ if (_nextPlugin && _nextPlugin[strGetPlugin]) {
1301
+ nextPlugin = _nextPlugin[strGetPlugin]();
1302
+ }
1303
+ _self.core = core;
1304
+ _rootCtx = new ProcessTelemetryContext(pluginChain, config, core, nextPlugin);
1305
+ _isinitialized = true;
1306
+ };
1307
+ }
1308
+ BaseTelemetryPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {
1309
+ this._baseTelInit(config, core, extensions, pluginChain);
1310
+ };
1311
+ return BaseTelemetryPlugin;
1312
+ }());
1313
+
1314
+ var strVisibilityChangeEvt = "visibilitychange";
1315
+ var strPageHide = "pagehide";
1316
+ var strPageShow = "pageshow";
1317
+ function addEventHandler(eventName, callback) {
1318
+ var result = false;
1319
+ var w = getWindow();
1320
+ if (w) {
1321
+ result = attachEvent(w, eventName, callback);
1322
+ result = attachEvent(w["body"], eventName, callback) || result;
1323
+ }
1324
+ var doc = getDocument();
1325
+ if (doc) {
1326
+ result = attachEvent(doc, eventName, callback) || result;
1327
+ }
1328
+ return result;
1329
+ }
1330
+ function addEventListeners(events, listener, excludeEvents) {
1331
+ var added = false;
1332
+ if (listener && events && isArray(events)) {
1333
+ var excluded_1 = [];
1334
+ arrForEach(events, function (name) {
1335
+ if (isString(name)) {
1336
+ if (!excludeEvents || arrIndexOf(excludeEvents, name) === -1) {
1337
+ added = addEventHandler(name, listener) || added;
1338
+ }
1339
+ else {
1340
+ excluded_1.push(name);
1341
+ }
1342
+ }
1343
+ });
1344
+ if (!added && excluded_1.length > 0) {
1345
+ added = addEventListeners(excluded_1, listener);
1346
+ }
1347
+ }
1348
+ return added;
1349
+ }
1350
+ function addPageUnloadEventListener(listener, excludeEvents) {
1351
+ return addEventListeners(["beforeunload", "unload", "pagehide"], listener, excludeEvents);
1352
+ }
1353
+ function addPageHideEventListener(listener, excludeEvents) {
1354
+ function _handlePageVisibility(evt) {
1355
+ var doc = getDocument();
1356
+ if (listener && doc && doc.visibilityState === "hidden") {
1357
+ listener(evt);
1358
+ }
1359
+ }
1360
+ var pageUnloadAdded = false;
1361
+ if (!excludeEvents || arrIndexOf(excludeEvents, strPageHide) === -1) {
1362
+ pageUnloadAdded = addEventHandler(strPageHide, listener);
1363
+ }
1364
+ if (!excludeEvents || arrIndexOf(excludeEvents, strVisibilityChangeEvt) === -1) {
1365
+ pageUnloadAdded = addEventHandler(strVisibilityChangeEvt, _handlePageVisibility) || pageUnloadAdded;
1366
+ }
1367
+ if (!pageUnloadAdded && excludeEvents) {
1368
+ pageUnloadAdded = addPageHideEventListener(listener);
1369
+ }
1370
+ return pageUnloadAdded;
1371
+ }
1372
+ function addPageShowEventListener(listener, excludeEvents) {
1373
+ function _handlePageVisibility(evt) {
1374
+ var doc = getDocument();
1375
+ if (listener && doc && doc.visibilityState === "visible") {
1376
+ listener(evt);
1377
+ }
1378
+ }
1379
+ var pageShowAdded = false;
1380
+ if (!excludeEvents || arrIndexOf(excludeEvents, strPageShow) === -1) {
1381
+ pageShowAdded = addEventHandler(strPageShow, listener);
1382
+ }
1383
+ if (!excludeEvents || arrIndexOf(excludeEvents, strVisibilityChangeEvt) === -1) {
1384
+ pageShowAdded = addEventHandler(strVisibilityChangeEvt, _handlePageVisibility) || pageShowAdded;
1385
+ }
1386
+ if (!pageShowAdded && excludeEvents) {
1387
+ pageShowAdded = addPageShowEventListener(listener);
1388
+ }
1389
+ return pageShowAdded;
1390
+ }
1391
+ function perfNow() {
1392
+ var perf = getPerformance();
1393
+ if (perf && perf.now) {
1394
+ return perf.now();
1395
+ }
1396
+ return dateNow();
1397
+ }
1398
+
1399
+ var ValueKind = {
1400
+ NotSet: 0,
1401
+ Pii_DistinguishedName: 1,
1402
+ Pii_GenericData: 2,
1403
+ Pii_IPV4Address: 3,
1404
+ Pii_IPv6Address: 4,
1405
+ Pii_MailSubject: 5,
1406
+ Pii_PhoneNumber: 6,
1407
+ Pii_QueryString: 7,
1408
+ Pii_SipAddress: 8,
1409
+ Pii_SmtpAddress: 9,
1410
+ Pii_Identity: 10,
1411
+ Pii_Uri: 11,
1412
+ Pii_Fqdn: 12,
1413
+ Pii_IPV4AddressLegacy: 13,
1414
+ CustomerContent_GenericContent: 32
1415
+ };
1416
+ var EventLatency = {
1417
+ Normal: 1 ,
1418
+ CostDeferred: 2 ,
1419
+ RealTime: 3 ,
1420
+ Immediate: 4
1421
+ };
1422
+ var EventPropertyType = {
1423
+ Unspecified: 0,
1424
+ String: 1,
1425
+ Int32: 2,
1426
+ UInt32: 3,
1427
+ Int64: 4,
1428
+ UInt64: 5,
1429
+ Double: 6,
1430
+ Bool: 7,
1431
+ Guid: 8,
1432
+ DateTime: 9
1433
+ };
1434
+ var _ExtendedInternalMessageId = __assignFn(__assignFn({}, _InternalMessageId), { AuthHandShakeError: 501, AuthRedirectFail: 502, BrowserCannotReadLocalStorage: 503, BrowserCannotWriteLocalStorage: 504, BrowserDoesNotSupportLocalStorage: 505, CannotParseBiBlobValue: 506, CannotParseDataAttribute: 507, CVPluginNotAvailable: 508, DroppedEvent: 509, ErrorParsingAISessionCookie: 510, ErrorProvidedChannels: 511, FailedToGetCookies: 512, FailedToInitializeCorrelationVector: 513, FailedToInitializeSDK: 514, InvalidContentBlob: 515, InvalidCorrelationValue: 516, SessionRenewalDateIsZero: 517, SendPostOnCompleteFailure: 518, PostResponseHandler: 519, SDKNotInitialized: 520 });
1435
+
1436
+ var _a$1;
1437
+ var Version = '3.1.10';
1438
+ var FullVersionString = "1DS-Web-JS-" + Version;
1439
+ var strDisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation";
1440
+ var strWithCredentials = "withCredentials";
1441
+ var _fieldTypeEventPropMap = (_a$1 = {},
1442
+ _a$1[0 ] = EventPropertyType.Unspecified,
1443
+ _a$1[2 ] = EventPropertyType.Double,
1444
+ _a$1[1 ] = EventPropertyType.String,
1445
+ _a$1[3 ] = EventPropertyType.Bool,
1446
+ _a$1[4096 | 2 ] = EventPropertyType.Double,
1447
+ _a$1[4096 | 1 ] = EventPropertyType.String,
1448
+ _a$1[4096 | 3 ] = EventPropertyType.Bool,
1449
+ _a$1);
1450
+ Boolean(getDocument());
1451
+ var isWindowObjectAvailable = Boolean(getWindow());
1452
+ function isValueAssigned(value) {
1453
+ return !(value === "" || isNullOrUndefined(value));
1454
+ }
1455
+ function getTenantId(apiKey) {
1456
+ if (apiKey) {
1457
+ var indexTenantId = apiKey.indexOf("-");
1458
+ if (indexTenantId > -1) {
1459
+ return apiKey.substring(0, indexTenantId);
1460
+ }
1461
+ }
1462
+ return "";
1463
+ }
1464
+ function sanitizeProperty(name, property, stringifyObjects) {
1465
+ if ((!property && !isValueAssigned(property)) || typeof name !== "string") {
1466
+ return null;
1467
+ }
1468
+ var propType = typeof property;
1469
+ if (propType === "string" || propType === "number" || propType === "boolean" || isArray(property)) {
1470
+ property = { value: property };
1471
+ }
1472
+ else if (propType === "object" && !property.hasOwnProperty("value")) {
1473
+ property = { value: stringifyObjects ? JSON.stringify(property) : property };
1474
+ }
1475
+ else if (isNullOrUndefined(property.value)
1476
+ || property.value === "" || (!isString(property.value)
1477
+ && !isNumber(property.value) && !isBoolean(property.value)
1478
+ && !isArray(property.value))) {
1479
+ return null;
1480
+ }
1481
+ if (isArray(property.value) &&
1482
+ !isArrayValid(property.value)) {
1483
+ return null;
1484
+ }
1485
+ if (!isNullOrUndefined(property.kind)) {
1486
+ if (isArray(property.value) || !isValueKind(property.kind)) {
1487
+ return null;
1488
+ }
1489
+ property.value = property.value.toString();
1490
+ }
1491
+ return property;
1492
+ }
1493
+ function getCommonSchemaMetaData(value, kind, type) {
1494
+ var encodedTypeValue = -1;
1495
+ if (!isUndefined(value)) {
1496
+ if (kind > 0) {
1497
+ if (kind === 32) {
1498
+ encodedTypeValue = (1 << 13);
1499
+ }
1500
+ else if (kind <= 13) {
1501
+ encodedTypeValue = (kind << 5);
1502
+ }
1503
+ }
1504
+ if (isDataType(type)) {
1505
+ if (encodedTypeValue === -1) {
1506
+ encodedTypeValue = 0;
1507
+ }
1508
+ encodedTypeValue |= type;
1509
+ }
1510
+ else {
1511
+ var propType = _fieldTypeEventPropMap[getFieldValueType(value)] || -1;
1512
+ if (encodedTypeValue !== -1 && propType !== -1) {
1513
+ encodedTypeValue |= propType;
1514
+ }
1515
+ else if (propType === EventPropertyType.Double) {
1516
+ encodedTypeValue = propType;
1517
+ }
1518
+ }
1519
+ }
1520
+ return encodedTypeValue;
1521
+ }
1522
+ function extend(obj, obj2, obj3, obj4, obj5) {
1523
+ var extended = {};
1524
+ var deep = false;
1525
+ var i = 0;
1526
+ var length = arguments.length;
1527
+ var objProto = Object[strShimPrototype];
1528
+ var theArgs = arguments;
1529
+ if (objProto.toString.call(theArgs[0]) === "[object Boolean]") {
1530
+ deep = theArgs[0];
1531
+ i++;
1532
+ }
1533
+ for (; i < length; i++) {
1534
+ var obj = theArgs[i];
1535
+ objForEachKey(obj, function (prop, value) {
1536
+ if (deep && value && isObject(value)) {
1537
+ if (isArray(value)) {
1538
+ extended[prop] = extended[prop] || [];
1539
+ arrForEach(value, function (arrayValue, arrayIndex) {
1540
+ if (arrayValue && isObject(arrayValue)) {
1541
+ extended[prop][arrayIndex] = extend(true, extended[prop][arrayIndex], arrayValue);
1542
+ }
1543
+ else {
1544
+ extended[prop][arrayIndex] = arrayValue;
1545
+ }
1546
+ });
1547
+ }
1548
+ else {
1549
+ extended[prop] = extend(true, extended[prop], value);
1550
+ }
1551
+ }
1552
+ else {
1553
+ extended[prop] = value;
1554
+ }
1555
+ });
1556
+ }
1557
+ return extended;
1558
+ }
1559
+ var getTime = perfNow;
1560
+ function isValueKind(value) {
1561
+ if (value === ValueKind.NotSet || ((value > ValueKind.NotSet && value <= ValueKind.Pii_IPV4AddressLegacy) || value === ValueKind.CustomerContent_GenericContent)) {
1562
+ return true;
1563
+ }
1564
+ return false;
1565
+ }
1566
+ function isDataType(value) {
1567
+ if (value >= 0 && value <= 9) {
1568
+ return true;
1569
+ }
1570
+ return false;
1571
+ }
1572
+ function isArrayValid(value) {
1573
+ return value.length > 0;
1574
+ }
1575
+ function setProcessTelemetryTimings(event, identifier) {
1576
+ var evt = event;
1577
+ evt.timings = evt.timings || {};
1578
+ evt.timings.processTelemetryStart = evt.timings.processTelemetryStart || {};
1579
+ evt.timings.processTelemetryStart[identifier] = getTime();
1580
+ }
1581
+ function getFieldValueType(value) {
1582
+ var theType = 0 ;
1583
+ if (value !== null && value !== undefined) {
1584
+ var objType = typeof value;
1585
+ if (objType === "string") {
1586
+ theType = 1 ;
1587
+ }
1588
+ else if (objType === "number") {
1589
+ theType = 2 ;
1590
+ }
1591
+ else if (objType === "boolean") {
1592
+ theType = 3 ;
1593
+ }
1594
+ else if (objType === strShimObject) {
1595
+ theType = 4 ;
1596
+ if (isArray(value)) {
1597
+ theType = 4096 ;
1598
+ if (value.length > 0) {
1599
+ theType |= getFieldValueType(value[0]);
1600
+ }
1601
+ }
1602
+ else if (hasOwnProperty(value, "value")) {
1603
+ theType = 8192 | getFieldValueType(value.value);
1604
+ }
1605
+ }
1606
+ }
1607
+ return theType;
1608
+ }
1609
+ function isChromium() {
1610
+ return !!getGlobalInst("chrome");
1611
+ }
1612
+ function openXhr(method, urlString, withCredentials, disabled, isSync) {
1613
+ if (disabled === void 0) { disabled = false; }
1614
+ if (isSync === void 0) { isSync = false; }
1615
+ function _wrapSetXhrProp(xhr, prop, value) {
1616
+ try {
1617
+ xhr[prop] = value;
1618
+ }
1619
+ catch (e) {
1620
+ }
1621
+ }
1622
+ var xhr = new XMLHttpRequest();
1623
+ if (disabled) {
1624
+ _wrapSetXhrProp(xhr, strDisabledPropertyName, disabled);
1625
+ }
1626
+ if (withCredentials) {
1627
+ _wrapSetXhrProp(xhr, strWithCredentials, withCredentials);
1628
+ }
1629
+ xhr.open(method, urlString, !isSync);
1630
+ if (withCredentials) {
1631
+ _wrapSetXhrProp(xhr, strWithCredentials, withCredentials);
1632
+ }
1633
+ return xhr;
1634
+ }
1635
+
1636
+ var RT_PROFILE = "REAL_TIME";
1637
+ var NRT_PROFILE = "NEAR_REAL_TIME";
1638
+ var BE_PROFILE = "BEST_EFFORT";
1639
+
1640
+ var Method = "POST";
1641
+ var DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation";
1642
+ var strDropped = "drop";
1643
+ var strSending = "send";
1644
+ var strRequeue = "requeue";
1645
+ var strResponseFail = "rspFail";
1646
+ var strOther = "oth";
1647
+ var defaultCacheControl = "no-cache, no-store";
1648
+ var defaultContentType = "application/x-json-stream";
1649
+ var strCacheControl = "cache-control";
1650
+ var strContentTypeHeader = "content-type";
1651
+ var strKillTokensHeader = "kill-tokens";
1652
+ var strKillDurationHeader = "kill-duration";
1653
+ var strKillDurationSecondsHeader = "kill-duration-seconds";
1654
+ var strTimeDeltaHeader = "time-delta-millis";
1655
+ var strClientVersion = "client-version";
1656
+ var strClientId = "client-id";
1657
+ var strTimeDeltaToApply = "time-delta-to-apply-millis";
1658
+ var strUploadTime = "upload-time";
1659
+ var strApiKey = "apikey";
1660
+ var strMsaDeviceTicket = "AuthMsaDeviceTicket";
1661
+ var strMsfpc = "msfpc";
1662
+
1663
+ function _getEventMsfpc(theEvent) {
1664
+ var intWeb = ((theEvent.ext || {})["intweb"]);
1665
+ if (intWeb && isValueAssigned(intWeb[strMsfpc])) {
1666
+ return intWeb[strMsfpc];
1667
+ }
1668
+ return null;
1669
+ }
1670
+ function _getMsfpc(theEvents) {
1671
+ var msfpc = null;
1672
+ for (var lp = 0; msfpc === null && lp < theEvents.length; lp++) {
1673
+ msfpc = _getEventMsfpc(theEvents[lp]);
1674
+ }
1675
+ return msfpc;
1676
+ }
1677
+ var EventBatch = /** @class */ (function () {
1678
+ function EventBatch(iKey, addEvents) {
1679
+ var events = addEvents ? [].concat(addEvents) : [];
1680
+ var _self = this;
1681
+ var _msfpc = _getMsfpc(events);
1682
+ _self.iKey = function () {
1683
+ return iKey;
1684
+ };
1685
+ _self.Msfpc = function () {
1686
+ return _msfpc || "";
1687
+ };
1688
+ _self.count = function () {
1689
+ return events.length;
1690
+ };
1691
+ _self.events = function () {
1692
+ return events;
1693
+ };
1694
+ _self.addEvent = function (theEvent) {
1695
+ if (theEvent) {
1696
+ events.push(theEvent);
1697
+ if (!_msfpc) {
1698
+ _msfpc = _getEventMsfpc(theEvent);
1699
+ }
1700
+ return true;
1701
+ }
1702
+ return false;
1703
+ };
1704
+ _self.split = function (fromEvent, numEvents) {
1705
+ var theEvents;
1706
+ if (fromEvent < events.length) {
1707
+ var cnt = events.length - fromEvent;
1708
+ if (!isNullOrUndefined(numEvents)) {
1709
+ cnt = numEvents < cnt ? numEvents : cnt;
1710
+ }
1711
+ theEvents = events.splice(fromEvent, cnt);
1712
+ _msfpc = _getMsfpc(events);
1713
+ }
1714
+ return new EventBatch(iKey, theEvents);
1715
+ };
1716
+ }
1717
+ EventBatch.create = function (iKey, theEvents) {
1718
+ return new EventBatch(iKey, theEvents);
1719
+ };
1720
+ return EventBatch;
1721
+ }());
1722
+
1723
+ var _MAX_STRING_JOINS = 20;
1724
+ var RequestSizeLimitBytes = 3984588;
1725
+ var BeaconRequestSizeLimitBytes = 65000;
1726
+ var MaxRecordSize = 2000000;
1727
+ var MaxBeaconRecordSize = Math.min(MaxRecordSize, BeaconRequestSizeLimitBytes);
1728
+ var metadata = "metadata";
1729
+ var f = "f";
1730
+ var rCheckDot = /\./;
1731
+ var Serializer = /** @class */ (function () {
1732
+ function Serializer(perfManager, valueSanitizer, stringifyObjects, enableCompoundKey) {
1733
+ var strData = "data";
1734
+ var strBaseData = "baseData";
1735
+ var strExt = "ext";
1736
+ var _checkForCompoundkey = !!enableCompoundKey;
1737
+ var _processSubMetaData = true;
1738
+ var _theSanitizer = valueSanitizer;
1739
+ var _isReservedCache = {};
1740
+ dynamicProto(Serializer, this, function (_self) {
1741
+ _self.createPayload = function (retryCnt, isTeardown, isSync, useSendBeacon, sendReason, sendType) {
1742
+ return {
1743
+ apiKeys: [],
1744
+ payloadBlob: "",
1745
+ overflow: null,
1746
+ sizeExceed: [],
1747
+ failedEvts: [],
1748
+ batches: [],
1749
+ numEvents: 0,
1750
+ retryCnt: retryCnt,
1751
+ isTeardown: isTeardown,
1752
+ isSync: isSync,
1753
+ isBeacon: useSendBeacon,
1754
+ sendType: sendType,
1755
+ sendReason: sendReason
1756
+ };
1757
+ };
1758
+ _self.appendPayload = function (payload, theBatch, maxEventsPerBatch) {
1759
+ var canAddEvents = payload && theBatch && !payload.overflow;
1760
+ if (canAddEvents) {
1761
+ doPerf(perfManager, function () { return "Serializer:appendPayload"; }, function () {
1762
+ var theEvents = theBatch.events();
1763
+ var payloadBlob = payload.payloadBlob;
1764
+ var payloadEvents = payload.numEvents;
1765
+ var eventsAdded = false;
1766
+ var sizeExceeded = [];
1767
+ var failedEvts = [];
1768
+ var isBeaconPayload = payload.isBeacon;
1769
+ var requestMaxSize = isBeaconPayload ? BeaconRequestSizeLimitBytes : RequestSizeLimitBytes;
1770
+ var recordMaxSize = isBeaconPayload ? MaxBeaconRecordSize : MaxRecordSize;
1771
+ var lp = 0;
1772
+ var joinCount = 0;
1773
+ while (lp < theEvents.length) {
1774
+ var theEvent = theEvents[lp];
1775
+ if (theEvent) {
1776
+ if (payloadEvents >= maxEventsPerBatch) {
1777
+ payload.overflow = theBatch.split(lp);
1778
+ break;
1779
+ }
1780
+ var eventBlob = _self.getEventBlob(theEvent);
1781
+ if (eventBlob && eventBlob.length <= recordMaxSize) {
1782
+ var blobLength = eventBlob.length;
1783
+ var currentSize = payloadBlob.length;
1784
+ if (currentSize + blobLength > requestMaxSize) {
1785
+ payload.overflow = theBatch.split(lp);
1786
+ break;
1787
+ }
1788
+ if (payloadBlob) {
1789
+ payloadBlob += "\n";
1790
+ }
1791
+ payloadBlob += eventBlob;
1792
+ joinCount++;
1793
+ if (joinCount > _MAX_STRING_JOINS) {
1794
+ payloadBlob.substr(0, 1);
1795
+ joinCount = 0;
1796
+ }
1797
+ eventsAdded = true;
1798
+ payloadEvents++;
1799
+ }
1800
+ else {
1801
+ if (eventBlob) {
1802
+ sizeExceeded.push(theEvent);
1803
+ }
1804
+ else {
1805
+ failedEvts.push(theEvent);
1806
+ }
1807
+ theEvents.splice(lp, 1);
1808
+ lp--;
1809
+ }
1810
+ }
1811
+ lp++;
1812
+ }
1813
+ if (sizeExceeded && sizeExceeded.length > 0) {
1814
+ payload.sizeExceed.push(EventBatch.create(theBatch.iKey(), sizeExceeded));
1815
+ }
1816
+ if (failedEvts && failedEvts.length > 0) {
1817
+ payload.failedEvts.push(EventBatch.create(theBatch.iKey(), failedEvts));
1818
+ }
1819
+ if (eventsAdded) {
1820
+ payload.batches.push(theBatch);
1821
+ payload.payloadBlob = payloadBlob;
1822
+ payload.numEvents = payloadEvents;
1823
+ var apiKey = theBatch.iKey();
1824
+ if (arrIndexOf(payload.apiKeys, apiKey) === -1) {
1825
+ payload.apiKeys.push(apiKey);
1826
+ }
1827
+ }
1828
+ }, function () { return ({ payload: payload, theBatch: { iKey: theBatch.iKey(), evts: theBatch.events() }, max: maxEventsPerBatch }); });
1829
+ }
1830
+ return canAddEvents;
1831
+ };
1832
+ _self.getEventBlob = function (eventData) {
1833
+ try {
1834
+ return doPerf(perfManager, function () { return "Serializer.getEventBlob"; }, function () {
1835
+ var serializedEvent = {};
1836
+ serializedEvent.name = eventData.name;
1837
+ serializedEvent.time = eventData.time;
1838
+ serializedEvent.ver = eventData.ver;
1839
+ serializedEvent.iKey = "o:" + getTenantId(eventData.iKey);
1840
+ var serializedExt = {};
1841
+ var eventExt = eventData[strExt];
1842
+ if (eventExt) {
1843
+ serializedEvent[strExt] = serializedExt;
1844
+ objForEachKey(eventExt, function (key, value) {
1845
+ var data = serializedExt[key] = {};
1846
+ _processPathKeys(value, data, "ext." + key, true, null, null, true);
1847
+ });
1848
+ }
1849
+ var serializedData = serializedEvent[strData] = {};
1850
+ serializedData.baseType = eventData.baseType;
1851
+ var serializedBaseData = serializedData[strBaseData] = {};
1852
+ _processPathKeys(eventData.baseData, serializedBaseData, strBaseData, false, [strBaseData], function (pathKeys, name, value) {
1853
+ _addJSONPropertyMetaData(serializedExt, pathKeys, name, value);
1854
+ }, _processSubMetaData);
1855
+ _processPathKeys(eventData.data, serializedData, strData, false, [], function (pathKeys, name, value) {
1856
+ _addJSONPropertyMetaData(serializedExt, pathKeys, name, value);
1857
+ }, _processSubMetaData);
1858
+ return JSON.stringify(serializedEvent);
1859
+ }, function () { return ({ item: eventData }); });
1860
+ }
1861
+ catch (e) {
1862
+ return null;
1863
+ }
1864
+ };
1865
+ function _isReservedField(path, name) {
1866
+ var result = _isReservedCache[path];
1867
+ if (result === undefined) {
1868
+ if (path.length >= 7) {
1869
+ result = strStartsWith(path, "ext.metadata") || strStartsWith(path, "ext.web");
1870
+ }
1871
+ _isReservedCache[path] = result;
1872
+ }
1873
+ return result;
1874
+ }
1875
+ function _processPathKeys(srcObj, target, thePath, checkReserved, metadataPathKeys, metadataCallback, processSubKeys) {
1876
+ objForEachKey(srcObj, function (key, srcValue) {
1877
+ var prop = null;
1878
+ if (srcValue || isValueAssigned(srcValue)) {
1879
+ var path = thePath;
1880
+ var name_1 = key;
1881
+ var theMetaPathKeys = metadataPathKeys;
1882
+ var destObj = target;
1883
+ if (_checkForCompoundkey && !checkReserved && rCheckDot.test(key)) {
1884
+ var subKeys = key.split(".");
1885
+ var keyLen = subKeys.length;
1886
+ if (keyLen > 1) {
1887
+ if (theMetaPathKeys) {
1888
+ theMetaPathKeys = theMetaPathKeys.slice();
1889
+ }
1890
+ for (var lp = 0; lp < keyLen - 1; lp++) {
1891
+ var subKey = subKeys[lp];
1892
+ destObj = destObj[subKey] = destObj[subKey] || {};
1893
+ path += "." + subKey;
1894
+ if (theMetaPathKeys) {
1895
+ theMetaPathKeys.push(subKey);
1896
+ }
1897
+ }
1898
+ name_1 = subKeys[keyLen - 1];
1899
+ }
1900
+ }
1901
+ var isReserved = checkReserved && _isReservedField(path);
1902
+ if (!isReserved && _theSanitizer && _theSanitizer.handleField(path, name_1)) {
1903
+ prop = _theSanitizer.value(path, name_1, srcValue, stringifyObjects);
1904
+ }
1905
+ else {
1906
+ prop = sanitizeProperty(name_1, srcValue, stringifyObjects);
1907
+ }
1908
+ if (prop) {
1909
+ var newValue = prop.value;
1910
+ destObj[name_1] = newValue;
1911
+ if (metadataCallback) {
1912
+ metadataCallback(theMetaPathKeys, name_1, prop);
1913
+ }
1914
+ if (processSubKeys && typeof newValue === "object" && !isArray(newValue)) {
1915
+ var newPath = theMetaPathKeys;
1916
+ if (newPath) {
1917
+ newPath = newPath.slice();
1918
+ newPath.push(name_1);
1919
+ }
1920
+ _processPathKeys(srcValue, newValue, path + "." + name_1, checkReserved, newPath, metadataCallback, processSubKeys);
1921
+ }
1922
+ }
1923
+ }
1924
+ });
1925
+ }
1926
+ });
1927
+ }
1928
+ return Serializer;
1929
+ }());
1930
+ function _addJSONPropertyMetaData(json, propKeys, name, propertyValue) {
1931
+ if (propertyValue && json) {
1932
+ var encodedTypeValue = getCommonSchemaMetaData(propertyValue.value, propertyValue.kind, propertyValue.propertyType);
1933
+ if (encodedTypeValue > -1) {
1934
+ var metaData = json[metadata];
1935
+ if (!metaData) {
1936
+ metaData = json[metadata] = { f: {} };
1937
+ }
1938
+ var metaTarget = metaData[f];
1939
+ if (!metaTarget) {
1940
+ metaTarget = metaData[f] = {};
1941
+ }
1942
+ if (propKeys) {
1943
+ for (var lp = 0; lp < propKeys.length; lp++) {
1944
+ var key = propKeys[lp];
1945
+ if (!metaTarget[key]) {
1946
+ metaTarget[key] = { f: {} };
1947
+ }
1948
+ var newTarget = metaTarget[key][f];
1949
+ if (!newTarget) {
1950
+ newTarget = metaTarget[key][f] = {};
1951
+ }
1952
+ metaTarget = newTarget;
1953
+ }
1954
+ }
1955
+ metaTarget = metaTarget[name] = {};
1956
+ if (isArray(propertyValue.value)) {
1957
+ metaTarget["a"] = {
1958
+ t: encodedTypeValue
1959
+ };
1960
+ }
1961
+ else {
1962
+ metaTarget["t"] = encodedTypeValue;
1963
+ }
1964
+ }
1965
+ }
1966
+ }
1967
+
1968
+ var RandomizationLowerThreshold = 0.8;
1969
+ var RandomizationUpperThreshold = 1.2;
1970
+ var BaseBackoff = 3000;
1971
+ var MaxBackoff = 600000;
1972
+ var RetryPolicy = /** @class */ (function () {
1973
+ function RetryPolicy() {
1974
+ }
1975
+ RetryPolicy.shouldRetryForStatus = function (httpStatusCode) {
1976
+ return !((httpStatusCode >= 300 && httpStatusCode < 500 && httpStatusCode != 408 && httpStatusCode != 429)
1977
+ || (httpStatusCode == 501)
1978
+ || (httpStatusCode == 505));
1979
+ };
1980
+ RetryPolicy.getMillisToBackoffForRetry = function (retriesSoFar) {
1981
+ var waitDuration = 0;
1982
+ var minBackoff = BaseBackoff * RandomizationLowerThreshold;
1983
+ var maxBackoff = BaseBackoff * RandomizationUpperThreshold;
1984
+ var randomBackoff = Math.floor(Math.random() * (maxBackoff - minBackoff)) + minBackoff;
1985
+ waitDuration = Math.pow(2, retriesSoFar) * randomBackoff;
1986
+ return Math.min(waitDuration, MaxBackoff);
1987
+ };
1988
+ return RetryPolicy;
1989
+ }());
1990
+ var RetryPolicy$1 = RetryPolicy;
1991
+
1992
+ var SecToMsMultiplier = 1000;
1993
+ var KillSwitch = /** @class */ (function () {
1994
+ function KillSwitch() {
1995
+ var _killedTokenDictionary = {};
1996
+ function _normalizeTenants(values) {
1997
+ var result = [];
1998
+ if (values) {
1999
+ arrForEach(values, function (value) {
2000
+ result.push(strTrim(value));
2001
+ });
2002
+ }
2003
+ return result;
2004
+ }
2005
+ dynamicProto(KillSwitch, this, function (_self) {
2006
+ _self.setKillSwitchTenants = function (killTokens, killDuration) {
2007
+ if (killTokens && killDuration) {
2008
+ try {
2009
+ var killedTokens = _normalizeTenants(killTokens.split(","));
2010
+ if (killDuration === "this-request-only") {
2011
+ return killedTokens;
2012
+ }
2013
+ var durationMs = parseInt(killDuration, 10) * SecToMsMultiplier;
2014
+ for (var i = 0; i < killedTokens.length; ++i) {
2015
+ _killedTokenDictionary[killedTokens[i]] = dateNow() + durationMs;
2016
+ }
2017
+ }
2018
+ catch (ex) {
2019
+ return [];
2020
+ }
2021
+ }
2022
+ return [];
2023
+ };
2024
+ _self.isTenantKilled = function (tenantToken) {
2025
+ var killDictionary = _killedTokenDictionary;
2026
+ var name = strTrim(tenantToken);
2027
+ if (killDictionary[name] !== undefined && killDictionary[name] > dateNow()) {
2028
+ return true;
2029
+ }
2030
+ delete killDictionary[name];
2031
+ return false;
2032
+ };
2033
+ });
2034
+ }
2035
+ return KillSwitch;
2036
+ }());
2037
+ var EVTKillSwitch = KillSwitch;
2038
+
2039
+ var ClockSkewManager = /** @class */ (function () {
2040
+ function ClockSkewManager() {
2041
+ var _allowRequestSending = true;
2042
+ var _shouldAddClockSkewHeaders = true;
2043
+ var _isFirstRequest = true;
2044
+ var _clockSkewHeaderValue = "use-collector-delta";
2045
+ var _clockSkewSet = false;
2046
+ dynamicProto(ClockSkewManager, this, function (_self) {
2047
+ _self.allowRequestSending = function () {
2048
+ return _allowRequestSending;
2049
+ };
2050
+ _self.firstRequestSent = function () {
2051
+ if (_isFirstRequest) {
2052
+ _isFirstRequest = false;
2053
+ if (!_clockSkewSet) {
2054
+ _allowRequestSending = false;
2055
+ }
2056
+ }
2057
+ };
2058
+ _self.shouldAddClockSkewHeaders = function () {
2059
+ return _shouldAddClockSkewHeaders;
2060
+ };
2061
+ _self.getClockSkewHeaderValue = function () {
2062
+ return _clockSkewHeaderValue;
2063
+ };
2064
+ _self.setClockSkew = function (timeDeltaInMillis) {
2065
+ if (!_clockSkewSet) {
2066
+ if (timeDeltaInMillis) {
2067
+ _clockSkewHeaderValue = timeDeltaInMillis;
2068
+ _shouldAddClockSkewHeaders = true;
2069
+ _clockSkewSet = true;
2070
+ }
2071
+ else {
2072
+ _shouldAddClockSkewHeaders = false;
2073
+ }
2074
+ _allowRequestSending = true;
2075
+ }
2076
+ };
2077
+ });
2078
+ }
2079
+ return ClockSkewManager;
2080
+ }());
2081
+ var EVTClockSkewManager = ClockSkewManager;
2082
+
2083
+ var _a;
2084
+ var _eventActionMap = (_a = {},
2085
+ _a[1 ] = strRequeue,
2086
+ _a[100 ] = strRequeue,
2087
+ _a[200 ] = "sent",
2088
+ _a[8004 ] = strDropped,
2089
+ _a[8003 ] = strDropped,
2090
+ _a);
2091
+ var _collectorQsHeaders = {};
2092
+ var _collectorHeaderToQs = {};
2093
+ function _addCollectorHeaderQsMapping(qsName, headerName) {
2094
+ _collectorQsHeaders[qsName] = headerName;
2095
+ _collectorHeaderToQs[headerName] = qsName;
2096
+ }
2097
+ _addCollectorHeaderQsMapping(strMsaDeviceTicket, strMsaDeviceTicket);
2098
+ function _getResponseText(xhr) {
2099
+ try {
2100
+ return xhr.responseText;
2101
+ }
2102
+ catch (e) {
2103
+ }
2104
+ return "";
2105
+ }
2106
+ function _hasHeader(headers, header) {
2107
+ var hasHeader = false;
2108
+ if (headers && header) {
2109
+ var keys = objKeys(headers);
2110
+ if (keys && keys.length > 0) {
2111
+ var lowerHeader = header.toLowerCase();
2112
+ for (var lp = 0; lp < keys.length; lp++) {
2113
+ var value = keys[lp];
2114
+ if (value && hasOwnProperty(header, value) &&
2115
+ value.toLowerCase() === lowerHeader) {
2116
+ hasHeader = true;
2117
+ break;
2118
+ }
2119
+ }
2120
+ }
2121
+ }
2122
+ return hasHeader;
2123
+ }
2124
+ function _addRequestDetails(details, name, value, useHeaders) {
2125
+ if (name && value && value.length > 0) {
2126
+ if (useHeaders && _collectorQsHeaders[name]) {
2127
+ details.hdrs[_collectorQsHeaders[name]] = value;
2128
+ details.useHdrs = true;
2129
+ }
2130
+ else {
2131
+ details.url += "&" + name + "=" + value;
2132
+ }
2133
+ }
2134
+ }
2135
+ var HttpManager = /** @class */ (function () {
2136
+ function HttpManager(maxEventsPerBatch, maxConnections, maxRetries, actions) {
2137
+ this._responseHandlers = [];
2138
+ var _urlString = "?cors=true&" + strContentTypeHeader.toLowerCase() + "=" + defaultContentType;
2139
+ var _killSwitch = new EVTKillSwitch();
2140
+ var _paused = false;
2141
+ var _clockSkewManager = new EVTClockSkewManager();
2142
+ var _useBeacons = false;
2143
+ var _outstandingRequests = 0;
2144
+ var _postManager;
2145
+ var _sendInterfaces;
2146
+ var _core;
2147
+ var _customHttpInterface = true;
2148
+ var _queryStringParameters = [];
2149
+ var _headers = {};
2150
+ var _batchQueue = [];
2151
+ var _serializer = null;
2152
+ var _enableEventTimings = false;
2153
+ var _cookieMgr;
2154
+ var _isUnloading = false;
2155
+ var _useHeaders = false;
2156
+ dynamicProto(HttpManager, this, function (_self) {
2157
+ var _sendCredentials = true;
2158
+ _self.initialize = function (endpointUrl, core, postChannel, httpInterface, channelConfig) {
2159
+ var _a;
2160
+ if (!channelConfig) {
2161
+ channelConfig = {};
2162
+ }
2163
+ _urlString = endpointUrl + _urlString;
2164
+ _useHeaders = !isUndefined(channelConfig.avoidOptions) ? !channelConfig.avoidOptions : false;
2165
+ _core = core;
2166
+ _cookieMgr = core.getCookieMgr();
2167
+ _enableEventTimings = !_core.config.disableEventTimings;
2168
+ var enableCompoundKey = !!_core.config.enableCompoundKey;
2169
+ _postManager = postChannel;
2170
+ var valueSanitizer = channelConfig.valueSanitizer;
2171
+ var stringifyObjects = channelConfig.stringifyObjects;
2172
+ if (!isUndefined(channelConfig.enableCompoundKey)) {
2173
+ enableCompoundKey = !!channelConfig.enableCompoundKey;
2174
+ }
2175
+ _useBeacons = !isReactNative();
2176
+ _serializer = new Serializer(_core, valueSanitizer, stringifyObjects, enableCompoundKey);
2177
+ var syncHttpInterface = httpInterface;
2178
+ if (!httpInterface) {
2179
+ _customHttpInterface = false;
2180
+ var location_1 = getLocation();
2181
+ if (location_1 && location_1.protocol && location_1.protocol.toLowerCase() === "file:") {
2182
+ _sendCredentials = false;
2183
+ }
2184
+ var theTransports = [];
2185
+ if (isReactNative()) {
2186
+ theTransports = [2 , 1 ];
2187
+ }
2188
+ else {
2189
+ theTransports = [1 , 2 , 3 ];
2190
+ }
2191
+ var configTransports = channelConfig.transports;
2192
+ if (configTransports) {
2193
+ if (isNumber(configTransports)) {
2194
+ theTransports = [configTransports].concat(theTransports);
2195
+ }
2196
+ else if (isArray(configTransports)) {
2197
+ theTransports = configTransports.concat(theTransports);
2198
+ }
2199
+ }
2200
+ httpInterface = _getSenderInterface(theTransports, false);
2201
+ syncHttpInterface = _getSenderInterface(theTransports, true);
2202
+ if (!httpInterface) {
2203
+ _postManager.diagLog().warnToConsole("No available transport to send events");
2204
+ }
2205
+ }
2206
+ _sendInterfaces = (_a = {},
2207
+ _a[0 ] = httpInterface,
2208
+ _a[1 ] = syncHttpInterface || _getSenderInterface([1 , 2 , 3 ], true),
2209
+ _a[2 ] = _getSenderInterface([3 , 2 , 1 ], true) || syncHttpInterface,
2210
+ _a[3 ] = _getSenderInterface([2 , 3 , 1 ], true) || syncHttpInterface,
2211
+ _a);
2212
+ };
2213
+ function _getSenderInterface(transports, syncSupport) {
2214
+ var transportType = 0 ;
2215
+ var sendPostFunc = null;
2216
+ var lp = 0;
2217
+ while (sendPostFunc == null && lp < transports.length) {
2218
+ transportType = transports[lp];
2219
+ if (transportType === 1 ) {
2220
+ if (useXDomainRequest()) {
2221
+ sendPostFunc = _xdrSendPost;
2222
+ }
2223
+ else if (isXhrSupported()) {
2224
+ sendPostFunc = _xhrSendPost;
2225
+ }
2226
+ }
2227
+ else if (transportType === 2 && isFetchSupported(syncSupport)) {
2228
+ sendPostFunc = _fetchSendPost;
2229
+ }
2230
+ else if (_useBeacons && transportType === 3 && isBeaconsSupported()) {
2231
+ sendPostFunc = _beaconSendPost;
2232
+ }
2233
+ lp++;
2234
+ }
2235
+ if (sendPostFunc) {
2236
+ return {
2237
+ _transport: transportType,
2238
+ _isSync: syncSupport,
2239
+ sendPOST: sendPostFunc
2240
+ };
2241
+ }
2242
+ return null;
2243
+ }
2244
+ _self["_getDbgPlgTargets"] = function () {
2245
+ return [_sendInterfaces[0 ], _killSwitch, _serializer, _sendInterfaces];
2246
+ };
2247
+ function _xdrSendPost(payload, oncomplete, sync) {
2248
+ var xdr = new XDomainRequest();
2249
+ xdr.open(Method, payload.urlString);
2250
+ xdr.onload = function () {
2251
+ var response = _getResponseText(xdr);
2252
+ _doOnComplete(oncomplete, 200, {}, response);
2253
+ _handleCollectorResponse(response);
2254
+ };
2255
+ xdr.onerror = function () {
2256
+ _doOnComplete(oncomplete, 400, {});
2257
+ };
2258
+ xdr.ontimeout = function () {
2259
+ _doOnComplete(oncomplete, 500, {});
2260
+ };
2261
+ xdr.onprogress = function () { };
2262
+ if (sync) {
2263
+ xdr.send(payload.data);
2264
+ }
2265
+ else {
2266
+ _postManager._setTimeoutOverride(function () {
2267
+ xdr.send(payload.data);
2268
+ }, 0);
2269
+ }
2270
+ }
2271
+ function _fetchSendPost(payload, oncomplete, sync) {
2272
+ var _a;
2273
+ var ignoreResponse = false;
2274
+ var responseHandled = false;
2275
+ var requestInit = (_a = {
2276
+ body: payload.data,
2277
+ method: Method
2278
+ },
2279
+ _a[DisabledPropertyName] = true,
2280
+ _a);
2281
+ if (sync) {
2282
+ requestInit.keepalive = true;
2283
+ if (payload._sendReason === 2 ) {
2284
+ ignoreResponse = true;
2285
+ }
2286
+ }
2287
+ if (_sendCredentials) {
2288
+ requestInit.credentials = "include";
2289
+ }
2290
+ if (payload.headers && objKeys(payload.headers).length > 0) {
2291
+ requestInit.headers = payload.headers;
2292
+ }
2293
+ fetch(payload.urlString, requestInit).then(function (response) {
2294
+ var headerMap = {};
2295
+ var responseText = "";
2296
+ if (response.headers) {
2297
+ response.headers.forEach(function (value, name) {
2298
+ headerMap[name] = value;
2299
+ });
2300
+ }
2301
+ if (response.body) {
2302
+ response.text().then(function (text) {
2303
+ responseText = text;
2304
+ });
2305
+ }
2306
+ if (!responseHandled) {
2307
+ responseHandled = true;
2308
+ _doOnComplete(oncomplete, response.status, headerMap, responseText);
2309
+ _handleCollectorResponse(responseText);
2310
+ }
2311
+ })["catch"](function (error) {
2312
+ if (!responseHandled) {
2313
+ responseHandled = true;
2314
+ _doOnComplete(oncomplete, 0, {});
2315
+ }
2316
+ });
2317
+ if (ignoreResponse && !responseHandled) {
2318
+ responseHandled = true;
2319
+ _doOnComplete(oncomplete, 200, {});
2320
+ }
2321
+ }
2322
+ function _xhrSendPost(payload, oncomplete, sync) {
2323
+ function _appendHeader(theHeaders, xhr, name) {
2324
+ if (!theHeaders[name] && xhr && xhr.getResponseHeader) {
2325
+ var value = xhr.getResponseHeader(name);
2326
+ if (value) {
2327
+ theHeaders[name] = strTrim(value);
2328
+ }
2329
+ }
2330
+ return theHeaders;
2331
+ }
2332
+ function _getAllResponseHeaders(xhr) {
2333
+ var theHeaders = {};
2334
+ if (!xhr.getAllResponseHeaders) {
2335
+ theHeaders = _appendHeader(theHeaders, xhr, strTimeDeltaHeader);
2336
+ theHeaders = _appendHeader(theHeaders, xhr, strKillDurationHeader);
2337
+ theHeaders = _appendHeader(theHeaders, xhr, strKillDurationSecondsHeader);
2338
+ }
2339
+ else {
2340
+ theHeaders = _convertAllHeadersToMap(xhr.getAllResponseHeaders());
2341
+ }
2342
+ return theHeaders;
2343
+ }
2344
+ function xhrComplete(xhr, responseTxt) {
2345
+ _doOnComplete(oncomplete, xhr.status, _getAllResponseHeaders(xhr), responseTxt);
2346
+ }
2347
+ var xhRequest = openXhr(Method, payload.urlString, _sendCredentials, true, sync);
2348
+ objForEachKey(payload.headers, function (name, value) {
2349
+ xhRequest.setRequestHeader(name, value);
2350
+ });
2351
+ xhRequest.onload = function () {
2352
+ var response = _getResponseText(xhRequest);
2353
+ xhrComplete(xhRequest, response);
2354
+ _handleCollectorResponse(response);
2355
+ };
2356
+ xhRequest.onerror = function () {
2357
+ xhrComplete(xhRequest);
2358
+ };
2359
+ xhRequest.ontimeout = function () {
2360
+ xhrComplete(xhRequest);
2361
+ };
2362
+ xhRequest.send(payload.data);
2363
+ }
2364
+ function _doOnComplete(oncomplete, status, headers, response) {
2365
+ try {
2366
+ oncomplete(status, headers, response);
2367
+ }
2368
+ catch (e) {
2369
+ _postManager.diagLog().throwInternal(LoggingSeverity.WARNING, _ExtendedInternalMessageId.SendPostOnCompleteFailure, dumpObj(e));
2370
+ }
2371
+ }
2372
+ function _beaconSendPost(payload, oncomplete, sync) {
2373
+ var internalPayloadData = payload;
2374
+ var status = 200;
2375
+ var thePayload = internalPayloadData._thePayload;
2376
+ try {
2377
+ var nav_1 = getNavigator();
2378
+ if (!nav_1.sendBeacon(payload.urlString, payload.data)) {
2379
+ if (thePayload) {
2380
+ var droppedBatches_1 = [];
2381
+ arrForEach(thePayload.batches, function (theBatch) {
2382
+ if (droppedBatches_1 && theBatch && theBatch.count() > 0) {
2383
+ var theEvents = theBatch.events();
2384
+ for (var lp = 0; lp < theEvents.length; lp++) {
2385
+ if (!nav_1.sendBeacon(payload.urlString, _serializer.getEventBlob(theEvents[lp]))) {
2386
+ droppedBatches_1.push(theBatch.split(lp));
2387
+ break;
2388
+ }
2389
+ }
2390
+ }
2391
+ else {
2392
+ droppedBatches_1.push(theBatch.split(0));
2393
+ }
2394
+ });
2395
+ _sendBatchesNotification(droppedBatches_1, 8003 , thePayload.sendType, true);
2396
+ }
2397
+ else {
2398
+ status = 0;
2399
+ }
2400
+ }
2401
+ }
2402
+ catch (ex) {
2403
+ _postManager.diagLog().warnToConsole("Failed to send telemetry using sendBeacon API. Ex:" + ex);
2404
+ status = 0;
2405
+ }
2406
+ finally {
2407
+ _doOnComplete(oncomplete, status, {}, "");
2408
+ }
2409
+ }
2410
+ function _isBeaconPayload(sendType) {
2411
+ return sendType === 2 || sendType === 3 ;
2412
+ }
2413
+ function _adjustSendType(sendType) {
2414
+ if (_isUnloading && _isBeaconPayload(sendType)) {
2415
+ sendType = 2 ;
2416
+ }
2417
+ return sendType;
2418
+ }
2419
+ _self.addQueryStringParameter = function (name, value) {
2420
+ for (var i = 0; i < _queryStringParameters.length; i++) {
2421
+ if (_queryStringParameters[i].name === name) {
2422
+ _queryStringParameters[i].value = value;
2423
+ return;
2424
+ }
2425
+ }
2426
+ _queryStringParameters.push({ name: name, value: value });
2427
+ };
2428
+ _self.addHeader = function (name, value) {
2429
+ _headers[name] = value;
2430
+ };
2431
+ _self.canSendRequest = function () {
2432
+ return _hasIdleConnection() && _clockSkewManager.allowRequestSending();
2433
+ };
2434
+ _self.sendQueuedRequests = function (sendType, sendReason) {
2435
+ if (isUndefined(sendType)) {
2436
+ sendType = 0 ;
2437
+ }
2438
+ if (_isUnloading) {
2439
+ sendType = _adjustSendType(sendType);
2440
+ sendReason = 2 ;
2441
+ }
2442
+ if (_canSendPayload(_batchQueue, sendType, 0)) {
2443
+ _sendBatches(_clearQueue(), 0, false, sendType, sendReason || 0 );
2444
+ }
2445
+ };
2446
+ _self.isCompletelyIdle = function () {
2447
+ return !_paused && _outstandingRequests === 0 && _batchQueue.length === 0;
2448
+ };
2449
+ _self.setUnloading = function (value) {
2450
+ _isUnloading = value;
2451
+ };
2452
+ _self.addBatch = function (theBatch) {
2453
+ if (theBatch && theBatch.count() > 0) {
2454
+ if (_killSwitch.isTenantKilled(theBatch.iKey())) {
2455
+ return false;
2456
+ }
2457
+ _batchQueue.push(theBatch);
2458
+ }
2459
+ return true;
2460
+ };
2461
+ _self.teardown = function () {
2462
+ if (_batchQueue.length > 0) {
2463
+ _sendBatches(_clearQueue(), 0, true, 2 , 2 );
2464
+ }
2465
+ };
2466
+ _self.pause = function () {
2467
+ _paused = true;
2468
+ };
2469
+ _self.resume = function () {
2470
+ _paused = false;
2471
+ _self.sendQueuedRequests(0 , 4 );
2472
+ };
2473
+ _self.sendSynchronousBatch = function (batch, sendType, sendReason) {
2474
+ if (batch && batch.count() > 0) {
2475
+ if (isNullOrUndefined(sendType)) {
2476
+ sendType = 1 ;
2477
+ }
2478
+ if (_isUnloading) {
2479
+ sendType = _adjustSendType(sendType);
2480
+ sendReason = 2 ;
2481
+ }
2482
+ _sendBatches([batch], 0, false, sendType, sendReason || 0 );
2483
+ }
2484
+ };
2485
+ function _hasIdleConnection() {
2486
+ return !_paused && _outstandingRequests < maxConnections;
2487
+ }
2488
+ function _clearQueue() {
2489
+ var theQueue = _batchQueue;
2490
+ _batchQueue = [];
2491
+ return theQueue;
2492
+ }
2493
+ function _canSendPayload(theBatches, sendType, retryCnt) {
2494
+ var result = false;
2495
+ if (theBatches && theBatches.length > 0 && !_paused && _sendInterfaces[sendType] && _serializer) {
2496
+ result = (sendType !== 0 ) || (_hasIdleConnection() && (retryCnt > 0 || _clockSkewManager.allowRequestSending()));
2497
+ }
2498
+ return result;
2499
+ }
2500
+ function _createDebugBatches(theBatches) {
2501
+ var values = {};
2502
+ if (theBatches) {
2503
+ arrForEach(theBatches, function (theBatch, idx) {
2504
+ values[idx] = {
2505
+ iKey: theBatch.iKey(),
2506
+ evts: theBatch.events()
2507
+ };
2508
+ });
2509
+ }
2510
+ return values;
2511
+ }
2512
+ function _sendBatches(theBatches, retryCount, isTeardown, sendType, sendReason) {
2513
+ if (!theBatches || theBatches.length === 0) {
2514
+ return;
2515
+ }
2516
+ if (_paused) {
2517
+ _sendBatchesNotification(theBatches, 1 , sendType);
2518
+ return;
2519
+ }
2520
+ sendType = _adjustSendType(sendType);
2521
+ try {
2522
+ var orgBatches_1 = theBatches;
2523
+ var isSynchronous_1 = sendType !== 0 ;
2524
+ doPerf(_core, function () { return "HttpManager:_sendBatches"; }, function (perfEvt) {
2525
+ if (perfEvt) {
2526
+ theBatches = theBatches.slice(0);
2527
+ }
2528
+ var droppedBatches = [];
2529
+ var thePayload = null;
2530
+ var serializationStart = getTime();
2531
+ var sendInterface = _sendInterfaces[sendType] || (isSynchronous_1 ? _sendInterfaces[1 ] : _sendInterfaces[0 ]);
2532
+ var isBeaconTransport = (_isUnloading || _isBeaconPayload(sendType) || (sendInterface && sendInterface._transport === 3 )) && _canUseSendBeaconApi();
2533
+ while (_canSendPayload(theBatches, sendType, retryCount)) {
2534
+ var theBatch = theBatches.shift();
2535
+ if (theBatch && theBatch.count() > 0) {
2536
+ if (!_killSwitch.isTenantKilled(theBatch.iKey())) {
2537
+ thePayload = thePayload || _serializer.createPayload(retryCount, isTeardown, isSynchronous_1, isBeaconTransport, sendReason, sendType);
2538
+ if (!_serializer.appendPayload(thePayload, theBatch, maxEventsPerBatch)) {
2539
+ _doPayloadSend(thePayload, serializationStart, getTime(), sendReason);
2540
+ serializationStart = getTime();
2541
+ theBatches = [theBatch].concat(theBatches);
2542
+ thePayload = null;
2543
+ }
2544
+ else if (thePayload.overflow !== null) {
2545
+ theBatches = [thePayload.overflow].concat(theBatches);
2546
+ thePayload.overflow = null;
2547
+ _doPayloadSend(thePayload, serializationStart, getTime(), sendReason);
2548
+ serializationStart = getTime();
2549
+ thePayload = null;
2550
+ }
2551
+ }
2552
+ else {
2553
+ droppedBatches.push(theBatch);
2554
+ }
2555
+ }
2556
+ }
2557
+ if (thePayload) {
2558
+ _doPayloadSend(thePayload, serializationStart, getTime(), sendReason);
2559
+ }
2560
+ if (theBatches.length > 0) {
2561
+ _batchQueue = theBatches.concat(_batchQueue);
2562
+ }
2563
+ _sendBatchesNotification(droppedBatches, 8004 , sendType);
2564
+ }, function () { return ({ batches: _createDebugBatches(orgBatches_1), retryCount: retryCount, isTeardown: isTeardown, isSynchronous: isSynchronous_1, sendReason: sendReason, useSendBeacon: _isBeaconPayload(sendType), sendType: sendType }); }, !isSynchronous_1);
2565
+ }
2566
+ catch (ex) {
2567
+ _postManager.diagLog().throwInternal(LoggingSeverity.WARNING, _ExtendedInternalMessageId.CannotSerializeObject, "Unexpected Exception sending batch: " + dumpObj(ex));
2568
+ }
2569
+ }
2570
+ function _buildRequestDetails(thePayload, useHeaders) {
2571
+ var requestDetails = {
2572
+ url: _urlString,
2573
+ hdrs: {},
2574
+ useHdrs: false
2575
+ };
2576
+ requestDetails.hdrs = extend(requestDetails.hdrs, _headers);
2577
+ requestDetails.useHdrs = (objKeys(requestDetails.hdrs).length > 0);
2578
+ _addRequestDetails(requestDetails, strClientId, "NO_AUTH", useHeaders);
2579
+ _addRequestDetails(requestDetails, strClientVersion, FullVersionString, useHeaders);
2580
+ var apiQsKeys = "";
2581
+ arrForEach(thePayload.apiKeys, function (apiKey) {
2582
+ if (apiQsKeys.length > 0) {
2583
+ apiQsKeys += ",";
2584
+ }
2585
+ apiQsKeys += apiKey;
2586
+ });
2587
+ _addRequestDetails(requestDetails, strApiKey, apiQsKeys, useHeaders);
2588
+ _addRequestDetails(requestDetails, strUploadTime, dateNow().toString(), useHeaders);
2589
+ var msfpc = _getMsfpc(thePayload);
2590
+ if (isValueAssigned(msfpc)) {
2591
+ requestDetails.url += "&ext.intweb.msfpc=" + msfpc;
2592
+ }
2593
+ if (_clockSkewManager.shouldAddClockSkewHeaders()) {
2594
+ _addRequestDetails(requestDetails, strTimeDeltaToApply, _clockSkewManager.getClockSkewHeaderValue(), useHeaders);
2595
+ }
2596
+ if (_core.getWParam) {
2597
+ var wParam = _core.getWParam();
2598
+ if (wParam >= 0) {
2599
+ requestDetails.url += "&w=" + wParam;
2600
+ }
2601
+ }
2602
+ for (var i = 0; i < _queryStringParameters.length; i++) {
2603
+ requestDetails.url += "&" + _queryStringParameters[i].name + "=" + _queryStringParameters[i].value;
2604
+ }
2605
+ return requestDetails;
2606
+ }
2607
+ function _canUseSendBeaconApi() {
2608
+ return !_customHttpInterface && _useBeacons && isBeaconsSupported();
2609
+ }
2610
+ function _setTimingValue(timings, name, value) {
2611
+ timings[name] = timings[name] || {};
2612
+ timings[name][_postManager.identifier] = value;
2613
+ }
2614
+ function _doPayloadSend(thePayload, serializationStart, serializationCompleted, sendReason) {
2615
+ if (thePayload && thePayload.payloadBlob && thePayload.payloadBlob.length > 0) {
2616
+ var useSendHook_1 = !!_self.sendHook;
2617
+ var sendInterface_1 = _sendInterfaces[thePayload.sendType];
2618
+ if (!_isBeaconPayload(thePayload.sendType) && thePayload.isBeacon && thePayload.sendReason === 2 ) {
2619
+ sendInterface_1 = _sendInterfaces[2 ] || _sendInterfaces[3 ] || sendInterface_1;
2620
+ }
2621
+ var useHeaders_1 = _useHeaders;
2622
+ if (thePayload.isBeacon || sendInterface_1._transport === 3 ) {
2623
+ useHeaders_1 = false;
2624
+ }
2625
+ var requestDetails_1 = _buildRequestDetails(thePayload, useHeaders_1);
2626
+ useHeaders_1 = useHeaders_1 || requestDetails_1.useHdrs;
2627
+ var sendEventStart_1 = getTime();
2628
+ var strSendAttempt_1 = "sendAttempt";
2629
+ doPerf(_core, function () { return "HttpManager:_doPayloadSend"; }, function () {
2630
+ for (var batchLp = 0; batchLp < thePayload.batches.length; batchLp++) {
2631
+ var theBatch = thePayload.batches[batchLp];
2632
+ var theEvents = theBatch.events();
2633
+ for (var evtLp = 0; evtLp < theEvents.length; evtLp++) {
2634
+ var telemetryItem = theEvents[evtLp];
2635
+ if (_enableEventTimings) {
2636
+ var timings = telemetryItem.timings = telemetryItem.timings || {};
2637
+ _setTimingValue(timings, "sendEventStart", sendEventStart_1);
2638
+ _setTimingValue(timings, "serializationStart", serializationStart);
2639
+ _setTimingValue(timings, "serializationCompleted", serializationCompleted);
2640
+ }
2641
+ telemetryItem[strSendAttempt_1] > 0 ? telemetryItem[strSendAttempt_1]++ : telemetryItem[strSendAttempt_1] = 1;
2642
+ }
2643
+ }
2644
+ _sendBatchesNotification(thePayload.batches, (1000 + (sendReason || 0 )), thePayload.sendType, true);
2645
+ var orgPayloadData = {
2646
+ data: thePayload.payloadBlob,
2647
+ urlString: requestDetails_1.url,
2648
+ headers: requestDetails_1.hdrs,
2649
+ _thePayload: thePayload,
2650
+ _sendReason: sendReason
2651
+ };
2652
+ if (useHeaders_1) {
2653
+ if (!_hasHeader(orgPayloadData.headers, strCacheControl)) {
2654
+ orgPayloadData.headers[strCacheControl] = defaultCacheControl;
2655
+ }
2656
+ if (!_hasHeader(orgPayloadData.headers, strContentTypeHeader)) {
2657
+ orgPayloadData.headers[strContentTypeHeader] = defaultContentType;
2658
+ }
2659
+ }
2660
+ var sender = null;
2661
+ if (sendInterface_1) {
2662
+ sender = function (payload) {
2663
+ _clockSkewManager.firstRequestSent();
2664
+ var onComplete = function (status, headers) {
2665
+ _retryRequestIfNeeded(status, headers, thePayload, sendReason);
2666
+ };
2667
+ var isSync = thePayload.isTeardown || thePayload.isSync;
2668
+ try {
2669
+ sendInterface_1.sendPOST(payload, onComplete, isSync);
2670
+ if (_self.sendListener) {
2671
+ _self.sendListener(orgPayloadData, payload, isSync, thePayload.isBeacon);
2672
+ }
2673
+ }
2674
+ catch (ex) {
2675
+ _postManager.diagLog().warnToConsole("Unexpected exception sending payload. Ex:" + dumpObj(ex));
2676
+ _doOnComplete(onComplete, 0, {});
2677
+ }
2678
+ };
2679
+ }
2680
+ doPerf(_core, function () { return "HttpManager:_doPayloadSend.sender"; }, function () {
2681
+ if (sender) {
2682
+ if (thePayload.sendType === 0 ) {
2683
+ _outstandingRequests++;
2684
+ }
2685
+ if (useSendHook_1 && !thePayload.isBeacon && sendInterface_1._transport !== 3 ) {
2686
+ var hookData_1 = {
2687
+ data: orgPayloadData.data,
2688
+ urlString: orgPayloadData.urlString,
2689
+ headers: extend({}, orgPayloadData.headers)
2690
+ };
2691
+ var senderCalled_1 = false;
2692
+ doPerf(_core, function () { return "HttpManager:_doPayloadSend.sendHook"; }, function () {
2693
+ try {
2694
+ _self.sendHook(hookData_1, function (payload) {
2695
+ senderCalled_1 = true;
2696
+ if (!_customHttpInterface && !payload._thePayload) {
2697
+ payload._thePayload = payload._thePayload || orgPayloadData._thePayload;
2698
+ payload._sendReason = payload._sendReason || orgPayloadData._sendReason;
2699
+ }
2700
+ sender(payload);
2701
+ }, thePayload.isSync || thePayload.isTeardown);
2702
+ }
2703
+ catch (ex) {
2704
+ if (!senderCalled_1) {
2705
+ sender(orgPayloadData);
2706
+ }
2707
+ }
2708
+ });
2709
+ }
2710
+ else {
2711
+ sender(orgPayloadData);
2712
+ }
2713
+ }
2714
+ });
2715
+ }, function () { return ({ thePayload: thePayload, serializationStart: serializationStart, serializationCompleted: serializationCompleted, sendReason: sendReason }); }, thePayload.isSync);
2716
+ }
2717
+ if (thePayload.sizeExceed && thePayload.sizeExceed.length > 0) {
2718
+ _sendBatchesNotification(thePayload.sizeExceed, 8003 , thePayload.sendType);
2719
+ }
2720
+ if (thePayload.failedEvts && thePayload.failedEvts.length > 0) {
2721
+ _sendBatchesNotification(thePayload.failedEvts, 8002 , thePayload.sendType);
2722
+ }
2723
+ }
2724
+ function _addEventCompletedTimings(theEvents, sendEventCompleted) {
2725
+ if (_enableEventTimings) {
2726
+ arrForEach(theEvents, function (theEvent) {
2727
+ var timings = theEvent.timings = theEvent.timings || {};
2728
+ _setTimingValue(timings, "sendEventCompleted", sendEventCompleted);
2729
+ });
2730
+ }
2731
+ }
2732
+ function _retryRequestIfNeeded(status, headers, thePayload, sendReason) {
2733
+ var reason = 9000 ;
2734
+ var droppedBatches = null;
2735
+ var isRetrying = false;
2736
+ var backOffTrans = false;
2737
+ try {
2738
+ var shouldRetry = true;
2739
+ if (typeof status !== strShimUndefined) {
2740
+ if (headers) {
2741
+ _clockSkewManager.setClockSkew(headers[strTimeDeltaHeader]);
2742
+ var killDuration = headers[strKillDurationHeader] || headers["kill-duration-seconds"];
2743
+ arrForEach(_killSwitch.setKillSwitchTenants(headers[strKillTokensHeader], killDuration), function (killToken) {
2744
+ arrForEach(thePayload.batches, function (theBatch) {
2745
+ if (theBatch.iKey() === killToken) {
2746
+ droppedBatches = droppedBatches || [];
2747
+ var removedEvents = theBatch.split(0);
2748
+ thePayload.numEvents -= removedEvents.count();
2749
+ droppedBatches.push(removedEvents);
2750
+ }
2751
+ });
2752
+ });
2753
+ }
2754
+ if (status == 200) {
2755
+ reason = 200 ;
2756
+ return;
2757
+ }
2758
+ if (!RetryPolicy$1.shouldRetryForStatus(status) || thePayload.numEvents <= 0) {
2759
+ shouldRetry = false;
2760
+ }
2761
+ reason = 9000 + (status % 1000);
2762
+ }
2763
+ if (shouldRetry) {
2764
+ reason = 100 ;
2765
+ var retryCount_1 = thePayload.retryCnt;
2766
+ if (thePayload.sendType === 0 ) {
2767
+ if (retryCount_1 < maxRetries) {
2768
+ isRetrying = true;
2769
+ _doAction(function () {
2770
+ if (thePayload.sendType === 0 ) {
2771
+ _outstandingRequests--;
2772
+ }
2773
+ _sendBatches(thePayload.batches, retryCount_1 + 1, thePayload.isTeardown, _isUnloading ? 2 : thePayload.sendType, 5 );
2774
+ }, _isUnloading, RetryPolicy$1.getMillisToBackoffForRetry(retryCount_1));
2775
+ }
2776
+ else {
2777
+ backOffTrans = true;
2778
+ }
2779
+ }
2780
+ }
2781
+ }
2782
+ finally {
2783
+ if (!isRetrying) {
2784
+ _clockSkewManager.setClockSkew();
2785
+ _handleRequestFinished(thePayload, reason, sendReason, backOffTrans);
2786
+ }
2787
+ _sendBatchesNotification(droppedBatches, 8004 , thePayload.sendType);
2788
+ }
2789
+ }
2790
+ function _handleRequestFinished(thePayload, batchReason, sendReason, backOffTrans) {
2791
+ try {
2792
+ if (backOffTrans) {
2793
+ _postManager._backOffTransmission();
2794
+ }
2795
+ if (batchReason === 200 ) {
2796
+ if (!backOffTrans && !thePayload.isSync) {
2797
+ _postManager._clearBackOff();
2798
+ }
2799
+ _addCompleteTimings(thePayload.batches);
2800
+ }
2801
+ _sendBatchesNotification(thePayload.batches, batchReason, thePayload.sendType, true);
2802
+ }
2803
+ finally {
2804
+ if (thePayload.sendType === 0 ) {
2805
+ _outstandingRequests--;
2806
+ if (sendReason !== 5 ) {
2807
+ _self.sendQueuedRequests(thePayload.sendType, sendReason);
2808
+ }
2809
+ }
2810
+ }
2811
+ }
2812
+ function _addCompleteTimings(theBatches) {
2813
+ if (_enableEventTimings) {
2814
+ var sendEventCompleted_1 = getTime();
2815
+ arrForEach(theBatches, function (theBatch) {
2816
+ if (theBatch && theBatch.count() > 0) {
2817
+ _addEventCompletedTimings(theBatch.events(), sendEventCompleted_1);
2818
+ }
2819
+ });
2820
+ }
2821
+ }
2822
+ function _doAction(cb, isSync, interval) {
2823
+ if (isSync) {
2824
+ cb();
2825
+ }
2826
+ else {
2827
+ _postManager._setTimeoutOverride(cb, interval);
2828
+ }
2829
+ }
2830
+ function _convertAllHeadersToMap(headersString) {
2831
+ var headers = {};
2832
+ if (isString(headersString)) {
2833
+ var headersArray = strTrim(headersString).split(/[\r\n]+/);
2834
+ arrForEach(headersArray, function (headerEntry) {
2835
+ if (headerEntry) {
2836
+ var idx = headerEntry.indexOf(": ");
2837
+ if (idx !== -1) {
2838
+ var header = strTrim(headerEntry.substring(0, idx)).toLowerCase();
2839
+ var value = strTrim(headerEntry.substring(idx + 1));
2840
+ headers[header] = value;
2841
+ }
2842
+ else {
2843
+ headers[strTrim(headerEntry)] = 1;
2844
+ }
2845
+ }
2846
+ });
2847
+ }
2848
+ return headers;
2849
+ }
2850
+ function _getMsfpc(thePayload) {
2851
+ for (var lp = 0; lp < thePayload.batches.length; lp++) {
2852
+ var msfpc = thePayload.batches[lp].Msfpc();
2853
+ if (msfpc) {
2854
+ return encodeURIComponent(msfpc);
2855
+ }
2856
+ }
2857
+ return "";
2858
+ }
2859
+ function _handleCollectorResponse(responseText) {
2860
+ var responseHandlers = _self._responseHandlers;
2861
+ try {
2862
+ for (var i = 0; i < responseHandlers.length; i++) {
2863
+ try {
2864
+ responseHandlers[i](responseText);
2865
+ }
2866
+ catch (e) {
2867
+ _postManager.diagLog().throwInternal(LoggingSeverity.CRITICAL, _ExtendedInternalMessageId.PostResponseHandler, "Response handler failed: " + e);
2868
+ }
2869
+ }
2870
+ if (responseText) {
2871
+ var response = JSON.parse(responseText);
2872
+ if (isValueAssigned(response.webResult) && isValueAssigned(response.webResult[strMsfpc])) {
2873
+ _cookieMgr.set("MSFPC", response.webResult[strMsfpc], 365 * 86400);
2874
+ }
2875
+ }
2876
+ }
2877
+ catch (ex) {
2878
+ }
2879
+ }
2880
+ function _sendBatchesNotification(theBatches, batchReason, sendType, sendSync) {
2881
+ if (theBatches && theBatches.length > 0 && actions) {
2882
+ var theAction_1 = actions[_getNotificationAction(batchReason)];
2883
+ if (theAction_1) {
2884
+ var isSyncRequest_1 = sendType !== 0 ;
2885
+ doPerf(_core, function () { return "HttpManager:_sendBatchesNotification"; }, function () {
2886
+ _doAction(function () {
2887
+ try {
2888
+ theAction_1.call(actions, theBatches, batchReason, isSyncRequest_1, sendType);
2889
+ }
2890
+ catch (e) {
2891
+ _postManager.diagLog().throwInternal(LoggingSeverity.CRITICAL, _ExtendedInternalMessageId.NotificationException, "send request notification failed: " + e);
2892
+ }
2893
+ }, sendSync || isSyncRequest_1, 0);
2894
+ }, function () { return ({ batches: _createDebugBatches(theBatches), reason: batchReason, isSync: isSyncRequest_1, sendSync: sendSync, sendType: sendType }); }, !isSyncRequest_1);
2895
+ }
2896
+ }
2897
+ }
2898
+ function _getNotificationAction(reason) {
2899
+ var action = _eventActionMap[reason];
2900
+ if (!isValueAssigned(action)) {
2901
+ action = strOther;
2902
+ if (reason >= 9000 && reason <= 9999 ) {
2903
+ action = strResponseFail;
2904
+ }
2905
+ else if (reason >= 8000 && reason <= 8999 ) {
2906
+ action = strDropped;
2907
+ }
2908
+ else if (reason >= 1000 && reason <= 1999 ) {
2909
+ action = strSending;
2910
+ }
2911
+ }
2912
+ return action;
2913
+ }
2914
+ });
2915
+ }
2916
+ return HttpManager;
2917
+ }());
2918
+
2919
+ var FlushCheckTimer = 0.250;
2920
+ var MaxNumberEventPerBatch = 500;
2921
+ var EventsDroppedAtOneTime = 20;
2922
+ var MaxSendAttempts = 6;
2923
+ var MaxBackoffCount = 4;
2924
+ var globalContext = isWindowObjectAvailable ? window : undefined;
2925
+ var MaxConnections = 2;
2926
+ var MaxRetries = 1;
2927
+ var strEventsDiscarded = "eventsDiscarded";
2928
+ var strOverrideInstrumentationKey = "overrideInstrumentationKey";
2929
+ var PostChannel = /** @class */ (function (_super) {
2930
+ __extendsFn(PostChannel, _super);
2931
+ function PostChannel() {
2932
+ var _this = _super.call(this) || this;
2933
+ _this.identifier = "PostChannel";
2934
+ _this.priority = 1011;
2935
+ _this.version = '3.1.10';
2936
+ var _config;
2937
+ var _isTeardownCalled = false;
2938
+ var _flushCallbackQueue = [];
2939
+ var _flushCallbackTimerId = null;
2940
+ var _paused = false;
2941
+ var _immediateQueueSize = 0;
2942
+ var _immediateQueueSizeLimit = 500;
2943
+ var _queueSize = 0;
2944
+ var _queueSizeLimit = 10000;
2945
+ var _profiles = {};
2946
+ var _currentProfile = RT_PROFILE;
2947
+ var _scheduledTimerId = null;
2948
+ var _immediateTimerId = null;
2949
+ var _currentBackoffCount = 0;
2950
+ var _timerCount = 0;
2951
+ var _xhrOverride;
2952
+ var _httpManager;
2953
+ var _batchQueues = {};
2954
+ var _autoFlushEventsLimit;
2955
+ var _autoFlushBatchLimit;
2956
+ var _delayedBatchSendLatency = -1;
2957
+ var _delayedBatchReason;
2958
+ var _optimizeObject = true;
2959
+ var _isPageUnloadTriggered = false;
2960
+ dynamicProto(PostChannel, _this, function (_self, _base) {
2961
+ _initializeProfiles();
2962
+ _clearQueues();
2963
+ _setAutoLimits();
2964
+ _httpManager = new HttpManager(MaxNumberEventPerBatch, MaxConnections, MaxRetries, {
2965
+ requeue: _requeueEvents,
2966
+ send: _sendingEvent,
2967
+ sent: _eventsSentEvent,
2968
+ drop: _eventsDropped,
2969
+ rspFail: _eventsResponseFail,
2970
+ oth: _otherEvent
2971
+ });
2972
+ _self["_getDbgPlgTargets"] = function () {
2973
+ return [_httpManager];
2974
+ };
2975
+ _self.initialize = function (coreConfig, core, extensions) {
2976
+ doPerf(core, function () { return "PostChannel:initialize"; }, function () {
2977
+ var extendedCore = core;
2978
+ _base.initialize(coreConfig, core, extensions);
2979
+ _self.setInitialized(false);
2980
+ var ctx = _self._getTelCtx();
2981
+ coreConfig.extensionConfig[_self.identifier] = coreConfig.extensionConfig[_self.identifier] || {};
2982
+ _config = ctx.getExtCfg(_self.identifier);
2983
+ _self._setTimeoutOverride = _config.setTimeoutOverride ? _config.setTimeoutOverride : setTimeout.bind(globalContext);
2984
+ _self._clearTimeoutOverride = _config.clearTimeoutOverride ? _config.clearTimeoutOverride : clearTimeout.bind(globalContext);
2985
+ _optimizeObject = !_config.disableOptimizeObj && isChromium();
2986
+ var existingGetWParamMethod = extendedCore.getWParam;
2987
+ extendedCore.getWParam = function () {
2988
+ var wparam = 0;
2989
+ if (_config.ignoreMc1Ms0CookieProcessing) {
2990
+ wparam = wparam | 2;
2991
+ }
2992
+ return wparam | existingGetWParamMethod();
2993
+ };
2994
+ if (_config.eventsLimitInMem > 0) {
2995
+ _queueSizeLimit = _config.eventsLimitInMem;
2996
+ }
2997
+ if (_config.immediateEventLimit > 0) {
2998
+ _immediateQueueSizeLimit = _config.immediateEventLimit;
2999
+ }
3000
+ if (_config.autoFlushEventsLimit > 0) {
3001
+ _autoFlushEventsLimit = _config.autoFlushEventsLimit;
3002
+ }
3003
+ _setAutoLimits();
3004
+ if (_config.httpXHROverride && _config.httpXHROverride.sendPOST) {
3005
+ _xhrOverride = _config.httpXHROverride;
3006
+ }
3007
+ if (isValueAssigned(coreConfig.anonCookieName)) {
3008
+ _httpManager.addQueryStringParameter("anoncknm", coreConfig.anonCookieName);
3009
+ }
3010
+ _httpManager.sendHook = _config.payloadPreprocessor;
3011
+ _httpManager.sendListener = _config.payloadListener;
3012
+ var endpointUrl = _config.overrideEndpointUrl ? _config.overrideEndpointUrl : coreConfig.endpointUrl;
3013
+ _self._notificationManager = coreConfig.extensionConfig.NotificationManager;
3014
+ _httpManager.initialize(endpointUrl, _self.core, _self, _xhrOverride, _config);
3015
+ function _handleUnloadEvents(evt) {
3016
+ var theEvt = evt || getWindow().event;
3017
+ if (theEvt.type !== "beforeunload") {
3018
+ _isPageUnloadTriggered = true;
3019
+ _httpManager.setUnloading(_isPageUnloadTriggered);
3020
+ }
3021
+ _releaseAllQueues(2 , 2 );
3022
+ }
3023
+ var excludePageUnloadEvents = coreConfig.disablePageUnloadEvents || [];
3024
+ addPageUnloadEventListener(_handleUnloadEvents, excludePageUnloadEvents);
3025
+ addPageHideEventListener(_handleUnloadEvents, excludePageUnloadEvents);
3026
+ addPageShowEventListener(function (evt) {
3027
+ _isPageUnloadTriggered = false;
3028
+ _httpManager.setUnloading(_isPageUnloadTriggered);
3029
+ }, coreConfig.disablePageShowEvents);
3030
+ _self.setInitialized(true);
3031
+ }, function () { return ({ coreConfig: coreConfig, core: core, extensions: extensions }); });
3032
+ };
3033
+ _self.processTelemetry = function (ev, itemCtx) {
3034
+ setProcessTelemetryTimings(ev, _self.identifier);
3035
+ itemCtx = _self._getTelCtx(itemCtx);
3036
+ var channelConfig = itemCtx.getExtCfg(_self.identifier);
3037
+ var disableTelemetry = !!_config.disableTelemetry;
3038
+ if (channelConfig) {
3039
+ disableTelemetry = disableTelemetry || !!channelConfig.disableTelemetry;
3040
+ }
3041
+ var event = ev;
3042
+ if (!disableTelemetry && !_isTeardownCalled) {
3043
+ if (_config[strOverrideInstrumentationKey]) {
3044
+ event.iKey = _config[strOverrideInstrumentationKey];
3045
+ }
3046
+ if (channelConfig && channelConfig[strOverrideInstrumentationKey]) {
3047
+ event.iKey = channelConfig[strOverrideInstrumentationKey];
3048
+ }
3049
+ _addEventToQueues(event, true);
3050
+ if (_isPageUnloadTriggered) {
3051
+ _releaseAllQueues(2 , 2 );
3052
+ }
3053
+ else {
3054
+ _scheduleTimer();
3055
+ }
3056
+ }
3057
+ _self.processNext(event, itemCtx);
3058
+ };
3059
+ function _addEventToQueues(event, append) {
3060
+ if (!event.sendAttempt) {
3061
+ event.sendAttempt = 0;
3062
+ }
3063
+ if (!event.latency) {
3064
+ event.latency = EventLatency.Normal;
3065
+ }
3066
+ if (event.ext && event.ext["trace"]) {
3067
+ delete (event.ext["trace"]);
3068
+ }
3069
+ if (event.ext && event.ext["user"] && event.ext["user"]["id"]) {
3070
+ delete (event.ext["user"]["id"]);
3071
+ }
3072
+ if (_optimizeObject) {
3073
+ event.ext = optimizeObject(event.ext);
3074
+ if (event.baseData) {
3075
+ event.baseData = optimizeObject(event.baseData);
3076
+ }
3077
+ if (event.data) {
3078
+ event.data = optimizeObject(event.data);
3079
+ }
3080
+ }
3081
+ if (event.sync) {
3082
+ if (_currentBackoffCount || _paused) {
3083
+ event.latency = EventLatency.RealTime;
3084
+ event.sync = false;
3085
+ }
3086
+ else {
3087
+ if (_httpManager) {
3088
+ if (_optimizeObject) {
3089
+ event = optimizeObject(event);
3090
+ }
3091
+ _httpManager.sendSynchronousBatch(EventBatch.create(event.iKey, [event]), event.sync === true ? 1 : event.sync, 3 );
3092
+ return;
3093
+ }
3094
+ }
3095
+ }
3096
+ var evtLatency = event.latency;
3097
+ var queueSize = _queueSize;
3098
+ var queueLimit = _queueSizeLimit;
3099
+ if (evtLatency === EventLatency.Immediate) {
3100
+ queueSize = _immediateQueueSize;
3101
+ queueLimit = _immediateQueueSizeLimit;
3102
+ }
3103
+ var eventDropped = false;
3104
+ if (queueSize < queueLimit) {
3105
+ eventDropped = !_addEventToProperQueue(event, append);
3106
+ }
3107
+ else {
3108
+ var dropLatency = EventLatency.Normal;
3109
+ var dropNumber = EventsDroppedAtOneTime;
3110
+ if (evtLatency === EventLatency.Immediate) {
3111
+ dropLatency = EventLatency.Immediate;
3112
+ dropNumber = 1;
3113
+ }
3114
+ eventDropped = true;
3115
+ if (_dropEventWithLatencyOrLess(event.iKey, event.latency, dropLatency, dropNumber)) {
3116
+ eventDropped = !_addEventToProperQueue(event, append);
3117
+ }
3118
+ }
3119
+ if (eventDropped) {
3120
+ _notifyEvents(strEventsDiscarded, [event], EventsDiscardedReason.QueueFull);
3121
+ }
3122
+ }
3123
+ _self.setEventQueueLimits = function (eventLimit, autoFlushLimit) {
3124
+ _queueSizeLimit = eventLimit > 0 ? eventLimit : 10000;
3125
+ _autoFlushEventsLimit = autoFlushLimit > 0 ? autoFlushLimit : 0;
3126
+ _setAutoLimits();
3127
+ var doFlush = _queueSize > eventLimit;
3128
+ if (!doFlush && _autoFlushBatchLimit > 0) {
3129
+ for (var latency = EventLatency.Normal; !doFlush && latency <= EventLatency.RealTime; latency++) {
3130
+ var batchQueue = _batchQueues[latency];
3131
+ if (batchQueue && batchQueue.batches) {
3132
+ arrForEach(batchQueue.batches, function (theBatch) {
3133
+ if (theBatch && theBatch.count() >= _autoFlushBatchLimit) {
3134
+ doFlush = true;
3135
+ }
3136
+ });
3137
+ }
3138
+ }
3139
+ }
3140
+ _performAutoFlush(true, doFlush);
3141
+ };
3142
+ _self.teardown = function () {
3143
+ _releaseAllQueues(2 , 2 );
3144
+ _isTeardownCalled = true;
3145
+ _httpManager.teardown();
3146
+ };
3147
+ _self.pause = function () {
3148
+ _clearScheduledTimer();
3149
+ _paused = true;
3150
+ _httpManager.pause();
3151
+ };
3152
+ _self.resume = function () {
3153
+ _paused = false;
3154
+ _httpManager.resume();
3155
+ _scheduleTimer();
3156
+ };
3157
+ _self.addResponseHandler = function (responseHandler) {
3158
+ _httpManager._responseHandlers.push(responseHandler);
3159
+ };
3160
+ _self._loadTransmitProfiles = function (profiles) {
3161
+ _resetTransmitProfiles();
3162
+ objForEachKey(profiles, function (profileName, profileValue) {
3163
+ var profLen = profileValue.length;
3164
+ if (profLen >= 2) {
3165
+ var directValue = (profLen > 2 ? profileValue[2] : 0);
3166
+ profileValue.splice(0, profLen - 2);
3167
+ if (profileValue[1] < 0) {
3168
+ profileValue[0] = -1;
3169
+ }
3170
+ if (profileValue[1] > 0 && profileValue[0] > 0) {
3171
+ var timerMultiplier = profileValue[0] / profileValue[1];
3172
+ profileValue[0] = Math.ceil(timerMultiplier) * profileValue[1];
3173
+ }
3174
+ if (directValue >= 0 && profileValue[1] >= 0 && directValue > profileValue[1]) {
3175
+ directValue = profileValue[1];
3176
+ }
3177
+ profileValue.push(directValue);
3178
+ _profiles[profileName] = profileValue;
3179
+ }
3180
+ });
3181
+ };
3182
+ _self.flush = function (async, callback, sendReason) {
3183
+ if (async === void 0) { async = true; }
3184
+ if (!_paused) {
3185
+ _clearScheduledTimer();
3186
+ sendReason = sendReason || 1 ;
3187
+ if (async) {
3188
+ _queueBatches(EventLatency.Normal, 0 , sendReason);
3189
+ _resetQueueCounts();
3190
+ if (_flushCallbackTimerId == null) {
3191
+ _flushCallbackTimerId = _createTimer(function () {
3192
+ _flushImpl(callback, sendReason);
3193
+ }, 0);
3194
+ }
3195
+ else {
3196
+ _flushCallbackQueue.push(callback);
3197
+ }
3198
+ }
3199
+ else {
3200
+ _sendEventsForLatencyAndAbove(EventLatency.Normal, 1 , sendReason);
3201
+ if (callback !== null && callback !== undefined) {
3202
+ callback();
3203
+ }
3204
+ }
3205
+ }
3206
+ };
3207
+ _self.setMsaAuthTicket = function (ticket) {
3208
+ _httpManager.addHeader(strMsaDeviceTicket, ticket);
3209
+ };
3210
+ _self.hasEvents = _hasEvents;
3211
+ _self._setTransmitProfile = function (profileName) {
3212
+ if (_currentProfile !== profileName && _profiles[profileName] !== undefined) {
3213
+ _clearScheduledTimer();
3214
+ _currentProfile = profileName;
3215
+ _scheduleTimer();
3216
+ }
3217
+ };
3218
+ function _sendEventsForLatencyAndAbove(latency, sendType, sendReason) {
3219
+ var queued = _queueBatches(latency, sendType, sendReason);
3220
+ _httpManager.sendQueuedRequests(sendType, sendReason);
3221
+ return queued;
3222
+ }
3223
+ function _hasEvents() {
3224
+ return _queueSize > 0;
3225
+ }
3226
+ function _scheduleTimer() {
3227
+ if (_delayedBatchSendLatency >= 0 && _queueBatches(_delayedBatchSendLatency, 0 , _delayedBatchReason)) {
3228
+ _httpManager.sendQueuedRequests(0 , _delayedBatchReason);
3229
+ }
3230
+ if (_immediateQueueSize > 0 && !_immediateTimerId && !_paused) {
3231
+ var immediateTimeOut = _profiles[_currentProfile][2];
3232
+ if (immediateTimeOut >= 0) {
3233
+ _immediateTimerId = _createTimer(function () {
3234
+ _immediateTimerId = null;
3235
+ _sendEventsForLatencyAndAbove(EventLatency.Immediate, 0 , 1 );
3236
+ _scheduleTimer();
3237
+ }, immediateTimeOut);
3238
+ }
3239
+ }
3240
+ var timeOut = _profiles[_currentProfile][1];
3241
+ if (!_scheduledTimerId && !_flushCallbackTimerId && timeOut >= 0 && !_paused) {
3242
+ if (_hasEvents()) {
3243
+ _scheduledTimerId = _createTimer(function () {
3244
+ _scheduledTimerId = null;
3245
+ _sendEventsForLatencyAndAbove(_timerCount === 0 ? EventLatency.RealTime : EventLatency.Normal, 0 , 1 );
3246
+ _timerCount++;
3247
+ _timerCount %= 2;
3248
+ _scheduleTimer();
3249
+ }, timeOut);
3250
+ }
3251
+ else {
3252
+ _timerCount = 0;
3253
+ }
3254
+ }
3255
+ }
3256
+ _self._backOffTransmission = function () {
3257
+ if (_currentBackoffCount < MaxBackoffCount) {
3258
+ _currentBackoffCount++;
3259
+ _clearScheduledTimer();
3260
+ _scheduleTimer();
3261
+ }
3262
+ };
3263
+ _self._clearBackOff = function () {
3264
+ if (_currentBackoffCount) {
3265
+ _currentBackoffCount = 0;
3266
+ _clearScheduledTimer();
3267
+ _scheduleTimer();
3268
+ }
3269
+ };
3270
+ function _createTimer(theTimerFunc, timeOut) {
3271
+ if (timeOut === 0 && _currentBackoffCount) {
3272
+ timeOut = 1;
3273
+ }
3274
+ var timerMultiplier = 1000;
3275
+ if (_currentBackoffCount) {
3276
+ timerMultiplier = RetryPolicy$1.getMillisToBackoffForRetry(_currentBackoffCount - 1);
3277
+ }
3278
+ return _self._setTimeoutOverride(theTimerFunc, timeOut * timerMultiplier);
3279
+ }
3280
+ function _clearScheduledTimer() {
3281
+ if (_scheduledTimerId !== null) {
3282
+ _self._clearTimeoutOverride(_scheduledTimerId);
3283
+ _scheduledTimerId = null;
3284
+ _timerCount = 0;
3285
+ }
3286
+ }
3287
+ function _releaseAllQueues(sendType, sendReason) {
3288
+ _clearScheduledTimer();
3289
+ if (_flushCallbackTimerId) {
3290
+ _self._clearTimeoutOverride(_flushCallbackTimerId);
3291
+ _flushCallbackTimerId = null;
3292
+ }
3293
+ if (!_paused) {
3294
+ _sendEventsForLatencyAndAbove(EventLatency.Normal, sendType, sendReason);
3295
+ }
3296
+ }
3297
+ function _clearQueues() {
3298
+ _batchQueues[EventLatency.Immediate] = {
3299
+ batches: [],
3300
+ iKeyMap: {}
3301
+ };
3302
+ _batchQueues[EventLatency.RealTime] = {
3303
+ batches: [],
3304
+ iKeyMap: {}
3305
+ };
3306
+ _batchQueues[EventLatency.CostDeferred] = {
3307
+ batches: [],
3308
+ iKeyMap: {}
3309
+ };
3310
+ _batchQueues[EventLatency.Normal] = {
3311
+ batches: [],
3312
+ iKeyMap: {}
3313
+ };
3314
+ }
3315
+ function _getEventBatch(iKey, latency, create) {
3316
+ var batchQueue = _batchQueues[latency];
3317
+ if (!batchQueue) {
3318
+ latency = EventLatency.Normal;
3319
+ batchQueue = _batchQueues[latency];
3320
+ }
3321
+ var eventBatch = batchQueue.iKeyMap[iKey];
3322
+ if (!eventBatch && create) {
3323
+ eventBatch = EventBatch.create(iKey);
3324
+ batchQueue.batches.push(eventBatch);
3325
+ batchQueue.iKeyMap[iKey] = eventBatch;
3326
+ }
3327
+ return eventBatch;
3328
+ }
3329
+ function _performAutoFlush(isAsync, doFlush) {
3330
+ if (_httpManager.canSendRequest() && !_currentBackoffCount) {
3331
+ if (_autoFlushEventsLimit > 0 && _queueSize > _autoFlushEventsLimit) {
3332
+ doFlush = true;
3333
+ }
3334
+ if (doFlush && _flushCallbackTimerId == null) {
3335
+ _self.flush(isAsync, null, 20 );
3336
+ }
3337
+ }
3338
+ }
3339
+ function _addEventToProperQueue(event, append) {
3340
+ if (_optimizeObject) {
3341
+ event = optimizeObject(event);
3342
+ }
3343
+ var latency = event.latency;
3344
+ var eventBatch = _getEventBatch(event.iKey, latency, true);
3345
+ if (eventBatch.addEvent(event)) {
3346
+ if (latency !== EventLatency.Immediate) {
3347
+ _queueSize++;
3348
+ if (append && event.sendAttempt === 0) {
3349
+ _performAutoFlush(!event.sync, _autoFlushBatchLimit > 0 && eventBatch.count() >= _autoFlushBatchLimit);
3350
+ }
3351
+ }
3352
+ else {
3353
+ _immediateQueueSize++;
3354
+ }
3355
+ return true;
3356
+ }
3357
+ return false;
3358
+ }
3359
+ function _dropEventWithLatencyOrLess(iKey, latency, currentLatency, dropNumber) {
3360
+ while (currentLatency <= latency) {
3361
+ var eventBatch = _getEventBatch(iKey, latency, true);
3362
+ if (eventBatch && eventBatch.count() > 0) {
3363
+ var droppedEvents = eventBatch.split(0, dropNumber);
3364
+ var droppedCount = droppedEvents.count();
3365
+ if (droppedCount > 0) {
3366
+ if (currentLatency === EventLatency.Immediate) {
3367
+ _immediateQueueSize -= droppedCount;
3368
+ }
3369
+ else {
3370
+ _queueSize -= droppedCount;
3371
+ }
3372
+ _notifyBatchEvents(strEventsDiscarded, [droppedEvents], EventsDiscardedReason.QueueFull);
3373
+ return true;
3374
+ }
3375
+ }
3376
+ currentLatency++;
3377
+ }
3378
+ _resetQueueCounts();
3379
+ return false;
3380
+ }
3381
+ function _resetQueueCounts() {
3382
+ var immediateQueue = 0;
3383
+ var normalQueue = 0;
3384
+ var _loop_1 = function (latency) {
3385
+ var batchQueue = _batchQueues[latency];
3386
+ if (batchQueue && batchQueue.batches) {
3387
+ arrForEach(batchQueue.batches, function (theBatch) {
3388
+ if (latency === EventLatency.Immediate) {
3389
+ immediateQueue += theBatch.count();
3390
+ }
3391
+ else {
3392
+ normalQueue += theBatch.count();
3393
+ }
3394
+ });
3395
+ }
3396
+ };
3397
+ for (var latency = EventLatency.Normal; latency <= EventLatency.Immediate; latency++) {
3398
+ _loop_1(latency);
3399
+ }
3400
+ _queueSize = normalQueue;
3401
+ _immediateQueueSize = immediateQueue;
3402
+ }
3403
+ function _queueBatches(latency, sendType, sendReason) {
3404
+ var eventsQueued = false;
3405
+ var isAsync = sendType === 0 ;
3406
+ if (!isAsync || _httpManager.canSendRequest()) {
3407
+ doPerf(_self.core, function () { return "PostChannel._queueBatches"; }, function () {
3408
+ var droppedEvents = [];
3409
+ var latencyToProcess = EventLatency.Immediate;
3410
+ while (latencyToProcess >= latency) {
3411
+ var batchQueue = _batchQueues[latencyToProcess];
3412
+ if (batchQueue && batchQueue.batches && batchQueue.batches.length > 0) {
3413
+ arrForEach(batchQueue.batches, function (theBatch) {
3414
+ if (!_httpManager.addBatch(theBatch)) {
3415
+ droppedEvents = droppedEvents.concat(theBatch.events());
3416
+ }
3417
+ else {
3418
+ eventsQueued = eventsQueued || (theBatch && theBatch.count() > 0);
3419
+ }
3420
+ if (latencyToProcess === EventLatency.Immediate) {
3421
+ _immediateQueueSize -= theBatch.count();
3422
+ }
3423
+ else {
3424
+ _queueSize -= theBatch.count();
3425
+ }
3426
+ });
3427
+ batchQueue.batches = [];
3428
+ batchQueue.iKeyMap = {};
3429
+ }
3430
+ latencyToProcess--;
3431
+ }
3432
+ if (droppedEvents.length > 0) {
3433
+ _notifyEvents(strEventsDiscarded, droppedEvents, EventsDiscardedReason.KillSwitch);
3434
+ }
3435
+ if (eventsQueued && _delayedBatchSendLatency >= latency) {
3436
+ _delayedBatchSendLatency = -1;
3437
+ _delayedBatchReason = 0 ;
3438
+ }
3439
+ }, function () { return ({ latency: latency, sendType: sendType, sendReason: sendReason }); }, !isAsync);
3440
+ }
3441
+ else {
3442
+ _delayedBatchSendLatency = _delayedBatchSendLatency >= 0 ? Math.min(_delayedBatchSendLatency, latency) : latency;
3443
+ _delayedBatchReason = Math.max(_delayedBatchReason, sendReason);
3444
+ }
3445
+ return eventsQueued;
3446
+ }
3447
+ function _flushImpl(callback, sendReason) {
3448
+ _sendEventsForLatencyAndAbove(EventLatency.Normal, 0 , sendReason);
3449
+ _waitForIdleManager(function () {
3450
+ if (callback) {
3451
+ callback();
3452
+ }
3453
+ if (_flushCallbackQueue.length > 0) {
3454
+ _flushCallbackTimerId = _createTimer(function () { return _flushImpl(_flushCallbackQueue.shift(), sendReason); }, 0);
3455
+ }
3456
+ else {
3457
+ _flushCallbackTimerId = null;
3458
+ if (_hasEvents()) {
3459
+ _scheduleTimer();
3460
+ }
3461
+ }
3462
+ });
3463
+ }
3464
+ function _waitForIdleManager(callback) {
3465
+ if (_httpManager.isCompletelyIdle()) {
3466
+ callback();
3467
+ }
3468
+ else {
3469
+ _flushCallbackTimerId = _createTimer(function () {
3470
+ _waitForIdleManager(callback);
3471
+ }, FlushCheckTimer);
3472
+ }
3473
+ }
3474
+ function _resetTransmitProfiles() {
3475
+ _clearScheduledTimer();
3476
+ _initializeProfiles();
3477
+ _currentProfile = RT_PROFILE;
3478
+ _scheduleTimer();
3479
+ }
3480
+ function _initializeProfiles() {
3481
+ _profiles = {};
3482
+ _profiles[RT_PROFILE] = [2, 1, 0];
3483
+ _profiles[NRT_PROFILE] = [6, 3, 0];
3484
+ _profiles[BE_PROFILE] = [18, 9, 0];
3485
+ }
3486
+ function _requeueEvents(batches, reason) {
3487
+ var droppedEvents = [];
3488
+ arrForEach(batches, function (theBatch) {
3489
+ if (theBatch && theBatch.count() > 0) {
3490
+ arrForEach(theBatch.events(), function (theEvent) {
3491
+ if (theEvent) {
3492
+ if (theEvent.sync) {
3493
+ theEvent.latency = EventLatency.Immediate;
3494
+ theEvent.sync = false;
3495
+ }
3496
+ if (theEvent.sendAttempt < MaxSendAttempts) {
3497
+ setProcessTelemetryTimings(theEvent, _self.identifier);
3498
+ _addEventToQueues(theEvent, false);
3499
+ }
3500
+ else {
3501
+ droppedEvents.push(theEvent);
3502
+ }
3503
+ }
3504
+ });
3505
+ }
3506
+ });
3507
+ if (droppedEvents.length > 0) {
3508
+ _notifyEvents(strEventsDiscarded, droppedEvents, EventsDiscardedReason.NonRetryableStatus);
3509
+ }
3510
+ if (_isPageUnloadTriggered) {
3511
+ _releaseAllQueues(2 , 2 );
3512
+ }
3513
+ }
3514
+ function _callNotification(evtName, theArgs) {
3515
+ var manager = (_self._notificationManager || {});
3516
+ var notifyFunc = manager[evtName];
3517
+ if (notifyFunc) {
3518
+ try {
3519
+ notifyFunc.apply(manager, theArgs);
3520
+ }
3521
+ catch (e) {
3522
+ _self.diagLog().throwInternal(LoggingSeverity.CRITICAL, _ExtendedInternalMessageId.NotificationException, evtName + " notification failed: " + e);
3523
+ }
3524
+ }
3525
+ }
3526
+ function _notifyEvents(evtName, theEvents) {
3527
+ var extraArgs = [];
3528
+ for (var _i = 2; _i < arguments.length; _i++) {
3529
+ extraArgs[_i - 2] = arguments[_i];
3530
+ }
3531
+ if (theEvents && theEvents.length > 0) {
3532
+ _callNotification(evtName, [theEvents].concat(extraArgs));
3533
+ }
3534
+ }
3535
+ function _notifyBatchEvents(evtName, batches) {
3536
+ var extraArgs = [];
3537
+ for (var _i = 2; _i < arguments.length; _i++) {
3538
+ extraArgs[_i - 2] = arguments[_i];
3539
+ }
3540
+ if (batches && batches.length > 0) {
3541
+ arrForEach(batches, function (theBatch) {
3542
+ if (theBatch && theBatch.count() > 0) {
3543
+ _callNotification(evtName, [theBatch.events()].concat(extraArgs));
3544
+ }
3545
+ });
3546
+ }
3547
+ }
3548
+ function _sendingEvent(batches, reason, isSyncRequest) {
3549
+ if (batches && batches.length > 0) {
3550
+ _callNotification("eventsSendRequest", [(reason >= 1000 && reason <= 1999 ?
3551
+ reason - 1000 :
3552
+ 0 ), isSyncRequest !== true]);
3553
+ }
3554
+ }
3555
+ function _eventsSentEvent(batches, reason) {
3556
+ _notifyBatchEvents("eventsSent", batches, reason);
3557
+ _scheduleTimer();
3558
+ }
3559
+ function _eventsDropped(batches, reason) {
3560
+ _notifyBatchEvents(strEventsDiscarded, batches, (reason >= 8000 && reason <= 8999 ?
3561
+ reason - 8000 :
3562
+ EventsDiscardedReason.Unknown));
3563
+ }
3564
+ function _eventsResponseFail(batches) {
3565
+ _notifyBatchEvents(strEventsDiscarded, batches, EventsDiscardedReason.NonRetryableStatus);
3566
+ _scheduleTimer();
3567
+ }
3568
+ function _otherEvent(batches, reason) {
3569
+ _notifyBatchEvents(strEventsDiscarded, batches, EventsDiscardedReason.Unknown);
3570
+ _scheduleTimer();
3571
+ }
3572
+ function _setAutoLimits() {
3573
+ if (!_config || !_config.disableAutoBatchFlushLimit) {
3574
+ _autoFlushBatchLimit = Math.max(MaxNumberEventPerBatch * (MaxConnections + 1), _queueSizeLimit / 6);
3575
+ }
3576
+ else {
3577
+ _autoFlushBatchLimit = 0;
3578
+ }
3579
+ }
3580
+ });
3581
+ return _this;
3582
+ }
3583
+ return PostChannel;
3584
+ }(BaseTelemetryPlugin));
3585
+ var PostChannel$1 = PostChannel;
3586
+
3587
+ exports.BE_PROFILE = BE_PROFILE;
3588
+ exports.NRT_PROFILE = NRT_PROFILE;
3589
+ exports.PostChannel = PostChannel$1;
3590
+ exports.RT_PROFILE = RT_PROFILE;
3591
+
3592
+ (function(obj, prop, descriptor) { /* ai_es3_polyfil defineProperty */ var func = Object["defineProperty"]; if (func) { try { return func(obj, prop, descriptor); } catch(e) { /* IE8 defines defineProperty, but will throw */ } } if (descriptor && typeof descriptor.value !== undefined) { obj[prop] = descriptor.value; } return obj; })(exports, '__esModule', { value: true });
3593
+
3594
+ })(this.oneDS = this.oneDS || {});
3595
+ //# sourceMappingURL=ms.post-3.1.10.gbl.js.map