@sentry/replay 0.4.8-1 → 0.4.8

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 (128) hide show
  1. package/README.md +15 -15
  2. package/dist/{jest.config.d.ts → config/dist/jest.config.d.ts} +0 -0
  3. package/dist/{jest.setup.d.ts → config/dist/jest.setup.d.ts} +0 -0
  4. package/dist/config/dist/src/api/captureReplay.d.ts +10 -0
  5. package/dist/config/dist/src/api/captureReplayUpdate.d.ts +12 -0
  6. package/dist/config/dist/src/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  7. package/dist/config/dist/src/coreHandlers/getSpanHandler.d.ts +5 -0
  8. package/dist/{src → config/dist/src}/coreHandlers/handleDom.d.ts +0 -0
  9. package/dist/config/dist/src/coreHandlers/handleFetch.d.ts +19 -0
  10. package/dist/{src → config/dist/src}/coreHandlers/handleFetch.test.d.ts +0 -0
  11. package/dist/config/dist/src/coreHandlers/handleHistory.d.ts +7 -0
  12. package/dist/{src → config/dist/src}/coreHandlers/handleScope-unit.test.d.ts +0 -0
  13. package/dist/{src → config/dist/src}/coreHandlers/handleScope.d.ts +0 -0
  14. package/dist/{src → config/dist/src}/coreHandlers/handleScope.test.d.ts +0 -0
  15. package/dist/config/dist/src/coreHandlers/handleXhr.d.ts +21 -0
  16. package/dist/{dist → config/dist/src}/coreHandlers/index.d.ts +0 -0
  17. package/dist/{src → config/dist/src}/createPerformanceEntry.d.ts +0 -0
  18. package/dist/{src → config/dist/src}/createPerformanceEntry.test.d.ts +0 -0
  19. package/dist/{src → config/dist/src}/eventBuffer.d.ts +9 -2
  20. package/dist/config/dist/src/eventBuffer.test.d.ts +1 -0
  21. package/dist/{src → config/dist/src}/flags.d.ts +0 -0
  22. package/dist/{src → config/dist/src}/index-captureOnlyOnError.test.d.ts +0 -0
  23. package/dist/{src → config/dist/src}/index-noSticky.test.d.ts +0 -0
  24. package/dist/{src → config/dist/src}/index-sampling.test.d.ts +0 -0
  25. package/dist/{src → config/dist/src}/index.d.ts +18 -11
  26. package/dist/{src → config/dist/src}/index.test.d.ts +0 -0
  27. package/dist/{src → config/dist/src}/session/Session.d.ts +0 -0
  28. package/dist/{src → config/dist/src}/session/Session.test.d.ts +0 -0
  29. package/dist/{src → config/dist/src}/session/constants.d.ts +0 -0
  30. package/dist/{src → config/dist/src}/session/createSession.d.ts +0 -0
  31. package/dist/{src → config/dist/src}/session/createSession.test.d.ts +0 -0
  32. package/dist/{src → config/dist/src}/session/fetchSession.d.ts +0 -0
  33. package/dist/{src → config/dist/src}/session/fetchSession.test.d.ts +0 -0
  34. package/dist/{src → config/dist/src}/session/getSession.d.ts +0 -0
  35. package/dist/{src → config/dist/src}/session/getSession.test.d.ts +0 -0
  36. package/dist/{src → config/dist/src}/session/index.d.ts +0 -0
  37. package/dist/{src → config/dist/src}/session/saveSession.d.ts +0 -0
  38. package/dist/{src → config/dist/src}/session/saveSession.test.d.ts +0 -0
  39. package/dist/{src → config/dist/src}/types.d.ts +22 -8
  40. package/dist/{src → config/dist/src}/util/createBreadcrumb.d.ts +0 -0
  41. package/dist/config/dist/src/util/createPayload.d.ts +5 -0
  42. package/dist/{src → config/dist/src}/util/isExpired.d.ts +0 -0
  43. package/dist/{src → config/dist/src}/util/isExpired.test.d.ts +0 -0
  44. package/dist/{src → config/dist/src}/util/isIngestHost.d.ts +0 -0
  45. package/dist/{src → config/dist/src}/util/isSampled.d.ts +0 -0
  46. package/dist/{src → config/dist/src}/util/isSampled.test.d.ts +0 -0
  47. package/dist/{src → config/dist/src}/util/isSessionExpired.d.ts +0 -0
  48. package/dist/{src → config/dist/src}/util/isSessionExpired.test.d.ts +0 -0
  49. package/dist/{src → config/dist/src}/util/logger.d.ts +0 -0
  50. package/dist/{src → config/dist/src}/util/supportsSendBeacon.d.ts +0 -0
  51. package/dist/{test → config/dist/test}/index.d.ts +0 -0
  52. package/dist/{test → config/dist/test}/mocks/mockRrweb.d.ts +0 -0
  53. package/dist/{test → config/dist/test}/mocks/mockSdk.d.ts +0 -0
  54. package/dist/dist/api/captureReplay.d.ts +5 -3
  55. package/dist/dist/api/captureReplayUpdate.d.ts +5 -3
  56. package/dist/dist/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  57. package/dist/dist/coreHandlers/getSpanHandler.d.ts +5 -0
  58. package/dist/dist/coreHandlers/handleFetch.d.ts +19 -2
  59. package/dist/dist/coreHandlers/handleHistory.d.ts +7 -0
  60. package/dist/dist/coreHandlers/handleXhr.d.ts +21 -2
  61. package/dist/dist/index.d.ts +18 -7
  62. package/dist/dist/types.d.ts +20 -8
  63. package/dist/index.es.js +223 -126
  64. package/dist/index.js +222 -125
  65. package/dist/index.js.map +1 -1
  66. package/package.json +1 -1
  67. package/dist/esm/index.js +0 -1454
  68. package/dist/esm/worker-aa3eb59a.js +0 -4
  69. package/dist/src/api/captureReplay.d.ts +0 -3
  70. package/dist/src/api/captureReplayUpdate.d.ts +0 -2
  71. package/dist/src/coreHandlers/handleFetch.d.ts +0 -2
  72. package/dist/src/coreHandlers/handleXhr.d.ts +0 -2
  73. package/dist/src/coreHandlers/index.d.ts +0 -4
  74. package/dist/src/eventBuffer.test.d.ts +0 -1
  75. package/dist/types/jest.config.d.ts +0 -3
  76. package/dist/types/jest.setup.d.ts +0 -10
  77. package/dist/types/src/api/captureReplay.d.ts +0 -3
  78. package/dist/types/src/api/captureReplayUpdate.d.ts +0 -2
  79. package/dist/types/src/coreHandlers/handleDom.d.ts +0 -1
  80. package/dist/types/src/coreHandlers/handleFetch.d.ts +0 -2
  81. package/dist/types/src/coreHandlers/handleFetch.test.d.ts +0 -1
  82. package/dist/types/src/coreHandlers/handleScope-unit.test.d.ts +0 -1
  83. package/dist/types/src/coreHandlers/handleScope.d.ts +0 -2
  84. package/dist/types/src/coreHandlers/handleScope.test.d.ts +0 -1
  85. package/dist/types/src/coreHandlers/handleXhr.d.ts +0 -2
  86. package/dist/types/src/coreHandlers/index.d.ts +0 -4
  87. package/dist/types/src/createPerformanceEntry.d.ts +0 -42
  88. package/dist/types/src/createPerformanceEntry.test.d.ts +0 -1
  89. package/dist/types/src/eventBuffer.d.ts +0 -31
  90. package/dist/types/src/eventBuffer.test.d.ts +0 -1
  91. package/dist/types/src/flags.d.ts +0 -2
  92. package/dist/types/src/index-captureOnlyOnError.test.d.ts +0 -1
  93. package/dist/types/src/index-noSticky.test.d.ts +0 -1
  94. package/dist/types/src/index-sampling.test.d.ts +0 -1
  95. package/dist/types/src/index.d.ts +0 -209
  96. package/dist/types/src/index.test.d.ts +0 -1
  97. package/dist/types/src/session/Session.d.ts +0 -63
  98. package/dist/types/src/session/Session.test.d.ts +0 -1
  99. package/dist/types/src/session/constants.d.ts +0 -5
  100. package/dist/types/src/session/createSession.d.ts +0 -19
  101. package/dist/types/src/session/createSession.test.d.ts +0 -1
  102. package/dist/types/src/session/fetchSession.d.ts +0 -5
  103. package/dist/types/src/session/fetchSession.test.d.ts +0 -1
  104. package/dist/types/src/session/getSession.d.ts +0 -28
  105. package/dist/types/src/session/getSession.test.d.ts +0 -1
  106. package/dist/types/src/session/index.d.ts +0 -1
  107. package/dist/types/src/session/saveSession.d.ts +0 -2
  108. package/dist/types/src/session/saveSession.test.d.ts +0 -1
  109. package/dist/types/src/session/types.d.ts +0 -0
  110. package/dist/types/src/types.d.ts +0 -76
  111. package/dist/types/src/util/createBreadcrumb.d.ts +0 -4
  112. package/dist/types/src/util/isExpired.d.ts +0 -5
  113. package/dist/types/src/util/isExpired.test.d.ts +0 -1
  114. package/dist/types/src/util/isIngestHost.d.ts +0 -4
  115. package/dist/types/src/util/isSampled.d.ts +0 -7
  116. package/dist/types/src/util/isSampled.test.d.ts +0 -1
  117. package/dist/types/src/util/isSessionExpired.d.ts +0 -5
  118. package/dist/types/src/util/isSessionExpired.test.d.ts +0 -1
  119. package/dist/types/src/util/logger.d.ts +0 -12
  120. package/dist/types/src/util/supportsSendBeacon.d.ts +0 -4
  121. package/dist/types/test/index.d.ts +0 -3
  122. package/dist/types/test/mocks/mockRrweb.d.ts +0 -15
  123. package/dist/types/test/mocks/mockSdk.d.ts +0 -11
  124. package/dist/types/worker/src/Compressor.d.ts +0 -15
  125. package/dist/types/worker/src/handleMessage.d.ts +0 -2
  126. package/dist/worker-aa3eb59a.js +0 -4
  127. package/dist/worker-f4750cfb.js +0 -7
  128. package/dist/worker-f4750cfb.js.map +0 -1
package/dist/esm/index.js DELETED
@@ -1,1454 +0,0 @@
1
- import { captureEvent, getCurrentHub, addGlobalEventProcessor } from '@sentry/core';
2
- import { uuid4, logger as logger$1, htmlTreeAsString, addInstrumentationHandler } from '@sentry/utils';
3
-
4
- /******************************************************************************
5
- Copyright (c) Microsoft Corporation.
6
-
7
- Permission to use, copy, modify, and/or distribute this software for any
8
- purpose with or without fee is hereby granted.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
- PERFORMANCE OF THIS SOFTWARE.
17
- ***************************************************************************** */
18
-
19
- var __assign = function() {
20
- __assign = Object.assign || function __assign(t) {
21
- for (var s, i = 1, n = arguments.length; i < n; i++) {
22
- s = arguments[i];
23
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
24
- }
25
- return t;
26
- };
27
- return __assign.apply(this, arguments);
28
- };
29
-
30
- function __rest(s, e) {
31
- var t = {};
32
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
33
- t[p] = s[p];
34
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
35
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
36
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
37
- t[p[i]] = s[p[i]];
38
- }
39
- return t;
40
- }
41
-
42
- function __awaiter(thisArg, _arguments, P, generator) {
43
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
44
- return new (P || (P = Promise))(function (resolve, reject) {
45
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
46
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
47
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
48
- step((generator = generator.apply(thisArg, _arguments || [])).next());
49
- });
50
- }
51
-
52
- function __generator(thisArg, body) {
53
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
54
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
55
- function verb(n) { return function (v) { return step([n, v]); }; }
56
- function step(op) {
57
- if (f) throw new TypeError("Generator is already executing.");
58
- while (_) try {
59
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
60
- if (y = 0, t) op = [op[0] & 2, t.value];
61
- switch (op[0]) {
62
- case 0: case 1: t = op; break;
63
- case 4: _.label++; return { value: op[1], done: false };
64
- case 5: _.label++; y = op[1]; op = [0]; continue;
65
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
66
- default:
67
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
68
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
69
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
70
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
71
- if (t[2]) _.ops.pop();
72
- _.trys.pop(); continue;
73
- }
74
- op = body.call(thisArg, _);
75
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
76
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
77
- }
78
- }
79
-
80
- function __spreadArray(to, from, pack) {
81
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
82
- if (ar || !(i in from)) {
83
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
84
- ar[i] = from[i];
85
- }
86
- }
87
- return to.concat(ar || Array.prototype.slice.call(from));
88
- }
89
-
90
- var REPLAY_SESSION_KEY = 'sentryReplaySession';
91
- var ROOT_REPLAY_NAME = 'sentry-replay';
92
- var REPLAY_EVENT_NAME = 'sentry-replay-event';
93
- // The idle limit for a session
94
- var SESSION_IDLE_DURATION = 900000; // 15 minutes
95
- // Grace period to keep a session when a user changes tabs or hides window
96
- var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
97
-
98
- function captureReplay(session, initialState) {
99
- captureEvent({
100
- message: ROOT_REPLAY_NAME,
101
- tags: { segmentId: session.segmentId, url: initialState.url },
102
- timestamp: initialState.timestamp,
103
- }, { event_id: session.id });
104
- }
105
-
106
- function captureReplayUpdate(session, timestamp) {
107
- captureEvent({
108
- timestamp: timestamp,
109
- message: "".concat(REPLAY_EVENT_NAME, "-").concat(uuid4().substring(16)),
110
- tags: {
111
- replayId: session.id,
112
- segmentId: session.segmentId++,
113
- },
114
- });
115
- }
116
-
117
- /**
118
- * Given an initial timestamp and an expiry duration, checks to see if current
119
- * time should be considered as expired.
120
- */
121
- function isExpired(initialTime, expiry, targetTime) {
122
- if (targetTime === void 0) { targetTime = +new Date(); }
123
- // Always expired if < 0
124
- if (expiry < 0) {
125
- return true;
126
- }
127
- // Never expires if == 0
128
- if (expiry === 0) {
129
- return false;
130
- }
131
- return initialTime + expiry <= targetTime;
132
- }
133
-
134
- /**
135
- * Checks to see if session is expired
136
- */
137
- function isSessionExpired(session, expiry, targetTime) {
138
- if (targetTime === void 0) { targetTime = +new Date(); }
139
- return isExpired(session.lastActivity, expiry, targetTime);
140
- }
141
-
142
- function wrapLogger(logFn) {
143
- return function wrappedLog() {
144
- {
145
- return;
146
- }
147
- };
148
- }
149
- var logger = __assign(__assign({}, logger$1), { error: wrapLogger(logger$1.error), warn: wrapLogger(logger$1.warn), log: wrapLogger(logger$1.log) });
150
-
151
- function saveSession(session) {
152
- var hasSessionStorage = 'sessionStorage' in window;
153
- if (!hasSessionStorage) {
154
- return;
155
- }
156
- try {
157
- window.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
158
- }
159
- catch (_a) {
160
- // this shouldn't happen
161
- }
162
- }
163
-
164
- /**
165
- * Given a sample rate, returns true if replay should be sampled.
166
- *
167
- * 1.0 = 100% sampling
168
- * 0.0 = 0% sampling
169
- */
170
- function isSampled(sampleRate) {
171
- // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
172
- return Math.random() < sampleRate;
173
- }
174
-
175
- var Session = /** @class */ (function () {
176
- function Session(session, _a) {
177
- if (session === void 0) { session = {}; }
178
- var _b = _a === void 0 ? {} : _a, _c = _b.stickySession, stickySession = _c === void 0 ? false : _c, _d = _b.samplingRate, samplingRate = _d === void 0 ? 1.0 : _d;
179
- var _e, _f, _g, _h;
180
- var now = new Date().getTime();
181
- this._id = session.id || uuid4();
182
- this._started = (_e = session.started) !== null && _e !== void 0 ? _e : now;
183
- this._lastActivity = (_f = session.lastActivity) !== null && _f !== void 0 ? _f : now;
184
- this._segmentId = (_g = session.segmentId) !== null && _g !== void 0 ? _g : 0;
185
- this._sampled = (_h = session.sampled) !== null && _h !== void 0 ? _h : isSampled(samplingRate);
186
- this.options = {
187
- stickySession: stickySession,
188
- };
189
- }
190
- Object.defineProperty(Session.prototype, "id", {
191
- get: function () {
192
- return this._id;
193
- },
194
- enumerable: false,
195
- configurable: true
196
- });
197
- Object.defineProperty(Session.prototype, "started", {
198
- get: function () {
199
- return this._started;
200
- },
201
- enumerable: false,
202
- configurable: true
203
- });
204
- Object.defineProperty(Session.prototype, "lastActivity", {
205
- get: function () {
206
- return this._lastActivity;
207
- },
208
- set: function (newDate) {
209
- this._lastActivity = newDate;
210
- if (this.options.stickySession) {
211
- saveSession(this);
212
- }
213
- },
214
- enumerable: false,
215
- configurable: true
216
- });
217
- Object.defineProperty(Session.prototype, "segmentId", {
218
- get: function () {
219
- return this._segmentId;
220
- },
221
- set: function (id) {
222
- this._segmentId = id;
223
- if (this.options.stickySession) {
224
- saveSession(this);
225
- }
226
- },
227
- enumerable: false,
228
- configurable: true
229
- });
230
- Object.defineProperty(Session.prototype, "previousSessionId", {
231
- get: function () {
232
- return this._previousSessionId;
233
- },
234
- set: function (id) {
235
- this._previousSessionId = id;
236
- },
237
- enumerable: false,
238
- configurable: true
239
- });
240
- Object.defineProperty(Session.prototype, "sampled", {
241
- get: function () {
242
- return this._sampled;
243
- },
244
- set: function (_isSampled) {
245
- throw new Error('Unable to change sampled value');
246
- },
247
- enumerable: false,
248
- configurable: true
249
- });
250
- Session.prototype.toJSON = function () {
251
- return {
252
- id: this.id,
253
- started: this.started,
254
- lastActivity: this.lastActivity,
255
- segmentId: this._segmentId,
256
- sampled: this._sampled,
257
- };
258
- };
259
- return Session;
260
- }());
261
-
262
- /**
263
- * Create a new session, which in its current implementation is a Sentry event
264
- * that all replays will be saved to as attachments. Currently, we only expect
265
- * one of these Sentry events per "replay session".
266
- */
267
- function createSession(_a) {
268
- var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b, _c = _a.samplingRate, samplingRate = _c === void 0 ? 1.0 : _c;
269
- var session = new Session(undefined, { stickySession: stickySession, samplingRate: samplingRate });
270
- logger.log("Creating new session: ".concat(session.id));
271
- if (stickySession) {
272
- saveSession(session);
273
- }
274
- return session;
275
- }
276
-
277
- /**
278
- * Fetches a session from storage
279
- */
280
- function fetchSession() {
281
- var hasSessionStorage = 'sessionStorage' in window;
282
- if (!hasSessionStorage) {
283
- return null;
284
- }
285
- try {
286
- return new Session(JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
287
- // We are assuming that if there is a saved item, then the session is sticky,
288
- // however this could break down if we used a different storage mechanism (e.g. localstorage)
289
- { stickySession: true });
290
- }
291
- catch (_a) {
292
- return null;
293
- }
294
- }
295
-
296
- /**
297
- * Get or create a session
298
- */
299
- function getSession(_a) {
300
- var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, samplingRate = _a.samplingRate;
301
- var session = stickySession ? fetchSession() : currentSession;
302
- if (session) {
303
- // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
304
- // TODO: We should probably set a max age on this as well
305
- var isExpired = isSessionExpired(session, expiry);
306
- if (!isExpired) {
307
- logger.log("Using existing session: ".concat(session.id));
308
- return { type: 'saved', session: session };
309
- }
310
- else {
311
- logger.log("Session has expired");
312
- }
313
- // Otherwise continue to create a new session
314
- }
315
- var newSession = createSession({ stickySession: stickySession, samplingRate: samplingRate });
316
- return { type: 'new', session: newSession };
317
- }
318
-
319
- function createBreadcrumb(breadcrumb) {
320
- return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
321
- }
322
-
323
- /**
324
- * Determine if there is browser support for `navigator.sendBeacon`
325
- */
326
- function supportsSendBeacon() {
327
- return 'navigator' in window && 'sendBeacon' in window.navigator;
328
- }
329
-
330
- function handleDom(handlerData) {
331
- return __awaiter(this, void 0, void 0, function () {
332
- var target, targetNode, record;
333
- return __generator(this, function (_a) {
334
- switch (_a.label) {
335
- case 0:
336
- // Accessing event.target can throw (see getsentry/raven-js#838, #768)
337
- try {
338
- targetNode =
339
- handlerData.event.target ||
340
- handlerData.event;
341
- target = htmlTreeAsString(targetNode);
342
- }
343
- catch (e) {
344
- target = '<unknown>';
345
- }
346
- if (target.length === 0) {
347
- return [2 /*return*/, null];
348
- }
349
- return [4 /*yield*/, import('rrweb')];
350
- case 1:
351
- record = (_a.sent()).record;
352
- return [2 /*return*/, createBreadcrumb({
353
- category: "ui.".concat(handlerData.name),
354
- message: target,
355
- data: __assign({}, (targetNode ? { nodeId: record.mirror.getId(targetNode) } : {})),
356
- })];
357
- }
358
- });
359
- });
360
- }
361
-
362
- function handleFetch(handlerData) {
363
- return __awaiter(this, void 0, void 0, function () {
364
- var _a, op, description;
365
- return __generator(this, function (_b) {
366
- if (!handlerData.endTimestamp) {
367
- return [2 /*return*/, null];
368
- }
369
- _a = handlerData.args, op = _a[0], description = _a[1];
370
- return [2 /*return*/, {
371
- description: description,
372
- op: op,
373
- startTimestamp: handlerData.startTimestamp / 1000,
374
- endTimestamp: handlerData.endTimestamp / 1000,
375
- data: {
376
- statusCode: handlerData.response.status,
377
- },
378
- }];
379
- });
380
- });
381
- }
382
-
383
- var _LAST_BREADCRUMB = null;
384
- function handleScope(scope) {
385
- var _a;
386
- return __awaiter(this, void 0, void 0, function () {
387
- var newBreadcrumb;
388
- return __generator(this, function (_b) {
389
- newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
390
- // Listener can be called when breadcrumbs have not changed, so we store the
391
- // reference to the last crumb and only return a crumb if it has changed
392
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
393
- return [2 /*return*/, null];
394
- }
395
- _LAST_BREADCRUMB = newBreadcrumb;
396
- if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
397
- ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
398
- return [2 /*return*/, null];
399
- }
400
- return [2 /*return*/, createBreadcrumb(newBreadcrumb)];
401
- });
402
- });
403
- }
404
-
405
- function handleXhr(handlerData) {
406
- return __awaiter(this, void 0, void 0, function () {
407
- var _a, op, description;
408
- return __generator(this, function (_b) {
409
- if (handlerData.startTimestamp) {
410
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
411
- }
412
- if (!handlerData.endTimestamp) {
413
- return [2 /*return*/, null];
414
- }
415
- _a = handlerData.args, op = _a[0], description = _a[1];
416
- return [2 /*return*/, {
417
- description: description,
418
- op: op,
419
- startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
420
- handlerData.endTimestamp / 1000.0,
421
- endTimestamp: handlerData.endTimestamp / 1000.0,
422
- data: {
423
- statusCode: handlerData.response.status,
424
- },
425
- }];
426
- });
427
- });
428
- }
429
-
430
- /**
431
- * Checks is `targetHost` is a Sentry ingestion host
432
- */
433
- function isIngestHost(targetHost) {
434
- var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
435
- return targetHost.startsWith("".concat(protocol, "://").concat(host));
436
- }
437
-
438
- var _a;
439
- // Map entryType -> function to normalize data for event
440
- var ENTRY_TYPES = (_a = {
441
- resource: createResourceEntry,
442
- paint: createPaintEntry,
443
- navigation: createNavigationEntry
444
- },
445
- _a['largest-contentful-paint'] = createLargestContentfulPaint,
446
- _a);
447
- function createPerformanceEntries(entries) {
448
- return __awaiter(this, void 0, void 0, function () {
449
- return __generator(this, function (_a) {
450
- switch (_a.label) {
451
- case 0: return [4 /*yield*/, Promise.all(entries.map(createPerformanceEntry).filter(Boolean))];
452
- case 1: return [2 /*return*/, _a.sent()];
453
- }
454
- });
455
- });
456
- }
457
- function createPerformanceEntry(entry) {
458
- if (ENTRY_TYPES[entry.entryType] === undefined) {
459
- return null;
460
- }
461
- return ENTRY_TYPES[entry.entryType](entry);
462
- }
463
- function getAbsoluteTime(time) {
464
- return (window.performance.timeOrigin + time) / 1000;
465
- }
466
- function createPaintEntry(entry) {
467
- var duration = entry.duration, entryType = entry.entryType, name = entry.name, startTime = entry.startTime;
468
- var start = getAbsoluteTime(startTime);
469
- return {
470
- type: entryType,
471
- name: name,
472
- start: start,
473
- end: start + duration,
474
- };
475
- }
476
- function createNavigationEntry(entry) {
477
- // TODO: There looks to be some more interesting bits in here (domComplete, domContentLoaded)
478
- var entryType = entry.entryType, name = entry.name, domComplete = entry.domComplete, startTime = entry.startTime, transferSize = entry.transferSize, type = entry.type;
479
- return {
480
- type: "".concat(entryType, ".").concat(type),
481
- start: getAbsoluteTime(startTime),
482
- end: getAbsoluteTime(domComplete),
483
- name: name,
484
- data: {
485
- size: transferSize,
486
- },
487
- };
488
- }
489
- function createResourceEntry(entry) {
490
- var entryType = entry.entryType, initiatorType = entry.initiatorType, name = entry.name, responseEnd = entry.responseEnd, startTime = entry.startTime, transferSize = entry.transferSize;
491
- // Do not capture fetches to Sentry ingestion endpoint
492
- if (isIngestHost(name)) {
493
- return null;
494
- }
495
- return {
496
- type: "".concat(entryType, ".").concat(initiatorType),
497
- start: getAbsoluteTime(startTime),
498
- end: getAbsoluteTime(responseEnd),
499
- name: name,
500
- data: {
501
- size: transferSize,
502
- },
503
- };
504
- }
505
- function createLargestContentfulPaint(entry) {
506
- return __awaiter(this, void 0, void 0, function () {
507
- var duration, entryType, startTime, size, start, record;
508
- return __generator(this, function (_a) {
509
- switch (_a.label) {
510
- case 0:
511
- duration = entry.duration, entryType = entry.entryType, startTime = entry.startTime, size = entry.size;
512
- start = getAbsoluteTime(startTime);
513
- return [4 /*yield*/, import('rrweb')];
514
- case 1:
515
- record = (_a.sent()).record;
516
- return [2 /*return*/, {
517
- type: entryType,
518
- name: entryType,
519
- start: start,
520
- end: start + duration,
521
- data: {
522
- size: size,
523
- // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
524
- nodeId: record.mirror.getId(entry.element),
525
- },
526
- }];
527
- }
528
- });
529
- });
530
- }
531
- function createMemoryEntry(memoryEntry) {
532
- var jsHeapSizeLimit = memoryEntry.jsHeapSizeLimit, totalJSHeapSize = memoryEntry.totalJSHeapSize, usedJSHeapSize = memoryEntry.usedJSHeapSize;
533
- // we can't use getAbsoluteTime because it adds the event time to
534
- // window.performance.timeOrigin, so we get right now instead.
535
- var time = new Date().getTime() / 1000;
536
- return {
537
- type: 'memory',
538
- name: 'memory',
539
- start: time,
540
- end: time,
541
- data: {
542
- memory: {
543
- jsHeapSizeLimit: jsHeapSizeLimit,
544
- totalJSHeapSize: totalJSHeapSize,
545
- usedJSHeapSize: usedJSHeapSize,
546
- },
547
- },
548
- };
549
- }
550
-
551
- function createEventBuffer(_a) {
552
- var useCompression = _a.useCompression;
553
- return __awaiter(this, void 0, void 0, function () {
554
- var workerString, workerBlob, workerUrl;
555
- return __generator(this, function (_b) {
556
- switch (_b.label) {
557
- case 0:
558
- if (!(useCompression && window.Worker)) return [3 /*break*/, 2];
559
- return [4 /*yield*/, import('./worker-aa3eb59a.js')];
560
- case 1:
561
- workerString = _b.sent();
562
- workerBlob = new Blob([workerString]);
563
- workerUrl = URL.createObjectURL(workerBlob);
564
- try {
565
- logger.log('using compression worker');
566
- return [2 /*return*/, new EventBufferCompressionWorker(new Worker(workerUrl))];
567
- }
568
- catch (_c) {
569
- // catch and ignore, fallback to simple event buffer
570
- }
571
- _b.label = 2;
572
- case 2:
573
- logger.log('falling back to simple event buffer');
574
- return [2 /*return*/, new EventBufferArray()];
575
- }
576
- });
577
- });
578
- }
579
- var EventBufferArray = /** @class */ (function () {
580
- function EventBufferArray() {
581
- this.events = [];
582
- }
583
- EventBufferArray.prototype.destroy = function () {
584
- this.events = [];
585
- };
586
- Object.defineProperty(EventBufferArray.prototype, "length", {
587
- get: function () {
588
- return this.events.length;
589
- },
590
- enumerable: false,
591
- configurable: true
592
- });
593
- EventBufferArray.prototype.addEvent = function (event, isCheckout) {
594
- if (isCheckout) {
595
- this.events = [event];
596
- return;
597
- }
598
- this.events.push(event);
599
- };
600
- EventBufferArray.prototype.finish = function () {
601
- var _this = this;
602
- return new Promise(function (resolve) {
603
- // Make a copy of the events array reference and immediately clear the
604
- // events member so that we do not lose new events while uploading
605
- // attachment.
606
- var eventsRet = _this.events;
607
- _this.events = [];
608
- resolve(JSON.stringify(eventsRet));
609
- });
610
- };
611
- return EventBufferArray;
612
- }());
613
- // exporting for testing
614
- var EventBufferCompressionWorker = /** @class */ (function () {
615
- function EventBufferCompressionWorker(worker) {
616
- this.eventBufferItemLength = 0;
617
- this.worker = worker;
618
- }
619
- EventBufferCompressionWorker.prototype.init = function () {
620
- this.worker.postMessage({ method: 'init', args: [] });
621
- logger.log('Message posted to worker');
622
- };
623
- EventBufferCompressionWorker.prototype.destroy = function () {
624
- this.worker.terminate();
625
- this.worker = null;
626
- };
627
- Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
628
- get: function () {
629
- return this.eventBufferItemLength;
630
- },
631
- enumerable: false,
632
- configurable: true
633
- });
634
- EventBufferCompressionWorker.prototype.addEvent = function (event, isCheckout) {
635
- var _this = this;
636
- // If it is a checkout we should make sure worker buffer is cleared before proceeding
637
- if (!isCheckout) {
638
- this.sendEventToWorker(event);
639
- return;
640
- }
641
- var initListener = function (_a) {
642
- var data = _a.data;
643
- if (data.method !== 'init') {
644
- return;
645
- }
646
- if (!data.success) {
647
- // TODO: Do some error handling, not sure what
648
- logger.error(data.response);
649
- return;
650
- }
651
- // Worker has been re-initialized, can add event now
652
- _this.sendEventToWorker(event);
653
- _this.worker.removeEventListener('message', initListener);
654
- };
655
- this.worker.addEventListener('message', initListener);
656
- this.worker.postMessage({ method: 'init', args: [] });
657
- };
658
- EventBufferCompressionWorker.prototype.sendEventToWorker = function (event) {
659
- this.worker.postMessage({
660
- method: 'addEvent',
661
- args: [event],
662
- });
663
- logger.log('Message posted to worker');
664
- this.eventBufferItemLength++;
665
- };
666
- EventBufferCompressionWorker.prototype.finish = function () {
667
- var _this = this;
668
- return new Promise(function (resolve) {
669
- var finishListener = function (_a) {
670
- var data = _a.data;
671
- if (data.method !== 'finish') {
672
- return;
673
- }
674
- if (!data.success) {
675
- // TODO: Do some error handling, not sure what
676
- logger.error(data.response);
677
- return;
678
- }
679
- logger.log('sending compressed');
680
- resolve(data.response);
681
- _this.eventBufferItemLength = 0;
682
- _this.worker.removeEventListener('message', finishListener);
683
- };
684
- _this.worker.addEventListener('message', finishListener);
685
- _this.worker.postMessage({ method: 'finish', args: [] });
686
- logger.log('Message posted to worker');
687
- });
688
- };
689
- return EventBufferCompressionWorker;
690
- }());
691
-
692
- var BASE_RETRY_INTERVAL = 5000;
693
- var MAX_RETRY_COUNT = 5;
694
- var SentryReplay = /** @class */ (function () {
695
- function SentryReplay(_a) {
696
- if (_a === void 0) { _a = {}; }
697
- var _this = this;
698
- var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? false : _e, // TBD: Making this opt-in for now
699
- _f = _a.useCompression, // TBD: Making this opt-in for now
700
- useCompression = _f === void 0 ? true : _f, _g = _a.captureOnlyOnError, captureOnlyOnError = _g === void 0 ? false : _g, _h = _a.replaysSamplingRate, replaysSamplingRate = _h === void 0 ? 1.0 : _h, _j = _a.recordingConfig, _k = _j === void 0 ? {} : _j, _l = _k.maskAllInputs, maskAllInputs = _l === void 0 ? true : _l, _m = _k.blockClass, blockClass = _m === void 0 ? 'sr-block' : _m, _o = _k.ignoreClass, ignoreClass = _o === void 0 ? 'sr-ignore' : _o, _p = _k.maskTextClass, maskTextClass = _p === void 0 ? 'sr-mask' : _p, recordingOptions = __rest(_k, ["maskAllInputs", "blockClass", "ignoreClass", "maskTextClass"]);
701
- /**
702
- * @inheritDoc
703
- */
704
- this.name = SentryReplay.id;
705
- /**
706
- * Buffer of breadcrumbs to be uploaded
707
- */
708
- this.breadcrumbs = [];
709
- /**
710
- * Buffer of replay spans to be uploaded
711
- */
712
- this.replaySpans = [];
713
- /**
714
- * List of PerformanceEntry from PerformanceObserver
715
- */
716
- this.performanceEvents = [];
717
- /**
718
- * The timestamp of the first event since the last flush. This is used to
719
- * determine if the maximum allowed time has passed before events should be
720
- * flushed again.
721
- */
722
- this.initialEventTimestampSinceFlush = null;
723
- this.performanceObserver = null;
724
- this.retryCount = 0;
725
- this.retryInterval = BASE_RETRY_INTERVAL;
726
- /**
727
- * Flag to make sure we only create a replay event when
728
- * necessary (i.e. we only want to have a single replay
729
- * event per session and it should only be created
730
- * immediately before sending recording)
731
- */
732
- this.needsCaptureReplay = false;
733
- /**
734
- * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
735
- * events as a tag. Also handles the case where we only want to capture a reply
736
- * when an error occurs.
737
- **/
738
- this.handleGlobalEvent = function (event) {
739
- var _a;
740
- // Do not apply replayId to the root event
741
- if (event.message === ROOT_REPLAY_NAME ||
742
- ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
743
- return event;
744
- }
745
- event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
746
- // Need to be very careful that this does not cause an infinite loop
747
- if (_this.options.captureOnlyOnError && event.exception) {
748
- // TODO: Do we continue to record after?
749
- // TODO: What happens if another error happens? Do we record in the same session?
750
- setTimeout(function () { return _this.flushUpdate(); });
751
- }
752
- return event;
753
- };
754
- /**
755
- * Handler for recording events.
756
- *
757
- * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.
758
- */
759
- this.handleRecordingEmit = function (event, isCheckout) {
760
- // If this is false, it means session is expired, create and a new session and wait for checkout
761
- if (!_this.checkAndHandleExpiredSession()) {
762
- logger.error(new Error('Received replay event after session expired.'));
763
- return;
764
- }
765
- _this.addUpdate(function () {
766
- // We need to clear existing events on a checkout, otherwise they are
767
- // incremental event updates and should be appended
768
- _this.eventBuffer.addEvent(event, isCheckout);
769
- // Different behavior for full snapshots (type=2), ignore other event types
770
- // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
771
- if (event.type !== 2) {
772
- return false;
773
- }
774
- // If there is a previousSessionId after a full snapshot occurs, then
775
- // the replay session was started due to session expiration. The new session
776
- // is started before triggering a new checkout and contains the id
777
- // of the previous session. Do not immediately flush in this case
778
- // to avoid capturing only the checkout and instead the replay will
779
- // be captured if they perform any follow-up actions.
780
- if (_this.session.previousSessionId) {
781
- return true;
782
- }
783
- // If the full snapshot is due to an initial load, we will not have
784
- // a previous session ID. In this case, we want to buffer events
785
- // for a set amount of time before flushing. This can help avoid
786
- // capturing replays of users that immediately close the window.
787
- var now = new Date().getTime();
788
- setTimeout(function () { return _this.conditionalFlush(now); }, _this.options.initialFlushDelay);
789
- return true;
790
- });
791
- };
792
- /**
793
- * Handle when visibility of the page content changes. Opening a new tab will
794
- * cause the state to change to hidden because of content of current page will
795
- * be hidden. Likewise, moving a different window to cover the contents of the
796
- * page will also trigger a change to a hidden state.
797
- */
798
- this.handleVisibilityChange = function () {
799
- if (document.visibilityState === 'visible') {
800
- _this.doChangeToForegroundTasks();
801
- }
802
- else {
803
- _this.doChangeToBackgroundTasks();
804
- }
805
- };
806
- /**
807
- * Handle when page is blurred
808
- */
809
- this.handleWindowBlur = function () {
810
- var breadcrumb = createBreadcrumb({
811
- category: 'ui.blur',
812
- });
813
- _this.doChangeToBackgroundTasks(breadcrumb);
814
- };
815
- /**
816
- * Handle when page is focused
817
- */
818
- this.handleWindowFocus = function () {
819
- var breadcrumb = createBreadcrumb({
820
- category: 'ui.focus',
821
- });
822
- _this.doChangeToForegroundTasks(breadcrumb);
823
- };
824
- /**
825
- * Handle when page is closed
826
- */
827
- this.handleWindowUnload = function () {
828
- _this.createCustomBreadcrumb(createBreadcrumb({
829
- category: 'ui.exit',
830
- }));
831
- _this.destroy();
832
- };
833
- /**
834
- * Handler for Sentry Core SDK events.
835
- *
836
- * Transforms core SDK events into replay events.
837
- *
838
- */
839
- this.handleCoreListener = function (type) { return function (handlerData) { return __awaiter(_this, void 0, void 0, function () {
840
- var handlerMap, _a, handlerFn, eventType, result;
841
- var _this = this;
842
- return __generator(this, function (_b) {
843
- switch (_b.label) {
844
- case 0:
845
- handlerMap = {
846
- scope: [handleScope, 'breadcrumb'],
847
- dom: [handleDom, 'breadcrumb'],
848
- fetch: [handleFetch, 'span'],
849
- xhr: [handleXhr, 'span'],
850
- };
851
- if (!(type in handlerMap)) {
852
- throw new Error("No handler defined for type: ".concat(type));
853
- }
854
- _a = handlerMap[type], handlerFn = _a[0], eventType = _a[1];
855
- return [4 /*yield*/, handlerFn(handlerData)];
856
- case 1:
857
- result = _b.sent();
858
- if (result === null) {
859
- return [2 /*return*/];
860
- }
861
- if (['sentry.transaction'].includes(result.category)) {
862
- return [2 /*return*/];
863
- }
864
- this.addUpdate(function () {
865
- _this.eventBuffer.addEvent({
866
- type: 5,
867
- // TODO: We were converting from ms to seconds for breadcrumbs, spans,
868
- // but maybe we should just keep them as milliseconds
869
- timestamp: result.timestamp * 1000 ||
870
- result.startTimestamp * 1000,
871
- data: {
872
- tag: eventType,
873
- payload: result,
874
- },
875
- });
876
- });
877
- return [2 /*return*/];
878
- }
879
- });
880
- }); }; };
881
- /**
882
- * Keep a list of performance entries that will be sent with a replay
883
- */
884
- this.handlePerformanceObserver = function (list
885
- // observer: PerformanceObserver
886
- ) {
887
- var newEntries = list.getEntries();
888
- _this.performanceEvents = __spreadArray(__spreadArray([], _this.performanceEvents, true), newEntries, true);
889
- };
890
- this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, recordingOptions);
891
- this.options = {
892
- flushMinDelay: flushMinDelay,
893
- flushMaxDelay: flushMaxDelay,
894
- stickySession: stickySession,
895
- initialFlushDelay: initialFlushDelay,
896
- captureOnlyOnError: captureOnlyOnError,
897
- replaysSamplingRate: replaysSamplingRate,
898
- useCompression: useCompression,
899
- };
900
- // Modify rrweb options to checkoutEveryNthSecond if this is defined, as we don't know when an error occurs, so we want to try to minimize the number of events captured.
901
- if (this.options.captureOnlyOnError) {
902
- // Checkout every minute, meaning we only get up-to one minute of events before the error happens
903
- this.recordingOptions.checkoutEveryNms = 60000;
904
- }
905
- }
906
- SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
907
- var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
908
- var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
909
- var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
910
- return "".concat(protocol, "://").concat(host).concat(port).concat(path, "/api/").concat(projectId, "/events/").concat(eventId, "/attachments/?sentry_key=").concat(publicKey, "&sentry_version=7&sentry_client=replay");
911
- };
912
- /**
913
- * Because we create a transaction in `setupOnce`, we can potentially create a
914
- * transaction before some native SDK integrations have run and applied their
915
- * own global event processor. An example is:
916
- * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
917
- *
918
- * So we call `this.setup` in next event loop as a workaround to wait for
919
- * other global event processors to finish
920
- */
921
- SentryReplay.prototype.setupOnce = function () {
922
- var _this = this;
923
- // XXX: See method comments above
924
- window.setTimeout(function () { return _this.setup(); });
925
- };
926
- /**
927
- * Initializes the plugin.
928
- *
929
- * Creates or loads a session, attaches listeners to varying events (DOM, PerformanceObserver, Recording, Sentry SDK, etc)
930
- */
931
- SentryReplay.prototype.setup = function () {
932
- return __awaiter(this, void 0, void 0, function () {
933
- var _a;
934
- return __generator(this, function (_b) {
935
- switch (_b.label) {
936
- case 0:
937
- this.loadSession({ expiry: SESSION_IDLE_DURATION });
938
- // If there is no session, then something bad has happened - can't continue
939
- if (!this.session) {
940
- throw new Error('Invalid session');
941
- }
942
- if (!this.session.sampled) {
943
- // If session was not sampled, then we do not initialize the integration at all.
944
- return [2 /*return*/];
945
- }
946
- _a = this;
947
- return [4 /*yield*/, createEventBuffer({
948
- useCompression: this.options.useCompression,
949
- })];
950
- case 1:
951
- _a.eventBuffer = _b.sent();
952
- this.addListeners();
953
- // Tag all (non replay) events that get sent to Sentry with the current
954
- // replay ID so that we can reference them later in the UI
955
- addGlobalEventProcessor(this.handleGlobalEvent);
956
- //
957
- // const { record } = await import('rrweb');
958
- // record({
959
- // ...this.recordingOptions,
960
- // emit: this.handleRecordingEmit,
961
- // });
962
- //
963
- // // Otherwise, these will be captured after the first flush, which means the
964
- // URL and timestamps could be incorrect
965
- this.initialState = {
966
- timestamp: new Date().getTime(),
967
- url: "".concat(window.location.origin).concat(window.location.pathname),
968
- };
969
- return [2 /*return*/];
970
- }
971
- });
972
- });
973
- };
974
- /**
975
- * We want to batch uploads of replay events. Save events only if
976
- * `<flushMinDelay>` milliseconds have elapsed since the last event
977
- * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
978
- *
979
- * Accepts a callback to perform side-effects and returns true to stop batch
980
- * processing and hand back control to caller.
981
- */
982
- SentryReplay.prototype.addUpdate = function (cb) {
983
- var _this = this;
984
- var now = new Date().getTime();
985
- // Timestamp of the first replay event since the last flush, this gets
986
- // reset when we finish the replay event
987
- if (!this.initialEventTimestampSinceFlush &&
988
- !this.options.captureOnlyOnError) {
989
- this.initialEventTimestampSinceFlush = now;
990
- }
991
- // Do not finish the replay event if we receive a new replay event
992
- if (this.timeout) {
993
- window.clearTimeout(this.timeout);
994
- }
995
- // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
996
- var cbResult = cb === null || cb === void 0 ? void 0 : cb();
997
- // If this option is turned on then we will only want to call `flushUpdate`
998
- // explicitly
999
- if (this.options.captureOnlyOnError) {
1000
- return;
1001
- }
1002
- // If callback is true, we do not want to continue with flushing -- the
1003
- // caller will need to handle it.
1004
- if (cbResult === true) {
1005
- return;
1006
- }
1007
- var flushMaxDelayExceeded = isExpired(this.initialEventTimestampSinceFlush, this.options.flushMaxDelay, now);
1008
- // If `flushMaxDelayExceeded` is true, then we should finish the replay event immediately,
1009
- // Otherwise schedule it to be finished in `this.options.flushMinDelay`
1010
- if (flushMaxDelayExceeded) {
1011
- logger.log('replay max delay exceeded, finishing replay event');
1012
- this.flushUpdate();
1013
- return;
1014
- }
1015
- // Set timer to finish replay event and send replay attachment to
1016
- // Sentry. Will be cancelled if an event happens before `flushMinDelay`
1017
- // elapses.
1018
- this.timeout = window.setTimeout(function () {
1019
- logger.log('replay timeout exceeded, finishing replay event');
1020
- _this.flushUpdate(now);
1021
- }, this.options.flushMinDelay);
1022
- };
1023
- /**
1024
- * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
1025
- */
1026
- SentryReplay.prototype.destroy = function () {
1027
- this.removeListeners();
1028
- this.eventBuffer.destroy();
1029
- };
1030
- SentryReplay.prototype.clearSession = function () {
1031
- this.session = null;
1032
- };
1033
- /**
1034
- * Loads a session from storage, or creates a new one if it does not exist or
1035
- * is expired.
1036
- */
1037
- SentryReplay.prototype.loadSession = function (_a) {
1038
- var _b, _c;
1039
- var expiry = _a.expiry;
1040
- var _d = getSession({
1041
- expiry: expiry,
1042
- stickySession: this.options.stickySession,
1043
- currentSession: this.session,
1044
- samplingRate: this.options.replaysSamplingRate,
1045
- }), type = _d.type, session = _d.session;
1046
- // If session was newly created (i.e. was not loaded from storage), then
1047
- // enable flag to create the root replay
1048
- if (type === 'new') {
1049
- this.needsCaptureReplay = true;
1050
- }
1051
- if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
1052
- session.previousSessionId = (_c = this.session) === null || _c === void 0 ? void 0 : _c.id;
1053
- }
1054
- this.session = session;
1055
- };
1056
- /**
1057
- * Adds listeners to record events for the replay
1058
- */
1059
- SentryReplay.prototype.addListeners = function () {
1060
- var _this = this;
1061
- document.addEventListener('visibilitychange', this.handleVisibilityChange);
1062
- window.addEventListener('blur', this.handleWindowBlur);
1063
- window.addEventListener('focus', this.handleWindowFocus);
1064
- window.addEventListener('beforeunload', this.handleWindowUnload);
1065
- // Listeners from core SDK //
1066
- var scope = getCurrentHub().getScope();
1067
- scope.addScopeListener(this.handleCoreListener('scope'));
1068
- addInstrumentationHandler('dom', this.handleCoreListener('dom'));
1069
- // PerformanceObserver //
1070
- if (!('PerformanceObserver' in window)) {
1071
- return;
1072
- }
1073
- this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
1074
- // Observe almost everything for now (no mark/measure)
1075
- [
1076
- 'element',
1077
- 'event',
1078
- 'first-input',
1079
- 'largest-contentful-paint',
1080
- 'layout-shift',
1081
- 'longtask',
1082
- 'navigation',
1083
- 'paint',
1084
- 'resource',
1085
- ].forEach(function (type) {
1086
- return _this.performanceObserver.observe({
1087
- type: type,
1088
- buffered: true,
1089
- });
1090
- });
1091
- };
1092
- /**
1093
- * Cleans up listeners that were created in `addListeners`
1094
- */
1095
- SentryReplay.prototype.removeListeners = function () {
1096
- document.removeEventListener('visibilitychange', this.handleVisibilityChange);
1097
- window.removeEventListener('blur', this.handleWindowBlur);
1098
- window.removeEventListener('focus', this.handleWindowFocus);
1099
- window.removeEventListener('beforeunload', this.handleWindowUnload);
1100
- if (this.performanceObserver) {
1101
- this.performanceObserver.disconnect();
1102
- this.performanceObserver = null;
1103
- }
1104
- };
1105
- /**
1106
- * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
1107
- */
1108
- SentryReplay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {
1109
- var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1110
- if (breadcrumb) {
1111
- this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), {
1112
- // if somehow the page went hidden while session is expired, attach to previous session
1113
- timestamp: isExpired
1114
- ? this.session.lastActivity / 1000
1115
- : breadcrumb.timestamp }));
1116
- }
1117
- // Send replay when the page/tab becomes hidden. There is no reason to send
1118
- // replay if it becomes visible, since no actions we care about were done
1119
- // while it was hidden
1120
- this.conditionalFlush();
1121
- };
1122
- /**
1123
- * Tasks to run when we consider a page to be visible (via focus and/or visibility)
1124
- */
1125
- SentryReplay.prototype.doChangeToForegroundTasks = function (breadcrumb) {
1126
- var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1127
- if (breadcrumb) {
1128
- this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), { timestamp: isExpired
1129
- ? new Date().getTime() / 1000
1130
- : breadcrumb.timestamp }));
1131
- }
1132
- if (isExpired) {
1133
- // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
1134
- // ms, we will re-use the existing session, otherwise create a new
1135
- // session
1136
- logger.log('Document has become active, but session has expired');
1137
- this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
1138
- this.triggerFullSnapshot();
1139
- return;
1140
- }
1141
- // Otherwise if session is not expired...
1142
- // Update with current timestamp as the last session activity
1143
- // Only updating session on visibility change to be conservative about
1144
- // writing to session storage. This could be changed in the future.
1145
- this.updateLastActivity();
1146
- };
1147
- /**
1148
- * Trigger rrweb to take a full snapshot which will cause this plugin to
1149
- * create a new Replay event.
1150
- */
1151
- SentryReplay.prototype.triggerFullSnapshot = function () {
1152
- return __awaiter(this, void 0, void 0, function () {
1153
- var record;
1154
- return __generator(this, function (_a) {
1155
- switch (_a.label) {
1156
- case 0:
1157
- logger.log('Taking full rrweb snapshot');
1158
- return [4 /*yield*/, import('rrweb')];
1159
- case 1:
1160
- record = (_a.sent()).record;
1161
- record.takeFullSnapshot(true);
1162
- return [2 /*return*/];
1163
- }
1164
- });
1165
- });
1166
- };
1167
- /**
1168
- * Updates the session's last activity timestamp
1169
- */
1170
- SentryReplay.prototype.updateLastActivity = function (lastActivity) {
1171
- if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1172
- this.session.lastActivity = lastActivity;
1173
- };
1174
- /**
1175
- * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
1176
- */
1177
- SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
1178
- var _this = this;
1179
- this.addUpdate(function () {
1180
- _this.eventBuffer.addEvent({
1181
- type: 5,
1182
- timestamp: breadcrumb.timestamp,
1183
- data: {
1184
- tag: 'breadcrumb',
1185
- payload: breadcrumb,
1186
- },
1187
- });
1188
- });
1189
- };
1190
- /**
1191
- * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
1192
- */
1193
- SentryReplay.prototype.createPerformanceSpans = function (entries) {
1194
- var _this = this;
1195
- entries.forEach(function (_a) {
1196
- var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1197
- _this.eventBuffer.addEvent({
1198
- type: 5,
1199
- timestamp: start,
1200
- data: {
1201
- tag: 'performanceSpan',
1202
- payload: {
1203
- op: type,
1204
- description: name,
1205
- startTimestamp: start,
1206
- endTimestamp: end,
1207
- data: data,
1208
- },
1209
- },
1210
- });
1211
- });
1212
- };
1213
- /**
1214
- * Observed performance events are added to `this.performanceEvents`. These
1215
- * are included in the replay event before it is finished and sent to Sentry.
1216
- */
1217
- SentryReplay.prototype.addPerformanceEntries = function () {
1218
- return __awaiter(this, void 0, void 0, function () {
1219
- var entries, entryEvents;
1220
- return __generator(this, function (_a) {
1221
- switch (_a.label) {
1222
- case 0:
1223
- entries = __spreadArray([], this.performanceEvents, true);
1224
- this.performanceEvents = [];
1225
- return [4 /*yield*/, createPerformanceEntries(entries)];
1226
- case 1:
1227
- entryEvents = _a.sent();
1228
- // window.performance.memory is a non-standard API and doesn't work on all browsers
1229
- // so we check before creating the event.
1230
- if ('memory' in window.performance) {
1231
- // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
1232
- entryEvents.push(createMemoryEntry(window.performance.memory));
1233
- }
1234
- this.createPerformanceSpans(entryEvents);
1235
- return [2 /*return*/];
1236
- }
1237
- });
1238
- });
1239
- };
1240
- /**
1241
- *
1242
- *
1243
- * Returns true if session is not expired, false otherwise.
1244
- */
1245
- SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
1246
- if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
1247
- var oldSessionId = this.session.id;
1248
- // This will create a new session if expired, based on expiry length
1249
- this.loadSession({ expiry: expiry });
1250
- // Session was expired if session ids do not match
1251
- var isExpired = oldSessionId !== this.session.id;
1252
- if (!isExpired) {
1253
- return true;
1254
- }
1255
- // TODO: We could potentially figure out a way to save the last session,
1256
- // and produce a checkout based on a previous checkout + updates, and then
1257
- // replay the event on top. Or maybe replay the event on top of a refresh
1258
- // snapshot.
1259
- // For now create a new snapshot
1260
- this.triggerFullSnapshot();
1261
- return false;
1262
- };
1263
- /**
1264
- * Only flush if `captureOnlyOnError` is false.
1265
- */
1266
- SentryReplay.prototype.conditionalFlush = function (lastActivity) {
1267
- if (this.options.captureOnlyOnError) {
1268
- return;
1269
- }
1270
- return this.flushUpdate(lastActivity);
1271
- };
1272
- /**
1273
- * Flushes replay event buffer to Sentry.
1274
- *
1275
- * Performance events are only added right before flushing - this is probably
1276
- * due to the buffered performance observer events.
1277
- */
1278
- SentryReplay.prototype.flushUpdate = function (lastActivity) {
1279
- return __awaiter(this, void 0, void 0, function () {
1280
- var timestamp, recordingData, err_1;
1281
- return __generator(this, function (_a) {
1282
- switch (_a.label) {
1283
- case 0:
1284
- if (!this.checkAndHandleExpiredSession()) {
1285
- logger.error(new Error('Attempting to finish replay event after session expired.'));
1286
- return [2 /*return*/];
1287
- }
1288
- if (!this.session.id) {
1289
- console.error(new Error('[Sentry]: No transaction, no replay'));
1290
- return [2 /*return*/];
1291
- }
1292
- return [4 /*yield*/, this.addPerformanceEntries()];
1293
- case 1:
1294
- _a.sent();
1295
- if (!this.eventBuffer.length) {
1296
- return [2 /*return*/];
1297
- }
1298
- // Only want to create replay event if session is new
1299
- if (this.needsCaptureReplay) {
1300
- // This event needs to exist before calling `sendReplay`
1301
- captureReplay(this.session, this.initialState);
1302
- this.needsCaptureReplay = false;
1303
- }
1304
- // Reset this to null regardless of `sendReplay` result so that future
1305
- // events will get flushed properly
1306
- this.initialEventTimestampSinceFlush = null;
1307
- _a.label = 2;
1308
- case 2:
1309
- _a.trys.push([2, 5, , 6]);
1310
- timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1311
- return [4 /*yield*/, this.eventBuffer.finish()];
1312
- case 3:
1313
- recordingData = _a.sent();
1314
- return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1315
- case 4:
1316
- _a.sent();
1317
- // The below will only happen after successfully sending replay //
1318
- // TBD: Alternatively we could update this after every rrweb event
1319
- // `timestamp` should reflect when the event happens. e.g. the timestamp
1320
- // of the event is passed as an argument in the case where a timeout
1321
- // occurs.
1322
- this.updateLastActivity(timestamp);
1323
- captureReplayUpdate(this.session, timestamp);
1324
- return [3 /*break*/, 6];
1325
- case 5:
1326
- err_1 = _a.sent();
1327
- console.error(err_1);
1328
- return [3 /*break*/, 6];
1329
- case 6: return [2 /*return*/];
1330
- }
1331
- });
1332
- });
1333
- };
1334
- /**
1335
- * Send replay attachment using either `sendBeacon()` or `fetch()`
1336
- */
1337
- SentryReplay.prototype.sendReplayRequest = function (_a) {
1338
- var endpoint = _a.endpoint, events = _a.events;
1339
- return __awaiter(this, void 0, void 0, function () {
1340
- var formData, payloadBlob;
1341
- return __generator(this, function (_b) {
1342
- switch (_b.label) {
1343
- case 0:
1344
- formData = new FormData();
1345
- payloadBlob = new Blob([events], {
1346
- type: 'application/json',
1347
- });
1348
- logger.log('blob size in bytes: ', payloadBlob.size);
1349
- formData.append('rrweb', payloadBlob, "rrweb-".concat(new Date().getTime(), ".json"));
1350
- // If sendBeacon is supported and payload is smol enough...
1351
- if (supportsSendBeacon() && payloadBlob.size <= 65535) {
1352
- logger.log("uploading attachment via sendBeacon()");
1353
- window.navigator.sendBeacon(endpoint, formData);
1354
- return [2 /*return*/];
1355
- }
1356
- // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1357
- logger.log("uploading attachment via fetch()");
1358
- return [4 /*yield*/, fetch(endpoint, {
1359
- method: 'POST',
1360
- body: formData,
1361
- })];
1362
- case 1:
1363
- _b.sent();
1364
- return [2 /*return*/];
1365
- }
1366
- });
1367
- });
1368
- };
1369
- SentryReplay.prototype.resetRetries = function () {
1370
- this.retryCount = 0;
1371
- this.retryInterval = BASE_RETRY_INTERVAL;
1372
- };
1373
- /**
1374
- * Finalize and send the current replay event to Sentry
1375
- */
1376
- SentryReplay.prototype.sendReplay = function (eventId, events) {
1377
- return __awaiter(this, void 0, void 0, function () {
1378
- var client, endpoint, ex_1;
1379
- var _this = this;
1380
- return __generator(this, function (_b) {
1381
- switch (_b.label) {
1382
- case 0:
1383
- // short circuit if there's no events to upload
1384
- if (!events.length) {
1385
- return [2 /*return*/];
1386
- }
1387
- client = getCurrentHub().getClient();
1388
- endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
1389
- _b.label = 1;
1390
- case 1:
1391
- _b.trys.push([1, 3, , 8]);
1392
- return [4 /*yield*/, this.sendReplayRequest({
1393
- endpoint: endpoint,
1394
- events: events,
1395
- })];
1396
- case 2:
1397
- _b.sent();
1398
- this.resetRetries();
1399
- return [2 /*return*/, true];
1400
- case 3:
1401
- ex_1 = _b.sent();
1402
- // we have to catch this otherwise it throws an infinite loop in Sentry
1403
- console.error(ex_1);
1404
- // If an error happened here, it's likely that uploading the attachment
1405
- // failed, we'll can retry with the same events payload
1406
- if (this.retryCount >= MAX_RETRY_COUNT) {
1407
- this.resetRetries();
1408
- return [2 /*return*/, false];
1409
- }
1410
- this.retryCount = this.retryCount + 1;
1411
- // will retry in intervals of 5, 10, 15, 20, 25 seconds
1412
- this.retryInterval = this.retryCount * this.retryInterval;
1413
- _b.label = 4;
1414
- case 4:
1415
- _b.trys.push([4, 6, , 7]);
1416
- return [4 /*yield*/, new Promise(function (resolve, reject) {
1417
- setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1418
- var result;
1419
- return __generator(this, function (_a) {
1420
- switch (_a.label) {
1421
- case 0: return [4 /*yield*/, this.sendReplay(eventId, events)];
1422
- case 1:
1423
- result = _a.sent();
1424
- if (result) {
1425
- resolve(true);
1426
- }
1427
- else {
1428
- reject(new Error('Could not send replay'));
1429
- }
1430
- return [2 /*return*/];
1431
- }
1432
- });
1433
- }); }, _this.retryInterval);
1434
- })];
1435
- case 5:
1436
- _b.sent();
1437
- return [2 /*return*/, true];
1438
- case 6:
1439
- _b.sent();
1440
- return [2 /*return*/, false];
1441
- case 7: return [3 /*break*/, 8];
1442
- case 8: return [2 /*return*/];
1443
- }
1444
- });
1445
- });
1446
- };
1447
- /**
1448
- * @inheritDoc
1449
- */
1450
- SentryReplay.id = 'Replay';
1451
- return SentryReplay;
1452
- }());
1453
-
1454
- export { SentryReplay };