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