@zaplier/sdk 1.3.0 → 1.3.1

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