@sentry/replay 0.5.11 → 0.5.14

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.
package/dist/index.js CHANGED
@@ -99,32 +99,13 @@ var SESSION_IDLE_DURATION = 900000; // 15 minutes
99
99
  // Grace period to keep a session when a user changes tabs or hides window
100
100
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
101
101
 
102
- function captureReplay(_a) {
103
- var session = _a.session, initialState = _a.initialState, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
104
- core.captureEvent({
102
+ function captureReplayEvent(_a) {
103
+ var initialState = _a.initialState, includeReplayStartTimestamp = _a.includeReplayStartTimestamp, errorIds = _a.errorIds, replay_id = _a.replayId, segment_id = _a.segmentId, timestamp = _a.timestamp, traceIds = _a.traceIds, urls = _a.urls;
104
+ core.captureEvent(__assign(__assign(__assign({
105
105
  // @ts-expect-error replay_event is a new event type
106
- type: REPLAY_EVENT_NAME,
107
- replay_start_timestamp: initialState.timestamp / 1000,
108
- error_ids: errorIds,
109
- trace_ids: traceIds,
110
- urls: urls,
111
- replay_id: session.id,
112
- segment_id: session.segmentId, // TODO: Should this increment?
113
- }, { event_id: session.id });
114
- }
115
-
116
- function captureReplayUpdate(_a) {
117
- var session = _a.session, timestamp = _a.timestamp, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
118
- core.captureEvent({
119
- // @ts-expect-error replay_event is a new event type
120
- type: REPLAY_EVENT_NAME,
121
- timestamp: timestamp / 1000,
122
- error_ids: errorIds,
123
- trace_ids: traceIds,
124
- urls: urls,
125
- replay_id: session.id,
126
- segment_id: ++session.segmentId,
127
- });
106
+ type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp
107
+ ? { replay_start_timestamp: initialState.timestamp / 1000 }
108
+ : {})), (timestamp ? { timestamp: timestamp / 1000 } : {})), { error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: replay_id, segment_id: segment_id }), { event_id: replay_id });
128
109
  }
129
110
 
130
111
  function createBreadcrumb(breadcrumb) {
@@ -802,7 +783,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
802
783
  }());
803
784
 
804
785
  var BASE_RETRY_INTERVAL = 5000;
805
- var MAX_RETRY_COUNT = 5;
786
+ var MAX_RETRY_COUNT = 3;
806
787
  var UNABLE_TO_SEND_REPLAY = 'Unable to send replay';
807
788
  var SentryReplay = /** @class */ (function () {
808
789
  function SentryReplay(_a) {
@@ -813,10 +794,6 @@ var SentryReplay = /** @class */ (function () {
813
794
  * @inheritDoc
814
795
  */
815
796
  this.name = SentryReplay.id;
816
- /**
817
- * Buffer of breadcrumbs to be uploaded
818
- */
819
- this.breadcrumbs = [];
820
797
  /**
821
798
  * List of PerformanceEntry from PerformanceObserver
822
799
  */
@@ -831,12 +808,23 @@ var SentryReplay = /** @class */ (function () {
831
808
  this.retryCount = 0;
832
809
  this.retryInterval = BASE_RETRY_INTERVAL;
833
810
  /**
834
- * Flag to make sure we only create a replay event when
835
- * necessary (i.e. we only want to have a single replay
836
- * event per session and it should only be created
837
- * immediately before sending recording)
811
+ * Flag when a new session has been created. Captured replay events behave
812
+ * slightly differently in this case: `replay_start_timestamp` is included.
813
+ */
814
+ this.newSessionCreated = false;
815
+ /**
816
+ * Is the integration currently active?
838
817
  */
839
- this.needsCaptureReplay = false;
818
+ this.isEnabled = false;
819
+ /**
820
+ * Have we attached listeners to the core SDK?
821
+ * Note we have to track this as there is no way to remove instrumentation handlers.
822
+ */
823
+ this.hasInitializedCoreListeners = false;
824
+ /**
825
+ * Function to stop recording
826
+ */
827
+ this.stopRecording = null;
840
828
  this.context = {
841
829
  errorIds: new Set(),
842
830
  traceIds: new Set(),
@@ -955,6 +943,9 @@ var SentryReplay = /** @class */ (function () {
955
943
  *
956
944
  */
957
945
  this.handleCoreSpanListener = function (type) { return function (handlerData) {
946
+ if (!_this.isEnabled) {
947
+ return;
948
+ }
958
949
  var handler = getSpanHandler(type);
959
950
  var result = handler(handlerData);
960
951
  if (result === null) {
@@ -978,6 +969,9 @@ var SentryReplay = /** @class */ (function () {
978
969
  * These events will create breadcrumb-like objects in the recording.
979
970
  */
980
971
  this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
972
+ if (!_this.isEnabled) {
973
+ return;
974
+ }
981
975
  var handler = getBreadcrumbHandler(type);
982
976
  var result = handler(handlerData);
983
977
  if (result === null) {
@@ -1060,7 +1054,8 @@ var SentryReplay = /** @class */ (function () {
1060
1054
  // Tag all (non replay) events that get sent to Sentry with the current
1061
1055
  // replay ID so that we can reference them later in the UI
1062
1056
  core.addGlobalEventProcessor(this.handleGlobalEvent);
1063
- rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1057
+ this.stopRecording = rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1058
+ this.isEnabled = true;
1064
1059
  };
1065
1060
  /**
1066
1061
  * We want to batch uploads of replay events. Save events only if
@@ -1115,8 +1110,13 @@ var SentryReplay = /** @class */ (function () {
1115
1110
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
1116
1111
  */
1117
1112
  SentryReplay.prototype.destroy = function () {
1113
+ var _a, _b;
1118
1114
  logger.log('Destroying instance');
1115
+ this.isEnabled = false;
1119
1116
  this.removeListeners();
1117
+ (_a = this.stopRecording) === null || _a === void 0 ? void 0 : _a.call(this);
1118
+ (_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.destroy();
1119
+ this.eventBuffer = null;
1120
1120
  };
1121
1121
  SentryReplay.prototype.clearSession = function () {
1122
1122
  deleteSession();
@@ -1138,7 +1138,7 @@ var SentryReplay = /** @class */ (function () {
1138
1138
  // If session was newly created (i.e. was not loaded from storage), then
1139
1139
  // enable flag to create the root replay
1140
1140
  if (type === 'new') {
1141
- this.needsCaptureReplay = true;
1141
+ this.newSessionCreated = true;
1142
1142
  this.setInitialState();
1143
1143
  }
1144
1144
  if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
@@ -1154,6 +1154,7 @@ var SentryReplay = /** @class */ (function () {
1154
1154
  SentryReplay.prototype.setInitialState = function () {
1155
1155
  var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1156
1156
  var url = "".concat(window.location.origin).concat(urlPath);
1157
+ this.performanceEvents = [];
1157
1158
  // Reset context as well
1158
1159
  this.popEventContext();
1159
1160
  this.initialState = {
@@ -1170,13 +1171,17 @@ var SentryReplay = /** @class */ (function () {
1170
1171
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
1171
1172
  window.addEventListener('blur', this.handleWindowBlur);
1172
1173
  window.addEventListener('focus', this.handleWindowFocus);
1173
- // Listeners from core SDK //
1174
- var scope = core.getCurrentHub().getScope();
1175
- scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1176
- utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1177
- utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1178
- utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1179
- utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1174
+ // There is no way to remove these listeners, so ensure they are only added once
1175
+ if (!this.hasInitializedCoreListeners) {
1176
+ // Listeners from core SDK //
1177
+ var scope = core.getCurrentHub().getScope();
1178
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1179
+ utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1180
+ utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1181
+ utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1182
+ utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1183
+ this.hasInitializedCoreListeners = true;
1184
+ }
1180
1185
  // PerformanceObserver //
1181
1186
  if (!('PerformanceObserver' in window)) {
1182
1187
  return;
@@ -1273,7 +1278,14 @@ var SentryReplay = /** @class */ (function () {
1273
1278
  * Add an event to the event buffer
1274
1279
  */
1275
1280
  SentryReplay.prototype.addEvent = function (event, isCheckout) {
1276
- var timestampInMs = event.timestamp * 1000;
1281
+ if (!this.eventBuffer) {
1282
+ // This implies that `isEnabled` is false
1283
+ return;
1284
+ }
1285
+ // TODO: sadness -- we will want to normalize timestamps to be in ms -
1286
+ // requires coordination with frontend
1287
+ var isMs = event.timestamp > 9999999999;
1288
+ var timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
1277
1289
  if (!this.context.earliestEvent ||
1278
1290
  timestampInMs < this.context.earliestEvent) {
1279
1291
  this.context.earliestEvent = timestampInMs;
@@ -1398,7 +1410,6 @@ var SentryReplay = /** @class */ (function () {
1398
1410
  initialState.timestamp = this.context.earliestEvent;
1399
1411
  }
1400
1412
  var context = {
1401
- session: this.session,
1402
1413
  initialState: initialState,
1403
1414
  timestamp: timestamp,
1404
1415
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
@@ -1419,12 +1430,17 @@ var SentryReplay = /** @class */ (function () {
1419
1430
  * due to the buffered performance observer events.
1420
1431
  */
1421
1432
  SentryReplay.prototype.flushUpdate = function () {
1422
- var _a;
1433
+ var _a, _b;
1423
1434
  return __awaiter(this, void 0, void 0, function () {
1424
- var timestamp, recordingData, err_1;
1425
- return __generator(this, function (_b) {
1426
- switch (_b.label) {
1435
+ var timestamp, replayId, newSessionCreated, segmentId, recordingData, err_1;
1436
+ return __generator(this, function (_c) {
1437
+ switch (_c.label) {
1427
1438
  case 0:
1439
+ if (!this.isEnabled) {
1440
+ // This is just a precaution, there should be no listeners that would
1441
+ // cause a flush.
1442
+ return [2 /*return*/];
1443
+ }
1428
1444
  if (!this.checkAndHandleExpiredSession()) {
1429
1445
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1430
1446
  return [2 /*return*/];
@@ -1437,44 +1453,42 @@ var SentryReplay = /** @class */ (function () {
1437
1453
  clearTimeout(this.timeout);
1438
1454
  return [4 /*yield*/, this.addPerformanceEntries()];
1439
1455
  case 1:
1440
- _b.sent();
1441
- if (!this.eventBuffer.length) {
1456
+ _c.sent();
1457
+ if (!((_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.length)) {
1442
1458
  return [2 /*return*/];
1443
1459
  }
1444
1460
  // Only attach memory event if eventBuffer is not empty
1445
1461
  return [4 /*yield*/, this.addMemoryEntry()];
1446
1462
  case 2:
1447
1463
  // Only attach memory event if eventBuffer is not empty
1448
- _b.sent();
1464
+ _c.sent();
1449
1465
  timestamp = new Date().getTime();
1450
- // Only want to create replay event if session is new
1451
- if (this.needsCaptureReplay) {
1452
- // This event needs to exist before calling `sendReplay`
1453
- captureReplay(this.popEventContext({ timestamp: timestamp }));
1454
- this.needsCaptureReplay = false;
1455
- }
1466
+ replayId = this.session.id;
1467
+ newSessionCreated = this.newSessionCreated;
1468
+ segmentId = this.session.segmentId++;
1456
1469
  // Reset this to null regardless of `sendReplay` result so that future
1457
1470
  // events will get flushed properly
1458
1471
  this.initialEventTimestampSinceFlush = null;
1459
- _b.label = 3;
1472
+ _c.label = 3;
1460
1473
  case 3:
1461
- _b.trys.push([3, 6, , 7]);
1474
+ _c.trys.push([3, 6, , 7]);
1462
1475
  return [4 /*yield*/, this.eventBuffer.finish()];
1463
1476
  case 4:
1464
- recordingData = _b.sent();
1465
- return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1477
+ recordingData = _c.sent();
1478
+ return [4 /*yield*/, this.sendReplay(replayId, recordingData, segmentId)];
1466
1479
  case 5:
1467
- _b.sent();
1480
+ _c.sent();
1468
1481
  // The below will only happen after successfully sending replay //
1469
1482
  // TBD: Alternatively we could update this after every rrweb event
1470
1483
  // `timestamp` should reflect when the event happens. e.g. the timestamp
1471
1484
  // of the event is passed as an argument in the case where a timeout
1472
1485
  // occurs.
1473
1486
  this.updateLastActivity(timestamp);
1474
- captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1487
+ captureReplayEvent(__assign(__assign({}, this.popEventContext({ timestamp: timestamp })), { replayId: replayId, segmentId: segmentId, includeReplayStartTimestamp: newSessionCreated }));
1488
+ this.newSessionCreated = false;
1475
1489
  return [3 /*break*/, 7];
1476
1490
  case 6:
1477
- err_1 = _b.sent();
1491
+ err_1 = _c.sent();
1478
1492
  core.captureException(err_1);
1479
1493
  console.error(err_1);
1480
1494
  return [3 /*break*/, 7];
@@ -1487,22 +1501,21 @@ var SentryReplay = /** @class */ (function () {
1487
1501
  * Send replay attachment using `fetch()`
1488
1502
  */
1489
1503
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1490
- var _b, _c;
1491
- var endpoint = _a.endpoint, events = _a.events;
1504
+ var endpoint = _a.endpoint, events = _a.events, event_id = _a.replayId, segment_id = _a.segmentId;
1492
1505
  return __awaiter(this, void 0, void 0, function () {
1493
- var payloadWithSequence, envelope, response, _d, _e;
1494
- var _f;
1495
- return __generator(this, function (_g) {
1496
- switch (_g.label) {
1506
+ var payloadWithSequence, envelope, response, _b, _c;
1507
+ var _d;
1508
+ return __generator(this, function (_e) {
1509
+ switch (_e.label) {
1497
1510
  case 0:
1498
1511
  payloadWithSequence = createPayload({
1499
1512
  events: events,
1500
1513
  headers: {
1501
- segment_id: (_b = this.session) === null || _b === void 0 ? void 0 : _b.segmentId,
1514
+ segment_id: segment_id,
1502
1515
  },
1503
1516
  });
1504
1517
  envelope = utils.createEnvelope({
1505
- event_id: (_c = this.session) === null || _c === void 0 ? void 0 : _c.id,
1518
+ event_id: event_id,
1506
1519
  sent_at: new Date().toISOString(),
1507
1520
  sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1508
1521
  }, [
@@ -1523,17 +1536,17 @@ var SentryReplay = /** @class */ (function () {
1523
1536
  body: utils.serializeEnvelope(envelope),
1524
1537
  })];
1525
1538
  case 1:
1526
- response = _g.sent();
1539
+ response = _e.sent();
1527
1540
  if (!(response.status !== 200)) return [3 /*break*/, 3];
1528
- _d = core.setContext;
1529
- _e = ['Send Replay Response'];
1530
- _f = {
1541
+ _b = core.setContext;
1542
+ _c = ['Send Replay Response'];
1543
+ _d = {
1531
1544
  status: response.status
1532
1545
  };
1533
1546
  return [4 /*yield*/, response.text()];
1534
1547
  case 2:
1535
- _d.apply(void 0, _e.concat([(_f.body = _g.sent(),
1536
- _f)]));
1548
+ _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1549
+ _d)]));
1537
1550
  throw new Error(UNABLE_TO_SEND_REPLAY);
1538
1551
  case 3: return [2 /*return*/];
1539
1552
  }
@@ -1547,7 +1560,7 @@ var SentryReplay = /** @class */ (function () {
1547
1560
  /**
1548
1561
  * Finalize and send the current replay event to Sentry
1549
1562
  */
1550
- SentryReplay.prototype.sendReplay = function (eventId, events) {
1563
+ SentryReplay.prototype.sendReplay = function (replayId, events, segmentId) {
1551
1564
  return __awaiter(this, void 0, void 0, function () {
1552
1565
  var client, endpoint, ex_1;
1553
1566
  var _this = this;
@@ -1566,6 +1579,8 @@ var SentryReplay = /** @class */ (function () {
1566
1579
  return [4 /*yield*/, this.sendReplayRequest({
1567
1580
  endpoint: endpoint,
1568
1581
  events: events,
1582
+ replayId: replayId,
1583
+ segmentId: segmentId,
1569
1584
  })];
1570
1585
  case 2:
1571
1586
  _b.sent();
@@ -1584,29 +1599,30 @@ var SentryReplay = /** @class */ (function () {
1584
1599
  // failed, we'll can retry with the same events payload
1585
1600
  if (this.retryCount >= MAX_RETRY_COUNT) {
1586
1601
  this.resetRetries();
1587
- return [2 /*return*/, false];
1602
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1588
1603
  }
1589
1604
  this.retryCount = this.retryCount + 1;
1590
- // will retry in intervals of 5, 10, 15, 20, 25 seconds
1605
+ // will retry in intervals of 5, 10, 30
1591
1606
  this.retryInterval = this.retryCount * this.retryInterval;
1592
1607
  _b.label = 4;
1593
1608
  case 4:
1594
1609
  _b.trys.push([4, 6, , 7]);
1595
1610
  return [4 /*yield*/, new Promise(function (resolve, reject) {
1596
1611
  setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1597
- var result;
1598
- return __generator(this, function (_a) {
1599
- switch (_a.label) {
1600
- case 0: return [4 /*yield*/, this.sendReplay(eventId, events)];
1612
+ return __generator(this, function (_b) {
1613
+ switch (_b.label) {
1614
+ case 0:
1615
+ _b.trys.push([0, 2, , 3]);
1616
+ return [4 /*yield*/, this.sendReplay(replayId, events, segmentId)];
1601
1617
  case 1:
1602
- result = _a.sent();
1603
- if (result) {
1604
- resolve(true);
1605
- }
1606
- else {
1607
- reject(new Error('Could not send replay'));
1608
- }
1609
- return [2 /*return*/];
1618
+ _b.sent();
1619
+ resolve(true);
1620
+ return [3 /*break*/, 3];
1621
+ case 2:
1622
+ _b.sent();
1623
+ reject(new Error(UNABLE_TO_SEND_REPLAY));
1624
+ return [3 /*break*/, 3];
1625
+ case 3: return [2 /*return*/];
1610
1626
  }
1611
1627
  });
1612
1628
  }); }, _this.retryInterval);
@@ -1616,7 +1632,7 @@ var SentryReplay = /** @class */ (function () {
1616
1632
  return [2 /*return*/, true];
1617
1633
  case 6:
1618
1634
  _b.sent();
1619
- return [2 /*return*/, false];
1635
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1620
1636
  case 7: return [3 /*break*/, 8];
1621
1637
  case 8: return [2 /*return*/];
1622
1638
  }