@dev-2-dev/websdk-plugin-session-tracker 0.9.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.
@@ -0,0 +1,4893 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ var NodeType;
5
+ (function (NodeType) {
6
+ NodeType[NodeType["Document"] = 0] = "Document";
7
+ NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
8
+ NodeType[NodeType["Element"] = 2] = "Element";
9
+ NodeType[NodeType["Text"] = 3] = "Text";
10
+ NodeType[NodeType["CDATA"] = 4] = "CDATA";
11
+ NodeType[NodeType["Comment"] = 5] = "Comment";
12
+ })(NodeType || (NodeType = {}));
13
+
14
+ function isElement(n) {
15
+ return n.nodeType === n.ELEMENT_NODE;
16
+ }
17
+ function isShadowRoot(n) {
18
+ var host = n === null || n === void 0 ? void 0 : n.host;
19
+ return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);
20
+ }
21
+ function isNativeShadowDom(shadowRoot) {
22
+ return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';
23
+ }
24
+ function fixBrowserCompatibilityIssuesInCSS(cssText) {
25
+ if (cssText.includes(' background-clip: text;') &&
26
+ !cssText.includes(' -webkit-background-clip: text;')) {
27
+ cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');
28
+ }
29
+ return cssText;
30
+ }
31
+ function getCssRulesString(s) {
32
+ try {
33
+ var rules = s.rules || s.cssRules;
34
+ return rules
35
+ ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(getCssRuleString).join(''))
36
+ : null;
37
+ }
38
+ catch (error) {
39
+ return null;
40
+ }
41
+ }
42
+ function getCssRuleString(rule) {
43
+ var cssStringified = rule.cssText;
44
+ if (isCSSImportRule(rule)) {
45
+ try {
46
+ cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;
47
+ }
48
+ catch (_a) {
49
+ }
50
+ }
51
+ return cssStringified;
52
+ }
53
+ function isCSSImportRule(rule) {
54
+ return 'styleSheet' in rule;
55
+ }
56
+ var Mirror = (function () {
57
+ function Mirror() {
58
+ this.idNodeMap = new Map();
59
+ this.nodeMetaMap = new WeakMap();
60
+ }
61
+ Mirror.prototype.getId = function (n) {
62
+ var _a;
63
+ if (!n)
64
+ return -1;
65
+ var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
66
+ return id !== null && id !== void 0 ? id : -1;
67
+ };
68
+ Mirror.prototype.getNode = function (id) {
69
+ return this.idNodeMap.get(id) || null;
70
+ };
71
+ Mirror.prototype.getIds = function () {
72
+ return Array.from(this.idNodeMap.keys());
73
+ };
74
+ Mirror.prototype.getMeta = function (n) {
75
+ return this.nodeMetaMap.get(n) || null;
76
+ };
77
+ Mirror.prototype.removeNodeFromMap = function (n) {
78
+ var _this = this;
79
+ var id = this.getId(n);
80
+ this.idNodeMap["delete"](id);
81
+ if (n.childNodes) {
82
+ n.childNodes.forEach(function (childNode) {
83
+ return _this.removeNodeFromMap(childNode);
84
+ });
85
+ }
86
+ };
87
+ Mirror.prototype.has = function (id) {
88
+ return this.idNodeMap.has(id);
89
+ };
90
+ Mirror.prototype.hasNode = function (node) {
91
+ return this.nodeMetaMap.has(node);
92
+ };
93
+ Mirror.prototype.add = function (n, meta) {
94
+ var id = meta.id;
95
+ this.idNodeMap.set(id, n);
96
+ this.nodeMetaMap.set(n, meta);
97
+ };
98
+ Mirror.prototype.replace = function (id, n) {
99
+ var oldNode = this.getNode(id);
100
+ if (oldNode) {
101
+ var meta = this.nodeMetaMap.get(oldNode);
102
+ if (meta)
103
+ this.nodeMetaMap.set(n, meta);
104
+ }
105
+ this.idNodeMap.set(id, n);
106
+ };
107
+ Mirror.prototype.reset = function () {
108
+ this.idNodeMap = new Map();
109
+ this.nodeMetaMap = new WeakMap();
110
+ };
111
+ return Mirror;
112
+ }());
113
+ function createMirror() {
114
+ return new Mirror();
115
+ }
116
+ function maskInputValue(_a) {
117
+ var maskInputOptions = _a.maskInputOptions, tagName = _a.tagName, type = _a.type, value = _a.value, maskInputFn = _a.maskInputFn;
118
+ var text = value || '';
119
+ if (maskInputOptions[tagName.toLowerCase()] ||
120
+ maskInputOptions[type]) {
121
+ if (maskInputFn) {
122
+ text = maskInputFn(text);
123
+ }
124
+ else {
125
+ text = '*'.repeat(text.length);
126
+ }
127
+ }
128
+ return text;
129
+ }
130
+ var ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';
131
+ function is2DCanvasBlank(canvas) {
132
+ var ctx = canvas.getContext('2d');
133
+ if (!ctx)
134
+ return true;
135
+ var chunkSize = 50;
136
+ for (var x = 0; x < canvas.width; x += chunkSize) {
137
+ for (var y = 0; y < canvas.height; y += chunkSize) {
138
+ var getImageData = ctx.getImageData;
139
+ var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData
140
+ ? getImageData[ORIGINAL_ATTRIBUTE_NAME]
141
+ : getImageData;
142
+ var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);
143
+ if (pixelBuffer.some(function (pixel) { return pixel !== 0; }))
144
+ return false;
145
+ }
146
+ }
147
+ return true;
148
+ }
149
+
150
+ var _id = 1;
151
+ var tagNameRegex = new RegExp('[^a-z0-9-_:]');
152
+ var IGNORED_NODE = -2;
153
+ function genId() {
154
+ return _id++;
155
+ }
156
+ function getValidTagName(element) {
157
+ if (element instanceof HTMLFormElement) {
158
+ return 'form';
159
+ }
160
+ var processedTagName = element.tagName.toLowerCase().trim();
161
+ if (tagNameRegex.test(processedTagName)) {
162
+ return 'div';
163
+ }
164
+ return processedTagName;
165
+ }
166
+ function stringifyStyleSheet(sheet) {
167
+ return sheet.cssRules
168
+ ? Array.from(sheet.cssRules)
169
+ .map(function (rule) { return rule.cssText || ''; })
170
+ .join('')
171
+ : '';
172
+ }
173
+ function extractOrigin(url) {
174
+ var origin = '';
175
+ if (url.indexOf('//') > -1) {
176
+ origin = url.split('/').slice(0, 3).join('/');
177
+ }
178
+ else {
179
+ origin = url.split('/')[0];
180
+ }
181
+ origin = origin.split('?')[0];
182
+ return origin;
183
+ }
184
+ var canvasService;
185
+ var canvasCtx;
186
+ var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
187
+ var RELATIVE_PATH = /^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/;
188
+ var DATA_URI = /^(data:)([^,]*),(.*)/i;
189
+ function absoluteToStylesheet(cssText, href) {
190
+ return (cssText || '').replace(URL_IN_CSS_REF, function (origin, quote1, path1, quote2, path2, path3) {
191
+ var filePath = path1 || path2 || path3;
192
+ var maybeQuote = quote1 || quote2 || '';
193
+ if (!filePath) {
194
+ return origin;
195
+ }
196
+ if (!RELATIVE_PATH.test(filePath)) {
197
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
198
+ }
199
+ if (DATA_URI.test(filePath)) {
200
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
201
+ }
202
+ if (filePath[0] === '/') {
203
+ return "url(".concat(maybeQuote).concat(extractOrigin(href) + filePath).concat(maybeQuote, ")");
204
+ }
205
+ var stack = href.split('/');
206
+ var parts = filePath.split('/');
207
+ stack.pop();
208
+ for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
209
+ var part = parts_1[_i];
210
+ if (part === '.') {
211
+ continue;
212
+ }
213
+ else if (part === '..') {
214
+ stack.pop();
215
+ }
216
+ else {
217
+ stack.push(part);
218
+ }
219
+ }
220
+ return "url(".concat(maybeQuote).concat(stack.join('/')).concat(maybeQuote, ")");
221
+ });
222
+ }
223
+ var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
224
+ var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
225
+ function getAbsoluteSrcsetString(doc, attributeValue) {
226
+ if (attributeValue.trim() === '') {
227
+ return attributeValue;
228
+ }
229
+ var pos = 0;
230
+ function collectCharacters(regEx) {
231
+ var chars;
232
+ var match = regEx.exec(attributeValue.substring(pos));
233
+ if (match) {
234
+ chars = match[0];
235
+ pos += chars.length;
236
+ return chars;
237
+ }
238
+ return '';
239
+ }
240
+ var output = [];
241
+ while (true) {
242
+ collectCharacters(SRCSET_COMMAS_OR_SPACES);
243
+ if (pos >= attributeValue.length) {
244
+ break;
245
+ }
246
+ var url = collectCharacters(SRCSET_NOT_SPACES);
247
+ if (url.slice(-1) === ',') {
248
+ url = absoluteToDoc(doc, url.substring(0, url.length - 1));
249
+ output.push(url);
250
+ }
251
+ else {
252
+ var descriptorsStr = '';
253
+ url = absoluteToDoc(doc, url);
254
+ var inParens = false;
255
+ while (true) {
256
+ var c = attributeValue.charAt(pos);
257
+ if (c === '') {
258
+ output.push((url + descriptorsStr).trim());
259
+ break;
260
+ }
261
+ else if (!inParens) {
262
+ if (c === ',') {
263
+ pos += 1;
264
+ output.push((url + descriptorsStr).trim());
265
+ break;
266
+ }
267
+ else if (c === '(') {
268
+ inParens = true;
269
+ }
270
+ }
271
+ else {
272
+ if (c === ')') {
273
+ inParens = false;
274
+ }
275
+ }
276
+ descriptorsStr += c;
277
+ pos += 1;
278
+ }
279
+ }
280
+ }
281
+ return output.join(', ');
282
+ }
283
+ function absoluteToDoc(doc, attributeValue) {
284
+ if (!attributeValue || attributeValue.trim() === '') {
285
+ return attributeValue;
286
+ }
287
+ var a = doc.createElement('a');
288
+ a.href = attributeValue;
289
+ return a.href;
290
+ }
291
+ function isSVGElement(el) {
292
+ return Boolean(el.tagName === 'svg' || el.ownerSVGElement);
293
+ }
294
+ function getHref() {
295
+ var a = document.createElement('a');
296
+ a.href = '';
297
+ return a.href;
298
+ }
299
+ function transformAttribute(doc, tagName, name, value) {
300
+ if (name === 'src' ||
301
+ (name === 'href' && value && !(tagName === 'use' && value[0] === '#'))) {
302
+ return absoluteToDoc(doc, value);
303
+ }
304
+ else if (name === 'xlink:href' && value && value[0] !== '#') {
305
+ return absoluteToDoc(doc, value);
306
+ }
307
+ else if (name === 'background' &&
308
+ value &&
309
+ (tagName === 'table' || tagName === 'td' || tagName === 'th')) {
310
+ return absoluteToDoc(doc, value);
311
+ }
312
+ else if (name === 'srcset' && value) {
313
+ return getAbsoluteSrcsetString(doc, value);
314
+ }
315
+ else if (name === 'style' && value) {
316
+ return absoluteToStylesheet(value, getHref());
317
+ }
318
+ else if (tagName === 'object' && name === 'data' && value) {
319
+ return absoluteToDoc(doc, value);
320
+ }
321
+ else {
322
+ return value;
323
+ }
324
+ }
325
+ function _isBlockedElement(element, blockClass, blockSelector) {
326
+ if (typeof blockClass === 'string') {
327
+ if (element.classList.contains(blockClass)) {
328
+ return true;
329
+ }
330
+ }
331
+ else {
332
+ for (var eIndex = element.classList.length; eIndex--;) {
333
+ var className = element.classList[eIndex];
334
+ if (blockClass.test(className)) {
335
+ return true;
336
+ }
337
+ }
338
+ }
339
+ if (blockSelector) {
340
+ return element.matches(blockSelector);
341
+ }
342
+ return false;
343
+ }
344
+ function classMatchesRegex(node, regex, checkAncestors) {
345
+ if (!node)
346
+ return false;
347
+ if (node.nodeType !== node.ELEMENT_NODE) {
348
+ if (!checkAncestors)
349
+ return false;
350
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
351
+ }
352
+ for (var eIndex = node.classList.length; eIndex--;) {
353
+ var className = node.classList[eIndex];
354
+ if (regex.test(className)) {
355
+ return true;
356
+ }
357
+ }
358
+ if (!checkAncestors)
359
+ return false;
360
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
361
+ }
362
+ function needMaskingText(node, maskTextClass, maskTextSelector) {
363
+ var el = node.nodeType === node.ELEMENT_NODE
364
+ ? node
365
+ : node.parentElement;
366
+ if (el === null)
367
+ return false;
368
+ if (typeof maskTextClass === 'string') {
369
+ if (el.classList.contains(maskTextClass))
370
+ return true;
371
+ if (el.closest(".".concat(maskTextClass)))
372
+ return true;
373
+ }
374
+ else {
375
+ if (classMatchesRegex(el, maskTextClass, true))
376
+ return true;
377
+ }
378
+ if (maskTextSelector) {
379
+ if (el.matches(maskTextSelector))
380
+ return true;
381
+ if (el.closest(maskTextSelector))
382
+ return true;
383
+ }
384
+ return false;
385
+ }
386
+ function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
387
+ var win = iframeEl.contentWindow;
388
+ if (!win) {
389
+ return;
390
+ }
391
+ var fired = false;
392
+ var readyState;
393
+ try {
394
+ readyState = win.document.readyState;
395
+ }
396
+ catch (error) {
397
+ return;
398
+ }
399
+ if (readyState !== 'complete') {
400
+ var timer_1 = setTimeout(function () {
401
+ if (!fired) {
402
+ listener();
403
+ fired = true;
404
+ }
405
+ }, iframeLoadTimeout);
406
+ iframeEl.addEventListener('load', function () {
407
+ clearTimeout(timer_1);
408
+ fired = true;
409
+ listener();
410
+ });
411
+ return;
412
+ }
413
+ var blankUrl = 'about:blank';
414
+ if (win.location.href !== blankUrl ||
415
+ iframeEl.src === blankUrl ||
416
+ iframeEl.src === '') {
417
+ setTimeout(listener, 0);
418
+ return iframeEl.addEventListener('load', listener);
419
+ }
420
+ iframeEl.addEventListener('load', listener);
421
+ }
422
+ function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
423
+ var fired = false;
424
+ var styleSheetLoaded;
425
+ try {
426
+ styleSheetLoaded = link.sheet;
427
+ }
428
+ catch (error) {
429
+ return;
430
+ }
431
+ if (styleSheetLoaded)
432
+ return;
433
+ var timer = setTimeout(function () {
434
+ if (!fired) {
435
+ listener();
436
+ fired = true;
437
+ }
438
+ }, styleSheetLoadTimeout);
439
+ link.addEventListener('load', function () {
440
+ clearTimeout(timer);
441
+ fired = true;
442
+ listener();
443
+ });
444
+ }
445
+ function serializeNode(n, options) {
446
+ var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c;
447
+ var rootId = getRootId(doc, mirror);
448
+ switch (n.nodeType) {
449
+ case n.DOCUMENT_NODE:
450
+ if (n.compatMode !== 'CSS1Compat') {
451
+ return {
452
+ type: NodeType.Document,
453
+ childNodes: [],
454
+ compatMode: n.compatMode
455
+ };
456
+ }
457
+ else {
458
+ return {
459
+ type: NodeType.Document,
460
+ childNodes: []
461
+ };
462
+ }
463
+ case n.DOCUMENT_TYPE_NODE:
464
+ return {
465
+ type: NodeType.DocumentType,
466
+ name: n.name,
467
+ publicId: n.publicId,
468
+ systemId: n.systemId,
469
+ rootId: rootId
470
+ };
471
+ case n.ELEMENT_NODE:
472
+ return serializeElementNode(n, {
473
+ doc: doc,
474
+ blockClass: blockClass,
475
+ blockSelector: blockSelector,
476
+ inlineStylesheet: inlineStylesheet,
477
+ maskInputOptions: maskInputOptions,
478
+ maskInputFn: maskInputFn,
479
+ dataURLOptions: dataURLOptions,
480
+ inlineImages: inlineImages,
481
+ recordCanvas: recordCanvas,
482
+ keepIframeSrcFn: keepIframeSrcFn,
483
+ newlyAddedElement: newlyAddedElement,
484
+ rootId: rootId
485
+ });
486
+ case n.TEXT_NODE:
487
+ return serializeTextNode(n, {
488
+ maskTextClass: maskTextClass,
489
+ maskTextSelector: maskTextSelector,
490
+ maskTextFn: maskTextFn,
491
+ rootId: rootId
492
+ });
493
+ case n.CDATA_SECTION_NODE:
494
+ return {
495
+ type: NodeType.CDATA,
496
+ textContent: '',
497
+ rootId: rootId
498
+ };
499
+ case n.COMMENT_NODE:
500
+ return {
501
+ type: NodeType.Comment,
502
+ textContent: n.textContent || '',
503
+ rootId: rootId
504
+ };
505
+ default:
506
+ return false;
507
+ }
508
+ }
509
+ function getRootId(doc, mirror) {
510
+ if (!mirror.hasNode(doc))
511
+ return undefined;
512
+ var docId = mirror.getId(doc);
513
+ return docId === 1 ? undefined : docId;
514
+ }
515
+ function serializeTextNode(n, options) {
516
+ var _a;
517
+ var maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, maskTextFn = options.maskTextFn, rootId = options.rootId;
518
+ var parentTagName = n.parentNode && n.parentNode.tagName;
519
+ var textContent = n.textContent;
520
+ var isStyle = parentTagName === 'STYLE' ? true : undefined;
521
+ var isScript = parentTagName === 'SCRIPT' ? true : undefined;
522
+ if (isStyle && textContent) {
523
+ try {
524
+ if (n.nextSibling || n.previousSibling) {
525
+ }
526
+ else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {
527
+ textContent = stringifyStyleSheet(n.parentNode.sheet);
528
+ }
529
+ }
530
+ catch (err) {
531
+ console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(err), n);
532
+ }
533
+ textContent = absoluteToStylesheet(textContent, getHref());
534
+ }
535
+ if (isScript) {
536
+ textContent = 'SCRIPT_PLACEHOLDER';
537
+ }
538
+ if (!isStyle &&
539
+ !isScript &&
540
+ textContent &&
541
+ needMaskingText(n, maskTextClass, maskTextSelector)) {
542
+ textContent = maskTextFn
543
+ ? maskTextFn(textContent)
544
+ : textContent.replace(/[\S]/g, '*');
545
+ }
546
+ return {
547
+ type: NodeType.Text,
548
+ textContent: textContent || '',
549
+ isStyle: isStyle,
550
+ rootId: rootId
551
+ };
552
+ }
553
+ function serializeElementNode(n, options) {
554
+ var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c, rootId = options.rootId;
555
+ var needBlock = _isBlockedElement(n, blockClass, blockSelector);
556
+ var tagName = getValidTagName(n);
557
+ var attributes = {};
558
+ var len = n.attributes.length;
559
+ for (var i = 0; i < len; i++) {
560
+ var attr = n.attributes[i];
561
+ attributes[attr.name] = transformAttribute(doc, tagName, attr.name, attr.value);
562
+ }
563
+ if (tagName === 'link' && inlineStylesheet) {
564
+ var stylesheet = Array.from(doc.styleSheets).find(function (s) {
565
+ return s.href === n.href;
566
+ });
567
+ var cssText = null;
568
+ if (stylesheet) {
569
+ cssText = getCssRulesString(stylesheet);
570
+ }
571
+ if (cssText) {
572
+ delete attributes.rel;
573
+ delete attributes.href;
574
+ attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
575
+ }
576
+ }
577
+ if (tagName === 'style' &&
578
+ n.sheet &&
579
+ !(n.innerText || n.textContent || '').trim().length) {
580
+ var cssText = getCssRulesString(n.sheet);
581
+ if (cssText) {
582
+ attributes._cssText = absoluteToStylesheet(cssText, getHref());
583
+ }
584
+ }
585
+ if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
586
+ var value = n.value;
587
+ var checked = n.checked;
588
+ if (attributes.type !== 'radio' &&
589
+ attributes.type !== 'checkbox' &&
590
+ attributes.type !== 'submit' &&
591
+ attributes.type !== 'button' &&
592
+ value) {
593
+ attributes.value = maskInputValue({
594
+ type: attributes.type,
595
+ tagName: tagName,
596
+ value: value,
597
+ maskInputOptions: maskInputOptions,
598
+ maskInputFn: maskInputFn
599
+ });
600
+ }
601
+ else if (checked) {
602
+ attributes.checked = checked;
603
+ }
604
+ }
605
+ if (tagName === 'option') {
606
+ if (n.selected && !maskInputOptions['select']) {
607
+ attributes.selected = true;
608
+ }
609
+ else {
610
+ delete attributes.selected;
611
+ }
612
+ }
613
+ if (tagName === 'canvas' && recordCanvas) {
614
+ if (n.__context === '2d') {
615
+ if (!is2DCanvasBlank(n)) {
616
+ attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
617
+ }
618
+ }
619
+ else if (!('__context' in n)) {
620
+ var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
621
+ var blankCanvas = document.createElement('canvas');
622
+ blankCanvas.width = n.width;
623
+ blankCanvas.height = n.height;
624
+ var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
625
+ if (canvasDataURL !== blankCanvasDataURL) {
626
+ attributes.rr_dataURL = canvasDataURL;
627
+ }
628
+ }
629
+ }
630
+ if (tagName === 'img' && inlineImages) {
631
+ if (!canvasService) {
632
+ canvasService = doc.createElement('canvas');
633
+ canvasCtx = canvasService.getContext('2d');
634
+ }
635
+ var image_1 = n;
636
+ var oldValue_1 = image_1.crossOrigin;
637
+ image_1.crossOrigin = 'anonymous';
638
+ var recordInlineImage = function () {
639
+ try {
640
+ canvasService.width = image_1.naturalWidth;
641
+ canvasService.height = image_1.naturalHeight;
642
+ canvasCtx.drawImage(image_1, 0, 0);
643
+ attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
644
+ }
645
+ catch (err) {
646
+ console.warn("Cannot inline img src=".concat(image_1.currentSrc, "! Error: ").concat(err));
647
+ }
648
+ oldValue_1
649
+ ? (attributes.crossOrigin = oldValue_1)
650
+ : image_1.removeAttribute('crossorigin');
651
+ };
652
+ if (image_1.complete && image_1.naturalWidth !== 0)
653
+ recordInlineImage();
654
+ else
655
+ image_1.onload = recordInlineImage;
656
+ }
657
+ if (tagName === 'audio' || tagName === 'video') {
658
+ attributes.rr_mediaState = n.paused
659
+ ? 'paused'
660
+ : 'played';
661
+ attributes.rr_mediaCurrentTime = n.currentTime;
662
+ }
663
+ if (!newlyAddedElement) {
664
+ if (n.scrollLeft) {
665
+ attributes.rr_scrollLeft = n.scrollLeft;
666
+ }
667
+ if (n.scrollTop) {
668
+ attributes.rr_scrollTop = n.scrollTop;
669
+ }
670
+ }
671
+ if (needBlock) {
672
+ var _d = n.getBoundingClientRect(), width = _d.width, height = _d.height;
673
+ attributes = {
674
+ "class": attributes["class"],
675
+ rr_width: "".concat(width, "px"),
676
+ rr_height: "".concat(height, "px")
677
+ };
678
+ }
679
+ if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {
680
+ if (!n.contentDocument) {
681
+ attributes.rr_src = attributes.src;
682
+ }
683
+ delete attributes.src;
684
+ }
685
+ return {
686
+ type: NodeType.Element,
687
+ tagName: tagName,
688
+ attributes: attributes,
689
+ childNodes: [],
690
+ isSVG: isSVGElement(n) || undefined,
691
+ needBlock: needBlock,
692
+ rootId: rootId
693
+ };
694
+ }
695
+ function lowerIfExists(maybeAttr) {
696
+ if (maybeAttr === undefined) {
697
+ return '';
698
+ }
699
+ else {
700
+ return maybeAttr.toLowerCase();
701
+ }
702
+ }
703
+ function slimDOMExcluded(sn, slimDOMOptions) {
704
+ if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
705
+ return true;
706
+ }
707
+ else if (sn.type === NodeType.Element) {
708
+ if (slimDOMOptions.script &&
709
+ (sn.tagName === 'script' ||
710
+ (sn.tagName === 'link' &&
711
+ sn.attributes.rel === 'preload' &&
712
+ sn.attributes.as === 'script') ||
713
+ (sn.tagName === 'link' &&
714
+ sn.attributes.rel === 'prefetch' &&
715
+ typeof sn.attributes.href === 'string' &&
716
+ sn.attributes.href.endsWith('.js')))) {
717
+ return true;
718
+ }
719
+ else if (slimDOMOptions.headFavicon &&
720
+ ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||
721
+ (sn.tagName === 'meta' &&
722
+ (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||
723
+ lowerIfExists(sn.attributes.name) === 'application-name' ||
724
+ lowerIfExists(sn.attributes.rel) === 'icon' ||
725
+ lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||
726
+ lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {
727
+ return true;
728
+ }
729
+ else if (sn.tagName === 'meta') {
730
+ if (slimDOMOptions.headMetaDescKeywords &&
731
+ lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
732
+ return true;
733
+ }
734
+ else if (slimDOMOptions.headMetaSocial &&
735
+ (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||
736
+ lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||
737
+ lowerIfExists(sn.attributes.name) === 'pinterest')) {
738
+ return true;
739
+ }
740
+ else if (slimDOMOptions.headMetaRobots &&
741
+ (lowerIfExists(sn.attributes.name) === 'robots' ||
742
+ lowerIfExists(sn.attributes.name) === 'googlebot' ||
743
+ lowerIfExists(sn.attributes.name) === 'bingbot')) {
744
+ return true;
745
+ }
746
+ else if (slimDOMOptions.headMetaHttpEquiv &&
747
+ sn.attributes['http-equiv'] !== undefined) {
748
+ return true;
749
+ }
750
+ else if (slimDOMOptions.headMetaAuthorship &&
751
+ (lowerIfExists(sn.attributes.name) === 'author' ||
752
+ lowerIfExists(sn.attributes.name) === 'generator' ||
753
+ lowerIfExists(sn.attributes.name) === 'framework' ||
754
+ lowerIfExists(sn.attributes.name) === 'publisher' ||
755
+ lowerIfExists(sn.attributes.name) === 'progid' ||
756
+ lowerIfExists(sn.attributes.property).match(/^article:/) ||
757
+ lowerIfExists(sn.attributes.property).match(/^product:/))) {
758
+ return true;
759
+ }
760
+ else if (slimDOMOptions.headMetaVerification &&
761
+ (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||
762
+ lowerIfExists(sn.attributes.name) === 'yandex-verification' ||
763
+ lowerIfExists(sn.attributes.name) === 'csrf-token' ||
764
+ lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||
765
+ lowerIfExists(sn.attributes.name) === 'verify-v1' ||
766
+ lowerIfExists(sn.attributes.name) === 'verification' ||
767
+ lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {
768
+ return true;
769
+ }
770
+ }
771
+ }
772
+ return false;
773
+ }
774
+ function serializeNodeWithId(n, options) {
775
+ var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.inlineStylesheet, inlineStylesheet = _b === void 0 ? true : _b, _c = options.maskInputOptions, maskInputOptions = _c === void 0 ? {} : _c, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _d = options.dataURLOptions, dataURLOptions = _d === void 0 ? {} : _d, _e = options.inlineImages, inlineImages = _e === void 0 ? false : _e, _f = options.recordCanvas, recordCanvas = _f === void 0 ? false : _f, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _g = options.iframeLoadTimeout, iframeLoadTimeout = _g === void 0 ? 5000 : _g, onStylesheetLoad = options.onStylesheetLoad, _h = options.stylesheetLoadTimeout, stylesheetLoadTimeout = _h === void 0 ? 5000 : _h, _j = options.keepIframeSrcFn, keepIframeSrcFn = _j === void 0 ? function () { return false; } : _j, _k = options.newlyAddedElement, newlyAddedElement = _k === void 0 ? false : _k;
776
+ var _l = options.preserveWhiteSpace, preserveWhiteSpace = _l === void 0 ? true : _l;
777
+ var _serializedNode = serializeNode(n, {
778
+ doc: doc,
779
+ mirror: mirror,
780
+ blockClass: blockClass,
781
+ blockSelector: blockSelector,
782
+ maskTextClass: maskTextClass,
783
+ maskTextSelector: maskTextSelector,
784
+ inlineStylesheet: inlineStylesheet,
785
+ maskInputOptions: maskInputOptions,
786
+ maskTextFn: maskTextFn,
787
+ maskInputFn: maskInputFn,
788
+ dataURLOptions: dataURLOptions,
789
+ inlineImages: inlineImages,
790
+ recordCanvas: recordCanvas,
791
+ keepIframeSrcFn: keepIframeSrcFn,
792
+ newlyAddedElement: newlyAddedElement
793
+ });
794
+ if (!_serializedNode) {
795
+ console.warn(n, 'not serialized');
796
+ return null;
797
+ }
798
+ var id;
799
+ if (mirror.hasNode(n)) {
800
+ id = mirror.getId(n);
801
+ }
802
+ else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||
803
+ (!preserveWhiteSpace &&
804
+ _serializedNode.type === NodeType.Text &&
805
+ !_serializedNode.isStyle &&
806
+ !_serializedNode.textContent.replace(/^\s+|\s+$/gm, '').length)) {
807
+ id = IGNORED_NODE;
808
+ }
809
+ else {
810
+ id = genId();
811
+ }
812
+ var serializedNode = Object.assign(_serializedNode, { id: id });
813
+ mirror.add(n, serializedNode);
814
+ if (id === IGNORED_NODE) {
815
+ return null;
816
+ }
817
+ if (onSerialize) {
818
+ onSerialize(n);
819
+ }
820
+ var recordChild = !skipChild;
821
+ if (serializedNode.type === NodeType.Element) {
822
+ recordChild = recordChild && !serializedNode.needBlock;
823
+ delete serializedNode.needBlock;
824
+ var shadowRoot = n.shadowRoot;
825
+ if (shadowRoot && isNativeShadowDom(shadowRoot))
826
+ serializedNode.isShadowHost = true;
827
+ }
828
+ if ((serializedNode.type === NodeType.Document ||
829
+ serializedNode.type === NodeType.Element) &&
830
+ recordChild) {
831
+ if (slimDOMOptions.headWhitespace &&
832
+ serializedNode.type === NodeType.Element &&
833
+ serializedNode.tagName === 'head') {
834
+ preserveWhiteSpace = false;
835
+ }
836
+ var bypassOptions = {
837
+ doc: doc,
838
+ mirror: mirror,
839
+ blockClass: blockClass,
840
+ blockSelector: blockSelector,
841
+ maskTextClass: maskTextClass,
842
+ maskTextSelector: maskTextSelector,
843
+ skipChild: skipChild,
844
+ inlineStylesheet: inlineStylesheet,
845
+ maskInputOptions: maskInputOptions,
846
+ maskTextFn: maskTextFn,
847
+ maskInputFn: maskInputFn,
848
+ slimDOMOptions: slimDOMOptions,
849
+ dataURLOptions: dataURLOptions,
850
+ inlineImages: inlineImages,
851
+ recordCanvas: recordCanvas,
852
+ preserveWhiteSpace: preserveWhiteSpace,
853
+ onSerialize: onSerialize,
854
+ onIframeLoad: onIframeLoad,
855
+ iframeLoadTimeout: iframeLoadTimeout,
856
+ onStylesheetLoad: onStylesheetLoad,
857
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
858
+ keepIframeSrcFn: keepIframeSrcFn
859
+ };
860
+ for (var _i = 0, _m = Array.from(n.childNodes); _i < _m.length; _i++) {
861
+ var childN = _m[_i];
862
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
863
+ if (serializedChildNode) {
864
+ serializedNode.childNodes.push(serializedChildNode);
865
+ }
866
+ }
867
+ if (isElement(n) && n.shadowRoot) {
868
+ for (var _o = 0, _p = Array.from(n.shadowRoot.childNodes); _o < _p.length; _o++) {
869
+ var childN = _p[_o];
870
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
871
+ if (serializedChildNode) {
872
+ isNativeShadowDom(n.shadowRoot) &&
873
+ (serializedChildNode.isShadow = true);
874
+ serializedNode.childNodes.push(serializedChildNode);
875
+ }
876
+ }
877
+ }
878
+ }
879
+ if (n.parentNode &&
880
+ isShadowRoot(n.parentNode) &&
881
+ isNativeShadowDom(n.parentNode)) {
882
+ serializedNode.isShadow = true;
883
+ }
884
+ if (serializedNode.type === NodeType.Element &&
885
+ serializedNode.tagName === 'iframe') {
886
+ onceIframeLoaded(n, function () {
887
+ var iframeDoc = n.contentDocument;
888
+ if (iframeDoc && onIframeLoad) {
889
+ var serializedIframeNode = serializeNodeWithId(iframeDoc, {
890
+ doc: iframeDoc,
891
+ mirror: mirror,
892
+ blockClass: blockClass,
893
+ blockSelector: blockSelector,
894
+ maskTextClass: maskTextClass,
895
+ maskTextSelector: maskTextSelector,
896
+ skipChild: false,
897
+ inlineStylesheet: inlineStylesheet,
898
+ maskInputOptions: maskInputOptions,
899
+ maskTextFn: maskTextFn,
900
+ maskInputFn: maskInputFn,
901
+ slimDOMOptions: slimDOMOptions,
902
+ dataURLOptions: dataURLOptions,
903
+ inlineImages: inlineImages,
904
+ recordCanvas: recordCanvas,
905
+ preserveWhiteSpace: preserveWhiteSpace,
906
+ onSerialize: onSerialize,
907
+ onIframeLoad: onIframeLoad,
908
+ iframeLoadTimeout: iframeLoadTimeout,
909
+ onStylesheetLoad: onStylesheetLoad,
910
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
911
+ keepIframeSrcFn: keepIframeSrcFn
912
+ });
913
+ if (serializedIframeNode) {
914
+ onIframeLoad(n, serializedIframeNode);
915
+ }
916
+ }
917
+ }, iframeLoadTimeout);
918
+ }
919
+ if (serializedNode.type === NodeType.Element &&
920
+ serializedNode.tagName === 'link' &&
921
+ serializedNode.attributes.rel === 'stylesheet') {
922
+ onceStylesheetLoaded(n, function () {
923
+ if (onStylesheetLoad) {
924
+ var serializedLinkNode = serializeNodeWithId(n, {
925
+ doc: doc,
926
+ mirror: mirror,
927
+ blockClass: blockClass,
928
+ blockSelector: blockSelector,
929
+ maskTextClass: maskTextClass,
930
+ maskTextSelector: maskTextSelector,
931
+ skipChild: false,
932
+ inlineStylesheet: inlineStylesheet,
933
+ maskInputOptions: maskInputOptions,
934
+ maskTextFn: maskTextFn,
935
+ maskInputFn: maskInputFn,
936
+ slimDOMOptions: slimDOMOptions,
937
+ dataURLOptions: dataURLOptions,
938
+ inlineImages: inlineImages,
939
+ recordCanvas: recordCanvas,
940
+ preserveWhiteSpace: preserveWhiteSpace,
941
+ onSerialize: onSerialize,
942
+ onIframeLoad: onIframeLoad,
943
+ iframeLoadTimeout: iframeLoadTimeout,
944
+ onStylesheetLoad: onStylesheetLoad,
945
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
946
+ keepIframeSrcFn: keepIframeSrcFn
947
+ });
948
+ if (serializedLinkNode) {
949
+ onStylesheetLoad(n, serializedLinkNode);
950
+ }
951
+ }
952
+ }, stylesheetLoadTimeout);
953
+ }
954
+ return serializedNode;
955
+ }
956
+ function snapshot(n, options) {
957
+ var _a = options || {}, _b = _a.mirror, mirror = _b === void 0 ? new Mirror() : _b, _c = _a.blockClass, blockClass = _c === void 0 ? 'rr-block' : _c, _d = _a.blockSelector, blockSelector = _d === void 0 ? null : _d, _e = _a.maskTextClass, maskTextClass = _e === void 0 ? 'rr-mask' : _e, _f = _a.maskTextSelector, maskTextSelector = _f === void 0 ? null : _f, _g = _a.inlineStylesheet, inlineStylesheet = _g === void 0 ? true : _g, _h = _a.inlineImages, inlineImages = _h === void 0 ? false : _h, _j = _a.recordCanvas, recordCanvas = _j === void 0 ? false : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? false : _k, maskTextFn = _a.maskTextFn, maskInputFn = _a.maskInputFn, _l = _a.slimDOM, slimDOM = _l === void 0 ? false : _l, dataURLOptions = _a.dataURLOptions, preserveWhiteSpace = _a.preserveWhiteSpace, onSerialize = _a.onSerialize, onIframeLoad = _a.onIframeLoad, iframeLoadTimeout = _a.iframeLoadTimeout, onStylesheetLoad = _a.onStylesheetLoad, stylesheetLoadTimeout = _a.stylesheetLoadTimeout, _m = _a.keepIframeSrcFn, keepIframeSrcFn = _m === void 0 ? function () { return false; } : _m;
958
+ var maskInputOptions = maskAllInputs === true
959
+ ? {
960
+ color: true,
961
+ date: true,
962
+ 'datetime-local': true,
963
+ email: true,
964
+ month: true,
965
+ number: true,
966
+ range: true,
967
+ search: true,
968
+ tel: true,
969
+ text: true,
970
+ time: true,
971
+ url: true,
972
+ week: true,
973
+ textarea: true,
974
+ select: true,
975
+ password: true
976
+ }
977
+ : maskAllInputs === false
978
+ ? {
979
+ password: true
980
+ }
981
+ : maskAllInputs;
982
+ var slimDOMOptions = slimDOM === true || slimDOM === 'all'
983
+ ?
984
+ {
985
+ script: true,
986
+ comment: true,
987
+ headFavicon: true,
988
+ headWhitespace: true,
989
+ headMetaDescKeywords: slimDOM === 'all',
990
+ headMetaSocial: true,
991
+ headMetaRobots: true,
992
+ headMetaHttpEquiv: true,
993
+ headMetaAuthorship: true,
994
+ headMetaVerification: true
995
+ }
996
+ : slimDOM === false
997
+ ? {}
998
+ : slimDOM;
999
+ return serializeNodeWithId(n, {
1000
+ doc: n,
1001
+ mirror: mirror,
1002
+ blockClass: blockClass,
1003
+ blockSelector: blockSelector,
1004
+ maskTextClass: maskTextClass,
1005
+ maskTextSelector: maskTextSelector,
1006
+ skipChild: false,
1007
+ inlineStylesheet: inlineStylesheet,
1008
+ maskInputOptions: maskInputOptions,
1009
+ maskTextFn: maskTextFn,
1010
+ maskInputFn: maskInputFn,
1011
+ slimDOMOptions: slimDOMOptions,
1012
+ dataURLOptions: dataURLOptions,
1013
+ inlineImages: inlineImages,
1014
+ recordCanvas: recordCanvas,
1015
+ preserveWhiteSpace: preserveWhiteSpace,
1016
+ onSerialize: onSerialize,
1017
+ onIframeLoad: onIframeLoad,
1018
+ iframeLoadTimeout: iframeLoadTimeout,
1019
+ onStylesheetLoad: onStylesheetLoad,
1020
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
1021
+ keepIframeSrcFn: keepIframeSrcFn,
1022
+ newlyAddedElement: false
1023
+ });
1024
+ }
1025
+
1026
+ function on(type, fn, target = document) {
1027
+ const options = { capture: true, passive: true };
1028
+ target.addEventListener(type, fn, options);
1029
+ return () => target.removeEventListener(type, fn, options);
1030
+ }
1031
+ const DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +
1032
+ '\r\n' +
1033
+ 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +
1034
+ '\r\n' +
1035
+ 'or you can use record.mirror to access the mirror instance during recording.';
1036
+ let _mirror = {
1037
+ map: {},
1038
+ getId() {
1039
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1040
+ return -1;
1041
+ },
1042
+ getNode() {
1043
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1044
+ return null;
1045
+ },
1046
+ removeNodeFromMap() {
1047
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1048
+ },
1049
+ has() {
1050
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1051
+ return false;
1052
+ },
1053
+ reset() {
1054
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1055
+ },
1056
+ };
1057
+ if (typeof window !== 'undefined' && window.Proxy && window.Reflect) {
1058
+ _mirror = new Proxy(_mirror, {
1059
+ get(target, prop, receiver) {
1060
+ if (prop === 'map') {
1061
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1062
+ }
1063
+ return Reflect.get(target, prop, receiver);
1064
+ },
1065
+ });
1066
+ }
1067
+ function throttle(func, wait, options = {}) {
1068
+ let timeout = null;
1069
+ let previous = 0;
1070
+ return function (...args) {
1071
+ const now = Date.now();
1072
+ if (!previous && options.leading === false) {
1073
+ previous = now;
1074
+ }
1075
+ const remaining = wait - (now - previous);
1076
+ const context = this;
1077
+ if (remaining <= 0 || remaining > wait) {
1078
+ if (timeout) {
1079
+ clearTimeout(timeout);
1080
+ timeout = null;
1081
+ }
1082
+ previous = now;
1083
+ func.apply(context, args);
1084
+ }
1085
+ else if (!timeout && options.trailing !== false) {
1086
+ timeout = setTimeout(() => {
1087
+ previous = options.leading === false ? 0 : Date.now();
1088
+ timeout = null;
1089
+ func.apply(context, args);
1090
+ }, remaining);
1091
+ }
1092
+ };
1093
+ }
1094
+ function hookSetter(target, key, d, isRevoked, win = window) {
1095
+ const original = win.Object.getOwnPropertyDescriptor(target, key);
1096
+ win.Object.defineProperty(target, key, isRevoked
1097
+ ? d
1098
+ : {
1099
+ set(value) {
1100
+ setTimeout(() => {
1101
+ d.set.call(this, value);
1102
+ }, 0);
1103
+ if (original && original.set) {
1104
+ original.set.call(this, value);
1105
+ }
1106
+ },
1107
+ });
1108
+ return () => hookSetter(target, key, original || {}, true);
1109
+ }
1110
+ function patch(source, name, replacement) {
1111
+ try {
1112
+ if (!(name in source)) {
1113
+ return () => {
1114
+ };
1115
+ }
1116
+ const original = source[name];
1117
+ const wrapped = replacement(original);
1118
+ if (typeof wrapped === 'function') {
1119
+ wrapped.prototype = wrapped.prototype || {};
1120
+ Object.defineProperties(wrapped, {
1121
+ __rrweb_original__: {
1122
+ enumerable: false,
1123
+ value: original,
1124
+ },
1125
+ });
1126
+ }
1127
+ source[name] = wrapped;
1128
+ return () => {
1129
+ source[name] = original;
1130
+ };
1131
+ }
1132
+ catch (_a) {
1133
+ return () => {
1134
+ };
1135
+ }
1136
+ }
1137
+ function getWindowHeight() {
1138
+ return (window.innerHeight ||
1139
+ (document.documentElement && document.documentElement.clientHeight) ||
1140
+ (document.body && document.body.clientHeight));
1141
+ }
1142
+ function getWindowWidth() {
1143
+ return (window.innerWidth ||
1144
+ (document.documentElement && document.documentElement.clientWidth) ||
1145
+ (document.body && document.body.clientWidth));
1146
+ }
1147
+ function isBlocked(node, blockClass, blockSelector, checkAncestors) {
1148
+ if (!node) {
1149
+ return false;
1150
+ }
1151
+ const el = node.nodeType === node.ELEMENT_NODE
1152
+ ? node
1153
+ : node.parentElement;
1154
+ if (!el)
1155
+ return false;
1156
+ if (typeof blockClass === 'string') {
1157
+ if (el.classList.contains(blockClass))
1158
+ return true;
1159
+ if (checkAncestors && el.closest('.' + blockClass) !== null)
1160
+ return true;
1161
+ }
1162
+ else {
1163
+ if (classMatchesRegex(el, blockClass, checkAncestors))
1164
+ return true;
1165
+ }
1166
+ if (blockSelector) {
1167
+ if (node.matches(blockSelector))
1168
+ return true;
1169
+ if (checkAncestors && el.closest(blockSelector) !== null)
1170
+ return true;
1171
+ }
1172
+ return false;
1173
+ }
1174
+ function isSerialized(n, mirror) {
1175
+ return mirror.getId(n) !== -1;
1176
+ }
1177
+ function isIgnored(n, mirror) {
1178
+ return mirror.getId(n) === IGNORED_NODE;
1179
+ }
1180
+ function isAncestorRemoved(target, mirror) {
1181
+ if (isShadowRoot(target)) {
1182
+ return false;
1183
+ }
1184
+ const id = mirror.getId(target);
1185
+ if (!mirror.has(id)) {
1186
+ return true;
1187
+ }
1188
+ if (target.parentNode &&
1189
+ target.parentNode.nodeType === target.DOCUMENT_NODE) {
1190
+ return false;
1191
+ }
1192
+ if (!target.parentNode) {
1193
+ return true;
1194
+ }
1195
+ return isAncestorRemoved(target.parentNode, mirror);
1196
+ }
1197
+ function isTouchEvent(event) {
1198
+ return Boolean(event.changedTouches);
1199
+ }
1200
+ function polyfill(win = window) {
1201
+ if ('NodeList' in win && !win.NodeList.prototype.forEach) {
1202
+ win.NodeList.prototype.forEach = Array.prototype
1203
+ .forEach;
1204
+ }
1205
+ if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {
1206
+ win.DOMTokenList.prototype.forEach = Array.prototype
1207
+ .forEach;
1208
+ }
1209
+ if (!Node.prototype.contains) {
1210
+ Node.prototype.contains = (...args) => {
1211
+ let node = args[0];
1212
+ if (!(0 in args)) {
1213
+ throw new TypeError('1 argument is required');
1214
+ }
1215
+ do {
1216
+ if (this === node) {
1217
+ return true;
1218
+ }
1219
+ } while ((node = node && node.parentNode));
1220
+ return false;
1221
+ };
1222
+ }
1223
+ }
1224
+ function isSerializedIframe(n, mirror) {
1225
+ return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
1226
+ }
1227
+ function isSerializedStylesheet(n, mirror) {
1228
+ return Boolean(n.nodeName === 'LINK' &&
1229
+ n.nodeType === n.ELEMENT_NODE &&
1230
+ n.getAttribute &&
1231
+ n.getAttribute('rel') === 'stylesheet' &&
1232
+ mirror.getMeta(n));
1233
+ }
1234
+ function hasShadowRoot(n) {
1235
+ return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);
1236
+ }
1237
+ class StyleSheetMirror {
1238
+ constructor() {
1239
+ this.id = 1;
1240
+ this.styleIDMap = new WeakMap();
1241
+ this.idStyleMap = new Map();
1242
+ }
1243
+ getId(stylesheet) {
1244
+ var _a;
1245
+ return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;
1246
+ }
1247
+ has(stylesheet) {
1248
+ return this.styleIDMap.has(stylesheet);
1249
+ }
1250
+ add(stylesheet, id) {
1251
+ if (this.has(stylesheet))
1252
+ return this.getId(stylesheet);
1253
+ let newId;
1254
+ if (id === undefined) {
1255
+ newId = this.id++;
1256
+ }
1257
+ else
1258
+ newId = id;
1259
+ this.styleIDMap.set(stylesheet, newId);
1260
+ this.idStyleMap.set(newId, stylesheet);
1261
+ return newId;
1262
+ }
1263
+ getStyle(id) {
1264
+ return this.idStyleMap.get(id) || null;
1265
+ }
1266
+ reset() {
1267
+ this.styleIDMap = new WeakMap();
1268
+ this.idStyleMap = new Map();
1269
+ this.id = 1;
1270
+ }
1271
+ generateId() {
1272
+ return this.id++;
1273
+ }
1274
+ }
1275
+
1276
+ var EventType = /* @__PURE__ */ ((EventType2) => {
1277
+ EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
1278
+ EventType2[EventType2["Load"] = 1] = "Load";
1279
+ EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
1280
+ EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
1281
+ EventType2[EventType2["Meta"] = 4] = "Meta";
1282
+ EventType2[EventType2["Custom"] = 5] = "Custom";
1283
+ EventType2[EventType2["Plugin"] = 6] = "Plugin";
1284
+ return EventType2;
1285
+ })(EventType || {});
1286
+ var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
1287
+ IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
1288
+ IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
1289
+ IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
1290
+ IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
1291
+ IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
1292
+ IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
1293
+ IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
1294
+ IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
1295
+ IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
1296
+ IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
1297
+ IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
1298
+ IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
1299
+ IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
1300
+ IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
1301
+ IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
1302
+ IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
1303
+ return IncrementalSource2;
1304
+ })(IncrementalSource || {});
1305
+ var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
1306
+ MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
1307
+ MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
1308
+ MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
1309
+ MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
1310
+ MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
1311
+ MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
1312
+ MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
1313
+ MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
1314
+ MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
1315
+ MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
1316
+ MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
1317
+ return MouseInteractions2;
1318
+ })(MouseInteractions || {});
1319
+ var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
1320
+ CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
1321
+ CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
1322
+ CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
1323
+ return CanvasContext2;
1324
+ })(CanvasContext || {});
1325
+
1326
+ function isNodeInLinkedList(n) {
1327
+ return '__ln' in n;
1328
+ }
1329
+ class DoubleLinkedList {
1330
+ constructor() {
1331
+ this.length = 0;
1332
+ this.head = null;
1333
+ }
1334
+ get(position) {
1335
+ if (position >= this.length) {
1336
+ throw new Error('Position outside of list range');
1337
+ }
1338
+ let current = this.head;
1339
+ for (let index = 0; index < position; index++) {
1340
+ current = (current === null || current === void 0 ? void 0 : current.next) || null;
1341
+ }
1342
+ return current;
1343
+ }
1344
+ addNode(n) {
1345
+ const node = {
1346
+ value: n,
1347
+ previous: null,
1348
+ next: null,
1349
+ };
1350
+ n.__ln = node;
1351
+ if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {
1352
+ const current = n.previousSibling.__ln.next;
1353
+ node.next = current;
1354
+ node.previous = n.previousSibling.__ln;
1355
+ n.previousSibling.__ln.next = node;
1356
+ if (current) {
1357
+ current.previous = node;
1358
+ }
1359
+ }
1360
+ else if (n.nextSibling &&
1361
+ isNodeInLinkedList(n.nextSibling) &&
1362
+ n.nextSibling.__ln.previous) {
1363
+ const current = n.nextSibling.__ln.previous;
1364
+ node.previous = current;
1365
+ node.next = n.nextSibling.__ln;
1366
+ n.nextSibling.__ln.previous = node;
1367
+ if (current) {
1368
+ current.next = node;
1369
+ }
1370
+ }
1371
+ else {
1372
+ if (this.head) {
1373
+ this.head.previous = node;
1374
+ }
1375
+ node.next = this.head;
1376
+ this.head = node;
1377
+ }
1378
+ this.length++;
1379
+ }
1380
+ removeNode(n) {
1381
+ const current = n.__ln;
1382
+ if (!this.head) {
1383
+ return;
1384
+ }
1385
+ if (!current.previous) {
1386
+ this.head = current.next;
1387
+ if (this.head) {
1388
+ this.head.previous = null;
1389
+ }
1390
+ }
1391
+ else {
1392
+ current.previous.next = current.next;
1393
+ if (current.next) {
1394
+ current.next.previous = current.previous;
1395
+ }
1396
+ }
1397
+ if (n.__ln) {
1398
+ delete n.__ln;
1399
+ }
1400
+ this.length--;
1401
+ }
1402
+ }
1403
+ const moveKey = (id, parentId) => `${id}@${parentId}`;
1404
+ class MutationBuffer {
1405
+ constructor() {
1406
+ this.frozen = false;
1407
+ this.locked = false;
1408
+ this.texts = [];
1409
+ this.attributes = [];
1410
+ this.removes = [];
1411
+ this.mapRemoves = [];
1412
+ this.movedMap = {};
1413
+ this.addedSet = new Set();
1414
+ this.movedSet = new Set();
1415
+ this.droppedSet = new Set();
1416
+ this.processMutations = (mutations) => {
1417
+ mutations.forEach(this.processMutation);
1418
+ this.emit();
1419
+ };
1420
+ this.emit = () => {
1421
+ if (this.frozen || this.locked) {
1422
+ return;
1423
+ }
1424
+ const adds = [];
1425
+ const addList = new DoubleLinkedList();
1426
+ const getNextId = (n) => {
1427
+ let ns = n;
1428
+ let nextId = IGNORED_NODE;
1429
+ while (nextId === IGNORED_NODE) {
1430
+ ns = ns && ns.nextSibling;
1431
+ nextId = ns && this.mirror.getId(ns);
1432
+ }
1433
+ return nextId;
1434
+ };
1435
+ const pushAdd = (n) => {
1436
+ var _a, _b, _c, _d;
1437
+ let shadowHost = null;
1438
+ if (((_b = (_a = n.getRootNode) === null || _a === void 0 ? void 0 : _a.call(n)) === null || _b === void 0 ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE &&
1439
+ n.getRootNode().host)
1440
+ shadowHost = n.getRootNode().host;
1441
+ let rootShadowHost = shadowHost;
1442
+ while (((_d = (_c = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _c === void 0 ? void 0 : _c.call(rootShadowHost)) === null || _d === void 0 ? void 0 : _d.nodeType) ===
1443
+ Node.DOCUMENT_FRAGMENT_NODE &&
1444
+ rootShadowHost.getRootNode().host)
1445
+ rootShadowHost = rootShadowHost.getRootNode().host;
1446
+ const notInDoc = !this.doc.contains(n) &&
1447
+ (!rootShadowHost || !this.doc.contains(rootShadowHost));
1448
+ if (!n.parentNode || notInDoc) {
1449
+ return;
1450
+ }
1451
+ const parentId = isShadowRoot(n.parentNode)
1452
+ ? this.mirror.getId(shadowHost)
1453
+ : this.mirror.getId(n.parentNode);
1454
+ const nextId = getNextId(n);
1455
+ if (parentId === -1 || nextId === -1) {
1456
+ return addList.addNode(n);
1457
+ }
1458
+ const sn = serializeNodeWithId(n, {
1459
+ doc: this.doc,
1460
+ mirror: this.mirror,
1461
+ blockClass: this.blockClass,
1462
+ blockSelector: this.blockSelector,
1463
+ maskTextClass: this.maskTextClass,
1464
+ maskTextSelector: this.maskTextSelector,
1465
+ skipChild: true,
1466
+ newlyAddedElement: true,
1467
+ inlineStylesheet: this.inlineStylesheet,
1468
+ maskInputOptions: this.maskInputOptions,
1469
+ maskTextFn: this.maskTextFn,
1470
+ maskInputFn: this.maskInputFn,
1471
+ slimDOMOptions: this.slimDOMOptions,
1472
+ dataURLOptions: this.dataURLOptions,
1473
+ recordCanvas: this.recordCanvas,
1474
+ inlineImages: this.inlineImages,
1475
+ onSerialize: (currentN) => {
1476
+ if (isSerializedIframe(currentN, this.mirror)) {
1477
+ this.iframeManager.addIframe(currentN);
1478
+ }
1479
+ if (isSerializedStylesheet(currentN, this.mirror)) {
1480
+ this.stylesheetManager.trackLinkElement(currentN);
1481
+ }
1482
+ if (hasShadowRoot(n)) {
1483
+ this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);
1484
+ }
1485
+ },
1486
+ onIframeLoad: (iframe, childSn) => {
1487
+ this.iframeManager.attachIframe(iframe, childSn);
1488
+ this.shadowDomManager.observeAttachShadow(iframe);
1489
+ },
1490
+ onStylesheetLoad: (link, childSn) => {
1491
+ this.stylesheetManager.attachLinkElement(link, childSn);
1492
+ },
1493
+ });
1494
+ if (sn) {
1495
+ adds.push({
1496
+ parentId,
1497
+ nextId,
1498
+ node: sn,
1499
+ });
1500
+ }
1501
+ };
1502
+ while (this.mapRemoves.length) {
1503
+ this.mirror.removeNodeFromMap(this.mapRemoves.shift());
1504
+ }
1505
+ for (const n of Array.from(this.movedSet.values())) {
1506
+ if (isParentRemoved(this.removes, n, this.mirror) &&
1507
+ !this.movedSet.has(n.parentNode)) {
1508
+ continue;
1509
+ }
1510
+ pushAdd(n);
1511
+ }
1512
+ for (const n of Array.from(this.addedSet.values())) {
1513
+ if (!isAncestorInSet(this.droppedSet, n) &&
1514
+ !isParentRemoved(this.removes, n, this.mirror)) {
1515
+ pushAdd(n);
1516
+ }
1517
+ else if (isAncestorInSet(this.movedSet, n)) {
1518
+ pushAdd(n);
1519
+ }
1520
+ else {
1521
+ this.droppedSet.add(n);
1522
+ }
1523
+ }
1524
+ let candidate = null;
1525
+ while (addList.length) {
1526
+ let node = null;
1527
+ if (candidate) {
1528
+ const parentId = this.mirror.getId(candidate.value.parentNode);
1529
+ const nextId = getNextId(candidate.value);
1530
+ if (parentId !== -1 && nextId !== -1) {
1531
+ node = candidate;
1532
+ }
1533
+ }
1534
+ if (!node) {
1535
+ for (let index = addList.length - 1; index >= 0; index--) {
1536
+ const _node = addList.get(index);
1537
+ if (_node) {
1538
+ const parentId = this.mirror.getId(_node.value.parentNode);
1539
+ const nextId = getNextId(_node.value);
1540
+ if (nextId === -1)
1541
+ continue;
1542
+ else if (parentId !== -1) {
1543
+ node = _node;
1544
+ break;
1545
+ }
1546
+ else {
1547
+ const unhandledNode = _node.value;
1548
+ if (unhandledNode.parentNode &&
1549
+ unhandledNode.parentNode.nodeType ===
1550
+ Node.DOCUMENT_FRAGMENT_NODE) {
1551
+ const shadowHost = unhandledNode.parentNode
1552
+ .host;
1553
+ const parentId = this.mirror.getId(shadowHost);
1554
+ if (parentId !== -1) {
1555
+ node = _node;
1556
+ break;
1557
+ }
1558
+ }
1559
+ }
1560
+ }
1561
+ }
1562
+ }
1563
+ if (!node) {
1564
+ while (addList.head) {
1565
+ addList.removeNode(addList.head.value);
1566
+ }
1567
+ break;
1568
+ }
1569
+ candidate = node.previous;
1570
+ addList.removeNode(node.value);
1571
+ pushAdd(node.value);
1572
+ }
1573
+ const payload = {
1574
+ texts: this.texts
1575
+ .map((text) => ({
1576
+ id: this.mirror.getId(text.node),
1577
+ value: text.value,
1578
+ }))
1579
+ .filter((text) => this.mirror.has(text.id)),
1580
+ attributes: this.attributes
1581
+ .map((attribute) => ({
1582
+ id: this.mirror.getId(attribute.node),
1583
+ attributes: attribute.attributes,
1584
+ }))
1585
+ .filter((attribute) => this.mirror.has(attribute.id)),
1586
+ removes: this.removes,
1587
+ adds,
1588
+ };
1589
+ if (!payload.texts.length &&
1590
+ !payload.attributes.length &&
1591
+ !payload.removes.length &&
1592
+ !payload.adds.length) {
1593
+ return;
1594
+ }
1595
+ this.texts = [];
1596
+ this.attributes = [];
1597
+ this.removes = [];
1598
+ this.addedSet = new Set();
1599
+ this.movedSet = new Set();
1600
+ this.droppedSet = new Set();
1601
+ this.movedMap = {};
1602
+ this.mutationCb(payload);
1603
+ };
1604
+ this.processMutation = (m) => {
1605
+ if (isIgnored(m.target, this.mirror)) {
1606
+ return;
1607
+ }
1608
+ switch (m.type) {
1609
+ case 'characterData': {
1610
+ const value = m.target.textContent;
1611
+ if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) &&
1612
+ value !== m.oldValue) {
1613
+ this.texts.push({
1614
+ value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector) && value
1615
+ ? this.maskTextFn
1616
+ ? this.maskTextFn(value)
1617
+ : value.replace(/[\S]/g, '*')
1618
+ : value,
1619
+ node: m.target,
1620
+ });
1621
+ }
1622
+ break;
1623
+ }
1624
+ case 'attributes': {
1625
+ const target = m.target;
1626
+ let value = m.target.getAttribute(m.attributeName);
1627
+ if (m.attributeName === 'value') {
1628
+ value = maskInputValue({
1629
+ maskInputOptions: this.maskInputOptions,
1630
+ tagName: m.target.tagName,
1631
+ type: m.target.getAttribute('type'),
1632
+ value,
1633
+ maskInputFn: this.maskInputFn,
1634
+ });
1635
+ }
1636
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
1637
+ value === m.oldValue) {
1638
+ return;
1639
+ }
1640
+ let item = this.attributes.find((a) => a.node === m.target);
1641
+ if (target.tagName === 'IFRAME' &&
1642
+ m.attributeName === 'src' &&
1643
+ !this.keepIframeSrcFn(value)) {
1644
+ if (!target.contentDocument) {
1645
+ m.attributeName = 'rr_src';
1646
+ }
1647
+ else {
1648
+ return;
1649
+ }
1650
+ }
1651
+ if (!item) {
1652
+ item = {
1653
+ node: m.target,
1654
+ attributes: {},
1655
+ };
1656
+ this.attributes.push(item);
1657
+ }
1658
+ if (m.attributeName === 'style') {
1659
+ const old = this.doc.createElement('span');
1660
+ if (m.oldValue) {
1661
+ old.setAttribute('style', m.oldValue);
1662
+ }
1663
+ if (item.attributes.style === undefined ||
1664
+ item.attributes.style === null) {
1665
+ item.attributes.style = {};
1666
+ }
1667
+ const styleObj = item.attributes.style;
1668
+ for (const pname of Array.from(target.style)) {
1669
+ const newValue = target.style.getPropertyValue(pname);
1670
+ const newPriority = target.style.getPropertyPriority(pname);
1671
+ if (newValue !== old.style.getPropertyValue(pname) ||
1672
+ newPriority !== old.style.getPropertyPriority(pname)) {
1673
+ if (newPriority === '') {
1674
+ styleObj[pname] = newValue;
1675
+ }
1676
+ else {
1677
+ styleObj[pname] = [newValue, newPriority];
1678
+ }
1679
+ }
1680
+ }
1681
+ for (const pname of Array.from(old.style)) {
1682
+ if (target.style.getPropertyValue(pname) === '') {
1683
+ styleObj[pname] = false;
1684
+ }
1685
+ }
1686
+ }
1687
+ else {
1688
+ item.attributes[m.attributeName] = transformAttribute(this.doc, target.tagName, m.attributeName, value);
1689
+ }
1690
+ break;
1691
+ }
1692
+ case 'childList': {
1693
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, true))
1694
+ return;
1695
+ m.addedNodes.forEach((n) => this.genAdds(n, m.target));
1696
+ m.removedNodes.forEach((n) => {
1697
+ const nodeId = this.mirror.getId(n);
1698
+ const parentId = isShadowRoot(m.target)
1699
+ ? this.mirror.getId(m.target.host)
1700
+ : this.mirror.getId(m.target);
1701
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
1702
+ isIgnored(n, this.mirror) ||
1703
+ !isSerialized(n, this.mirror)) {
1704
+ return;
1705
+ }
1706
+ if (this.addedSet.has(n)) {
1707
+ deepDelete(this.addedSet, n);
1708
+ this.droppedSet.add(n);
1709
+ }
1710
+ else if (this.addedSet.has(m.target) && nodeId === -1) ;
1711
+ else if (isAncestorRemoved(m.target, this.mirror)) ;
1712
+ else if (this.movedSet.has(n) &&
1713
+ this.movedMap[moveKey(nodeId, parentId)]) {
1714
+ deepDelete(this.movedSet, n);
1715
+ }
1716
+ else {
1717
+ this.removes.push({
1718
+ parentId,
1719
+ id: nodeId,
1720
+ isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)
1721
+ ? true
1722
+ : undefined,
1723
+ });
1724
+ }
1725
+ this.mapRemoves.push(n);
1726
+ });
1727
+ break;
1728
+ }
1729
+ }
1730
+ };
1731
+ this.genAdds = (n, target) => {
1732
+ if (this.mirror.hasNode(n)) {
1733
+ if (isIgnored(n, this.mirror)) {
1734
+ return;
1735
+ }
1736
+ this.movedSet.add(n);
1737
+ let targetId = null;
1738
+ if (target && this.mirror.hasNode(target)) {
1739
+ targetId = this.mirror.getId(target);
1740
+ }
1741
+ if (targetId && targetId !== -1) {
1742
+ this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
1743
+ }
1744
+ }
1745
+ else {
1746
+ this.addedSet.add(n);
1747
+ this.droppedSet.delete(n);
1748
+ }
1749
+ if (!isBlocked(n, this.blockClass, this.blockSelector, false))
1750
+ n.childNodes.forEach((childN) => this.genAdds(childN));
1751
+ };
1752
+ }
1753
+ init(options) {
1754
+ [
1755
+ 'mutationCb',
1756
+ 'blockClass',
1757
+ 'blockSelector',
1758
+ 'maskTextClass',
1759
+ 'maskTextSelector',
1760
+ 'inlineStylesheet',
1761
+ 'maskInputOptions',
1762
+ 'maskTextFn',
1763
+ 'maskInputFn',
1764
+ 'keepIframeSrcFn',
1765
+ 'recordCanvas',
1766
+ 'inlineImages',
1767
+ 'slimDOMOptions',
1768
+ 'dataURLOptions',
1769
+ 'doc',
1770
+ 'mirror',
1771
+ 'iframeManager',
1772
+ 'stylesheetManager',
1773
+ 'shadowDomManager',
1774
+ 'canvasManager',
1775
+ ].forEach((key) => {
1776
+ this[key] = options[key];
1777
+ });
1778
+ }
1779
+ freeze() {
1780
+ this.frozen = true;
1781
+ this.canvasManager.freeze();
1782
+ }
1783
+ unfreeze() {
1784
+ this.frozen = false;
1785
+ this.canvasManager.unfreeze();
1786
+ this.emit();
1787
+ }
1788
+ isFrozen() {
1789
+ return this.frozen;
1790
+ }
1791
+ lock() {
1792
+ this.locked = true;
1793
+ this.canvasManager.lock();
1794
+ }
1795
+ unlock() {
1796
+ this.locked = false;
1797
+ this.canvasManager.unlock();
1798
+ this.emit();
1799
+ }
1800
+ reset() {
1801
+ this.shadowDomManager.reset();
1802
+ this.canvasManager.reset();
1803
+ }
1804
+ }
1805
+ function deepDelete(addsSet, n) {
1806
+ addsSet.delete(n);
1807
+ n.childNodes.forEach((childN) => deepDelete(addsSet, childN));
1808
+ }
1809
+ function isParentRemoved(removes, n, mirror) {
1810
+ if (removes.length === 0)
1811
+ return false;
1812
+ return _isParentRemoved(removes, n, mirror);
1813
+ }
1814
+ function _isParentRemoved(removes, n, mirror) {
1815
+ const { parentNode } = n;
1816
+ if (!parentNode) {
1817
+ return false;
1818
+ }
1819
+ const parentId = mirror.getId(parentNode);
1820
+ if (removes.some((r) => r.id === parentId)) {
1821
+ return true;
1822
+ }
1823
+ return _isParentRemoved(removes, parentNode, mirror);
1824
+ }
1825
+ function isAncestorInSet(set, n) {
1826
+ if (set.size === 0)
1827
+ return false;
1828
+ return _isAncestorInSet(set, n);
1829
+ }
1830
+ function _isAncestorInSet(set, n) {
1831
+ const { parentNode } = n;
1832
+ if (!parentNode) {
1833
+ return false;
1834
+ }
1835
+ if (set.has(parentNode)) {
1836
+ return true;
1837
+ }
1838
+ return _isAncestorInSet(set, parentNode);
1839
+ }
1840
+
1841
+ const mutationBuffers = [];
1842
+ const isCSSGroupingRuleSupported = typeof CSSGroupingRule !== 'undefined';
1843
+ const isCSSMediaRuleSupported = typeof CSSMediaRule !== 'undefined';
1844
+ const isCSSSupportsRuleSupported = typeof CSSSupportsRule !== 'undefined';
1845
+ const isCSSConditionRuleSupported = typeof CSSConditionRule !== 'undefined';
1846
+ function getEventTarget(event) {
1847
+ try {
1848
+ if ('composedPath' in event) {
1849
+ const path = event.composedPath();
1850
+ if (path.length) {
1851
+ return path[0];
1852
+ }
1853
+ }
1854
+ else if ('path' in event && event.path.length) {
1855
+ return event.path[0];
1856
+ }
1857
+ return event.target;
1858
+ }
1859
+ catch (_a) {
1860
+ return event.target;
1861
+ }
1862
+ }
1863
+ function initMutationObserver(options, rootEl) {
1864
+ var _a, _b;
1865
+ const mutationBuffer = new MutationBuffer();
1866
+ mutationBuffers.push(mutationBuffer);
1867
+ mutationBuffer.init(options);
1868
+ let mutationObserverCtor = window.MutationObserver ||
1869
+ window.__rrMutationObserver;
1870
+ const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');
1871
+ if (angularZoneSymbol &&
1872
+ window[angularZoneSymbol]) {
1873
+ mutationObserverCtor = window[angularZoneSymbol];
1874
+ }
1875
+ const observer = new mutationObserverCtor(mutationBuffer.processMutations.bind(mutationBuffer));
1876
+ observer.observe(rootEl, {
1877
+ attributes: true,
1878
+ attributeOldValue: true,
1879
+ characterData: true,
1880
+ characterDataOldValue: true,
1881
+ childList: true,
1882
+ subtree: true,
1883
+ });
1884
+ return observer;
1885
+ }
1886
+ function initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {
1887
+ if (sampling.mousemove === false) {
1888
+ return () => {
1889
+ };
1890
+ }
1891
+ const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;
1892
+ const callbackThreshold = typeof sampling.mousemoveCallback === 'number'
1893
+ ? sampling.mousemoveCallback
1894
+ : 500;
1895
+ let positions = [];
1896
+ let timeBaseline;
1897
+ const wrappedCb = throttle((source) => {
1898
+ const totalOffset = Date.now() - timeBaseline;
1899
+ mousemoveCb(positions.map((p) => {
1900
+ p.timeOffset -= totalOffset;
1901
+ return p;
1902
+ }), source);
1903
+ positions = [];
1904
+ timeBaseline = null;
1905
+ }, callbackThreshold);
1906
+ const updatePosition = throttle((evt) => {
1907
+ const target = getEventTarget(evt);
1908
+ const { clientX, clientY } = isTouchEvent(evt)
1909
+ ? evt.changedTouches[0]
1910
+ : evt;
1911
+ if (!timeBaseline) {
1912
+ timeBaseline = Date.now();
1913
+ }
1914
+ positions.push({
1915
+ x: clientX,
1916
+ y: clientY,
1917
+ id: mirror.getId(target),
1918
+ timeOffset: Date.now() - timeBaseline,
1919
+ });
1920
+ wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent
1921
+ ? IncrementalSource.Drag
1922
+ : evt instanceof MouseEvent
1923
+ ? IncrementalSource.MouseMove
1924
+ : IncrementalSource.TouchMove);
1925
+ }, threshold, {
1926
+ trailing: false,
1927
+ });
1928
+ const handlers = [
1929
+ on('mousemove', updatePosition, doc),
1930
+ on('touchmove', updatePosition, doc),
1931
+ on('drag', updatePosition, doc),
1932
+ ];
1933
+ return () => {
1934
+ handlers.forEach((h) => h());
1935
+ };
1936
+ }
1937
+ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, sampling, }) {
1938
+ if (sampling.mouseInteraction === false) {
1939
+ return () => {
1940
+ };
1941
+ }
1942
+ const disableMap = sampling.mouseInteraction === true ||
1943
+ sampling.mouseInteraction === undefined
1944
+ ? {}
1945
+ : sampling.mouseInteraction;
1946
+ const handlers = [];
1947
+ const getHandler = (eventKey) => {
1948
+ return (event) => {
1949
+ const target = getEventTarget(event);
1950
+ if (isBlocked(target, blockClass, blockSelector, true)) {
1951
+ return;
1952
+ }
1953
+ const e = isTouchEvent(event) ? event.changedTouches[0] : event;
1954
+ if (!e) {
1955
+ return;
1956
+ }
1957
+ const id = mirror.getId(target);
1958
+ const { clientX, clientY } = e;
1959
+ mouseInteractionCb({
1960
+ type: MouseInteractions[eventKey],
1961
+ id,
1962
+ x: clientX,
1963
+ y: clientY,
1964
+ });
1965
+ };
1966
+ };
1967
+ Object.keys(MouseInteractions)
1968
+ .filter((key) => Number.isNaN(Number(key)) &&
1969
+ !key.endsWith('_Departed') &&
1970
+ disableMap[key] !== false)
1971
+ .forEach((eventKey) => {
1972
+ const eventName = eventKey.toLowerCase();
1973
+ const handler = getHandler(eventKey);
1974
+ handlers.push(on(eventName, handler, doc));
1975
+ });
1976
+ return () => {
1977
+ handlers.forEach((h) => h());
1978
+ };
1979
+ }
1980
+ function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, sampling, }) {
1981
+ const updatePosition = throttle((evt) => {
1982
+ const target = getEventTarget(evt);
1983
+ if (!target || isBlocked(target, blockClass, blockSelector, true)) {
1984
+ return;
1985
+ }
1986
+ const id = mirror.getId(target);
1987
+ if (target === doc) {
1988
+ const scrollEl = (doc.scrollingElement || doc.documentElement);
1989
+ scrollCb({
1990
+ id,
1991
+ x: scrollEl.scrollLeft,
1992
+ y: scrollEl.scrollTop,
1993
+ });
1994
+ }
1995
+ else {
1996
+ scrollCb({
1997
+ id,
1998
+ x: target.scrollLeft,
1999
+ y: target.scrollTop,
2000
+ });
2001
+ }
2002
+ }, sampling.scroll || 100);
2003
+ return on('scroll', updatePosition, doc);
2004
+ }
2005
+ function initViewportResizeObserver({ viewportResizeCb, }) {
2006
+ let lastH = -1;
2007
+ let lastW = -1;
2008
+ const updateDimension = throttle(() => {
2009
+ const height = getWindowHeight();
2010
+ const width = getWindowWidth();
2011
+ if (lastH !== height || lastW !== width) {
2012
+ viewportResizeCb({
2013
+ width: Number(width),
2014
+ height: Number(height),
2015
+ });
2016
+ lastH = height;
2017
+ lastW = width;
2018
+ }
2019
+ }, 200);
2020
+ return on('resize', updateDimension, window);
2021
+ }
2022
+ function wrapEventWithUserTriggeredFlag(v, enable) {
2023
+ const value = Object.assign({}, v);
2024
+ if (!enable)
2025
+ delete value.userTriggered;
2026
+ return value;
2027
+ }
2028
+ const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
2029
+ const lastInputValueMap = new WeakMap();
2030
+ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ignoreClass, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {
2031
+ function eventHandler(event) {
2032
+ let target = getEventTarget(event);
2033
+ const userTriggered = event.isTrusted;
2034
+ if (target && target.tagName === 'OPTION')
2035
+ target = target.parentElement;
2036
+ if (!target ||
2037
+ !target.tagName ||
2038
+ INPUT_TAGS.indexOf(target.tagName) < 0 ||
2039
+ isBlocked(target, blockClass, blockSelector, true)) {
2040
+ return;
2041
+ }
2042
+ const type = target.type;
2043
+ if (target.classList.contains(ignoreClass)) {
2044
+ return;
2045
+ }
2046
+ let text = target.value;
2047
+ let isChecked = false;
2048
+ if (type === 'radio' || type === 'checkbox') {
2049
+ isChecked = target.checked;
2050
+ }
2051
+ else if (maskInputOptions[target.tagName.toLowerCase()] ||
2052
+ maskInputOptions[type]) {
2053
+ text = maskInputValue({
2054
+ maskInputOptions,
2055
+ tagName: target.tagName,
2056
+ type,
2057
+ value: text,
2058
+ maskInputFn,
2059
+ });
2060
+ }
2061
+ cbWithDedup(target, wrapEventWithUserTriggeredFlag({ text, isChecked, userTriggered }, userTriggeredOnInput));
2062
+ const name = target.name;
2063
+ if (type === 'radio' && name && isChecked) {
2064
+ doc
2065
+ .querySelectorAll(`input[type="radio"][name="${name}"]`)
2066
+ .forEach((el) => {
2067
+ if (el !== target) {
2068
+ cbWithDedup(el, wrapEventWithUserTriggeredFlag({
2069
+ text: el.value,
2070
+ isChecked: !isChecked,
2071
+ userTriggered: false,
2072
+ }, userTriggeredOnInput));
2073
+ }
2074
+ });
2075
+ }
2076
+ }
2077
+ function cbWithDedup(target, v) {
2078
+ const lastInputValue = lastInputValueMap.get(target);
2079
+ if (!lastInputValue ||
2080
+ lastInputValue.text !== v.text ||
2081
+ lastInputValue.isChecked !== v.isChecked) {
2082
+ lastInputValueMap.set(target, v);
2083
+ const id = mirror.getId(target);
2084
+ inputCb(Object.assign(Object.assign({}, v), { id }));
2085
+ }
2086
+ }
2087
+ const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
2088
+ const handlers = events.map((eventName) => on(eventName, eventHandler, doc));
2089
+ const currentWindow = doc.defaultView;
2090
+ if (!currentWindow) {
2091
+ return () => {
2092
+ handlers.forEach((h) => h());
2093
+ };
2094
+ }
2095
+ const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');
2096
+ const hookProperties = [
2097
+ [currentWindow.HTMLInputElement.prototype, 'value'],
2098
+ [currentWindow.HTMLInputElement.prototype, 'checked'],
2099
+ [currentWindow.HTMLSelectElement.prototype, 'value'],
2100
+ [currentWindow.HTMLTextAreaElement.prototype, 'value'],
2101
+ [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],
2102
+ [currentWindow.HTMLOptionElement.prototype, 'selected'],
2103
+ ];
2104
+ if (propertyDescriptor && propertyDescriptor.set) {
2105
+ handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {
2106
+ set() {
2107
+ eventHandler({ target: this });
2108
+ },
2109
+ }, false, currentWindow)));
2110
+ }
2111
+ return () => {
2112
+ handlers.forEach((h) => h());
2113
+ };
2114
+ }
2115
+ function getNestedCSSRulePositions(rule) {
2116
+ const positions = [];
2117
+ function recurse(childRule, pos) {
2118
+ if ((isCSSGroupingRuleSupported &&
2119
+ childRule.parentRule instanceof CSSGroupingRule) ||
2120
+ (isCSSMediaRuleSupported &&
2121
+ childRule.parentRule instanceof CSSMediaRule) ||
2122
+ (isCSSSupportsRuleSupported &&
2123
+ childRule.parentRule instanceof CSSSupportsRule) ||
2124
+ (isCSSConditionRuleSupported &&
2125
+ childRule.parentRule instanceof CSSConditionRule)) {
2126
+ const rules = Array.from(childRule.parentRule.cssRules);
2127
+ const index = rules.indexOf(childRule);
2128
+ pos.unshift(index);
2129
+ }
2130
+ else if (childRule.parentStyleSheet) {
2131
+ const rules = Array.from(childRule.parentStyleSheet.cssRules);
2132
+ const index = rules.indexOf(childRule);
2133
+ pos.unshift(index);
2134
+ }
2135
+ return pos;
2136
+ }
2137
+ return recurse(rule, positions);
2138
+ }
2139
+ function getIdAndStyleId(sheet, mirror, styleMirror) {
2140
+ let id, styleId;
2141
+ if (!sheet)
2142
+ return {};
2143
+ if (sheet.ownerNode)
2144
+ id = mirror.getId(sheet.ownerNode);
2145
+ else
2146
+ styleId = styleMirror.getId(sheet);
2147
+ return {
2148
+ styleId,
2149
+ id,
2150
+ };
2151
+ }
2152
+ function initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {
2153
+ const insertRule = win.CSSStyleSheet.prototype.insertRule;
2154
+ win.CSSStyleSheet.prototype.insertRule = function (rule, index) {
2155
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2156
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2157
+ styleSheetRuleCb({
2158
+ id,
2159
+ styleId,
2160
+ adds: [{ rule, index }],
2161
+ });
2162
+ }
2163
+ return insertRule.apply(this, [rule, index]);
2164
+ };
2165
+ const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
2166
+ win.CSSStyleSheet.prototype.deleteRule = function (index) {
2167
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2168
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2169
+ styleSheetRuleCb({
2170
+ id,
2171
+ styleId,
2172
+ removes: [{ index }],
2173
+ });
2174
+ }
2175
+ return deleteRule.apply(this, [index]);
2176
+ };
2177
+ let replace;
2178
+ if (win.CSSStyleSheet.prototype.replace) {
2179
+ replace = win.CSSStyleSheet.prototype.replace;
2180
+ win.CSSStyleSheet.prototype.replace = function (text) {
2181
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2182
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2183
+ styleSheetRuleCb({
2184
+ id,
2185
+ styleId,
2186
+ replace: text,
2187
+ });
2188
+ }
2189
+ return replace.apply(this, [text]);
2190
+ };
2191
+ }
2192
+ let replaceSync;
2193
+ if (win.CSSStyleSheet.prototype.replaceSync) {
2194
+ replaceSync = win.CSSStyleSheet.prototype.replaceSync;
2195
+ win.CSSStyleSheet.prototype.replaceSync = function (text) {
2196
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2197
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2198
+ styleSheetRuleCb({
2199
+ id,
2200
+ styleId,
2201
+ replaceSync: text,
2202
+ });
2203
+ }
2204
+ return replaceSync.apply(this, [text]);
2205
+ };
2206
+ }
2207
+ const supportedNestedCSSRuleTypes = {};
2208
+ if (isCSSGroupingRuleSupported) {
2209
+ supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
2210
+ }
2211
+ else {
2212
+ if (isCSSMediaRuleSupported) {
2213
+ supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
2214
+ }
2215
+ if (isCSSConditionRuleSupported) {
2216
+ supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
2217
+ }
2218
+ if (isCSSSupportsRuleSupported) {
2219
+ supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
2220
+ }
2221
+ }
2222
+ const unmodifiedFunctions = {};
2223
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
2224
+ unmodifiedFunctions[typeKey] = {
2225
+ insertRule: type.prototype.insertRule,
2226
+ deleteRule: type.prototype.deleteRule,
2227
+ };
2228
+ type.prototype.insertRule = function (rule, index) {
2229
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2230
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2231
+ styleSheetRuleCb({
2232
+ id,
2233
+ styleId,
2234
+ adds: [
2235
+ {
2236
+ rule,
2237
+ index: [
2238
+ ...getNestedCSSRulePositions(this),
2239
+ index || 0,
2240
+ ],
2241
+ },
2242
+ ],
2243
+ });
2244
+ }
2245
+ return unmodifiedFunctions[typeKey].insertRule.apply(this, [rule, index]);
2246
+ };
2247
+ type.prototype.deleteRule = function (index) {
2248
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2249
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2250
+ styleSheetRuleCb({
2251
+ id,
2252
+ styleId,
2253
+ removes: [
2254
+ { index: [...getNestedCSSRulePositions(this), index] },
2255
+ ],
2256
+ });
2257
+ }
2258
+ return unmodifiedFunctions[typeKey].deleteRule.apply(this, [index]);
2259
+ };
2260
+ });
2261
+ return () => {
2262
+ win.CSSStyleSheet.prototype.insertRule = insertRule;
2263
+ win.CSSStyleSheet.prototype.deleteRule = deleteRule;
2264
+ replace && (win.CSSStyleSheet.prototype.replace = replace);
2265
+ replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
2266
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
2267
+ type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
2268
+ type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
2269
+ });
2270
+ };
2271
+ }
2272
+ function initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {
2273
+ var _a, _b, _c;
2274
+ let hostId = null;
2275
+ if (host.nodeName === '#document')
2276
+ hostId = mirror.getId(host);
2277
+ else
2278
+ hostId = mirror.getId(host.host);
2279
+ const patchTarget = host.nodeName === '#document'
2280
+ ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document
2281
+ : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;
2282
+ const originalPropertyDescriptor = Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets');
2283
+ if (hostId === null ||
2284
+ hostId === -1 ||
2285
+ !patchTarget ||
2286
+ !originalPropertyDescriptor)
2287
+ return () => {
2288
+ };
2289
+ Object.defineProperty(host, 'adoptedStyleSheets', {
2290
+ configurable: originalPropertyDescriptor.configurable,
2291
+ enumerable: originalPropertyDescriptor.enumerable,
2292
+ get() {
2293
+ var _a;
2294
+ return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);
2295
+ },
2296
+ set(sheets) {
2297
+ var _a;
2298
+ const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);
2299
+ if (hostId !== null && hostId !== -1) {
2300
+ try {
2301
+ stylesheetManager.adoptStyleSheets(sheets, hostId);
2302
+ }
2303
+ catch (e) {
2304
+ }
2305
+ }
2306
+ return result;
2307
+ },
2308
+ });
2309
+ return () => {
2310
+ Object.defineProperty(host, 'adoptedStyleSheets', {
2311
+ configurable: originalPropertyDescriptor.configurable,
2312
+ enumerable: originalPropertyDescriptor.enumerable,
2313
+ get: originalPropertyDescriptor.get,
2314
+ set: originalPropertyDescriptor.set,
2315
+ });
2316
+ };
2317
+ }
2318
+ function initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {
2319
+ const setProperty = win.CSSStyleDeclaration.prototype.setProperty;
2320
+ win.CSSStyleDeclaration.prototype.setProperty = function (property, value, priority) {
2321
+ var _a;
2322
+ if (ignoreCSSAttributes.has(property)) {
2323
+ return setProperty.apply(this, [property, value, priority]);
2324
+ }
2325
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2326
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2327
+ styleDeclarationCb({
2328
+ id,
2329
+ styleId,
2330
+ set: {
2331
+ property,
2332
+ value,
2333
+ priority,
2334
+ },
2335
+ index: getNestedCSSRulePositions(this.parentRule),
2336
+ });
2337
+ }
2338
+ return setProperty.apply(this, [property, value, priority]);
2339
+ };
2340
+ const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
2341
+ win.CSSStyleDeclaration.prototype.removeProperty = function (property) {
2342
+ var _a;
2343
+ if (ignoreCSSAttributes.has(property)) {
2344
+ return removeProperty.apply(this, [property]);
2345
+ }
2346
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2347
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2348
+ styleDeclarationCb({
2349
+ id,
2350
+ styleId,
2351
+ remove: {
2352
+ property,
2353
+ },
2354
+ index: getNestedCSSRulePositions(this.parentRule),
2355
+ });
2356
+ }
2357
+ return removeProperty.apply(this, [property]);
2358
+ };
2359
+ return () => {
2360
+ win.CSSStyleDeclaration.prototype.setProperty = setProperty;
2361
+ win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
2362
+ };
2363
+ }
2364
+ function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, mirror, sampling, }) {
2365
+ const handler = (type) => throttle((event) => {
2366
+ const target = getEventTarget(event);
2367
+ if (!target ||
2368
+ isBlocked(target, blockClass, blockSelector, true)) {
2369
+ return;
2370
+ }
2371
+ const { currentTime, volume, muted, playbackRate, } = target;
2372
+ mediaInteractionCb({
2373
+ type,
2374
+ id: mirror.getId(target),
2375
+ currentTime,
2376
+ volume,
2377
+ muted,
2378
+ playbackRate,
2379
+ });
2380
+ }, sampling.media || 500);
2381
+ const handlers = [
2382
+ on('play', handler(0)),
2383
+ on('pause', handler(1)),
2384
+ on('seeked', handler(2)),
2385
+ on('volumechange', handler(3)),
2386
+ on('ratechange', handler(4)),
2387
+ ];
2388
+ return () => {
2389
+ handlers.forEach((h) => h());
2390
+ };
2391
+ }
2392
+ function initFontObserver({ fontCb, doc }) {
2393
+ const win = doc.defaultView;
2394
+ if (!win) {
2395
+ return () => {
2396
+ };
2397
+ }
2398
+ const handlers = [];
2399
+ const fontMap = new WeakMap();
2400
+ const originalFontFace = win.FontFace;
2401
+ win.FontFace = function FontFace(family, source, descriptors) {
2402
+ const fontFace = new originalFontFace(family, source, descriptors);
2403
+ fontMap.set(fontFace, {
2404
+ family,
2405
+ buffer: typeof source !== 'string',
2406
+ descriptors,
2407
+ fontSource: typeof source === 'string'
2408
+ ? source
2409
+ : JSON.stringify(Array.from(new Uint8Array(source))),
2410
+ });
2411
+ return fontFace;
2412
+ };
2413
+ const restoreHandler = patch(doc.fonts, 'add', function (original) {
2414
+ return function (fontFace) {
2415
+ setTimeout(() => {
2416
+ const p = fontMap.get(fontFace);
2417
+ if (p) {
2418
+ fontCb(p);
2419
+ fontMap.delete(fontFace);
2420
+ }
2421
+ }, 0);
2422
+ return original.apply(this, [fontFace]);
2423
+ };
2424
+ });
2425
+ handlers.push(() => {
2426
+ win.FontFace = originalFontFace;
2427
+ });
2428
+ handlers.push(restoreHandler);
2429
+ return () => {
2430
+ handlers.forEach((h) => h());
2431
+ };
2432
+ }
2433
+ function initSelectionObserver(param) {
2434
+ const { doc, mirror, blockClass, blockSelector, selectionCb } = param;
2435
+ let collapsed = true;
2436
+ const updateSelection = () => {
2437
+ const selection = doc.getSelection();
2438
+ if (!selection || (collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)))
2439
+ return;
2440
+ collapsed = selection.isCollapsed || false;
2441
+ const ranges = [];
2442
+ const count = selection.rangeCount || 0;
2443
+ for (let i = 0; i < count; i++) {
2444
+ const range = selection.getRangeAt(i);
2445
+ const { startContainer, startOffset, endContainer, endOffset } = range;
2446
+ const blocked = isBlocked(startContainer, blockClass, blockSelector, true) ||
2447
+ isBlocked(endContainer, blockClass, blockSelector, true);
2448
+ if (blocked)
2449
+ continue;
2450
+ ranges.push({
2451
+ start: mirror.getId(startContainer),
2452
+ startOffset,
2453
+ end: mirror.getId(endContainer),
2454
+ endOffset,
2455
+ });
2456
+ }
2457
+ selectionCb({ ranges });
2458
+ };
2459
+ updateSelection();
2460
+ return on('selectionchange', updateSelection);
2461
+ }
2462
+ function mergeHooks(o, hooks) {
2463
+ const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, } = o;
2464
+ o.mutationCb = (...p) => {
2465
+ if (hooks.mutation) {
2466
+ hooks.mutation(...p);
2467
+ }
2468
+ mutationCb(...p);
2469
+ };
2470
+ o.mousemoveCb = (...p) => {
2471
+ if (hooks.mousemove) {
2472
+ hooks.mousemove(...p);
2473
+ }
2474
+ mousemoveCb(...p);
2475
+ };
2476
+ o.mouseInteractionCb = (...p) => {
2477
+ if (hooks.mouseInteraction) {
2478
+ hooks.mouseInteraction(...p);
2479
+ }
2480
+ mouseInteractionCb(...p);
2481
+ };
2482
+ o.scrollCb = (...p) => {
2483
+ if (hooks.scroll) {
2484
+ hooks.scroll(...p);
2485
+ }
2486
+ scrollCb(...p);
2487
+ };
2488
+ o.viewportResizeCb = (...p) => {
2489
+ if (hooks.viewportResize) {
2490
+ hooks.viewportResize(...p);
2491
+ }
2492
+ viewportResizeCb(...p);
2493
+ };
2494
+ o.inputCb = (...p) => {
2495
+ if (hooks.input) {
2496
+ hooks.input(...p);
2497
+ }
2498
+ inputCb(...p);
2499
+ };
2500
+ o.mediaInteractionCb = (...p) => {
2501
+ if (hooks.mediaInteaction) {
2502
+ hooks.mediaInteaction(...p);
2503
+ }
2504
+ mediaInteractionCb(...p);
2505
+ };
2506
+ o.styleSheetRuleCb = (...p) => {
2507
+ if (hooks.styleSheetRule) {
2508
+ hooks.styleSheetRule(...p);
2509
+ }
2510
+ styleSheetRuleCb(...p);
2511
+ };
2512
+ o.styleDeclarationCb = (...p) => {
2513
+ if (hooks.styleDeclaration) {
2514
+ hooks.styleDeclaration(...p);
2515
+ }
2516
+ styleDeclarationCb(...p);
2517
+ };
2518
+ o.canvasMutationCb = (...p) => {
2519
+ if (hooks.canvasMutation) {
2520
+ hooks.canvasMutation(...p);
2521
+ }
2522
+ canvasMutationCb(...p);
2523
+ };
2524
+ o.fontCb = (...p) => {
2525
+ if (hooks.font) {
2526
+ hooks.font(...p);
2527
+ }
2528
+ fontCb(...p);
2529
+ };
2530
+ o.selectionCb = (...p) => {
2531
+ if (hooks.selection) {
2532
+ hooks.selection(...p);
2533
+ }
2534
+ selectionCb(...p);
2535
+ };
2536
+ }
2537
+ function initObservers(o, hooks = {}) {
2538
+ const currentWindow = o.doc.defaultView;
2539
+ if (!currentWindow) {
2540
+ return () => {
2541
+ };
2542
+ }
2543
+ mergeHooks(o, hooks);
2544
+ const mutationObserver = initMutationObserver(o, o.doc);
2545
+ const mousemoveHandler = initMoveObserver(o);
2546
+ const mouseInteractionHandler = initMouseInteractionObserver(o);
2547
+ const scrollHandler = initScrollObserver(o);
2548
+ const viewportResizeHandler = initViewportResizeObserver(o);
2549
+ const inputHandler = initInputObserver(o);
2550
+ const mediaInteractionHandler = initMediaInteractionObserver(o);
2551
+ const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });
2552
+ const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);
2553
+ const styleDeclarationObserver = initStyleDeclarationObserver(o, {
2554
+ win: currentWindow,
2555
+ });
2556
+ const fontObserver = o.collectFonts
2557
+ ? initFontObserver(o)
2558
+ : () => {
2559
+ };
2560
+ const selectionObserver = initSelectionObserver(o);
2561
+ const pluginHandlers = [];
2562
+ for (const plugin of o.plugins) {
2563
+ pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
2564
+ }
2565
+ return () => {
2566
+ mutationBuffers.forEach((b) => b.reset());
2567
+ mutationObserver.disconnect();
2568
+ mousemoveHandler();
2569
+ mouseInteractionHandler();
2570
+ scrollHandler();
2571
+ viewportResizeHandler();
2572
+ inputHandler();
2573
+ mediaInteractionHandler();
2574
+ styleSheetObserver();
2575
+ adoptedStyleSheetObserver();
2576
+ styleDeclarationObserver();
2577
+ fontObserver();
2578
+ selectionObserver();
2579
+ pluginHandlers.forEach((h) => h());
2580
+ };
2581
+ }
2582
+
2583
+ class CrossOriginIframeMirror {
2584
+ constructor(generateIdFn) {
2585
+ this.generateIdFn = generateIdFn;
2586
+ this.iframeIdToRemoteIdMap = new WeakMap();
2587
+ this.iframeRemoteIdToIdMap = new WeakMap();
2588
+ }
2589
+ getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
2590
+ const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
2591
+ const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
2592
+ let id = idToRemoteIdMap.get(remoteId);
2593
+ if (!id) {
2594
+ id = this.generateIdFn();
2595
+ idToRemoteIdMap.set(remoteId, id);
2596
+ remoteIdToIdMap.set(id, remoteId);
2597
+ }
2598
+ return id;
2599
+ }
2600
+ getIds(iframe, remoteId) {
2601
+ const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
2602
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
2603
+ return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));
2604
+ }
2605
+ getRemoteId(iframe, id, map) {
2606
+ const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
2607
+ if (typeof id !== 'number')
2608
+ return id;
2609
+ const remoteId = remoteIdToIdMap.get(id);
2610
+ if (!remoteId)
2611
+ return -1;
2612
+ return remoteId;
2613
+ }
2614
+ getRemoteIds(iframe, ids) {
2615
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
2616
+ return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));
2617
+ }
2618
+ reset(iframe) {
2619
+ if (!iframe) {
2620
+ this.iframeIdToRemoteIdMap = new WeakMap();
2621
+ this.iframeRemoteIdToIdMap = new WeakMap();
2622
+ return;
2623
+ }
2624
+ this.iframeIdToRemoteIdMap.delete(iframe);
2625
+ this.iframeRemoteIdToIdMap.delete(iframe);
2626
+ }
2627
+ getIdToRemoteIdMap(iframe) {
2628
+ let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
2629
+ if (!idToRemoteIdMap) {
2630
+ idToRemoteIdMap = new Map();
2631
+ this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
2632
+ }
2633
+ return idToRemoteIdMap;
2634
+ }
2635
+ getRemoteIdToIdMap(iframe) {
2636
+ let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
2637
+ if (!remoteIdToIdMap) {
2638
+ remoteIdToIdMap = new Map();
2639
+ this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
2640
+ }
2641
+ return remoteIdToIdMap;
2642
+ }
2643
+ }
2644
+
2645
+ class IframeManager {
2646
+ constructor(options) {
2647
+ this.iframes = new WeakMap();
2648
+ this.crossOriginIframeMap = new WeakMap();
2649
+ this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
2650
+ this.mutationCb = options.mutationCb;
2651
+ this.wrappedEmit = options.wrappedEmit;
2652
+ this.stylesheetManager = options.stylesheetManager;
2653
+ this.recordCrossOriginIframes = options.recordCrossOriginIframes;
2654
+ this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
2655
+ this.mirror = options.mirror;
2656
+ if (this.recordCrossOriginIframes) {
2657
+ window.addEventListener('message', this.handleMessage.bind(this));
2658
+ }
2659
+ }
2660
+ addIframe(iframeEl) {
2661
+ this.iframes.set(iframeEl, true);
2662
+ if (iframeEl.contentWindow)
2663
+ this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
2664
+ }
2665
+ addLoadListener(cb) {
2666
+ this.loadListener = cb;
2667
+ }
2668
+ attachIframe(iframeEl, childSn) {
2669
+ var _a;
2670
+ this.mutationCb({
2671
+ adds: [
2672
+ {
2673
+ parentId: this.mirror.getId(iframeEl),
2674
+ nextId: null,
2675
+ node: childSn,
2676
+ },
2677
+ ],
2678
+ removes: [],
2679
+ texts: [],
2680
+ attributes: [],
2681
+ isAttachIframe: true,
2682
+ });
2683
+ (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);
2684
+ if (iframeEl.contentDocument &&
2685
+ iframeEl.contentDocument.adoptedStyleSheets &&
2686
+ iframeEl.contentDocument.adoptedStyleSheets.length > 0)
2687
+ this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
2688
+ }
2689
+ handleMessage(message) {
2690
+ if (message.data.type === 'rrweb') {
2691
+ const iframeSourceWindow = message.source;
2692
+ if (!iframeSourceWindow)
2693
+ return;
2694
+ const iframeEl = this.crossOriginIframeMap.get(message.source);
2695
+ if (!iframeEl)
2696
+ return;
2697
+ const transformedEvent = this.transformCrossOriginEvent(iframeEl, message.data.event);
2698
+ if (transformedEvent)
2699
+ this.wrappedEmit(transformedEvent, message.data.isCheckout);
2700
+ }
2701
+ }
2702
+ transformCrossOriginEvent(iframeEl, e) {
2703
+ var _a;
2704
+ switch (e.type) {
2705
+ case EventType.FullSnapshot: {
2706
+ this.crossOriginIframeMirror.reset(iframeEl);
2707
+ this.crossOriginIframeStyleMirror.reset(iframeEl);
2708
+ this.replaceIdOnNode(e.data.node, iframeEl);
2709
+ return {
2710
+ timestamp: e.timestamp,
2711
+ type: EventType.IncrementalSnapshot,
2712
+ data: {
2713
+ source: IncrementalSource.Mutation,
2714
+ adds: [
2715
+ {
2716
+ parentId: this.mirror.getId(iframeEl),
2717
+ nextId: null,
2718
+ node: e.data.node,
2719
+ },
2720
+ ],
2721
+ removes: [],
2722
+ texts: [],
2723
+ attributes: [],
2724
+ isAttachIframe: true,
2725
+ },
2726
+ };
2727
+ }
2728
+ case EventType.Meta:
2729
+ case EventType.Load:
2730
+ case EventType.DomContentLoaded: {
2731
+ return false;
2732
+ }
2733
+ case EventType.Plugin: {
2734
+ return e;
2735
+ }
2736
+ case EventType.Custom: {
2737
+ this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);
2738
+ return e;
2739
+ }
2740
+ case EventType.IncrementalSnapshot: {
2741
+ switch (e.data.source) {
2742
+ case IncrementalSource.Mutation: {
2743
+ e.data.adds.forEach((n) => {
2744
+ this.replaceIds(n, iframeEl, [
2745
+ 'parentId',
2746
+ 'nextId',
2747
+ 'previousId',
2748
+ ]);
2749
+ this.replaceIdOnNode(n.node, iframeEl);
2750
+ });
2751
+ e.data.removes.forEach((n) => {
2752
+ this.replaceIds(n, iframeEl, ['parentId', 'id']);
2753
+ });
2754
+ e.data.attributes.forEach((n) => {
2755
+ this.replaceIds(n, iframeEl, ['id']);
2756
+ });
2757
+ e.data.texts.forEach((n) => {
2758
+ this.replaceIds(n, iframeEl, ['id']);
2759
+ });
2760
+ return e;
2761
+ }
2762
+ case IncrementalSource.Drag:
2763
+ case IncrementalSource.TouchMove:
2764
+ case IncrementalSource.MouseMove: {
2765
+ e.data.positions.forEach((p) => {
2766
+ this.replaceIds(p, iframeEl, ['id']);
2767
+ });
2768
+ return e;
2769
+ }
2770
+ case IncrementalSource.ViewportResize: {
2771
+ return false;
2772
+ }
2773
+ case IncrementalSource.MediaInteraction:
2774
+ case IncrementalSource.MouseInteraction:
2775
+ case IncrementalSource.Scroll:
2776
+ case IncrementalSource.CanvasMutation:
2777
+ case IncrementalSource.Input: {
2778
+ this.replaceIds(e.data, iframeEl, ['id']);
2779
+ return e;
2780
+ }
2781
+ case IncrementalSource.StyleSheetRule:
2782
+ case IncrementalSource.StyleDeclaration: {
2783
+ this.replaceIds(e.data, iframeEl, ['id']);
2784
+ this.replaceStyleIds(e.data, iframeEl, ['styleId']);
2785
+ return e;
2786
+ }
2787
+ case IncrementalSource.Font: {
2788
+ return e;
2789
+ }
2790
+ case IncrementalSource.Selection: {
2791
+ e.data.ranges.forEach((range) => {
2792
+ this.replaceIds(range, iframeEl, ['start', 'end']);
2793
+ });
2794
+ return e;
2795
+ }
2796
+ case IncrementalSource.AdoptedStyleSheet: {
2797
+ this.replaceIds(e.data, iframeEl, ['id']);
2798
+ this.replaceStyleIds(e.data, iframeEl, ['styleIds']);
2799
+ (_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach((style) => {
2800
+ this.replaceStyleIds(style, iframeEl, ['styleId']);
2801
+ });
2802
+ return e;
2803
+ }
2804
+ }
2805
+ }
2806
+ }
2807
+ }
2808
+ replace(iframeMirror, obj, iframeEl, keys) {
2809
+ for (const key of keys) {
2810
+ if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')
2811
+ continue;
2812
+ if (Array.isArray(obj[key])) {
2813
+ obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
2814
+ }
2815
+ else {
2816
+ obj[key] = iframeMirror.getId(iframeEl, obj[key]);
2817
+ }
2818
+ }
2819
+ return obj;
2820
+ }
2821
+ replaceIds(obj, iframeEl, keys) {
2822
+ return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
2823
+ }
2824
+ replaceStyleIds(obj, iframeEl, keys) {
2825
+ return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
2826
+ }
2827
+ replaceIdOnNode(node, iframeEl) {
2828
+ this.replaceIds(node, iframeEl, ['id']);
2829
+ if ('childNodes' in node) {
2830
+ node.childNodes.forEach((child) => {
2831
+ this.replaceIdOnNode(child, iframeEl);
2832
+ });
2833
+ }
2834
+ }
2835
+ }
2836
+
2837
+ class ShadowDomManager {
2838
+ constructor(options) {
2839
+ this.shadowDoms = new WeakSet();
2840
+ this.restorePatches = [];
2841
+ this.mutationCb = options.mutationCb;
2842
+ this.scrollCb = options.scrollCb;
2843
+ this.bypassOptions = options.bypassOptions;
2844
+ this.mirror = options.mirror;
2845
+ const manager = this;
2846
+ this.restorePatches.push(patch(Element.prototype, 'attachShadow', function (original) {
2847
+ return function (option) {
2848
+ const shadowRoot = original.call(this, option);
2849
+ if (this.shadowRoot)
2850
+ manager.addShadowRoot(this.shadowRoot, this.ownerDocument);
2851
+ return shadowRoot;
2852
+ };
2853
+ }));
2854
+ }
2855
+ addShadowRoot(shadowRoot, doc) {
2856
+ if (!isNativeShadowDom(shadowRoot))
2857
+ return;
2858
+ if (this.shadowDoms.has(shadowRoot))
2859
+ return;
2860
+ this.shadowDoms.add(shadowRoot);
2861
+ initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);
2862
+ initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));
2863
+ setTimeout(() => {
2864
+ if (shadowRoot.adoptedStyleSheets &&
2865
+ shadowRoot.adoptedStyleSheets.length > 0)
2866
+ this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
2867
+ initAdoptedStyleSheetObserver({
2868
+ mirror: this.mirror,
2869
+ stylesheetManager: this.bypassOptions.stylesheetManager,
2870
+ }, shadowRoot);
2871
+ }, 0);
2872
+ }
2873
+ observeAttachShadow(iframeElement) {
2874
+ if (iframeElement.contentWindow) {
2875
+ const manager = this;
2876
+ this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {
2877
+ return function (option) {
2878
+ const shadowRoot = original.call(this, option);
2879
+ if (this.shadowRoot)
2880
+ manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);
2881
+ return shadowRoot;
2882
+ };
2883
+ }));
2884
+ }
2885
+ }
2886
+ reset() {
2887
+ this.restorePatches.forEach((restorePatch) => restorePatch());
2888
+ this.shadowDoms = new WeakSet();
2889
+ }
2890
+ }
2891
+
2892
+ /*! *****************************************************************************
2893
+ Copyright (c) Microsoft Corporation.
2894
+
2895
+ Permission to use, copy, modify, and/or distribute this software for any
2896
+ purpose with or without fee is hereby granted.
2897
+
2898
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2899
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2900
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2901
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2902
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2903
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2904
+ PERFORMANCE OF THIS SOFTWARE.
2905
+ ***************************************************************************** */
2906
+
2907
+ function __rest(s, e) {
2908
+ var t = {};
2909
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2910
+ t[p] = s[p];
2911
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
2912
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2913
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2914
+ t[p[i]] = s[p[i]];
2915
+ }
2916
+ return t;
2917
+ }
2918
+
2919
+ function __awaiter(thisArg, _arguments, P, generator) {
2920
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2921
+ return new (P || (P = Promise))(function (resolve, reject) {
2922
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2923
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2924
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2925
+ step((generator = generator.apply(thisArg, [])).next());
2926
+ });
2927
+ }
2928
+
2929
+ /*
2930
+ * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
2931
+ * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
2932
+ * Released under MIT License
2933
+ */
2934
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2935
+ // Use a lookup table to find the index.
2936
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
2937
+ for (var i$1 = 0; i$1 < chars.length; i$1++) {
2938
+ lookup[chars.charCodeAt(i$1)] = i$1;
2939
+ }
2940
+ var encode = function (arraybuffer) {
2941
+ var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
2942
+ for (i = 0; i < len; i += 3) {
2943
+ base64 += chars[bytes[i] >> 2];
2944
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
2945
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
2946
+ base64 += chars[bytes[i + 2] & 63];
2947
+ }
2948
+ if (len % 3 === 2) {
2949
+ base64 = base64.substring(0, base64.length - 1) + '=';
2950
+ }
2951
+ else if (len % 3 === 1) {
2952
+ base64 = base64.substring(0, base64.length - 2) + '==';
2953
+ }
2954
+ return base64;
2955
+ };
2956
+
2957
+ const canvasVarMap = new Map();
2958
+ function variableListFor(ctx, ctor) {
2959
+ let contextMap = canvasVarMap.get(ctx);
2960
+ if (!contextMap) {
2961
+ contextMap = new Map();
2962
+ canvasVarMap.set(ctx, contextMap);
2963
+ }
2964
+ if (!contextMap.has(ctor)) {
2965
+ contextMap.set(ctor, []);
2966
+ }
2967
+ return contextMap.get(ctor);
2968
+ }
2969
+ const saveWebGLVar = (value, win, ctx) => {
2970
+ if (!value ||
2971
+ !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))
2972
+ return;
2973
+ const name = value.constructor.name;
2974
+ const list = variableListFor(ctx, name);
2975
+ let index = list.indexOf(value);
2976
+ if (index === -1) {
2977
+ index = list.length;
2978
+ list.push(value);
2979
+ }
2980
+ return index;
2981
+ };
2982
+ function serializeArg(value, win, ctx) {
2983
+ if (value instanceof Array) {
2984
+ return value.map((arg) => serializeArg(arg, win, ctx));
2985
+ }
2986
+ else if (value === null) {
2987
+ return value;
2988
+ }
2989
+ else if (value instanceof Float32Array ||
2990
+ value instanceof Float64Array ||
2991
+ value instanceof Int32Array ||
2992
+ value instanceof Uint32Array ||
2993
+ value instanceof Uint8Array ||
2994
+ value instanceof Uint16Array ||
2995
+ value instanceof Int16Array ||
2996
+ value instanceof Int8Array ||
2997
+ value instanceof Uint8ClampedArray) {
2998
+ const name = value.constructor.name;
2999
+ return {
3000
+ rr_type: name,
3001
+ args: [Object.values(value)],
3002
+ };
3003
+ }
3004
+ else if (value instanceof ArrayBuffer) {
3005
+ const name = value.constructor.name;
3006
+ const base64 = encode(value);
3007
+ return {
3008
+ rr_type: name,
3009
+ base64,
3010
+ };
3011
+ }
3012
+ else if (value instanceof DataView) {
3013
+ const name = value.constructor.name;
3014
+ return {
3015
+ rr_type: name,
3016
+ args: [
3017
+ serializeArg(value.buffer, win, ctx),
3018
+ value.byteOffset,
3019
+ value.byteLength,
3020
+ ],
3021
+ };
3022
+ }
3023
+ else if (value instanceof HTMLImageElement) {
3024
+ const name = value.constructor.name;
3025
+ const { src } = value;
3026
+ return {
3027
+ rr_type: name,
3028
+ src,
3029
+ };
3030
+ }
3031
+ else if (value instanceof HTMLCanvasElement) {
3032
+ const name = 'HTMLImageElement';
3033
+ const src = value.toDataURL();
3034
+ return {
3035
+ rr_type: name,
3036
+ src,
3037
+ };
3038
+ }
3039
+ else if (value instanceof ImageData) {
3040
+ const name = value.constructor.name;
3041
+ return {
3042
+ rr_type: name,
3043
+ args: [serializeArg(value.data, win, ctx), value.width, value.height],
3044
+ };
3045
+ }
3046
+ else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {
3047
+ const name = value.constructor.name;
3048
+ const index = saveWebGLVar(value, win, ctx);
3049
+ return {
3050
+ rr_type: name,
3051
+ index: index,
3052
+ };
3053
+ }
3054
+ return value;
3055
+ }
3056
+ const serializeArgs = (args, win, ctx) => {
3057
+ return [...args].map((arg) => serializeArg(arg, win, ctx));
3058
+ };
3059
+ const isInstanceOfWebGLObject = (value, win) => {
3060
+ const webGLConstructorNames = [
3061
+ 'WebGLActiveInfo',
3062
+ 'WebGLBuffer',
3063
+ 'WebGLFramebuffer',
3064
+ 'WebGLProgram',
3065
+ 'WebGLRenderbuffer',
3066
+ 'WebGLShader',
3067
+ 'WebGLShaderPrecisionFormat',
3068
+ 'WebGLTexture',
3069
+ 'WebGLUniformLocation',
3070
+ 'WebGLVertexArrayObject',
3071
+ 'WebGLVertexArrayObjectOES',
3072
+ ];
3073
+ const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');
3074
+ return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));
3075
+ };
3076
+
3077
+ function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
3078
+ const handlers = [];
3079
+ const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
3080
+ for (const prop of props2D) {
3081
+ try {
3082
+ if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {
3083
+ continue;
3084
+ }
3085
+ const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {
3086
+ return function (...args) {
3087
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
3088
+ setTimeout(() => {
3089
+ const recordArgs = serializeArgs([...args], win, this);
3090
+ cb(this.canvas, {
3091
+ type: CanvasContext['2D'],
3092
+ property: prop,
3093
+ args: recordArgs,
3094
+ });
3095
+ }, 0);
3096
+ }
3097
+ return original.apply(this, args);
3098
+ };
3099
+ });
3100
+ handlers.push(restoreHandler);
3101
+ }
3102
+ catch (_a) {
3103
+ const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
3104
+ set(v) {
3105
+ cb(this.canvas, {
3106
+ type: CanvasContext['2D'],
3107
+ property: prop,
3108
+ args: [v],
3109
+ setter: true,
3110
+ });
3111
+ },
3112
+ });
3113
+ handlers.push(hookHandler);
3114
+ }
3115
+ }
3116
+ return () => {
3117
+ handlers.forEach((h) => h());
3118
+ };
3119
+ }
3120
+
3121
+ function initCanvasContextObserver(win, blockClass, blockSelector) {
3122
+ const handlers = [];
3123
+ try {
3124
+ const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {
3125
+ return function (contextType, ...args) {
3126
+ if (!isBlocked(this, blockClass, blockSelector, true)) {
3127
+ if (!('__context' in this))
3128
+ this.__context = contextType;
3129
+ }
3130
+ return original.apply(this, [contextType, ...args]);
3131
+ };
3132
+ });
3133
+ handlers.push(restoreHandler);
3134
+ }
3135
+ catch (_a) {
3136
+ console.error('failed to patch HTMLCanvasElement.prototype.getContext');
3137
+ }
3138
+ return () => {
3139
+ handlers.forEach((h) => h());
3140
+ };
3141
+ }
3142
+
3143
+ function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {
3144
+ const handlers = [];
3145
+ const props = Object.getOwnPropertyNames(prototype);
3146
+ for (const prop of props) {
3147
+ if ([
3148
+ 'isContextLost',
3149
+ 'canvas',
3150
+ 'drawingBufferWidth',
3151
+ 'drawingBufferHeight',
3152
+ ].includes(prop)) {
3153
+ continue;
3154
+ }
3155
+ try {
3156
+ if (typeof prototype[prop] !== 'function') {
3157
+ continue;
3158
+ }
3159
+ const restoreHandler = patch(prototype, prop, function (original) {
3160
+ return function (...args) {
3161
+ const result = original.apply(this, args);
3162
+ saveWebGLVar(result, win, this);
3163
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
3164
+ const recordArgs = serializeArgs([...args], win, this);
3165
+ const mutation = {
3166
+ type,
3167
+ property: prop,
3168
+ args: recordArgs,
3169
+ };
3170
+ cb(this.canvas, mutation);
3171
+ }
3172
+ return result;
3173
+ };
3174
+ });
3175
+ handlers.push(restoreHandler);
3176
+ }
3177
+ catch (_a) {
3178
+ const hookHandler = hookSetter(prototype, prop, {
3179
+ set(v) {
3180
+ cb(this.canvas, {
3181
+ type,
3182
+ property: prop,
3183
+ args: [v],
3184
+ setter: true,
3185
+ });
3186
+ },
3187
+ });
3188
+ handlers.push(hookHandler);
3189
+ }
3190
+ }
3191
+ return handlers;
3192
+ }
3193
+ function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {
3194
+ const handlers = [];
3195
+ handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));
3196
+ if (typeof win.WebGL2RenderingContext !== 'undefined') {
3197
+ handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));
3198
+ }
3199
+ return () => {
3200
+ handlers.forEach((h) => h());
3201
+ };
3202
+ }
3203
+
3204
+ var WorkerClass = null;
3205
+
3206
+ try {
3207
+ var WorkerThreads =
3208
+ typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') ||
3209
+ typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') ||
3210
+ typeof require === 'function' && require('worker_threads');
3211
+ WorkerClass = WorkerThreads.Worker;
3212
+ } catch(e) {} // eslint-disable-line
3213
+
3214
+ function decodeBase64$1(base64, enableUnicode) {
3215
+ return Buffer.from(base64, 'base64').toString('utf8');
3216
+ }
3217
+
3218
+ function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) {
3219
+ var source = decodeBase64$1(base64);
3220
+ var start = source.indexOf('\n', 10) + 1;
3221
+ var body = source.substring(start) + ('');
3222
+ return function WorkerFactory(options) {
3223
+ return new WorkerClass(body, Object.assign({}, options, { eval: true }));
3224
+ };
3225
+ }
3226
+
3227
+ function decodeBase64(base64, enableUnicode) {
3228
+ var binaryString = atob(base64);
3229
+ return binaryString;
3230
+ }
3231
+
3232
+ function createURL(base64, sourcemapArg, enableUnicodeArg) {
3233
+ var source = decodeBase64(base64);
3234
+ var start = source.indexOf('\n', 10) + 1;
3235
+ var body = source.substring(start) + ('');
3236
+ var blob = new Blob([body], { type: 'application/javascript' });
3237
+ return URL.createObjectURL(blob);
3238
+ }
3239
+
3240
+ function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) {
3241
+ var url;
3242
+ return function WorkerFactory(options) {
3243
+ url = url || createURL(base64);
3244
+ return new Worker(url, options);
3245
+ };
3246
+ }
3247
+
3248
+ var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
3249
+
3250
+ function isNodeJS() {
3251
+ return kIsNodeJS;
3252
+ }
3253
+
3254
+ function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
3255
+ if (isNodeJS()) {
3256
+ return createBase64WorkerFactory$2(base64);
3257
+ }
3258
+ return createBase64WorkerFactory$1(base64);
3259
+ }
3260
+
3261
+ var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=');
3262
+
3263
+ class CanvasManager {
3264
+ constructor(options) {
3265
+ this.pendingCanvasMutations = new Map();
3266
+ this.rafStamps = { latestId: 0, invokeId: null };
3267
+ this.frozen = false;
3268
+ this.locked = false;
3269
+ this.processMutation = (target, mutation) => {
3270
+ const newFrame = this.rafStamps.invokeId &&
3271
+ this.rafStamps.latestId !== this.rafStamps.invokeId;
3272
+ if (newFrame || !this.rafStamps.invokeId)
3273
+ this.rafStamps.invokeId = this.rafStamps.latestId;
3274
+ if (!this.pendingCanvasMutations.has(target)) {
3275
+ this.pendingCanvasMutations.set(target, []);
3276
+ }
3277
+ this.pendingCanvasMutations.get(target).push(mutation);
3278
+ };
3279
+ const { sampling = 'all', win, blockClass, blockSelector, recordCanvas, dataURLOptions, } = options;
3280
+ this.mutationCb = options.mutationCb;
3281
+ this.mirror = options.mirror;
3282
+ if (recordCanvas && sampling === 'all')
3283
+ this.initCanvasMutationObserver(win, blockClass, blockSelector);
3284
+ if (recordCanvas && typeof sampling === 'number')
3285
+ this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
3286
+ dataURLOptions,
3287
+ });
3288
+ }
3289
+ reset() {
3290
+ this.pendingCanvasMutations.clear();
3291
+ this.resetObservers && this.resetObservers();
3292
+ }
3293
+ freeze() {
3294
+ this.frozen = true;
3295
+ }
3296
+ unfreeze() {
3297
+ this.frozen = false;
3298
+ }
3299
+ lock() {
3300
+ this.locked = true;
3301
+ }
3302
+ unlock() {
3303
+ this.locked = false;
3304
+ }
3305
+ initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
3306
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
3307
+ const snapshotInProgressMap = new Map();
3308
+ const worker = new WorkerFactory();
3309
+ worker.onmessage = (e) => {
3310
+ const { id } = e.data;
3311
+ snapshotInProgressMap.set(id, false);
3312
+ if (!('base64' in e.data))
3313
+ return;
3314
+ const { base64, type, width, height } = e.data;
3315
+ this.mutationCb({
3316
+ id,
3317
+ type: CanvasContext['2D'],
3318
+ commands: [
3319
+ {
3320
+ property: 'clearRect',
3321
+ args: [0, 0, width, height],
3322
+ },
3323
+ {
3324
+ property: 'drawImage',
3325
+ args: [
3326
+ {
3327
+ rr_type: 'ImageBitmap',
3328
+ args: [
3329
+ {
3330
+ rr_type: 'Blob',
3331
+ data: [{ rr_type: 'ArrayBuffer', base64 }],
3332
+ type,
3333
+ },
3334
+ ],
3335
+ },
3336
+ 0,
3337
+ 0,
3338
+ ],
3339
+ },
3340
+ ],
3341
+ });
3342
+ };
3343
+ const timeBetweenSnapshots = 1000 / fps;
3344
+ let lastSnapshotTime = 0;
3345
+ let rafId;
3346
+ const getCanvas = () => {
3347
+ const matchedCanvas = [];
3348
+ win.document.querySelectorAll('canvas').forEach((canvas) => {
3349
+ if (!isBlocked(canvas, blockClass, blockSelector, true)) {
3350
+ matchedCanvas.push(canvas);
3351
+ }
3352
+ });
3353
+ return matchedCanvas;
3354
+ };
3355
+ const takeCanvasSnapshots = (timestamp) => {
3356
+ if (lastSnapshotTime &&
3357
+ timestamp - lastSnapshotTime < timeBetweenSnapshots) {
3358
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
3359
+ return;
3360
+ }
3361
+ lastSnapshotTime = timestamp;
3362
+ getCanvas()
3363
+ .forEach((canvas) => __awaiter(this, void 0, void 0, function* () {
3364
+ var _a;
3365
+ const id = this.mirror.getId(canvas);
3366
+ if (snapshotInProgressMap.get(id))
3367
+ return;
3368
+ snapshotInProgressMap.set(id, true);
3369
+ if (['webgl', 'webgl2'].includes(canvas.__context)) {
3370
+ const context = canvas.getContext(canvas.__context);
3371
+ if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {
3372
+ context === null || context === void 0 ? void 0 : context.clear(context.COLOR_BUFFER_BIT);
3373
+ }
3374
+ }
3375
+ const bitmap = yield createImageBitmap(canvas);
3376
+ worker.postMessage({
3377
+ id,
3378
+ bitmap,
3379
+ width: canvas.width,
3380
+ height: canvas.height,
3381
+ dataURLOptions: options.dataURLOptions,
3382
+ }, [bitmap]);
3383
+ }));
3384
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
3385
+ };
3386
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
3387
+ this.resetObservers = () => {
3388
+ canvasContextReset();
3389
+ cancelAnimationFrame(rafId);
3390
+ };
3391
+ }
3392
+ initCanvasMutationObserver(win, blockClass, blockSelector) {
3393
+ this.startRAFTimestamping();
3394
+ this.startPendingCanvasMutationFlusher();
3395
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
3396
+ const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
3397
+ const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);
3398
+ this.resetObservers = () => {
3399
+ canvasContextReset();
3400
+ canvas2DReset();
3401
+ canvasWebGL1and2Reset();
3402
+ };
3403
+ }
3404
+ startPendingCanvasMutationFlusher() {
3405
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
3406
+ }
3407
+ startRAFTimestamping() {
3408
+ const setLatestRAFTimestamp = (timestamp) => {
3409
+ this.rafStamps.latestId = timestamp;
3410
+ requestAnimationFrame(setLatestRAFTimestamp);
3411
+ };
3412
+ requestAnimationFrame(setLatestRAFTimestamp);
3413
+ }
3414
+ flushPendingCanvasMutations() {
3415
+ this.pendingCanvasMutations.forEach((values, canvas) => {
3416
+ const id = this.mirror.getId(canvas);
3417
+ this.flushPendingCanvasMutationFor(canvas, id);
3418
+ });
3419
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
3420
+ }
3421
+ flushPendingCanvasMutationFor(canvas, id) {
3422
+ if (this.frozen || this.locked) {
3423
+ return;
3424
+ }
3425
+ const valuesWithType = this.pendingCanvasMutations.get(canvas);
3426
+ if (!valuesWithType || id === -1)
3427
+ return;
3428
+ const values = valuesWithType.map((value) => {
3429
+ const rest = __rest(value, ["type"]);
3430
+ return rest;
3431
+ });
3432
+ const { type } = valuesWithType[0];
3433
+ this.mutationCb({ id, type, commands: values });
3434
+ this.pendingCanvasMutations.delete(canvas);
3435
+ }
3436
+ }
3437
+
3438
+ class StylesheetManager {
3439
+ constructor(options) {
3440
+ this.trackedLinkElements = new WeakSet();
3441
+ this.styleMirror = new StyleSheetMirror();
3442
+ this.mutationCb = options.mutationCb;
3443
+ this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
3444
+ }
3445
+ attachLinkElement(linkEl, childSn) {
3446
+ if ('_cssText' in childSn.attributes)
3447
+ this.mutationCb({
3448
+ adds: [],
3449
+ removes: [],
3450
+ texts: [],
3451
+ attributes: [
3452
+ {
3453
+ id: childSn.id,
3454
+ attributes: childSn
3455
+ .attributes,
3456
+ },
3457
+ ],
3458
+ });
3459
+ this.trackLinkElement(linkEl);
3460
+ }
3461
+ trackLinkElement(linkEl) {
3462
+ if (this.trackedLinkElements.has(linkEl))
3463
+ return;
3464
+ this.trackedLinkElements.add(linkEl);
3465
+ this.trackStylesheetInLinkElement(linkEl);
3466
+ }
3467
+ adoptStyleSheets(sheets, hostId) {
3468
+ if (sheets.length === 0)
3469
+ return;
3470
+ const adoptedStyleSheetData = {
3471
+ id: hostId,
3472
+ styleIds: [],
3473
+ };
3474
+ const styles = [];
3475
+ for (const sheet of sheets) {
3476
+ let styleId;
3477
+ if (!this.styleMirror.has(sheet)) {
3478
+ styleId = this.styleMirror.add(sheet);
3479
+ const rules = Array.from(sheet.rules || CSSRule);
3480
+ styles.push({
3481
+ styleId,
3482
+ rules: rules.map((r, index) => {
3483
+ return {
3484
+ rule: getCssRuleString(r),
3485
+ index,
3486
+ };
3487
+ }),
3488
+ });
3489
+ }
3490
+ else
3491
+ styleId = this.styleMirror.getId(sheet);
3492
+ adoptedStyleSheetData.styleIds.push(styleId);
3493
+ }
3494
+ if (styles.length > 0)
3495
+ adoptedStyleSheetData.styles = styles;
3496
+ this.adoptedStyleSheetCb(adoptedStyleSheetData);
3497
+ }
3498
+ reset() {
3499
+ this.styleMirror.reset();
3500
+ this.trackedLinkElements = new WeakSet();
3501
+ }
3502
+ trackStylesheetInLinkElement(linkEl) {
3503
+ }
3504
+ }
3505
+
3506
+ function wrapEvent(e) {
3507
+ return Object.assign(Object.assign({}, e), { timestamp: Date.now() });
3508
+ }
3509
+ let wrappedEmit;
3510
+ let takeFullSnapshot;
3511
+ let canvasManager;
3512
+ let recording = false;
3513
+ const mirror = createMirror();
3514
+ function record(options = {}) {
3515
+ const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, ignoreClass = 'rr-ignore', maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), } = options;
3516
+ const inEmittingFrame = recordCrossOriginIframes
3517
+ ? window.parent === window
3518
+ : true;
3519
+ let passEmitsToParent = false;
3520
+ if (!inEmittingFrame) {
3521
+ try {
3522
+ window.parent.document;
3523
+ passEmitsToParent = false;
3524
+ }
3525
+ catch (e) {
3526
+ passEmitsToParent = true;
3527
+ }
3528
+ }
3529
+ if (inEmittingFrame && !emit) {
3530
+ throw new Error('emit function is required');
3531
+ }
3532
+ if (mousemoveWait !== undefined && sampling.mousemove === undefined) {
3533
+ sampling.mousemove = mousemoveWait;
3534
+ }
3535
+ mirror.reset();
3536
+ const maskInputOptions = maskAllInputs === true
3537
+ ? {
3538
+ color: true,
3539
+ date: true,
3540
+ 'datetime-local': true,
3541
+ email: true,
3542
+ month: true,
3543
+ number: true,
3544
+ range: true,
3545
+ search: true,
3546
+ tel: true,
3547
+ text: true,
3548
+ time: true,
3549
+ url: true,
3550
+ week: true,
3551
+ textarea: true,
3552
+ select: true,
3553
+ password: true,
3554
+ }
3555
+ : _maskInputOptions !== undefined
3556
+ ? _maskInputOptions
3557
+ : { password: true };
3558
+ const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'
3559
+ ? {
3560
+ script: true,
3561
+ comment: true,
3562
+ headFavicon: true,
3563
+ headWhitespace: true,
3564
+ headMetaSocial: true,
3565
+ headMetaRobots: true,
3566
+ headMetaHttpEquiv: true,
3567
+ headMetaVerification: true,
3568
+ headMetaAuthorship: _slimDOMOptions === 'all',
3569
+ headMetaDescKeywords: _slimDOMOptions === 'all',
3570
+ }
3571
+ : _slimDOMOptions
3572
+ ? _slimDOMOptions
3573
+ : {};
3574
+ polyfill();
3575
+ let lastFullSnapshotEvent;
3576
+ let incrementalSnapshotCount = 0;
3577
+ const eventProcessor = (e) => {
3578
+ for (const plugin of plugins || []) {
3579
+ if (plugin.eventProcessor) {
3580
+ e = plugin.eventProcessor(e);
3581
+ }
3582
+ }
3583
+ if (packFn) {
3584
+ e = packFn(e);
3585
+ }
3586
+ return e;
3587
+ };
3588
+ wrappedEmit = (e, isCheckout) => {
3589
+ var _a;
3590
+ if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&
3591
+ e.type !== EventType.FullSnapshot &&
3592
+ !(e.type === EventType.IncrementalSnapshot &&
3593
+ e.data.source === IncrementalSource.Mutation)) {
3594
+ mutationBuffers.forEach((buf) => buf.unfreeze());
3595
+ }
3596
+ if (inEmittingFrame) {
3597
+ emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);
3598
+ }
3599
+ else if (passEmitsToParent) {
3600
+ const message = {
3601
+ type: 'rrweb',
3602
+ event: eventProcessor(e),
3603
+ isCheckout,
3604
+ };
3605
+ window.parent.postMessage(message, '*');
3606
+ }
3607
+ if (e.type === EventType.FullSnapshot) {
3608
+ lastFullSnapshotEvent = e;
3609
+ incrementalSnapshotCount = 0;
3610
+ }
3611
+ else if (e.type === EventType.IncrementalSnapshot) {
3612
+ if (e.data.source === IncrementalSource.Mutation &&
3613
+ e.data.isAttachIframe) {
3614
+ return;
3615
+ }
3616
+ incrementalSnapshotCount++;
3617
+ const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
3618
+ const exceedTime = checkoutEveryNms &&
3619
+ e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
3620
+ if (exceedCount || exceedTime) {
3621
+ takeFullSnapshot(true);
3622
+ }
3623
+ }
3624
+ };
3625
+ const wrappedMutationEmit = (m) => {
3626
+ wrappedEmit(wrapEvent({
3627
+ type: EventType.IncrementalSnapshot,
3628
+ data: Object.assign({ source: IncrementalSource.Mutation }, m),
3629
+ }));
3630
+ };
3631
+ const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({
3632
+ type: EventType.IncrementalSnapshot,
3633
+ data: Object.assign({ source: IncrementalSource.Scroll }, p),
3634
+ }));
3635
+ const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({
3636
+ type: EventType.IncrementalSnapshot,
3637
+ data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),
3638
+ }));
3639
+ const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({
3640
+ type: EventType.IncrementalSnapshot,
3641
+ data: Object.assign({ source: IncrementalSource.AdoptedStyleSheet }, a),
3642
+ }));
3643
+ const stylesheetManager = new StylesheetManager({
3644
+ mutationCb: wrappedMutationEmit,
3645
+ adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,
3646
+ });
3647
+ const iframeManager = new IframeManager({
3648
+ mirror,
3649
+ mutationCb: wrappedMutationEmit,
3650
+ stylesheetManager: stylesheetManager,
3651
+ recordCrossOriginIframes,
3652
+ wrappedEmit,
3653
+ });
3654
+ for (const plugin of plugins || []) {
3655
+ if (plugin.getMirror)
3656
+ plugin.getMirror({
3657
+ nodeMirror: mirror,
3658
+ crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
3659
+ crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,
3660
+ });
3661
+ }
3662
+ canvasManager = new CanvasManager({
3663
+ recordCanvas,
3664
+ mutationCb: wrappedCanvasMutationEmit,
3665
+ win: window,
3666
+ blockClass,
3667
+ blockSelector,
3668
+ mirror,
3669
+ sampling: sampling.canvas,
3670
+ dataURLOptions,
3671
+ });
3672
+ const shadowDomManager = new ShadowDomManager({
3673
+ mutationCb: wrappedMutationEmit,
3674
+ scrollCb: wrappedScrollEmit,
3675
+ bypassOptions: {
3676
+ blockClass,
3677
+ blockSelector,
3678
+ maskTextClass,
3679
+ maskTextSelector,
3680
+ inlineStylesheet,
3681
+ maskInputOptions,
3682
+ dataURLOptions,
3683
+ maskTextFn,
3684
+ maskInputFn,
3685
+ recordCanvas,
3686
+ inlineImages,
3687
+ sampling,
3688
+ slimDOMOptions,
3689
+ iframeManager,
3690
+ stylesheetManager,
3691
+ canvasManager,
3692
+ keepIframeSrcFn,
3693
+ },
3694
+ mirror,
3695
+ });
3696
+ takeFullSnapshot = (isCheckout = false) => {
3697
+ var _a, _b, _c, _d, _e, _f;
3698
+ wrappedEmit(wrapEvent({
3699
+ type: EventType.Meta,
3700
+ data: {
3701
+ href: window.location.href,
3702
+ width: getWindowWidth(),
3703
+ height: getWindowHeight(),
3704
+ },
3705
+ }), isCheckout);
3706
+ stylesheetManager.reset();
3707
+ mutationBuffers.forEach((buf) => buf.lock());
3708
+ const node = snapshot(document, {
3709
+ mirror,
3710
+ blockClass,
3711
+ blockSelector,
3712
+ maskTextClass,
3713
+ maskTextSelector,
3714
+ inlineStylesheet,
3715
+ maskAllInputs: maskInputOptions,
3716
+ maskTextFn,
3717
+ slimDOM: slimDOMOptions,
3718
+ dataURLOptions,
3719
+ recordCanvas,
3720
+ inlineImages,
3721
+ onSerialize: (n) => {
3722
+ if (isSerializedIframe(n, mirror)) {
3723
+ iframeManager.addIframe(n);
3724
+ }
3725
+ if (isSerializedStylesheet(n, mirror)) {
3726
+ stylesheetManager.trackLinkElement(n);
3727
+ }
3728
+ if (hasShadowRoot(n)) {
3729
+ shadowDomManager.addShadowRoot(n.shadowRoot, document);
3730
+ }
3731
+ },
3732
+ onIframeLoad: (iframe, childSn) => {
3733
+ iframeManager.attachIframe(iframe, childSn);
3734
+ shadowDomManager.observeAttachShadow(iframe);
3735
+ },
3736
+ onStylesheetLoad: (linkEl, childSn) => {
3737
+ stylesheetManager.attachLinkElement(linkEl, childSn);
3738
+ },
3739
+ keepIframeSrcFn,
3740
+ });
3741
+ if (!node) {
3742
+ return console.warn('Failed to snapshot the document');
3743
+ }
3744
+ wrappedEmit(wrapEvent({
3745
+ type: EventType.FullSnapshot,
3746
+ data: {
3747
+ node,
3748
+ initialOffset: {
3749
+ left: window.pageXOffset !== undefined
3750
+ ? window.pageXOffset
3751
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||
3752
+ ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||
3753
+ ((_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) ||
3754
+ 0,
3755
+ top: window.pageYOffset !== undefined
3756
+ ? window.pageYOffset
3757
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||
3758
+ ((_e = (_d = document === null || document === void 0 ? void 0 : document.body) === null || _d === void 0 ? void 0 : _d.parentElement) === null || _e === void 0 ? void 0 : _e.scrollTop) ||
3759
+ ((_f = document === null || document === void 0 ? void 0 : document.body) === null || _f === void 0 ? void 0 : _f.scrollTop) ||
3760
+ 0,
3761
+ },
3762
+ },
3763
+ }));
3764
+ mutationBuffers.forEach((buf) => buf.unlock());
3765
+ if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)
3766
+ stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
3767
+ };
3768
+ try {
3769
+ const handlers = [];
3770
+ handlers.push(on('DOMContentLoaded', () => {
3771
+ wrappedEmit(wrapEvent({
3772
+ type: EventType.DomContentLoaded,
3773
+ data: {},
3774
+ }));
3775
+ }));
3776
+ const observe = (doc) => {
3777
+ var _a;
3778
+ return initObservers({
3779
+ mutationCb: wrappedMutationEmit,
3780
+ mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({
3781
+ type: EventType.IncrementalSnapshot,
3782
+ data: {
3783
+ source,
3784
+ positions,
3785
+ },
3786
+ })),
3787
+ mouseInteractionCb: (d) => wrappedEmit(wrapEvent({
3788
+ type: EventType.IncrementalSnapshot,
3789
+ data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),
3790
+ })),
3791
+ scrollCb: wrappedScrollEmit,
3792
+ viewportResizeCb: (d) => wrappedEmit(wrapEvent({
3793
+ type: EventType.IncrementalSnapshot,
3794
+ data: Object.assign({ source: IncrementalSource.ViewportResize }, d),
3795
+ })),
3796
+ inputCb: (v) => wrappedEmit(wrapEvent({
3797
+ type: EventType.IncrementalSnapshot,
3798
+ data: Object.assign({ source: IncrementalSource.Input }, v),
3799
+ })),
3800
+ mediaInteractionCb: (p) => wrappedEmit(wrapEvent({
3801
+ type: EventType.IncrementalSnapshot,
3802
+ data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),
3803
+ })),
3804
+ styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({
3805
+ type: EventType.IncrementalSnapshot,
3806
+ data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),
3807
+ })),
3808
+ styleDeclarationCb: (r) => wrappedEmit(wrapEvent({
3809
+ type: EventType.IncrementalSnapshot,
3810
+ data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),
3811
+ })),
3812
+ canvasMutationCb: wrappedCanvasMutationEmit,
3813
+ fontCb: (p) => wrappedEmit(wrapEvent({
3814
+ type: EventType.IncrementalSnapshot,
3815
+ data: Object.assign({ source: IncrementalSource.Font }, p),
3816
+ })),
3817
+ selectionCb: (p) => {
3818
+ wrappedEmit(wrapEvent({
3819
+ type: EventType.IncrementalSnapshot,
3820
+ data: Object.assign({ source: IncrementalSource.Selection }, p),
3821
+ }));
3822
+ },
3823
+ blockClass,
3824
+ ignoreClass,
3825
+ maskTextClass,
3826
+ maskTextSelector,
3827
+ maskInputOptions,
3828
+ inlineStylesheet,
3829
+ sampling,
3830
+ recordCanvas,
3831
+ inlineImages,
3832
+ userTriggeredOnInput,
3833
+ collectFonts,
3834
+ doc,
3835
+ maskInputFn,
3836
+ maskTextFn,
3837
+ keepIframeSrcFn,
3838
+ blockSelector,
3839
+ slimDOMOptions,
3840
+ dataURLOptions,
3841
+ mirror,
3842
+ iframeManager,
3843
+ stylesheetManager,
3844
+ shadowDomManager,
3845
+ canvasManager,
3846
+ ignoreCSSAttributes,
3847
+ plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({
3848
+ observer: p.observer,
3849
+ options: p.options,
3850
+ callback: (payload) => wrappedEmit(wrapEvent({
3851
+ type: EventType.Plugin,
3852
+ data: {
3853
+ plugin: p.name,
3854
+ payload,
3855
+ },
3856
+ })),
3857
+ }))) || [],
3858
+ }, hooks);
3859
+ };
3860
+ iframeManager.addLoadListener((iframeEl) => {
3861
+ handlers.push(observe(iframeEl.contentDocument));
3862
+ });
3863
+ const init = () => {
3864
+ takeFullSnapshot();
3865
+ handlers.push(observe(document));
3866
+ recording = true;
3867
+ };
3868
+ if (document.readyState === 'interactive' ||
3869
+ document.readyState === 'complete') {
3870
+ init();
3871
+ }
3872
+ else {
3873
+ handlers.push(on('load', () => {
3874
+ wrappedEmit(wrapEvent({
3875
+ type: EventType.Load,
3876
+ data: {},
3877
+ }));
3878
+ init();
3879
+ }, window));
3880
+ }
3881
+ return () => {
3882
+ handlers.forEach((h) => h());
3883
+ recording = false;
3884
+ };
3885
+ }
3886
+ catch (error) {
3887
+ console.warn(error);
3888
+ }
3889
+ }
3890
+ record.addCustomEvent = (tag, payload) => {
3891
+ if (!recording) {
3892
+ throw new Error('please add custom event after start recording');
3893
+ }
3894
+ wrappedEmit(wrapEvent({
3895
+ type: EventType.Custom,
3896
+ data: {
3897
+ tag,
3898
+ payload,
3899
+ },
3900
+ }));
3901
+ };
3902
+ record.freezePage = () => {
3903
+ mutationBuffers.forEach((buf) => buf.freeze());
3904
+ };
3905
+ record.takeFullSnapshot = (isCheckout) => {
3906
+ if (!recording) {
3907
+ throw new Error('please take full snapshot after start recording');
3908
+ }
3909
+ takeFullSnapshot(isCheckout);
3910
+ };
3911
+ record.mirror = mirror;
3912
+
3913
+ var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
3914
+ var fleb = new u8([
3915
+ 0,
3916
+ 0,
3917
+ 0,
3918
+ 0,
3919
+ 0,
3920
+ 0,
3921
+ 0,
3922
+ 0,
3923
+ 1,
3924
+ 1,
3925
+ 1,
3926
+ 1,
3927
+ 2,
3928
+ 2,
3929
+ 2,
3930
+ 2,
3931
+ 3,
3932
+ 3,
3933
+ 3,
3934
+ 3,
3935
+ 4,
3936
+ 4,
3937
+ 4,
3938
+ 4,
3939
+ 5,
3940
+ 5,
3941
+ 5,
3942
+ 5,
3943
+ 0,
3944
+ /* unused */
3945
+ 0,
3946
+ 0,
3947
+ /* impossible */
3948
+ 0
3949
+ ]);
3950
+ var fdeb = new u8([
3951
+ 0,
3952
+ 0,
3953
+ 0,
3954
+ 0,
3955
+ 1,
3956
+ 1,
3957
+ 2,
3958
+ 2,
3959
+ 3,
3960
+ 3,
3961
+ 4,
3962
+ 4,
3963
+ 5,
3964
+ 5,
3965
+ 6,
3966
+ 6,
3967
+ 7,
3968
+ 7,
3969
+ 8,
3970
+ 8,
3971
+ 9,
3972
+ 9,
3973
+ 10,
3974
+ 10,
3975
+ 11,
3976
+ 11,
3977
+ 12,
3978
+ 12,
3979
+ 13,
3980
+ 13,
3981
+ /* unused */
3982
+ 0,
3983
+ 0
3984
+ ]);
3985
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
3986
+ var freb = function(eb, start) {
3987
+ var b = new u16(31);
3988
+ for (var i = 0; i < 31; ++i) {
3989
+ b[i] = start += 1 << eb[i - 1];
3990
+ }
3991
+ var r = new u32(b[30]);
3992
+ for (var i = 1; i < 30; ++i) {
3993
+ for (var j = b[i]; j < b[i + 1]; ++j) {
3994
+ r[j] = j - b[i] << 5 | i;
3995
+ }
3996
+ }
3997
+ return [b, r];
3998
+ };
3999
+ var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
4000
+ fl[28] = 258, revfl[258] = 28;
4001
+ var _b = freb(fdeb, 0), revfd = _b[1];
4002
+ var rev = new u16(32768);
4003
+ for (var i = 0; i < 32768; ++i) {
4004
+ var x = (i & 43690) >>> 1 | (i & 21845) << 1;
4005
+ x = (x & 52428) >>> 2 | (x & 13107) << 2;
4006
+ x = (x & 61680) >>> 4 | (x & 3855) << 4;
4007
+ rev[i] = ((x & 65280) >>> 8 | (x & 255) << 8) >>> 1;
4008
+ }
4009
+ var hMap = function(cd, mb, r) {
4010
+ var s = cd.length;
4011
+ var i = 0;
4012
+ var l = new u16(mb);
4013
+ for (; i < s; ++i)
4014
+ ++l[cd[i] - 1];
4015
+ var le = new u16(mb);
4016
+ for (i = 0; i < mb; ++i) {
4017
+ le[i] = le[i - 1] + l[i - 1] << 1;
4018
+ }
4019
+ var co;
4020
+ if (r) {
4021
+ co = new u16(1 << mb);
4022
+ var rvb = 15 - mb;
4023
+ for (i = 0; i < s; ++i) {
4024
+ if (cd[i]) {
4025
+ var sv = i << 4 | cd[i];
4026
+ var r_1 = mb - cd[i];
4027
+ var v = le[cd[i] - 1]++ << r_1;
4028
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
4029
+ co[rev[v] >>> rvb] = sv;
4030
+ }
4031
+ }
4032
+ }
4033
+ } else {
4034
+ co = new u16(s);
4035
+ for (i = 0; i < s; ++i)
4036
+ co[i] = rev[le[cd[i] - 1]++] >>> 15 - cd[i];
4037
+ }
4038
+ return co;
4039
+ };
4040
+ var flt = new u8(288);
4041
+ for (var i = 0; i < 144; ++i)
4042
+ flt[i] = 8;
4043
+ for (var i = 144; i < 256; ++i)
4044
+ flt[i] = 9;
4045
+ for (var i = 256; i < 280; ++i)
4046
+ flt[i] = 7;
4047
+ for (var i = 280; i < 288; ++i)
4048
+ flt[i] = 8;
4049
+ var fdt = new u8(32);
4050
+ for (var i = 0; i < 32; ++i)
4051
+ fdt[i] = 5;
4052
+ var flm = /* @__PURE__ */ hMap(flt, 9, 0);
4053
+ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
4054
+ var shft = function(p) {
4055
+ return (p / 8 >> 0) + (p & 7 && 1);
4056
+ };
4057
+ var slc = function(v, s, e) {
4058
+ if (e == null || e > v.length)
4059
+ e = v.length;
4060
+ var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s);
4061
+ n.set(v.subarray(s, e));
4062
+ return n;
4063
+ };
4064
+ var wbits = function(d, p, v) {
4065
+ v <<= p & 7;
4066
+ var o = p / 8 >> 0;
4067
+ d[o] |= v;
4068
+ d[o + 1] |= v >>> 8;
4069
+ };
4070
+ var wbits16 = function(d, p, v) {
4071
+ v <<= p & 7;
4072
+ var o = p / 8 >> 0;
4073
+ d[o] |= v;
4074
+ d[o + 1] |= v >>> 8;
4075
+ d[o + 2] |= v >>> 16;
4076
+ };
4077
+ var hTree = function(d, mb) {
4078
+ var t = [];
4079
+ for (var i = 0; i < d.length; ++i) {
4080
+ if (d[i])
4081
+ t.push({ s: i, f: d[i] });
4082
+ }
4083
+ var s = t.length;
4084
+ var t2 = t.slice();
4085
+ if (!s)
4086
+ return [new u8(0), 0];
4087
+ if (s == 1) {
4088
+ var v = new u8(t[0].s + 1);
4089
+ v[t[0].s] = 1;
4090
+ return [v, 1];
4091
+ }
4092
+ t.sort(function(a, b) {
4093
+ return a.f - b.f;
4094
+ });
4095
+ t.push({ s: -1, f: 25001 });
4096
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
4097
+ t[0] = { s: -1, f: l.f + r.f, l, r };
4098
+ while (i1 != s - 1) {
4099
+ l = t[t[i0].f < t[i2].f ? i0++ : i2++];
4100
+ r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
4101
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
4102
+ }
4103
+ var maxSym = t2[0].s;
4104
+ for (var i = 1; i < s; ++i) {
4105
+ if (t2[i].s > maxSym)
4106
+ maxSym = t2[i].s;
4107
+ }
4108
+ var tr = new u16(maxSym + 1);
4109
+ var mbt = ln(t[i1 - 1], tr, 0);
4110
+ if (mbt > mb) {
4111
+ var i = 0, dt = 0;
4112
+ var lft = mbt - mb, cst = 1 << lft;
4113
+ t2.sort(function(a, b) {
4114
+ return tr[b.s] - tr[a.s] || a.f - b.f;
4115
+ });
4116
+ for (; i < s; ++i) {
4117
+ var i2_1 = t2[i].s;
4118
+ if (tr[i2_1] > mb) {
4119
+ dt += cst - (1 << mbt - tr[i2_1]);
4120
+ tr[i2_1] = mb;
4121
+ } else
4122
+ break;
4123
+ }
4124
+ dt >>>= lft;
4125
+ while (dt > 0) {
4126
+ var i2_2 = t2[i].s;
4127
+ if (tr[i2_2] < mb)
4128
+ dt -= 1 << mb - tr[i2_2]++ - 1;
4129
+ else
4130
+ ++i;
4131
+ }
4132
+ for (; i >= 0 && dt; --i) {
4133
+ var i2_3 = t2[i].s;
4134
+ if (tr[i2_3] == mb) {
4135
+ --tr[i2_3];
4136
+ ++dt;
4137
+ }
4138
+ }
4139
+ mbt = mb;
4140
+ }
4141
+ return [new u8(tr), mbt];
4142
+ };
4143
+ var ln = function(n, l, d) {
4144
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
4145
+ };
4146
+ var lc = function(c) {
4147
+ var s = c.length;
4148
+ while (s && !c[--s])
4149
+ ;
4150
+ var cl = new u16(++s);
4151
+ var cli = 0, cln = c[0], cls = 1;
4152
+ var w = function(v) {
4153
+ cl[cli++] = v;
4154
+ };
4155
+ for (var i = 1; i <= s; ++i) {
4156
+ if (c[i] == cln && i != s)
4157
+ ++cls;
4158
+ else {
4159
+ if (!cln && cls > 2) {
4160
+ for (; cls > 138; cls -= 138)
4161
+ w(32754);
4162
+ if (cls > 2) {
4163
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
4164
+ cls = 0;
4165
+ }
4166
+ } else if (cls > 3) {
4167
+ w(cln), --cls;
4168
+ for (; cls > 6; cls -= 6)
4169
+ w(8304);
4170
+ if (cls > 2)
4171
+ w(cls - 3 << 5 | 8208), cls = 0;
4172
+ }
4173
+ while (cls--)
4174
+ w(cln);
4175
+ cls = 1;
4176
+ cln = c[i];
4177
+ }
4178
+ }
4179
+ return [cl.subarray(0, cli), s];
4180
+ };
4181
+ var clen = function(cf, cl) {
4182
+ var l = 0;
4183
+ for (var i = 0; i < cl.length; ++i)
4184
+ l += cf[i] * cl[i];
4185
+ return l;
4186
+ };
4187
+ var wfblk = function(out, pos, dat) {
4188
+ var s = dat.length;
4189
+ var o = shft(pos + 2);
4190
+ out[o] = s & 255;
4191
+ out[o + 1] = s >>> 8;
4192
+ out[o + 2] = out[o] ^ 255;
4193
+ out[o + 3] = out[o + 1] ^ 255;
4194
+ for (var i = 0; i < s; ++i)
4195
+ out[o + i + 4] = dat[i];
4196
+ return (o + 4 + s) * 8;
4197
+ };
4198
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
4199
+ wbits(out, p++, final);
4200
+ ++lf[256];
4201
+ var _a2 = hTree(lf, 15), dlt = _a2[0], mlb = _a2[1];
4202
+ var _b2 = hTree(df, 15), ddt = _b2[0], mdb = _b2[1];
4203
+ var _c = lc(dlt), lclt = _c[0], nlc = _c[1];
4204
+ var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];
4205
+ var lcfreq = new u16(19);
4206
+ for (var i = 0; i < lclt.length; ++i)
4207
+ lcfreq[lclt[i] & 31]++;
4208
+ for (var i = 0; i < lcdt.length; ++i)
4209
+ lcfreq[lcdt[i] & 31]++;
4210
+ var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];
4211
+ var nlcc = 19;
4212
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
4213
+ ;
4214
+ var flen = bl + 5 << 3;
4215
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
4216
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);
4217
+ if (flen <= ftlen && flen <= dtlen)
4218
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
4219
+ var lm, ll, dm, dl;
4220
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
4221
+ if (dtlen < ftlen) {
4222
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
4223
+ var llm = hMap(lct, mlcb, 0);
4224
+ wbits(out, p, nlc - 257);
4225
+ wbits(out, p + 5, ndc - 1);
4226
+ wbits(out, p + 10, nlcc - 4);
4227
+ p += 14;
4228
+ for (var i = 0; i < nlcc; ++i)
4229
+ wbits(out, p + 3 * i, lct[clim[i]]);
4230
+ p += 3 * nlcc;
4231
+ var lcts = [lclt, lcdt];
4232
+ for (var it = 0; it < 2; ++it) {
4233
+ var clct = lcts[it];
4234
+ for (var i = 0; i < clct.length; ++i) {
4235
+ var len = clct[i] & 31;
4236
+ wbits(out, p, llm[len]), p += lct[len];
4237
+ if (len > 15)
4238
+ wbits(out, p, clct[i] >>> 5 & 127), p += clct[i] >>> 12;
4239
+ }
4240
+ }
4241
+ } else {
4242
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
4243
+ }
4244
+ for (var i = 0; i < li; ++i) {
4245
+ if (syms[i] > 255) {
4246
+ var len = syms[i] >>> 18 & 31;
4247
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
4248
+ if (len > 7)
4249
+ wbits(out, p, syms[i] >>> 23 & 31), p += fleb[len];
4250
+ var dst = syms[i] & 31;
4251
+ wbits16(out, p, dm[dst]), p += dl[dst];
4252
+ if (dst > 3)
4253
+ wbits16(out, p, syms[i] >>> 5 & 8191), p += fdeb[dst];
4254
+ } else {
4255
+ wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];
4256
+ }
4257
+ }
4258
+ wbits16(out, p, lm[256]);
4259
+ return p + ll[256];
4260
+ };
4261
+ var deo = /* @__PURE__ */ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
4262
+ var dflt = function(dat, lvl, plvl, pre, post, lst) {
4263
+ var s = dat.length;
4264
+ var o = new u8(pre + s + 5 * (1 + Math.floor(s / 7e3)) + post);
4265
+ var w = o.subarray(pre, o.length - post);
4266
+ var pos = 0;
4267
+ if (!lvl || s < 8) {
4268
+ for (var i = 0; i <= s; i += 65535) {
4269
+ var e = i + 65535;
4270
+ if (e < s) {
4271
+ pos = wfblk(w, pos, dat.subarray(i, e));
4272
+ } else {
4273
+ w[i] = lst;
4274
+ pos = wfblk(w, pos, dat.subarray(i, s));
4275
+ }
4276
+ }
4277
+ } else {
4278
+ var opt = deo[lvl - 1];
4279
+ var n = opt >>> 13, c = opt & 8191;
4280
+ var msk_1 = (1 << plvl) - 1;
4281
+ var prev = new u16(32768), head = new u16(msk_1 + 1);
4282
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
4283
+ var hsh = function(i2) {
4284
+ return (dat[i2] ^ dat[i2 + 1] << bs1_1 ^ dat[i2 + 2] << bs2_1) & msk_1;
4285
+ };
4286
+ var syms = new u32(25e3);
4287
+ var lf = new u16(288), df = new u16(32);
4288
+ var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;
4289
+ for (; i < s; ++i) {
4290
+ var hv = hsh(i);
4291
+ var imod = i & 32767;
4292
+ var pimod = head[hv];
4293
+ prev[imod] = pimod;
4294
+ head[hv] = imod;
4295
+ if (wi <= i) {
4296
+ var rem = s - i;
4297
+ if ((lc_1 > 7e3 || li > 24576) && rem > 423) {
4298
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
4299
+ li = lc_1 = eb = 0, bs = i;
4300
+ for (var j = 0; j < 286; ++j)
4301
+ lf[j] = 0;
4302
+ for (var j = 0; j < 30; ++j)
4303
+ df[j] = 0;
4304
+ }
4305
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
4306
+ if (rem > 2 && hv == hsh(i - dif)) {
4307
+ var maxn = Math.min(n, rem) - 1;
4308
+ var maxd = Math.min(32767, i);
4309
+ var ml = Math.min(258, rem);
4310
+ while (dif <= maxd && --ch_1 && imod != pimod) {
4311
+ if (dat[i + l] == dat[i + l - dif]) {
4312
+ var nl = 0;
4313
+ for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
4314
+ ;
4315
+ if (nl > l) {
4316
+ l = nl, d = dif;
4317
+ if (nl > maxn)
4318
+ break;
4319
+ var mmd = Math.min(dif, nl - 2);
4320
+ var md = 0;
4321
+ for (var j = 0; j < mmd; ++j) {
4322
+ var ti = i - dif + j + 32768 & 32767;
4323
+ var pti = prev[ti];
4324
+ var cd = ti - pti + 32768 & 32767;
4325
+ if (cd > md)
4326
+ md = cd, pimod = ti;
4327
+ }
4328
+ }
4329
+ }
4330
+ imod = pimod, pimod = prev[imod];
4331
+ dif += imod - pimod + 32768 & 32767;
4332
+ }
4333
+ }
4334
+ if (d) {
4335
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
4336
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
4337
+ eb += fleb[lin] + fdeb[din];
4338
+ ++lf[257 + lin];
4339
+ ++df[din];
4340
+ wi = i + l;
4341
+ ++lc_1;
4342
+ } else {
4343
+ syms[li++] = dat[i];
4344
+ ++lf[dat[i]];
4345
+ }
4346
+ }
4347
+ }
4348
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
4349
+ }
4350
+ return slc(o, 0, pre + shft(pos) + post);
4351
+ };
4352
+ var adler = function() {
4353
+ var a = 1, b = 0;
4354
+ return {
4355
+ p: function(d) {
4356
+ var n = a, m = b;
4357
+ var l = d.length;
4358
+ for (var i = 0; i != l; ) {
4359
+ var e = Math.min(i + 5552, l);
4360
+ for (; i < e; ++i)
4361
+ n += d[i], m += n;
4362
+ n %= 65521, m %= 65521;
4363
+ }
4364
+ a = n, b = m;
4365
+ },
4366
+ d: function() {
4367
+ return (a >>> 8 << 16 | (b & 255) << 8 | b >>> 8) + ((a & 255) << 23) * 2;
4368
+ }
4369
+ };
4370
+ };
4371
+ var dopt = function(dat, opt, pre, post, st) {
4372
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 12 + opt.mem, pre, post, true);
4373
+ };
4374
+ var wbytes = function(d, b, v) {
4375
+ for (; v; ++b)
4376
+ d[b] = v, v >>>= 8;
4377
+ };
4378
+ var zlh = function(c, o) {
4379
+ var lv = o.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
4380
+ c[0] = 120, c[1] = fl2 << 6 | (fl2 ? 32 - 2 * fl2 : 1);
4381
+ };
4382
+ function zlibSync(data, opts) {
4383
+ if (opts === void 0) {
4384
+ opts = {};
4385
+ }
4386
+ var a = adler();
4387
+ a.p(data);
4388
+ var d = dopt(data, opts, 2, 4);
4389
+ return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
4390
+ }
4391
+ function strToU8(str, latin1) {
4392
+ var l = str.length;
4393
+ if (typeof TextEncoder != "undefined")
4394
+ return new TextEncoder().encode(str);
4395
+ var ar = new u8(str.length + (str.length >>> 1));
4396
+ var ai = 0;
4397
+ var w = function(v) {
4398
+ ar[ai++] = v;
4399
+ };
4400
+ for (var i = 0; i < l; ++i) {
4401
+ if (ai + 5 > ar.length) {
4402
+ var n = new u8(ai + 8 + (l - i << 1));
4403
+ n.set(ar);
4404
+ ar = n;
4405
+ }
4406
+ var c = str.charCodeAt(i);
4407
+ if (c < 128 || latin1)
4408
+ w(c);
4409
+ else if (c < 2048)
4410
+ w(192 | c >>> 6), w(128 | c & 63);
4411
+ else if (c > 55295 && c < 57344)
4412
+ c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i) & 1023, w(240 | c >>> 18), w(128 | c >>> 12 & 63), w(128 | c >>> 6 & 63), w(128 | c & 63);
4413
+ else
4414
+ w(224 | c >>> 12), w(128 | c >>> 6 & 63), w(128 | c & 63);
4415
+ }
4416
+ return slc(ar, 0, ai);
4417
+ }
4418
+ function strFromU8(dat, latin1) {
4419
+ var r = "";
4420
+ for (var i = 0; i < dat.length; ) {
4421
+ var c = dat[i++];
4422
+ r += String.fromCharCode(c);
4423
+ }
4424
+ return r;
4425
+ }
4426
+ const MARK = "v1";
4427
+
4428
+ const pack = (event) => {
4429
+ const _e = {
4430
+ ...event,
4431
+ v: MARK
4432
+ };
4433
+ return strFromU8(zlibSync(strToU8(JSON.stringify(_e))));
4434
+ };
4435
+
4436
+ class D2DWebSessionTracker {
4437
+ constructor(config) {
4438
+ this.name = 'session-tracker';
4439
+ this.version = '"0.9.0"';
4440
+ this.context = null;
4441
+ this.config = {};
4442
+ this.userConfig = null;
4443
+ this.sessionStartTime = 0;
4444
+ this.isActive = false;
4445
+ this.stopRecording = null;
4446
+ this.sessionEvents = [];
4447
+ this.sessionId = '';
4448
+ this.currentSessionSize = 0;
4449
+ this.lastBatchTime = 0;
4450
+ this.activeBatchCount = 0;
4451
+ // Event ordering and batch management
4452
+ this.pendingEvents = []; // Events waiting to be sent
4453
+ this.sentEventCount = 0; // Total events sent successfully
4454
+ // Delayed URL management for final batch
4455
+ this.delayedS3Url = null;
4456
+ this.delayedUrlTtl = 0;
4457
+ this.delayedUrlRefreshTimer = null;
4458
+ this.userConfig = config || {};
4459
+ }
4460
+ // MARK: Init
4461
+ init(context, config) {
4462
+ console.log('D2DWebSessionTracker init', config);
4463
+ this.context = context;
4464
+ const webSessionsConfig = typeof config?.webSessions === 'object'
4465
+ ? config?.webSessions
4466
+ : null;
4467
+ const defaultConfig = {
4468
+ enableSessionRecording: config?.webSessions === true || webSessionsConfig?.enabled || true,
4469
+ maxBatchSize: 1024 * 1024, // 1MB default
4470
+ maxSessionDuration: null,
4471
+ batchSize: 50, // 50 events per batch
4472
+ batchInterval: 30000, // 30 seconds between batches
4473
+ compressionEnabled: false,
4474
+ recordingOptions: {
4475
+ recordCanvas: true,
4476
+ recordCrossOriginIframes: false,
4477
+ recordAfter: 'DOMContentLoaded',
4478
+ maskAllInputs: false,
4479
+ maskInputOptions: {
4480
+ password: true,
4481
+ email: true,
4482
+ text: false,
4483
+ },
4484
+ blockClass: 'sensitive-field',
4485
+ slimDOMOptions: {
4486
+ script: false,
4487
+ comment: true,
4488
+ headFavicon: true,
4489
+ headWhitespace: true,
4490
+ headMetaDescKeywords: true,
4491
+ headMetaSocial: true,
4492
+ headMetaRobots: true,
4493
+ headMetaHttpEquiv: true,
4494
+ headMetaAuthorship: true,
4495
+ headMetaVerification: true,
4496
+ },
4497
+ sampling: {
4498
+ scroll: 150,
4499
+ mouseInteraction: true,
4500
+ input: 'last',
4501
+ mutation: true,
4502
+ },
4503
+ ...(this.userConfig ? this.userConfig : {}),
4504
+ ...(this.config.recordingOptions ? this.config.recordingOptions : {}),
4505
+ },
4506
+ };
4507
+ this.config = { ...defaultConfig };
4508
+ console.log('D2DWebSessionTracker initialized', this.config);
4509
+ }
4510
+ // MARK: Start
4511
+ start() {
4512
+ console.log('D2DWebSessionTracker start');
4513
+ if (!this.context || this.isActive) {
4514
+ this.context?.logger.error('Session tracker is not initialized or already active');
4515
+ return;
4516
+ }
4517
+ // Clear any existing delayed URL refresh timer
4518
+ if (this.delayedUrlRefreshTimer) {
4519
+ clearTimeout(this.delayedUrlRefreshTimer);
4520
+ this.delayedUrlRefreshTimer = null;
4521
+ }
4522
+ this.isActive = true;
4523
+ this.sessionStartTime = Date.now();
4524
+ this.sessionId = String(this.context.userManager.getSessionId());
4525
+ this.sessionEvents = [];
4526
+ this.pendingEvents = [];
4527
+ this.currentSessionSize = 0;
4528
+ this.lastBatchTime = Date.now();
4529
+ this.sentEventCount = 0;
4530
+ this.delayedS3Url = null;
4531
+ this.delayedUrlTtl = 0;
4532
+ // Check recording logic
4533
+ if (this.config.enableSessionRecording) {
4534
+ this.handleRecordingStart();
4535
+ }
4536
+ }
4537
+ // MARK: Handle Recording Start
4538
+ async handleRecordingStart() {
4539
+ if (!this.context)
4540
+ return;
4541
+ const isRecordingActive = this.context.getPluginField('isRecordingActive');
4542
+ const isNewSession = this.context.isNewSession;
4543
+ console.log('isRecordingActive', isRecordingActive);
4544
+ console.log('isNewSession', isNewSession);
4545
+ if (!isNewSession && isRecordingActive) {
4546
+ this.startSessionRecording();
4547
+ return;
4548
+ }
4549
+ if (isNewSession || !isRecordingActive) {
4550
+ try {
4551
+ const appId = this.context.appManager.getAppId();
4552
+ // GET /sessions/configurations/get?appId={appId}
4553
+ const url = this.context.api.buildUrl(['sessions', 'configurations', 'get'], { appId });
4554
+ const response = await this.sendRequest(url, null, 'GET');
4555
+ if (response && response.data) {
4556
+ const config = response.data;
4557
+ if (config.blocked || !config.active) {
4558
+ this.context.logger.debug(`Session configuration is ${config.blocked ? 'blocked' : 'inactive'}`);
4559
+ this.context.setPluginField('isRecordingActive', false);
4560
+ this.isActive = false;
4561
+ return;
4562
+ }
4563
+ const shouldRecord = Math.random() * 100 < config.record_chance_percent;
4564
+ if (shouldRecord) {
4565
+ this.context.setPluginField('isRecordingActive', true);
4566
+ this.startSessionRecording();
4567
+ }
4568
+ else {
4569
+ this.context.setPluginField('isRecordingActive', false);
4570
+ }
4571
+ }
4572
+ }
4573
+ catch (error) {
4574
+ this.context.logger.error('Failed to fetch session configuration', {
4575
+ error,
4576
+ });
4577
+ this.context.setPluginField('isRecordingActive', false);
4578
+ this.isActive = false;
4579
+ }
4580
+ }
4581
+ }
4582
+ // MARK: Stop
4583
+ stop() {
4584
+ if (!this.isActive)
4585
+ return;
4586
+ this.context?.setPluginField('isRecordingActive', false);
4587
+ this.isActive = false;
4588
+ // Clear delayed URL refresh timer
4589
+ if (this.delayedUrlRefreshTimer) {
4590
+ clearTimeout(this.delayedUrlRefreshTimer);
4591
+ this.delayedUrlRefreshTimer = null;
4592
+ }
4593
+ // Stop session recording
4594
+ if (this.config.enableSessionRecording && this.stopRecording) {
4595
+ this.stopRecording();
4596
+ this.stopRecording = null;
4597
+ // Handle async operation without blocking - onBlur / stop will handle final batch
4598
+ }
4599
+ }
4600
+ // MARK: Destroy
4601
+ destroy() {
4602
+ this.stop();
4603
+ // Ensure timer is cleared
4604
+ if (this.delayedUrlRefreshTimer) {
4605
+ clearTimeout(this.delayedUrlRefreshTimer);
4606
+ this.delayedUrlRefreshTimer = null;
4607
+ }
4608
+ this.context = null;
4609
+ }
4610
+ // MARK: On Event
4611
+ onEvent(eventCode, _bundle) {
4612
+ if (!this.isActive)
4613
+ return;
4614
+ if (eventCode === 'session_start') {
4615
+ this.sessionStartTime = Date.now();
4616
+ }
4617
+ }
4618
+ // MARK: On User Change
4619
+ onUserChange(_userId) {
4620
+ if (!this.isActive)
4621
+ return;
4622
+ this.sessionStartTime = Date.now();
4623
+ }
4624
+ // MARK: On Focus
4625
+ onFocus() {
4626
+ if (!this.isActive)
4627
+ return;
4628
+ this.start();
4629
+ }
4630
+ // MARK: On Blur
4631
+ onBlur() {
4632
+ if (!this.isActive)
4633
+ return;
4634
+ console.log('onBlur');
4635
+ this.stop();
4636
+ // Send final batch via addWithFile
4637
+ this.sendFinalBatch().catch(err => {
4638
+ this.context?.logger.error('Error sending final batch', { error: err });
4639
+ });
4640
+ }
4641
+ // MARK: On Before Unload
4642
+ onBeforeUnload() {
4643
+ if (!this.isActive)
4644
+ return;
4645
+ console.log('onBeforeUnload');
4646
+ this.stop();
4647
+ // Send final batch via addWithFile
4648
+ this.sendFinalBatch().catch(err => {
4649
+ this.context?.logger.error('Error sending final batch', { error: err });
4650
+ });
4651
+ }
4652
+ // MARK: On Tracking Change
4653
+ onTrackingChange(isTracking) {
4654
+ if (!this.isActive)
4655
+ return;
4656
+ if (isTracking) {
4657
+ this.start();
4658
+ }
4659
+ else {
4660
+ this.destroy();
4661
+ }
4662
+ }
4663
+ // MARK: On Session Start
4664
+ onSessionStart() {
4665
+ if (!this.isActive)
4666
+ return;
4667
+ this.start();
4668
+ }
4669
+ // MARK: On Session End
4670
+ onSessionEnd() {
4671
+ if (!this.isActive)
4672
+ return;
4673
+ this.stop();
4674
+ }
4675
+ // MARK: Start Session Recording
4676
+ startSessionRecording() {
4677
+ if (!this.config.enableSessionRecording)
4678
+ return;
4679
+ // Fetch delayed URL when recording starts
4680
+ this.fetchDelayedUrl();
4681
+ const recordOptions = {
4682
+ emit: (event) => {
4683
+ // Add event to both active and pending collections
4684
+ this.sessionEvents.push(event);
4685
+ this.pendingEvents.push(event);
4686
+ this.currentSessionSize += JSON.stringify(event).length;
4687
+ // Check if we need to send batch due to size, duration, or batch size limits
4688
+ this.checkBatchLimits();
4689
+ },
4690
+ ...this.config.recordingOptions,
4691
+ };
4692
+ // Add packFn for compression if enabled
4693
+ if (this.config.compressionEnabled) {
4694
+ recordOptions.packFn = pack;
4695
+ }
4696
+ const stopFn = record(recordOptions);
4697
+ this.stopRecording = stopFn || null;
4698
+ }
4699
+ // MARK: Check Batch Limits
4700
+ checkBatchLimits() {
4701
+ const sessionDuration = Date.now() - this.sessionStartTime;
4702
+ const batchSizeReached = this.pendingEvents.length >= (this.config.batchSize || 50);
4703
+ const sizeLimitReached = this.currentSessionSize >= (this.config.maxBatchSize || 1024 * 1024);
4704
+ const durationLimitReached = this.config.maxSessionDuration &&
4705
+ sessionDuration >= this.config.maxSessionDuration;
4706
+ const timeLimitReached = Date.now() - this.lastBatchTime >= (this.config.batchInterval || 30000);
4707
+ if (batchSizeReached ||
4708
+ sizeLimitReached ||
4709
+ durationLimitReached ||
4710
+ timeLimitReached) {
4711
+ // Handle async operation without blocking
4712
+ this.sendBatchToBackend().catch(error => {
4713
+ this.context?.logger.error('Error in checkBatchLimits sendBatchToBackend', {
4714
+ error: error instanceof Error ? error.message : error,
4715
+ pendingEventsCount: this.pendingEvents.length,
4716
+ });
4717
+ });
4718
+ }
4719
+ }
4720
+ // MARK: Send Batch To Backend
4721
+ async sendBatchToBackend() {
4722
+ if (!this.pendingEvents.length || !this.context)
4723
+ return;
4724
+ // Take a snapshot of events to send and immediately remove them from pending
4725
+ // This allows concurrent batch sends without duplicate events
4726
+ const eventsToSend = [...this.pendingEvents];
4727
+ this.pendingEvents = []; // Clear immediately to prevent duplicates in concurrent sends
4728
+ // Update session size immediately
4729
+ const sentSize = eventsToSend.reduce((total, event) => total + JSON.stringify(event).length, 0);
4730
+ this.currentSessionSize -= sentSize;
4731
+ this.currentSessionSize = Math.max(0, this.currentSessionSize); // Prevent negative
4732
+ this.activeBatchCount++;
4733
+ try {
4734
+ const batchStartTime = eventsToSend[0]?.timestamp || Date.now();
4735
+ const batchEndTime = eventsToSend[eventsToSend.length - 1]?.timestamp || Date.now();
4736
+ const batchMetadata = {
4737
+ appId: this.context.appManager.getAppId(),
4738
+ session_id: this.sessionId,
4739
+ user_id: this.context.userManager.getUserId(),
4740
+ start_time: batchStartTime,
4741
+ end_time: batchEndTime,
4742
+ };
4743
+ // 1. Get S3 URL
4744
+ const addUrl = this.context.api.buildUrl(['sessions', 'add'], batchMetadata);
4745
+ const response = await this.sendRequest(addUrl, null, 'GET', {}, true);
4746
+ if (response.status === 204) {
4747
+ // Storage exceeded - events already removed from pending, so just log
4748
+ this.context.logger.warning('Session storage exceeded');
4749
+ this.isActive = false;
4750
+ this.context?.setPluginField('isRecordingActive', false);
4751
+ return;
4752
+ }
4753
+ const s3Url = response.data;
4754
+ // Assuming response.data is the URL string or { url: string }
4755
+ const uploadUrl = typeof s3Url === 'string' ? s3Url : s3Url?.url;
4756
+ if (uploadUrl) {
4757
+ // 2. Upload to S3
4758
+ await this.uploadToS3(uploadUrl, eventsToSend);
4759
+ this.sentEventCount += eventsToSend.length;
4760
+ this.lastBatchTime = Date.now();
4761
+ }
4762
+ else {
4763
+ throw new Error('No S3 URL returned');
4764
+ }
4765
+ }
4766
+ catch (error) {
4767
+ this.context?.logger.error('Error sending session batch to backend', {
4768
+ error: error instanceof Error ? error.message : error,
4769
+ eventsCount: eventsToSend.length,
4770
+ });
4771
+ // Optionally: re-add events to pending on failure if you want retry logic
4772
+ // this.pendingEvents.push(...eventsToSend);
4773
+ throw error;
4774
+ }
4775
+ finally {
4776
+ this.activeBatchCount--;
4777
+ // Check if there are more events to send after this batch completes
4778
+ if (this.pendingEvents.length > 0) {
4779
+ this.checkBatchLimits();
4780
+ }
4781
+ }
4782
+ }
4783
+ // MARK: Fetch Delayed URL
4784
+ async fetchDelayedUrl() {
4785
+ if (!this.context)
4786
+ return;
4787
+ try {
4788
+ const appId = this.context.appManager.getAppId();
4789
+ const url = this.context.api.buildUrl(['sessions', 'addDelayed'], {
4790
+ session_id: this.sessionId,
4791
+ appId,
4792
+ user_id: this.context.userManager.getUserId(),
4793
+ });
4794
+ const response = await this.sendRequest(url, null, 'GET');
4795
+ if (response && response.data) {
4796
+ const data = response.data;
4797
+ this.delayedS3Url = data.url;
4798
+ this.delayedUrlTtl = data.ttl;
4799
+ // Schedule refresh before TTL expires (with 10 second buffer for request time)
4800
+ this.scheduleDelayedUrlRefresh();
4801
+ }
4802
+ }
4803
+ catch (error) {
4804
+ this.context.logger.error('Failed to fetch delayed URL', { error });
4805
+ }
4806
+ }
4807
+ // MARK: Schedule Delayed URL Refresh
4808
+ scheduleDelayedUrlRefresh() {
4809
+ // Clear existing timer
4810
+ if (this.delayedUrlRefreshTimer) {
4811
+ clearTimeout(this.delayedUrlRefreshTimer);
4812
+ }
4813
+ // Calculate refresh time: TTL minus 10 seconds buffer for request time
4814
+ const bufferTime = 10000; // 10 seconds
4815
+ const refreshTime = Math.max(0, this.delayedUrlTtl - bufferTime);
4816
+ this.delayedUrlRefreshTimer = setTimeout(() => {
4817
+ this.fetchDelayedUrl();
4818
+ }, refreshTime);
4819
+ }
4820
+ // MARK: Send Final Batch
4821
+ async sendFinalBatch() {
4822
+ if (!this.pendingEvents.length || !this.context)
4823
+ return;
4824
+ // Ensure we have a valid delayed URL
4825
+ if (!this.delayedS3Url) {
4826
+ this.context.logger.warning('No delayed URL available, attempting to fetch...');
4827
+ await this.fetchDelayedUrl();
4828
+ if (!this.delayedS3Url) {
4829
+ this.context.logger.error('Failed to get delayed URL for final batch');
4830
+ return;
4831
+ }
4832
+ }
4833
+ const eventsToSend = [...this.pendingEvents];
4834
+ this.pendingEvents = []; // Clear immediately
4835
+ this.currentSessionSize = 0; // Reset since all events are sent
4836
+ // Events are already compressed by packFn if compressionEnabled is true
4837
+ const fileContent = JSON.stringify(eventsToSend);
4838
+ const blob = new Blob([fileContent], { type: 'application/json' });
4839
+ // Use fetch with keepalive for page unload reliability
4840
+ // credentials: 'omit' prevents CORS issues with S3 buckets that use wildcard CORS
4841
+ try {
4842
+ const response = await fetch(this.delayedS3Url, {
4843
+ method: 'PUT',
4844
+ body: blob,
4845
+ keepalive: true, // Ensures request continues even if page unloads
4846
+ credentials: 'omit', // Prevents CORS issues with wildcard Access-Control-Allow-Origin
4847
+ });
4848
+ if (!response.ok) {
4849
+ throw new Error(`S3 upload failed: ${response.statusText}`);
4850
+ }
4851
+ this.lastBatchTime = Date.now();
4852
+ }
4853
+ catch (error) {
4854
+ this.context.logger.error('Error sending final batch', { error });
4855
+ }
4856
+ }
4857
+ // MARK: Upload To S3
4858
+ async uploadToS3(url, data) {
4859
+ // Events are already compressed by packFn if compressionEnabled is true
4860
+ const body = JSON.stringify(data);
4861
+ // Use native fetch for S3 to avoid SDK headers which might cause issues with presigned URLs
4862
+ const response = await fetch(url, {
4863
+ method: 'PUT', // Usually S3 uploads are PUT
4864
+ body: body,
4865
+ });
4866
+ if (!response.ok) {
4867
+ throw new Error(`S3 upload failed: ${response.statusText}`);
4868
+ }
4869
+ }
4870
+ // MARK: Send Request
4871
+ sendRequest(url, body, method = 'POST', headers = {}, noContentType = false) {
4872
+ return new Promise((resolve, reject) => {
4873
+ if (!this.context)
4874
+ return reject(new Error('No context'));
4875
+ const request = this.context.api.createRequestStructure(url, body, headers, method);
4876
+ this.context.api.sendRequest(`req-${Date.now()}-${Math.random()}`, request, (status, data, error) => {
4877
+ if (status >= 200 && status < 300) {
4878
+ resolve({ status, data });
4879
+ }
4880
+ else {
4881
+ reject({ status, data, error });
4882
+ }
4883
+ }, { gzip: false, method, noContentType });
4884
+ });
4885
+ }
4886
+ }
4887
+
4888
+ if (typeof window !== 'undefined') {
4889
+ window.D2DWebSessionTracker = D2DWebSessionTracker;
4890
+ }
4891
+
4892
+ })();
4893
+ //# sourceMappingURL=browser.js.map