@sentry/replay 0.6.3 → 0.6.4

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.
@@ -1,10 +1,31 @@
1
1
  /// <reference types="jest" />
2
2
  import { Session } from './src/session/Session';
3
+ declare type SentReplayExpected = {
4
+ envelopeHeader?: {
5
+ event_id: string;
6
+ sent_at: string;
7
+ sdk: {
8
+ name: string;
9
+ version?: string;
10
+ };
11
+ };
12
+ replayEventHeader?: {
13
+ type: 'replay_event';
14
+ };
15
+ replayEventPayload?: Record<string, any>;
16
+ recordingHeader?: {
17
+ type: 'replay_recording';
18
+ length: number;
19
+ };
20
+ recordingPayloadHeader?: Record<string, any>;
21
+ events?: string | Uint8Array;
22
+ };
3
23
  declare global {
4
24
  namespace jest {
5
25
  interface Matchers<R> {
6
- toHaveSentReplay(expected?: string | Uint8Array): CustomMatcherResult;
26
+ toHaveSentReplay(expected?: SentReplayExpected): CustomMatcherResult;
7
27
  toHaveSameSession(expected: undefined | Session): CustomMatcherResult;
8
28
  }
9
29
  }
10
30
  }
31
+ export {};
@@ -1,9 +1,8 @@
1
1
  import { Breadcrumb, Event, Integration } from '@sentry/types';
2
- import { CaptureReplayEventParams } from './api/captureReplayEvent';
3
2
  import { Session } from './session/Session';
4
3
  import { ReplayPerformanceEntry } from './createPerformanceEntry';
5
4
  import { IEventBuffer } from './eventBuffer';
6
- import type { AllPerformanceEntry, InstrumentationTypeBreadcrumb, InstrumentationTypeSpan, RecordedEvents, RecordingEvent, RecordingOptions, ReplayConfiguration, ReplayPluginOptions, ReplayRequest } from './types';
5
+ import type { AllPerformanceEntry, InitialState, InstrumentationTypeBreadcrumb, InstrumentationTypeSpan, RecordedEvents, RecordingEvent, RecordingOptions, ReplayConfiguration, ReplayPluginOptions, SendReplayRequest } from './types';
7
6
  /**
8
7
  * Returns true to return control to calling function, otherwise continue with normal batching
9
8
  */
@@ -208,9 +207,12 @@ export declare class Replay implements Integration {
208
207
  /**
209
208
  * Return and clear context
210
209
  */
211
- popEventContext({ timestamp, }: {
212
- timestamp: number;
213
- }): Omit<CaptureReplayEventParams, 'includeReplayStartTimestamp' | 'segmentId' | 'replayId'>;
210
+ popEventContext(): {
211
+ initialState: InitialState;
212
+ errorIds: string[];
213
+ traceIds: string[];
214
+ urls: string[];
215
+ };
214
216
  /**
215
217
  * Flushes replay event buffer to Sentry.
216
218
  *
@@ -228,11 +230,16 @@ export declare class Replay implements Integration {
228
230
  /**
229
231
  * Send replay attachment using `fetch()`
230
232
  */
231
- sendReplayRequest({ endpoint, events, replayId: event_id, segmentId: segment_id, }: ReplayRequest): Promise<void>;
233
+ sendReplayRequest({ endpoint, events, replayId: event_id, segmentId: segment_id, includeReplayStartTimestamp, }: SendReplayRequest): Promise<void>;
232
234
  resetRetries(): void;
233
235
  /**
234
236
  * Finalize and send the current replay event to Sentry
235
237
  */
236
- sendReplay(replayId: string, events: RecordedEvents, segmentId: number): Promise<unknown>;
238
+ sendReplay({ replayId, events, segmentId, includeReplayStartTimestamp, }: {
239
+ replayId: string;
240
+ events: RecordedEvents;
241
+ segmentId: number;
242
+ includeReplayStartTimestamp: boolean;
243
+ }): Promise<unknown>;
237
244
  }
238
245
  export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -3,11 +3,12 @@ export declare type RecordingEvent = eventWithTime;
3
3
  export declare type RecordingOptions = recordOptions<eventWithTime>;
4
4
  export declare type RecordedEvents = Uint8Array | string;
5
5
  export declare type AllPerformanceEntry = PerformancePaintTiming | PerformanceResourceTiming | PerformanceNavigationTiming;
6
- export interface ReplayRequest {
6
+ export interface SendReplayRequest {
7
7
  endpoint: string;
8
8
  events: RecordedEvents;
9
9
  replayId: string;
10
10
  segmentId: number;
11
+ includeReplayStartTimestamp: boolean;
11
12
  }
12
13
  export declare type InstrumentationTypeBreadcrumb = 'dom' | 'scope';
13
14
  export declare type InstrumentationTypeSpan = 'fetch' | 'xhr' | 'history';
@@ -1,4 +1,3 @@
1
- /// <reference types="jest" />
2
1
  import { RecordingEvent } from '../../src/types';
3
2
  declare type RecordAdditionalProperties = {
4
3
  takeFullSnapshot: jest.Mock;
@@ -10,6 +9,6 @@ declare type RecordAdditionalProperties = {
10
9
  export declare type RecordMock = jest.MockedFunction<typeof rrweb.record> & RecordAdditionalProperties;
11
10
  import * as rrweb from 'rrweb';
12
11
  export declare function mockRrweb(): {
13
- record: RecordMock;
12
+ record: any;
14
13
  };
15
14
  export {};
@@ -1,11 +1,10 @@
1
1
  import { BrowserOptions } from '@sentry/browser';
2
- import { Replay } from '../../src';
3
2
  import { ReplayConfiguration } from '../../src/types';
4
3
  interface MockSdkParams {
5
4
  replayOptions?: ReplayConfiguration;
6
5
  sentryOptions?: BrowserOptions;
7
6
  }
8
- export declare function mockSdk({ replayOptions, sentryOptions, }?: MockSdkParams): {
9
- replay: Replay;
10
- };
7
+ export declare function mockSdk({ replayOptions, sentryOptions, }?: MockSdkParams): Promise<{
8
+ replay: import("../../src").Replay;
9
+ }>;
11
10
  export {};
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { addBreadcrumb, withScope, captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
1
+ import { getCurrentHub, addBreadcrumb, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
2
  import { htmlTreeAsString, logger as logger$1, uuid4, browserPerformanceTimeOrigin, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
3
  import debounce from 'lodash.debounce';
4
4
  import { record, EventType } from 'rrweb';
@@ -89,49 +89,6 @@ function __spreadArray(to, from, pack) {
89
89
  return to.concat(ar || Array.prototype.slice.call(from));
90
90
  }
91
91
 
92
- var REPLAY_SESSION_KEY = 'sentryReplaySession';
93
- var REPLAY_EVENT_NAME = 'replay_event';
94
- // The idle limit for a session
95
- var SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
96
- // Grace period to keep a session when a user changes tabs or hides window
97
- var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
98
-
99
- /**
100
- * Returns true if we are currently recording an internal to Sentry replay
101
- * (e.g. on https://sentry.io )
102
- */
103
- function isInternal() {
104
- return ['sentry.io', 'dev.getsentry.net'].includes(window.location.host);
105
- }
106
-
107
- /**
108
- * Wrapper for core SDK's `addBreadcrumb` only when used on `sentry.io`
109
- */
110
- function addInternalBreadcrumb(arg) {
111
- if (!isInternal()) {
112
- return;
113
- }
114
- var category = arg.category, level = arg.level, message = arg.message, rest = __rest(arg, ["category", "level", "message"]);
115
- addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: "[debug]: ".concat(message) }, rest));
116
- }
117
-
118
- function captureReplayEvent(_a) {
119
- 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;
120
- if (segment_id !== 0 && includeReplayStartTimestamp) {
121
- addInternalBreadcrumb({
122
- message: "Including replay_start_timestamp on non-initial segment (id: ".concat(segment_id, ")"),
123
- });
124
- }
125
- withScope(function (scope) {
126
- scope.setTag('replay_sdk_version', "0.6.3");
127
- captureEvent(__assign(__assign({
128
- // @ts-expect-error replay_event is a new event type
129
- type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp
130
- ? { replay_start_timestamp: initialState.timestamp / 1000 }
131
- : {})), { timestamp: timestamp / 1000, error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: replay_id, segment_id: segment_id }), { event_id: replay_id });
132
- });
133
- }
134
-
135
92
  function createBreadcrumb(breadcrumb) {
136
93
  return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
137
94
  }
@@ -185,6 +142,14 @@ function getBreadcrumbHandler(type) {
185
142
  return handleDom;
186
143
  }
187
144
 
145
+ /**
146
+ * Returns true if we are currently recording an internal to Sentry replay
147
+ * (e.g. on https://sentry.io )
148
+ */
149
+ function isInternal() {
150
+ return ['sentry.io', 'dev.getsentry.net'].includes(window.location.host);
151
+ }
152
+
188
153
  /**
189
154
  * Checks is `targetHost` is a Sentry ingestion host
190
155
  */
@@ -277,6 +242,13 @@ function getSpanHandler(type) {
277
242
  return handleHistory;
278
243
  }
279
244
 
245
+ var REPLAY_SESSION_KEY = 'sentryReplaySession';
246
+ var REPLAY_EVENT_NAME = 'replay_event';
247
+ // The idle limit for a session
248
+ var SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
249
+ // Grace period to keep a session when a user changes tabs or hides window
250
+ var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
251
+
280
252
  /**
281
253
  * Deletes a session from storage
282
254
  */
@@ -499,6 +471,17 @@ function getSession(_a) {
499
471
  return { type: 'new', session: newSession };
500
472
  }
501
473
 
474
+ /**
475
+ * Wrapper for core SDK's `addBreadcrumb` only when used on `sentry.io`
476
+ */
477
+ function addInternalBreadcrumb(arg) {
478
+ if (!isInternal()) {
479
+ return;
480
+ }
481
+ var category = arg.category, level = arg.level, message = arg.message, rest = __rest(arg, ["category", "level", "message"]);
482
+ addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: "[debug]: ".concat(message) }, rest));
483
+ }
484
+
502
485
  /**
503
486
  * Captures exceptions to Sentry only when it occurs on sentry.io
504
487
  */
@@ -903,6 +886,7 @@ var BASE_RETRY_INTERVAL = 5000;
903
886
  var MAX_RETRY_COUNT = 3;
904
887
  var UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';
905
888
  var MEDIA_SELECTORS = 'img,image,svg,path,rect,area,video,object,picture,embed,map,audio';
889
+ var _initialized = false;
906
890
  var Replay = /** @class */ (function () {
907
891
  function Replay(_a) {
908
892
  if (_a === void 0) { _a = {}; }
@@ -1222,6 +1206,12 @@ var Replay = /** @class */ (function () {
1222
1206
  this.debouncedFlush = debounce(function () { return _this.flush(); }, this.options.flushMinDelay, {
1223
1207
  maxWait: this.options.flushMaxDelay,
1224
1208
  });
1209
+ if (_initialized) {
1210
+ var error = new Error('Multiple Sentry Session Replay instances are not supported');
1211
+ captureInternalException(error);
1212
+ throw error;
1213
+ }
1214
+ _initialized = true;
1225
1215
  }
1226
1216
  /**
1227
1217
  * Because we create a transaction in `setupOnce`, we can potentially create a
@@ -1246,7 +1236,8 @@ var Replay = /** @class */ (function () {
1246
1236
  this.loadSession({ expiry: SESSION_IDLE_DURATION });
1247
1237
  // If there is no session, then something bad has happened - can't continue
1248
1238
  if (!this.session) {
1249
- throw new Error('Invalid session');
1239
+ captureInternalException(new Error('Invalid session'));
1240
+ return;
1250
1241
  }
1251
1242
  if (!this.session.sampled) {
1252
1243
  // If session was not sampled, then we do not initialize the integration at all.
@@ -1597,8 +1588,7 @@ var Replay = /** @class */ (function () {
1597
1588
  /**
1598
1589
  * Return and clear context
1599
1590
  */
1600
- Replay.prototype.popEventContext = function (_a) {
1601
- var timestamp = _a.timestamp;
1591
+ Replay.prototype.popEventContext = function () {
1602
1592
  var initialState = this.initialState;
1603
1593
  if (this.initialState &&
1604
1594
  this.context.earliestEvent &&
@@ -1607,7 +1597,6 @@ var Replay = /** @class */ (function () {
1607
1597
  }
1608
1598
  var context = {
1609
1599
  initialState: initialState,
1610
- timestamp: timestamp,
1611
1600
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
1612
1601
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
1613
1602
  urls: this.context.urls,
@@ -1658,11 +1647,14 @@ var Replay = /** @class */ (function () {
1658
1647
  return [4 /*yield*/, this.eventBuffer.finish()];
1659
1648
  case 4:
1660
1649
  recordingData = _d.sent();
1661
- return [4 /*yield*/, this.sendReplay(replayId, recordingData, segmentId)];
1650
+ return [4 /*yield*/, this.sendReplay({
1651
+ replayId: replayId,
1652
+ events: recordingData,
1653
+ segmentId: segmentId,
1654
+ includeReplayStartTimestamp: newSessionCreated,
1655
+ })];
1662
1656
  case 5:
1663
1657
  _d.sent();
1664
- // The below will only happen after successfully sending replay //
1665
- captureReplayEvent(__assign(__assign({}, this.popEventContext({ timestamp: new Date().getTime() })), { replayId: replayId, segmentId: segmentId, includeReplayStartTimestamp: newSessionCreated }));
1666
1658
  this.newSessionCreated = false;
1667
1659
  return [3 /*break*/, 7];
1668
1660
  case 6:
@@ -1679,12 +1671,13 @@ var Replay = /** @class */ (function () {
1679
1671
  * Send replay attachment using `fetch()`
1680
1672
  */
1681
1673
  Replay.prototype.sendReplayRequest = function (_a) {
1682
- var endpoint = _a.endpoint, events = _a.events, event_id = _a.replayId, segment_id = _a.segmentId;
1674
+ var endpoint = _a.endpoint, events = _a.events, event_id = _a.replayId, segment_id = _a.segmentId, includeReplayStartTimestamp = _a.includeReplayStartTimestamp;
1683
1675
  return __awaiter(this, void 0, void 0, function () {
1684
- var payloadWithSequence, envelope, response, _b, _c;
1685
- var _d;
1686
- return __generator(this, function (_e) {
1687
- switch (_e.label) {
1676
+ var payloadWithSequence, _b, urls, errorIds, traceIds, initialState, timestamp, sdkInfo, replayEvent, envelope, response, _c, _d;
1677
+ var _e;
1678
+ var _this = this;
1679
+ return __generator(this, function (_f) {
1680
+ switch (_f.label) {
1688
1681
  case 0:
1689
1682
  payloadWithSequence = createPayload({
1690
1683
  events: events,
@@ -1692,14 +1685,43 @@ var Replay = /** @class */ (function () {
1692
1685
  segment_id: segment_id,
1693
1686
  },
1694
1687
  });
1688
+ _b = this.popEventContext(), urls = _b.urls, errorIds = _b.errorIds, traceIds = _b.traceIds, initialState = _b.initialState;
1689
+ timestamp = new Date().getTime();
1690
+ sdkInfo = {
1691
+ name: 'sentry.javascript.integration.replay',
1692
+ version: "0.6.4",
1693
+ };
1694
+ return [4 /*yield*/, new Promise(function (resolve) {
1695
+ var _a;
1696
+ (_a = getCurrentHub()) === null || _a === void 0 ? void 0 : _a._withClient(function (client, scope) { return __awaiter(_this, void 0, void 0, function () {
1697
+ var preparedEvent, session;
1698
+ return __generator(this, function (_a) {
1699
+ switch (_a.label) {
1700
+ case 0: return [4 /*yield*/, client._prepareEvent(__assign(__assign({ type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp
1701
+ ? { replay_start_timestamp: initialState.timestamp / 1000 }
1702
+ : {})), { timestamp: timestamp / 1000, error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: event_id, segment_id: segment_id }), { event_id: event_id }, scope)];
1703
+ case 1:
1704
+ preparedEvent = _a.sent();
1705
+ session = scope && scope.getSession();
1706
+ if (session) {
1707
+ client._updateSessionFromEvent(session, preparedEvent);
1708
+ }
1709
+ preparedEvent.sdk = __assign(__assign({}, preparedEvent.sdk), sdkInfo);
1710
+ resolve(preparedEvent);
1711
+ return [2 /*return*/];
1712
+ }
1713
+ });
1714
+ }); });
1715
+ })];
1716
+ case 1:
1717
+ replayEvent = _f.sent();
1695
1718
  envelope = createEnvelope({
1696
1719
  event_id: event_id,
1697
1720
  sent_at: new Date().toISOString(),
1698
- sdk: {
1699
- name: 'sentry.javascript.integration.replay',
1700
- version: "0.6.3",
1701
- },
1721
+ sdk: sdkInfo,
1702
1722
  }, [
1723
+ // @ts-expect-error New types
1724
+ [{ type: 'replay_event' }, replayEvent],
1703
1725
  [
1704
1726
  {
1705
1727
  // @ts-expect-error setting envelope
@@ -1716,20 +1738,20 @@ var Replay = /** @class */ (function () {
1716
1738
  method: 'POST',
1717
1739
  body: serializeEnvelope(envelope),
1718
1740
  })];
1719
- case 1:
1720
- response = _e.sent();
1721
- if (!(response.status !== 200)) return [3 /*break*/, 3];
1722
- _b = setContext;
1723
- _c = ['Send Replay Response'];
1724
- _d = {
1741
+ case 2:
1742
+ response = _f.sent();
1743
+ if (!(response.status !== 200)) return [3 /*break*/, 4];
1744
+ _c = setContext;
1745
+ _d = ['Send Replay Response'];
1746
+ _e = {
1725
1747
  status: response.status
1726
1748
  };
1727
1749
  return [4 /*yield*/, response.text()];
1728
- case 2:
1729
- _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1730
- _d)]));
1750
+ case 3:
1751
+ _c.apply(void 0, _d.concat([(_e.body = _f.sent(),
1752
+ _e)]));
1731
1753
  throw new Error(UNABLE_TO_SEND_REPLAY);
1732
- case 3: return [2 /*return*/];
1754
+ case 4: return [2 /*return*/];
1733
1755
  }
1734
1756
  });
1735
1757
  });
@@ -1741,12 +1763,13 @@ var Replay = /** @class */ (function () {
1741
1763
  /**
1742
1764
  * Finalize and send the current replay event to Sentry
1743
1765
  */
1744
- Replay.prototype.sendReplay = function (replayId, events, segmentId) {
1766
+ Replay.prototype.sendReplay = function (_a) {
1767
+ var replayId = _a.replayId, events = _a.events, segmentId = _a.segmentId, includeReplayStartTimestamp = _a.includeReplayStartTimestamp;
1745
1768
  return __awaiter(this, void 0, void 0, function () {
1746
1769
  var client, endpoint, ex_1;
1747
1770
  var _this = this;
1748
- return __generator(this, function (_a) {
1749
- switch (_a.label) {
1771
+ return __generator(this, function (_b) {
1772
+ switch (_b.label) {
1750
1773
  case 0:
1751
1774
  // short circuit if there's no events to upload
1752
1775
  if (!events.length) {
@@ -1754,21 +1777,22 @@ var Replay = /** @class */ (function () {
1754
1777
  }
1755
1778
  client = getCurrentHub().getClient();
1756
1779
  endpoint = getEnvelopeEndpointWithUrlEncodedAuth(client.getDsn());
1757
- _a.label = 1;
1780
+ _b.label = 1;
1758
1781
  case 1:
1759
- _a.trys.push([1, 3, , 5]);
1782
+ _b.trys.push([1, 3, , 5]);
1760
1783
  return [4 /*yield*/, this.sendReplayRequest({
1761
1784
  endpoint: endpoint,
1762
1785
  events: events,
1763
1786
  replayId: replayId,
1764
1787
  segmentId: segmentId,
1788
+ includeReplayStartTimestamp: includeReplayStartTimestamp,
1765
1789
  })];
1766
1790
  case 2:
1767
- _a.sent();
1791
+ _b.sent();
1768
1792
  this.resetRetries();
1769
1793
  return [2 /*return*/, true];
1770
1794
  case 3:
1771
- ex_1 = _a.sent();
1795
+ ex_1 = _b.sent();
1772
1796
  console.error(ex_1);
1773
1797
  // Capture error for every failed replay
1774
1798
  // TODO: Remove this before GA as this will create an error on customer's project
@@ -1791,7 +1815,12 @@ var Replay = /** @class */ (function () {
1791
1815
  switch (_a.label) {
1792
1816
  case 0:
1793
1817
  _a.trys.push([0, 2, , 3]);
1794
- return [4 /*yield*/, this.sendReplay(replayId, events, segmentId)];
1818
+ return [4 /*yield*/, this.sendReplay({
1819
+ replayId: replayId,
1820
+ events: events,
1821
+ segmentId: segmentId,
1822
+ includeReplayStartTimestamp: includeReplayStartTimestamp,
1823
+ })];
1795
1824
  case 1:
1796
1825
  _a.sent();
1797
1826
  resolve(true);
@@ -1805,7 +1834,7 @@ var Replay = /** @class */ (function () {
1805
1834
  });
1806
1835
  }); }, _this.retryInterval);
1807
1836
  })];
1808
- case 4: return [2 /*return*/, _a.sent()];
1837
+ case 4: return [2 /*return*/, _b.sent()];
1809
1838
  case 5: return [2 /*return*/];
1810
1839
  }
1811
1840
  });