@sentry/replay 0.4.8-3 → 0.5.0

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 (30) hide show
  1. package/README.md +15 -15
  2. package/dist/config/dist/src/api/captureReplay.d.ts +5 -3
  3. package/dist/config/dist/src/api/captureReplayUpdate.d.ts +5 -3
  4. package/dist/config/dist/src/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  5. package/dist/config/dist/src/coreHandlers/getSpanHandler.d.ts +5 -0
  6. package/dist/config/dist/src/coreHandlers/handleFetch.d.ts +19 -2
  7. package/dist/config/dist/src/coreHandlers/handleHistory.d.ts +7 -0
  8. package/dist/config/dist/src/coreHandlers/handleXhr.d.ts +21 -2
  9. package/dist/config/dist/src/eventBuffer.d.ts +11 -4
  10. package/dist/config/dist/src/index.d.ts +28 -13
  11. package/dist/config/dist/src/session/constants.d.ts +2 -2
  12. package/dist/config/dist/src/types.d.ts +22 -9
  13. package/dist/config/dist/src/util/createPayload.d.ts +5 -0
  14. package/dist/dist/api/captureReplay.d.ts +5 -3
  15. package/dist/dist/api/captureReplayUpdate.d.ts +5 -3
  16. package/dist/dist/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  17. package/dist/dist/coreHandlers/getSpanHandler.d.ts +5 -0
  18. package/dist/dist/coreHandlers/handleFetch.d.ts +19 -2
  19. package/dist/dist/coreHandlers/handleHistory.d.ts +7 -0
  20. package/dist/dist/coreHandlers/handleXhr.d.ts +21 -2
  21. package/dist/dist/eventBuffer.d.ts +11 -4
  22. package/dist/dist/index.d.ts +28 -13
  23. package/dist/dist/session/constants.d.ts +2 -2
  24. package/dist/dist/types.d.ts +22 -9
  25. package/dist/dist/util/createPayload.d.ts +5 -0
  26. package/dist/index.es.js +379 -222
  27. package/dist/index.js +377 -220
  28. package/dist/index.js.map +1 -1
  29. package/package.json +2 -2
  30. package/dist/dist/coreHandlers/index.d.ts +0 -4
package/dist/index.es.js CHANGED
@@ -1,5 +1,5 @@
1
- import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor } from '@sentry/core';
2
- import { uuid4, logger as logger$1, htmlTreeAsString, addInstrumentationHandler } from '@sentry/utils';
1
+ import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
+ import { htmlTreeAsString, logger as logger$1, uuid4, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
3
  import { record, EventType } from 'rrweb';
4
4
 
5
5
  /******************************************************************************
@@ -89,34 +89,177 @@ function __spreadArray(to, from, pack) {
89
89
  }
90
90
 
91
91
  var REPLAY_SESSION_KEY = 'sentryReplaySession';
92
- var ROOT_REPLAY_NAME = 'sentry-replay';
93
- var REPLAY_EVENT_NAME = 'sentry-replay-event';
92
+ var REPLAY_EVENT_NAME = 'replay_event';
94
93
  // The idle limit for a session
95
94
  var SESSION_IDLE_DURATION = 900000; // 15 minutes
96
95
  // Grace period to keep a session when a user changes tabs or hides window
97
96
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
98
97
 
99
98
  function captureReplay(_a) {
100
- var session = _a.session, initialState = _a.initialState;
99
+ var session = _a.session, initialState = _a.initialState, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
101
100
  captureEvent({
102
- message: ROOT_REPLAY_NAME,
103
- tags: { segmentId: session.segmentId, url: initialState.url },
104
- timestamp: initialState.timestamp / 1000,
101
+ // @ts-expect-error replay_event is a new event type
102
+ type: REPLAY_EVENT_NAME,
103
+ replay_start_timestamp: initialState.timestamp / 1000,
104
+ error_ids: errorIds,
105
+ trace_ids: traceIds,
106
+ urls: urls,
107
+ replay_id: session.id,
108
+ segment_id: session.segmentId, // TODO: Should this increment?
105
109
  }, { event_id: session.id });
106
110
  }
107
111
 
108
112
  function captureReplayUpdate(_a) {
109
- var session = _a.session, timestamp = _a.timestamp;
113
+ var session = _a.session, timestamp = _a.timestamp, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
110
114
  captureEvent({
111
- timestamp: timestamp / 1000,
112
- message: "".concat(REPLAY_EVENT_NAME, "-").concat(uuid4().substring(16)),
113
- tags: {
114
- replayId: session.id,
115
- segmentId: session.segmentId++,
116
- },
115
+ // @ts-expect-error replay_event is a new event type
116
+ type: REPLAY_EVENT_NAME,
117
+ replay_start_timestamp: timestamp / 1000,
118
+ error_ids: errorIds,
119
+ trace_ids: traceIds,
120
+ urls: urls,
121
+ replay_id: session.id,
122
+ segment_id: ++session.segmentId,
123
+ });
124
+ }
125
+
126
+ function createBreadcrumb(breadcrumb) {
127
+ return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
128
+ }
129
+
130
+ function handleDom(handlerData) {
131
+ // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
132
+ var target;
133
+ var targetNode;
134
+ // Accessing event.target can throw (see getsentry/raven-js#838, #768)
135
+ try {
136
+ targetNode =
137
+ handlerData.event.target ||
138
+ handlerData.event;
139
+ target = htmlTreeAsString(targetNode);
140
+ }
141
+ catch (e) {
142
+ target = '<unknown>';
143
+ }
144
+ if (target.length === 0) {
145
+ return null;
146
+ }
147
+ return createBreadcrumb({
148
+ category: "ui.".concat(handlerData.name),
149
+ message: target,
150
+ data: __assign({}, (targetNode ? { nodeId: record.mirror.getId(targetNode) } : {})),
117
151
  });
118
152
  }
119
153
 
154
+ var _LAST_BREADCRUMB = null;
155
+ function handleScope(scope) {
156
+ var _a;
157
+ //@ts-expect-error using private val
158
+ var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
159
+ // Listener can be called when breadcrumbs have not changed, so we store the
160
+ // reference to the last crumb and only return a crumb if it has changed
161
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
162
+ return null;
163
+ }
164
+ _LAST_BREADCRUMB = newBreadcrumb;
165
+ if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
166
+ ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
167
+ return null;
168
+ }
169
+ return createBreadcrumb(newBreadcrumb);
170
+ }
171
+
172
+ function getBreadcrumbHandler(type) {
173
+ if (type === 'scope') {
174
+ return handleScope;
175
+ }
176
+ return handleDom;
177
+ }
178
+
179
+ /**
180
+ * Checks is `targetHost` is a Sentry ingestion host
181
+ */
182
+ function isIngestHost(targetHost) {
183
+ var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
184
+ return targetHost.startsWith("".concat(protocol, "://").concat(host));
185
+ }
186
+
187
+ function handleFetch(handlerData) {
188
+ if (!handlerData.endTimestamp) {
189
+ return null;
190
+ }
191
+ var startTimestamp = handlerData.startTimestamp, endTimestamp = handlerData.endTimestamp, fetchData = handlerData.fetchData, response = handlerData.response;
192
+ // Do not capture fetches to Sentry ingestion endpoint
193
+ if (isIngestHost(fetchData.url)) {
194
+ return null;
195
+ }
196
+ return {
197
+ type: 'resource.fetch',
198
+ start: startTimestamp / 1000,
199
+ end: endTimestamp / 1000,
200
+ name: fetchData.url,
201
+ data: {
202
+ method: fetchData.method,
203
+ statusCode: response.status,
204
+ },
205
+ };
206
+ }
207
+
208
+ function handleHistory(handlerData) {
209
+ var from = handlerData.from, to = handlerData.to;
210
+ var now = new Date().getTime() / 1000;
211
+ return {
212
+ type: 'navigation.push',
213
+ start: now,
214
+ end: now,
215
+ name: to,
216
+ data: {
217
+ previous: from,
218
+ },
219
+ };
220
+ }
221
+
222
+ function handleXhr(handlerData) {
223
+ if (handlerData.xhr.__sentry_own_request__) {
224
+ // Taken from sentry-javascript
225
+ // Only capture non-sentry requests
226
+ return null;
227
+ }
228
+ if (handlerData.startTimestamp) {
229
+ // TODO: See if this is still needed
230
+ handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
231
+ }
232
+ if (!handlerData.endTimestamp) {
233
+ return null;
234
+ }
235
+ var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, statusCode = _a.status_code;
236
+ // Do not capture fetches to Sentry ingestion endpoint
237
+ if (isIngestHost(url)) {
238
+ return null;
239
+ }
240
+ return {
241
+ type: 'resource.xhr',
242
+ name: url,
243
+ start: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
244
+ handlerData.endTimestamp / 1000.0,
245
+ end: handlerData.endTimestamp / 1000.0,
246
+ data: {
247
+ method: method,
248
+ statusCode: statusCode,
249
+ },
250
+ };
251
+ }
252
+
253
+ function getSpanHandler(type) {
254
+ if (type === 'fetch') {
255
+ return handleFetch;
256
+ }
257
+ if (type === 'xhr') {
258
+ return handleXhr;
259
+ }
260
+ return handleHistory;
261
+ }
262
+
120
263
  /**
121
264
  * Given an initial timestamp and an expiry duration, checks to see if current
122
265
  * time should be considered as expired.
@@ -320,8 +463,24 @@ function getSession(_a) {
320
463
  return { type: 'new', session: newSession };
321
464
  }
322
465
 
323
- function createBreadcrumb(breadcrumb) {
324
- return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
466
+ function createPayload(_a) {
467
+ var events = _a.events, headers = _a.headers;
468
+ var payloadWithSequence;
469
+ // XXX: newline is needed to separate sequence id from events
470
+ var replayHeaders = "".concat(JSON.stringify(headers), "\n");
471
+ if (typeof events === 'string') {
472
+ payloadWithSequence = "".concat(replayHeaders).concat(events);
473
+ }
474
+ else {
475
+ var enc = new TextEncoder();
476
+ // XXX: newline is needed to separate sequence id from events
477
+ var sequence = enc.encode(replayHeaders);
478
+ // Merge the two Uint8Arrays
479
+ payloadWithSequence = new Uint8Array(sequence.length + events.length);
480
+ payloadWithSequence.set(sequence);
481
+ payloadWithSequence.set(events, sequence.length);
482
+ }
483
+ return payloadWithSequence;
325
484
  }
326
485
 
327
486
  /**
@@ -331,92 +490,6 @@ function supportsSendBeacon() {
331
490
  return 'navigator' in window && 'sendBeacon' in window.navigator;
332
491
  }
333
492
 
334
- function handleDom(handlerData) {
335
- // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
336
- var target;
337
- var targetNode;
338
- // Accessing event.target can throw (see getsentry/raven-js#838, #768)
339
- try {
340
- targetNode =
341
- handlerData.event.target ||
342
- handlerData.event;
343
- target = htmlTreeAsString(targetNode);
344
- }
345
- catch (e) {
346
- target = '<unknown>';
347
- }
348
- if (target.length === 0) {
349
- return null;
350
- }
351
- return createBreadcrumb({
352
- category: "ui.".concat(handlerData.name),
353
- message: target,
354
- data: __assign({}, (targetNode ? { nodeId: record.mirror.getId(targetNode) } : {})),
355
- });
356
- }
357
-
358
- function handleFetch(handlerData) {
359
- if (!handlerData.endTimestamp) {
360
- return null;
361
- }
362
- var _a = handlerData.args, op = _a[0], description = _a[1];
363
- return {
364
- description: description,
365
- op: op,
366
- startTimestamp: handlerData.startTimestamp / 1000,
367
- endTimestamp: handlerData.endTimestamp / 1000,
368
- data: {
369
- statusCode: handlerData.response.status,
370
- },
371
- };
372
- }
373
-
374
- var _LAST_BREADCRUMB = null;
375
- function handleScope(scope) {
376
- var _a;
377
- //@ts-expect-error using private val
378
- var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
379
- // Listener can be called when breadcrumbs have not changed, so we store the
380
- // reference to the last crumb and only return a crumb if it has changed
381
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
382
- return null;
383
- }
384
- _LAST_BREADCRUMB = newBreadcrumb;
385
- if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
386
- ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
387
- return null;
388
- }
389
- return createBreadcrumb(newBreadcrumb);
390
- }
391
-
392
- function handleXhr(handlerData) {
393
- if (handlerData.startTimestamp) {
394
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
395
- }
396
- if (!handlerData.endTimestamp) {
397
- return null;
398
- }
399
- var _a = handlerData.args, op = _a[0], description = _a[1];
400
- return {
401
- description: description,
402
- op: op,
403
- startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
404
- handlerData.endTimestamp / 1000.0,
405
- endTimestamp: handlerData.endTimestamp / 1000.0,
406
- data: {
407
- statusCode: handlerData.response.status,
408
- },
409
- };
410
- }
411
-
412
- /**
413
- * Checks is `targetHost` is a Sentry ingestion host
414
- */
415
- function isIngestHost(targetHost) {
416
- var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
417
- return targetHost.startsWith("".concat(protocol, "://").concat(host));
418
- }
419
-
420
493
  var _a;
421
494
  // Map entryType -> function to normalize data for event
422
495
  var ENTRY_TYPES = (_a = {
@@ -467,6 +540,10 @@ function createResourceEntry(entry) {
467
540
  if (isIngestHost(name)) {
468
541
  return null;
469
542
  }
543
+ // Core SDK handles these
544
+ if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {
545
+ return null;
546
+ }
470
547
  return {
471
548
  type: "".concat(entryType, ".").concat(initiatorType),
472
549
  start: getAbsoluteTime(startTime),
@@ -527,7 +604,6 @@ function createEventBuffer(_a) {
527
604
  return new EventBufferCompressionWorker(worker);
528
605
  }
529
606
  else {
530
- // TODO: Debugging
531
607
  captureException(new Error('Unable to create compression worker'));
532
608
  }
533
609
  }
@@ -580,38 +656,25 @@ var EventBufferCompressionWorker = /** @class */ (function () {
580
656
  this.eventBufferItemLength = 0;
581
657
  this._id = 0;
582
658
  this.sendEventToWorker = function (event) {
583
- _this.postMessage({
659
+ var promise = _this.postMessage({
584
660
  id: _this.id,
585
661
  method: 'addEvent',
586
662
  args: [event],
587
663
  });
664
+ logger.log('Message posted to worker');
665
+ // XXX: See note in `get length()`
588
666
  _this.eventBufferItemLength++;
667
+ return promise;
589
668
  };
590
- this.finishRequest = function (id) {
591
- return new Promise(function (resolve, reject) {
592
- var finishListener = function (_a) {
593
- var data = _a.data;
594
- if (data.method !== 'finish') {
595
- return;
596
- }
597
- if (data.id !== id) {
598
- return;
599
- }
600
- if (!data.success) {
601
- // TODO: Do some error handling, not sure what
602
- logger.error(data.response);
603
- reject(new Error('Error in compression worker'));
604
- return;
605
- }
606
- resolve(data.response);
607
- logger.log('Worker responded with compressed payload');
608
- _this.eventBufferItemLength = 0;
609
- _this.worker.removeEventListener('message', finishListener);
610
- };
611
- _this.worker.addEventListener('message', finishListener);
612
- _this.postMessage({ id: id, method: 'finish', args: [] });
669
+ this.finishRequest = function (id) { return __awaiter(_this, void 0, void 0, function () {
670
+ var promise;
671
+ return __generator(this, function (_a) {
672
+ promise = this.postMessage({ id: id, method: 'finish', args: [] });
673
+ // XXX: See note in `get length()`
674
+ this.eventBufferItemLength = 0;
675
+ return [2 /*return*/, promise];
613
676
  });
614
- };
677
+ }); };
615
678
  this.worker = worker;
616
679
  }
617
680
  Object.defineProperty(EventBufferCompressionWorker.prototype, "id", {
@@ -624,8 +687,38 @@ var EventBufferCompressionWorker = /** @class */ (function () {
624
687
  enumerable: false,
625
688
  configurable: true
626
689
  });
627
- EventBufferCompressionWorker.prototype.postMessage = function (args) {
628
- this.worker.postMessage(args);
690
+ /**
691
+ * Post message to worker and wait for response before resolving promise.
692
+ */
693
+ EventBufferCompressionWorker.prototype.postMessage = function (_a) {
694
+ var _this = this;
695
+ var id = _a.id, method = _a.method, args = _a.args;
696
+ return new Promise(function (resolve, reject) {
697
+ var listener = function (_a) {
698
+ var data = _a.data;
699
+ if (data.method !== method) {
700
+ return;
701
+ }
702
+ // There can be multiple listeners for a single method, the id ensures
703
+ // that the response matches the caller.
704
+ if (data.id !== id) {
705
+ return;
706
+ }
707
+ // At this point, we'll always want to remove listener regardless of result status
708
+ _this.worker.removeEventListener('message', listener);
709
+ if (!data.success) {
710
+ // TODO: Do some error handling, not sure what
711
+ logger.error(data.response);
712
+ reject(new Error('Error in compression worker'));
713
+ return;
714
+ }
715
+ resolve(data.response);
716
+ };
717
+ // Note: we can't use `once` option because it's possible it needs to
718
+ // listen to multiple messages
719
+ _this.worker.addEventListener('message', listener);
720
+ _this.worker.postMessage({ id: id, method: method, args: args });
721
+ });
629
722
  };
630
723
  EventBufferCompressionWorker.prototype.init = function () {
631
724
  this.postMessage({ id: this.id, method: 'init', args: [] });
@@ -637,6 +730,10 @@ var EventBufferCompressionWorker = /** @class */ (function () {
637
730
  this.worker = null;
638
731
  };
639
732
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
733
+ /**
734
+ * Note that this may not reflect what is actually in the event buffer. This
735
+ * is only a local count of the buffer size since `addEvent` is async.
736
+ */
640
737
  get: function () {
641
738
  return this.eventBufferItemLength;
642
739
  },
@@ -644,39 +741,31 @@ var EventBufferCompressionWorker = /** @class */ (function () {
644
741
  configurable: true
645
742
  });
646
743
  EventBufferCompressionWorker.prototype.addEvent = function (event, isCheckout) {
647
- var _this = this;
648
- // If it is a checkout we should make sure worker buffer is cleared before proceeding
649
- if (!isCheckout) {
650
- this.sendEventToWorker(event);
651
- return;
652
- }
653
- var initListener = function (_a) {
654
- var data = _a.data;
655
- if (data.method !== 'init') {
656
- return;
657
- }
658
- if (!data.success) {
659
- // TODO: Do some error handling, not sure what
660
- logger.error(data.response);
661
- return;
662
- }
663
- // Worker has been re-initialized, can add event now
664
- _this.sendEventToWorker(event);
665
- _this.worker.removeEventListener('message', initListener);
666
- };
667
- this.worker.addEventListener('message', initListener);
668
- this.postMessage({ id: this.id, method: 'init', args: [] });
669
- };
670
- EventBufferCompressionWorker.prototype.finish = function () {
671
744
  return __awaiter(this, void 0, void 0, function () {
672
745
  return __generator(this, function (_a) {
673
746
  switch (_a.label) {
674
- case 0: return [4 /*yield*/, this.finishRequest(this.id)];
675
- case 1: return [2 /*return*/, _a.sent()];
747
+ case 0:
748
+ if (!isCheckout) return [3 /*break*/, 2];
749
+ // This event is a checkout, make sure worker buffer is cleared before
750
+ // proceeding.
751
+ return [4 /*yield*/, this.postMessage({
752
+ id: this.id,
753
+ method: 'init',
754
+ args: [],
755
+ })];
756
+ case 1:
757
+ // This event is a checkout, make sure worker buffer is cleared before
758
+ // proceeding.
759
+ _a.sent();
760
+ _a.label = 2;
761
+ case 2: return [2 /*return*/, this.sendEventToWorker(event)];
676
762
  }
677
763
  });
678
764
  });
679
765
  };
766
+ EventBufferCompressionWorker.prototype.finish = function () {
767
+ return this.finishRequest(this.id);
768
+ };
680
769
  return EventBufferCompressionWorker;
681
770
  }());
682
771
 
@@ -697,10 +786,6 @@ var SentryReplay = /** @class */ (function () {
697
786
  * Buffer of breadcrumbs to be uploaded
698
787
  */
699
788
  this.breadcrumbs = [];
700
- /**
701
- * Buffer of replay spans to be uploaded
702
- */
703
- this.replaySpans = [];
704
789
  /**
705
790
  * List of PerformanceEntry from PerformanceObserver
706
791
  */
@@ -721,6 +806,11 @@ var SentryReplay = /** @class */ (function () {
721
806
  * immediately before sending recording)
722
807
  */
723
808
  this.needsCaptureReplay = false;
809
+ this.context = {
810
+ errorIds: new Set(),
811
+ traceIds: new Set(),
812
+ urls: [],
813
+ };
724
814
  /**
725
815
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
726
816
  * events as a tag. Also handles the case where we only want to capture a reply
@@ -729,11 +819,21 @@ var SentryReplay = /** @class */ (function () {
729
819
  this.handleGlobalEvent = function (event) {
730
820
  var _a;
731
821
  // Do not apply replayId to the root event
732
- if (event.message === ROOT_REPLAY_NAME ||
733
- ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
822
+ if (
823
+ // @ts-expect-error new event type
824
+ event.type === REPLAY_EVENT_NAME) {
825
+ // Replays have separate set of breadcrumbs, do not include breadcrumbs
826
+ // from core SDK
827
+ delete event.breadcrumbs;
734
828
  return event;
735
829
  }
736
830
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
831
+ if (event.type === 'transaction') {
832
+ _this.context.traceIds.add(String(((_a = event.contexts) === null || _a === void 0 ? void 0 : _a.trace.trace_id) || ''));
833
+ return event;
834
+ }
835
+ // XXX: Is it safe to assume that all other events are error events?
836
+ _this.context.errorIds.add(event.event_id);
737
837
  // Need to be very careful that this does not cause an infinite loop
738
838
  if (_this.options.captureOnlyOnError && event.exception) {
739
839
  // TODO: Do we continue to record after?
@@ -824,25 +924,35 @@ var SentryReplay = /** @class */ (function () {
824
924
  /**
825
925
  * Handler for Sentry Core SDK events.
826
926
  *
827
- * Transforms core SDK events into replay events.
927
+ * These specific events will create span-like objects in the recording.
828
928
  *
829
929
  */
830
- this.handleCoreListener = function (type) { return function (handlerData) {
831
- var handlerMap = {
832
- scope: [handleScope, 'breadcrumb'],
833
- dom: [handleDom, 'breadcrumb'],
834
- fetch: [handleFetch, 'span'],
835
- xhr: [handleXhr, 'span'],
836
- };
837
- if (!(type in handlerMap)) {
838
- throw new Error("No handler defined for type: ".concat(type));
930
+ this.handleCoreSpanListener = function (type) { return function (handlerData) {
931
+ var handler = getSpanHandler(type);
932
+ var result = handler(handlerData);
933
+ if (result === null) {
934
+ return;
935
+ }
936
+ if (type === 'history') {
937
+ // Need to collect visited URLs
938
+ _this.context.urls.push(result.name);
839
939
  }
840
- var _a = handlerMap[type], handlerFn = _a[0], eventType = _a[1];
841
- var result = handlerFn(handlerData);
940
+ _this.addUpdate(function () {
941
+ _this.createPerformanceSpans([result]);
942
+ });
943
+ }; };
944
+ /**
945
+ * Handler for Sentry Core SDK events.
946
+ *
947
+ * These events will create breadcrumb-like objects in the recording.
948
+ */
949
+ this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
950
+ var handler = getBreadcrumbHandler(type);
951
+ var result = handler(handlerData);
842
952
  if (result === null) {
843
953
  return;
844
954
  }
845
- if (['sentry.transaction'].includes(result.category)) {
955
+ if (result.category === 'sentry.transaction') {
846
956
  return;
847
957
  }
848
958
  _this.addUpdate(function () {
@@ -850,10 +960,9 @@ var SentryReplay = /** @class */ (function () {
850
960
  type: EventType.Custom,
851
961
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
852
962
  // but maybe we should just keep them as milliseconds
853
- timestamp: result.timestamp * 1000 ||
854
- result.startTimestamp * 1000,
963
+ timestamp: result.timestamp * 1000,
855
964
  data: {
856
- tag: eventType,
965
+ tag: 'breadcrumb',
857
966
  payload: result,
858
967
  },
859
968
  });
@@ -884,12 +993,6 @@ var SentryReplay = /** @class */ (function () {
884
993
  this.recordingOptions.checkoutEveryNms = 60000;
885
994
  }
886
995
  }
887
- SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
888
- var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
889
- var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
890
- var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
891
- 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");
892
- };
893
996
  /**
894
997
  * Because we create a transaction in `setupOnce`, we can potentially create a
895
998
  * transaction before some native SDK integrations have run and applied their
@@ -927,12 +1030,15 @@ var SentryReplay = /** @class */ (function () {
927
1030
  // replay ID so that we can reference them later in the UI
928
1031
  addGlobalEventProcessor(this.handleGlobalEvent);
929
1032
  record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1033
+ var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1034
+ var url = "".concat(window.location.origin).concat(urlPath);
930
1035
  // Otherwise, these will be captured after the first flush, which means the
931
1036
  // URL and timestamps could be incorrect
932
1037
  this.initialState = {
933
1038
  timestamp: new Date().getTime(),
934
- url: "".concat(window.location.origin).concat(window.location.pathname),
1039
+ url: url,
935
1040
  };
1041
+ this.context.urls.push(url);
936
1042
  };
937
1043
  /**
938
1044
  * We want to batch uploads of replay events. Save events only if
@@ -989,7 +1095,6 @@ var SentryReplay = /** @class */ (function () {
989
1095
  SentryReplay.prototype.destroy = function () {
990
1096
  logger.log('Destroying instance');
991
1097
  this.removeListeners();
992
- // this.eventBuffer.clear();
993
1098
  };
994
1099
  SentryReplay.prototype.clearSession = function () {
995
1100
  this.session = null;
@@ -1028,8 +1133,11 @@ var SentryReplay = /** @class */ (function () {
1028
1133
  window.addEventListener('beforeunload', this.handleWindowUnload);
1029
1134
  // Listeners from core SDK //
1030
1135
  var scope = getCurrentHub().getScope();
1031
- scope.addScopeListener(this.handleCoreListener('scope'));
1032
- addInstrumentationHandler('dom', this.handleCoreListener('dom'));
1136
+ scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1137
+ addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1138
+ addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1139
+ addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1140
+ addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1033
1141
  // PerformanceObserver //
1034
1142
  if (!('PerformanceObserver' in window)) {
1035
1143
  return;
@@ -1140,13 +1248,13 @@ var SentryReplay = /** @class */ (function () {
1140
1248
  });
1141
1249
  };
1142
1250
  /**
1143
- * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
1251
+ * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
1144
1252
  */
1145
1253
  SentryReplay.prototype.createPerformanceSpans = function (entries) {
1146
1254
  var _this = this;
1147
- entries.forEach(function (_a) {
1255
+ return Promise.all(entries.map(function (_a) {
1148
1256
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1149
- _this.eventBuffer.addEvent({
1257
+ return _this.eventBuffer.addEvent({
1150
1258
  type: EventType.Custom,
1151
1259
  timestamp: start,
1152
1260
  data: {
@@ -1160,7 +1268,7 @@ var SentryReplay = /** @class */ (function () {
1160
1268
  },
1161
1269
  },
1162
1270
  });
1163
- });
1271
+ }));
1164
1272
  };
1165
1273
  /**
1166
1274
  * Observed performance events are added to `this.performanceEvents`. These
@@ -1170,15 +1278,22 @@ var SentryReplay = /** @class */ (function () {
1170
1278
  // Copy and reset entries before processing
1171
1279
  var entries = __spreadArray([], this.performanceEvents, true);
1172
1280
  this.performanceEvents = [];
1173
- // Parse the entries
1174
- var entryEvents = createPerformanceEntries(entries);
1281
+ return this.createPerformanceSpans(createPerformanceEntries(entries));
1282
+ };
1283
+ /**
1284
+ * Create a "span" for the total amount of memory being used by JS objects
1285
+ * (including v8 internal objects).
1286
+ */
1287
+ SentryReplay.prototype.addMemoryEntry = function () {
1175
1288
  // window.performance.memory is a non-standard API and doesn't work on all browsers
1176
1289
  // so we check before creating the event.
1177
- if ('memory' in window.performance) {
1178
- // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
1179
- entryEvents.push(createMemoryEntry(window.performance.memory));
1290
+ if (!('memory' in window.performance)) {
1291
+ return;
1180
1292
  }
1181
- this.createPerformanceSpans(entryEvents);
1293
+ return this.createPerformanceSpans([
1294
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)
1295
+ createMemoryEntry(window.performance.memory),
1296
+ ]);
1182
1297
  };
1183
1298
  /**
1184
1299
  *
@@ -1212,6 +1327,24 @@ var SentryReplay = /** @class */ (function () {
1212
1327
  }
1213
1328
  return this.flushUpdate(lastActivity);
1214
1329
  };
1330
+ /**
1331
+ * Return and clear context
1332
+ */
1333
+ SentryReplay.prototype.popEventContext = function (_a) {
1334
+ var timestamp = _a.timestamp;
1335
+ var context = {
1336
+ session: this.session,
1337
+ initialState: this.initialState,
1338
+ timestamp: timestamp,
1339
+ errorIds: Array.from(this.context.errorIds).filter(Boolean),
1340
+ traceIds: Array.from(this.context.traceIds).filter(Boolean),
1341
+ urls: this.context.urls,
1342
+ };
1343
+ this.context.errorIds.clear();
1344
+ this.context.traceIds.clear();
1345
+ this.context.urls = [];
1346
+ return context;
1347
+ };
1215
1348
  /**
1216
1349
  * Flushes replay event buffer to Sentry.
1217
1350
  *
@@ -1232,28 +1365,37 @@ var SentryReplay = /** @class */ (function () {
1232
1365
  console.error(new Error('[Sentry]: No transaction, no replay'));
1233
1366
  return [2 /*return*/];
1234
1367
  }
1235
- this.addPerformanceEntries();
1368
+ // Since already flushing, ensure other queued flushes are cancelled
1369
+ clearTimeout(this.timeout);
1370
+ return [4 /*yield*/, this.addPerformanceEntries()];
1371
+ case 1:
1372
+ _a.sent();
1236
1373
  if (!this.eventBuffer.length) {
1237
1374
  return [2 /*return*/];
1238
1375
  }
1376
+ // Only attach memory event if eventBuffer is not empty
1377
+ return [4 /*yield*/, this.addMemoryEntry()];
1378
+ case 2:
1379
+ // Only attach memory event if eventBuffer is not empty
1380
+ _a.sent();
1381
+ timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1239
1382
  // Only want to create replay event if session is new
1240
1383
  if (this.needsCaptureReplay) {
1241
1384
  // This event needs to exist before calling `sendReplay`
1242
- captureReplay({ session: this.session, initialState: this.initialState });
1385
+ captureReplay(this.popEventContext({ timestamp: timestamp }));
1243
1386
  this.needsCaptureReplay = false;
1244
1387
  }
1245
1388
  // Reset this to null regardless of `sendReplay` result so that future
1246
1389
  // events will get flushed properly
1247
1390
  this.initialEventTimestampSinceFlush = null;
1248
- _a.label = 1;
1249
- case 1:
1250
- _a.trys.push([1, 4, , 5]);
1251
- timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1391
+ _a.label = 3;
1392
+ case 3:
1393
+ _a.trys.push([3, 6, , 7]);
1252
1394
  return [4 /*yield*/, this.eventBuffer.finish()];
1253
- case 2:
1395
+ case 4:
1254
1396
  recordingData = _a.sent();
1255
1397
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1256
- case 3:
1398
+ case 5:
1257
1399
  _a.sent();
1258
1400
  // The below will only happen after successfully sending replay //
1259
1401
  // TBD: Alternatively we could update this after every rrweb event
@@ -1261,13 +1403,14 @@ var SentryReplay = /** @class */ (function () {
1261
1403
  // of the event is passed as an argument in the case where a timeout
1262
1404
  // occurs.
1263
1405
  this.updateLastActivity(timestamp);
1264
- captureReplayUpdate({ session: this.session, timestamp: timestamp });
1265
- return [3 /*break*/, 5];
1266
- case 4:
1406
+ captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1407
+ return [3 /*break*/, 7];
1408
+ case 6:
1267
1409
  err_1 = _a.sent();
1410
+ captureException(err_1);
1268
1411
  console.error(err_1);
1269
- return [3 /*break*/, 5];
1270
- case 5: return [2 /*return*/];
1412
+ return [3 /*break*/, 7];
1413
+ case 7: return [2 /*return*/];
1271
1414
  }
1272
1415
  });
1273
1416
  });
@@ -1278,27 +1421,41 @@ var SentryReplay = /** @class */ (function () {
1278
1421
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1279
1422
  var endpoint = _a.endpoint, events = _a.events;
1280
1423
  return __awaiter(this, void 0, void 0, function () {
1281
- var formData, payloadBlob;
1424
+ var payloadWithSequence, envelope;
1282
1425
  return __generator(this, function (_b) {
1283
1426
  switch (_b.label) {
1284
1427
  case 0:
1285
- formData = new FormData();
1286
- payloadBlob = new Blob([events], {
1287
- type: 'application/json',
1428
+ payloadWithSequence = createPayload({
1429
+ events: events,
1430
+ headers: {
1431
+ segment_id: this.session.segmentId,
1432
+ },
1288
1433
  });
1289
- logger.log('blob size in bytes: ', payloadBlob.size);
1290
- formData.append('rrweb', payloadBlob, "rrweb-".concat(new Date().getTime(), ".json"));
1434
+ envelope = createEnvelope({
1435
+ event_id: this.session.id,
1436
+ sent_at: new Date().toISOString(),
1437
+ sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1438
+ }, [
1439
+ [
1440
+ {
1441
+ // @ts-expect-error setting envelope
1442
+ type: 'replay_recording',
1443
+ length: payloadWithSequence.length,
1444
+ },
1445
+ payloadWithSequence,
1446
+ ],
1447
+ ]);
1291
1448
  // If sendBeacon is supported and payload is smol enough...
1292
- if (supportsSendBeacon() && payloadBlob.size <= 65535) {
1449
+ if (supportsSendBeacon() && events.length <= 65536) {
1293
1450
  logger.log("uploading attachment via sendBeacon()");
1294
- window.navigator.sendBeacon(endpoint, formData);
1451
+ window.navigator.sendBeacon(endpoint, serializeEnvelope(envelope));
1295
1452
  return [2 /*return*/];
1296
1453
  }
1297
1454
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1298
1455
  logger.log("uploading attachment via fetch()");
1299
1456
  return [4 /*yield*/, fetch(endpoint, {
1300
1457
  method: 'POST',
1301
- body: formData,
1458
+ body: serializeEnvelope(envelope),
1302
1459
  })];
1303
1460
  case 1:
1304
1461
  _b.sent();
@@ -1326,7 +1483,7 @@ var SentryReplay = /** @class */ (function () {
1326
1483
  return [2 /*return*/];
1327
1484
  }
1328
1485
  client = getCurrentHub().getClient();
1329
- endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
1486
+ endpoint = getEnvelopeEndpointWithUrlEncodedAuth(client.getDsn());
1330
1487
  _b.label = 1;
1331
1488
  case 1:
1332
1489
  _b.trys.push([1, 3, , 8]);