@sentry/replay 0.5.4 → 0.5.7

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 (61) hide show
  1. package/dist/index.es.js +98 -72
  2. package/dist/index.js +98 -72
  3. package/dist/index.js.map +1 -1
  4. package/dist/types/src/coreHandlers/handleFetch.d.ts +1 -1
  5. package/dist/types/src/coreHandlers/handleXhr.d.ts +2 -2
  6. package/dist/types/src/index.d.ts +0 -4
  7. package/dist/types/src/session/Session.d.ts +2 -2
  8. package/dist/types/src/types.d.ts +4 -0
  9. package/dist/types/src/util/isExpired.d.ts +1 -1
  10. package/package.json +1 -1
  11. package/dist/config/types/jest.config.d.ts +0 -3
  12. package/dist/config/types/jest.setup.d.ts +0 -10
  13. package/dist/config/types/src/api/captureReplay.d.ts +0 -10
  14. package/dist/config/types/src/api/captureReplayUpdate.d.ts +0 -12
  15. package/dist/config/types/src/coreHandlers/getBreadcrumbHandler.d.ts +0 -3
  16. package/dist/config/types/src/coreHandlers/getSpanHandler.d.ts +0 -5
  17. package/dist/config/types/src/coreHandlers/handleDom.d.ts +0 -1
  18. package/dist/config/types/src/coreHandlers/handleFetch.d.ts +0 -19
  19. package/dist/config/types/src/coreHandlers/handleFetch.test.d.ts +0 -1
  20. package/dist/config/types/src/coreHandlers/handleHistory.d.ts +0 -7
  21. package/dist/config/types/src/coreHandlers/handleScope-unit.test.d.ts +0 -1
  22. package/dist/config/types/src/coreHandlers/handleScope.d.ts +0 -2
  23. package/dist/config/types/src/coreHandlers/handleScope.test.d.ts +0 -1
  24. package/dist/config/types/src/coreHandlers/handleXhr.d.ts +0 -21
  25. package/dist/config/types/src/createPerformanceEntry.d.ts +0 -42
  26. package/dist/config/types/src/createPerformanceEntry.test.d.ts +0 -1
  27. package/dist/config/types/src/eventBuffer.d.ts +0 -45
  28. package/dist/config/types/src/eventBuffer.test.d.ts +0 -1
  29. package/dist/config/types/src/flags.d.ts +0 -2
  30. package/dist/config/types/src/index-captureOnlyOnError.test.d.ts +0 -1
  31. package/dist/config/types/src/index-noSticky.test.d.ts +0 -1
  32. package/dist/config/types/src/index-sampling.test.d.ts +0 -1
  33. package/dist/config/types/src/index.d.ts +0 -234
  34. package/dist/config/types/src/index.test.d.ts +0 -1
  35. package/dist/config/types/src/session/Session.d.ts +0 -63
  36. package/dist/config/types/src/session/Session.test.d.ts +0 -1
  37. package/dist/config/types/src/session/constants.d.ts +0 -5
  38. package/dist/config/types/src/session/createSession.d.ts +0 -19
  39. package/dist/config/types/src/session/createSession.test.d.ts +0 -1
  40. package/dist/config/types/src/session/fetchSession.d.ts +0 -5
  41. package/dist/config/types/src/session/fetchSession.test.d.ts +0 -1
  42. package/dist/config/types/src/session/getSession.d.ts +0 -28
  43. package/dist/config/types/src/session/getSession.test.d.ts +0 -1
  44. package/dist/config/types/src/session/index.d.ts +0 -1
  45. package/dist/config/types/src/session/saveSession.d.ts +0 -2
  46. package/dist/config/types/src/session/saveSession.test.d.ts +0 -1
  47. package/dist/config/types/src/types.d.ts +0 -91
  48. package/dist/config/types/src/util/createBreadcrumb.d.ts +0 -4
  49. package/dist/config/types/src/util/createPayload.d.ts +0 -5
  50. package/dist/config/types/src/util/isExpired.d.ts +0 -5
  51. package/dist/config/types/src/util/isExpired.test.d.ts +0 -1
  52. package/dist/config/types/src/util/isIngestHost.d.ts +0 -4
  53. package/dist/config/types/src/util/isSampled.d.ts +0 -7
  54. package/dist/config/types/src/util/isSampled.test.d.ts +0 -1
  55. package/dist/config/types/src/util/isSessionExpired.d.ts +0 -5
  56. package/dist/config/types/src/util/isSessionExpired.test.d.ts +0 -1
  57. package/dist/config/types/src/util/logger.d.ts +0 -12
  58. package/dist/config/types/src/util/supportsSendBeacon.d.ts +0 -4
  59. package/dist/config/types/test/index.d.ts +0 -3
  60. package/dist/config/types/test/mocks/mockRrweb.d.ts +0 -15
  61. package/dist/config/types/test/mocks/mockSdk.d.ts +0 -11
package/dist/index.es.js CHANGED
@@ -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 });
@@ -493,7 +498,9 @@ var ENTRY_TYPES = (_a = {
493
498
  _a['largest-contentful-paint'] = createLargestContentfulPaint,
494
499
  _a);
495
500
  function createPerformanceEntries(entries) {
496
- return entries.map(createPerformanceEntry).filter(Boolean);
501
+ return entries
502
+ .map(createPerformanceEntry)
503
+ .filter(Boolean);
497
504
  }
498
505
  function createPerformanceEntry(entry) {
499
506
  if (ENTRY_TYPES[entry.entryType] === undefined) {
@@ -687,7 +694,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
687
694
  var _this = this;
688
695
  var id = _a.id, method = _a.method, args = _a.args;
689
696
  return new Promise(function (resolve, reject) {
697
+ var _a, _b;
690
698
  var listener = function (_a) {
699
+ var _b;
691
700
  var data = _a.data;
692
701
  if (data.method !== method) {
693
702
  return;
@@ -698,7 +707,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
698
707
  return;
699
708
  }
700
709
  // At this point, we'll always want to remove listener regardless of result status
701
- _this.worker.removeEventListener('message', listener);
710
+ (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.removeEventListener('message', listener);
702
711
  if (!data.success) {
703
712
  // TODO: Do some error handling, not sure what
704
713
  logger.error(data.response);
@@ -709,8 +718,8 @@ var EventBufferCompressionWorker = /** @class */ (function () {
709
718
  };
710
719
  // Note: we can't use `once` option because it's possible it needs to
711
720
  // listen to multiple messages
712
- _this.worker.addEventListener('message', listener);
713
- _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 });
714
723
  });
715
724
  };
716
725
  EventBufferCompressionWorker.prototype.init = function () {
@@ -718,8 +727,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
718
727
  logger.log('Initialized compression worker');
719
728
  };
720
729
  EventBufferCompressionWorker.prototype.destroy = function () {
730
+ var _a;
721
731
  logger.log('Destroying compression worker');
722
- this.worker.terminate();
732
+ (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();
723
733
  this.worker = null;
724
734
  };
725
735
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
@@ -804,6 +814,7 @@ var SentryReplay = /** @class */ (function () {
804
814
  errorIds: new Set(),
805
815
  traceIds: new Set(),
806
816
  urls: [],
817
+ earliestEvent: null,
807
818
  };
808
819
  /**
809
820
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
@@ -811,7 +822,7 @@ var SentryReplay = /** @class */ (function () {
811
822
  * when an error occurs.
812
823
  **/
813
824
  this.handleGlobalEvent = function (event) {
814
- var _a;
825
+ var _a, _b;
815
826
  // Do not apply replayId to the root event
816
827
  if (
817
828
  // @ts-expect-error new event type
@@ -821,12 +832,13 @@ var SentryReplay = /** @class */ (function () {
821
832
  delete event.breadcrumbs;
822
833
  return event;
823
834
  }
824
- 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 });
825
836
  if (event.type === 'transaction') {
826
- _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) || ''));
827
838
  return event;
828
839
  }
829
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)
830
842
  _this.context.errorIds.add(event.event_id);
831
843
  // Need to be very careful that this does not cause an infinite loop
832
844
  if (_this.options.captureOnlyOnError &&
@@ -851,6 +863,7 @@ var SentryReplay = /** @class */ (function () {
851
863
  return;
852
864
  }
853
865
  _this.addUpdate(function () {
866
+ var _a;
854
867
  // We need to clear existing events on a checkout, otherwise they are
855
868
  // incremental event updates and should be appended
856
869
  _this.addEvent(event, isCheckout);
@@ -865,7 +878,7 @@ var SentryReplay = /** @class */ (function () {
865
878
  // of the previous session. Do not immediately flush in this case
866
879
  // to avoid capturing only the checkout and instead the replay will
867
880
  // be captured if they perform any follow-up actions.
868
- if (_this.session.previousSessionId) {
881
+ if ((_a = _this.session) === null || _a === void 0 ? void 0 : _a.previousSessionId) {
869
882
  return true;
870
883
  }
871
884
  // If the full snapshot is due to an initial load, we will not have
@@ -909,15 +922,6 @@ var SentryReplay = /** @class */ (function () {
909
922
  });
910
923
  _this.doChangeToForegroundTasks(breadcrumb);
911
924
  };
912
- /**
913
- * Handle when page is closed
914
- */
915
- this.handleWindowUnload = function () {
916
- _this.createCustomBreadcrumb(createBreadcrumb({
917
- category: 'ui.exit',
918
- }));
919
- _this.destroy();
920
- };
921
925
  /**
922
926
  * Handler for Sentry Core SDK events.
923
927
  *
@@ -936,6 +940,10 @@ var SentryReplay = /** @class */ (function () {
936
940
  }
937
941
  _this.addUpdate(function () {
938
942
  _this.createPerformanceSpans([result]);
943
+ // Returning true will cause `addUpdate` to not flush
944
+ // We do not want network requests to cause a flush. This will prevent
945
+ // recurring/polling requests from keeping the replay session alive.
946
+ return ['xhr', 'fetch'].includes(type);
939
947
  });
940
948
  }; };
941
949
  /**
@@ -957,7 +965,7 @@ var SentryReplay = /** @class */ (function () {
957
965
  type: EventType.Custom,
958
966
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
959
967
  // but maybe we should just keep them as milliseconds
960
- timestamp: result.timestamp * 1000,
968
+ timestamp: (result.timestamp || 0) * 1000,
961
969
  data: {
962
970
  tag: 'breadcrumb',
963
971
  payload: result,
@@ -1020,7 +1028,7 @@ var SentryReplay = /** @class */ (function () {
1020
1028
  return;
1021
1029
  }
1022
1030
  this.eventBuffer = createEventBuffer({
1023
- useCompression: this.options.useCompression,
1031
+ useCompression: Boolean(this.options.useCompression),
1024
1032
  });
1025
1033
  this.addListeners();
1026
1034
  // Tag all (non replay) events that get sent to Sentry with the current
@@ -1085,7 +1093,7 @@ var SentryReplay = /** @class */ (function () {
1085
1093
  this.removeListeners();
1086
1094
  };
1087
1095
  SentryReplay.prototype.clearSession = function () {
1088
- this.session = null;
1096
+ this.session = undefined;
1089
1097
  };
1090
1098
  /**
1091
1099
  * Loads a session from storage, or creates a new one if it does not exist or
@@ -1096,7 +1104,7 @@ var SentryReplay = /** @class */ (function () {
1096
1104
  var expiry = _a.expiry;
1097
1105
  var _d = getSession({
1098
1106
  expiry: expiry,
1099
- stickySession: this.options.stickySession,
1107
+ stickySession: Boolean(this.options.stickySession),
1100
1108
  currentSession: this.session,
1101
1109
  samplingRate: this.options.replaysSamplingRate,
1102
1110
  }), type = _d.type, session = _d.session;
@@ -1135,10 +1143,9 @@ var SentryReplay = /** @class */ (function () {
1135
1143
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
1136
1144
  window.addEventListener('blur', this.handleWindowBlur);
1137
1145
  window.addEventListener('focus', this.handleWindowFocus);
1138
- window.addEventListener('beforeunload', this.handleWindowUnload);
1139
1146
  // Listeners from core SDK //
1140
1147
  var scope = getCurrentHub().getScope();
1141
- scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1148
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1142
1149
  addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1143
1150
  addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1144
1151
  addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
@@ -1160,7 +1167,8 @@ var SentryReplay = /** @class */ (function () {
1160
1167
  'paint',
1161
1168
  'resource',
1162
1169
  ].forEach(function (type) {
1163
- return _this.performanceObserver.observe({
1170
+ var _a;
1171
+ return (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({
1164
1172
  type: type,
1165
1173
  buffered: true,
1166
1174
  });
@@ -1173,7 +1181,6 @@ var SentryReplay = /** @class */ (function () {
1173
1181
  document.removeEventListener('visibilitychange', this.handleVisibilityChange);
1174
1182
  window.removeEventListener('blur', this.handleWindowBlur);
1175
1183
  window.removeEventListener('focus', this.handleWindowFocus);
1176
- window.removeEventListener('beforeunload', this.handleWindowUnload);
1177
1184
  if (this.performanceObserver) {
1178
1185
  this.performanceObserver.disconnect();
1179
1186
  this.performanceObserver = null;
@@ -1183,13 +1190,12 @@ var SentryReplay = /** @class */ (function () {
1183
1190
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
1184
1191
  */
1185
1192
  SentryReplay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {
1193
+ if (!this.session) {
1194
+ return;
1195
+ }
1186
1196
  var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1187
- if (breadcrumb) {
1188
- this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), {
1189
- // if somehow the page went hidden while session is expired, attach to previous session
1190
- timestamp: isExpired
1191
- ? this.session.lastActivity / 1000
1192
- : breadcrumb.timestamp }));
1197
+ if (breadcrumb && !isExpired) {
1198
+ this.createCustomBreadcrumb(breadcrumb);
1193
1199
  }
1194
1200
  // Send replay when the page/tab becomes hidden. There is no reason to send
1195
1201
  // replay if it becomes visible, since no actions we care about were done
@@ -1200,12 +1206,10 @@ var SentryReplay = /** @class */ (function () {
1200
1206
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
1201
1207
  */
1202
1208
  SentryReplay.prototype.doChangeToForegroundTasks = function (breadcrumb) {
1203
- var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1204
- if (breadcrumb) {
1205
- this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), { timestamp: isExpired
1206
- ? new Date().getTime() / 1000
1207
- : breadcrumb.timestamp }));
1209
+ if (!this.session) {
1210
+ return;
1208
1211
  }
1212
+ var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1209
1213
  if (isExpired) {
1210
1214
  // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
1211
1215
  // ms, we will re-use the existing session, otherwise create a new
@@ -1215,6 +1219,9 @@ var SentryReplay = /** @class */ (function () {
1215
1219
  this.triggerFullSnapshot();
1216
1220
  return;
1217
1221
  }
1222
+ if (breadcrumb) {
1223
+ this.createCustomBreadcrumb(breadcrumb);
1224
+ }
1218
1225
  // Otherwise if session is not expired...
1219
1226
  // Update with current timestamp as the last session activity
1220
1227
  // Only updating session on visibility change to be conservative about
@@ -1233,6 +1240,11 @@ var SentryReplay = /** @class */ (function () {
1233
1240
  * Add an event to the event buffer
1234
1241
  */
1235
1242
  SentryReplay.prototype.addEvent = function (event, isCheckout) {
1243
+ var timestampInMs = event.timestamp * 1000;
1244
+ if (!this.context.earliestEvent ||
1245
+ timestampInMs < this.context.earliestEvent) {
1246
+ this.context.earliestEvent = timestampInMs;
1247
+ }
1236
1248
  this.eventBuffer.addEvent(event, isCheckout);
1237
1249
  };
1238
1250
  /**
@@ -1240,7 +1252,9 @@ var SentryReplay = /** @class */ (function () {
1240
1252
  */
1241
1253
  SentryReplay.prototype.updateLastActivity = function (lastActivity) {
1242
1254
  if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1243
- this.session.lastActivity = lastActivity;
1255
+ if (this.session) {
1256
+ this.session.lastActivity = lastActivity;
1257
+ }
1244
1258
  };
1245
1259
  /**
1246
1260
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
@@ -1250,7 +1264,7 @@ var SentryReplay = /** @class */ (function () {
1250
1264
  this.addUpdate(function () {
1251
1265
  _this.addEvent({
1252
1266
  type: EventType.Custom,
1253
- timestamp: breadcrumb.timestamp,
1267
+ timestamp: breadcrumb.timestamp || 0,
1254
1268
  data: {
1255
1269
  tag: 'breadcrumb',
1256
1270
  payload: breadcrumb,
@@ -1312,12 +1326,13 @@ var SentryReplay = /** @class */ (function () {
1312
1326
  * Returns true if session is not expired, false otherwise.
1313
1327
  */
1314
1328
  SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
1329
+ var _a, _b;
1315
1330
  if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
1316
- var oldSessionId = this.session.id;
1331
+ var oldSessionId = (_a = this.session) === null || _a === void 0 ? void 0 : _a.id;
1317
1332
  // This will create a new session if expired, based on expiry length
1318
1333
  this.loadSession({ expiry: expiry });
1319
1334
  // Session was expired if session ids do not match
1320
- var isExpired = oldSessionId !== this.session.id;
1335
+ var isExpired = oldSessionId !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id);
1321
1336
  if (!isExpired) {
1322
1337
  return true;
1323
1338
  }
@@ -1343,9 +1358,15 @@ var SentryReplay = /** @class */ (function () {
1343
1358
  */
1344
1359
  SentryReplay.prototype.popEventContext = function (_a) {
1345
1360
  var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1361
+ var initialState = this.initialState;
1362
+ if (this.initialState &&
1363
+ this.context.earliestEvent &&
1364
+ this.context.earliestEvent < this.initialState.timestamp) {
1365
+ initialState.timestamp = this.context.earliestEvent;
1366
+ }
1346
1367
  var context = {
1347
1368
  session: this.session,
1348
- initialState: this.initialState,
1369
+ initialState: initialState,
1349
1370
  timestamp: timestamp,
1350
1371
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
1351
1372
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
@@ -1354,6 +1375,8 @@ var SentryReplay = /** @class */ (function () {
1354
1375
  this.context.errorIds.clear();
1355
1376
  this.context.traceIds.clear();
1356
1377
  this.context.urls = [];
1378
+ this.context.earliestEvent = null;
1379
+ // @ts-expect-error: Type 'undefined' is not assignable to type 'Session'.ts(2322)
1357
1380
  return context;
1358
1381
  };
1359
1382
  /**
@@ -1363,16 +1386,17 @@ var SentryReplay = /** @class */ (function () {
1363
1386
  * due to the buffered performance observer events.
1364
1387
  */
1365
1388
  SentryReplay.prototype.flushUpdate = function (lastActivity) {
1389
+ var _a;
1366
1390
  return __awaiter(this, void 0, void 0, function () {
1367
1391
  var timestamp, recordingData, err_1;
1368
- return __generator(this, function (_a) {
1369
- switch (_a.label) {
1392
+ return __generator(this, function (_b) {
1393
+ switch (_b.label) {
1370
1394
  case 0:
1371
1395
  if (!this.checkAndHandleExpiredSession()) {
1372
1396
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1373
1397
  return [2 /*return*/];
1374
1398
  }
1375
- if (!this.session.id) {
1399
+ if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1376
1400
  console.error(new Error('[Sentry]: No transaction, no replay'));
1377
1401
  return [2 /*return*/];
1378
1402
  }
@@ -1380,7 +1404,7 @@ var SentryReplay = /** @class */ (function () {
1380
1404
  clearTimeout(this.timeout);
1381
1405
  return [4 /*yield*/, this.addPerformanceEntries()];
1382
1406
  case 1:
1383
- _a.sent();
1407
+ _b.sent();
1384
1408
  if (!this.eventBuffer.length) {
1385
1409
  return [2 /*return*/];
1386
1410
  }
@@ -1388,7 +1412,7 @@ var SentryReplay = /** @class */ (function () {
1388
1412
  return [4 /*yield*/, this.addMemoryEntry()];
1389
1413
  case 2:
1390
1414
  // Only attach memory event if eventBuffer is not empty
1391
- _a.sent();
1415
+ _b.sent();
1392
1416
  timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1393
1417
  // Only want to create replay event if session is new
1394
1418
  if (this.needsCaptureReplay) {
@@ -1399,15 +1423,15 @@ var SentryReplay = /** @class */ (function () {
1399
1423
  // Reset this to null regardless of `sendReplay` result so that future
1400
1424
  // events will get flushed properly
1401
1425
  this.initialEventTimestampSinceFlush = null;
1402
- _a.label = 3;
1426
+ _b.label = 3;
1403
1427
  case 3:
1404
- _a.trys.push([3, 6, , 7]);
1428
+ _b.trys.push([3, 6, , 7]);
1405
1429
  return [4 /*yield*/, this.eventBuffer.finish()];
1406
1430
  case 4:
1407
- recordingData = _a.sent();
1431
+ recordingData = _b.sent();
1408
1432
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1409
1433
  case 5:
1410
- _a.sent();
1434
+ _b.sent();
1411
1435
  // The below will only happen after successfully sending replay //
1412
1436
  // TBD: Alternatively we could update this after every rrweb event
1413
1437
  // `timestamp` should reflect when the event happens. e.g. the timestamp
@@ -1417,7 +1441,7 @@ var SentryReplay = /** @class */ (function () {
1417
1441
  captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1418
1442
  return [3 /*break*/, 7];
1419
1443
  case 6:
1420
- err_1 = _a.sent();
1444
+ err_1 = _b.sent();
1421
1445
  captureException(err_1);
1422
1446
  console.error(err_1);
1423
1447
  return [3 /*break*/, 7];
@@ -1430,21 +1454,22 @@ var SentryReplay = /** @class */ (function () {
1430
1454
  * Send replay attachment using `fetch()`
1431
1455
  */
1432
1456
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1457
+ var _b, _c;
1433
1458
  var endpoint = _a.endpoint, events = _a.events;
1434
1459
  return __awaiter(this, void 0, void 0, function () {
1435
- var payloadWithSequence, envelope, response, _b, _c;
1436
- var _d;
1437
- return __generator(this, function (_e) {
1438
- switch (_e.label) {
1460
+ var payloadWithSequence, envelope, response, _d, _e;
1461
+ var _f;
1462
+ return __generator(this, function (_g) {
1463
+ switch (_g.label) {
1439
1464
  case 0:
1440
1465
  payloadWithSequence = createPayload({
1441
1466
  events: events,
1442
1467
  headers: {
1443
- segment_id: this.session.segmentId,
1468
+ segment_id: (_b = this.session) === null || _b === void 0 ? void 0 : _b.segmentId,
1444
1469
  },
1445
1470
  });
1446
1471
  envelope = createEnvelope({
1447
- event_id: this.session.id,
1472
+ event_id: (_c = this.session) === null || _c === void 0 ? void 0 : _c.id,
1448
1473
  sent_at: new Date().toISOString(),
1449
1474
  sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1450
1475
  }, [
@@ -1454,6 +1479,7 @@ var SentryReplay = /** @class */ (function () {
1454
1479
  type: 'replay_recording',
1455
1480
  length: payloadWithSequence.length,
1456
1481
  },
1482
+ // @ts-expect-error: Type 'string' is not assignable to type 'ClientReport'.ts(2322)
1457
1483
  payloadWithSequence,
1458
1484
  ],
1459
1485
  ]);
@@ -1464,17 +1490,17 @@ var SentryReplay = /** @class */ (function () {
1464
1490
  body: serializeEnvelope(envelope),
1465
1491
  })];
1466
1492
  case 1:
1467
- response = _e.sent();
1493
+ response = _g.sent();
1468
1494
  if (!(response.status !== 200)) return [3 /*break*/, 3];
1469
- _b = setContext;
1470
- _c = ['Send Replay Response'];
1471
- _d = {
1495
+ _d = setContext;
1496
+ _e = ['Send Replay Response'];
1497
+ _f = {
1472
1498
  status: response.status
1473
1499
  };
1474
1500
  return [4 /*yield*/, response.text()];
1475
1501
  case 2:
1476
- _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1477
- _d)]));
1502
+ _d.apply(void 0, _e.concat([(_f.body = _g.sent(),
1503
+ _f)]));
1478
1504
  throw new Error(UNABLE_TO_SEND_REPLAY);
1479
1505
  case 3: return [2 /*return*/];
1480
1506
  }