@sentry/replay 0.5.3 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/index.es.js +123 -66
  2. package/dist/index.js +122 -65
  3. package/dist/index.js.map +1 -1
  4. package/dist/{config/types/jest.config.d.ts → jest.config.d.ts} +0 -0
  5. package/dist/{config/types/jest.setup.d.ts → jest.setup.d.ts} +1 -1
  6. package/dist/{config/types/src → src}/api/captureReplay.d.ts +0 -0
  7. package/dist/{config/types/src → src}/api/captureReplayUpdate.d.ts +0 -0
  8. package/dist/{config/types/src → src}/coreHandlers/getBreadcrumbHandler.d.ts +0 -0
  9. package/dist/{config/types/src → src}/coreHandlers/getSpanHandler.d.ts +0 -0
  10. package/dist/{config/types/src → src}/coreHandlers/handleDom.d.ts +0 -0
  11. package/dist/{config/types/src → src}/coreHandlers/handleFetch.d.ts +1 -1
  12. package/dist/{config/types/src → src}/coreHandlers/handleFetch.test.d.ts +0 -0
  13. package/dist/{config/types/src → src}/coreHandlers/handleHistory.d.ts +0 -0
  14. package/dist/{config/types/src → src}/coreHandlers/handleScope-unit.test.d.ts +0 -0
  15. package/dist/{config/types/src → src}/coreHandlers/handleScope.d.ts +0 -0
  16. package/dist/{config/types/src → src}/coreHandlers/handleScope.test.d.ts +0 -0
  17. package/dist/{config/types/src → src}/coreHandlers/handleXhr.d.ts +2 -2
  18. package/dist/{config/types/src → src}/createPerformanceEntry.d.ts +0 -0
  19. package/dist/{config/types/src → src}/createPerformanceEntry.test.d.ts +0 -0
  20. package/dist/{config/types/src → src}/eventBuffer.d.ts +0 -0
  21. package/dist/{config/types/src → src}/eventBuffer.test.d.ts +0 -0
  22. package/dist/{config/types/src → src}/flags.d.ts +0 -0
  23. package/dist/{config/types/src → src}/index-captureOnlyOnError.test.d.ts +0 -0
  24. package/dist/{config/types/src → src}/index-noSticky.test.d.ts +0 -0
  25. package/dist/{config/types/src → src}/index-sampling.test.d.ts +0 -0
  26. package/dist/{config/types/src → src}/index.d.ts +5 -1
  27. package/dist/{config/types/src → src}/index.test.d.ts +0 -0
  28. package/dist/{types/src → src}/session/Session.d.ts +2 -2
  29. package/dist/{config/types/src → src}/session/Session.test.d.ts +0 -0
  30. package/dist/{config/types/src → src}/session/constants.d.ts +0 -0
  31. package/dist/{config/types/src → src}/session/createSession.d.ts +0 -0
  32. package/dist/{config/types/src → src}/session/createSession.test.d.ts +0 -0
  33. package/dist/{config/types/src → src}/session/fetchSession.d.ts +0 -0
  34. package/dist/{config/types/src → src}/session/fetchSession.test.d.ts +0 -0
  35. package/dist/{config/types/src → src}/session/getSession.d.ts +0 -0
  36. package/dist/{config/types/src → src}/session/getSession.test.d.ts +0 -0
  37. package/dist/{config/types/src → src}/session/index.d.ts +0 -0
  38. package/dist/{config/types/src → src}/session/saveSession.d.ts +0 -0
  39. package/dist/{config/types/src → src}/session/saveSession.test.d.ts +0 -0
  40. package/dist/{config/types/src → src}/types.d.ts +4 -0
  41. package/dist/{config/types/src → src}/util/createBreadcrumb.d.ts +0 -0
  42. package/dist/{config/types/src → src}/util/createPayload.d.ts +0 -0
  43. package/dist/{types/src → src}/util/isExpired.d.ts +1 -1
  44. package/dist/{config/types/src → src}/util/isExpired.test.d.ts +0 -0
  45. package/dist/{config/types/src → src}/util/isIngestHost.d.ts +0 -0
  46. package/dist/{config/types/src → src}/util/isSampled.d.ts +0 -0
  47. package/dist/{config/types/src → src}/util/isSampled.test.d.ts +0 -0
  48. package/dist/{config/types/src → src}/util/isSessionExpired.d.ts +0 -0
  49. package/dist/{config/types/src → src}/util/isSessionExpired.test.d.ts +0 -0
  50. package/dist/{config/types/src → src}/util/logger.d.ts +0 -0
  51. package/dist/{config/types/test → test}/index.d.ts +0 -0
  52. package/dist/{config/types/test → test}/mocks/mockRrweb.d.ts +0 -0
  53. package/dist/{config/types/test → test}/mocks/mockSdk.d.ts +0 -0
  54. package/package.json +1 -1
  55. package/dist/config/types/src/session/Session.d.ts +0 -63
  56. package/dist/config/types/src/util/getAdditionalRequestData.d.ts +0 -2
  57. package/dist/config/types/src/util/isExpired.d.ts +0 -5
  58. package/dist/config/types/src/util/supportsSendBeacon.d.ts +0 -4
  59. package/dist/types/src/api/captureReplay.d.ts +0 -10
  60. package/dist/types/src/api/captureReplayUpdate.d.ts +0 -12
  61. package/dist/types/src/coreHandlers/getBreadcrumbHandler.d.ts +0 -3
  62. package/dist/types/src/coreHandlers/getSpanHandler.d.ts +0 -5
  63. package/dist/types/src/coreHandlers/handleDom.d.ts +0 -1
  64. package/dist/types/src/coreHandlers/handleFetch.d.ts +0 -19
  65. package/dist/types/src/coreHandlers/handleHistory.d.ts +0 -7
  66. package/dist/types/src/coreHandlers/handleScope.d.ts +0 -2
  67. package/dist/types/src/coreHandlers/handleXhr.d.ts +0 -21
  68. package/dist/types/src/createPerformanceEntry.d.ts +0 -42
  69. package/dist/types/src/eventBuffer.d.ts +0 -45
  70. package/dist/types/src/flags.d.ts +0 -2
  71. package/dist/types/src/index.d.ts +0 -230
  72. package/dist/types/src/session/constants.d.ts +0 -5
  73. package/dist/types/src/session/createSession.d.ts +0 -19
  74. package/dist/types/src/session/fetchSession.d.ts +0 -5
  75. package/dist/types/src/session/getSession.d.ts +0 -28
  76. package/dist/types/src/session/index.d.ts +0 -1
  77. package/dist/types/src/session/saveSession.d.ts +0 -2
  78. package/dist/types/src/types.d.ts +0 -91
  79. package/dist/types/src/util/createBreadcrumb.d.ts +0 -4
  80. package/dist/types/src/util/createPayload.d.ts +0 -5
  81. package/dist/types/src/util/isIngestHost.d.ts +0 -4
  82. package/dist/types/src/util/isSampled.d.ts +0 -7
  83. package/dist/types/src/util/isSessionExpired.d.ts +0 -5
  84. package/dist/types/src/util/logger.d.ts +0 -12
  85. package/dist/types/src/util/supportsSendBeacon.d.ts +0 -4
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
1
+ import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
2
  import { htmlTreeAsString, logger as logger$1, uuid4, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
3
  import { record, EventType } from 'rrweb';
4
4
 
@@ -114,7 +114,7 @@ function captureReplayUpdate(_a) {
114
114
  captureEvent({
115
115
  // @ts-expect-error replay_event is a new event type
116
116
  type: REPLAY_EVENT_NAME,
117
- replay_start_timestamp: timestamp / 1000,
117
+ timestamp: timestamp / 1000,
118
118
  error_ids: errorIds,
119
119
  trace_ids: traceIds,
120
120
  urls: urls,
@@ -180,7 +180,8 @@ function getBreadcrumbHandler(type) {
180
180
  * Checks is `targetHost` is a Sentry ingestion host
181
181
  */
182
182
  function isIngestHost(targetHost) {
183
- var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
183
+ var _a;
184
+ var _b = ((_a = getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getDsn()) || {}, protocol = _b.protocol, host = _b.host;
184
185
  return targetHost.startsWith("".concat(protocol, "://").concat(host));
185
186
  }
186
187
 
@@ -220,6 +221,7 @@ function handleHistory(handlerData) {
220
221
  }
221
222
 
222
223
  function handleXhr(handlerData) {
224
+ var _a;
223
225
  if (handlerData.xhr.__sentry_own_request__) {
224
226
  // Taken from sentry-javascript
225
227
  // Only capture non-sentry requests
@@ -227,20 +229,21 @@ function handleXhr(handlerData) {
227
229
  }
228
230
  if (handlerData.startTimestamp) {
229
231
  // TODO: See if this is still needed
232
+ handlerData.xhr.__sentry_xhr__ = handlerData.xhr.__sentry_xhr__ || {};
230
233
  handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
231
234
  }
232
235
  if (!handlerData.endTimestamp) {
233
236
  return null;
234
237
  }
235
- var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, statusCode = _a.status_code;
238
+ var _b = handlerData.xhr.__sentry_xhr__ || {}, method = _b.method, url = _b.url, statusCode = _b.status_code;
236
239
  // Do not capture fetches to Sentry ingestion endpoint
237
- if (isIngestHost(url)) {
240
+ if (url === undefined || isIngestHost(url)) {
238
241
  return null;
239
242
  }
240
243
  return {
241
244
  type: 'resource.xhr',
242
245
  name: url,
243
- start: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
246
+ start: (((_a = handlerData.xhr.__sentry_xhr__) === null || _a === void 0 ? void 0 : _a.startTimestamp) || 0) / 1000 ||
244
247
  handlerData.endTimestamp / 1000.0,
245
248
  end: handlerData.endTimestamp / 1000.0,
246
249
  data: {
@@ -267,7 +270,7 @@ function getSpanHandler(type) {
267
270
  function isExpired(initialTime, expiry, targetTime) {
268
271
  if (targetTime === void 0) { targetTime = +new Date(); }
269
272
  // Always expired if < 0
270
- if (expiry < 0) {
273
+ if (initialTime === null || expiry === undefined || expiry < 0) {
271
274
  return true;
272
275
  }
273
276
  // Never expires if == 0
@@ -282,7 +285,7 @@ function isExpired(initialTime, expiry, targetTime) {
282
285
  */
283
286
  function isSessionExpired(session, expiry, targetTime) {
284
287
  if (targetTime === void 0) { targetTime = +new Date(); }
285
- return isExpired(session.lastActivity, expiry, targetTime);
288
+ return isExpired(session === null || session === void 0 ? void 0 : session.lastActivity, expiry, targetTime);
286
289
  }
287
290
 
288
291
  function wrapLogger(logFn) {
@@ -431,7 +434,9 @@ function fetchSession() {
431
434
  return null;
432
435
  }
433
436
  try {
434
- return new Session(JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
437
+ return new Session(
438
+ // @ts-expect-error: Type 'null' is not assignable to type 'string'.ts(2345)
439
+ JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
435
440
  // We are assuming that if there is a saved item, then the session is sticky,
436
441
  // however this could break down if we used a different storage mechanism (e.g. localstorage)
437
442
  { stickySession: true });
@@ -483,13 +488,6 @@ function createPayload(_a) {
483
488
  return payloadWithSequence;
484
489
  }
485
490
 
486
- /**
487
- * Determine if there is browser support for `navigator.sendBeacon`
488
- */
489
- function supportsSendBeacon() {
490
- return 'navigator' in window && 'sendBeacon' in window.navigator;
491
- }
492
-
493
491
  var _a;
494
492
  // Map entryType -> function to normalize data for event
495
493
  var ENTRY_TYPES = (_a = {
@@ -500,7 +498,9 @@ var ENTRY_TYPES = (_a = {
500
498
  _a['largest-contentful-paint'] = createLargestContentfulPaint,
501
499
  _a);
502
500
  function createPerformanceEntries(entries) {
503
- return entries.map(createPerformanceEntry).filter(Boolean);
501
+ return entries
502
+ .map(createPerformanceEntry)
503
+ .filter(Boolean);
504
504
  }
505
505
  function createPerformanceEntry(entry) {
506
506
  if (ENTRY_TYPES[entry.entryType] === undefined) {
@@ -694,7 +694,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
694
694
  var _this = this;
695
695
  var id = _a.id, method = _a.method, args = _a.args;
696
696
  return new Promise(function (resolve, reject) {
697
+ var _a, _b;
697
698
  var listener = function (_a) {
699
+ var _b;
698
700
  var data = _a.data;
699
701
  if (data.method !== method) {
700
702
  return;
@@ -705,7 +707,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
705
707
  return;
706
708
  }
707
709
  // At this point, we'll always want to remove listener regardless of result status
708
- _this.worker.removeEventListener('message', listener);
710
+ (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.removeEventListener('message', listener);
709
711
  if (!data.success) {
710
712
  // TODO: Do some error handling, not sure what
711
713
  logger.error(data.response);
@@ -716,8 +718,8 @@ var EventBufferCompressionWorker = /** @class */ (function () {
716
718
  };
717
719
  // Note: we can't use `once` option because it's possible it needs to
718
720
  // listen to multiple messages
719
- _this.worker.addEventListener('message', listener);
720
- _this.worker.postMessage({ id: id, method: method, args: args });
721
+ (_a = _this.worker) === null || _a === void 0 ? void 0 : _a.addEventListener('message', listener);
722
+ (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.postMessage({ id: id, method: method, args: args });
721
723
  });
722
724
  };
723
725
  EventBufferCompressionWorker.prototype.init = function () {
@@ -725,8 +727,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
725
727
  logger.log('Initialized compression worker');
726
728
  };
727
729
  EventBufferCompressionWorker.prototype.destroy = function () {
730
+ var _a;
728
731
  logger.log('Destroying compression worker');
729
- this.worker.terminate();
732
+ (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();
730
733
  this.worker = null;
731
734
  };
732
735
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
@@ -771,6 +774,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
771
774
 
772
775
  var BASE_RETRY_INTERVAL = 5000;
773
776
  var MAX_RETRY_COUNT = 5;
777
+ var UNABLE_TO_SEND_REPLAY = 'Unable to send replay';
774
778
  var SentryReplay = /** @class */ (function () {
775
779
  function SentryReplay(_a) {
776
780
  if (_a === void 0) { _a = {}; }
@@ -810,6 +814,7 @@ var SentryReplay = /** @class */ (function () {
810
814
  errorIds: new Set(),
811
815
  traceIds: new Set(),
812
816
  urls: [],
817
+ earliestEvent: null,
813
818
  };
814
819
  /**
815
820
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
@@ -817,7 +822,7 @@ var SentryReplay = /** @class */ (function () {
817
822
  * when an error occurs.
818
823
  **/
819
824
  this.handleGlobalEvent = function (event) {
820
- var _a;
825
+ var _a, _b;
821
826
  // Do not apply replayId to the root event
822
827
  if (
823
828
  // @ts-expect-error new event type
@@ -827,15 +832,19 @@ var SentryReplay = /** @class */ (function () {
827
832
  delete event.breadcrumbs;
828
833
  return event;
829
834
  }
830
- event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
835
+ event.tags = __assign(__assign({}, event.tags), { replayId: (_a = _this.session) === null || _a === void 0 ? void 0 : _a.id });
831
836
  if (event.type === 'transaction') {
832
- _this.context.traceIds.add(String(((_a = event.contexts) === null || _a === void 0 ? void 0 : _a.trace.trace_id) || ''));
837
+ _this.context.traceIds.add(String(((_b = event.contexts) === null || _b === void 0 ? void 0 : _b.trace.trace_id) || ''));
833
838
  return event;
834
839
  }
835
840
  // XXX: Is it safe to assume that all other events are error events?
841
+ // @ts-expect-error: Type 'undefined' is not assignable to type 'string'.ts(2345)
836
842
  _this.context.errorIds.add(event.event_id);
837
843
  // Need to be very careful that this does not cause an infinite loop
838
- if (_this.options.captureOnlyOnError && event.exception) {
844
+ if (_this.options.captureOnlyOnError &&
845
+ event.exception &&
846
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
847
+ ) {
839
848
  // TODO: Do we continue to record after?
840
849
  // TODO: What happens if another error happens? Do we record in the same session?
841
850
  setTimeout(function () { return _this.flushUpdate(); });
@@ -854,9 +863,10 @@ var SentryReplay = /** @class */ (function () {
854
863
  return;
855
864
  }
856
865
  _this.addUpdate(function () {
866
+ var _a;
857
867
  // We need to clear existing events on a checkout, otherwise they are
858
868
  // incremental event updates and should be appended
859
- _this.eventBuffer.addEvent(event, isCheckout);
869
+ _this.addEvent(event, isCheckout);
860
870
  // Different behavior for full snapshots (type=2), ignore other event types
861
871
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
862
872
  if (event.type !== 2) {
@@ -868,7 +878,7 @@ var SentryReplay = /** @class */ (function () {
868
878
  // of the previous session. Do not immediately flush in this case
869
879
  // to avoid capturing only the checkout and instead the replay will
870
880
  // be captured if they perform any follow-up actions.
871
- if (_this.session.previousSessionId) {
881
+ if ((_a = _this.session) === null || _a === void 0 ? void 0 : _a.previousSessionId) {
872
882
  return true;
873
883
  }
874
884
  // If the full snapshot is due to an initial load, we will not have
@@ -939,6 +949,10 @@ var SentryReplay = /** @class */ (function () {
939
949
  }
940
950
  _this.addUpdate(function () {
941
951
  _this.createPerformanceSpans([result]);
952
+ // Returning true will cause `addUpdate` to not flush
953
+ // We do not want network requests to cause a flush. This will prevent
954
+ // recurring/polling requests from keeping the replay session alive.
955
+ return ['xhr', 'fetch'].includes(type);
942
956
  });
943
957
  }; };
944
958
  /**
@@ -956,11 +970,11 @@ var SentryReplay = /** @class */ (function () {
956
970
  return;
957
971
  }
958
972
  _this.addUpdate(function () {
959
- _this.eventBuffer.addEvent({
973
+ _this.addEvent({
960
974
  type: EventType.Custom,
961
975
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
962
976
  // but maybe we should just keep them as milliseconds
963
- timestamp: result.timestamp * 1000,
977
+ timestamp: (result.timestamp || 0) * 1000,
964
978
  data: {
965
979
  tag: 'breadcrumb',
966
980
  payload: result,
@@ -1023,7 +1037,7 @@ var SentryReplay = /** @class */ (function () {
1023
1037
  return;
1024
1038
  }
1025
1039
  this.eventBuffer = createEventBuffer({
1026
- useCompression: this.options.useCompression,
1040
+ useCompression: Boolean(this.options.useCompression),
1027
1041
  });
1028
1042
  this.addListeners();
1029
1043
  // Tag all (non replay) events that get sent to Sentry with the current
@@ -1088,7 +1102,7 @@ var SentryReplay = /** @class */ (function () {
1088
1102
  this.removeListeners();
1089
1103
  };
1090
1104
  SentryReplay.prototype.clearSession = function () {
1091
- this.session = null;
1105
+ this.session = undefined;
1092
1106
  };
1093
1107
  /**
1094
1108
  * Loads a session from storage, or creates a new one if it does not exist or
@@ -1099,7 +1113,7 @@ var SentryReplay = /** @class */ (function () {
1099
1113
  var expiry = _a.expiry;
1100
1114
  var _d = getSession({
1101
1115
  expiry: expiry,
1102
- stickySession: this.options.stickySession,
1116
+ stickySession: Boolean(this.options.stickySession),
1103
1117
  currentSession: this.session,
1104
1118
  samplingRate: this.options.replaysSamplingRate,
1105
1119
  }), type = _d.type, session = _d.session;
@@ -1141,7 +1155,7 @@ var SentryReplay = /** @class */ (function () {
1141
1155
  window.addEventListener('beforeunload', this.handleWindowUnload);
1142
1156
  // Listeners from core SDK //
1143
1157
  var scope = getCurrentHub().getScope();
1144
- scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1158
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1145
1159
  addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1146
1160
  addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1147
1161
  addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
@@ -1163,7 +1177,8 @@ var SentryReplay = /** @class */ (function () {
1163
1177
  'paint',
1164
1178
  'resource',
1165
1179
  ].forEach(function (type) {
1166
- return _this.performanceObserver.observe({
1180
+ var _a;
1181
+ return (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({
1167
1182
  type: type,
1168
1183
  buffered: true,
1169
1184
  });
@@ -1186,6 +1201,9 @@ var SentryReplay = /** @class */ (function () {
1186
1201
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
1187
1202
  */
1188
1203
  SentryReplay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {
1204
+ if (!this.session) {
1205
+ return;
1206
+ }
1189
1207
  var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1190
1208
  if (breadcrumb) {
1191
1209
  this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), {
@@ -1203,6 +1221,9 @@ var SentryReplay = /** @class */ (function () {
1203
1221
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
1204
1222
  */
1205
1223
  SentryReplay.prototype.doChangeToForegroundTasks = function (breadcrumb) {
1224
+ if (!this.session) {
1225
+ return;
1226
+ }
1206
1227
  var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1207
1228
  if (breadcrumb) {
1208
1229
  this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), { timestamp: isExpired
@@ -1232,12 +1253,25 @@ var SentryReplay = /** @class */ (function () {
1232
1253
  logger.log('Taking full rrweb snapshot');
1233
1254
  record.takeFullSnapshot(true);
1234
1255
  };
1256
+ /**
1257
+ * Add an event to the event buffer
1258
+ */
1259
+ SentryReplay.prototype.addEvent = function (event, isCheckout) {
1260
+ var timestampInMs = event.timestamp * 1000;
1261
+ if (!this.context.earliestEvent ||
1262
+ timestampInMs < this.context.earliestEvent) {
1263
+ this.context.earliestEvent = timestampInMs;
1264
+ }
1265
+ this.eventBuffer.addEvent(event, isCheckout);
1266
+ };
1235
1267
  /**
1236
1268
  * Updates the session's last activity timestamp
1237
1269
  */
1238
1270
  SentryReplay.prototype.updateLastActivity = function (lastActivity) {
1239
1271
  if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1240
- this.session.lastActivity = lastActivity;
1272
+ if (this.session) {
1273
+ this.session.lastActivity = lastActivity;
1274
+ }
1241
1275
  };
1242
1276
  /**
1243
1277
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
@@ -1245,9 +1279,9 @@ var SentryReplay = /** @class */ (function () {
1245
1279
  SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
1246
1280
  var _this = this;
1247
1281
  this.addUpdate(function () {
1248
- _this.eventBuffer.addEvent({
1282
+ _this.addEvent({
1249
1283
  type: EventType.Custom,
1250
- timestamp: breadcrumb.timestamp,
1284
+ timestamp: breadcrumb.timestamp || 0,
1251
1285
  data: {
1252
1286
  tag: 'breadcrumb',
1253
1287
  payload: breadcrumb,
@@ -1262,7 +1296,7 @@ var SentryReplay = /** @class */ (function () {
1262
1296
  var _this = this;
1263
1297
  return Promise.all(entries.map(function (_a) {
1264
1298
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1265
- return _this.eventBuffer.addEvent({
1299
+ return _this.addEvent({
1266
1300
  type: EventType.Custom,
1267
1301
  timestamp: start,
1268
1302
  data: {
@@ -1309,12 +1343,13 @@ var SentryReplay = /** @class */ (function () {
1309
1343
  * Returns true if session is not expired, false otherwise.
1310
1344
  */
1311
1345
  SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
1346
+ var _a, _b;
1312
1347
  if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
1313
- var oldSessionId = this.session.id;
1348
+ var oldSessionId = (_a = this.session) === null || _a === void 0 ? void 0 : _a.id;
1314
1349
  // This will create a new session if expired, based on expiry length
1315
1350
  this.loadSession({ expiry: expiry });
1316
1351
  // Session was expired if session ids do not match
1317
- var isExpired = oldSessionId !== this.session.id;
1352
+ var isExpired = oldSessionId !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id);
1318
1353
  if (!isExpired) {
1319
1354
  return true;
1320
1355
  }
@@ -1340,9 +1375,15 @@ var SentryReplay = /** @class */ (function () {
1340
1375
  */
1341
1376
  SentryReplay.prototype.popEventContext = function (_a) {
1342
1377
  var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1378
+ var initialState = this.initialState;
1379
+ if (this.initialState &&
1380
+ this.context.earliestEvent &&
1381
+ this.context.earliestEvent < this.initialState.timestamp) {
1382
+ initialState.timestamp = this.context.earliestEvent;
1383
+ }
1343
1384
  var context = {
1344
1385
  session: this.session,
1345
- initialState: this.initialState,
1386
+ initialState: initialState,
1346
1387
  timestamp: timestamp,
1347
1388
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
1348
1389
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
@@ -1351,6 +1392,8 @@ var SentryReplay = /** @class */ (function () {
1351
1392
  this.context.errorIds.clear();
1352
1393
  this.context.traceIds.clear();
1353
1394
  this.context.urls = [];
1395
+ this.context.earliestEvent = null;
1396
+ // @ts-expect-error: Type 'undefined' is not assignable to type 'Session'.ts(2322)
1354
1397
  return context;
1355
1398
  };
1356
1399
  /**
@@ -1360,16 +1403,17 @@ var SentryReplay = /** @class */ (function () {
1360
1403
  * due to the buffered performance observer events.
1361
1404
  */
1362
1405
  SentryReplay.prototype.flushUpdate = function (lastActivity) {
1406
+ var _a;
1363
1407
  return __awaiter(this, void 0, void 0, function () {
1364
1408
  var timestamp, recordingData, err_1;
1365
- return __generator(this, function (_a) {
1366
- switch (_a.label) {
1409
+ return __generator(this, function (_b) {
1410
+ switch (_b.label) {
1367
1411
  case 0:
1368
1412
  if (!this.checkAndHandleExpiredSession()) {
1369
1413
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1370
1414
  return [2 /*return*/];
1371
1415
  }
1372
- if (!this.session.id) {
1416
+ if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1373
1417
  console.error(new Error('[Sentry]: No transaction, no replay'));
1374
1418
  return [2 /*return*/];
1375
1419
  }
@@ -1377,7 +1421,7 @@ var SentryReplay = /** @class */ (function () {
1377
1421
  clearTimeout(this.timeout);
1378
1422
  return [4 /*yield*/, this.addPerformanceEntries()];
1379
1423
  case 1:
1380
- _a.sent();
1424
+ _b.sent();
1381
1425
  if (!this.eventBuffer.length) {
1382
1426
  return [2 /*return*/];
1383
1427
  }
@@ -1385,7 +1429,7 @@ var SentryReplay = /** @class */ (function () {
1385
1429
  return [4 /*yield*/, this.addMemoryEntry()];
1386
1430
  case 2:
1387
1431
  // Only attach memory event if eventBuffer is not empty
1388
- _a.sent();
1432
+ _b.sent();
1389
1433
  timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1390
1434
  // Only want to create replay event if session is new
1391
1435
  if (this.needsCaptureReplay) {
@@ -1396,15 +1440,15 @@ var SentryReplay = /** @class */ (function () {
1396
1440
  // Reset this to null regardless of `sendReplay` result so that future
1397
1441
  // events will get flushed properly
1398
1442
  this.initialEventTimestampSinceFlush = null;
1399
- _a.label = 3;
1443
+ _b.label = 3;
1400
1444
  case 3:
1401
- _a.trys.push([3, 6, , 7]);
1445
+ _b.trys.push([3, 6, , 7]);
1402
1446
  return [4 /*yield*/, this.eventBuffer.finish()];
1403
1447
  case 4:
1404
- recordingData = _a.sent();
1448
+ recordingData = _b.sent();
1405
1449
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1406
1450
  case 5:
1407
- _a.sent();
1451
+ _b.sent();
1408
1452
  // The below will only happen after successfully sending replay //
1409
1453
  // TBD: Alternatively we could update this after every rrweb event
1410
1454
  // `timestamp` should reflect when the event happens. e.g. the timestamp
@@ -1414,7 +1458,7 @@ var SentryReplay = /** @class */ (function () {
1414
1458
  captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1415
1459
  return [3 /*break*/, 7];
1416
1460
  case 6:
1417
- err_1 = _a.sent();
1461
+ err_1 = _b.sent();
1418
1462
  captureException(err_1);
1419
1463
  console.error(err_1);
1420
1464
  return [3 /*break*/, 7];
@@ -1424,23 +1468,25 @@ var SentryReplay = /** @class */ (function () {
1424
1468
  });
1425
1469
  };
1426
1470
  /**
1427
- * Send replay attachment using either `sendBeacon()` or `fetch()`
1471
+ * Send replay attachment using `fetch()`
1428
1472
  */
1429
1473
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1474
+ var _b, _c;
1430
1475
  var endpoint = _a.endpoint, events = _a.events;
1431
1476
  return __awaiter(this, void 0, void 0, function () {
1432
- var payloadWithSequence, envelope;
1433
- return __generator(this, function (_b) {
1434
- switch (_b.label) {
1477
+ var payloadWithSequence, envelope, response, _d, _e;
1478
+ var _f;
1479
+ return __generator(this, function (_g) {
1480
+ switch (_g.label) {
1435
1481
  case 0:
1436
1482
  payloadWithSequence = createPayload({
1437
1483
  events: events,
1438
1484
  headers: {
1439
- segment_id: this.session.segmentId,
1485
+ segment_id: (_b = this.session) === null || _b === void 0 ? void 0 : _b.segmentId,
1440
1486
  },
1441
1487
  });
1442
1488
  envelope = createEnvelope({
1443
- event_id: this.session.id,
1489
+ event_id: (_c = this.session) === null || _c === void 0 ? void 0 : _c.id,
1444
1490
  sent_at: new Date().toISOString(),
1445
1491
  sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1446
1492
  }, [
@@ -1450,15 +1496,10 @@ var SentryReplay = /** @class */ (function () {
1450
1496
  type: 'replay_recording',
1451
1497
  length: payloadWithSequence.length,
1452
1498
  },
1499
+ // @ts-expect-error: Type 'string' is not assignable to type 'ClientReport'.ts(2322)
1453
1500
  payloadWithSequence,
1454
1501
  ],
1455
1502
  ]);
1456
- // If sendBeacon is supported and payload is smol enough...
1457
- if (supportsSendBeacon() && events.length <= 65536) {
1458
- logger.log("uploading attachment via sendBeacon()");
1459
- window.navigator.sendBeacon(endpoint, serializeEnvelope(envelope));
1460
- return [2 /*return*/];
1461
- }
1462
1503
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1463
1504
  logger.log("uploading attachment via fetch()");
1464
1505
  return [4 /*yield*/, fetch(endpoint, {
@@ -1466,8 +1507,19 @@ var SentryReplay = /** @class */ (function () {
1466
1507
  body: serializeEnvelope(envelope),
1467
1508
  })];
1468
1509
  case 1:
1469
- _b.sent();
1470
- return [2 /*return*/];
1510
+ response = _g.sent();
1511
+ if (!(response.status !== 200)) return [3 /*break*/, 3];
1512
+ _d = setContext;
1513
+ _e = ['Send Replay Response'];
1514
+ _f = {
1515
+ status: response.status
1516
+ };
1517
+ return [4 /*yield*/, response.text()];
1518
+ case 2:
1519
+ _d.apply(void 0, _e.concat([(_f.body = _g.sent(),
1520
+ _f)]));
1521
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1522
+ case 3: return [2 /*return*/];
1471
1523
  }
1472
1524
  });
1473
1525
  });
@@ -1505,8 +1557,13 @@ var SentryReplay = /** @class */ (function () {
1505
1557
  return [2 /*return*/, true];
1506
1558
  case 3:
1507
1559
  ex_1 = _b.sent();
1508
- // we have to catch this otherwise it throws an infinite loop in Sentry
1509
1560
  console.error(ex_1);
1561
+ // Capture error for every failed replay
1562
+ // TODO: Remove this before GA as this will create an error on customer's project
1563
+ setContext('Replays', {
1564
+ retryCount: this.retryCount,
1565
+ });
1566
+ captureException(new Error(UNABLE_TO_SEND_REPLAY));
1510
1567
  // If an error happened here, it's likely that uploading the attachment
1511
1568
  // failed, we'll can retry with the same events payload
1512
1569
  if (this.retryCount >= MAX_RETRY_COUNT) {