@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.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 });
@@ -497,7 +502,9 @@ var ENTRY_TYPES = (_a = {
497
502
  _a['largest-contentful-paint'] = createLargestContentfulPaint,
498
503
  _a);
499
504
  function createPerformanceEntries(entries) {
500
- return entries.map(createPerformanceEntry).filter(Boolean);
505
+ return entries
506
+ .map(createPerformanceEntry)
507
+ .filter(Boolean);
501
508
  }
502
509
  function createPerformanceEntry(entry) {
503
510
  if (ENTRY_TYPES[entry.entryType] === undefined) {
@@ -691,7 +698,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
691
698
  var _this = this;
692
699
  var id = _a.id, method = _a.method, args = _a.args;
693
700
  return new Promise(function (resolve, reject) {
701
+ var _a, _b;
694
702
  var listener = function (_a) {
703
+ var _b;
695
704
  var data = _a.data;
696
705
  if (data.method !== method) {
697
706
  return;
@@ -702,7 +711,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
702
711
  return;
703
712
  }
704
713
  // At this point, we'll always want to remove listener regardless of result status
705
- _this.worker.removeEventListener('message', listener);
714
+ (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.removeEventListener('message', listener);
706
715
  if (!data.success) {
707
716
  // TODO: Do some error handling, not sure what
708
717
  logger.error(data.response);
@@ -713,8 +722,8 @@ var EventBufferCompressionWorker = /** @class */ (function () {
713
722
  };
714
723
  // Note: we can't use `once` option because it's possible it needs to
715
724
  // listen to multiple messages
716
- _this.worker.addEventListener('message', listener);
717
- _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 });
718
727
  });
719
728
  };
720
729
  EventBufferCompressionWorker.prototype.init = function () {
@@ -722,8 +731,9 @@ var EventBufferCompressionWorker = /** @class */ (function () {
722
731
  logger.log('Initialized compression worker');
723
732
  };
724
733
  EventBufferCompressionWorker.prototype.destroy = function () {
734
+ var _a;
725
735
  logger.log('Destroying compression worker');
726
- this.worker.terminate();
736
+ (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();
727
737
  this.worker = null;
728
738
  };
729
739
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
@@ -808,6 +818,7 @@ var SentryReplay = /** @class */ (function () {
808
818
  errorIds: new Set(),
809
819
  traceIds: new Set(),
810
820
  urls: [],
821
+ earliestEvent: null,
811
822
  };
812
823
  /**
813
824
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
@@ -815,7 +826,7 @@ var SentryReplay = /** @class */ (function () {
815
826
  * when an error occurs.
816
827
  **/
817
828
  this.handleGlobalEvent = function (event) {
818
- var _a;
829
+ var _a, _b;
819
830
  // Do not apply replayId to the root event
820
831
  if (
821
832
  // @ts-expect-error new event type
@@ -825,12 +836,13 @@ var SentryReplay = /** @class */ (function () {
825
836
  delete event.breadcrumbs;
826
837
  return event;
827
838
  }
828
- 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 });
829
840
  if (event.type === 'transaction') {
830
- _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) || ''));
831
842
  return event;
832
843
  }
833
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)
834
846
  _this.context.errorIds.add(event.event_id);
835
847
  // Need to be very careful that this does not cause an infinite loop
836
848
  if (_this.options.captureOnlyOnError &&
@@ -855,6 +867,7 @@ var SentryReplay = /** @class */ (function () {
855
867
  return;
856
868
  }
857
869
  _this.addUpdate(function () {
870
+ var _a;
858
871
  // We need to clear existing events on a checkout, otherwise they are
859
872
  // incremental event updates and should be appended
860
873
  _this.addEvent(event, isCheckout);
@@ -869,7 +882,7 @@ var SentryReplay = /** @class */ (function () {
869
882
  // of the previous session. Do not immediately flush in this case
870
883
  // to avoid capturing only the checkout and instead the replay will
871
884
  // be captured if they perform any follow-up actions.
872
- if (_this.session.previousSessionId) {
885
+ if ((_a = _this.session) === null || _a === void 0 ? void 0 : _a.previousSessionId) {
873
886
  return true;
874
887
  }
875
888
  // If the full snapshot is due to an initial load, we will not have
@@ -913,15 +926,6 @@ var SentryReplay = /** @class */ (function () {
913
926
  });
914
927
  _this.doChangeToForegroundTasks(breadcrumb);
915
928
  };
916
- /**
917
- * Handle when page is closed
918
- */
919
- this.handleWindowUnload = function () {
920
- _this.createCustomBreadcrumb(createBreadcrumb({
921
- category: 'ui.exit',
922
- }));
923
- _this.destroy();
924
- };
925
929
  /**
926
930
  * Handler for Sentry Core SDK events.
927
931
  *
@@ -940,6 +944,10 @@ var SentryReplay = /** @class */ (function () {
940
944
  }
941
945
  _this.addUpdate(function () {
942
946
  _this.createPerformanceSpans([result]);
947
+ // Returning true will cause `addUpdate` to not flush
948
+ // We do not want network requests to cause a flush. This will prevent
949
+ // recurring/polling requests from keeping the replay session alive.
950
+ return ['xhr', 'fetch'].includes(type);
943
951
  });
944
952
  }; };
945
953
  /**
@@ -961,7 +969,7 @@ var SentryReplay = /** @class */ (function () {
961
969
  type: rrweb.EventType.Custom,
962
970
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
963
971
  // but maybe we should just keep them as milliseconds
964
- timestamp: result.timestamp * 1000,
972
+ timestamp: (result.timestamp || 0) * 1000,
965
973
  data: {
966
974
  tag: 'breadcrumb',
967
975
  payload: result,
@@ -1024,7 +1032,7 @@ var SentryReplay = /** @class */ (function () {
1024
1032
  return;
1025
1033
  }
1026
1034
  this.eventBuffer = createEventBuffer({
1027
- useCompression: this.options.useCompression,
1035
+ useCompression: Boolean(this.options.useCompression),
1028
1036
  });
1029
1037
  this.addListeners();
1030
1038
  // Tag all (non replay) events that get sent to Sentry with the current
@@ -1089,7 +1097,7 @@ var SentryReplay = /** @class */ (function () {
1089
1097
  this.removeListeners();
1090
1098
  };
1091
1099
  SentryReplay.prototype.clearSession = function () {
1092
- this.session = null;
1100
+ this.session = undefined;
1093
1101
  };
1094
1102
  /**
1095
1103
  * Loads a session from storage, or creates a new one if it does not exist or
@@ -1100,7 +1108,7 @@ var SentryReplay = /** @class */ (function () {
1100
1108
  var expiry = _a.expiry;
1101
1109
  var _d = getSession({
1102
1110
  expiry: expiry,
1103
- stickySession: this.options.stickySession,
1111
+ stickySession: Boolean(this.options.stickySession),
1104
1112
  currentSession: this.session,
1105
1113
  samplingRate: this.options.replaysSamplingRate,
1106
1114
  }), type = _d.type, session = _d.session;
@@ -1139,10 +1147,9 @@ var SentryReplay = /** @class */ (function () {
1139
1147
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
1140
1148
  window.addEventListener('blur', this.handleWindowBlur);
1141
1149
  window.addEventListener('focus', this.handleWindowFocus);
1142
- window.addEventListener('beforeunload', this.handleWindowUnload);
1143
1150
  // Listeners from core SDK //
1144
1151
  var scope = core.getCurrentHub().getScope();
1145
- scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1152
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1146
1153
  utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1147
1154
  utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1148
1155
  utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
@@ -1164,7 +1171,8 @@ var SentryReplay = /** @class */ (function () {
1164
1171
  'paint',
1165
1172
  'resource',
1166
1173
  ].forEach(function (type) {
1167
- return _this.performanceObserver.observe({
1174
+ var _a;
1175
+ return (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({
1168
1176
  type: type,
1169
1177
  buffered: true,
1170
1178
  });
@@ -1177,7 +1185,6 @@ var SentryReplay = /** @class */ (function () {
1177
1185
  document.removeEventListener('visibilitychange', this.handleVisibilityChange);
1178
1186
  window.removeEventListener('blur', this.handleWindowBlur);
1179
1187
  window.removeEventListener('focus', this.handleWindowFocus);
1180
- window.removeEventListener('beforeunload', this.handleWindowUnload);
1181
1188
  if (this.performanceObserver) {
1182
1189
  this.performanceObserver.disconnect();
1183
1190
  this.performanceObserver = null;
@@ -1187,13 +1194,12 @@ var SentryReplay = /** @class */ (function () {
1187
1194
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
1188
1195
  */
1189
1196
  SentryReplay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {
1197
+ if (!this.session) {
1198
+ return;
1199
+ }
1190
1200
  var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1191
- if (breadcrumb) {
1192
- this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), {
1193
- // if somehow the page went hidden while session is expired, attach to previous session
1194
- timestamp: isExpired
1195
- ? this.session.lastActivity / 1000
1196
- : breadcrumb.timestamp }));
1201
+ if (breadcrumb && !isExpired) {
1202
+ this.createCustomBreadcrumb(breadcrumb);
1197
1203
  }
1198
1204
  // Send replay when the page/tab becomes hidden. There is no reason to send
1199
1205
  // replay if it becomes visible, since no actions we care about were done
@@ -1204,12 +1210,10 @@ var SentryReplay = /** @class */ (function () {
1204
1210
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
1205
1211
  */
1206
1212
  SentryReplay.prototype.doChangeToForegroundTasks = function (breadcrumb) {
1207
- var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1208
- if (breadcrumb) {
1209
- this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), { timestamp: isExpired
1210
- ? new Date().getTime() / 1000
1211
- : breadcrumb.timestamp }));
1213
+ if (!this.session) {
1214
+ return;
1212
1215
  }
1216
+ var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1213
1217
  if (isExpired) {
1214
1218
  // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
1215
1219
  // ms, we will re-use the existing session, otherwise create a new
@@ -1219,6 +1223,9 @@ var SentryReplay = /** @class */ (function () {
1219
1223
  this.triggerFullSnapshot();
1220
1224
  return;
1221
1225
  }
1226
+ if (breadcrumb) {
1227
+ this.createCustomBreadcrumb(breadcrumb);
1228
+ }
1222
1229
  // Otherwise if session is not expired...
1223
1230
  // Update with current timestamp as the last session activity
1224
1231
  // Only updating session on visibility change to be conservative about
@@ -1237,6 +1244,11 @@ var SentryReplay = /** @class */ (function () {
1237
1244
  * Add an event to the event buffer
1238
1245
  */
1239
1246
  SentryReplay.prototype.addEvent = function (event, isCheckout) {
1247
+ var timestampInMs = event.timestamp * 1000;
1248
+ if (!this.context.earliestEvent ||
1249
+ timestampInMs < this.context.earliestEvent) {
1250
+ this.context.earliestEvent = timestampInMs;
1251
+ }
1240
1252
  this.eventBuffer.addEvent(event, isCheckout);
1241
1253
  };
1242
1254
  /**
@@ -1244,7 +1256,9 @@ var SentryReplay = /** @class */ (function () {
1244
1256
  */
1245
1257
  SentryReplay.prototype.updateLastActivity = function (lastActivity) {
1246
1258
  if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1247
- this.session.lastActivity = lastActivity;
1259
+ if (this.session) {
1260
+ this.session.lastActivity = lastActivity;
1261
+ }
1248
1262
  };
1249
1263
  /**
1250
1264
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
@@ -1254,7 +1268,7 @@ var SentryReplay = /** @class */ (function () {
1254
1268
  this.addUpdate(function () {
1255
1269
  _this.addEvent({
1256
1270
  type: rrweb.EventType.Custom,
1257
- timestamp: breadcrumb.timestamp,
1271
+ timestamp: breadcrumb.timestamp || 0,
1258
1272
  data: {
1259
1273
  tag: 'breadcrumb',
1260
1274
  payload: breadcrumb,
@@ -1316,12 +1330,13 @@ var SentryReplay = /** @class */ (function () {
1316
1330
  * Returns true if session is not expired, false otherwise.
1317
1331
  */
1318
1332
  SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
1333
+ var _a, _b;
1319
1334
  if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
1320
- var oldSessionId = this.session.id;
1335
+ var oldSessionId = (_a = this.session) === null || _a === void 0 ? void 0 : _a.id;
1321
1336
  // This will create a new session if expired, based on expiry length
1322
1337
  this.loadSession({ expiry: expiry });
1323
1338
  // Session was expired if session ids do not match
1324
- var isExpired = oldSessionId !== this.session.id;
1339
+ var isExpired = oldSessionId !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id);
1325
1340
  if (!isExpired) {
1326
1341
  return true;
1327
1342
  }
@@ -1347,9 +1362,15 @@ var SentryReplay = /** @class */ (function () {
1347
1362
  */
1348
1363
  SentryReplay.prototype.popEventContext = function (_a) {
1349
1364
  var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1365
+ var initialState = this.initialState;
1366
+ if (this.initialState &&
1367
+ this.context.earliestEvent &&
1368
+ this.context.earliestEvent < this.initialState.timestamp) {
1369
+ initialState.timestamp = this.context.earliestEvent;
1370
+ }
1350
1371
  var context = {
1351
1372
  session: this.session,
1352
- initialState: this.initialState,
1373
+ initialState: initialState,
1353
1374
  timestamp: timestamp,
1354
1375
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
1355
1376
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
@@ -1358,6 +1379,8 @@ var SentryReplay = /** @class */ (function () {
1358
1379
  this.context.errorIds.clear();
1359
1380
  this.context.traceIds.clear();
1360
1381
  this.context.urls = [];
1382
+ this.context.earliestEvent = null;
1383
+ // @ts-expect-error: Type 'undefined' is not assignable to type 'Session'.ts(2322)
1361
1384
  return context;
1362
1385
  };
1363
1386
  /**
@@ -1367,16 +1390,17 @@ var SentryReplay = /** @class */ (function () {
1367
1390
  * due to the buffered performance observer events.
1368
1391
  */
1369
1392
  SentryReplay.prototype.flushUpdate = function (lastActivity) {
1393
+ var _a;
1370
1394
  return __awaiter(this, void 0, void 0, function () {
1371
1395
  var timestamp, recordingData, err_1;
1372
- return __generator(this, function (_a) {
1373
- switch (_a.label) {
1396
+ return __generator(this, function (_b) {
1397
+ switch (_b.label) {
1374
1398
  case 0:
1375
1399
  if (!this.checkAndHandleExpiredSession()) {
1376
1400
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1377
1401
  return [2 /*return*/];
1378
1402
  }
1379
- if (!this.session.id) {
1403
+ if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1380
1404
  console.error(new Error('[Sentry]: No transaction, no replay'));
1381
1405
  return [2 /*return*/];
1382
1406
  }
@@ -1384,7 +1408,7 @@ var SentryReplay = /** @class */ (function () {
1384
1408
  clearTimeout(this.timeout);
1385
1409
  return [4 /*yield*/, this.addPerformanceEntries()];
1386
1410
  case 1:
1387
- _a.sent();
1411
+ _b.sent();
1388
1412
  if (!this.eventBuffer.length) {
1389
1413
  return [2 /*return*/];
1390
1414
  }
@@ -1392,7 +1416,7 @@ var SentryReplay = /** @class */ (function () {
1392
1416
  return [4 /*yield*/, this.addMemoryEntry()];
1393
1417
  case 2:
1394
1418
  // Only attach memory event if eventBuffer is not empty
1395
- _a.sent();
1419
+ _b.sent();
1396
1420
  timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1397
1421
  // Only want to create replay event if session is new
1398
1422
  if (this.needsCaptureReplay) {
@@ -1403,15 +1427,15 @@ var SentryReplay = /** @class */ (function () {
1403
1427
  // Reset this to null regardless of `sendReplay` result so that future
1404
1428
  // events will get flushed properly
1405
1429
  this.initialEventTimestampSinceFlush = null;
1406
- _a.label = 3;
1430
+ _b.label = 3;
1407
1431
  case 3:
1408
- _a.trys.push([3, 6, , 7]);
1432
+ _b.trys.push([3, 6, , 7]);
1409
1433
  return [4 /*yield*/, this.eventBuffer.finish()];
1410
1434
  case 4:
1411
- recordingData = _a.sent();
1435
+ recordingData = _b.sent();
1412
1436
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1413
1437
  case 5:
1414
- _a.sent();
1438
+ _b.sent();
1415
1439
  // The below will only happen after successfully sending replay //
1416
1440
  // TBD: Alternatively we could update this after every rrweb event
1417
1441
  // `timestamp` should reflect when the event happens. e.g. the timestamp
@@ -1421,7 +1445,7 @@ var SentryReplay = /** @class */ (function () {
1421
1445
  captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1422
1446
  return [3 /*break*/, 7];
1423
1447
  case 6:
1424
- err_1 = _a.sent();
1448
+ err_1 = _b.sent();
1425
1449
  core.captureException(err_1);
1426
1450
  console.error(err_1);
1427
1451
  return [3 /*break*/, 7];
@@ -1434,21 +1458,22 @@ var SentryReplay = /** @class */ (function () {
1434
1458
  * Send replay attachment using `fetch()`
1435
1459
  */
1436
1460
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1461
+ var _b, _c;
1437
1462
  var endpoint = _a.endpoint, events = _a.events;
1438
1463
  return __awaiter(this, void 0, void 0, function () {
1439
- var payloadWithSequence, envelope, response, _b, _c;
1440
- var _d;
1441
- return __generator(this, function (_e) {
1442
- switch (_e.label) {
1464
+ var payloadWithSequence, envelope, response, _d, _e;
1465
+ var _f;
1466
+ return __generator(this, function (_g) {
1467
+ switch (_g.label) {
1443
1468
  case 0:
1444
1469
  payloadWithSequence = createPayload({
1445
1470
  events: events,
1446
1471
  headers: {
1447
- segment_id: this.session.segmentId,
1472
+ segment_id: (_b = this.session) === null || _b === void 0 ? void 0 : _b.segmentId,
1448
1473
  },
1449
1474
  });
1450
1475
  envelope = utils.createEnvelope({
1451
- event_id: this.session.id,
1476
+ event_id: (_c = this.session) === null || _c === void 0 ? void 0 : _c.id,
1452
1477
  sent_at: new Date().toISOString(),
1453
1478
  sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1454
1479
  }, [
@@ -1458,6 +1483,7 @@ var SentryReplay = /** @class */ (function () {
1458
1483
  type: 'replay_recording',
1459
1484
  length: payloadWithSequence.length,
1460
1485
  },
1486
+ // @ts-expect-error: Type 'string' is not assignable to type 'ClientReport'.ts(2322)
1461
1487
  payloadWithSequence,
1462
1488
  ],
1463
1489
  ]);
@@ -1468,17 +1494,17 @@ var SentryReplay = /** @class */ (function () {
1468
1494
  body: utils.serializeEnvelope(envelope),
1469
1495
  })];
1470
1496
  case 1:
1471
- response = _e.sent();
1497
+ response = _g.sent();
1472
1498
  if (!(response.status !== 200)) return [3 /*break*/, 3];
1473
- _b = core.setContext;
1474
- _c = ['Send Replay Response'];
1475
- _d = {
1499
+ _d = core.setContext;
1500
+ _e = ['Send Replay Response'];
1501
+ _f = {
1476
1502
  status: response.status
1477
1503
  };
1478
1504
  return [4 /*yield*/, response.text()];
1479
1505
  case 2:
1480
- _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1481
- _d)]));
1506
+ _d.apply(void 0, _e.concat([(_f.body = _g.sent(),
1507
+ _f)]));
1482
1508
  throw new Error(UNABLE_TO_SEND_REPLAY);
1483
1509
  case 3: return [2 /*return*/];
1484
1510
  }