@zaplier/sdk 1.3.0 → 1.3.2

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.esm.js CHANGED
@@ -6855,136 +6855,3924 @@ class HeatmapEngine {
6855
6855
  }
6856
6856
  }
6857
6857
 
6858
+ var NodeType;
6859
+ (function (NodeType) {
6860
+ NodeType[NodeType["Document"] = 0] = "Document";
6861
+ NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
6862
+ NodeType[NodeType["Element"] = 2] = "Element";
6863
+ NodeType[NodeType["Text"] = 3] = "Text";
6864
+ NodeType[NodeType["CDATA"] = 4] = "CDATA";
6865
+ NodeType[NodeType["Comment"] = 5] = "Comment";
6866
+ })(NodeType || (NodeType = {}));
6867
+
6868
+ function isElement(n) {
6869
+ return n.nodeType === n.ELEMENT_NODE;
6870
+ }
6871
+ function isShadowRoot(n) {
6872
+ var host = n === null || n === void 0 ? void 0 : n.host;
6873
+ return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);
6874
+ }
6875
+ function isNativeShadowDom(shadowRoot) {
6876
+ return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';
6877
+ }
6878
+ function fixBrowserCompatibilityIssuesInCSS(cssText) {
6879
+ if (cssText.includes(' background-clip: text;') &&
6880
+ !cssText.includes(' -webkit-background-clip: text;')) {
6881
+ cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');
6882
+ }
6883
+ return cssText;
6884
+ }
6885
+ function getCssRulesString(s) {
6886
+ try {
6887
+ var rules = s.rules || s.cssRules;
6888
+ return rules
6889
+ ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(getCssRuleString).join(''))
6890
+ : null;
6891
+ }
6892
+ catch (error) {
6893
+ return null;
6894
+ }
6895
+ }
6896
+ function getCssRuleString(rule) {
6897
+ var cssStringified = rule.cssText;
6898
+ if (isCSSImportRule(rule)) {
6899
+ try {
6900
+ cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;
6901
+ }
6902
+ catch (_a) {
6903
+ }
6904
+ }
6905
+ return cssStringified;
6906
+ }
6907
+ function isCSSImportRule(rule) {
6908
+ return 'styleSheet' in rule;
6909
+ }
6910
+ var Mirror = (function () {
6911
+ function Mirror() {
6912
+ this.idNodeMap = new Map();
6913
+ this.nodeMetaMap = new WeakMap();
6914
+ }
6915
+ Mirror.prototype.getId = function (n) {
6916
+ var _a;
6917
+ if (!n)
6918
+ return -1;
6919
+ var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
6920
+ return id !== null && id !== void 0 ? id : -1;
6921
+ };
6922
+ Mirror.prototype.getNode = function (id) {
6923
+ return this.idNodeMap.get(id) || null;
6924
+ };
6925
+ Mirror.prototype.getIds = function () {
6926
+ return Array.from(this.idNodeMap.keys());
6927
+ };
6928
+ Mirror.prototype.getMeta = function (n) {
6929
+ return this.nodeMetaMap.get(n) || null;
6930
+ };
6931
+ Mirror.prototype.removeNodeFromMap = function (n) {
6932
+ var _this = this;
6933
+ var id = this.getId(n);
6934
+ this.idNodeMap["delete"](id);
6935
+ if (n.childNodes) {
6936
+ n.childNodes.forEach(function (childNode) {
6937
+ return _this.removeNodeFromMap(childNode);
6938
+ });
6939
+ }
6940
+ };
6941
+ Mirror.prototype.has = function (id) {
6942
+ return this.idNodeMap.has(id);
6943
+ };
6944
+ Mirror.prototype.hasNode = function (node) {
6945
+ return this.nodeMetaMap.has(node);
6946
+ };
6947
+ Mirror.prototype.add = function (n, meta) {
6948
+ var id = meta.id;
6949
+ this.idNodeMap.set(id, n);
6950
+ this.nodeMetaMap.set(n, meta);
6951
+ };
6952
+ Mirror.prototype.replace = function (id, n) {
6953
+ var oldNode = this.getNode(id);
6954
+ if (oldNode) {
6955
+ var meta = this.nodeMetaMap.get(oldNode);
6956
+ if (meta)
6957
+ this.nodeMetaMap.set(n, meta);
6958
+ }
6959
+ this.idNodeMap.set(id, n);
6960
+ };
6961
+ Mirror.prototype.reset = function () {
6962
+ this.idNodeMap = new Map();
6963
+ this.nodeMetaMap = new WeakMap();
6964
+ };
6965
+ return Mirror;
6966
+ }());
6967
+ function createMirror() {
6968
+ return new Mirror();
6969
+ }
6970
+ function maskInputValue(_a) {
6971
+ var maskInputOptions = _a.maskInputOptions, tagName = _a.tagName, type = _a.type, value = _a.value, maskInputFn = _a.maskInputFn;
6972
+ var text = value || '';
6973
+ if (maskInputOptions[tagName.toLowerCase()] ||
6974
+ maskInputOptions[type]) {
6975
+ if (maskInputFn) {
6976
+ text = maskInputFn(text);
6977
+ }
6978
+ else {
6979
+ text = '*'.repeat(text.length);
6980
+ }
6981
+ }
6982
+ return text;
6983
+ }
6984
+ var ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';
6985
+ function is2DCanvasBlank(canvas) {
6986
+ var ctx = canvas.getContext('2d');
6987
+ if (!ctx)
6988
+ return true;
6989
+ var chunkSize = 50;
6990
+ for (var x = 0; x < canvas.width; x += chunkSize) {
6991
+ for (var y = 0; y < canvas.height; y += chunkSize) {
6992
+ var getImageData = ctx.getImageData;
6993
+ var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData
6994
+ ? getImageData[ORIGINAL_ATTRIBUTE_NAME]
6995
+ : getImageData;
6996
+ var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);
6997
+ if (pixelBuffer.some(function (pixel) { return pixel !== 0; }))
6998
+ return false;
6999
+ }
7000
+ }
7001
+ return true;
7002
+ }
7003
+
7004
+ var _id = 1;
7005
+ var tagNameRegex = new RegExp('[^a-z0-9-_:]');
7006
+ var IGNORED_NODE = -2;
7007
+ function genId() {
7008
+ return _id++;
7009
+ }
7010
+ function getValidTagName(element) {
7011
+ if (element instanceof HTMLFormElement) {
7012
+ return 'form';
7013
+ }
7014
+ var processedTagName = element.tagName.toLowerCase().trim();
7015
+ if (tagNameRegex.test(processedTagName)) {
7016
+ return 'div';
7017
+ }
7018
+ return processedTagName;
7019
+ }
7020
+ function stringifyStyleSheet(sheet) {
7021
+ return sheet.cssRules
7022
+ ? Array.from(sheet.cssRules)
7023
+ .map(function (rule) { return rule.cssText || ''; })
7024
+ .join('')
7025
+ : '';
7026
+ }
7027
+ function extractOrigin(url) {
7028
+ var origin = '';
7029
+ if (url.indexOf('//') > -1) {
7030
+ origin = url.split('/').slice(0, 3).join('/');
7031
+ }
7032
+ else {
7033
+ origin = url.split('/')[0];
7034
+ }
7035
+ origin = origin.split('?')[0];
7036
+ return origin;
7037
+ }
7038
+ var canvasService;
7039
+ var canvasCtx;
7040
+ var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
7041
+ var RELATIVE_PATH = /^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/;
7042
+ var DATA_URI = /^(data:)([^,]*),(.*)/i;
7043
+ function absoluteToStylesheet(cssText, href) {
7044
+ return (cssText || '').replace(URL_IN_CSS_REF, function (origin, quote1, path1, quote2, path2, path3) {
7045
+ var filePath = path1 || path2 || path3;
7046
+ var maybeQuote = quote1 || quote2 || '';
7047
+ if (!filePath) {
7048
+ return origin;
7049
+ }
7050
+ if (!RELATIVE_PATH.test(filePath)) {
7051
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
7052
+ }
7053
+ if (DATA_URI.test(filePath)) {
7054
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
7055
+ }
7056
+ if (filePath[0] === '/') {
7057
+ return "url(".concat(maybeQuote).concat(extractOrigin(href) + filePath).concat(maybeQuote, ")");
7058
+ }
7059
+ var stack = href.split('/');
7060
+ var parts = filePath.split('/');
7061
+ stack.pop();
7062
+ for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
7063
+ var part = parts_1[_i];
7064
+ if (part === '.') {
7065
+ continue;
7066
+ }
7067
+ else if (part === '..') {
7068
+ stack.pop();
7069
+ }
7070
+ else {
7071
+ stack.push(part);
7072
+ }
7073
+ }
7074
+ return "url(".concat(maybeQuote).concat(stack.join('/')).concat(maybeQuote, ")");
7075
+ });
7076
+ }
7077
+ var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
7078
+ var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
7079
+ function getAbsoluteSrcsetString(doc, attributeValue) {
7080
+ if (attributeValue.trim() === '') {
7081
+ return attributeValue;
7082
+ }
7083
+ var pos = 0;
7084
+ function collectCharacters(regEx) {
7085
+ var chars;
7086
+ var match = regEx.exec(attributeValue.substring(pos));
7087
+ if (match) {
7088
+ chars = match[0];
7089
+ pos += chars.length;
7090
+ return chars;
7091
+ }
7092
+ return '';
7093
+ }
7094
+ var output = [];
7095
+ while (true) {
7096
+ collectCharacters(SRCSET_COMMAS_OR_SPACES);
7097
+ if (pos >= attributeValue.length) {
7098
+ break;
7099
+ }
7100
+ var url = collectCharacters(SRCSET_NOT_SPACES);
7101
+ if (url.slice(-1) === ',') {
7102
+ url = absoluteToDoc(doc, url.substring(0, url.length - 1));
7103
+ output.push(url);
7104
+ }
7105
+ else {
7106
+ var descriptorsStr = '';
7107
+ url = absoluteToDoc(doc, url);
7108
+ var inParens = false;
7109
+ while (true) {
7110
+ var c = attributeValue.charAt(pos);
7111
+ if (c === '') {
7112
+ output.push((url + descriptorsStr).trim());
7113
+ break;
7114
+ }
7115
+ else if (!inParens) {
7116
+ if (c === ',') {
7117
+ pos += 1;
7118
+ output.push((url + descriptorsStr).trim());
7119
+ break;
7120
+ }
7121
+ else if (c === '(') {
7122
+ inParens = true;
7123
+ }
7124
+ }
7125
+ else {
7126
+ if (c === ')') {
7127
+ inParens = false;
7128
+ }
7129
+ }
7130
+ descriptorsStr += c;
7131
+ pos += 1;
7132
+ }
7133
+ }
7134
+ }
7135
+ return output.join(', ');
7136
+ }
7137
+ function absoluteToDoc(doc, attributeValue) {
7138
+ if (!attributeValue || attributeValue.trim() === '') {
7139
+ return attributeValue;
7140
+ }
7141
+ var a = doc.createElement('a');
7142
+ a.href = attributeValue;
7143
+ return a.href;
7144
+ }
7145
+ function isSVGElement(el) {
7146
+ return Boolean(el.tagName === 'svg' || el.ownerSVGElement);
7147
+ }
7148
+ function getHref() {
7149
+ var a = document.createElement('a');
7150
+ a.href = '';
7151
+ return a.href;
7152
+ }
7153
+ function transformAttribute(doc, tagName, name, value) {
7154
+ if (name === 'src' ||
7155
+ (name === 'href' && value && !(tagName === 'use' && value[0] === '#'))) {
7156
+ return absoluteToDoc(doc, value);
7157
+ }
7158
+ else if (name === 'xlink:href' && value && value[0] !== '#') {
7159
+ return absoluteToDoc(doc, value);
7160
+ }
7161
+ else if (name === 'background' &&
7162
+ value &&
7163
+ (tagName === 'table' || tagName === 'td' || tagName === 'th')) {
7164
+ return absoluteToDoc(doc, value);
7165
+ }
7166
+ else if (name === 'srcset' && value) {
7167
+ return getAbsoluteSrcsetString(doc, value);
7168
+ }
7169
+ else if (name === 'style' && value) {
7170
+ return absoluteToStylesheet(value, getHref());
7171
+ }
7172
+ else if (tagName === 'object' && name === 'data' && value) {
7173
+ return absoluteToDoc(doc, value);
7174
+ }
7175
+ else {
7176
+ return value;
7177
+ }
7178
+ }
7179
+ function _isBlockedElement(element, blockClass, blockSelector) {
7180
+ if (typeof blockClass === 'string') {
7181
+ if (element.classList.contains(blockClass)) {
7182
+ return true;
7183
+ }
7184
+ }
7185
+ else {
7186
+ for (var eIndex = element.classList.length; eIndex--;) {
7187
+ var className = element.classList[eIndex];
7188
+ if (blockClass.test(className)) {
7189
+ return true;
7190
+ }
7191
+ }
7192
+ }
7193
+ if (blockSelector) {
7194
+ return element.matches(blockSelector);
7195
+ }
7196
+ return false;
7197
+ }
7198
+ function classMatchesRegex(node, regex, checkAncestors) {
7199
+ if (!node)
7200
+ return false;
7201
+ if (node.nodeType !== node.ELEMENT_NODE) {
7202
+ if (!checkAncestors)
7203
+ return false;
7204
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
7205
+ }
7206
+ for (var eIndex = node.classList.length; eIndex--;) {
7207
+ var className = node.classList[eIndex];
7208
+ if (regex.test(className)) {
7209
+ return true;
7210
+ }
7211
+ }
7212
+ if (!checkAncestors)
7213
+ return false;
7214
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
7215
+ }
7216
+ function needMaskingText(node, maskTextClass, maskTextSelector) {
7217
+ var el = node.nodeType === node.ELEMENT_NODE
7218
+ ? node
7219
+ : node.parentElement;
7220
+ if (el === null)
7221
+ return false;
7222
+ if (typeof maskTextClass === 'string') {
7223
+ if (el.classList.contains(maskTextClass))
7224
+ return true;
7225
+ if (el.closest(".".concat(maskTextClass)))
7226
+ return true;
7227
+ }
7228
+ else {
7229
+ if (classMatchesRegex(el, maskTextClass, true))
7230
+ return true;
7231
+ }
7232
+ if (maskTextSelector) {
7233
+ if (el.matches(maskTextSelector))
7234
+ return true;
7235
+ if (el.closest(maskTextSelector))
7236
+ return true;
7237
+ }
7238
+ return false;
7239
+ }
7240
+ function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
7241
+ var win = iframeEl.contentWindow;
7242
+ if (!win) {
7243
+ return;
7244
+ }
7245
+ var fired = false;
7246
+ var readyState;
7247
+ try {
7248
+ readyState = win.document.readyState;
7249
+ }
7250
+ catch (error) {
7251
+ return;
7252
+ }
7253
+ if (readyState !== 'complete') {
7254
+ var timer_1 = setTimeout(function () {
7255
+ if (!fired) {
7256
+ listener();
7257
+ fired = true;
7258
+ }
7259
+ }, iframeLoadTimeout);
7260
+ iframeEl.addEventListener('load', function () {
7261
+ clearTimeout(timer_1);
7262
+ fired = true;
7263
+ listener();
7264
+ });
7265
+ return;
7266
+ }
7267
+ var blankUrl = 'about:blank';
7268
+ if (win.location.href !== blankUrl ||
7269
+ iframeEl.src === blankUrl ||
7270
+ iframeEl.src === '') {
7271
+ setTimeout(listener, 0);
7272
+ return iframeEl.addEventListener('load', listener);
7273
+ }
7274
+ iframeEl.addEventListener('load', listener);
7275
+ }
7276
+ function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
7277
+ var fired = false;
7278
+ var styleSheetLoaded;
7279
+ try {
7280
+ styleSheetLoaded = link.sheet;
7281
+ }
7282
+ catch (error) {
7283
+ return;
7284
+ }
7285
+ if (styleSheetLoaded)
7286
+ return;
7287
+ var timer = setTimeout(function () {
7288
+ if (!fired) {
7289
+ listener();
7290
+ fired = true;
7291
+ }
7292
+ }, styleSheetLoadTimeout);
7293
+ link.addEventListener('load', function () {
7294
+ clearTimeout(timer);
7295
+ fired = true;
7296
+ listener();
7297
+ });
7298
+ }
7299
+ function serializeNode(n, options) {
7300
+ 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;
7301
+ var rootId = getRootId(doc, mirror);
7302
+ switch (n.nodeType) {
7303
+ case n.DOCUMENT_NODE:
7304
+ if (n.compatMode !== 'CSS1Compat') {
7305
+ return {
7306
+ type: NodeType.Document,
7307
+ childNodes: [],
7308
+ compatMode: n.compatMode
7309
+ };
7310
+ }
7311
+ else {
7312
+ return {
7313
+ type: NodeType.Document,
7314
+ childNodes: []
7315
+ };
7316
+ }
7317
+ case n.DOCUMENT_TYPE_NODE:
7318
+ return {
7319
+ type: NodeType.DocumentType,
7320
+ name: n.name,
7321
+ publicId: n.publicId,
7322
+ systemId: n.systemId,
7323
+ rootId: rootId
7324
+ };
7325
+ case n.ELEMENT_NODE:
7326
+ return serializeElementNode(n, {
7327
+ doc: doc,
7328
+ blockClass: blockClass,
7329
+ blockSelector: blockSelector,
7330
+ inlineStylesheet: inlineStylesheet,
7331
+ maskInputOptions: maskInputOptions,
7332
+ maskInputFn: maskInputFn,
7333
+ dataURLOptions: dataURLOptions,
7334
+ inlineImages: inlineImages,
7335
+ recordCanvas: recordCanvas,
7336
+ keepIframeSrcFn: keepIframeSrcFn,
7337
+ newlyAddedElement: newlyAddedElement,
7338
+ rootId: rootId
7339
+ });
7340
+ case n.TEXT_NODE:
7341
+ return serializeTextNode(n, {
7342
+ maskTextClass: maskTextClass,
7343
+ maskTextSelector: maskTextSelector,
7344
+ maskTextFn: maskTextFn,
7345
+ rootId: rootId
7346
+ });
7347
+ case n.CDATA_SECTION_NODE:
7348
+ return {
7349
+ type: NodeType.CDATA,
7350
+ textContent: '',
7351
+ rootId: rootId
7352
+ };
7353
+ case n.COMMENT_NODE:
7354
+ return {
7355
+ type: NodeType.Comment,
7356
+ textContent: n.textContent || '',
7357
+ rootId: rootId
7358
+ };
7359
+ default:
7360
+ return false;
7361
+ }
7362
+ }
7363
+ function getRootId(doc, mirror) {
7364
+ if (!mirror.hasNode(doc))
7365
+ return undefined;
7366
+ var docId = mirror.getId(doc);
7367
+ return docId === 1 ? undefined : docId;
7368
+ }
7369
+ function serializeTextNode(n, options) {
7370
+ var _a;
7371
+ var maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, maskTextFn = options.maskTextFn, rootId = options.rootId;
7372
+ var parentTagName = n.parentNode && n.parentNode.tagName;
7373
+ var textContent = n.textContent;
7374
+ var isStyle = parentTagName === 'STYLE' ? true : undefined;
7375
+ var isScript = parentTagName === 'SCRIPT' ? true : undefined;
7376
+ if (isStyle && textContent) {
7377
+ try {
7378
+ if (n.nextSibling || n.previousSibling) {
7379
+ }
7380
+ else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {
7381
+ textContent = stringifyStyleSheet(n.parentNode.sheet);
7382
+ }
7383
+ }
7384
+ catch (err) {
7385
+ console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(err), n);
7386
+ }
7387
+ textContent = absoluteToStylesheet(textContent, getHref());
7388
+ }
7389
+ if (isScript) {
7390
+ textContent = 'SCRIPT_PLACEHOLDER';
7391
+ }
7392
+ if (!isStyle &&
7393
+ !isScript &&
7394
+ textContent &&
7395
+ needMaskingText(n, maskTextClass, maskTextSelector)) {
7396
+ textContent = maskTextFn
7397
+ ? maskTextFn(textContent)
7398
+ : textContent.replace(/[\S]/g, '*');
7399
+ }
7400
+ return {
7401
+ type: NodeType.Text,
7402
+ textContent: textContent || '',
7403
+ isStyle: isStyle,
7404
+ rootId: rootId
7405
+ };
7406
+ }
7407
+ function serializeElementNode(n, options) {
7408
+ 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;
7409
+ var needBlock = _isBlockedElement(n, blockClass, blockSelector);
7410
+ var tagName = getValidTagName(n);
7411
+ var attributes = {};
7412
+ var len = n.attributes.length;
7413
+ for (var i = 0; i < len; i++) {
7414
+ var attr = n.attributes[i];
7415
+ attributes[attr.name] = transformAttribute(doc, tagName, attr.name, attr.value);
7416
+ }
7417
+ if (tagName === 'link' && inlineStylesheet) {
7418
+ var stylesheet = Array.from(doc.styleSheets).find(function (s) {
7419
+ return s.href === n.href;
7420
+ });
7421
+ var cssText = null;
7422
+ if (stylesheet) {
7423
+ cssText = getCssRulesString(stylesheet);
7424
+ }
7425
+ if (cssText) {
7426
+ delete attributes.rel;
7427
+ delete attributes.href;
7428
+ attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
7429
+ }
7430
+ }
7431
+ if (tagName === 'style' &&
7432
+ n.sheet &&
7433
+ !(n.innerText || n.textContent || '').trim().length) {
7434
+ var cssText = getCssRulesString(n.sheet);
7435
+ if (cssText) {
7436
+ attributes._cssText = absoluteToStylesheet(cssText, getHref());
7437
+ }
7438
+ }
7439
+ if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
7440
+ var value = n.value;
7441
+ var checked = n.checked;
7442
+ if (attributes.type !== 'radio' &&
7443
+ attributes.type !== 'checkbox' &&
7444
+ attributes.type !== 'submit' &&
7445
+ attributes.type !== 'button' &&
7446
+ value) {
7447
+ attributes.value = maskInputValue({
7448
+ type: attributes.type,
7449
+ tagName: tagName,
7450
+ value: value,
7451
+ maskInputOptions: maskInputOptions,
7452
+ maskInputFn: maskInputFn
7453
+ });
7454
+ }
7455
+ else if (checked) {
7456
+ attributes.checked = checked;
7457
+ }
7458
+ }
7459
+ if (tagName === 'option') {
7460
+ if (n.selected && !maskInputOptions['select']) {
7461
+ attributes.selected = true;
7462
+ }
7463
+ else {
7464
+ delete attributes.selected;
7465
+ }
7466
+ }
7467
+ if (tagName === 'canvas' && recordCanvas) {
7468
+ if (n.__context === '2d') {
7469
+ if (!is2DCanvasBlank(n)) {
7470
+ attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7471
+ }
7472
+ }
7473
+ else if (!('__context' in n)) {
7474
+ var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7475
+ var blankCanvas = document.createElement('canvas');
7476
+ blankCanvas.width = n.width;
7477
+ blankCanvas.height = n.height;
7478
+ var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7479
+ if (canvasDataURL !== blankCanvasDataURL) {
7480
+ attributes.rr_dataURL = canvasDataURL;
7481
+ }
7482
+ }
7483
+ }
7484
+ if (tagName === 'img' && inlineImages) {
7485
+ if (!canvasService) {
7486
+ canvasService = doc.createElement('canvas');
7487
+ canvasCtx = canvasService.getContext('2d');
7488
+ }
7489
+ var image_1 = n;
7490
+ var oldValue_1 = image_1.crossOrigin;
7491
+ image_1.crossOrigin = 'anonymous';
7492
+ var recordInlineImage = function () {
7493
+ try {
7494
+ canvasService.width = image_1.naturalWidth;
7495
+ canvasService.height = image_1.naturalHeight;
7496
+ canvasCtx.drawImage(image_1, 0, 0);
7497
+ attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7498
+ }
7499
+ catch (err) {
7500
+ console.warn("Cannot inline img src=".concat(image_1.currentSrc, "! Error: ").concat(err));
7501
+ }
7502
+ oldValue_1
7503
+ ? (attributes.crossOrigin = oldValue_1)
7504
+ : image_1.removeAttribute('crossorigin');
7505
+ };
7506
+ if (image_1.complete && image_1.naturalWidth !== 0)
7507
+ recordInlineImage();
7508
+ else
7509
+ image_1.onload = recordInlineImage;
7510
+ }
7511
+ if (tagName === 'audio' || tagName === 'video') {
7512
+ attributes.rr_mediaState = n.paused
7513
+ ? 'paused'
7514
+ : 'played';
7515
+ attributes.rr_mediaCurrentTime = n.currentTime;
7516
+ }
7517
+ if (!newlyAddedElement) {
7518
+ if (n.scrollLeft) {
7519
+ attributes.rr_scrollLeft = n.scrollLeft;
7520
+ }
7521
+ if (n.scrollTop) {
7522
+ attributes.rr_scrollTop = n.scrollTop;
7523
+ }
7524
+ }
7525
+ if (needBlock) {
7526
+ var _d = n.getBoundingClientRect(), width = _d.width, height = _d.height;
7527
+ attributes = {
7528
+ "class": attributes["class"],
7529
+ rr_width: "".concat(width, "px"),
7530
+ rr_height: "".concat(height, "px")
7531
+ };
7532
+ }
7533
+ if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {
7534
+ if (!n.contentDocument) {
7535
+ attributes.rr_src = attributes.src;
7536
+ }
7537
+ delete attributes.src;
7538
+ }
7539
+ return {
7540
+ type: NodeType.Element,
7541
+ tagName: tagName,
7542
+ attributes: attributes,
7543
+ childNodes: [],
7544
+ isSVG: isSVGElement(n) || undefined,
7545
+ needBlock: needBlock,
7546
+ rootId: rootId
7547
+ };
7548
+ }
7549
+ function lowerIfExists(maybeAttr) {
7550
+ if (maybeAttr === undefined) {
7551
+ return '';
7552
+ }
7553
+ else {
7554
+ return maybeAttr.toLowerCase();
7555
+ }
7556
+ }
7557
+ function slimDOMExcluded(sn, slimDOMOptions) {
7558
+ if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
7559
+ return true;
7560
+ }
7561
+ else if (sn.type === NodeType.Element) {
7562
+ if (slimDOMOptions.script &&
7563
+ (sn.tagName === 'script' ||
7564
+ (sn.tagName === 'link' &&
7565
+ sn.attributes.rel === 'preload' &&
7566
+ sn.attributes.as === 'script') ||
7567
+ (sn.tagName === 'link' &&
7568
+ sn.attributes.rel === 'prefetch' &&
7569
+ typeof sn.attributes.href === 'string' &&
7570
+ sn.attributes.href.endsWith('.js')))) {
7571
+ return true;
7572
+ }
7573
+ else if (slimDOMOptions.headFavicon &&
7574
+ ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||
7575
+ (sn.tagName === 'meta' &&
7576
+ (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||
7577
+ lowerIfExists(sn.attributes.name) === 'application-name' ||
7578
+ lowerIfExists(sn.attributes.rel) === 'icon' ||
7579
+ lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||
7580
+ lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {
7581
+ return true;
7582
+ }
7583
+ else if (sn.tagName === 'meta') {
7584
+ if (slimDOMOptions.headMetaDescKeywords &&
7585
+ lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
7586
+ return true;
7587
+ }
7588
+ else if (slimDOMOptions.headMetaSocial &&
7589
+ (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||
7590
+ lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||
7591
+ lowerIfExists(sn.attributes.name) === 'pinterest')) {
7592
+ return true;
7593
+ }
7594
+ else if (slimDOMOptions.headMetaRobots &&
7595
+ (lowerIfExists(sn.attributes.name) === 'robots' ||
7596
+ lowerIfExists(sn.attributes.name) === 'googlebot' ||
7597
+ lowerIfExists(sn.attributes.name) === 'bingbot')) {
7598
+ return true;
7599
+ }
7600
+ else if (slimDOMOptions.headMetaHttpEquiv &&
7601
+ sn.attributes['http-equiv'] !== undefined) {
7602
+ return true;
7603
+ }
7604
+ else if (slimDOMOptions.headMetaAuthorship &&
7605
+ (lowerIfExists(sn.attributes.name) === 'author' ||
7606
+ lowerIfExists(sn.attributes.name) === 'generator' ||
7607
+ lowerIfExists(sn.attributes.name) === 'framework' ||
7608
+ lowerIfExists(sn.attributes.name) === 'publisher' ||
7609
+ lowerIfExists(sn.attributes.name) === 'progid' ||
7610
+ lowerIfExists(sn.attributes.property).match(/^article:/) ||
7611
+ lowerIfExists(sn.attributes.property).match(/^product:/))) {
7612
+ return true;
7613
+ }
7614
+ else if (slimDOMOptions.headMetaVerification &&
7615
+ (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||
7616
+ lowerIfExists(sn.attributes.name) === 'yandex-verification' ||
7617
+ lowerIfExists(sn.attributes.name) === 'csrf-token' ||
7618
+ lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||
7619
+ lowerIfExists(sn.attributes.name) === 'verify-v1' ||
7620
+ lowerIfExists(sn.attributes.name) === 'verification' ||
7621
+ lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {
7622
+ return true;
7623
+ }
7624
+ }
7625
+ }
7626
+ return false;
7627
+ }
7628
+ function serializeNodeWithId(n, options) {
7629
+ 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;
7630
+ var _l = options.preserveWhiteSpace, preserveWhiteSpace = _l === void 0 ? true : _l;
7631
+ var _serializedNode = serializeNode(n, {
7632
+ doc: doc,
7633
+ mirror: mirror,
7634
+ blockClass: blockClass,
7635
+ blockSelector: blockSelector,
7636
+ maskTextClass: maskTextClass,
7637
+ maskTextSelector: maskTextSelector,
7638
+ inlineStylesheet: inlineStylesheet,
7639
+ maskInputOptions: maskInputOptions,
7640
+ maskTextFn: maskTextFn,
7641
+ maskInputFn: maskInputFn,
7642
+ dataURLOptions: dataURLOptions,
7643
+ inlineImages: inlineImages,
7644
+ recordCanvas: recordCanvas,
7645
+ keepIframeSrcFn: keepIframeSrcFn,
7646
+ newlyAddedElement: newlyAddedElement
7647
+ });
7648
+ if (!_serializedNode) {
7649
+ console.warn(n, 'not serialized');
7650
+ return null;
7651
+ }
7652
+ var id;
7653
+ if (mirror.hasNode(n)) {
7654
+ id = mirror.getId(n);
7655
+ }
7656
+ else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||
7657
+ (!preserveWhiteSpace &&
7658
+ _serializedNode.type === NodeType.Text &&
7659
+ !_serializedNode.isStyle &&
7660
+ !_serializedNode.textContent.replace(/^\s+|\s+$/gm, '').length)) {
7661
+ id = IGNORED_NODE;
7662
+ }
7663
+ else {
7664
+ id = genId();
7665
+ }
7666
+ var serializedNode = Object.assign(_serializedNode, { id: id });
7667
+ mirror.add(n, serializedNode);
7668
+ if (id === IGNORED_NODE) {
7669
+ return null;
7670
+ }
7671
+ if (onSerialize) {
7672
+ onSerialize(n);
7673
+ }
7674
+ var recordChild = !skipChild;
7675
+ if (serializedNode.type === NodeType.Element) {
7676
+ recordChild = recordChild && !serializedNode.needBlock;
7677
+ delete serializedNode.needBlock;
7678
+ var shadowRoot = n.shadowRoot;
7679
+ if (shadowRoot && isNativeShadowDom(shadowRoot))
7680
+ serializedNode.isShadowHost = true;
7681
+ }
7682
+ if ((serializedNode.type === NodeType.Document ||
7683
+ serializedNode.type === NodeType.Element) &&
7684
+ recordChild) {
7685
+ if (slimDOMOptions.headWhitespace &&
7686
+ serializedNode.type === NodeType.Element &&
7687
+ serializedNode.tagName === 'head') {
7688
+ preserveWhiteSpace = false;
7689
+ }
7690
+ var bypassOptions = {
7691
+ doc: doc,
7692
+ mirror: mirror,
7693
+ blockClass: blockClass,
7694
+ blockSelector: blockSelector,
7695
+ maskTextClass: maskTextClass,
7696
+ maskTextSelector: maskTextSelector,
7697
+ skipChild: skipChild,
7698
+ inlineStylesheet: inlineStylesheet,
7699
+ maskInputOptions: maskInputOptions,
7700
+ maskTextFn: maskTextFn,
7701
+ maskInputFn: maskInputFn,
7702
+ slimDOMOptions: slimDOMOptions,
7703
+ dataURLOptions: dataURLOptions,
7704
+ inlineImages: inlineImages,
7705
+ recordCanvas: recordCanvas,
7706
+ preserveWhiteSpace: preserveWhiteSpace,
7707
+ onSerialize: onSerialize,
7708
+ onIframeLoad: onIframeLoad,
7709
+ iframeLoadTimeout: iframeLoadTimeout,
7710
+ onStylesheetLoad: onStylesheetLoad,
7711
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
7712
+ keepIframeSrcFn: keepIframeSrcFn
7713
+ };
7714
+ for (var _i = 0, _m = Array.from(n.childNodes); _i < _m.length; _i++) {
7715
+ var childN = _m[_i];
7716
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
7717
+ if (serializedChildNode) {
7718
+ serializedNode.childNodes.push(serializedChildNode);
7719
+ }
7720
+ }
7721
+ if (isElement(n) && n.shadowRoot) {
7722
+ for (var _o = 0, _p = Array.from(n.shadowRoot.childNodes); _o < _p.length; _o++) {
7723
+ var childN = _p[_o];
7724
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
7725
+ if (serializedChildNode) {
7726
+ isNativeShadowDom(n.shadowRoot) &&
7727
+ (serializedChildNode.isShadow = true);
7728
+ serializedNode.childNodes.push(serializedChildNode);
7729
+ }
7730
+ }
7731
+ }
7732
+ }
7733
+ if (n.parentNode &&
7734
+ isShadowRoot(n.parentNode) &&
7735
+ isNativeShadowDom(n.parentNode)) {
7736
+ serializedNode.isShadow = true;
7737
+ }
7738
+ if (serializedNode.type === NodeType.Element &&
7739
+ serializedNode.tagName === 'iframe') {
7740
+ onceIframeLoaded(n, function () {
7741
+ var iframeDoc = n.contentDocument;
7742
+ if (iframeDoc && onIframeLoad) {
7743
+ var serializedIframeNode = serializeNodeWithId(iframeDoc, {
7744
+ doc: iframeDoc,
7745
+ mirror: mirror,
7746
+ blockClass: blockClass,
7747
+ blockSelector: blockSelector,
7748
+ maskTextClass: maskTextClass,
7749
+ maskTextSelector: maskTextSelector,
7750
+ skipChild: false,
7751
+ inlineStylesheet: inlineStylesheet,
7752
+ maskInputOptions: maskInputOptions,
7753
+ maskTextFn: maskTextFn,
7754
+ maskInputFn: maskInputFn,
7755
+ slimDOMOptions: slimDOMOptions,
7756
+ dataURLOptions: dataURLOptions,
7757
+ inlineImages: inlineImages,
7758
+ recordCanvas: recordCanvas,
7759
+ preserveWhiteSpace: preserveWhiteSpace,
7760
+ onSerialize: onSerialize,
7761
+ onIframeLoad: onIframeLoad,
7762
+ iframeLoadTimeout: iframeLoadTimeout,
7763
+ onStylesheetLoad: onStylesheetLoad,
7764
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
7765
+ keepIframeSrcFn: keepIframeSrcFn
7766
+ });
7767
+ if (serializedIframeNode) {
7768
+ onIframeLoad(n, serializedIframeNode);
7769
+ }
7770
+ }
7771
+ }, iframeLoadTimeout);
7772
+ }
7773
+ if (serializedNode.type === NodeType.Element &&
7774
+ serializedNode.tagName === 'link' &&
7775
+ serializedNode.attributes.rel === 'stylesheet') {
7776
+ onceStylesheetLoaded(n, function () {
7777
+ if (onStylesheetLoad) {
7778
+ var serializedLinkNode = serializeNodeWithId(n, {
7779
+ doc: doc,
7780
+ mirror: mirror,
7781
+ blockClass: blockClass,
7782
+ blockSelector: blockSelector,
7783
+ maskTextClass: maskTextClass,
7784
+ maskTextSelector: maskTextSelector,
7785
+ skipChild: false,
7786
+ inlineStylesheet: inlineStylesheet,
7787
+ maskInputOptions: maskInputOptions,
7788
+ maskTextFn: maskTextFn,
7789
+ maskInputFn: maskInputFn,
7790
+ slimDOMOptions: slimDOMOptions,
7791
+ dataURLOptions: dataURLOptions,
7792
+ inlineImages: inlineImages,
7793
+ recordCanvas: recordCanvas,
7794
+ preserveWhiteSpace: preserveWhiteSpace,
7795
+ onSerialize: onSerialize,
7796
+ onIframeLoad: onIframeLoad,
7797
+ iframeLoadTimeout: iframeLoadTimeout,
7798
+ onStylesheetLoad: onStylesheetLoad,
7799
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
7800
+ keepIframeSrcFn: keepIframeSrcFn
7801
+ });
7802
+ if (serializedLinkNode) {
7803
+ onStylesheetLoad(n, serializedLinkNode);
7804
+ }
7805
+ }
7806
+ }, stylesheetLoadTimeout);
7807
+ }
7808
+ return serializedNode;
7809
+ }
7810
+ function snapshot(n, options) {
7811
+ 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;
7812
+ var maskInputOptions = maskAllInputs === true
7813
+ ? {
7814
+ color: true,
7815
+ date: true,
7816
+ 'datetime-local': true,
7817
+ email: true,
7818
+ month: true,
7819
+ number: true,
7820
+ range: true,
7821
+ search: true,
7822
+ tel: true,
7823
+ text: true,
7824
+ time: true,
7825
+ url: true,
7826
+ week: true,
7827
+ textarea: true,
7828
+ select: true,
7829
+ password: true
7830
+ }
7831
+ : maskAllInputs === false
7832
+ ? {
7833
+ password: true
7834
+ }
7835
+ : maskAllInputs;
7836
+ var slimDOMOptions = slimDOM === true || slimDOM === 'all'
7837
+ ?
7838
+ {
7839
+ script: true,
7840
+ comment: true,
7841
+ headFavicon: true,
7842
+ headWhitespace: true,
7843
+ headMetaDescKeywords: slimDOM === 'all',
7844
+ headMetaSocial: true,
7845
+ headMetaRobots: true,
7846
+ headMetaHttpEquiv: true,
7847
+ headMetaAuthorship: true,
7848
+ headMetaVerification: true
7849
+ }
7850
+ : slimDOM === false
7851
+ ? {}
7852
+ : slimDOM;
7853
+ return serializeNodeWithId(n, {
7854
+ doc: n,
7855
+ mirror: mirror,
7856
+ blockClass: blockClass,
7857
+ blockSelector: blockSelector,
7858
+ maskTextClass: maskTextClass,
7859
+ maskTextSelector: maskTextSelector,
7860
+ skipChild: false,
7861
+ inlineStylesheet: inlineStylesheet,
7862
+ maskInputOptions: maskInputOptions,
7863
+ maskTextFn: maskTextFn,
7864
+ maskInputFn: maskInputFn,
7865
+ slimDOMOptions: slimDOMOptions,
7866
+ dataURLOptions: dataURLOptions,
7867
+ inlineImages: inlineImages,
7868
+ recordCanvas: recordCanvas,
7869
+ preserveWhiteSpace: preserveWhiteSpace,
7870
+ onSerialize: onSerialize,
7871
+ onIframeLoad: onIframeLoad,
7872
+ iframeLoadTimeout: iframeLoadTimeout,
7873
+ onStylesheetLoad: onStylesheetLoad,
7874
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
7875
+ keepIframeSrcFn: keepIframeSrcFn,
7876
+ newlyAddedElement: false
7877
+ });
7878
+ }
7879
+
7880
+ function on(type, fn, target = document) {
7881
+ const options = { capture: true, passive: true };
7882
+ target.addEventListener(type, fn, options);
7883
+ return () => target.removeEventListener(type, fn, options);
7884
+ }
7885
+ const DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +
7886
+ '\r\n' +
7887
+ 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +
7888
+ '\r\n' +
7889
+ 'or you can use record.mirror to access the mirror instance during recording.';
7890
+ let _mirror = {
7891
+ map: {},
7892
+ getId() {
7893
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
7894
+ return -1;
7895
+ },
7896
+ getNode() {
7897
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
7898
+ return null;
7899
+ },
7900
+ removeNodeFromMap() {
7901
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
7902
+ },
7903
+ has() {
7904
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
7905
+ return false;
7906
+ },
7907
+ reset() {
7908
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
7909
+ },
7910
+ };
7911
+ if (typeof window !== 'undefined' && window.Proxy && window.Reflect) {
7912
+ _mirror = new Proxy(_mirror, {
7913
+ get(target, prop, receiver) {
7914
+ if (prop === 'map') {
7915
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
7916
+ }
7917
+ return Reflect.get(target, prop, receiver);
7918
+ },
7919
+ });
7920
+ }
7921
+ function throttle(func, wait, options = {}) {
7922
+ let timeout = null;
7923
+ let previous = 0;
7924
+ return function (...args) {
7925
+ const now = Date.now();
7926
+ if (!previous && options.leading === false) {
7927
+ previous = now;
7928
+ }
7929
+ const remaining = wait - (now - previous);
7930
+ const context = this;
7931
+ if (remaining <= 0 || remaining > wait) {
7932
+ if (timeout) {
7933
+ clearTimeout(timeout);
7934
+ timeout = null;
7935
+ }
7936
+ previous = now;
7937
+ func.apply(context, args);
7938
+ }
7939
+ else if (!timeout && options.trailing !== false) {
7940
+ timeout = setTimeout(() => {
7941
+ previous = options.leading === false ? 0 : Date.now();
7942
+ timeout = null;
7943
+ func.apply(context, args);
7944
+ }, remaining);
7945
+ }
7946
+ };
7947
+ }
7948
+ function hookSetter(target, key, d, isRevoked, win = window) {
7949
+ const original = win.Object.getOwnPropertyDescriptor(target, key);
7950
+ win.Object.defineProperty(target, key, isRevoked
7951
+ ? d
7952
+ : {
7953
+ set(value) {
7954
+ setTimeout(() => {
7955
+ d.set.call(this, value);
7956
+ }, 0);
7957
+ if (original && original.set) {
7958
+ original.set.call(this, value);
7959
+ }
7960
+ },
7961
+ });
7962
+ return () => hookSetter(target, key, original || {}, true);
7963
+ }
7964
+ function patch(source, name, replacement) {
7965
+ try {
7966
+ if (!(name in source)) {
7967
+ return () => {
7968
+ };
7969
+ }
7970
+ const original = source[name];
7971
+ const wrapped = replacement(original);
7972
+ if (typeof wrapped === 'function') {
7973
+ wrapped.prototype = wrapped.prototype || {};
7974
+ Object.defineProperties(wrapped, {
7975
+ __rrweb_original__: {
7976
+ enumerable: false,
7977
+ value: original,
7978
+ },
7979
+ });
7980
+ }
7981
+ source[name] = wrapped;
7982
+ return () => {
7983
+ source[name] = original;
7984
+ };
7985
+ }
7986
+ catch (_a) {
7987
+ return () => {
7988
+ };
7989
+ }
7990
+ }
7991
+ function getWindowHeight() {
7992
+ return (window.innerHeight ||
7993
+ (document.documentElement && document.documentElement.clientHeight) ||
7994
+ (document.body && document.body.clientHeight));
7995
+ }
7996
+ function getWindowWidth() {
7997
+ return (window.innerWidth ||
7998
+ (document.documentElement && document.documentElement.clientWidth) ||
7999
+ (document.body && document.body.clientWidth));
8000
+ }
8001
+ function isBlocked(node, blockClass, blockSelector, checkAncestors) {
8002
+ if (!node) {
8003
+ return false;
8004
+ }
8005
+ const el = node.nodeType === node.ELEMENT_NODE
8006
+ ? node
8007
+ : node.parentElement;
8008
+ if (!el)
8009
+ return false;
8010
+ if (typeof blockClass === 'string') {
8011
+ if (el.classList.contains(blockClass))
8012
+ return true;
8013
+ if (checkAncestors && el.closest('.' + blockClass) !== null)
8014
+ return true;
8015
+ }
8016
+ else {
8017
+ if (classMatchesRegex(el, blockClass, checkAncestors))
8018
+ return true;
8019
+ }
8020
+ if (blockSelector) {
8021
+ if (node.matches(blockSelector))
8022
+ return true;
8023
+ if (checkAncestors && el.closest(blockSelector) !== null)
8024
+ return true;
8025
+ }
8026
+ return false;
8027
+ }
8028
+ function isSerialized(n, mirror) {
8029
+ return mirror.getId(n) !== -1;
8030
+ }
8031
+ function isIgnored(n, mirror) {
8032
+ return mirror.getId(n) === IGNORED_NODE;
8033
+ }
8034
+ function isAncestorRemoved(target, mirror) {
8035
+ if (isShadowRoot(target)) {
8036
+ return false;
8037
+ }
8038
+ const id = mirror.getId(target);
8039
+ if (!mirror.has(id)) {
8040
+ return true;
8041
+ }
8042
+ if (target.parentNode &&
8043
+ target.parentNode.nodeType === target.DOCUMENT_NODE) {
8044
+ return false;
8045
+ }
8046
+ if (!target.parentNode) {
8047
+ return true;
8048
+ }
8049
+ return isAncestorRemoved(target.parentNode, mirror);
8050
+ }
8051
+ function isTouchEvent(event) {
8052
+ return Boolean(event.changedTouches);
8053
+ }
8054
+ function polyfill(win = window) {
8055
+ if ('NodeList' in win && !win.NodeList.prototype.forEach) {
8056
+ win.NodeList.prototype.forEach = Array.prototype
8057
+ .forEach;
8058
+ }
8059
+ if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {
8060
+ win.DOMTokenList.prototype.forEach = Array.prototype
8061
+ .forEach;
8062
+ }
8063
+ if (!Node.prototype.contains) {
8064
+ Node.prototype.contains = (...args) => {
8065
+ let node = args[0];
8066
+ if (!(0 in args)) {
8067
+ throw new TypeError('1 argument is required');
8068
+ }
8069
+ do {
8070
+ if (this === node) {
8071
+ return true;
8072
+ }
8073
+ } while ((node = node && node.parentNode));
8074
+ return false;
8075
+ };
8076
+ }
8077
+ }
8078
+ function isSerializedIframe(n, mirror) {
8079
+ return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
8080
+ }
8081
+ function isSerializedStylesheet(n, mirror) {
8082
+ return Boolean(n.nodeName === 'LINK' &&
8083
+ n.nodeType === n.ELEMENT_NODE &&
8084
+ n.getAttribute &&
8085
+ n.getAttribute('rel') === 'stylesheet' &&
8086
+ mirror.getMeta(n));
8087
+ }
8088
+ function hasShadowRoot(n) {
8089
+ return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);
8090
+ }
8091
+ class StyleSheetMirror {
8092
+ constructor() {
8093
+ this.id = 1;
8094
+ this.styleIDMap = new WeakMap();
8095
+ this.idStyleMap = new Map();
8096
+ }
8097
+ getId(stylesheet) {
8098
+ var _a;
8099
+ return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;
8100
+ }
8101
+ has(stylesheet) {
8102
+ return this.styleIDMap.has(stylesheet);
8103
+ }
8104
+ add(stylesheet, id) {
8105
+ if (this.has(stylesheet))
8106
+ return this.getId(stylesheet);
8107
+ let newId;
8108
+ if (id === undefined) {
8109
+ newId = this.id++;
8110
+ }
8111
+ else
8112
+ newId = id;
8113
+ this.styleIDMap.set(stylesheet, newId);
8114
+ this.idStyleMap.set(newId, stylesheet);
8115
+ return newId;
8116
+ }
8117
+ getStyle(id) {
8118
+ return this.idStyleMap.get(id) || null;
8119
+ }
8120
+ reset() {
8121
+ this.styleIDMap = new WeakMap();
8122
+ this.idStyleMap = new Map();
8123
+ this.id = 1;
8124
+ }
8125
+ generateId() {
8126
+ return this.id++;
8127
+ }
8128
+ }
8129
+
8130
+ var EventType = /* @__PURE__ */ ((EventType2) => {
8131
+ EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
8132
+ EventType2[EventType2["Load"] = 1] = "Load";
8133
+ EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
8134
+ EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
8135
+ EventType2[EventType2["Meta"] = 4] = "Meta";
8136
+ EventType2[EventType2["Custom"] = 5] = "Custom";
8137
+ EventType2[EventType2["Plugin"] = 6] = "Plugin";
8138
+ return EventType2;
8139
+ })(EventType || {});
8140
+ var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
8141
+ IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
8142
+ IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
8143
+ IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
8144
+ IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
8145
+ IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
8146
+ IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
8147
+ IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
8148
+ IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
8149
+ IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
8150
+ IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
8151
+ IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
8152
+ IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
8153
+ IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
8154
+ IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
8155
+ IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
8156
+ IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
8157
+ return IncrementalSource2;
8158
+ })(IncrementalSource || {});
8159
+ var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
8160
+ MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
8161
+ MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
8162
+ MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
8163
+ MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
8164
+ MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
8165
+ MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
8166
+ MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
8167
+ MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
8168
+ MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
8169
+ MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
8170
+ MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
8171
+ return MouseInteractions2;
8172
+ })(MouseInteractions || {});
8173
+ var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
8174
+ CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
8175
+ CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
8176
+ CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
8177
+ return CanvasContext2;
8178
+ })(CanvasContext || {});
8179
+
8180
+ function isNodeInLinkedList(n) {
8181
+ return '__ln' in n;
8182
+ }
8183
+ class DoubleLinkedList {
8184
+ constructor() {
8185
+ this.length = 0;
8186
+ this.head = null;
8187
+ }
8188
+ get(position) {
8189
+ if (position >= this.length) {
8190
+ throw new Error('Position outside of list range');
8191
+ }
8192
+ let current = this.head;
8193
+ for (let index = 0; index < position; index++) {
8194
+ current = (current === null || current === void 0 ? void 0 : current.next) || null;
8195
+ }
8196
+ return current;
8197
+ }
8198
+ addNode(n) {
8199
+ const node = {
8200
+ value: n,
8201
+ previous: null,
8202
+ next: null,
8203
+ };
8204
+ n.__ln = node;
8205
+ if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {
8206
+ const current = n.previousSibling.__ln.next;
8207
+ node.next = current;
8208
+ node.previous = n.previousSibling.__ln;
8209
+ n.previousSibling.__ln.next = node;
8210
+ if (current) {
8211
+ current.previous = node;
8212
+ }
8213
+ }
8214
+ else if (n.nextSibling &&
8215
+ isNodeInLinkedList(n.nextSibling) &&
8216
+ n.nextSibling.__ln.previous) {
8217
+ const current = n.nextSibling.__ln.previous;
8218
+ node.previous = current;
8219
+ node.next = n.nextSibling.__ln;
8220
+ n.nextSibling.__ln.previous = node;
8221
+ if (current) {
8222
+ current.next = node;
8223
+ }
8224
+ }
8225
+ else {
8226
+ if (this.head) {
8227
+ this.head.previous = node;
8228
+ }
8229
+ node.next = this.head;
8230
+ this.head = node;
8231
+ }
8232
+ this.length++;
8233
+ }
8234
+ removeNode(n) {
8235
+ const current = n.__ln;
8236
+ if (!this.head) {
8237
+ return;
8238
+ }
8239
+ if (!current.previous) {
8240
+ this.head = current.next;
8241
+ if (this.head) {
8242
+ this.head.previous = null;
8243
+ }
8244
+ }
8245
+ else {
8246
+ current.previous.next = current.next;
8247
+ if (current.next) {
8248
+ current.next.previous = current.previous;
8249
+ }
8250
+ }
8251
+ if (n.__ln) {
8252
+ delete n.__ln;
8253
+ }
8254
+ this.length--;
8255
+ }
8256
+ }
8257
+ const moveKey = (id, parentId) => `${id}@${parentId}`;
8258
+ class MutationBuffer {
8259
+ constructor() {
8260
+ this.frozen = false;
8261
+ this.locked = false;
8262
+ this.texts = [];
8263
+ this.attributes = [];
8264
+ this.removes = [];
8265
+ this.mapRemoves = [];
8266
+ this.movedMap = {};
8267
+ this.addedSet = new Set();
8268
+ this.movedSet = new Set();
8269
+ this.droppedSet = new Set();
8270
+ this.processMutations = (mutations) => {
8271
+ mutations.forEach(this.processMutation);
8272
+ this.emit();
8273
+ };
8274
+ this.emit = () => {
8275
+ if (this.frozen || this.locked) {
8276
+ return;
8277
+ }
8278
+ const adds = [];
8279
+ const addList = new DoubleLinkedList();
8280
+ const getNextId = (n) => {
8281
+ let ns = n;
8282
+ let nextId = IGNORED_NODE;
8283
+ while (nextId === IGNORED_NODE) {
8284
+ ns = ns && ns.nextSibling;
8285
+ nextId = ns && this.mirror.getId(ns);
8286
+ }
8287
+ return nextId;
8288
+ };
8289
+ const pushAdd = (n) => {
8290
+ var _a, _b, _c, _d;
8291
+ let shadowHost = null;
8292
+ 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 &&
8293
+ n.getRootNode().host)
8294
+ shadowHost = n.getRootNode().host;
8295
+ let rootShadowHost = shadowHost;
8296
+ 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) ===
8297
+ Node.DOCUMENT_FRAGMENT_NODE &&
8298
+ rootShadowHost.getRootNode().host)
8299
+ rootShadowHost = rootShadowHost.getRootNode().host;
8300
+ const notInDoc = !this.doc.contains(n) &&
8301
+ (!rootShadowHost || !this.doc.contains(rootShadowHost));
8302
+ if (!n.parentNode || notInDoc) {
8303
+ return;
8304
+ }
8305
+ const parentId = isShadowRoot(n.parentNode)
8306
+ ? this.mirror.getId(shadowHost)
8307
+ : this.mirror.getId(n.parentNode);
8308
+ const nextId = getNextId(n);
8309
+ if (parentId === -1 || nextId === -1) {
8310
+ return addList.addNode(n);
8311
+ }
8312
+ const sn = serializeNodeWithId(n, {
8313
+ doc: this.doc,
8314
+ mirror: this.mirror,
8315
+ blockClass: this.blockClass,
8316
+ blockSelector: this.blockSelector,
8317
+ maskTextClass: this.maskTextClass,
8318
+ maskTextSelector: this.maskTextSelector,
8319
+ skipChild: true,
8320
+ newlyAddedElement: true,
8321
+ inlineStylesheet: this.inlineStylesheet,
8322
+ maskInputOptions: this.maskInputOptions,
8323
+ maskTextFn: this.maskTextFn,
8324
+ maskInputFn: this.maskInputFn,
8325
+ slimDOMOptions: this.slimDOMOptions,
8326
+ dataURLOptions: this.dataURLOptions,
8327
+ recordCanvas: this.recordCanvas,
8328
+ inlineImages: this.inlineImages,
8329
+ onSerialize: (currentN) => {
8330
+ if (isSerializedIframe(currentN, this.mirror)) {
8331
+ this.iframeManager.addIframe(currentN);
8332
+ }
8333
+ if (isSerializedStylesheet(currentN, this.mirror)) {
8334
+ this.stylesheetManager.trackLinkElement(currentN);
8335
+ }
8336
+ if (hasShadowRoot(n)) {
8337
+ this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);
8338
+ }
8339
+ },
8340
+ onIframeLoad: (iframe, childSn) => {
8341
+ this.iframeManager.attachIframe(iframe, childSn);
8342
+ this.shadowDomManager.observeAttachShadow(iframe);
8343
+ },
8344
+ onStylesheetLoad: (link, childSn) => {
8345
+ this.stylesheetManager.attachLinkElement(link, childSn);
8346
+ },
8347
+ });
8348
+ if (sn) {
8349
+ adds.push({
8350
+ parentId,
8351
+ nextId,
8352
+ node: sn,
8353
+ });
8354
+ }
8355
+ };
8356
+ while (this.mapRemoves.length) {
8357
+ this.mirror.removeNodeFromMap(this.mapRemoves.shift());
8358
+ }
8359
+ for (const n of Array.from(this.movedSet.values())) {
8360
+ if (isParentRemoved(this.removes, n, this.mirror) &&
8361
+ !this.movedSet.has(n.parentNode)) {
8362
+ continue;
8363
+ }
8364
+ pushAdd(n);
8365
+ }
8366
+ for (const n of Array.from(this.addedSet.values())) {
8367
+ if (!isAncestorInSet(this.droppedSet, n) &&
8368
+ !isParentRemoved(this.removes, n, this.mirror)) {
8369
+ pushAdd(n);
8370
+ }
8371
+ else if (isAncestorInSet(this.movedSet, n)) {
8372
+ pushAdd(n);
8373
+ }
8374
+ else {
8375
+ this.droppedSet.add(n);
8376
+ }
8377
+ }
8378
+ let candidate = null;
8379
+ while (addList.length) {
8380
+ let node = null;
8381
+ if (candidate) {
8382
+ const parentId = this.mirror.getId(candidate.value.parentNode);
8383
+ const nextId = getNextId(candidate.value);
8384
+ if (parentId !== -1 && nextId !== -1) {
8385
+ node = candidate;
8386
+ }
8387
+ }
8388
+ if (!node) {
8389
+ for (let index = addList.length - 1; index >= 0; index--) {
8390
+ const _node = addList.get(index);
8391
+ if (_node) {
8392
+ const parentId = this.mirror.getId(_node.value.parentNode);
8393
+ const nextId = getNextId(_node.value);
8394
+ if (nextId === -1)
8395
+ continue;
8396
+ else if (parentId !== -1) {
8397
+ node = _node;
8398
+ break;
8399
+ }
8400
+ else {
8401
+ const unhandledNode = _node.value;
8402
+ if (unhandledNode.parentNode &&
8403
+ unhandledNode.parentNode.nodeType ===
8404
+ Node.DOCUMENT_FRAGMENT_NODE) {
8405
+ const shadowHost = unhandledNode.parentNode
8406
+ .host;
8407
+ const parentId = this.mirror.getId(shadowHost);
8408
+ if (parentId !== -1) {
8409
+ node = _node;
8410
+ break;
8411
+ }
8412
+ }
8413
+ }
8414
+ }
8415
+ }
8416
+ }
8417
+ if (!node) {
8418
+ while (addList.head) {
8419
+ addList.removeNode(addList.head.value);
8420
+ }
8421
+ break;
8422
+ }
8423
+ candidate = node.previous;
8424
+ addList.removeNode(node.value);
8425
+ pushAdd(node.value);
8426
+ }
8427
+ const payload = {
8428
+ texts: this.texts
8429
+ .map((text) => ({
8430
+ id: this.mirror.getId(text.node),
8431
+ value: text.value,
8432
+ }))
8433
+ .filter((text) => this.mirror.has(text.id)),
8434
+ attributes: this.attributes
8435
+ .map((attribute) => ({
8436
+ id: this.mirror.getId(attribute.node),
8437
+ attributes: attribute.attributes,
8438
+ }))
8439
+ .filter((attribute) => this.mirror.has(attribute.id)),
8440
+ removes: this.removes,
8441
+ adds,
8442
+ };
8443
+ if (!payload.texts.length &&
8444
+ !payload.attributes.length &&
8445
+ !payload.removes.length &&
8446
+ !payload.adds.length) {
8447
+ return;
8448
+ }
8449
+ this.texts = [];
8450
+ this.attributes = [];
8451
+ this.removes = [];
8452
+ this.addedSet = new Set();
8453
+ this.movedSet = new Set();
8454
+ this.droppedSet = new Set();
8455
+ this.movedMap = {};
8456
+ this.mutationCb(payload);
8457
+ };
8458
+ this.processMutation = (m) => {
8459
+ if (isIgnored(m.target, this.mirror)) {
8460
+ return;
8461
+ }
8462
+ switch (m.type) {
8463
+ case 'characterData': {
8464
+ const value = m.target.textContent;
8465
+ if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) &&
8466
+ value !== m.oldValue) {
8467
+ this.texts.push({
8468
+ value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector) && value
8469
+ ? this.maskTextFn
8470
+ ? this.maskTextFn(value)
8471
+ : value.replace(/[\S]/g, '*')
8472
+ : value,
8473
+ node: m.target,
8474
+ });
8475
+ }
8476
+ break;
8477
+ }
8478
+ case 'attributes': {
8479
+ const target = m.target;
8480
+ let value = m.target.getAttribute(m.attributeName);
8481
+ if (m.attributeName === 'value') {
8482
+ value = maskInputValue({
8483
+ maskInputOptions: this.maskInputOptions,
8484
+ tagName: m.target.tagName,
8485
+ type: m.target.getAttribute('type'),
8486
+ value,
8487
+ maskInputFn: this.maskInputFn,
8488
+ });
8489
+ }
8490
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
8491
+ value === m.oldValue) {
8492
+ return;
8493
+ }
8494
+ let item = this.attributes.find((a) => a.node === m.target);
8495
+ if (target.tagName === 'IFRAME' &&
8496
+ m.attributeName === 'src' &&
8497
+ !this.keepIframeSrcFn(value)) {
8498
+ if (!target.contentDocument) {
8499
+ m.attributeName = 'rr_src';
8500
+ }
8501
+ else {
8502
+ return;
8503
+ }
8504
+ }
8505
+ if (!item) {
8506
+ item = {
8507
+ node: m.target,
8508
+ attributes: {},
8509
+ };
8510
+ this.attributes.push(item);
8511
+ }
8512
+ if (m.attributeName === 'style') {
8513
+ const old = this.doc.createElement('span');
8514
+ if (m.oldValue) {
8515
+ old.setAttribute('style', m.oldValue);
8516
+ }
8517
+ if (item.attributes.style === undefined ||
8518
+ item.attributes.style === null) {
8519
+ item.attributes.style = {};
8520
+ }
8521
+ const styleObj = item.attributes.style;
8522
+ for (const pname of Array.from(target.style)) {
8523
+ const newValue = target.style.getPropertyValue(pname);
8524
+ const newPriority = target.style.getPropertyPriority(pname);
8525
+ if (newValue !== old.style.getPropertyValue(pname) ||
8526
+ newPriority !== old.style.getPropertyPriority(pname)) {
8527
+ if (newPriority === '') {
8528
+ styleObj[pname] = newValue;
8529
+ }
8530
+ else {
8531
+ styleObj[pname] = [newValue, newPriority];
8532
+ }
8533
+ }
8534
+ }
8535
+ for (const pname of Array.from(old.style)) {
8536
+ if (target.style.getPropertyValue(pname) === '') {
8537
+ styleObj[pname] = false;
8538
+ }
8539
+ }
8540
+ }
8541
+ else {
8542
+ item.attributes[m.attributeName] = transformAttribute(this.doc, target.tagName, m.attributeName, value);
8543
+ }
8544
+ break;
8545
+ }
8546
+ case 'childList': {
8547
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, true))
8548
+ return;
8549
+ m.addedNodes.forEach((n) => this.genAdds(n, m.target));
8550
+ m.removedNodes.forEach((n) => {
8551
+ const nodeId = this.mirror.getId(n);
8552
+ const parentId = isShadowRoot(m.target)
8553
+ ? this.mirror.getId(m.target.host)
8554
+ : this.mirror.getId(m.target);
8555
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
8556
+ isIgnored(n, this.mirror) ||
8557
+ !isSerialized(n, this.mirror)) {
8558
+ return;
8559
+ }
8560
+ if (this.addedSet.has(n)) {
8561
+ deepDelete(this.addedSet, n);
8562
+ this.droppedSet.add(n);
8563
+ }
8564
+ else if (this.addedSet.has(m.target) && nodeId === -1) ;
8565
+ else if (isAncestorRemoved(m.target, this.mirror)) ;
8566
+ else if (this.movedSet.has(n) &&
8567
+ this.movedMap[moveKey(nodeId, parentId)]) {
8568
+ deepDelete(this.movedSet, n);
8569
+ }
8570
+ else {
8571
+ this.removes.push({
8572
+ parentId,
8573
+ id: nodeId,
8574
+ isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)
8575
+ ? true
8576
+ : undefined,
8577
+ });
8578
+ }
8579
+ this.mapRemoves.push(n);
8580
+ });
8581
+ break;
8582
+ }
8583
+ }
8584
+ };
8585
+ this.genAdds = (n, target) => {
8586
+ if (this.mirror.hasNode(n)) {
8587
+ if (isIgnored(n, this.mirror)) {
8588
+ return;
8589
+ }
8590
+ this.movedSet.add(n);
8591
+ let targetId = null;
8592
+ if (target && this.mirror.hasNode(target)) {
8593
+ targetId = this.mirror.getId(target);
8594
+ }
8595
+ if (targetId && targetId !== -1) {
8596
+ this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
8597
+ }
8598
+ }
8599
+ else {
8600
+ this.addedSet.add(n);
8601
+ this.droppedSet.delete(n);
8602
+ }
8603
+ if (!isBlocked(n, this.blockClass, this.blockSelector, false))
8604
+ n.childNodes.forEach((childN) => this.genAdds(childN));
8605
+ };
8606
+ }
8607
+ init(options) {
8608
+ [
8609
+ 'mutationCb',
8610
+ 'blockClass',
8611
+ 'blockSelector',
8612
+ 'maskTextClass',
8613
+ 'maskTextSelector',
8614
+ 'inlineStylesheet',
8615
+ 'maskInputOptions',
8616
+ 'maskTextFn',
8617
+ 'maskInputFn',
8618
+ 'keepIframeSrcFn',
8619
+ 'recordCanvas',
8620
+ 'inlineImages',
8621
+ 'slimDOMOptions',
8622
+ 'dataURLOptions',
8623
+ 'doc',
8624
+ 'mirror',
8625
+ 'iframeManager',
8626
+ 'stylesheetManager',
8627
+ 'shadowDomManager',
8628
+ 'canvasManager',
8629
+ ].forEach((key) => {
8630
+ this[key] = options[key];
8631
+ });
8632
+ }
8633
+ freeze() {
8634
+ this.frozen = true;
8635
+ this.canvasManager.freeze();
8636
+ }
8637
+ unfreeze() {
8638
+ this.frozen = false;
8639
+ this.canvasManager.unfreeze();
8640
+ this.emit();
8641
+ }
8642
+ isFrozen() {
8643
+ return this.frozen;
8644
+ }
8645
+ lock() {
8646
+ this.locked = true;
8647
+ this.canvasManager.lock();
8648
+ }
8649
+ unlock() {
8650
+ this.locked = false;
8651
+ this.canvasManager.unlock();
8652
+ this.emit();
8653
+ }
8654
+ reset() {
8655
+ this.shadowDomManager.reset();
8656
+ this.canvasManager.reset();
8657
+ }
8658
+ }
8659
+ function deepDelete(addsSet, n) {
8660
+ addsSet.delete(n);
8661
+ n.childNodes.forEach((childN) => deepDelete(addsSet, childN));
8662
+ }
8663
+ function isParentRemoved(removes, n, mirror) {
8664
+ if (removes.length === 0)
8665
+ return false;
8666
+ return _isParentRemoved(removes, n, mirror);
8667
+ }
8668
+ function _isParentRemoved(removes, n, mirror) {
8669
+ const { parentNode } = n;
8670
+ if (!parentNode) {
8671
+ return false;
8672
+ }
8673
+ const parentId = mirror.getId(parentNode);
8674
+ if (removes.some((r) => r.id === parentId)) {
8675
+ return true;
8676
+ }
8677
+ return _isParentRemoved(removes, parentNode, mirror);
8678
+ }
8679
+ function isAncestorInSet(set, n) {
8680
+ if (set.size === 0)
8681
+ return false;
8682
+ return _isAncestorInSet(set, n);
8683
+ }
8684
+ function _isAncestorInSet(set, n) {
8685
+ const { parentNode } = n;
8686
+ if (!parentNode) {
8687
+ return false;
8688
+ }
8689
+ if (set.has(parentNode)) {
8690
+ return true;
8691
+ }
8692
+ return _isAncestorInSet(set, parentNode);
8693
+ }
8694
+
8695
+ const mutationBuffers = [];
8696
+ const isCSSGroupingRuleSupported = typeof CSSGroupingRule !== 'undefined';
8697
+ const isCSSMediaRuleSupported = typeof CSSMediaRule !== 'undefined';
8698
+ const isCSSSupportsRuleSupported = typeof CSSSupportsRule !== 'undefined';
8699
+ const isCSSConditionRuleSupported = typeof CSSConditionRule !== 'undefined';
8700
+ function getEventTarget(event) {
8701
+ try {
8702
+ if ('composedPath' in event) {
8703
+ const path = event.composedPath();
8704
+ if (path.length) {
8705
+ return path[0];
8706
+ }
8707
+ }
8708
+ else if ('path' in event && event.path.length) {
8709
+ return event.path[0];
8710
+ }
8711
+ return event.target;
8712
+ }
8713
+ catch (_a) {
8714
+ return event.target;
8715
+ }
8716
+ }
8717
+ function initMutationObserver(options, rootEl) {
8718
+ var _a, _b;
8719
+ const mutationBuffer = new MutationBuffer();
8720
+ mutationBuffers.push(mutationBuffer);
8721
+ mutationBuffer.init(options);
8722
+ let mutationObserverCtor = window.MutationObserver ||
8723
+ window.__rrMutationObserver;
8724
+ 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');
8725
+ if (angularZoneSymbol &&
8726
+ window[angularZoneSymbol]) {
8727
+ mutationObserverCtor = window[angularZoneSymbol];
8728
+ }
8729
+ const observer = new mutationObserverCtor(mutationBuffer.processMutations.bind(mutationBuffer));
8730
+ observer.observe(rootEl, {
8731
+ attributes: true,
8732
+ attributeOldValue: true,
8733
+ characterData: true,
8734
+ characterDataOldValue: true,
8735
+ childList: true,
8736
+ subtree: true,
8737
+ });
8738
+ return observer;
8739
+ }
8740
+ function initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {
8741
+ if (sampling.mousemove === false) {
8742
+ return () => {
8743
+ };
8744
+ }
8745
+ const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;
8746
+ const callbackThreshold = typeof sampling.mousemoveCallback === 'number'
8747
+ ? sampling.mousemoveCallback
8748
+ : 500;
8749
+ let positions = [];
8750
+ let timeBaseline;
8751
+ const wrappedCb = throttle((source) => {
8752
+ const totalOffset = Date.now() - timeBaseline;
8753
+ mousemoveCb(positions.map((p) => {
8754
+ p.timeOffset -= totalOffset;
8755
+ return p;
8756
+ }), source);
8757
+ positions = [];
8758
+ timeBaseline = null;
8759
+ }, callbackThreshold);
8760
+ const updatePosition = throttle((evt) => {
8761
+ const target = getEventTarget(evt);
8762
+ const { clientX, clientY } = isTouchEvent(evt)
8763
+ ? evt.changedTouches[0]
8764
+ : evt;
8765
+ if (!timeBaseline) {
8766
+ timeBaseline = Date.now();
8767
+ }
8768
+ positions.push({
8769
+ x: clientX,
8770
+ y: clientY,
8771
+ id: mirror.getId(target),
8772
+ timeOffset: Date.now() - timeBaseline,
8773
+ });
8774
+ wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent
8775
+ ? IncrementalSource.Drag
8776
+ : evt instanceof MouseEvent
8777
+ ? IncrementalSource.MouseMove
8778
+ : IncrementalSource.TouchMove);
8779
+ }, threshold, {
8780
+ trailing: false,
8781
+ });
8782
+ const handlers = [
8783
+ on('mousemove', updatePosition, doc),
8784
+ on('touchmove', updatePosition, doc),
8785
+ on('drag', updatePosition, doc),
8786
+ ];
8787
+ return () => {
8788
+ handlers.forEach((h) => h());
8789
+ };
8790
+ }
8791
+ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, sampling, }) {
8792
+ if (sampling.mouseInteraction === false) {
8793
+ return () => {
8794
+ };
8795
+ }
8796
+ const disableMap = sampling.mouseInteraction === true ||
8797
+ sampling.mouseInteraction === undefined
8798
+ ? {}
8799
+ : sampling.mouseInteraction;
8800
+ const handlers = [];
8801
+ const getHandler = (eventKey) => {
8802
+ return (event) => {
8803
+ const target = getEventTarget(event);
8804
+ if (isBlocked(target, blockClass, blockSelector, true)) {
8805
+ return;
8806
+ }
8807
+ const e = isTouchEvent(event) ? event.changedTouches[0] : event;
8808
+ if (!e) {
8809
+ return;
8810
+ }
8811
+ const id = mirror.getId(target);
8812
+ const { clientX, clientY } = e;
8813
+ mouseInteractionCb({
8814
+ type: MouseInteractions[eventKey],
8815
+ id,
8816
+ x: clientX,
8817
+ y: clientY,
8818
+ });
8819
+ };
8820
+ };
8821
+ Object.keys(MouseInteractions)
8822
+ .filter((key) => Number.isNaN(Number(key)) &&
8823
+ !key.endsWith('_Departed') &&
8824
+ disableMap[key] !== false)
8825
+ .forEach((eventKey) => {
8826
+ const eventName = eventKey.toLowerCase();
8827
+ const handler = getHandler(eventKey);
8828
+ handlers.push(on(eventName, handler, doc));
8829
+ });
8830
+ return () => {
8831
+ handlers.forEach((h) => h());
8832
+ };
8833
+ }
8834
+ function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, sampling, }) {
8835
+ const updatePosition = throttle((evt) => {
8836
+ const target = getEventTarget(evt);
8837
+ if (!target || isBlocked(target, blockClass, blockSelector, true)) {
8838
+ return;
8839
+ }
8840
+ const id = mirror.getId(target);
8841
+ if (target === doc) {
8842
+ const scrollEl = (doc.scrollingElement || doc.documentElement);
8843
+ scrollCb({
8844
+ id,
8845
+ x: scrollEl.scrollLeft,
8846
+ y: scrollEl.scrollTop,
8847
+ });
8848
+ }
8849
+ else {
8850
+ scrollCb({
8851
+ id,
8852
+ x: target.scrollLeft,
8853
+ y: target.scrollTop,
8854
+ });
8855
+ }
8856
+ }, sampling.scroll || 100);
8857
+ return on('scroll', updatePosition, doc);
8858
+ }
8859
+ function initViewportResizeObserver({ viewportResizeCb, }) {
8860
+ let lastH = -1;
8861
+ let lastW = -1;
8862
+ const updateDimension = throttle(() => {
8863
+ const height = getWindowHeight();
8864
+ const width = getWindowWidth();
8865
+ if (lastH !== height || lastW !== width) {
8866
+ viewportResizeCb({
8867
+ width: Number(width),
8868
+ height: Number(height),
8869
+ });
8870
+ lastH = height;
8871
+ lastW = width;
8872
+ }
8873
+ }, 200);
8874
+ return on('resize', updateDimension, window);
8875
+ }
8876
+ function wrapEventWithUserTriggeredFlag(v, enable) {
8877
+ const value = Object.assign({}, v);
8878
+ if (!enable)
8879
+ delete value.userTriggered;
8880
+ return value;
8881
+ }
8882
+ const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
8883
+ const lastInputValueMap = new WeakMap();
8884
+ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ignoreClass, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {
8885
+ function eventHandler(event) {
8886
+ let target = getEventTarget(event);
8887
+ const userTriggered = event.isTrusted;
8888
+ if (target && target.tagName === 'OPTION')
8889
+ target = target.parentElement;
8890
+ if (!target ||
8891
+ !target.tagName ||
8892
+ INPUT_TAGS.indexOf(target.tagName) < 0 ||
8893
+ isBlocked(target, blockClass, blockSelector, true)) {
8894
+ return;
8895
+ }
8896
+ const type = target.type;
8897
+ if (target.classList.contains(ignoreClass)) {
8898
+ return;
8899
+ }
8900
+ let text = target.value;
8901
+ let isChecked = false;
8902
+ if (type === 'radio' || type === 'checkbox') {
8903
+ isChecked = target.checked;
8904
+ }
8905
+ else if (maskInputOptions[target.tagName.toLowerCase()] ||
8906
+ maskInputOptions[type]) {
8907
+ text = maskInputValue({
8908
+ maskInputOptions,
8909
+ tagName: target.tagName,
8910
+ type,
8911
+ value: text,
8912
+ maskInputFn,
8913
+ });
8914
+ }
8915
+ cbWithDedup(target, wrapEventWithUserTriggeredFlag({ text, isChecked, userTriggered }, userTriggeredOnInput));
8916
+ const name = target.name;
8917
+ if (type === 'radio' && name && isChecked) {
8918
+ doc
8919
+ .querySelectorAll(`input[type="radio"][name="${name}"]`)
8920
+ .forEach((el) => {
8921
+ if (el !== target) {
8922
+ cbWithDedup(el, wrapEventWithUserTriggeredFlag({
8923
+ text: el.value,
8924
+ isChecked: !isChecked,
8925
+ userTriggered: false,
8926
+ }, userTriggeredOnInput));
8927
+ }
8928
+ });
8929
+ }
8930
+ }
8931
+ function cbWithDedup(target, v) {
8932
+ const lastInputValue = lastInputValueMap.get(target);
8933
+ if (!lastInputValue ||
8934
+ lastInputValue.text !== v.text ||
8935
+ lastInputValue.isChecked !== v.isChecked) {
8936
+ lastInputValueMap.set(target, v);
8937
+ const id = mirror.getId(target);
8938
+ inputCb(Object.assign(Object.assign({}, v), { id }));
8939
+ }
8940
+ }
8941
+ const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
8942
+ const handlers = events.map((eventName) => on(eventName, eventHandler, doc));
8943
+ const currentWindow = doc.defaultView;
8944
+ if (!currentWindow) {
8945
+ return () => {
8946
+ handlers.forEach((h) => h());
8947
+ };
8948
+ }
8949
+ const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');
8950
+ const hookProperties = [
8951
+ [currentWindow.HTMLInputElement.prototype, 'value'],
8952
+ [currentWindow.HTMLInputElement.prototype, 'checked'],
8953
+ [currentWindow.HTMLSelectElement.prototype, 'value'],
8954
+ [currentWindow.HTMLTextAreaElement.prototype, 'value'],
8955
+ [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],
8956
+ [currentWindow.HTMLOptionElement.prototype, 'selected'],
8957
+ ];
8958
+ if (propertyDescriptor && propertyDescriptor.set) {
8959
+ handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {
8960
+ set() {
8961
+ eventHandler({ target: this });
8962
+ },
8963
+ }, false, currentWindow)));
8964
+ }
8965
+ return () => {
8966
+ handlers.forEach((h) => h());
8967
+ };
8968
+ }
8969
+ function getNestedCSSRulePositions(rule) {
8970
+ const positions = [];
8971
+ function recurse(childRule, pos) {
8972
+ if ((isCSSGroupingRuleSupported &&
8973
+ childRule.parentRule instanceof CSSGroupingRule) ||
8974
+ (isCSSMediaRuleSupported &&
8975
+ childRule.parentRule instanceof CSSMediaRule) ||
8976
+ (isCSSSupportsRuleSupported &&
8977
+ childRule.parentRule instanceof CSSSupportsRule) ||
8978
+ (isCSSConditionRuleSupported &&
8979
+ childRule.parentRule instanceof CSSConditionRule)) {
8980
+ const rules = Array.from(childRule.parentRule.cssRules);
8981
+ const index = rules.indexOf(childRule);
8982
+ pos.unshift(index);
8983
+ }
8984
+ else if (childRule.parentStyleSheet) {
8985
+ const rules = Array.from(childRule.parentStyleSheet.cssRules);
8986
+ const index = rules.indexOf(childRule);
8987
+ pos.unshift(index);
8988
+ }
8989
+ return pos;
8990
+ }
8991
+ return recurse(rule, positions);
8992
+ }
8993
+ function getIdAndStyleId(sheet, mirror, styleMirror) {
8994
+ let id, styleId;
8995
+ if (!sheet)
8996
+ return {};
8997
+ if (sheet.ownerNode)
8998
+ id = mirror.getId(sheet.ownerNode);
8999
+ else
9000
+ styleId = styleMirror.getId(sheet);
9001
+ return {
9002
+ styleId,
9003
+ id,
9004
+ };
9005
+ }
9006
+ function initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {
9007
+ const insertRule = win.CSSStyleSheet.prototype.insertRule;
9008
+ win.CSSStyleSheet.prototype.insertRule = function (rule, index) {
9009
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
9010
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9011
+ styleSheetRuleCb({
9012
+ id,
9013
+ styleId,
9014
+ adds: [{ rule, index }],
9015
+ });
9016
+ }
9017
+ return insertRule.apply(this, [rule, index]);
9018
+ };
9019
+ const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
9020
+ win.CSSStyleSheet.prototype.deleteRule = function (index) {
9021
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
9022
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9023
+ styleSheetRuleCb({
9024
+ id,
9025
+ styleId,
9026
+ removes: [{ index }],
9027
+ });
9028
+ }
9029
+ return deleteRule.apply(this, [index]);
9030
+ };
9031
+ let replace;
9032
+ if (win.CSSStyleSheet.prototype.replace) {
9033
+ replace = win.CSSStyleSheet.prototype.replace;
9034
+ win.CSSStyleSheet.prototype.replace = function (text) {
9035
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
9036
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9037
+ styleSheetRuleCb({
9038
+ id,
9039
+ styleId,
9040
+ replace: text,
9041
+ });
9042
+ }
9043
+ return replace.apply(this, [text]);
9044
+ };
9045
+ }
9046
+ let replaceSync;
9047
+ if (win.CSSStyleSheet.prototype.replaceSync) {
9048
+ replaceSync = win.CSSStyleSheet.prototype.replaceSync;
9049
+ win.CSSStyleSheet.prototype.replaceSync = function (text) {
9050
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
9051
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9052
+ styleSheetRuleCb({
9053
+ id,
9054
+ styleId,
9055
+ replaceSync: text,
9056
+ });
9057
+ }
9058
+ return replaceSync.apply(this, [text]);
9059
+ };
9060
+ }
9061
+ const supportedNestedCSSRuleTypes = {};
9062
+ if (isCSSGroupingRuleSupported) {
9063
+ supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
9064
+ }
9065
+ else {
9066
+ if (isCSSMediaRuleSupported) {
9067
+ supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
9068
+ }
9069
+ if (isCSSConditionRuleSupported) {
9070
+ supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
9071
+ }
9072
+ if (isCSSSupportsRuleSupported) {
9073
+ supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
9074
+ }
9075
+ }
9076
+ const unmodifiedFunctions = {};
9077
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
9078
+ unmodifiedFunctions[typeKey] = {
9079
+ insertRule: type.prototype.insertRule,
9080
+ deleteRule: type.prototype.deleteRule,
9081
+ };
9082
+ type.prototype.insertRule = function (rule, index) {
9083
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
9084
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9085
+ styleSheetRuleCb({
9086
+ id,
9087
+ styleId,
9088
+ adds: [
9089
+ {
9090
+ rule,
9091
+ index: [
9092
+ ...getNestedCSSRulePositions(this),
9093
+ index || 0,
9094
+ ],
9095
+ },
9096
+ ],
9097
+ });
9098
+ }
9099
+ return unmodifiedFunctions[typeKey].insertRule.apply(this, [rule, index]);
9100
+ };
9101
+ type.prototype.deleteRule = function (index) {
9102
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
9103
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9104
+ styleSheetRuleCb({
9105
+ id,
9106
+ styleId,
9107
+ removes: [
9108
+ { index: [...getNestedCSSRulePositions(this), index] },
9109
+ ],
9110
+ });
9111
+ }
9112
+ return unmodifiedFunctions[typeKey].deleteRule.apply(this, [index]);
9113
+ };
9114
+ });
9115
+ return () => {
9116
+ win.CSSStyleSheet.prototype.insertRule = insertRule;
9117
+ win.CSSStyleSheet.prototype.deleteRule = deleteRule;
9118
+ replace && (win.CSSStyleSheet.prototype.replace = replace);
9119
+ replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
9120
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
9121
+ type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
9122
+ type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
9123
+ });
9124
+ };
9125
+ }
9126
+ function initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {
9127
+ var _a, _b, _c;
9128
+ let hostId = null;
9129
+ if (host.nodeName === '#document')
9130
+ hostId = mirror.getId(host);
9131
+ else
9132
+ hostId = mirror.getId(host.host);
9133
+ const patchTarget = host.nodeName === '#document'
9134
+ ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document
9135
+ : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;
9136
+ const originalPropertyDescriptor = Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets');
9137
+ if (hostId === null ||
9138
+ hostId === -1 ||
9139
+ !patchTarget ||
9140
+ !originalPropertyDescriptor)
9141
+ return () => {
9142
+ };
9143
+ Object.defineProperty(host, 'adoptedStyleSheets', {
9144
+ configurable: originalPropertyDescriptor.configurable,
9145
+ enumerable: originalPropertyDescriptor.enumerable,
9146
+ get() {
9147
+ var _a;
9148
+ return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);
9149
+ },
9150
+ set(sheets) {
9151
+ var _a;
9152
+ const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);
9153
+ if (hostId !== null && hostId !== -1) {
9154
+ try {
9155
+ stylesheetManager.adoptStyleSheets(sheets, hostId);
9156
+ }
9157
+ catch (e) {
9158
+ }
9159
+ }
9160
+ return result;
9161
+ },
9162
+ });
9163
+ return () => {
9164
+ Object.defineProperty(host, 'adoptedStyleSheets', {
9165
+ configurable: originalPropertyDescriptor.configurable,
9166
+ enumerable: originalPropertyDescriptor.enumerable,
9167
+ get: originalPropertyDescriptor.get,
9168
+ set: originalPropertyDescriptor.set,
9169
+ });
9170
+ };
9171
+ }
9172
+ function initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {
9173
+ const setProperty = win.CSSStyleDeclaration.prototype.setProperty;
9174
+ win.CSSStyleDeclaration.prototype.setProperty = function (property, value, priority) {
9175
+ var _a;
9176
+ if (ignoreCSSAttributes.has(property)) {
9177
+ return setProperty.apply(this, [property, value, priority]);
9178
+ }
9179
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
9180
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9181
+ styleDeclarationCb({
9182
+ id,
9183
+ styleId,
9184
+ set: {
9185
+ property,
9186
+ value,
9187
+ priority,
9188
+ },
9189
+ index: getNestedCSSRulePositions(this.parentRule),
9190
+ });
9191
+ }
9192
+ return setProperty.apply(this, [property, value, priority]);
9193
+ };
9194
+ const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
9195
+ win.CSSStyleDeclaration.prototype.removeProperty = function (property) {
9196
+ var _a;
9197
+ if (ignoreCSSAttributes.has(property)) {
9198
+ return removeProperty.apply(this, [property]);
9199
+ }
9200
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
9201
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
9202
+ styleDeclarationCb({
9203
+ id,
9204
+ styleId,
9205
+ remove: {
9206
+ property,
9207
+ },
9208
+ index: getNestedCSSRulePositions(this.parentRule),
9209
+ });
9210
+ }
9211
+ return removeProperty.apply(this, [property]);
9212
+ };
9213
+ return () => {
9214
+ win.CSSStyleDeclaration.prototype.setProperty = setProperty;
9215
+ win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
9216
+ };
9217
+ }
9218
+ function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, mirror, sampling, }) {
9219
+ const handler = (type) => throttle((event) => {
9220
+ const target = getEventTarget(event);
9221
+ if (!target ||
9222
+ isBlocked(target, blockClass, blockSelector, true)) {
9223
+ return;
9224
+ }
9225
+ const { currentTime, volume, muted, playbackRate, } = target;
9226
+ mediaInteractionCb({
9227
+ type,
9228
+ id: mirror.getId(target),
9229
+ currentTime,
9230
+ volume,
9231
+ muted,
9232
+ playbackRate,
9233
+ });
9234
+ }, sampling.media || 500);
9235
+ const handlers = [
9236
+ on('play', handler(0)),
9237
+ on('pause', handler(1)),
9238
+ on('seeked', handler(2)),
9239
+ on('volumechange', handler(3)),
9240
+ on('ratechange', handler(4)),
9241
+ ];
9242
+ return () => {
9243
+ handlers.forEach((h) => h());
9244
+ };
9245
+ }
9246
+ function initFontObserver({ fontCb, doc }) {
9247
+ const win = doc.defaultView;
9248
+ if (!win) {
9249
+ return () => {
9250
+ };
9251
+ }
9252
+ const handlers = [];
9253
+ const fontMap = new WeakMap();
9254
+ const originalFontFace = win.FontFace;
9255
+ win.FontFace = function FontFace(family, source, descriptors) {
9256
+ const fontFace = new originalFontFace(family, source, descriptors);
9257
+ fontMap.set(fontFace, {
9258
+ family,
9259
+ buffer: typeof source !== 'string',
9260
+ descriptors,
9261
+ fontSource: typeof source === 'string'
9262
+ ? source
9263
+ : JSON.stringify(Array.from(new Uint8Array(source))),
9264
+ });
9265
+ return fontFace;
9266
+ };
9267
+ const restoreHandler = patch(doc.fonts, 'add', function (original) {
9268
+ return function (fontFace) {
9269
+ setTimeout(() => {
9270
+ const p = fontMap.get(fontFace);
9271
+ if (p) {
9272
+ fontCb(p);
9273
+ fontMap.delete(fontFace);
9274
+ }
9275
+ }, 0);
9276
+ return original.apply(this, [fontFace]);
9277
+ };
9278
+ });
9279
+ handlers.push(() => {
9280
+ win.FontFace = originalFontFace;
9281
+ });
9282
+ handlers.push(restoreHandler);
9283
+ return () => {
9284
+ handlers.forEach((h) => h());
9285
+ };
9286
+ }
9287
+ function initSelectionObserver(param) {
9288
+ const { doc, mirror, blockClass, blockSelector, selectionCb } = param;
9289
+ let collapsed = true;
9290
+ const updateSelection = () => {
9291
+ const selection = doc.getSelection();
9292
+ if (!selection || (collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)))
9293
+ return;
9294
+ collapsed = selection.isCollapsed || false;
9295
+ const ranges = [];
9296
+ const count = selection.rangeCount || 0;
9297
+ for (let i = 0; i < count; i++) {
9298
+ const range = selection.getRangeAt(i);
9299
+ const { startContainer, startOffset, endContainer, endOffset } = range;
9300
+ const blocked = isBlocked(startContainer, blockClass, blockSelector, true) ||
9301
+ isBlocked(endContainer, blockClass, blockSelector, true);
9302
+ if (blocked)
9303
+ continue;
9304
+ ranges.push({
9305
+ start: mirror.getId(startContainer),
9306
+ startOffset,
9307
+ end: mirror.getId(endContainer),
9308
+ endOffset,
9309
+ });
9310
+ }
9311
+ selectionCb({ ranges });
9312
+ };
9313
+ updateSelection();
9314
+ return on('selectionchange', updateSelection);
9315
+ }
9316
+ function mergeHooks(o, hooks) {
9317
+ const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, } = o;
9318
+ o.mutationCb = (...p) => {
9319
+ if (hooks.mutation) {
9320
+ hooks.mutation(...p);
9321
+ }
9322
+ mutationCb(...p);
9323
+ };
9324
+ o.mousemoveCb = (...p) => {
9325
+ if (hooks.mousemove) {
9326
+ hooks.mousemove(...p);
9327
+ }
9328
+ mousemoveCb(...p);
9329
+ };
9330
+ o.mouseInteractionCb = (...p) => {
9331
+ if (hooks.mouseInteraction) {
9332
+ hooks.mouseInteraction(...p);
9333
+ }
9334
+ mouseInteractionCb(...p);
9335
+ };
9336
+ o.scrollCb = (...p) => {
9337
+ if (hooks.scroll) {
9338
+ hooks.scroll(...p);
9339
+ }
9340
+ scrollCb(...p);
9341
+ };
9342
+ o.viewportResizeCb = (...p) => {
9343
+ if (hooks.viewportResize) {
9344
+ hooks.viewportResize(...p);
9345
+ }
9346
+ viewportResizeCb(...p);
9347
+ };
9348
+ o.inputCb = (...p) => {
9349
+ if (hooks.input) {
9350
+ hooks.input(...p);
9351
+ }
9352
+ inputCb(...p);
9353
+ };
9354
+ o.mediaInteractionCb = (...p) => {
9355
+ if (hooks.mediaInteaction) {
9356
+ hooks.mediaInteaction(...p);
9357
+ }
9358
+ mediaInteractionCb(...p);
9359
+ };
9360
+ o.styleSheetRuleCb = (...p) => {
9361
+ if (hooks.styleSheetRule) {
9362
+ hooks.styleSheetRule(...p);
9363
+ }
9364
+ styleSheetRuleCb(...p);
9365
+ };
9366
+ o.styleDeclarationCb = (...p) => {
9367
+ if (hooks.styleDeclaration) {
9368
+ hooks.styleDeclaration(...p);
9369
+ }
9370
+ styleDeclarationCb(...p);
9371
+ };
9372
+ o.canvasMutationCb = (...p) => {
9373
+ if (hooks.canvasMutation) {
9374
+ hooks.canvasMutation(...p);
9375
+ }
9376
+ canvasMutationCb(...p);
9377
+ };
9378
+ o.fontCb = (...p) => {
9379
+ if (hooks.font) {
9380
+ hooks.font(...p);
9381
+ }
9382
+ fontCb(...p);
9383
+ };
9384
+ o.selectionCb = (...p) => {
9385
+ if (hooks.selection) {
9386
+ hooks.selection(...p);
9387
+ }
9388
+ selectionCb(...p);
9389
+ };
9390
+ }
9391
+ function initObservers(o, hooks = {}) {
9392
+ const currentWindow = o.doc.defaultView;
9393
+ if (!currentWindow) {
9394
+ return () => {
9395
+ };
9396
+ }
9397
+ mergeHooks(o, hooks);
9398
+ const mutationObserver = initMutationObserver(o, o.doc);
9399
+ const mousemoveHandler = initMoveObserver(o);
9400
+ const mouseInteractionHandler = initMouseInteractionObserver(o);
9401
+ const scrollHandler = initScrollObserver(o);
9402
+ const viewportResizeHandler = initViewportResizeObserver(o);
9403
+ const inputHandler = initInputObserver(o);
9404
+ const mediaInteractionHandler = initMediaInteractionObserver(o);
9405
+ const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });
9406
+ const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);
9407
+ const styleDeclarationObserver = initStyleDeclarationObserver(o, {
9408
+ win: currentWindow,
9409
+ });
9410
+ const fontObserver = o.collectFonts
9411
+ ? initFontObserver(o)
9412
+ : () => {
9413
+ };
9414
+ const selectionObserver = initSelectionObserver(o);
9415
+ const pluginHandlers = [];
9416
+ for (const plugin of o.plugins) {
9417
+ pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
9418
+ }
9419
+ return () => {
9420
+ mutationBuffers.forEach((b) => b.reset());
9421
+ mutationObserver.disconnect();
9422
+ mousemoveHandler();
9423
+ mouseInteractionHandler();
9424
+ scrollHandler();
9425
+ viewportResizeHandler();
9426
+ inputHandler();
9427
+ mediaInteractionHandler();
9428
+ styleSheetObserver();
9429
+ adoptedStyleSheetObserver();
9430
+ styleDeclarationObserver();
9431
+ fontObserver();
9432
+ selectionObserver();
9433
+ pluginHandlers.forEach((h) => h());
9434
+ };
9435
+ }
9436
+
9437
+ class CrossOriginIframeMirror {
9438
+ constructor(generateIdFn) {
9439
+ this.generateIdFn = generateIdFn;
9440
+ this.iframeIdToRemoteIdMap = new WeakMap();
9441
+ this.iframeRemoteIdToIdMap = new WeakMap();
9442
+ }
9443
+ getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
9444
+ const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
9445
+ const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
9446
+ let id = idToRemoteIdMap.get(remoteId);
9447
+ if (!id) {
9448
+ id = this.generateIdFn();
9449
+ idToRemoteIdMap.set(remoteId, id);
9450
+ remoteIdToIdMap.set(id, remoteId);
9451
+ }
9452
+ return id;
9453
+ }
9454
+ getIds(iframe, remoteId) {
9455
+ const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
9456
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
9457
+ return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));
9458
+ }
9459
+ getRemoteId(iframe, id, map) {
9460
+ const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
9461
+ if (typeof id !== 'number')
9462
+ return id;
9463
+ const remoteId = remoteIdToIdMap.get(id);
9464
+ if (!remoteId)
9465
+ return -1;
9466
+ return remoteId;
9467
+ }
9468
+ getRemoteIds(iframe, ids) {
9469
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
9470
+ return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));
9471
+ }
9472
+ reset(iframe) {
9473
+ if (!iframe) {
9474
+ this.iframeIdToRemoteIdMap = new WeakMap();
9475
+ this.iframeRemoteIdToIdMap = new WeakMap();
9476
+ return;
9477
+ }
9478
+ this.iframeIdToRemoteIdMap.delete(iframe);
9479
+ this.iframeRemoteIdToIdMap.delete(iframe);
9480
+ }
9481
+ getIdToRemoteIdMap(iframe) {
9482
+ let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
9483
+ if (!idToRemoteIdMap) {
9484
+ idToRemoteIdMap = new Map();
9485
+ this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
9486
+ }
9487
+ return idToRemoteIdMap;
9488
+ }
9489
+ getRemoteIdToIdMap(iframe) {
9490
+ let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
9491
+ if (!remoteIdToIdMap) {
9492
+ remoteIdToIdMap = new Map();
9493
+ this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
9494
+ }
9495
+ return remoteIdToIdMap;
9496
+ }
9497
+ }
9498
+
9499
+ class IframeManager {
9500
+ constructor(options) {
9501
+ this.iframes = new WeakMap();
9502
+ this.crossOriginIframeMap = new WeakMap();
9503
+ this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
9504
+ this.mutationCb = options.mutationCb;
9505
+ this.wrappedEmit = options.wrappedEmit;
9506
+ this.stylesheetManager = options.stylesheetManager;
9507
+ this.recordCrossOriginIframes = options.recordCrossOriginIframes;
9508
+ this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
9509
+ this.mirror = options.mirror;
9510
+ if (this.recordCrossOriginIframes) {
9511
+ window.addEventListener('message', this.handleMessage.bind(this));
9512
+ }
9513
+ }
9514
+ addIframe(iframeEl) {
9515
+ this.iframes.set(iframeEl, true);
9516
+ if (iframeEl.contentWindow)
9517
+ this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
9518
+ }
9519
+ addLoadListener(cb) {
9520
+ this.loadListener = cb;
9521
+ }
9522
+ attachIframe(iframeEl, childSn) {
9523
+ var _a;
9524
+ this.mutationCb({
9525
+ adds: [
9526
+ {
9527
+ parentId: this.mirror.getId(iframeEl),
9528
+ nextId: null,
9529
+ node: childSn,
9530
+ },
9531
+ ],
9532
+ removes: [],
9533
+ texts: [],
9534
+ attributes: [],
9535
+ isAttachIframe: true,
9536
+ });
9537
+ (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);
9538
+ if (iframeEl.contentDocument &&
9539
+ iframeEl.contentDocument.adoptedStyleSheets &&
9540
+ iframeEl.contentDocument.adoptedStyleSheets.length > 0)
9541
+ this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
9542
+ }
9543
+ handleMessage(message) {
9544
+ if (message.data.type === 'rrweb') {
9545
+ const iframeSourceWindow = message.source;
9546
+ if (!iframeSourceWindow)
9547
+ return;
9548
+ const iframeEl = this.crossOriginIframeMap.get(message.source);
9549
+ if (!iframeEl)
9550
+ return;
9551
+ const transformedEvent = this.transformCrossOriginEvent(iframeEl, message.data.event);
9552
+ if (transformedEvent)
9553
+ this.wrappedEmit(transformedEvent, message.data.isCheckout);
9554
+ }
9555
+ }
9556
+ transformCrossOriginEvent(iframeEl, e) {
9557
+ var _a;
9558
+ switch (e.type) {
9559
+ case EventType.FullSnapshot: {
9560
+ this.crossOriginIframeMirror.reset(iframeEl);
9561
+ this.crossOriginIframeStyleMirror.reset(iframeEl);
9562
+ this.replaceIdOnNode(e.data.node, iframeEl);
9563
+ return {
9564
+ timestamp: e.timestamp,
9565
+ type: EventType.IncrementalSnapshot,
9566
+ data: {
9567
+ source: IncrementalSource.Mutation,
9568
+ adds: [
9569
+ {
9570
+ parentId: this.mirror.getId(iframeEl),
9571
+ nextId: null,
9572
+ node: e.data.node,
9573
+ },
9574
+ ],
9575
+ removes: [],
9576
+ texts: [],
9577
+ attributes: [],
9578
+ isAttachIframe: true,
9579
+ },
9580
+ };
9581
+ }
9582
+ case EventType.Meta:
9583
+ case EventType.Load:
9584
+ case EventType.DomContentLoaded: {
9585
+ return false;
9586
+ }
9587
+ case EventType.Plugin: {
9588
+ return e;
9589
+ }
9590
+ case EventType.Custom: {
9591
+ this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);
9592
+ return e;
9593
+ }
9594
+ case EventType.IncrementalSnapshot: {
9595
+ switch (e.data.source) {
9596
+ case IncrementalSource.Mutation: {
9597
+ e.data.adds.forEach((n) => {
9598
+ this.replaceIds(n, iframeEl, [
9599
+ 'parentId',
9600
+ 'nextId',
9601
+ 'previousId',
9602
+ ]);
9603
+ this.replaceIdOnNode(n.node, iframeEl);
9604
+ });
9605
+ e.data.removes.forEach((n) => {
9606
+ this.replaceIds(n, iframeEl, ['parentId', 'id']);
9607
+ });
9608
+ e.data.attributes.forEach((n) => {
9609
+ this.replaceIds(n, iframeEl, ['id']);
9610
+ });
9611
+ e.data.texts.forEach((n) => {
9612
+ this.replaceIds(n, iframeEl, ['id']);
9613
+ });
9614
+ return e;
9615
+ }
9616
+ case IncrementalSource.Drag:
9617
+ case IncrementalSource.TouchMove:
9618
+ case IncrementalSource.MouseMove: {
9619
+ e.data.positions.forEach((p) => {
9620
+ this.replaceIds(p, iframeEl, ['id']);
9621
+ });
9622
+ return e;
9623
+ }
9624
+ case IncrementalSource.ViewportResize: {
9625
+ return false;
9626
+ }
9627
+ case IncrementalSource.MediaInteraction:
9628
+ case IncrementalSource.MouseInteraction:
9629
+ case IncrementalSource.Scroll:
9630
+ case IncrementalSource.CanvasMutation:
9631
+ case IncrementalSource.Input: {
9632
+ this.replaceIds(e.data, iframeEl, ['id']);
9633
+ return e;
9634
+ }
9635
+ case IncrementalSource.StyleSheetRule:
9636
+ case IncrementalSource.StyleDeclaration: {
9637
+ this.replaceIds(e.data, iframeEl, ['id']);
9638
+ this.replaceStyleIds(e.data, iframeEl, ['styleId']);
9639
+ return e;
9640
+ }
9641
+ case IncrementalSource.Font: {
9642
+ return e;
9643
+ }
9644
+ case IncrementalSource.Selection: {
9645
+ e.data.ranges.forEach((range) => {
9646
+ this.replaceIds(range, iframeEl, ['start', 'end']);
9647
+ });
9648
+ return e;
9649
+ }
9650
+ case IncrementalSource.AdoptedStyleSheet: {
9651
+ this.replaceIds(e.data, iframeEl, ['id']);
9652
+ this.replaceStyleIds(e.data, iframeEl, ['styleIds']);
9653
+ (_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach((style) => {
9654
+ this.replaceStyleIds(style, iframeEl, ['styleId']);
9655
+ });
9656
+ return e;
9657
+ }
9658
+ }
9659
+ }
9660
+ }
9661
+ }
9662
+ replace(iframeMirror, obj, iframeEl, keys) {
9663
+ for (const key of keys) {
9664
+ if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')
9665
+ continue;
9666
+ if (Array.isArray(obj[key])) {
9667
+ obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
9668
+ }
9669
+ else {
9670
+ obj[key] = iframeMirror.getId(iframeEl, obj[key]);
9671
+ }
9672
+ }
9673
+ return obj;
9674
+ }
9675
+ replaceIds(obj, iframeEl, keys) {
9676
+ return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
9677
+ }
9678
+ replaceStyleIds(obj, iframeEl, keys) {
9679
+ return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
9680
+ }
9681
+ replaceIdOnNode(node, iframeEl) {
9682
+ this.replaceIds(node, iframeEl, ['id']);
9683
+ if ('childNodes' in node) {
9684
+ node.childNodes.forEach((child) => {
9685
+ this.replaceIdOnNode(child, iframeEl);
9686
+ });
9687
+ }
9688
+ }
9689
+ }
9690
+
9691
+ class ShadowDomManager {
9692
+ constructor(options) {
9693
+ this.shadowDoms = new WeakSet();
9694
+ this.restorePatches = [];
9695
+ this.mutationCb = options.mutationCb;
9696
+ this.scrollCb = options.scrollCb;
9697
+ this.bypassOptions = options.bypassOptions;
9698
+ this.mirror = options.mirror;
9699
+ const manager = this;
9700
+ this.restorePatches.push(patch(Element.prototype, 'attachShadow', function (original) {
9701
+ return function (option) {
9702
+ const shadowRoot = original.call(this, option);
9703
+ if (this.shadowRoot)
9704
+ manager.addShadowRoot(this.shadowRoot, this.ownerDocument);
9705
+ return shadowRoot;
9706
+ };
9707
+ }));
9708
+ }
9709
+ addShadowRoot(shadowRoot, doc) {
9710
+ if (!isNativeShadowDom(shadowRoot))
9711
+ return;
9712
+ if (this.shadowDoms.has(shadowRoot))
9713
+ return;
9714
+ this.shadowDoms.add(shadowRoot);
9715
+ initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);
9716
+ initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));
9717
+ setTimeout(() => {
9718
+ if (shadowRoot.adoptedStyleSheets &&
9719
+ shadowRoot.adoptedStyleSheets.length > 0)
9720
+ this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
9721
+ initAdoptedStyleSheetObserver({
9722
+ mirror: this.mirror,
9723
+ stylesheetManager: this.bypassOptions.stylesheetManager,
9724
+ }, shadowRoot);
9725
+ }, 0);
9726
+ }
9727
+ observeAttachShadow(iframeElement) {
9728
+ if (iframeElement.contentWindow) {
9729
+ const manager = this;
9730
+ this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {
9731
+ return function (option) {
9732
+ const shadowRoot = original.call(this, option);
9733
+ if (this.shadowRoot)
9734
+ manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);
9735
+ return shadowRoot;
9736
+ };
9737
+ }));
9738
+ }
9739
+ }
9740
+ reset() {
9741
+ this.restorePatches.forEach((restorePatch) => restorePatch());
9742
+ this.shadowDoms = new WeakSet();
9743
+ }
9744
+ }
9745
+
9746
+ /*! *****************************************************************************
9747
+ Copyright (c) Microsoft Corporation.
9748
+
9749
+ Permission to use, copy, modify, and/or distribute this software for any
9750
+ purpose with or without fee is hereby granted.
9751
+
9752
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
9753
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9754
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
9755
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
9756
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
9757
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
9758
+ PERFORMANCE OF THIS SOFTWARE.
9759
+ ***************************************************************************** */
9760
+
9761
+ function __rest(s, e) {
9762
+ var t = {};
9763
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
9764
+ t[p] = s[p];
9765
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
9766
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
9767
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9768
+ t[p[i]] = s[p[i]];
9769
+ }
9770
+ return t;
9771
+ }
9772
+
9773
+ function __awaiter(thisArg, _arguments, P, generator) {
9774
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9775
+ return new (P || (P = Promise))(function (resolve, reject) {
9776
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9777
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9778
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9779
+ step((generator = generator.apply(thisArg, [])).next());
9780
+ });
9781
+ }
9782
+
9783
+ /*
9784
+ * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
9785
+ * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
9786
+ * Released under MIT License
9787
+ */
9788
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
9789
+ // Use a lookup table to find the index.
9790
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
9791
+ for (var i = 0; i < chars.length; i++) {
9792
+ lookup[chars.charCodeAt(i)] = i;
9793
+ }
9794
+ var encode = function (arraybuffer) {
9795
+ var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
9796
+ for (i = 0; i < len; i += 3) {
9797
+ base64 += chars[bytes[i] >> 2];
9798
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
9799
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
9800
+ base64 += chars[bytes[i + 2] & 63];
9801
+ }
9802
+ if (len % 3 === 2) {
9803
+ base64 = base64.substring(0, base64.length - 1) + '=';
9804
+ }
9805
+ else if (len % 3 === 1) {
9806
+ base64 = base64.substring(0, base64.length - 2) + '==';
9807
+ }
9808
+ return base64;
9809
+ };
9810
+
9811
+ const canvasVarMap = new Map();
9812
+ function variableListFor(ctx, ctor) {
9813
+ let contextMap = canvasVarMap.get(ctx);
9814
+ if (!contextMap) {
9815
+ contextMap = new Map();
9816
+ canvasVarMap.set(ctx, contextMap);
9817
+ }
9818
+ if (!contextMap.has(ctor)) {
9819
+ contextMap.set(ctor, []);
9820
+ }
9821
+ return contextMap.get(ctor);
9822
+ }
9823
+ const saveWebGLVar = (value, win, ctx) => {
9824
+ if (!value ||
9825
+ !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))
9826
+ return;
9827
+ const name = value.constructor.name;
9828
+ const list = variableListFor(ctx, name);
9829
+ let index = list.indexOf(value);
9830
+ if (index === -1) {
9831
+ index = list.length;
9832
+ list.push(value);
9833
+ }
9834
+ return index;
9835
+ };
9836
+ function serializeArg(value, win, ctx) {
9837
+ if (value instanceof Array) {
9838
+ return value.map((arg) => serializeArg(arg, win, ctx));
9839
+ }
9840
+ else if (value === null) {
9841
+ return value;
9842
+ }
9843
+ else if (value instanceof Float32Array ||
9844
+ value instanceof Float64Array ||
9845
+ value instanceof Int32Array ||
9846
+ value instanceof Uint32Array ||
9847
+ value instanceof Uint8Array ||
9848
+ value instanceof Uint16Array ||
9849
+ value instanceof Int16Array ||
9850
+ value instanceof Int8Array ||
9851
+ value instanceof Uint8ClampedArray) {
9852
+ const name = value.constructor.name;
9853
+ return {
9854
+ rr_type: name,
9855
+ args: [Object.values(value)],
9856
+ };
9857
+ }
9858
+ else if (value instanceof ArrayBuffer) {
9859
+ const name = value.constructor.name;
9860
+ const base64 = encode(value);
9861
+ return {
9862
+ rr_type: name,
9863
+ base64,
9864
+ };
9865
+ }
9866
+ else if (value instanceof DataView) {
9867
+ const name = value.constructor.name;
9868
+ return {
9869
+ rr_type: name,
9870
+ args: [
9871
+ serializeArg(value.buffer, win, ctx),
9872
+ value.byteOffset,
9873
+ value.byteLength,
9874
+ ],
9875
+ };
9876
+ }
9877
+ else if (value instanceof HTMLImageElement) {
9878
+ const name = value.constructor.name;
9879
+ const { src } = value;
9880
+ return {
9881
+ rr_type: name,
9882
+ src,
9883
+ };
9884
+ }
9885
+ else if (value instanceof HTMLCanvasElement) {
9886
+ const name = 'HTMLImageElement';
9887
+ const src = value.toDataURL();
9888
+ return {
9889
+ rr_type: name,
9890
+ src,
9891
+ };
9892
+ }
9893
+ else if (value instanceof ImageData) {
9894
+ const name = value.constructor.name;
9895
+ return {
9896
+ rr_type: name,
9897
+ args: [serializeArg(value.data, win, ctx), value.width, value.height],
9898
+ };
9899
+ }
9900
+ else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {
9901
+ const name = value.constructor.name;
9902
+ const index = saveWebGLVar(value, win, ctx);
9903
+ return {
9904
+ rr_type: name,
9905
+ index: index,
9906
+ };
9907
+ }
9908
+ return value;
9909
+ }
9910
+ const serializeArgs = (args, win, ctx) => {
9911
+ return [...args].map((arg) => serializeArg(arg, win, ctx));
9912
+ };
9913
+ const isInstanceOfWebGLObject = (value, win) => {
9914
+ const webGLConstructorNames = [
9915
+ 'WebGLActiveInfo',
9916
+ 'WebGLBuffer',
9917
+ 'WebGLFramebuffer',
9918
+ 'WebGLProgram',
9919
+ 'WebGLRenderbuffer',
9920
+ 'WebGLShader',
9921
+ 'WebGLShaderPrecisionFormat',
9922
+ 'WebGLTexture',
9923
+ 'WebGLUniformLocation',
9924
+ 'WebGLVertexArrayObject',
9925
+ 'WebGLVertexArrayObjectOES',
9926
+ ];
9927
+ const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');
9928
+ return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));
9929
+ };
9930
+
9931
+ function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
9932
+ const handlers = [];
9933
+ const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
9934
+ for (const prop of props2D) {
9935
+ try {
9936
+ if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {
9937
+ continue;
9938
+ }
9939
+ const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {
9940
+ return function (...args) {
9941
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
9942
+ setTimeout(() => {
9943
+ const recordArgs = serializeArgs([...args], win, this);
9944
+ cb(this.canvas, {
9945
+ type: CanvasContext['2D'],
9946
+ property: prop,
9947
+ args: recordArgs,
9948
+ });
9949
+ }, 0);
9950
+ }
9951
+ return original.apply(this, args);
9952
+ };
9953
+ });
9954
+ handlers.push(restoreHandler);
9955
+ }
9956
+ catch (_a) {
9957
+ const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
9958
+ set(v) {
9959
+ cb(this.canvas, {
9960
+ type: CanvasContext['2D'],
9961
+ property: prop,
9962
+ args: [v],
9963
+ setter: true,
9964
+ });
9965
+ },
9966
+ });
9967
+ handlers.push(hookHandler);
9968
+ }
9969
+ }
9970
+ return () => {
9971
+ handlers.forEach((h) => h());
9972
+ };
9973
+ }
9974
+
9975
+ function initCanvasContextObserver(win, blockClass, blockSelector) {
9976
+ const handlers = [];
9977
+ try {
9978
+ const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {
9979
+ return function (contextType, ...args) {
9980
+ if (!isBlocked(this, blockClass, blockSelector, true)) {
9981
+ if (!('__context' in this))
9982
+ this.__context = contextType;
9983
+ }
9984
+ return original.apply(this, [contextType, ...args]);
9985
+ };
9986
+ });
9987
+ handlers.push(restoreHandler);
9988
+ }
9989
+ catch (_a) {
9990
+ console.error('failed to patch HTMLCanvasElement.prototype.getContext');
9991
+ }
9992
+ return () => {
9993
+ handlers.forEach((h) => h());
9994
+ };
9995
+ }
9996
+
9997
+ function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {
9998
+ const handlers = [];
9999
+ const props = Object.getOwnPropertyNames(prototype);
10000
+ for (const prop of props) {
10001
+ if ([
10002
+ 'isContextLost',
10003
+ 'canvas',
10004
+ 'drawingBufferWidth',
10005
+ 'drawingBufferHeight',
10006
+ ].includes(prop)) {
10007
+ continue;
10008
+ }
10009
+ try {
10010
+ if (typeof prototype[prop] !== 'function') {
10011
+ continue;
10012
+ }
10013
+ const restoreHandler = patch(prototype, prop, function (original) {
10014
+ return function (...args) {
10015
+ const result = original.apply(this, args);
10016
+ saveWebGLVar(result, win, this);
10017
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
10018
+ const recordArgs = serializeArgs([...args], win, this);
10019
+ const mutation = {
10020
+ type,
10021
+ property: prop,
10022
+ args: recordArgs,
10023
+ };
10024
+ cb(this.canvas, mutation);
10025
+ }
10026
+ return result;
10027
+ };
10028
+ });
10029
+ handlers.push(restoreHandler);
10030
+ }
10031
+ catch (_a) {
10032
+ const hookHandler = hookSetter(prototype, prop, {
10033
+ set(v) {
10034
+ cb(this.canvas, {
10035
+ type,
10036
+ property: prop,
10037
+ args: [v],
10038
+ setter: true,
10039
+ });
10040
+ },
10041
+ });
10042
+ handlers.push(hookHandler);
10043
+ }
10044
+ }
10045
+ return handlers;
10046
+ }
10047
+ function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {
10048
+ const handlers = [];
10049
+ handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));
10050
+ if (typeof win.WebGL2RenderingContext !== 'undefined') {
10051
+ handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));
10052
+ }
10053
+ return () => {
10054
+ handlers.forEach((h) => h());
10055
+ };
10056
+ }
10057
+
10058
+ var WorkerClass = null;
10059
+
10060
+ try {
10061
+ var WorkerThreads =
10062
+ typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') ||
10063
+ typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') ||
10064
+ typeof require === 'function' && require('worker_threads');
10065
+ WorkerClass = WorkerThreads.Worker;
10066
+ } catch(e) {} // eslint-disable-line
10067
+
10068
+ function decodeBase64$1(base64, enableUnicode) {
10069
+ return Buffer.from(base64, 'base64').toString('utf8');
10070
+ }
10071
+
10072
+ function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) {
10073
+ var source = decodeBase64$1(base64);
10074
+ var start = source.indexOf('\n', 10) + 1;
10075
+ var body = source.substring(start) + ('');
10076
+ return function WorkerFactory(options) {
10077
+ return new WorkerClass(body, Object.assign({}, options, { eval: true }));
10078
+ };
10079
+ }
10080
+
10081
+ function decodeBase64(base64, enableUnicode) {
10082
+ var binaryString = atob(base64);
10083
+ return binaryString;
10084
+ }
10085
+
10086
+ function createURL(base64, sourcemapArg, enableUnicodeArg) {
10087
+ var source = decodeBase64(base64);
10088
+ var start = source.indexOf('\n', 10) + 1;
10089
+ var body = source.substring(start) + ('');
10090
+ var blob = new Blob([body], { type: 'application/javascript' });
10091
+ return URL.createObjectURL(blob);
10092
+ }
10093
+
10094
+ function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) {
10095
+ var url;
10096
+ return function WorkerFactory(options) {
10097
+ url = url || createURL(base64);
10098
+ return new Worker(url, options);
10099
+ };
10100
+ }
10101
+
10102
+ var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
10103
+
10104
+ function isNodeJS() {
10105
+ return kIsNodeJS;
10106
+ }
10107
+
10108
+ function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
10109
+ if (isNodeJS()) {
10110
+ return createBase64WorkerFactory$2(base64);
10111
+ }
10112
+ return createBase64WorkerFactory$1(base64);
10113
+ }
10114
+
10115
+ var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=');
10116
+
10117
+ class CanvasManager {
10118
+ constructor(options) {
10119
+ this.pendingCanvasMutations = new Map();
10120
+ this.rafStamps = { latestId: 0, invokeId: null };
10121
+ this.frozen = false;
10122
+ this.locked = false;
10123
+ this.processMutation = (target, mutation) => {
10124
+ const newFrame = this.rafStamps.invokeId &&
10125
+ this.rafStamps.latestId !== this.rafStamps.invokeId;
10126
+ if (newFrame || !this.rafStamps.invokeId)
10127
+ this.rafStamps.invokeId = this.rafStamps.latestId;
10128
+ if (!this.pendingCanvasMutations.has(target)) {
10129
+ this.pendingCanvasMutations.set(target, []);
10130
+ }
10131
+ this.pendingCanvasMutations.get(target).push(mutation);
10132
+ };
10133
+ const { sampling = 'all', win, blockClass, blockSelector, recordCanvas, dataURLOptions, } = options;
10134
+ this.mutationCb = options.mutationCb;
10135
+ this.mirror = options.mirror;
10136
+ if (recordCanvas && sampling === 'all')
10137
+ this.initCanvasMutationObserver(win, blockClass, blockSelector);
10138
+ if (recordCanvas && typeof sampling === 'number')
10139
+ this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
10140
+ dataURLOptions,
10141
+ });
10142
+ }
10143
+ reset() {
10144
+ this.pendingCanvasMutations.clear();
10145
+ this.resetObservers && this.resetObservers();
10146
+ }
10147
+ freeze() {
10148
+ this.frozen = true;
10149
+ }
10150
+ unfreeze() {
10151
+ this.frozen = false;
10152
+ }
10153
+ lock() {
10154
+ this.locked = true;
10155
+ }
10156
+ unlock() {
10157
+ this.locked = false;
10158
+ }
10159
+ initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
10160
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
10161
+ const snapshotInProgressMap = new Map();
10162
+ const worker = new WorkerFactory();
10163
+ worker.onmessage = (e) => {
10164
+ const { id } = e.data;
10165
+ snapshotInProgressMap.set(id, false);
10166
+ if (!('base64' in e.data))
10167
+ return;
10168
+ const { base64, type, width, height } = e.data;
10169
+ this.mutationCb({
10170
+ id,
10171
+ type: CanvasContext['2D'],
10172
+ commands: [
10173
+ {
10174
+ property: 'clearRect',
10175
+ args: [0, 0, width, height],
10176
+ },
10177
+ {
10178
+ property: 'drawImage',
10179
+ args: [
10180
+ {
10181
+ rr_type: 'ImageBitmap',
10182
+ args: [
10183
+ {
10184
+ rr_type: 'Blob',
10185
+ data: [{ rr_type: 'ArrayBuffer', base64 }],
10186
+ type,
10187
+ },
10188
+ ],
10189
+ },
10190
+ 0,
10191
+ 0,
10192
+ ],
10193
+ },
10194
+ ],
10195
+ });
10196
+ };
10197
+ const timeBetweenSnapshots = 1000 / fps;
10198
+ let lastSnapshotTime = 0;
10199
+ let rafId;
10200
+ const getCanvas = () => {
10201
+ const matchedCanvas = [];
10202
+ win.document.querySelectorAll('canvas').forEach((canvas) => {
10203
+ if (!isBlocked(canvas, blockClass, blockSelector, true)) {
10204
+ matchedCanvas.push(canvas);
10205
+ }
10206
+ });
10207
+ return matchedCanvas;
10208
+ };
10209
+ const takeCanvasSnapshots = (timestamp) => {
10210
+ if (lastSnapshotTime &&
10211
+ timestamp - lastSnapshotTime < timeBetweenSnapshots) {
10212
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
10213
+ return;
10214
+ }
10215
+ lastSnapshotTime = timestamp;
10216
+ getCanvas()
10217
+ .forEach((canvas) => __awaiter(this, void 0, void 0, function* () {
10218
+ var _a;
10219
+ const id = this.mirror.getId(canvas);
10220
+ if (snapshotInProgressMap.get(id))
10221
+ return;
10222
+ snapshotInProgressMap.set(id, true);
10223
+ if (['webgl', 'webgl2'].includes(canvas.__context)) {
10224
+ const context = canvas.getContext(canvas.__context);
10225
+ if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {
10226
+ context === null || context === void 0 ? void 0 : context.clear(context.COLOR_BUFFER_BIT);
10227
+ }
10228
+ }
10229
+ const bitmap = yield createImageBitmap(canvas);
10230
+ worker.postMessage({
10231
+ id,
10232
+ bitmap,
10233
+ width: canvas.width,
10234
+ height: canvas.height,
10235
+ dataURLOptions: options.dataURLOptions,
10236
+ }, [bitmap]);
10237
+ }));
10238
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
10239
+ };
10240
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
10241
+ this.resetObservers = () => {
10242
+ canvasContextReset();
10243
+ cancelAnimationFrame(rafId);
10244
+ };
10245
+ }
10246
+ initCanvasMutationObserver(win, blockClass, blockSelector) {
10247
+ this.startRAFTimestamping();
10248
+ this.startPendingCanvasMutationFlusher();
10249
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
10250
+ const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
10251
+ const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);
10252
+ this.resetObservers = () => {
10253
+ canvasContextReset();
10254
+ canvas2DReset();
10255
+ canvasWebGL1and2Reset();
10256
+ };
10257
+ }
10258
+ startPendingCanvasMutationFlusher() {
10259
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
10260
+ }
10261
+ startRAFTimestamping() {
10262
+ const setLatestRAFTimestamp = (timestamp) => {
10263
+ this.rafStamps.latestId = timestamp;
10264
+ requestAnimationFrame(setLatestRAFTimestamp);
10265
+ };
10266
+ requestAnimationFrame(setLatestRAFTimestamp);
10267
+ }
10268
+ flushPendingCanvasMutations() {
10269
+ this.pendingCanvasMutations.forEach((values, canvas) => {
10270
+ const id = this.mirror.getId(canvas);
10271
+ this.flushPendingCanvasMutationFor(canvas, id);
10272
+ });
10273
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
10274
+ }
10275
+ flushPendingCanvasMutationFor(canvas, id) {
10276
+ if (this.frozen || this.locked) {
10277
+ return;
10278
+ }
10279
+ const valuesWithType = this.pendingCanvasMutations.get(canvas);
10280
+ if (!valuesWithType || id === -1)
10281
+ return;
10282
+ const values = valuesWithType.map((value) => {
10283
+ const rest = __rest(value, ["type"]);
10284
+ return rest;
10285
+ });
10286
+ const { type } = valuesWithType[0];
10287
+ this.mutationCb({ id, type, commands: values });
10288
+ this.pendingCanvasMutations.delete(canvas);
10289
+ }
10290
+ }
10291
+
10292
+ class StylesheetManager {
10293
+ constructor(options) {
10294
+ this.trackedLinkElements = new WeakSet();
10295
+ this.styleMirror = new StyleSheetMirror();
10296
+ this.mutationCb = options.mutationCb;
10297
+ this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
10298
+ }
10299
+ attachLinkElement(linkEl, childSn) {
10300
+ if ('_cssText' in childSn.attributes)
10301
+ this.mutationCb({
10302
+ adds: [],
10303
+ removes: [],
10304
+ texts: [],
10305
+ attributes: [
10306
+ {
10307
+ id: childSn.id,
10308
+ attributes: childSn
10309
+ .attributes,
10310
+ },
10311
+ ],
10312
+ });
10313
+ this.trackLinkElement(linkEl);
10314
+ }
10315
+ trackLinkElement(linkEl) {
10316
+ if (this.trackedLinkElements.has(linkEl))
10317
+ return;
10318
+ this.trackedLinkElements.add(linkEl);
10319
+ this.trackStylesheetInLinkElement(linkEl);
10320
+ }
10321
+ adoptStyleSheets(sheets, hostId) {
10322
+ if (sheets.length === 0)
10323
+ return;
10324
+ const adoptedStyleSheetData = {
10325
+ id: hostId,
10326
+ styleIds: [],
10327
+ };
10328
+ const styles = [];
10329
+ for (const sheet of sheets) {
10330
+ let styleId;
10331
+ if (!this.styleMirror.has(sheet)) {
10332
+ styleId = this.styleMirror.add(sheet);
10333
+ const rules = Array.from(sheet.rules || CSSRule);
10334
+ styles.push({
10335
+ styleId,
10336
+ rules: rules.map((r, index) => {
10337
+ return {
10338
+ rule: getCssRuleString(r),
10339
+ index,
10340
+ };
10341
+ }),
10342
+ });
10343
+ }
10344
+ else
10345
+ styleId = this.styleMirror.getId(sheet);
10346
+ adoptedStyleSheetData.styleIds.push(styleId);
10347
+ }
10348
+ if (styles.length > 0)
10349
+ adoptedStyleSheetData.styles = styles;
10350
+ this.adoptedStyleSheetCb(adoptedStyleSheetData);
10351
+ }
10352
+ reset() {
10353
+ this.styleMirror.reset();
10354
+ this.trackedLinkElements = new WeakSet();
10355
+ }
10356
+ trackStylesheetInLinkElement(linkEl) {
10357
+ }
10358
+ }
10359
+
10360
+ function wrapEvent(e) {
10361
+ return Object.assign(Object.assign({}, e), { timestamp: Date.now() });
10362
+ }
10363
+ let wrappedEmit;
10364
+ let takeFullSnapshot;
10365
+ let canvasManager;
10366
+ let recording = false;
10367
+ const mirror = createMirror();
10368
+ function record(options = {}) {
10369
+ 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;
10370
+ const inEmittingFrame = recordCrossOriginIframes
10371
+ ? window.parent === window
10372
+ : true;
10373
+ let passEmitsToParent = false;
10374
+ if (!inEmittingFrame) {
10375
+ try {
10376
+ window.parent.document;
10377
+ passEmitsToParent = false;
10378
+ }
10379
+ catch (e) {
10380
+ passEmitsToParent = true;
10381
+ }
10382
+ }
10383
+ if (inEmittingFrame && !emit) {
10384
+ throw new Error('emit function is required');
10385
+ }
10386
+ if (mousemoveWait !== undefined && sampling.mousemove === undefined) {
10387
+ sampling.mousemove = mousemoveWait;
10388
+ }
10389
+ mirror.reset();
10390
+ const maskInputOptions = maskAllInputs === true
10391
+ ? {
10392
+ color: true,
10393
+ date: true,
10394
+ 'datetime-local': true,
10395
+ email: true,
10396
+ month: true,
10397
+ number: true,
10398
+ range: true,
10399
+ search: true,
10400
+ tel: true,
10401
+ text: true,
10402
+ time: true,
10403
+ url: true,
10404
+ week: true,
10405
+ textarea: true,
10406
+ select: true,
10407
+ password: true,
10408
+ }
10409
+ : _maskInputOptions !== undefined
10410
+ ? _maskInputOptions
10411
+ : { password: true };
10412
+ const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'
10413
+ ? {
10414
+ script: true,
10415
+ comment: true,
10416
+ headFavicon: true,
10417
+ headWhitespace: true,
10418
+ headMetaSocial: true,
10419
+ headMetaRobots: true,
10420
+ headMetaHttpEquiv: true,
10421
+ headMetaVerification: true,
10422
+ headMetaAuthorship: _slimDOMOptions === 'all',
10423
+ headMetaDescKeywords: _slimDOMOptions === 'all',
10424
+ }
10425
+ : _slimDOMOptions
10426
+ ? _slimDOMOptions
10427
+ : {};
10428
+ polyfill();
10429
+ let lastFullSnapshotEvent;
10430
+ let incrementalSnapshotCount = 0;
10431
+ const eventProcessor = (e) => {
10432
+ for (const plugin of plugins || []) {
10433
+ if (plugin.eventProcessor) {
10434
+ e = plugin.eventProcessor(e);
10435
+ }
10436
+ }
10437
+ if (packFn) {
10438
+ e = packFn(e);
10439
+ }
10440
+ return e;
10441
+ };
10442
+ wrappedEmit = (e, isCheckout) => {
10443
+ var _a;
10444
+ if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&
10445
+ e.type !== EventType.FullSnapshot &&
10446
+ !(e.type === EventType.IncrementalSnapshot &&
10447
+ e.data.source === IncrementalSource.Mutation)) {
10448
+ mutationBuffers.forEach((buf) => buf.unfreeze());
10449
+ }
10450
+ if (inEmittingFrame) {
10451
+ emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);
10452
+ }
10453
+ else if (passEmitsToParent) {
10454
+ const message = {
10455
+ type: 'rrweb',
10456
+ event: eventProcessor(e),
10457
+ isCheckout,
10458
+ };
10459
+ window.parent.postMessage(message, '*');
10460
+ }
10461
+ if (e.type === EventType.FullSnapshot) {
10462
+ lastFullSnapshotEvent = e;
10463
+ incrementalSnapshotCount = 0;
10464
+ }
10465
+ else if (e.type === EventType.IncrementalSnapshot) {
10466
+ if (e.data.source === IncrementalSource.Mutation &&
10467
+ e.data.isAttachIframe) {
10468
+ return;
10469
+ }
10470
+ incrementalSnapshotCount++;
10471
+ const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
10472
+ const exceedTime = checkoutEveryNms &&
10473
+ e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
10474
+ if (exceedCount || exceedTime) {
10475
+ takeFullSnapshot(true);
10476
+ }
10477
+ }
10478
+ };
10479
+ const wrappedMutationEmit = (m) => {
10480
+ wrappedEmit(wrapEvent({
10481
+ type: EventType.IncrementalSnapshot,
10482
+ data: Object.assign({ source: IncrementalSource.Mutation }, m),
10483
+ }));
10484
+ };
10485
+ const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({
10486
+ type: EventType.IncrementalSnapshot,
10487
+ data: Object.assign({ source: IncrementalSource.Scroll }, p),
10488
+ }));
10489
+ const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({
10490
+ type: EventType.IncrementalSnapshot,
10491
+ data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),
10492
+ }));
10493
+ const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({
10494
+ type: EventType.IncrementalSnapshot,
10495
+ data: Object.assign({ source: IncrementalSource.AdoptedStyleSheet }, a),
10496
+ }));
10497
+ const stylesheetManager = new StylesheetManager({
10498
+ mutationCb: wrappedMutationEmit,
10499
+ adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,
10500
+ });
10501
+ const iframeManager = new IframeManager({
10502
+ mirror,
10503
+ mutationCb: wrappedMutationEmit,
10504
+ stylesheetManager: stylesheetManager,
10505
+ recordCrossOriginIframes,
10506
+ wrappedEmit,
10507
+ });
10508
+ for (const plugin of plugins || []) {
10509
+ if (plugin.getMirror)
10510
+ plugin.getMirror({
10511
+ nodeMirror: mirror,
10512
+ crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
10513
+ crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,
10514
+ });
10515
+ }
10516
+ canvasManager = new CanvasManager({
10517
+ recordCanvas,
10518
+ mutationCb: wrappedCanvasMutationEmit,
10519
+ win: window,
10520
+ blockClass,
10521
+ blockSelector,
10522
+ mirror,
10523
+ sampling: sampling.canvas,
10524
+ dataURLOptions,
10525
+ });
10526
+ const shadowDomManager = new ShadowDomManager({
10527
+ mutationCb: wrappedMutationEmit,
10528
+ scrollCb: wrappedScrollEmit,
10529
+ bypassOptions: {
10530
+ blockClass,
10531
+ blockSelector,
10532
+ maskTextClass,
10533
+ maskTextSelector,
10534
+ inlineStylesheet,
10535
+ maskInputOptions,
10536
+ dataURLOptions,
10537
+ maskTextFn,
10538
+ maskInputFn,
10539
+ recordCanvas,
10540
+ inlineImages,
10541
+ sampling,
10542
+ slimDOMOptions,
10543
+ iframeManager,
10544
+ stylesheetManager,
10545
+ canvasManager,
10546
+ keepIframeSrcFn,
10547
+ },
10548
+ mirror,
10549
+ });
10550
+ takeFullSnapshot = (isCheckout = false) => {
10551
+ var _a, _b, _c, _d, _e, _f;
10552
+ wrappedEmit(wrapEvent({
10553
+ type: EventType.Meta,
10554
+ data: {
10555
+ href: window.location.href,
10556
+ width: getWindowWidth(),
10557
+ height: getWindowHeight(),
10558
+ },
10559
+ }), isCheckout);
10560
+ stylesheetManager.reset();
10561
+ mutationBuffers.forEach((buf) => buf.lock());
10562
+ const node = snapshot(document, {
10563
+ mirror,
10564
+ blockClass,
10565
+ blockSelector,
10566
+ maskTextClass,
10567
+ maskTextSelector,
10568
+ inlineStylesheet,
10569
+ maskAllInputs: maskInputOptions,
10570
+ maskTextFn,
10571
+ slimDOM: slimDOMOptions,
10572
+ dataURLOptions,
10573
+ recordCanvas,
10574
+ inlineImages,
10575
+ onSerialize: (n) => {
10576
+ if (isSerializedIframe(n, mirror)) {
10577
+ iframeManager.addIframe(n);
10578
+ }
10579
+ if (isSerializedStylesheet(n, mirror)) {
10580
+ stylesheetManager.trackLinkElement(n);
10581
+ }
10582
+ if (hasShadowRoot(n)) {
10583
+ shadowDomManager.addShadowRoot(n.shadowRoot, document);
10584
+ }
10585
+ },
10586
+ onIframeLoad: (iframe, childSn) => {
10587
+ iframeManager.attachIframe(iframe, childSn);
10588
+ shadowDomManager.observeAttachShadow(iframe);
10589
+ },
10590
+ onStylesheetLoad: (linkEl, childSn) => {
10591
+ stylesheetManager.attachLinkElement(linkEl, childSn);
10592
+ },
10593
+ keepIframeSrcFn,
10594
+ });
10595
+ if (!node) {
10596
+ return console.warn('Failed to snapshot the document');
10597
+ }
10598
+ wrappedEmit(wrapEvent({
10599
+ type: EventType.FullSnapshot,
10600
+ data: {
10601
+ node,
10602
+ initialOffset: {
10603
+ left: window.pageXOffset !== undefined
10604
+ ? window.pageXOffset
10605
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||
10606
+ ((_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) ||
10607
+ ((_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) ||
10608
+ 0,
10609
+ top: window.pageYOffset !== undefined
10610
+ ? window.pageYOffset
10611
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||
10612
+ ((_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) ||
10613
+ ((_f = document === null || document === void 0 ? void 0 : document.body) === null || _f === void 0 ? void 0 : _f.scrollTop) ||
10614
+ 0,
10615
+ },
10616
+ },
10617
+ }));
10618
+ mutationBuffers.forEach((buf) => buf.unlock());
10619
+ if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)
10620
+ stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
10621
+ };
10622
+ try {
10623
+ const handlers = [];
10624
+ handlers.push(on('DOMContentLoaded', () => {
10625
+ wrappedEmit(wrapEvent({
10626
+ type: EventType.DomContentLoaded,
10627
+ data: {},
10628
+ }));
10629
+ }));
10630
+ const observe = (doc) => {
10631
+ var _a;
10632
+ return initObservers({
10633
+ mutationCb: wrappedMutationEmit,
10634
+ mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({
10635
+ type: EventType.IncrementalSnapshot,
10636
+ data: {
10637
+ source,
10638
+ positions,
10639
+ },
10640
+ })),
10641
+ mouseInteractionCb: (d) => wrappedEmit(wrapEvent({
10642
+ type: EventType.IncrementalSnapshot,
10643
+ data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),
10644
+ })),
10645
+ scrollCb: wrappedScrollEmit,
10646
+ viewportResizeCb: (d) => wrappedEmit(wrapEvent({
10647
+ type: EventType.IncrementalSnapshot,
10648
+ data: Object.assign({ source: IncrementalSource.ViewportResize }, d),
10649
+ })),
10650
+ inputCb: (v) => wrappedEmit(wrapEvent({
10651
+ type: EventType.IncrementalSnapshot,
10652
+ data: Object.assign({ source: IncrementalSource.Input }, v),
10653
+ })),
10654
+ mediaInteractionCb: (p) => wrappedEmit(wrapEvent({
10655
+ type: EventType.IncrementalSnapshot,
10656
+ data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),
10657
+ })),
10658
+ styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({
10659
+ type: EventType.IncrementalSnapshot,
10660
+ data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),
10661
+ })),
10662
+ styleDeclarationCb: (r) => wrappedEmit(wrapEvent({
10663
+ type: EventType.IncrementalSnapshot,
10664
+ data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),
10665
+ })),
10666
+ canvasMutationCb: wrappedCanvasMutationEmit,
10667
+ fontCb: (p) => wrappedEmit(wrapEvent({
10668
+ type: EventType.IncrementalSnapshot,
10669
+ data: Object.assign({ source: IncrementalSource.Font }, p),
10670
+ })),
10671
+ selectionCb: (p) => {
10672
+ wrappedEmit(wrapEvent({
10673
+ type: EventType.IncrementalSnapshot,
10674
+ data: Object.assign({ source: IncrementalSource.Selection }, p),
10675
+ }));
10676
+ },
10677
+ blockClass,
10678
+ ignoreClass,
10679
+ maskTextClass,
10680
+ maskTextSelector,
10681
+ maskInputOptions,
10682
+ inlineStylesheet,
10683
+ sampling,
10684
+ recordCanvas,
10685
+ inlineImages,
10686
+ userTriggeredOnInput,
10687
+ collectFonts,
10688
+ doc,
10689
+ maskInputFn,
10690
+ maskTextFn,
10691
+ keepIframeSrcFn,
10692
+ blockSelector,
10693
+ slimDOMOptions,
10694
+ dataURLOptions,
10695
+ mirror,
10696
+ iframeManager,
10697
+ stylesheetManager,
10698
+ shadowDomManager,
10699
+ canvasManager,
10700
+ ignoreCSSAttributes,
10701
+ plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({
10702
+ observer: p.observer,
10703
+ options: p.options,
10704
+ callback: (payload) => wrappedEmit(wrapEvent({
10705
+ type: EventType.Plugin,
10706
+ data: {
10707
+ plugin: p.name,
10708
+ payload,
10709
+ },
10710
+ })),
10711
+ }))) || [],
10712
+ }, hooks);
10713
+ };
10714
+ iframeManager.addLoadListener((iframeEl) => {
10715
+ handlers.push(observe(iframeEl.contentDocument));
10716
+ });
10717
+ const init = () => {
10718
+ takeFullSnapshot();
10719
+ handlers.push(observe(document));
10720
+ recording = true;
10721
+ };
10722
+ if (document.readyState === 'interactive' ||
10723
+ document.readyState === 'complete') {
10724
+ init();
10725
+ }
10726
+ else {
10727
+ handlers.push(on('load', () => {
10728
+ wrappedEmit(wrapEvent({
10729
+ type: EventType.Load,
10730
+ data: {},
10731
+ }));
10732
+ init();
10733
+ }, window));
10734
+ }
10735
+ return () => {
10736
+ handlers.forEach((h) => h());
10737
+ recording = false;
10738
+ };
10739
+ }
10740
+ catch (error) {
10741
+ console.warn(error);
10742
+ }
10743
+ }
10744
+ record.addCustomEvent = (tag, payload) => {
10745
+ if (!recording) {
10746
+ throw new Error('please add custom event after start recording');
10747
+ }
10748
+ wrappedEmit(wrapEvent({
10749
+ type: EventType.Custom,
10750
+ data: {
10751
+ tag,
10752
+ payload,
10753
+ },
10754
+ }));
10755
+ };
10756
+ record.freezePage = () => {
10757
+ mutationBuffers.forEach((buf) => buf.freeze());
10758
+ };
10759
+ record.takeFullSnapshot = (isCheckout) => {
10760
+ if (!recording) {
10761
+ throw new Error('please take full snapshot after start recording');
10762
+ }
10763
+ takeFullSnapshot(isCheckout);
10764
+ };
10765
+ record.mirror = mirror;
10766
+
6858
10767
  /**
6859
10768
  * Session Replay Engine
6860
- * Captures DOM mutations, user interactions, and viewport changes
6861
- * for comprehensive session recording
10769
+ * Uses rrweb to capture DOM snapshots and events for session replay
6862
10770
  */
6863
10771
  class SessionReplayEngine {
6864
10772
  constructor(sessionId, config = {}) {
6865
10773
  this.events = [];
6866
- this.sequence = 0;
6867
10774
  this.isActive = false;
6868
- this.lastMouseMove = 0;
6869
- this.mouseMoveThrottle = 100; // ms
6870
- /**
6871
- * Handle click events
6872
- */
6873
- this.handleClick = (event) => {
6874
- const target = event.target;
6875
- const path = this.getElementPath(target);
6876
- this.addEvent({
6877
- type: "click",
6878
- timestamp: Date.now(),
6879
- data: {
6880
- x: event.clientX,
6881
- y: event.clientY,
6882
- element: path,
6883
- button: event.button,
6884
- ctrlKey: event.ctrlKey,
6885
- shiftKey: event.shiftKey,
6886
- altKey: event.altKey,
6887
- },
6888
- sequence: this.sequence++,
6889
- });
6890
- };
6891
- /**
6892
- * Handle scroll events
6893
- */
6894
- this.handleScroll = () => {
6895
- this.addEvent({
6896
- type: "scroll",
6897
- timestamp: Date.now(),
6898
- data: {
6899
- x: window.pageXOffset || document.documentElement.scrollLeft,
6900
- y: window.pageYOffset || document.documentElement.scrollTop,
6901
- },
6902
- sequence: this.sequence++,
6903
- });
6904
- };
6905
- /**
6906
- * Handle input events
6907
- */
6908
- this.handleInput = (event) => {
6909
- const target = event.target;
6910
- const path = this.getElementPath(target);
6911
- let value = target.value;
6912
- // Mask sensitive fields
6913
- if (this.config.maskSensitiveFields && this.isSensitiveField(target)) {
6914
- value = "*".repeat(value.length);
6915
- }
6916
- this.addEvent({
6917
- type: "input",
6918
- timestamp: Date.now(),
6919
- data: {
6920
- element: path,
6921
- value: value,
6922
- inputType: event.inputType,
6923
- },
6924
- sequence: this.sequence++,
6925
- });
6926
- };
6927
- /**
6928
- * Handle change events
6929
- */
6930
- this.handleChange = (event) => {
6931
- const target = event.target;
6932
- const path = this.getElementPath(target);
6933
- let value = target.value;
6934
- if (this.config.maskSensitiveFields && this.isSensitiveField(target)) {
6935
- value = "*".repeat(value.length);
6936
- }
6937
- this.addEvent({
6938
- type: "input",
6939
- timestamp: Date.now(),
6940
- data: {
6941
- element: path,
6942
- value: value,
6943
- type: "change",
6944
- },
6945
- sequence: this.sequence++,
6946
- });
6947
- };
6948
- /**
6949
- * Handle mouse move events (throttled)
6950
- */
6951
- this.handleMouseMove = (event) => {
6952
- const now = Date.now();
6953
- if (now - this.lastMouseMove < this.mouseMoveThrottle) {
6954
- return;
6955
- }
6956
- this.lastMouseMove = now;
6957
- this.addEvent({
6958
- type: "mouse",
6959
- timestamp: now,
6960
- data: {
6961
- x: event.clientX,
6962
- y: event.clientY,
6963
- },
6964
- sequence: this.sequence++,
6965
- });
6966
- };
6967
- /**
6968
- * Handle viewport changes
6969
- */
6970
- this.handleViewportChange = () => {
6971
- this.addEvent({
6972
- type: "viewport",
6973
- timestamp: Date.now(),
6974
- data: {
6975
- width: window.innerWidth,
6976
- height: window.innerHeight,
6977
- },
6978
- sequence: this.sequence++,
6979
- });
6980
- };
6981
- /**
6982
- * Handle navigation events
6983
- */
6984
- this.handleNavigation = () => {
6985
- // Send final batch before navigation
6986
- this.sendBatch();
6987
- };
10775
+ this.hasFullSnapshot = false;
6988
10776
  this.sessionId = sessionId;
6989
10777
  this.config = {
6990
10778
  enabled: true,
@@ -7001,7 +10789,7 @@ class SessionReplayEngine {
7001
10789
  };
7002
10790
  }
7003
10791
  /**
7004
- * Start session replay recording
10792
+ * Start session replay recording using rrweb
7005
10793
  */
7006
10794
  start() {
7007
10795
  if (!this.config.enabled || this.isActive) {
@@ -7011,13 +10799,34 @@ class SessionReplayEngine {
7011
10799
  if (Math.random() > this.config.sampleRate) {
7012
10800
  return false;
7013
10801
  }
7014
- this.isActive = true;
7015
- this.setupDOMObserver();
7016
- this.setupEventListeners();
7017
- this.startBatchTimer();
7018
- // Record initial state
7019
- this.recordInitialState();
7020
- return true;
10802
+ try {
10803
+ // Start rrweb recording
10804
+ this.rrwebStopRecord = record({
10805
+ emit: (event) => {
10806
+ this.handleRRWebEvent(event);
10807
+ },
10808
+ maskAllInputs: this.config.maskSensitiveFields,
10809
+ maskTextSelector: 'input[type="password"], input[type="email"], [data-sensitive], [data-mask]',
10810
+ blockSelector: "[data-no-replay]",
10811
+ recordCanvas: false, // Disable canvas recording for performance
10812
+ recordCrossOriginIframes: false,
10813
+ inlineStylesheet: true,
10814
+ collectFonts: false, // Disable font collection for smaller payloads
10815
+ // Add error handler to catch and log issues
10816
+ errorHandler: (error) => {
10817
+ console.warn("[Zaplier] rrweb error:", error);
10818
+ },
10819
+ });
10820
+ this.isActive = true;
10821
+ this.hasFullSnapshot = false;
10822
+ this.startBatchTimer();
10823
+ console.log("[Zaplier] Session replay started with rrweb");
10824
+ return true;
10825
+ }
10826
+ catch (error) {
10827
+ console.error("[Zaplier] Failed to start rrweb recording:", error);
10828
+ return false;
10829
+ }
7021
10830
  }
7022
10831
  /**
7023
10832
  * Stop session replay recording
@@ -7026,11 +10835,11 @@ class SessionReplayEngine {
7026
10835
  if (!this.isActive)
7027
10836
  return;
7028
10837
  this.isActive = false;
7029
- if (this.observer) {
7030
- this.observer.disconnect();
7031
- this.observer = undefined;
10838
+ // Stop rrweb recording
10839
+ if (this.rrwebStopRecord) {
10840
+ this.rrwebStopRecord();
10841
+ this.rrwebStopRecord = undefined;
7032
10842
  }
7033
- this.removeEventListeners();
7034
10843
  if (this.batchTimer) {
7035
10844
  clearInterval(this.batchTimer);
7036
10845
  this.batchTimer = undefined;
@@ -7039,205 +10848,16 @@ class SessionReplayEngine {
7039
10848
  this.sendBatch();
7040
10849
  }
7041
10850
  /**
7042
- * Setup DOM mutation observer
10851
+ * Handle events from rrweb
7043
10852
  */
7044
- setupDOMObserver() {
7045
- if (typeof MutationObserver === "undefined")
7046
- return;
7047
- this.observer = new MutationObserver((mutations) => {
7048
- const serializedMutations = mutations
7049
- .map((mutation) => this.serializeMutation(mutation))
7050
- .filter(Boolean);
7051
- if (serializedMutations.length > 0) {
7052
- this.addEvent({
7053
- type: "mutation",
7054
- timestamp: Date.now(),
7055
- data: { mutations: serializedMutations },
7056
- sequence: this.sequence++,
7057
- });
7058
- }
7059
- });
7060
- this.observer.observe(document, {
7061
- childList: true,
7062
- subtree: true,
7063
- attributes: true,
7064
- attributeOldValue: true,
7065
- characterData: true,
7066
- characterDataOldValue: true,
7067
- });
7068
- }
7069
- /**
7070
- * Setup event listeners
7071
- */
7072
- setupEventListeners() {
7073
- if (this.config.captureClicks) {
7074
- document.addEventListener("click", this.handleClick, true);
7075
- }
7076
- if (this.config.captureScrolls) {
7077
- window.addEventListener("scroll", this.handleScroll, { passive: true });
7078
- document.addEventListener("scroll", this.handleScroll, { passive: true });
7079
- }
7080
- if (this.config.captureInputs) {
7081
- document.addEventListener("input", this.handleInput, true);
7082
- document.addEventListener("change", this.handleChange, true);
10853
+ handleRRWebEvent(event) {
10854
+ // Check if this is a FullSnapshot (type 2)
10855
+ if (event.type === 2) {
10856
+ this.hasFullSnapshot = true;
10857
+ console.log("[Zaplier] FullSnapshot captured");
7083
10858
  }
7084
- if (this.config.captureMouseMoves) {
7085
- document.addEventListener("mousemove", this.handleMouseMove, {
7086
- passive: true,
7087
- });
7088
- }
7089
- // Viewport changes
7090
- window.addEventListener("resize", this.handleViewportChange);
7091
- window.addEventListener("orientationchange", this.handleViewportChange);
7092
- // Navigation
7093
- window.addEventListener("beforeunload", this.handleNavigation);
7094
- window.addEventListener("pagehide", this.handleNavigation);
7095
- }
7096
- /**
7097
- * Remove event listeners
7098
- */
7099
- removeEventListeners() {
7100
- document.removeEventListener("click", this.handleClick, true);
7101
- window.removeEventListener("scroll", this.handleScroll);
7102
- document.removeEventListener("scroll", this.handleScroll);
7103
- document.removeEventListener("input", this.handleInput, true);
7104
- document.removeEventListener("change", this.handleChange, true);
7105
- document.removeEventListener("mousemove", this.handleMouseMove);
7106
- window.removeEventListener("resize", this.handleViewportChange);
7107
- window.removeEventListener("orientationchange", this.handleViewportChange);
7108
- window.removeEventListener("beforeunload", this.handleNavigation);
7109
- window.removeEventListener("pagehide", this.handleNavigation);
7110
- }
7111
- /**
7112
- * Record initial DOM state
7113
- */
7114
- recordInitialState() {
7115
- this.addEvent({
7116
- type: "navigation",
7117
- timestamp: Date.now(),
7118
- data: {
7119
- url: window.location.href,
7120
- referrer: document.referrer,
7121
- title: document.title,
7122
- viewport: {
7123
- width: window.innerWidth,
7124
- height: window.innerHeight,
7125
- },
7126
- screen: {
7127
- width: window.screen?.width || 0,
7128
- height: window.screen?.height || 0,
7129
- },
7130
- },
7131
- sequence: this.sequence++,
7132
- });
7133
- }
7134
- /**
7135
- * Serialize DOM mutation
7136
- */
7137
- serializeMutation(mutation) {
7138
- const result = {
7139
- type: mutation.type,
7140
- target: this.getElementPath(mutation.target),
7141
- };
7142
- switch (mutation.type) {
7143
- case "childList":
7144
- result.addedNodes = Array.from(mutation.addedNodes)
7145
- .filter((node) => node.nodeType === Node.ELEMENT_NODE)
7146
- .map((node) => this.serializeElement(node))
7147
- .slice(0, 10); // Limit to prevent huge payloads
7148
- result.removedNodes = Array.from(mutation.removedNodes)
7149
- .filter((node) => node.nodeType === Node.ELEMENT_NODE)
7150
- .map((node) => this.getElementPath(node))
7151
- .slice(0, 10);
7152
- break;
7153
- case "attributes":
7154
- result.attributeName = mutation.attributeName;
7155
- result.oldValue = mutation.oldValue;
7156
- result.newValue = mutation.target.getAttribute(mutation.attributeName);
7157
- break;
7158
- case "characterData":
7159
- result.oldValue = mutation.oldValue;
7160
- result.newValue = mutation.target.textContent;
7161
- break;
7162
- }
7163
- return result;
7164
- }
7165
- /**
7166
- * Serialize DOM element
7167
- */
7168
- serializeElement(element) {
7169
- const attributes = {};
7170
- for (const attr of Array.from(element.attributes)) {
7171
- // Skip sensitive attributes
7172
- if (!this.isSensitiveAttribute(attr.name)) {
7173
- attributes[attr.name] = attr.value;
7174
- }
7175
- }
7176
- return {
7177
- tagName: element.tagName.toLowerCase(),
7178
- attributes,
7179
- textContent: element.textContent?.substring(0, 1000) || "", // Limit text content
7180
- };
7181
- }
7182
- /**
7183
- * Get element path for targeting
7184
- */
7185
- getElementPath(element) {
7186
- const path = [];
7187
- let current = element;
7188
- while (current && current !== document.body) {
7189
- let selector = current.tagName.toLowerCase();
7190
- if (current.id) {
7191
- selector += `#${current.id}`;
7192
- path.unshift(selector);
7193
- break;
7194
- }
7195
- if (current.className) {
7196
- const classes = current.className.toString().split(/\s+/).slice(0, 2);
7197
- selector += `.${classes.join(".")}`;
7198
- }
7199
- // Add nth-child if no unique identifier
7200
- if (!current.id && !current.className) {
7201
- const siblings = Array.from(current.parentElement?.children || []);
7202
- const index = siblings.indexOf(current);
7203
- selector += `:nth-child(${index + 1})`;
7204
- }
7205
- path.unshift(selector);
7206
- current = current.parentElement;
7207
- }
7208
- return path.join(" > ");
7209
- }
7210
- /**
7211
- * Check if field should be masked
7212
- */
7213
- isSensitiveField(element) {
7214
- const sensitiveTypes = ["password", "email", "tel", "ssn", "cc"];
7215
- const sensitiveNames = [
7216
- "password",
7217
- "email",
7218
- "phone",
7219
- "credit",
7220
- "card",
7221
- "ssn",
7222
- "social",
7223
- ];
7224
- const type = element.getAttribute("type")?.toLowerCase();
7225
- const name = element.getAttribute("name")?.toLowerCase();
7226
- const className = element.className.toLowerCase();
7227
- return (sensitiveTypes.includes(type || "") ||
7228
- sensitiveNames.some((term) => (name && name.includes(term)) || className.includes(term)));
7229
- }
7230
- /**
7231
- * Check if attribute should be masked
7232
- */
7233
- isSensitiveAttribute(attrName) {
7234
- const sensitiveAttrs = [
7235
- "data-token",
7236
- "data-key",
7237
- "data-secret",
7238
- "authorization",
7239
- ];
7240
- return sensitiveAttrs.includes(attrName.toLowerCase());
10859
+ // Add event to buffer
10860
+ this.addEvent(event);
7241
10861
  }
7242
10862
  /**
7243
10863
  * Add event to buffer
@@ -7246,7 +10866,18 @@ class SessionReplayEngine {
7246
10866
  this.events.push(event);
7247
10867
  // Prevent memory overflow
7248
10868
  if (this.events.length > this.config.maxEventBuffer) {
7249
- this.events = this.events.slice(-this.config.maxEventBuffer);
10869
+ // Keep FullSnapshot if present
10870
+ const fullSnapshotIndex = this.events.findIndex((e) => e.type === 2);
10871
+ if (fullSnapshotIndex >= 0 &&
10872
+ fullSnapshotIndex < this.events.length - this.config.maxEventBuffer) {
10873
+ // Keep snapshot and recent events
10874
+ const snapshot = this.events[fullSnapshotIndex];
10875
+ const recentEvents = this.events.slice(-this.config.maxEventBuffer + 1);
10876
+ this.events = [snapshot, ...recentEvents];
10877
+ }
10878
+ else {
10879
+ this.events = this.events.slice(-this.config.maxEventBuffer);
10880
+ }
7250
10881
  }
7251
10882
  }
7252
10883
  /**
@@ -7262,12 +10893,21 @@ class SessionReplayEngine {
7262
10893
  */
7263
10894
  sendBatch() {
7264
10895
  if (this.events.length === 0) {
7265
- console.log("[Zaplier] No events to send in batch");
10896
+ return;
10897
+ }
10898
+ // Wait for FullSnapshot before sending first batch
10899
+ if (!this.hasFullSnapshot) {
10900
+ console.log("[Zaplier] Waiting for FullSnapshot before sending batch...");
7266
10901
  return;
7267
10902
  }
7268
10903
  const batch = [...this.events];
7269
10904
  this.events = [];
7270
- console.log(`[Zaplier] Sending batch with ${batch.length} events for session ${this.sessionId}`);
10905
+ // Verify batch has FullSnapshot
10906
+ const hasSnapshot = batch.some((e) => e.type === 2);
10907
+ if (!hasSnapshot && this.hasFullSnapshot) {
10908
+ console.warn("[Zaplier] Batch missing FullSnapshot, but one was captured earlier");
10909
+ }
10910
+ console.log(`[Zaplier] Sending batch with ${batch.length} events for session ${this.sessionId}`, { hasSnapshot, firstEventType: batch[0]?.type });
7271
10911
  const payload = {
7272
10912
  sessionId: this.sessionId,
7273
10913
  events: batch,