@microsoft/applicationinsights-channel-js 2.8.0-nightly.2202-06 → 2.8.0-nightly.2204-06

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 (41) hide show
  1. package/browser/applicationinsights-channel-js.integrity.json +9 -9
  2. package/browser/applicationinsights-channel-js.js +1666 -1012
  3. package/browser/applicationinsights-channel-js.js.map +1 -1
  4. package/browser/applicationinsights-channel-js.min.js +2 -2
  5. package/browser/applicationinsights-channel-js.min.js.map +1 -1
  6. package/dist/applicationinsights-channel-js.api.json +56 -58
  7. package/dist/applicationinsights-channel-js.api.md +0 -2
  8. package/dist/applicationinsights-channel-js.d.ts +1 -2
  9. package/dist/applicationinsights-channel-js.js +1666 -1012
  10. package/dist/applicationinsights-channel-js.js.map +1 -1
  11. package/dist/applicationinsights-channel-js.min.js +2 -2
  12. package/dist/applicationinsights-channel-js.min.js.map +1 -1
  13. package/dist/applicationinsights-channel-js.rollup.d.ts +1 -2
  14. package/dist-esm/EnvelopeCreator.js +5 -5
  15. package/dist-esm/EnvelopeCreator.js.map +1 -1
  16. package/dist-esm/Interfaces.js +1 -1
  17. package/dist-esm/Offline.js +77 -65
  18. package/dist-esm/Offline.js.map +1 -1
  19. package/dist-esm/SendBuffer.js +7 -7
  20. package/dist-esm/SendBuffer.js.map +1 -1
  21. package/dist-esm/Sender.js +73 -63
  22. package/dist-esm/Sender.js.map +1 -1
  23. package/dist-esm/Serializer.js +10 -10
  24. package/dist-esm/Serializer.js.map +1 -1
  25. package/dist-esm/TelemetryProcessors/Sample.js +3 -3
  26. package/dist-esm/TelemetryProcessors/Sample.js.map +1 -1
  27. package/dist-esm/TelemetryProcessors/SamplingScoreGenerators/HashCodeScoreGenerator.js +1 -1
  28. package/dist-esm/TelemetryProcessors/SamplingScoreGenerators/SamplingScoreGenerator.js +1 -1
  29. package/dist-esm/applicationinsights-channel-js.js +1 -1
  30. package/package.json +4 -4
  31. package/src/EnvelopeCreator.ts +8 -8
  32. package/src/Offline.ts +88 -76
  33. package/src/SendBuffer.ts +14 -14
  34. package/src/Sender.ts +106 -113
  35. package/src/Serializer.ts +17 -21
  36. package/src/TelemetryProcessors/Sample.ts +1 -1
  37. package/src/TelemetryProcessors/SamplingScoreGenerators/HashCodeScoreGenerator.ts +3 -1
  38. package/types/Offline.d.ts +8 -11
  39. package/types/Sender.d.ts +0 -1
  40. package/types/TelemetryProcessors/Sample.d.ts +2 -2
  41. package/types/tsdoc-metadata.json +1 -1
package/src/Sender.ts CHANGED
@@ -15,12 +15,13 @@ import {
15
15
  } from "@microsoft/applicationinsights-common";
16
16
  import {
17
17
  ITelemetryItem, IProcessTelemetryContext, IConfiguration,
18
- _InternalMessageId, LoggingSeverity, IDiagnosticLogger, IAppInsightsCore, IPlugin,
18
+ _eInternalMessageId, eLoggingSeverity, IDiagnosticLogger, IAppInsightsCore, IPlugin,
19
19
  getWindow, getNavigator, getJSON, BaseTelemetryPlugin, ITelemetryPluginChain, INotificationManager,
20
- SendRequestReason, objForEachKey, isNullOrUndefined, arrForEach, dateNow, dumpObj, getExceptionName, getIEVersion, throwError, objKeys,
21
- isBeaconsSupported, isFetchSupported, useXDomainRequest, isXhrSupported, isArray
20
+ SendRequestReason, objForEachKey, isNullOrUndefined, arrForEach, dateNow, dumpObj, getExceptionName, getIEVersion, objKeys,
21
+ isBeaconsSupported, isFetchSupported, useXDomainRequest, isXhrSupported, isArray, createUniqueNamespace, mergeEvtNamespace,
22
+ IProcessTelemetryUnloadContext, ITelemetryUnloadState, _throwInternal, _warnToConsole
22
23
  } from "@microsoft/applicationinsights-core-js";
23
- import { Offline } from "./Offline";
24
+ import { createOfflineListener, IOfflineListener } from "./Offline";
24
25
  import { Sample } from "./TelemetryProcessors/Sample"
25
26
  import dynamicProto from "@microsoft/dynamicproto-js";
26
27
 
@@ -103,7 +104,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
103
104
  /**
104
105
  * The configuration for this sender instance
105
106
  */
106
- public readonly _senderConfig: ISenderConfig;
107
+ public readonly _senderConfig: ISenderConfig = _getDefaultAppInsightsChannelConfig();
107
108
 
108
109
  /**
109
110
  * A method which will cause data to be send to the url
@@ -125,57 +126,24 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
125
126
  constructor() {
126
127
  super();
127
128
 
128
- /**
129
- * How many times in a row a retryable error condition has occurred.
130
- */
131
- let _consecutiveErrors: number;
132
-
133
- /**
134
- * The time to retry at in milliseconds from 1970/01/01 (this makes the timer calculation easy).
135
- */
136
- let _retryAt: number;
137
-
138
- /**
139
- * The time of the last send operation.
140
- */
141
- let _lastSend: number;
142
-
143
- /**
144
- * Flag indicating that the sending should be paused
145
- */
146
- let _paused = false;
147
-
148
- /**
149
- * Handle to the timer for delayed sending of batches of data.
150
- */
151
- let _timeoutHandle: any;
152
-
129
+ // Don't set the defaults here, set them in the _initDefaults() as this is also called during unload
130
+ let _consecutiveErrors: number; // How many times in a row a retryable error condition has occurred.
131
+ let _retryAt: number; // The time to retry at in milliseconds from 1970/01/01 (this makes the timer calculation easy).
132
+ let _lastSend: number; // The time of the last send operation.
133
+ let _paused: boolean; // Flag indicating that the sending should be paused
134
+ let _timeoutHandle: any; // Handle to the timer for delayed sending of batches of data.
153
135
  let _serializer: Serializer;
154
-
155
136
  let _stamp_specific_redirects: number;
156
-
157
- let _headers: { [name: string]: string } = {};
158
-
159
- // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)
160
- let _syncFetchPayload = 0;
161
-
162
- /**
163
- * The sender to use if the payload size is too large
164
- */
165
- let _fallbackSender: SenderFunction;
166
-
167
- /**
168
- * The identified sender to use for the synchronous unload stage
169
- */
170
- let _syncUnloadSender: SenderFunction;
171
-
172
- this._senderConfig = _getDefaultAppInsightsChannelConfig();
137
+ let _headers: { [name: string]: string };
138
+ let _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)
139
+ let _fallbackSender: SenderFunction; // The sender to use if the payload size is too large
140
+ let _syncUnloadSender: SenderFunction; // The identified sender to use for the synchronous unload stage
141
+ let _offlineListener: IOfflineListener;
142
+ let _evtNamespace: string | string[];
173
143
 
174
144
  dynamicProto(Sender, this, (_self, _base) => {
175
145
 
176
- function _notImplemented() {
177
- throwError("Method not implemented.");
178
- }
146
+ _initDefaults();
179
147
 
180
148
  _self.pause = () => {
181
149
  _clearScheduledTimer();
@@ -196,16 +164,16 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
196
164
  }
197
165
  };
198
166
 
199
- _self.flush = () => {
167
+ _self.flush = (isAsync: boolean = true, callBack?: () => void, sendReason?: SendRequestReason) => {
200
168
  if (!_paused) {
201
169
  // Clear the normal schedule timer as we are going to try and flush ASAP
202
170
  _clearScheduledTimer();
203
171
 
204
172
  try {
205
- _self.triggerSend(true, null, SendRequestReason.ManualFlush);
173
+ _self.triggerSend(isAsync, null, sendReason || SendRequestReason.ManualFlush);
206
174
  } catch (e) {
207
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
208
- _InternalMessageId.FlushFailed,
175
+ _throwInternal(_self.diagLog(), eLoggingSeverity.CRITICAL,
176
+ _eInternalMessageId.FlushFailed,
209
177
  "flush failed, telemetry will not be collected: " + getExceptionName(e),
210
178
  { exception: dumpObj(e) });
211
179
  }
@@ -218,8 +186,8 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
218
186
  try {
219
187
  _self.triggerSend(true, _doUnloadSend, SendRequestReason.Unload);
220
188
  } catch (e) {
221
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
222
- _InternalMessageId.FailedToSendQueuedTelemetry,
189
+ _throwInternal(_self.diagLog(), eLoggingSeverity.CRITICAL,
190
+ _eInternalMessageId.FailedToSendQueuedTelemetry,
223
191
  "failed to flush with beacon sender on page unload, telemetry will not be collected: " + getExceptionName(e),
224
192
  { exception: dumpObj(e) });
225
193
  }
@@ -229,13 +197,15 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
229
197
  }
230
198
  };
231
199
 
232
- _self.teardown = _notImplemented;
233
-
234
200
  _self.addHeader = (name: string, value: string) => {
235
201
  _headers[name] = value;
236
202
  };
237
203
 
238
204
  _self.initialize = (config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain): void => {
205
+ if (_self.isInitialized()) {
206
+ _throwInternal(_self.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.SenderNotInitialized, "Sender is already initialized");
207
+ }
208
+
239
209
  _base.initialize(config, core, extensions, pluginChain);
240
210
  let ctx = _self._getTelCtx();
241
211
  let identifier = _self.identifier;
@@ -246,6 +216,8 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
246
216
  _self._sender = null;
247
217
  _stamp_specific_redirects = 0;
248
218
  let diagLog = _self.diagLog();
219
+ _evtNamespace = mergeEvtNamespace(createUniqueNamespace("Sender"), core.evtNamespace && core.evtNamespace());
220
+ _offlineListener = createOfflineListener(_evtNamespace);
249
221
 
250
222
  const defaultConfig = _getDefaultAppInsightsChannelConfig();
251
223
  objForEachKey(defaultConfig, (field, value) => {
@@ -257,9 +229,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
257
229
  _self._sample = new Sample(_self._senderConfig.samplingPercentage(), diagLog);
258
230
 
259
231
  if(!_validateInstrumentationKey(config)) {
260
- diagLog.throwInternal(
261
- LoggingSeverity.CRITICAL,
262
- _InternalMessageId.InvalidInstrumentationKey, "Invalid Instrumentation key "+config.instrumentationKey);
232
+ _throwInternal(diagLog,
233
+ eLoggingSeverity.CRITICAL,
234
+ _eInternalMessageId.InvalidInstrumentationKey, "Invalid Instrumentation key "+config.instrumentationKey);
263
235
  }
264
236
 
265
237
  if (!isInternalApplicationInsightsEndpoint(_self._senderConfig.endpointUrl()) && _self._senderConfig.customHeaders() && _self._senderConfig.customHeaders().length > 0) {
@@ -317,13 +289,13 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
317
289
 
318
290
  // validate input
319
291
  if (!telemetryItem) {
320
- itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSendEmptyTelemetry, "Cannot send empty telemetry");
292
+ _throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.CannotSendEmptyTelemetry, "Cannot send empty telemetry");
321
293
  return;
322
294
  }
323
295
 
324
296
  // validate event
325
297
  if (telemetryItem.baseData && !telemetryItem.baseType) {
326
- itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.InvalidEvent, "Cannot send telemetry without baseData and baseType");
298
+ _throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.InvalidEvent, "Cannot send telemetry without baseData and baseType");
327
299
  return;
328
300
  }
329
301
 
@@ -334,14 +306,14 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
334
306
 
335
307
  // ensure a sender was constructed
336
308
  if (!_self._sender) {
337
- itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.SenderNotInitialized, "Sender was not initialized");
309
+ _throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.SenderNotInitialized, "Sender was not initialized");
338
310
  return;
339
311
  }
340
312
 
341
313
  // check if this item should be sampled in, else add sampleRate tag
342
314
  if (!_isSampledIn(telemetryItem)) {
343
315
  // Item is sampled out, do not send it
344
- itemCtx.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TelemetrySampledAndNotSent,
316
+ _throwInternal(itemCtx.diagLog(), eLoggingSeverity.WARNING, _eInternalMessageId.TelemetrySampledAndNotSent,
345
317
  "Telemetry item was sampled out and not sent", { SampleRate: _self._sample.sampleRate });
346
318
  return;
347
319
  } else {
@@ -354,7 +326,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
354
326
  let defaultEnvelopeIkey = telemetryItem.iKey || _self._senderConfig.instrumentationKey();
355
327
  let aiEnvelope = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, itemCtx.diagLog(), convertUndefined);
356
328
  if (!aiEnvelope) {
357
- itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CreateEnvelopeError, "Unable to create an AppInsights envelope");
329
+ _throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.CreateEnvelopeError, "Unable to create an AppInsights envelope");
358
330
  return;
359
331
  }
360
332
 
@@ -365,13 +337,13 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
365
337
  try {
366
338
  if (callBack && callBack(aiEnvelope) === false) {
367
339
  doNotSendItem = true;
368
- itemCtx.diagLog().warnToConsole("Telemetry processor check returns false");
340
+ _warnToConsole(itemCtx.diagLog(), "Telemetry processor check returns false");
369
341
  }
370
342
  } catch (e) {
371
343
  // log error but dont stop executing rest of the telemetry initializers
372
344
  // doNotSendItem = true;
373
- itemCtx.diagLog().throwInternal(
374
- LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e),
345
+ _throwInternal(itemCtx.diagLog(),
346
+ eLoggingSeverity.CRITICAL, _eInternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e),
375
347
  { exception: dumpObj(e) }, true);
376
348
  }
377
349
  });
@@ -400,9 +372,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
400
372
  _setupTimer();
401
373
 
402
374
  } catch (e) {
403
- itemCtx.diagLog().throwInternal(
404
- LoggingSeverity.WARNING,
405
- _InternalMessageId.FailedAddingTelemetryToBuffer,
375
+ _throwInternal(itemCtx.diagLog(),
376
+ eLoggingSeverity.WARNING,
377
+ _eInternalMessageId.FailedAddingTelemetryToBuffer,
406
378
  "Failed adding telemetry to the sender's buffer, some telemetry will be lost: " + getExceptionName(e),
407
379
  { exception: dumpObj(e) });
408
380
  }
@@ -457,9 +429,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
457
429
  /* Ignore this error for IE under v10 */
458
430
  let ieVer = getIEVersion();
459
431
  if (!ieVer || ieVer > 9) {
460
- _self.diagLog().throwInternal(
461
- LoggingSeverity.CRITICAL,
462
- _InternalMessageId.TransmissionFailed,
432
+ _throwInternal(_self.diagLog(),
433
+ eLoggingSeverity.CRITICAL,
434
+ _eInternalMessageId.TransmissionFailed,
463
435
  "Telemetry transmission failed, some telemetry will be lost: " + getExceptionName(e),
464
436
  { exception: dumpObj(e) });
465
437
  }
@@ -467,13 +439,19 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
467
439
  }
468
440
  };
469
441
 
442
+ _self._doTeardown = (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => {
443
+ _self.onunloadFlush();
444
+ _offlineListener.unload();
445
+ _initDefaults();
446
+ };
447
+
470
448
  /**
471
449
  * error handler
472
450
  */
473
451
  _self._onError = (payload: string[], message: string, event?: ErrorEvent) => {
474
- _self.diagLog().throwInternal(
475
- LoggingSeverity.WARNING,
476
- _InternalMessageId.OnError,
452
+ _throwInternal(_self.diagLog(),
453
+ eLoggingSeverity.WARNING,
454
+ _eInternalMessageId.OnError,
477
455
  "Failed to send telemetry.",
478
456
  { message });
479
457
 
@@ -510,9 +488,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
510
488
  if (retry.length > 0) {
511
489
  _resendPayload(retry);
512
490
 
513
- _self.diagLog().throwInternal(
514
- LoggingSeverity.WARNING,
515
- _InternalMessageId.TransmissionFailed, "Partial success. " +
491
+ _throwInternal(_self.diagLog(),
492
+ eLoggingSeverity.WARNING,
493
+ _eInternalMessageId.TransmissionFailed, "Partial success. " +
516
494
  "Delivered: " + payload.length + ", Failed: " + failed.length +
517
495
  ". Will retry to send " + retry.length + " our of " + results.itemsReceived + " items");
518
496
  }
@@ -572,22 +550,22 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
572
550
 
573
551
  if (!_self._senderConfig.isRetryDisabled() && _isRetriable(status)) {
574
552
  _resendPayload(payload);
575
- _self.diagLog().throwInternal(
576
- LoggingSeverity.WARNING,
577
- _InternalMessageId.TransmissionFailed, ". " +
553
+ _throwInternal(_self.diagLog(),
554
+ eLoggingSeverity.WARNING,
555
+ _eInternalMessageId.TransmissionFailed, ". " +
578
556
  "Response code " + status + ". Will retry to send " + payload.length + " items.");
579
557
  } else {
580
558
  _self._onError(payload, errorMessage);
581
559
  }
582
- } else if (Offline.isOffline()) { // offline
560
+ } else if (_offlineListener && !_offlineListener.isOnline()) { // offline
583
561
  // Note: Don't check for status == 0, since adblock gives this code
584
562
  if (!_self._senderConfig.isRetryDisabled()) {
585
563
  const offlineBackOffMultiplier = 10; // arbritrary number
586
564
  _resendPayload(payload, offlineBackOffMultiplier);
587
565
 
588
- _self.diagLog().throwInternal(
589
- LoggingSeverity.WARNING,
590
- _InternalMessageId.TransmissionFailed, `. Offline - Response Code: ${status}. Offline status: ${Offline.isOffline()}. Will retry to send ${payload.length} items.`);
566
+ _throwInternal(_self.diagLog(),
567
+ eLoggingSeverity.WARNING,
568
+ _eInternalMessageId.TransmissionFailed, `. Offline - Response Code: ${status}. Offline status: ${!_offlineListener.isOnline()}. Will retry to send ${payload.length} items.`);
591
569
  }
592
570
  } else {
593
571
 
@@ -614,9 +592,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
614
592
 
615
593
  function _checkAndUpdateEndPointUrl(responseUrl: string) {
616
594
  // Maximum stamp specific redirects allowed(uncomment this when breeze is ready with not allowing redirects feature)
617
- if(_stamp_specific_redirects >= 10) {
618
- // _self._senderConfig.endpointUrl = () => Sender._getDefaultAppInsightsChannelConfig().endpointUrl()+"/?redirect=false";
619
- // _stamp_specific_redirects = 0;
595
+ if(_stamp_specific_redirects >= 10) {
596
+ // _self._senderConfig.endpointUrl = () => Sender._getDefaultAppInsightsChannelConfig().endpointUrl()+"/?redirect=false";
597
+ // _stamp_specific_redirects = 0;
620
598
  return false;
621
599
  }
622
600
  if(!isNullOrUndefined(responseUrl) && responseUrl !== "") {
@@ -682,8 +660,8 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
682
660
  }
683
661
 
684
662
  if (droppedPayload.length > 0) {
685
- _fallbackSender(droppedPayload, true);
686
- _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, ". " + "Failed to send telemetry with Beacon API, retried with normal sender.");
663
+ _fallbackSender && _fallbackSender(droppedPayload, true);
664
+ _throwInternal(_self.diagLog(), eLoggingSeverity.WARNING, _eInternalMessageId.TransmissionFailed, ". " + "Failed to send telemetry with Beacon API, retried with normal sender.");
687
665
  }
688
666
  }
689
667
  }
@@ -740,7 +718,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
740
718
  } else {
741
719
  // Payload is going to be too big so just try and send via XHR
742
720
  _fallbackSender && _fallbackSender(payload, true);
743
- _self.diagLog().throwInternal(LoggingSeverity.WARNING, _InternalMessageId.TransmissionFailed, ". " + "Failed to send telemetry with Beacon API, retried with xhrSender.");
721
+ _throwInternal(_self.diagLog(), eLoggingSeverity.WARNING, _eInternalMessageId.TransmissionFailed, ". " + "Failed to send telemetry with Beacon API, retried with xhrSender.");
744
722
  }
745
723
  }
746
724
  }
@@ -750,16 +728,16 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
750
728
  * @param payload {string} - The data payload to be sent.
751
729
  * @param isAsync {boolean} - not used
752
730
  */
753
- function _fetchSender(payload: string[], isAsync: boolean) {
754
- _doFetchSender(payload, true);
755
- }
731
+ function _fetchSender(payload: string[], isAsync: boolean) {
732
+ _doFetchSender(payload, true);
733
+ }
756
734
 
757
735
  /**
758
736
  * Send fetch API request
759
737
  * @param payload {string} - The data payload to be sent.
760
738
  * @param isAsync {boolean} - For fetch this identifies whether we are "unloading" (false) or a normal request
761
739
  */
762
- function _doFetchSender(payload: string[], isAsync: boolean) {
740
+ function _doFetchSender(payload: string[], isAsync: boolean) {
763
741
  const endPointUrl = _self._senderConfig.endpointUrl();
764
742
  const batch = _self._buffer.batchPayloads(payload);
765
743
  const plainTextBatch = new Blob([batch], { type: "application/json" });
@@ -865,9 +843,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
865
843
  }
866
844
  }
867
845
  } catch (e) {
868
- _self.diagLog().throwInternal(
869
- LoggingSeverity.CRITICAL,
870
- _InternalMessageId.InvalidBackendResponse,
846
+ _throwInternal(_self.diagLog(),
847
+ eLoggingSeverity.CRITICAL,
848
+ _eInternalMessageId.InvalidBackendResponse,
871
849
  "Cannot parse the response. " + getExceptionName(e),
872
850
  {
873
851
  response
@@ -985,12 +963,12 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
985
963
  // If the protocol doesn't match, we can't send the telemetry :(.
986
964
  const hostingProtocol = _window && _window.location && _window.location.protocol || "";
987
965
  if (_self._senderConfig.endpointUrl().lastIndexOf(hostingProtocol, 0) !== 0) {
988
- _self.diagLog().throwInternal(
989
- LoggingSeverity.WARNING,
990
- _InternalMessageId.TransmissionFailed, ". " +
966
+ _throwInternal(_self.diagLog(),
967
+ eLoggingSeverity.WARNING,
968
+ _eInternalMessageId.TransmissionFailed, ". " +
991
969
  "Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.");
992
970
 
993
- buffer.clear();
971
+ buffer.clear();
994
972
  return;
995
973
  }
996
974
 
@@ -1029,8 +1007,8 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
1029
1007
  try {
1030
1008
  manager.eventsSendRequest(sendRequest, isAsync);
1031
1009
  } catch (e) {
1032
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
1033
- _InternalMessageId.NotificationException,
1010
+ _throwInternal(_self.diagLog(), eLoggingSeverity.CRITICAL,
1011
+ _eInternalMessageId.NotificationException,
1034
1012
  "send request notification failed: " + getExceptionName(e),
1035
1013
  { exception: dumpObj(e) });
1036
1014
  }
@@ -1051,6 +1029,25 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
1051
1029
  return regexp.test(config.instrumentationKey);
1052
1030
  }
1053
1031
 
1032
+ function _initDefaults() {
1033
+ _self._sender = null;
1034
+ _self._buffer = null;
1035
+ _self._appId = null;
1036
+ _self._sample = null;
1037
+ _headers = {};
1038
+ _offlineListener = null;
1039
+ _consecutiveErrors = 0;
1040
+ _retryAt = null;
1041
+ _lastSend = null;
1042
+ _paused = false;
1043
+ _timeoutHandle = null;
1044
+ _serializer = null;
1045
+ _stamp_specific_redirects = 0;
1046
+ _syncFetchPayload = 0;
1047
+ _fallbackSender = null;
1048
+ _syncUnloadSender = null;
1049
+ _evtNamespace = null;
1050
+ }
1054
1051
  });
1055
1052
  }
1056
1053
 
@@ -1088,10 +1085,6 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
1088
1085
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
1089
1086
  }
1090
1087
 
1091
- public teardown(): void {
1092
- // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
1093
- }
1094
-
1095
1088
  public initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain): void {
1096
1089
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
1097
1090
  }
@@ -1149,7 +1142,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
1149
1142
  * @param name - Header name.
1150
1143
  * @param value - Header value.
1151
1144
  */
1152
- public addHeader(name: string, value: string) {
1145
+ public addHeader(name: string, value: string) {
1153
1146
  // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging
1154
1147
  }
1155
1148
  }
package/src/Serializer.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ISerializable, FieldType } from "@microsoft/applicationinsights-common";
2
2
  import {
3
- IDiagnosticLogger, LoggingSeverity, _InternalMessageId, getJSON, objForEachKey, isFunction, isObject, isArray
3
+ IDiagnosticLogger, eLoggingSeverity, _eInternalMessageId, getJSON, objForEachKey, isFunction, isObject, isArray, _throwInternal
4
4
  } from "@microsoft/applicationinsights-core-js";
5
5
  import dynamicProto from "@microsoft/dynamicproto-js"
6
6
 
@@ -17,7 +17,7 @@ export class Serializer {
17
17
  return getJSON().stringify(output);
18
18
  } catch (e) {
19
19
  // if serialization fails return an empty string
20
- logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSerializeObject, (e && isFunction(e.toString)) ? e.toString() : "Error serializing object", null, true);
20
+ _throwInternal(logger, eLoggingSeverity.CRITICAL, _eInternalMessageId.CannotSerializeObject, (e && isFunction(e.toString)) ? e.toString() : "Error serializing object", null, true);
21
21
  }
22
22
  }
23
23
 
@@ -26,12 +26,12 @@ export class Serializer {
26
26
  let output = {};
27
27
 
28
28
  if (!source) {
29
- logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSerializeObject, "cannot serialize object because it is null or undefined", { name }, true);
29
+ _throwInternal(logger, eLoggingSeverity.CRITICAL, _eInternalMessageId.CannotSerializeObject, "cannot serialize object because it is null or undefined", { name }, true);
30
30
  return output;
31
31
  }
32
32
 
33
33
  if (source[circularReferenceCheck]) {
34
- logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CircularReferenceDetected, "Circular reference detected while serializing object", { name }, true);
34
+ _throwInternal(logger, eLoggingSeverity.WARNING, _eInternalMessageId.CircularReferenceDetected, "Circular reference detected while serializing object", { name }, true);
35
35
  return output;
36
36
  }
37
37
 
@@ -46,7 +46,7 @@ export class Serializer {
46
46
  } else if (isArray(source)) {
47
47
  output = _serializeArray(source as any, name);
48
48
  } else {
49
- logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.CannotSerializeObjectNonSerializable, "Attempting to serialize an object which does not implement ISerializable", { name }, true);
49
+ _throwInternal(logger, eLoggingSeverity.WARNING, _eInternalMessageId.CannotSerializeObjectNonSerializable, "Attempting to serialize an object which does not implement ISerializable", { name }, true);
50
50
 
51
51
  try {
52
52
  // verify that the object can be stringified
@@ -54,7 +54,7 @@ export class Serializer {
54
54
  output = source;
55
55
  } catch (e) {
56
56
  // if serialization fails return an empty string
57
- logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.CannotSerializeObject, (e && isFunction(e.toString)) ? e.toString() : "Error serializing object", null, true);
57
+ _throwInternal(logger, eLoggingSeverity.CRITICAL, _eInternalMessageId.CannotSerializeObject, (e && isFunction(e.toString)) ? e.toString() : "Error serializing object", null, true);
58
58
  }
59
59
  }
60
60
 
@@ -71,9 +71,9 @@ export class Serializer {
71
71
  const isObj = isObject(source[field]) && source[field] !== null;
72
72
 
73
73
  if (isRequired && !isPresent && !isArray) {
74
- logger.throwInternal(
75
- LoggingSeverity.CRITICAL,
76
- _InternalMessageId.MissingRequiredFieldSpecification,
74
+ _throwInternal(logger,
75
+ eLoggingSeverity.CRITICAL,
76
+ _eInternalMessageId.MissingRequiredFieldSpecification,
77
77
  "Missing required field specification. The field is required but not present on source",
78
78
  { field, name });
79
79
 
@@ -109,9 +109,9 @@ export class Serializer {
109
109
 
110
110
  if (!!sources) {
111
111
  if (!isArray(sources)) {
112
- logger.throwInternal(
113
- LoggingSeverity.CRITICAL,
114
- _InternalMessageId.ItemNotInArray,
112
+ _throwInternal(logger,
113
+ eLoggingSeverity.CRITICAL,
114
+ _eInternalMessageId.ItemNotInArray,
115
115
  "This field was specified as an array in the contract but the item is not an array.\r\n",
116
116
  { name }, true);
117
117
  } else {
@@ -139,12 +139,10 @@ export class Serializer {
139
139
  output[field] = "null";
140
140
  } else if (!value.toString) {
141
141
  output[field] = "invalid field: toString() is not defined.";
142
- }
143
- else {
142
+ } else {
144
143
  output[field] = value.toString();
145
144
  }
146
- }
147
- else if (expectedType === "number") {
145
+ } else if (expectedType === "number") {
148
146
  if (value === undefined) {
149
147
  output[field] = "undefined";
150
148
  } else if (value === null) {
@@ -153,15 +151,13 @@ export class Serializer {
153
151
  const num = parseFloat(value);
154
152
  if (isNaN(num)) {
155
153
  output[field] = "NaN";
156
- }
157
- else {
154
+ } else {
158
155
  output[field] = num;
159
156
  }
160
157
  }
161
- }
162
- else {
158
+ } else {
163
159
  output[field] = "invalid field: " + name + " is of unknown type.";
164
- logger.throwInternal(LoggingSeverity.CRITICAL, output[field], null, true);
160
+ _throwInternal(logger, eLoggingSeverity.CRITICAL, output[field], null, true);
165
161
  }
166
162
  });
167
163
  }
@@ -27,7 +27,7 @@ export class Sample implements ISample {
27
27
  this.samplingScoreGenerator = new SamplingScoreGenerator();
28
28
  }
29
29
 
30
- /**
30
+ /**
31
31
  * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).
32
32
  */
33
33
  public isSampledIn(envelope: ITelemetryItem): boolean {
@@ -14,7 +14,9 @@ export class HashCodeScoreGenerator {
14
14
  }
15
15
 
16
16
  public getHashCode(input: string): number {
17
- if (input === "") { return 0; }
17
+ if (input === "") {
18
+ return 0;
19
+ }
18
20
 
19
21
  while (input.length < MIN_INPUT_LENGTH) {
20
22
  input = input.concat(input);
@@ -1,13 +1,10 @@
1
+ export interface IOfflineListener {
2
+ isOnline: () => boolean;
3
+ isListening: () => boolean;
4
+ unload: () => void;
5
+ }
1
6
  /**
2
- * @description Monitors browser for offline events
3
- * @export default - Offline: Static instance of OfflineListener
4
- * @class OfflineListener
7
+ * Create a new OfflineListener instance to monitor browser online / offline events
8
+ * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance
5
9
  */
6
- export declare class OfflineListener {
7
- static Offline: OfflineListener;
8
- isListening: boolean;
9
- constructor();
10
- isOnline(): boolean;
11
- isOffline(): boolean;
12
- }
13
- export declare const Offline: OfflineListener;
10
+ export declare function createOfflineListener(parentEvtNamespace?: string | string[]): IOfflineListener;
package/types/Sender.d.ts CHANGED
@@ -47,7 +47,6 @@ export declare class Sender extends BaseTelemetryPlugin implements IChannelContr
47
47
  * Will not flush if the Send has been paused.
48
48
  */
49
49
  onunloadFlush(): void;
50
- teardown(): void;
51
50
  initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain): void;
52
51
  processTelemetry(telemetryItem: ITelemetryItem, itemCtx?: IProcessTelemetryContext): void;
53
52
  /**
@@ -6,7 +6,7 @@ export declare class Sample implements ISample {
6
6
  private samplingScoreGenerator;
7
7
  constructor(sampleRate: number, logger?: IDiagnosticLogger);
8
8
  /**
9
- * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).
10
- */
9
+ * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).
10
+ */
11
11
  isSampledIn(envelope: ITelemetryItem): boolean;
12
12
  }
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.19.4"
8
+ "packageVersion": "7.20.0"
9
9
  }
10
10
  ]
11
11
  }