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