@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.js CHANGED
@@ -118,7 +118,7 @@ function captureReplayUpdate(_a) {
118
118
  core.captureEvent({
119
119
  // @ts-expect-error replay_event is a new event type
120
120
  type: REPLAY_EVENT_NAME,
121
- replay_start_timestamp: timestamp / 1000,
121
+ timestamp: timestamp / 1000,
122
122
  error_ids: errorIds,
123
123
  trace_ids: traceIds,
124
124
  urls: urls,
@@ -184,7 +184,8 @@ function getBreadcrumbHandler(type) {
184
184
  * Checks is `targetHost` is a Sentry ingestion host
185
185
  */
186
186
  function isIngestHost(targetHost) {
187
- var _a = core.getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
187
+ var _a;
188
+ var _b = ((_a = core.getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getDsn()) || {}, protocol = _b.protocol, host = _b.host;
188
189
  return targetHost.startsWith("".concat(protocol, "://").concat(host));
189
190
  }
190
191
 
@@ -224,6 +225,7 @@ function handleHistory(handlerData) {
224
225
  }
225
226
 
226
227
  function handleXhr(handlerData) {
228
+ var _a;
227
229
  if (handlerData.xhr.__sentry_own_request__) {
228
230
  // Taken from sentry-javascript
229
231
  // Only capture non-sentry requests
@@ -231,20 +233,21 @@ function handleXhr(handlerData) {
231
233
  }
232
234
  if (handlerData.startTimestamp) {
233
235
  // TODO: See if this is still needed
236
+ handlerData.xhr.__sentry_xhr__ = handlerData.xhr.__sentry_xhr__ || {};
234
237
  handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
235
238
  }
236
239
  if (!handlerData.endTimestamp) {
237
240
  return null;
238
241
  }
239
- var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, statusCode = _a.status_code;
242
+ var _b = handlerData.xhr.__sentry_xhr__ || {}, method = _b.method, url = _b.url, statusCode = _b.status_code;
240
243
  // Do not capture fetches to Sentry ingestion endpoint
241
- if (isIngestHost(url)) {
244
+ if (url === undefined || isIngestHost(url)) {
242
245
  return null;
243
246
  }
244
247
  return {
245
248
  type: 'resource.xhr',
246
249
  name: url,
247
- start: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
250
+ start: (((_a = handlerData.xhr.__sentry_xhr__) === null || _a === void 0 ? void 0 : _a.startTimestamp) || 0) / 1000 ||
248
251
  handlerData.endTimestamp / 1000.0,
249
252
  end: handlerData.endTimestamp / 1000.0,
250
253
  data: {
@@ -271,7 +274,7 @@ function getSpanHandler(type) {
271
274
  function isExpired(initialTime, expiry, targetTime) {
272
275
  if (targetTime === void 0) { targetTime = +new Date(); }
273
276
  // Always expired if < 0
274
- if (expiry < 0) {
277
+ if (initialTime === null || expiry === undefined || expiry < 0) {
275
278
  return true;
276
279
  }
277
280
  // Never expires if == 0
@@ -286,7 +289,7 @@ function isExpired(initialTime, expiry, targetTime) {
286
289
  */
287
290
  function isSessionExpired(session, expiry, targetTime) {
288
291
  if (targetTime === void 0) { targetTime = +new Date(); }
289
- return isExpired(session.lastActivity, expiry, targetTime);
292
+ return isExpired(session === null || session === void 0 ? void 0 : session.lastActivity, expiry, targetTime);
290
293
  }
291
294
 
292
295
  function wrapLogger(logFn) {
@@ -435,7 +438,9 @@ function fetchSession() {
435
438
  return null;
436
439
  }
437
440
  try {
438
- return new Session(JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
441
+ return new Session(
442
+ // @ts-expect-error: Type 'null' is not assignable to type 'string'.ts(2345)
443
+ JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
439
444
  // We are assuming that if there is a saved item, then the session is sticky,
440
445
  // however this could break down if we used a different storage mechanism (e.g. localstorage)
441
446
  { stickySession: true });
@@ -487,13 +492,6 @@ function createPayload(_a) {
487
492
  return payloadWithSequence;
488
493
  }
489
494
 
490
- /**
491
- * Determine if there is browser support for `navigator.sendBeacon`
492
- */
493
- function supportsSendBeacon() {
494
- return 'navigator' in window && 'sendBeacon' in window.navigator;
495
- }
496
-
497
495
  var _a;
498
496
  // Map entryType -> function to normalize data for event
499
497
  var ENTRY_TYPES = (_a = {
@@ -504,7 +502,9 @@ var ENTRY_TYPES = (_a = {
504
502
  _a['largest-contentful-paint'] = createLargestContentfulPaint,
505
503
  _a);
506
504
  function createPerformanceEntries(entries) {
507
- return entries.map(createPerformanceEntry).filter(Boolean);
505
+ return entries
506
+ .map(createPerformanceEntry)
507
+ .filter(Boolean);
508
508
  }
509
509
  function createPerformanceEntry(entry) {
510
510
  if (ENTRY_TYPES[entry.entryType] === undefined) {
@@ -698,7 +698,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
698
698
  var _this = this;
699
699
  var id = _a.id, method = _a.method, args = _a.args;
700
700
  return new Promise(function (resolve, reject) {
701
+ var _a, _b;
701
702
  var listener = function (_a) {
703
+ var _b;
702
704
  var data = _a.data;
703
705
  if (data.method !== method) {
704
706
  return;
@@ -709,7 +711,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
709
711
  return;
710
712
  }
711
713
  // At this point, we'll always want to remove listener regardless of result status
712
- _this.worker.removeEventListener('message', listener);
714
+ (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.removeEventListener('message', listener);
713
715
  if (!data.success) {
714
716
  // TODO: Do some error handling, not sure what
715
717
  logger.error(data.response);
@@ -720,8 +722,8 @@ var EventBufferCompressionWorker = /** @class */ (function () {
720
722
  };
721
723
  // Note: we can't use `once` option because it's possible it needs to
722
724
  // listen to multiple messages
723
- _this.worker.addEventListener('message', listener);
724
- _this.worker.postMessage({ id: id, method: method, args: args });
725
+ (_a = _this.worker) === null || _a === void 0 ? void 0 : _a.addEventListener('message', listener);
726
+ (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.postMessage({ id: id, method: method, args: args });
725
727
  });
726
728
  };
727
729
  EventBufferCompressionWorker.prototype.init = function () {
@@ -729,8 +731,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
729
731
  logger.log('Initialized compression worker');
730
732
  };
731
733
  EventBufferCompressionWorker.prototype.destroy = function () {
734
+ var _a;
732
735
  logger.log('Destroying compression worker');
733
- this.worker.terminate();
736
+ (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();
734
737
  this.worker = null;
735
738
  };
736
739
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
@@ -775,6 +778,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
775
778
 
776
779
  var BASE_RETRY_INTERVAL = 5000;
777
780
  var MAX_RETRY_COUNT = 5;
781
+ var UNABLE_TO_SEND_REPLAY = 'Unable to send replay';
778
782
  var SentryReplay = /** @class */ (function () {
779
783
  function SentryReplay(_a) {
780
784
  if (_a === void 0) { _a = {}; }
@@ -814,6 +818,7 @@ var SentryReplay = /** @class */ (function () {
814
818
  errorIds: new Set(),
815
819
  traceIds: new Set(),
816
820
  urls: [],
821
+ earliestEvent: null,
817
822
  };
818
823
  /**
819
824
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
@@ -821,7 +826,7 @@ var SentryReplay = /** @class */ (function () {
821
826
  * when an error occurs.
822
827
  **/
823
828
  this.handleGlobalEvent = function (event) {
824
- var _a;
829
+ var _a, _b;
825
830
  // Do not apply replayId to the root event
826
831
  if (
827
832
  // @ts-expect-error new event type
@@ -831,15 +836,19 @@ var SentryReplay = /** @class */ (function () {
831
836
  delete event.breadcrumbs;
832
837
  return event;
833
838
  }
834
- event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
839
+ event.tags = __assign(__assign({}, event.tags), { replayId: (_a = _this.session) === null || _a === void 0 ? void 0 : _a.id });
835
840
  if (event.type === 'transaction') {
836
- _this.context.traceIds.add(String(((_a = event.contexts) === null || _a === void 0 ? void 0 : _a.trace.trace_id) || ''));
841
+ _this.context.traceIds.add(String(((_b = event.contexts) === null || _b === void 0 ? void 0 : _b.trace.trace_id) || ''));
837
842
  return event;
838
843
  }
839
844
  // XXX: Is it safe to assume that all other events are error events?
845
+ // @ts-expect-error: Type 'undefined' is not assignable to type 'string'.ts(2345)
840
846
  _this.context.errorIds.add(event.event_id);
841
847
  // Need to be very careful that this does not cause an infinite loop
842
- if (_this.options.captureOnlyOnError && event.exception) {
848
+ if (_this.options.captureOnlyOnError &&
849
+ event.exception &&
850
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
851
+ ) {
843
852
  // TODO: Do we continue to record after?
844
853
  // TODO: What happens if another error happens? Do we record in the same session?
845
854
  setTimeout(function () { return _this.flushUpdate(); });
@@ -858,9 +867,10 @@ var SentryReplay = /** @class */ (function () {
858
867
  return;
859
868
  }
860
869
  _this.addUpdate(function () {
870
+ var _a;
861
871
  // We need to clear existing events on a checkout, otherwise they are
862
872
  // incremental event updates and should be appended
863
- _this.eventBuffer.addEvent(event, isCheckout);
873
+ _this.addEvent(event, isCheckout);
864
874
  // Different behavior for full snapshots (type=2), ignore other event types
865
875
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
866
876
  if (event.type !== 2) {
@@ -872,7 +882,7 @@ var SentryReplay = /** @class */ (function () {
872
882
  // of the previous session. Do not immediately flush in this case
873
883
  // to avoid capturing only the checkout and instead the replay will
874
884
  // be captured if they perform any follow-up actions.
875
- if (_this.session.previousSessionId) {
885
+ if ((_a = _this.session) === null || _a === void 0 ? void 0 : _a.previousSessionId) {
876
886
  return true;
877
887
  }
878
888
  // If the full snapshot is due to an initial load, we will not have
@@ -943,6 +953,10 @@ var SentryReplay = /** @class */ (function () {
943
953
  }
944
954
  _this.addUpdate(function () {
945
955
  _this.createPerformanceSpans([result]);
956
+ // Returning true will cause `addUpdate` to not flush
957
+ // We do not want network requests to cause a flush. This will prevent
958
+ // recurring/polling requests from keeping the replay session alive.
959
+ return ['xhr', 'fetch'].includes(type);
946
960
  });
947
961
  }; };
948
962
  /**
@@ -960,11 +974,11 @@ var SentryReplay = /** @class */ (function () {
960
974
  return;
961
975
  }
962
976
  _this.addUpdate(function () {
963
- _this.eventBuffer.addEvent({
977
+ _this.addEvent({
964
978
  type: rrweb.EventType.Custom,
965
979
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
966
980
  // but maybe we should just keep them as milliseconds
967
- timestamp: result.timestamp * 1000,
981
+ timestamp: (result.timestamp || 0) * 1000,
968
982
  data: {
969
983
  tag: 'breadcrumb',
970
984
  payload: result,
@@ -1027,7 +1041,7 @@ var SentryReplay = /** @class */ (function () {
1027
1041
  return;
1028
1042
  }
1029
1043
  this.eventBuffer = createEventBuffer({
1030
- useCompression: this.options.useCompression,
1044
+ useCompression: Boolean(this.options.useCompression),
1031
1045
  });
1032
1046
  this.addListeners();
1033
1047
  // Tag all (non replay) events that get sent to Sentry with the current
@@ -1092,7 +1106,7 @@ var SentryReplay = /** @class */ (function () {
1092
1106
  this.removeListeners();
1093
1107
  };
1094
1108
  SentryReplay.prototype.clearSession = function () {
1095
- this.session = null;
1109
+ this.session = undefined;
1096
1110
  };
1097
1111
  /**
1098
1112
  * Loads a session from storage, or creates a new one if it does not exist or
@@ -1103,7 +1117,7 @@ var SentryReplay = /** @class */ (function () {
1103
1117
  var expiry = _a.expiry;
1104
1118
  var _d = getSession({
1105
1119
  expiry: expiry,
1106
- stickySession: this.options.stickySession,
1120
+ stickySession: Boolean(this.options.stickySession),
1107
1121
  currentSession: this.session,
1108
1122
  samplingRate: this.options.replaysSamplingRate,
1109
1123
  }), type = _d.type, session = _d.session;
@@ -1145,7 +1159,7 @@ var SentryReplay = /** @class */ (function () {
1145
1159
  window.addEventListener('beforeunload', this.handleWindowUnload);
1146
1160
  // Listeners from core SDK //
1147
1161
  var scope = core.getCurrentHub().getScope();
1148
- scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1162
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1149
1163
  utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1150
1164
  utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1151
1165
  utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
@@ -1167,7 +1181,8 @@ var SentryReplay = /** @class */ (function () {
1167
1181
  'paint',
1168
1182
  'resource',
1169
1183
  ].forEach(function (type) {
1170
- return _this.performanceObserver.observe({
1184
+ var _a;
1185
+ return (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({
1171
1186
  type: type,
1172
1187
  buffered: true,
1173
1188
  });
@@ -1190,6 +1205,9 @@ var SentryReplay = /** @class */ (function () {
1190
1205
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
1191
1206
  */
1192
1207
  SentryReplay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {
1208
+ if (!this.session) {
1209
+ return;
1210
+ }
1193
1211
  var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1194
1212
  if (breadcrumb) {
1195
1213
  this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), {
@@ -1207,6 +1225,9 @@ var SentryReplay = /** @class */ (function () {
1207
1225
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
1208
1226
  */
1209
1227
  SentryReplay.prototype.doChangeToForegroundTasks = function (breadcrumb) {
1228
+ if (!this.session) {
1229
+ return;
1230
+ }
1210
1231
  var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1211
1232
  if (breadcrumb) {
1212
1233
  this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), { timestamp: isExpired
@@ -1236,12 +1257,25 @@ var SentryReplay = /** @class */ (function () {
1236
1257
  logger.log('Taking full rrweb snapshot');
1237
1258
  rrweb.record.takeFullSnapshot(true);
1238
1259
  };
1260
+ /**
1261
+ * Add an event to the event buffer
1262
+ */
1263
+ SentryReplay.prototype.addEvent = function (event, isCheckout) {
1264
+ var timestampInMs = event.timestamp * 1000;
1265
+ if (!this.context.earliestEvent ||
1266
+ timestampInMs < this.context.earliestEvent) {
1267
+ this.context.earliestEvent = timestampInMs;
1268
+ }
1269
+ this.eventBuffer.addEvent(event, isCheckout);
1270
+ };
1239
1271
  /**
1240
1272
  * Updates the session's last activity timestamp
1241
1273
  */
1242
1274
  SentryReplay.prototype.updateLastActivity = function (lastActivity) {
1243
1275
  if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1244
- this.session.lastActivity = lastActivity;
1276
+ if (this.session) {
1277
+ this.session.lastActivity = lastActivity;
1278
+ }
1245
1279
  };
1246
1280
  /**
1247
1281
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
@@ -1249,9 +1283,9 @@ var SentryReplay = /** @class */ (function () {
1249
1283
  SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
1250
1284
  var _this = this;
1251
1285
  this.addUpdate(function () {
1252
- _this.eventBuffer.addEvent({
1286
+ _this.addEvent({
1253
1287
  type: rrweb.EventType.Custom,
1254
- timestamp: breadcrumb.timestamp,
1288
+ timestamp: breadcrumb.timestamp || 0,
1255
1289
  data: {
1256
1290
  tag: 'breadcrumb',
1257
1291
  payload: breadcrumb,
@@ -1266,7 +1300,7 @@ var SentryReplay = /** @class */ (function () {
1266
1300
  var _this = this;
1267
1301
  return Promise.all(entries.map(function (_a) {
1268
1302
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1269
- return _this.eventBuffer.addEvent({
1303
+ return _this.addEvent({
1270
1304
  type: rrweb.EventType.Custom,
1271
1305
  timestamp: start,
1272
1306
  data: {
@@ -1313,12 +1347,13 @@ var SentryReplay = /** @class */ (function () {
1313
1347
  * Returns true if session is not expired, false otherwise.
1314
1348
  */
1315
1349
  SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
1350
+ var _a, _b;
1316
1351
  if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
1317
- var oldSessionId = this.session.id;
1352
+ var oldSessionId = (_a = this.session) === null || _a === void 0 ? void 0 : _a.id;
1318
1353
  // This will create a new session if expired, based on expiry length
1319
1354
  this.loadSession({ expiry: expiry });
1320
1355
  // Session was expired if session ids do not match
1321
- var isExpired = oldSessionId !== this.session.id;
1356
+ var isExpired = oldSessionId !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id);
1322
1357
  if (!isExpired) {
1323
1358
  return true;
1324
1359
  }
@@ -1344,9 +1379,15 @@ var SentryReplay = /** @class */ (function () {
1344
1379
  */
1345
1380
  SentryReplay.prototype.popEventContext = function (_a) {
1346
1381
  var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1382
+ var initialState = this.initialState;
1383
+ if (this.initialState &&
1384
+ this.context.earliestEvent &&
1385
+ this.context.earliestEvent < this.initialState.timestamp) {
1386
+ initialState.timestamp = this.context.earliestEvent;
1387
+ }
1347
1388
  var context = {
1348
1389
  session: this.session,
1349
- initialState: this.initialState,
1390
+ initialState: initialState,
1350
1391
  timestamp: timestamp,
1351
1392
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
1352
1393
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
@@ -1355,6 +1396,8 @@ var SentryReplay = /** @class */ (function () {
1355
1396
  this.context.errorIds.clear();
1356
1397
  this.context.traceIds.clear();
1357
1398
  this.context.urls = [];
1399
+ this.context.earliestEvent = null;
1400
+ // @ts-expect-error: Type 'undefined' is not assignable to type 'Session'.ts(2322)
1358
1401
  return context;
1359
1402
  };
1360
1403
  /**
@@ -1364,16 +1407,17 @@ var SentryReplay = /** @class */ (function () {
1364
1407
  * due to the buffered performance observer events.
1365
1408
  */
1366
1409
  SentryReplay.prototype.flushUpdate = function (lastActivity) {
1410
+ var _a;
1367
1411
  return __awaiter(this, void 0, void 0, function () {
1368
1412
  var timestamp, recordingData, err_1;
1369
- return __generator(this, function (_a) {
1370
- switch (_a.label) {
1413
+ return __generator(this, function (_b) {
1414
+ switch (_b.label) {
1371
1415
  case 0:
1372
1416
  if (!this.checkAndHandleExpiredSession()) {
1373
1417
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1374
1418
  return [2 /*return*/];
1375
1419
  }
1376
- if (!this.session.id) {
1420
+ if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1377
1421
  console.error(new Error('[Sentry]: No transaction, no replay'));
1378
1422
  return [2 /*return*/];
1379
1423
  }
@@ -1381,7 +1425,7 @@ var SentryReplay = /** @class */ (function () {
1381
1425
  clearTimeout(this.timeout);
1382
1426
  return [4 /*yield*/, this.addPerformanceEntries()];
1383
1427
  case 1:
1384
- _a.sent();
1428
+ _b.sent();
1385
1429
  if (!this.eventBuffer.length) {
1386
1430
  return [2 /*return*/];
1387
1431
  }
@@ -1389,7 +1433,7 @@ var SentryReplay = /** @class */ (function () {
1389
1433
  return [4 /*yield*/, this.addMemoryEntry()];
1390
1434
  case 2:
1391
1435
  // Only attach memory event if eventBuffer is not empty
1392
- _a.sent();
1436
+ _b.sent();
1393
1437
  timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1394
1438
  // Only want to create replay event if session is new
1395
1439
  if (this.needsCaptureReplay) {
@@ -1400,15 +1444,15 @@ var SentryReplay = /** @class */ (function () {
1400
1444
  // Reset this to null regardless of `sendReplay` result so that future
1401
1445
  // events will get flushed properly
1402
1446
  this.initialEventTimestampSinceFlush = null;
1403
- _a.label = 3;
1447
+ _b.label = 3;
1404
1448
  case 3:
1405
- _a.trys.push([3, 6, , 7]);
1449
+ _b.trys.push([3, 6, , 7]);
1406
1450
  return [4 /*yield*/, this.eventBuffer.finish()];
1407
1451
  case 4:
1408
- recordingData = _a.sent();
1452
+ recordingData = _b.sent();
1409
1453
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1410
1454
  case 5:
1411
- _a.sent();
1455
+ _b.sent();
1412
1456
  // The below will only happen after successfully sending replay //
1413
1457
  // TBD: Alternatively we could update this after every rrweb event
1414
1458
  // `timestamp` should reflect when the event happens. e.g. the timestamp
@@ -1418,7 +1462,7 @@ var SentryReplay = /** @class */ (function () {
1418
1462
  captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1419
1463
  return [3 /*break*/, 7];
1420
1464
  case 6:
1421
- err_1 = _a.sent();
1465
+ err_1 = _b.sent();
1422
1466
  core.captureException(err_1);
1423
1467
  console.error(err_1);
1424
1468
  return [3 /*break*/, 7];
@@ -1428,23 +1472,25 @@ var SentryReplay = /** @class */ (function () {
1428
1472
  });
1429
1473
  };
1430
1474
  /**
1431
- * Send replay attachment using either `sendBeacon()` or `fetch()`
1475
+ * Send replay attachment using `fetch()`
1432
1476
  */
1433
1477
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1478
+ var _b, _c;
1434
1479
  var endpoint = _a.endpoint, events = _a.events;
1435
1480
  return __awaiter(this, void 0, void 0, function () {
1436
- var payloadWithSequence, envelope;
1437
- return __generator(this, function (_b) {
1438
- switch (_b.label) {
1481
+ var payloadWithSequence, envelope, response, _d, _e;
1482
+ var _f;
1483
+ return __generator(this, function (_g) {
1484
+ switch (_g.label) {
1439
1485
  case 0:
1440
1486
  payloadWithSequence = createPayload({
1441
1487
  events: events,
1442
1488
  headers: {
1443
- segment_id: this.session.segmentId,
1489
+ segment_id: (_b = this.session) === null || _b === void 0 ? void 0 : _b.segmentId,
1444
1490
  },
1445
1491
  });
1446
1492
  envelope = utils.createEnvelope({
1447
- event_id: this.session.id,
1493
+ event_id: (_c = this.session) === null || _c === void 0 ? void 0 : _c.id,
1448
1494
  sent_at: new Date().toISOString(),
1449
1495
  sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1450
1496
  }, [
@@ -1454,15 +1500,10 @@ var SentryReplay = /** @class */ (function () {
1454
1500
  type: 'replay_recording',
1455
1501
  length: payloadWithSequence.length,
1456
1502
  },
1503
+ // @ts-expect-error: Type 'string' is not assignable to type 'ClientReport'.ts(2322)
1457
1504
  payloadWithSequence,
1458
1505
  ],
1459
1506
  ]);
1460
- // If sendBeacon is supported and payload is smol enough...
1461
- if (supportsSendBeacon() && events.length <= 65536) {
1462
- logger.log("uploading attachment via sendBeacon()");
1463
- window.navigator.sendBeacon(endpoint, utils.serializeEnvelope(envelope));
1464
- return [2 /*return*/];
1465
- }
1466
1507
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1467
1508
  logger.log("uploading attachment via fetch()");
1468
1509
  return [4 /*yield*/, fetch(endpoint, {
@@ -1470,8 +1511,19 @@ var SentryReplay = /** @class */ (function () {
1470
1511
  body: utils.serializeEnvelope(envelope),
1471
1512
  })];
1472
1513
  case 1:
1473
- _b.sent();
1474
- return [2 /*return*/];
1514
+ response = _g.sent();
1515
+ if (!(response.status !== 200)) return [3 /*break*/, 3];
1516
+ _d = core.setContext;
1517
+ _e = ['Send Replay Response'];
1518
+ _f = {
1519
+ status: response.status
1520
+ };
1521
+ return [4 /*yield*/, response.text()];
1522
+ case 2:
1523
+ _d.apply(void 0, _e.concat([(_f.body = _g.sent(),
1524
+ _f)]));
1525
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1526
+ case 3: return [2 /*return*/];
1475
1527
  }
1476
1528
  });
1477
1529
  });
@@ -1509,8 +1561,13 @@ var SentryReplay = /** @class */ (function () {
1509
1561
  return [2 /*return*/, true];
1510
1562
  case 3:
1511
1563
  ex_1 = _b.sent();
1512
- // we have to catch this otherwise it throws an infinite loop in Sentry
1513
1564
  console.error(ex_1);
1565
+ // Capture error for every failed replay
1566
+ // TODO: Remove this before GA as this will create an error on customer's project
1567
+ core.setContext('Replays', {
1568
+ retryCount: this.retryCount,
1569
+ });
1570
+ core.captureException(new Error(UNABLE_TO_SEND_REPLAY));
1514
1571
  // If an error happened here, it's likely that uploading the attachment
1515
1572
  // failed, we'll can retry with the same events payload
1516
1573
  if (this.retryCount >= MAX_RETRY_COUNT) {