posthog-js 1.391.6 → 1.391.7
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/all-external-dependencies.js.map +1 -1
- package/dist/array.full.es5.js +1 -1
- package/dist/array.full.js +1 -1
- package/dist/array.full.js.map +1 -1
- package/dist/array.full.no-external.js +1 -1
- package/dist/array.full.no-external.js.map +1 -1
- package/dist/array.js +1 -1
- package/dist/array.no-external.js +1 -1
- package/dist/customizations.full.js +1 -1
- package/dist/default-extensions.js +1 -1
- package/dist/extension-bundles.js +1 -1
- package/dist/lazy-recorder.js +1 -1
- package/dist/lazy-recorder.js.map +1 -1
- package/dist/main.js +1 -1
- package/dist/module.full.js +1 -1
- package/dist/module.full.js.map +1 -1
- package/dist/module.full.no-external.js +1 -1
- package/dist/module.full.no-external.js.map +1 -1
- package/dist/module.js +1 -1
- package/dist/module.no-external.js +1 -1
- package/dist/module.slim.js +1 -1
- package/dist/module.slim.no-external.js +1 -1
- package/dist/posthog-recorder.js +1 -1
- package/dist/posthog-recorder.js.map +1 -1
- package/dist/recorder-v2.js.map +1 -1
- package/dist/recorder.js.map +1 -1
- package/lib/package.json +1 -1
- package/lib/src/extensions/replay/external/config.js +30 -5
- package/lib/src/extensions/replay/external/config.js.map +1 -1
- package/package.json +3 -3
package/dist/recorder-v2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recorder-v2.js","sources":["../../rrweb/record/dist/rrweb-record.js","../../rrweb/plugins/rrweb-plugin-console-record/dist/rrweb-plugin-console-record.js","../../core/dist/utils/type-utils.mjs","../src/utils/globals.ts","../src/utils/type-utils.ts","../src/utils/logger.ts","../src/utils/request-utils.ts","../src/utils/index.ts","../src/extensions/replay/rrweb-plugins/patch.ts","../src/extensions/replay/external/denylist.ts","../src/extensions/replay/external/config.ts","../src/extensions/replay/external/network-plugin.ts","../src/entrypoints/recorder.ts"],"sourcesContent":["var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar _a;\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nconst FullscreenCustomEventTag = \"rrweb/fullscreen\";\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {\n MediaInteractions2[MediaInteractions2[\"Play\"] = 0] = \"Play\";\n MediaInteractions2[MediaInteractions2[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions2[MediaInteractions2[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions2[MediaInteractions2[\"VolumeChange\"] = 3] = \"VolumeChange\";\n MediaInteractions2[MediaInteractions2[\"RateChange\"] = 4] = \"RateChange\";\n return MediaInteractions2;\n})(MediaInteractions || {});\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType || {});\nconst testableAccessors = {\n Node: [\"childNodes\", \"parentNode\", \"parentElement\", \"textContent\"],\n ShadowRoot: [\"host\", \"styleSheets\"],\n Element: [\"shadowRoot\"],\n MutationObserver: []\n};\nconst testableMethods = {\n Node: [\"contains\", \"getRootNode\"],\n ShadowRoot: [\"getSelection\"],\n Element: [\"querySelector\", \"querySelectorAll\"],\n MutationObserver: [\"constructor\"]\n};\nconst untaintedBasePrototype = {};\nfunction angularZoneUnpatchedAlternative(key) {\n var _a2, _b;\n const angularUnpatchedVersionSymbol = (_b = (_a2 = globalThis == null ? void 0 : globalThis.Zone) == null ? void 0 : _a2.__symbol__) == null ? void 0 : _b.call(_a2, key);\n if (angularUnpatchedVersionSymbol && globalThis[angularUnpatchedVersionSymbol]) {\n return globalThis[angularUnpatchedVersionSymbol];\n } else {\n return void 0;\n }\n}\nfunction getUntaintedPrototype(key) {\n if (untaintedBasePrototype[key])\n return untaintedBasePrototype[key];\n const candidate = angularZoneUnpatchedAlternative(key) || globalThis[key];\n const defaultPrototype = candidate.prototype;\n const accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;\n const isUntaintedAccessors = Boolean(\n accessorNames && // @ts-expect-error 2345\n accessorNames.every(\n (accessor) => {\n var _a2, _b;\n return Boolean(\n (_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes(\"[native code]\")\n );\n }\n )\n );\n const methodNames = key in testableMethods ? testableMethods[key] : void 0;\n const isUntaintedMethods = Boolean(\n methodNames && methodNames.every(\n // @ts-expect-error 2345\n (method) => {\n var _a2;\n return typeof defaultPrototype[method] === \"function\" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes(\"[native code]\"));\n }\n )\n );\n if (isUntaintedAccessors && isUntaintedMethods) {\n untaintedBasePrototype[key] = candidate.prototype;\n return candidate.prototype;\n }\n const iframeEl = document.createElement(\"iframe\");\n try {\n document.body.appendChild(iframeEl);\n const win = iframeEl.contentWindow;\n if (!win) return candidate.prototype;\n const untaintedObject = win[key].prototype;\n if (!untaintedObject) return defaultPrototype;\n return untaintedBasePrototype[key] = untaintedObject;\n } catch {\n return defaultPrototype;\n } finally {\n if (iframeEl.parentNode) {\n document.body.removeChild(iframeEl);\n }\n }\n}\nconst untaintedAccessorCache = {};\nfunction getUntaintedAccessor(key, instance, accessor) {\n var _a2;\n const cacheKey = `${key}.${String(accessor)}`;\n if (untaintedAccessorCache[cacheKey])\n return untaintedAccessorCache[cacheKey].call(\n instance\n );\n const untaintedPrototype = getUntaintedPrototype(key);\n const untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(\n untaintedPrototype,\n accessor\n )) == null ? void 0 : _a2.get;\n if (!untaintedAccessor) return instance[accessor];\n untaintedAccessorCache[cacheKey] = untaintedAccessor;\n return untaintedAccessor.call(instance);\n}\nconst untaintedMethodCache = {};\nfunction getUntaintedMethod(key, instance, method) {\n const cacheKey = `${key}.${String(method)}`;\n if (untaintedMethodCache[cacheKey])\n return untaintedMethodCache[cacheKey].bind(\n instance\n );\n const untaintedPrototype = getUntaintedPrototype(key);\n const untaintedMethod = untaintedPrototype[method];\n if (typeof untaintedMethod !== \"function\") return instance[method];\n untaintedMethodCache[cacheKey] = untaintedMethod;\n return untaintedMethod.bind(instance);\n}\nfunction childNodes(n) {\n return getUntaintedAccessor(\"Node\", n, \"childNodes\");\n}\nfunction parentNode(n) {\n return getUntaintedAccessor(\"Node\", n, \"parentNode\");\n}\nfunction parentElement(n) {\n return getUntaintedAccessor(\"Node\", n, \"parentElement\");\n}\nfunction textContent(n) {\n return getUntaintedAccessor(\"Node\", n, \"textContent\");\n}\nfunction contains(n, other) {\n return getUntaintedMethod(\"Node\", n, \"contains\")(other);\n}\nfunction getRootNode(n) {\n return getUntaintedMethod(\"Node\", n, \"getRootNode\")();\n}\nfunction host(n) {\n if (!n || !(\"host\" in n)) return null;\n return getUntaintedAccessor(\"ShadowRoot\", n, \"host\");\n}\nfunction styleSheets(n) {\n return n.styleSheets;\n}\nfunction shadowRoot(n) {\n if (!n || !(\"shadowRoot\" in n)) return null;\n return getUntaintedAccessor(\"Element\", n, \"shadowRoot\");\n}\nfunction querySelector(n, selectors) {\n return getUntaintedMethod(\"Element\", n, \"querySelector\")(selectors);\n}\nfunction querySelectorAll(n, selectors) {\n return getUntaintedMethod(\"Element\", n, \"querySelectorAll\")(selectors);\n}\nfunction mutationObserverCtor() {\n return getUntaintedPrototype(\"MutationObserver\").constructor;\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nconst index = {\n childNodes,\n parentNode,\n parentElement,\n textContent,\n contains,\n getRootNode,\n host,\n styleSheets,\n shadowRoot,\n querySelector,\n querySelectorAll,\n mutationObserver: mutationObserverCtor,\n patch\n};\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const hostEl = (\n // anchor and textarea elements also have a `host` property\n // but only shadow roots have a `mode` property\n n && \"host\" in n && \"mode\" in n && index.host(n) || null\n );\n return Boolean(\n hostEl && \"shadowRoot\" in hostEl && index.shadowRoot(hostEl) === n\n );\n}\nfunction isNativeShadowDom(shadowRoot2) {\n return Object.prototype.toString.call(shadowRoot2) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n cssText = cssText.replace(\n /\\sbackground-clip:\\s*text;/g,\n \" -webkit-background-clip: text; background-clip: text;\"\n );\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3) return cssText;\n const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === \"\") {\n statement.push(`layer`);\n } else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(\" \") + \";\";\n}\nfunction hasEmptyShorthandLonghand(css) {\n return /(?:^|[\\s;{}])-?[a-zA-Z][\\w-]*\\s*:\\s*;/.test(css);\n}\nfunction stringifyStylesheet(s) {\n try {\n const rules = s.rules || s.cssRules;\n if (!rules) {\n return null;\n }\n let sheetHref = s.href;\n if (!sheetHref && s.ownerNode) {\n sheetHref = s.ownerNode.baseURI;\n }\n const stringifiedRules = Array.from(\n rules,\n (rule) => stringifyRule(rule, sheetHref)\n ).join(\"\");\n return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);\n } catch (error) {\n return null;\n }\n}\nfunction stringifyRule(rule, sheetHref) {\n var _a2;\n if (isCSSImportRule(rule)) {\n let importStringified;\n try {\n importStringified = // for same-origin stylesheets,\n // we can access the imported stylesheet rules directly\n stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n escapeImportStatement(rule);\n } catch (error) {\n importStringified = rule.cssText;\n }\n try {\n if (importStringified && ((_a2 = rule.styleSheet) == null ? void 0 : _a2.href)) {\n return absolutifyURLs(importStringified, rule.styleSheet.href);\n }\n } catch {\n }\n return importStringified;\n } else {\n let ruleStringified = rule.cssText;\n if (isCSSStyleRule(rule) && rule.selectorText.includes(\":\")) {\n ruleStringified = fixSafariColons(ruleStringified);\n }\n if (sheetHref) {\n return absolutifyURLs(ruleStringified, sheetHref);\n }\n return ruleStringified;\n }\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n return \"selectorText\" in rule;\n}\nclass Mirror {\n constructor() {\n __publicField(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n) {\n var _a2;\n if (!n) return -1;\n const id = (_a2 = this.getMeta(n)) == null ? void 0 : _a2.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n) {\n return this.nodeMetaMap.get(n) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n) {\n const id = this.getId(n);\n this.idNodeMap.delete(id);\n if (n.childNodes) {\n n.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n if (isElement(n)) {\n const shadowRootEl = index.shadowRoot(n);\n if (shadowRootEl) {\n this.removeNodeFromMap(shadowRootEl);\n }\n if (n.nodeName === \"IFRAME\" && n.contentDocument) {\n this.removeNodeFromMap(\n n.contentDocument\n );\n }\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n);\n this.nodeMetaMap.set(n, meta);\n }\n replace(id, n) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n, meta);\n }\n this.idNodeMap.set(id, n);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction createMirror() {\n return new Mirror();\n}\nfunction maskInputValue({\n element,\n maskInputOptions,\n tagName,\n type,\n value,\n maskInputFn\n}) {\n let text = value || \"\";\n const actualType = type && toLowerCase(type);\n if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {\n if (maskInputFn) {\n text = maskInputFn(text, element);\n } else {\n text = \"*\".repeat(text.length);\n }\n }\n return text;\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n const pixelBuffer = new Uint32Array(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n originalGetImageData.call(\n ctx,\n x,\n y,\n Math.min(chunkSize, canvas.width - x),\n Math.min(chunkSize, canvas.height - y)\n ).data.buffer\n );\n if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n toLowerCase(type)\n ) : null;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n } catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return (match == null ? void 0 : match[1]) ?? null;\n}\nfunction extractOrigin(url) {\n let origin = \"\";\n if (url.indexOf(\"//\") > -1) {\n origin = url.split(\"/\").slice(0, 3).join(\"/\");\n } else {\n origin = url.split(\"/\")[0];\n }\n origin = origin.split(\"?\")[0];\n return origin;\n}\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absolutifyURLs(cssText, href) {\n return (cssText || \"\").replace(\n URL_IN_CSS_REF,\n (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || \"\";\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === \"/\") {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split(\"/\");\n const parts = filePath.split(\"/\");\n stack.pop();\n for (const part of parts) {\n if (part === \".\") {\n continue;\n } else if (part === \"..\") {\n stack.pop();\n } else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join(\"/\")}${maybeQuote})`;\n }\n );\n}\nconst STRIPED_PLACEHOLDER_SVG = \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxkZWZzPgogICAgPHBhdHRlcm4gaWQ9InN0cmlwZXMiIHBhdHRlcm5Vbml0cz0idXNlclNwYWNlT25Vc2UiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+CiAgICAgIDxyZWN0IHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iYmxhY2siLz4KICAgICAgPHBhdGggZD0iTTggMEgxNkwwIDE2VjhMOCAwWiIgZmlsbD0iIzJEMkQyRCIvPgogICAgICA8cGF0aCBkPSJNMTYgOFYxNkg4TDE2IDhaIiBmaWxsPSIjMkQyRDJEIi8+CiAgICA8L3BhdHRlcm4+CiAgPC9kZWZzPgogIDxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjc3RyaXBlcykiLz4KPC9zdmc+Cg==\";\nconst MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION = 4096;\nfunction recompressBase64Image(img, dataURL, type, quality) {\n if (!img.complete || img.naturalWidth === 0) {\n return dataURL;\n }\n if (img.naturalWidth > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION || img.naturalHeight > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION) {\n return dataURL;\n }\n try {\n const canvas = document.createElement(\"canvas\");\n canvas.width = img.naturalWidth;\n canvas.height = img.naturalHeight;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n return dataURL;\n }\n ctx.drawImage(img, 0, 0);\n const recompressed = canvas.toDataURL(type || \"image/webp\", quality ?? 0.4);\n return recompressed;\n } catch (err) {\n return dataURL;\n }\n}\nfunction checkDataURLSize(dataURL, maxLength) {\n if (!maxLength || dataURL.length <= maxLength) {\n return dataURL;\n }\n return STRIPED_PLACEHOLDER_SVG;\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return \"form\";\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return \"div\";\n }\n return processedTagName;\n}\nlet canvasService;\nlet canvasCtx;\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === \"\") {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars2;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars2 = match[0];\n pos += chars2.length;\n return chars2;\n }\n return \"\";\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === \",\") {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n } else {\n let descriptorsStr = \"\";\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c = attributeValue.charAt(pos);\n if (c === \"\") {\n output.push((url + descriptorsStr).trim());\n break;\n } else if (!inParens) {\n if (c === \",\") {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n } else if (c === \"(\") {\n inParens = true;\n }\n } else {\n if (c === \")\") {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === \"\") {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a = cachedDocument.get(doc);\n if (!a) {\n a = doc.createElement(\"a\");\n cachedDocument.set(doc, a);\n }\n if (!customHref) {\n customHref = \"\";\n } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n return customHref;\n }\n a.setAttribute(\"href\", customHref);\n return a.href;\n}\nfunction capDataURLSize(dataURL, dataURLOptions) {\n if (dataURLOptions == null ? void 0 : dataURLOptions.maxBase64ImageLength) {\n return checkDataURLSize(dataURL, dataURLOptions.maxBase64ImageLength);\n }\n return dataURL;\n}\nfunction transformAttribute(doc, tagName, name, value, element, dataURLOptions) {\n var _a2;\n if (!value) {\n return value;\n }\n if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n if (tagName === \"link\" && element) {\n const sheetHref = (_a2 = element.sheet) == null ? void 0 : _a2.href;\n if (sheetHref) {\n return sheetHref;\n }\n }\n const transformedValue = absoluteToDoc(doc, value);\n if (transformedValue.startsWith(\"data:\")) {\n if (tagName === \"img\" && element) {\n let processedDataURL = transformedValue;\n if ((dataURLOptions == null ? void 0 : dataURLOptions.type) || (dataURLOptions == null ? void 0 : dataURLOptions.quality) !== void 0) {\n processedDataURL = recompressBase64Image(\n element,\n transformedValue,\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n return capDataURLSize(processedDataURL, dataURLOptions);\n }\n if (tagName === \"image\") {\n return capDataURLSize(transformedValue, dataURLOptions);\n }\n }\n return transformedValue;\n } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n const transformedValue = absoluteToDoc(doc, value);\n if (tagName === \"image\" && transformedValue.startsWith(\"data:\")) {\n return capDataURLSize(transformedValue, dataURLOptions);\n }\n return transformedValue;\n } else if (name === \"background\" && (tagName === \"table\" || tagName === \"td\" || tagName === \"th\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"srcset\") {\n return getAbsoluteSrcsetString(doc, value);\n } else if (name === \"style\") {\n return absolutifyURLs(value, getHref(doc));\n } else if (tagName === \"object\" && name === \"data\") {\n return absoluteToDoc(doc, value);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return (tagName === \"video\" || tagName === \"audio\") && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector) {\n try {\n if (typeof blockClass === \"string\") {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n } else {\n for (let eIndex = element.classList.length; eIndex--; ) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n } catch (e) {\n }\n return false;\n}\nfunction classMatchesRegex(node, regex, checkAncestors) {\n if (!node) return false;\n if (node.nodeType !== node.ELEMENT_NODE) {\n if (!checkAncestors) return false;\n return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n }\n for (let eIndex = node.classList.length; eIndex--; ) {\n const className = node.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n if (!checkAncestors) return false;\n return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, checkAncestors) {\n let el;\n if (isElement(node)) {\n el = node;\n if (!index.childNodes(el).length) {\n return false;\n }\n } else if (index.parentElement(node) === null) {\n return false;\n } else {\n el = index.parentElement(node);\n }\n try {\n if (typeof maskTextClass === \"string\") {\n if (checkAncestors) {\n if (el.closest(`.${maskTextClass}`)) return true;\n } else {\n if (el.classList.contains(maskTextClass)) return true;\n }\n } else {\n if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;\n }\n if (maskTextSelector) {\n if (checkAncestors) {\n if (el.closest(maskTextSelector)) return true;\n } else {\n if (el.matches(maskTextSelector)) return true;\n }\n }\n } catch (e) {\n }\n return false;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const noop = () => {\n };\n const win = iframeEl.contentWindow;\n if (!win) {\n return noop;\n }\n let readyState;\n try {\n readyState = win.document.readyState;\n } catch (error) {\n return noop;\n }\n const onSubsequentLoad = () => listener();\n if (readyState !== \"complete\") {\n let fired = false;\n let timer = null;\n const fireOnce = () => {\n if (fired) return;\n fired = true;\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n iframeEl.removeEventListener(\"load\", onInitialLoad);\n iframeEl.addEventListener(\"load\", onSubsequentLoad);\n listener();\n };\n const onInitialLoad = () => fireOnce();\n timer = setTimeout(fireOnce, iframeLoadTimeout);\n iframeEl.addEventListener(\"load\", onInitialLoad);\n return () => {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n if (fired) {\n iframeEl.removeEventListener(\"load\", onSubsequentLoad);\n } else {\n fired = true;\n iframeEl.removeEventListener(\"load\", onInitialLoad);\n }\n };\n }\n const blankUrl = \"about:blank\";\n let winLocationHref;\n try {\n winLocationHref = win.location.href;\n } catch {\n return noop;\n }\n if (winLocationHref !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n const initialTimer = setTimeout(listener, 0);\n iframeEl.addEventListener(\"load\", onSubsequentLoad);\n return () => {\n clearTimeout(initialTimer);\n iframeEl.removeEventListener(\"load\", onSubsequentLoad);\n };\n }\n iframeEl.addEventListener(\"load\", onSubsequentLoad);\n return () => {\n iframeEl.removeEventListener(\"load\", onSubsequentLoad);\n };\n}\nconst stylesheetLoadTracked = /* @__PURE__ */ new Map();\nfunction resetStylesheetLoadTracking() {\n stylesheetLoadTracked.forEach((controller) => controller.abort());\n stylesheetLoadTracked.clear();\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n if (stylesheetLoadTracked.has(link)) return;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n } catch (error) {\n return;\n }\n if (styleSheetLoaded) return;\n const controller = new AbortController();\n let fired = false;\n const fire = () => {\n if (fired) return;\n fired = true;\n try {\n listener();\n } finally {\n stylesheetLoadTracked.delete(link);\n controller.abort();\n }\n };\n const timer = setTimeout(fire, styleSheetLoadTimeout);\n controller.signal.addEventListener(\"abort\", () => clearTimeout(timer), {\n once: true\n });\n link.addEventListener(\"load\", fire, {\n signal: controller.signal,\n once: true\n });\n stylesheetLoadTracked.set(link, controller);\n}\nfunction serializeNode(n, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n inlineStylesheet,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false\n } = options;\n const rootId = getRootId(doc, mirror2);\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== \"CSS1Compat\") {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode\n // probably \"BackCompat\"\n };\n } else {\n return {\n type: NodeType.Document,\n childNodes: []\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId\n };\n case n.ELEMENT_NODE:\n return serializeElementNode(n, {\n doc,\n blockClass,\n blockSelector,\n inlineStylesheet,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId\n });\n case n.TEXT_NODE:\n return serializeTextNode(n, {\n doc,\n needsMask,\n maskTextFn,\n rootId\n });\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: \"\",\n rootId\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: index.textContent(n) || \"\",\n rootId\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror2) {\n if (!mirror2.hasNode(doc)) return void 0;\n const docId = mirror2.getId(doc);\n return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n, options) {\n var _a2;\n const { needsMask, maskTextFn, rootId } = options;\n const parent = index.parentNode(n);\n const parentTagName = parent && parent.tagName;\n let text = index.textContent(n);\n const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n if (isStyle && text) {\n try {\n if (n.nextSibling || n.previousSibling) {\n } else if ((_a2 = parent.sheet) == null ? void 0 : _a2.cssRules) {\n const stringified = stringifyStylesheet(\n parent.sheet\n );\n if (stringified && !hasEmptyShorthandLonghand(stringified)) {\n text = stringified;\n }\n }\n } catch (err) {\n console.warn(\n `Cannot get CSS styles from text's parentNode. Error: ${err}`,\n n\n );\n }\n text = absolutifyURLs(text, getHref(options.doc));\n }\n if (isScript) {\n text = \"SCRIPT_PLACEHOLDER\";\n }\n if (!isStyle && !isScript && text && needsMask) {\n text = maskTextFn ? maskTextFn(text, index.parentElement(n)) : text.replace(/[\\S]/g, \"*\");\n }\n return {\n type: NodeType.Text,\n textContent: text || \"\",\n isStyle,\n rootId\n };\n}\nfunction findStylesheet(doc, href) {\n return Array.from(doc.styleSheets).find((s) => s.href === href);\n}\nfunction hrefFrom(n) {\n return n.href;\n}\nfunction serializeElementNode(n, options) {\n var _a2, _b, _c;\n const {\n doc,\n blockClass,\n blockSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n rootId\n } = options;\n const needBlock = _isBlockedElement(n, blockClass, blockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n const len = n.attributes.length;\n for (let i = 0; i < len; i++) {\n const attr = n.attributes[i];\n if (!ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes[attr.name] = transformAttribute(\n doc,\n tagName,\n toLowerCase(attr.name),\n attr.value,\n n,\n dataURLOptions\n );\n }\n }\n if (tagName === \"link\" && inlineStylesheet) {\n let stylesheet = n.sheet;\n if (!stylesheet) {\n const href = hrefFrom(n);\n if (href) {\n stylesheet = findStylesheet(doc, href);\n if (!stylesheet && href.includes(\".css\")) {\n const rootDomain = window.location.origin;\n const stylesheetPath = href.replace(window.location.href, \"\");\n const potentialStylesheetHref = rootDomain + \"/\" + stylesheetPath;\n stylesheet = findStylesheet(doc, potentialStylesheetHref);\n }\n }\n }\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = cssText;\n }\n }\n if (tagName === \"style\" && n.sheet && // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n !(n.innerText || index.textContent(n) || \"\").trim().length) {\n const cssText = stringifyStylesheet(\n n.sheet\n );\n if (cssText) {\n attributes._cssText = cssText;\n }\n }\n if (tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\") {\n const value = n.value;\n const checked = n.checked;\n if (attributes.type !== \"radio\" && attributes.type !== \"checkbox\" && attributes.type !== \"submit\" && attributes.type !== \"button\" && value) {\n attributes.value = maskInputValue({\n element: n,\n type: getInputType(n),\n tagName,\n value,\n maskInputOptions,\n maskInputFn\n });\n } else if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === \"option\") {\n if (n.selected && !maskInputOptions[\"select\"]) {\n attributes.selected = true;\n } else {\n delete attributes.selected;\n }\n }\n if (tagName === \"dialog\" && n.open) {\n try {\n attributes.rr_open_mode = n.matches(\"dialog:modal\") ? \"modal\" : \"non-modal\";\n } catch {\n attributes.rr_open_mode = \"modal\";\n attributes.ph_rr_could_not_detect_modal = true;\n }\n }\n if (tagName === \"canvas\" && recordCanvas) {\n if (n.__context === \"2d\") {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n } else if (!(\"__context\" in n)) {\n const canvasDataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n const blankCanvas = doc.createElement(\"canvas\");\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === \"img\" && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement(\"canvas\");\n canvasCtx = canvasService.getContext(\"2d\");\n }\n const image = n;\n const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"<unknown-src>\";\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener(\"load\", recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n } catch (err) {\n if (image.crossOrigin !== \"anonymous\") {\n image.crossOrigin = \"anonymous\";\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n return;\n } else {\n console.warn(\n `Cannot inline img src=${imageSrc}! Error: ${err}`\n );\n }\n }\n if (image.crossOrigin === \"anonymous\") {\n priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n }\n };\n if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n }\n if (tagName === \"audio\" || tagName === \"video\") {\n const mediaAttributes = attributes;\n mediaAttributes.rr_mediaState = n.paused ? \"paused\" : \"played\";\n mediaAttributes.rr_mediaCurrentTime = n.currentTime;\n mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;\n mediaAttributes.rr_mediaMuted = n.muted;\n mediaAttributes.rr_mediaLoop = n.loop;\n mediaAttributes.rr_mediaVolume = n.volume;\n }\n if (!newlyAddedElement) {\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height, left, top } = n.getBoundingClientRect();\n const computed = (_a2 = doc.defaultView) == null ? void 0 : _a2.getComputedStyle(n);\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n rr_left: `${Math.floor(left + (((_b = doc.defaultView) == null ? void 0 : _b.scrollX) || 0))}px`,\n rr_top: `${Math.floor(top + (((_c = doc.defaultView) == null ? void 0 : _c.scrollY) || 0))}px`\n };\n if (computed) {\n attributes.rr_position = computed.position || \"static\";\n if (computed.transform && computed.transform !== \"none\") {\n attributes.rr_transform = computed.transform;\n }\n if (computed.display && computed.display.startsWith(\"inline\")) {\n attributes.rr_display = computed.display;\n }\n }\n }\n if (tagName === \"iframe\" && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName)) isCustomElement = true;\n } catch (e) {\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || void 0,\n needBlock,\n rootId,\n isCustom: isCustomElement\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === void 0 || maybeAttr === null) {\n return \"\";\n } else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n } else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script && // script tag\n (sn.tagName === \"script\" || // (module)preload link\n sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" && sn.attributes.as === \"script\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n return true;\n } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n /^msapplication-tile(image|color)$/\n ) || lowerIfExists(sn.attributes.name) === \"application-name\" || [\"icon\", \"apple-touch-icon\", \"shortcut icon\"].includes(\n lowerIfExists(sn.attributes.rel)\n )))) {\n return true;\n } else if (sn.tagName === \"meta\") {\n if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n return true;\n } else if (slimDOMOptions.headMetaRobots && [\"robots\", \"googlebot\", \"bingbot\"].includes(\n lowerIfExists(sn.attributes.name)\n )) {\n return true;\n } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n return true;\n } else if (slimDOMOptions.headMetaAuthorship && ([\"author\", \"generator\", \"framework\", \"publisher\", \"progid\"].includes(\n lowerIfExists(sn.attributes.name)\n ) || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n } else if (slimDOMOptions.headMetaVerification && [\n \"google-site-verification\",\n \"yandex-verification\",\n \"csrf-token\",\n \"p:domain_verify\",\n \"verify-v1\",\n \"verification\",\n \"shopify-checkout-api-token\"\n ].includes(lowerIfExists(sn.attributes.name))) {\n return true;\n }\n }\n }\n return false;\n}\nconst DEFAULT_MAX_DEPTH = 50;\nlet _maxDepthWarned = false;\nlet _maxDepthReached = false;\nfunction wasMaxDepthReached() {\n return _maxDepthReached;\n}\nfunction resetMaxDepthState() {\n _maxDepthReached = false;\n _maxDepthWarned = false;\n}\nfunction serializeNodeWithId(n, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n skipChild = false,\n inlineStylesheet = true,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions = {},\n inlineImages = false,\n recordCanvas = false,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout = 5e3,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout = 5e3,\n keepIframeSrcFn = () => false,\n newlyAddedElement = false,\n depth = 0,\n maxDepth = DEFAULT_MAX_DEPTH\n } = options;\n let { needsMask } = options;\n let { preserveWhiteSpace = true } = options;\n if (depth >= maxDepth) {\n _maxDepthReached = true;\n if (!_maxDepthWarned) {\n _maxDepthWarned = true;\n console.warn(\n `[rrweb-snapshot] DOM tree depth exceeded max depth of ${maxDepth}. Children beyond this depth will not be recorded. This may indicate deeply nested DOM structures.`\n );\n }\n return null;\n }\n if (!needsMask) {\n const checkAncestors = needsMask === void 0;\n needsMask = needMaskingText(\n n,\n maskTextClass,\n maskTextSelector,\n checkAncestors\n );\n }\n const _serializedNode = serializeNode(n, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement\n });\n if (!_serializedNode) {\n console.warn(n, \"not serialized\");\n return null;\n }\n let id;\n if (mirror2.hasNode(n)) {\n id = mirror2.getId(n);\n } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.isStyle && // codeql[js/polynomial-redos] Bounded DOM text node; worst case is recorder slowdown, no exploit.\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n id = IGNORED_NODE;\n } else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n mirror2.add(n, serializedNode);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n const shadowRootEl = index.shadowRoot(n);\n if (shadowRootEl && isNativeShadowDom(shadowRootEl))\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {\n if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === \"head\") {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n depth: depth + 1,\n maxDepth\n };\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"textarea\" && serializedNode.attributes.value !== void 0) ;\n else {\n for (const childN of Array.from(index.childNodes(n))) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n let shadowRootEl = null;\n if (isElement(n) && (shadowRootEl = index.shadowRoot(n))) {\n for (const childN of Array.from(index.childNodes(shadowRootEl))) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(shadowRootEl) && (serializedChildNode.isShadow = true);\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n const parent = index.parentNode(n);\n if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"iframe\") {\n const iframeDisposer = onceIframeLoaded(\n n,\n () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n depth: depth + 1,\n maxDepth\n });\n if (serializedIframeNode) {\n onIframeLoad(\n n,\n serializedIframeNode\n );\n }\n }\n },\n iframeLoadTimeout\n );\n onIframeListenerRegistered == null ? void 0 : onIframeListenerRegistered(n, iframeDisposer);\n }\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"link\" && serializedNode.attributes.rel === \"stylesheet\") {\n onceStylesheetLoaded(\n n,\n () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n depth,\n maxDepth\n });\n if (serializedLinkNode) {\n onStylesheetLoad(\n n,\n serializedLinkNode\n );\n }\n }\n },\n stylesheetLoadTimeout\n );\n }\n return serializedNode;\n}\nfunction slimDOMDefaults(slimDOM) {\n if (slimDOM === true || slimDOM === \"all\") {\n return {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: slimDOM === \"all\",\n headMetaDescKeywords: slimDOM === \"all\",\n headTitleMutations: slimDOM === \"all\"\n };\n }\n if (slimDOM === false) {\n return {};\n }\n return slimDOM;\n}\nfunction snapshot(n, options) {\n const {\n mirror: mirror2 = new Mirror(),\n blockClass = \"rr-block\",\n blockSelector = null,\n maskTextClass = \"rr-mask\",\n maskTextSelector = null,\n inlineStylesheet = true,\n inlineImages = false,\n recordCanvas = false,\n maskAllInputs = false,\n maskTextFn,\n maskInputFn,\n slimDOM = false,\n dataURLOptions,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn = () => false,\n maxDepth\n } = options || {};\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n } : maskAllInputs === false ? {\n password: true\n } : maskAllInputs;\n const slimDOMOptions = slimDOMDefaults(slimDOM);\n return serializeNodeWithId(n, {\n doc: n,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n maxDepth\n });\n}\nclass BaseRRNode {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n constructor(..._args) {\n __publicField(this, \"parentElement\", null);\n __publicField(this, \"parentNode\", null);\n __publicField(this, \"ownerDocument\");\n __publicField(this, \"firstChild\", null);\n __publicField(this, \"lastChild\", null);\n __publicField(this, \"previousSibling\", null);\n __publicField(this, \"nextSibling\", null);\n __publicField(this, \"ELEMENT_NODE\", 1);\n __publicField(this, \"TEXT_NODE\", 3);\n // corresponding nodeType value of standard HTML Node\n __publicField(this, \"nodeType\");\n __publicField(this, \"nodeName\");\n __publicField(this, \"RRNodeType\");\n }\n get childNodes() {\n const childNodes2 = [];\n let childIterator = this.firstChild;\n while (childIterator) {\n childNodes2.push(childIterator);\n childIterator = childIterator.nextSibling;\n }\n return childNodes2;\n }\n contains(node) {\n if (!(node instanceof BaseRRNode)) return false;\n else if (node.ownerDocument !== this.ownerDocument) return false;\n else if (node === this) return true;\n while (node.parentNode) {\n if (node.parentNode === this) return true;\n node = node.parentNode;\n }\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n appendChild(_newChild) {\n throw new Error(\n `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n insertBefore(_newChild, _refChild) {\n throw new Error(\n `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n removeChild(_node) {\n throw new Error(\n `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n toString() {\n return \"RRNode\";\n }\n}\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nfunction callSafely(fn) {\n try {\n fn();\n } catch (error) {\n if (!(error instanceof DOMException && error.name === \"SecurityError\")) {\n throw error;\n }\n }\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = \"Please stop import mirror directly. Instead of that,\\r\\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\r\\nor you can use record.mirror to access the mirror instance during recording.\";\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n};\nif (typeof window !== \"undefined\" && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === \"map\") {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function(...args) {\n const now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n const remaining = wait - (now - previous);\n const context = this;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(\n target,\n key,\n isRevoked ? d : {\n set(value) {\n setTimeout(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n }\n }\n );\n return () => hookSetter(target, key, original || {}, true);\n}\nlet nowTimestamp = Date.now;\nif (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {\n nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\n}\nfunction getWindowScroll(win) {\n var _a2, _b, _c, _d;\n const doc = win.document;\n return {\n left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc.documentElement.scrollLeft || (doc == null ? void 0 : doc.body) && ((_a2 = index.parentElement(doc.body)) == null ? void 0 : _a2.scrollLeft) || ((_b = doc == null ? void 0 : doc.body) == null ? void 0 : _b.scrollLeft) || 0,\n top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || (doc == null ? void 0 : doc.body) && ((_c = index.parentElement(doc.body)) == null ? void 0 : _c.scrollTop) || ((_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.scrollTop) || 0\n };\n}\nfunction getWindowHeight() {\n return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;\n}\nfunction getWindowWidth() {\n return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;\n}\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n const el = node.nodeType === node.ELEMENT_NODE ? node : index.parentElement(node);\n return el;\n}\nfunction isBlocked(node, blockClass, blockSelector, checkAncestors) {\n if (!node) {\n return false;\n }\n const el = closestElementOfNode(node);\n if (!el) {\n return false;\n }\n try {\n if (typeof blockClass === \"string\") {\n if (el.classList.contains(blockClass)) return true;\n if (checkAncestors && el.closest(\".\" + blockClass) !== null) return true;\n } else {\n if (classMatchesRegex(el, blockClass, checkAncestors)) return true;\n }\n } catch (e) {\n }\n if (blockSelector) {\n if (el.matches(blockSelector)) return true;\n if (checkAncestors && el.closest(blockSelector) !== null) return true;\n }\n return false;\n}\nfunction isSerialized(n, mirror2) {\n return mirror2.getId(n) !== -1;\n}\nfunction isIgnored(n, mirror2, slimDOMOptions) {\n if (n.tagName === \"TITLE\" && slimDOMOptions.headTitleMutations) {\n return true;\n }\n return mirror2.getId(n) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror2) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror2.getId(target);\n if (!mirror2.has(id)) {\n return true;\n }\n const parent = index.parentNode(target);\n if (parent && parent.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!parent) {\n return true;\n }\n return isAncestorRemoved(parent, mirror2);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if (\"NodeList\" in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype.forEach;\n }\n if (\"DOMTokenList\" in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype.forEach;\n }\n}\nfunction isSerializedIframe(n, mirror2) {\n return Boolean(n.nodeName === \"IFRAME\" && mirror2.getMeta(n));\n}\nfunction isSerializedStylesheet(n, mirror2) {\n return Boolean(\n n.nodeName === \"LINK\" && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute(\"rel\") === \"stylesheet\" && mirror2.getMeta(n)\n );\n}\nfunction hasShadowRoot(n) {\n if (!n) return false;\n if (n instanceof BaseRRNode && \"shadowRoot\" in n) {\n return Boolean(n.shadowRoot);\n }\n return Boolean(index.shadowRoot(n));\n}\nclass StyleSheetMirror {\n constructor() {\n __publicField(this, \"id\", 1);\n __publicField(this, \"styleIDMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"idStyleMap\", /* @__PURE__ */ new Map());\n }\n getId(stylesheet) {\n return this.styleIDMap.get(stylesheet) ?? -1;\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n /**\n * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n */\n add(stylesheet, id) {\n if (this.has(stylesheet)) return this.getId(stylesheet);\n let newId;\n if (id === void 0) {\n newId = this.id++;\n } else newId = id;\n this.styleIDMap.set(stylesheet, newId);\n this.idStyleMap.set(newId, stylesheet);\n return newId;\n }\n getStyle(id) {\n return this.idStyleMap.get(id) || null;\n }\n reset() {\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n) {\n var _a2;\n let shadowHost = null;\n if (\"getRootNode\" in n && ((_a2 = index.getRootNode(n)) == null ? void 0 : _a2.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && index.host(index.getRootNode(n)))\n shadowHost = index.host(index.getRootNode(n));\n return shadowHost;\n}\nfunction getRootShadowHost(n) {\n let rootShadowHost = n;\n let shadowHost;\n while (shadowHost = getShadowHost(rootShadowHost))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n) {\n const doc = n.ownerDocument;\n if (!doc) return false;\n const shadowHost = getRootShadowHost(n);\n return index.contains(doc, shadowHost);\n}\nfunction inDom(n) {\n const doc = n.ownerDocument;\n if (!doc) return false;\n return index.contains(doc, n) || shadowHostInDom(n);\n}\nfunction isNodeInLinkedList(n) {\n return \"__ln\" in n;\n}\nclass DoubleLinkedList {\n constructor() {\n __publicField(this, \"length\", 0);\n __publicField(this, \"head\", null);\n __publicField(this, \"tail\", null);\n }\n get(position) {\n if (position >= this.length) {\n throw new Error(\"Position outside of list range\");\n }\n let current = this.head;\n for (let index2 = 0; index2 < position; index2++) {\n current = (current == null ? void 0 : current.next) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n } else if (n.nextSibling && isNodeInLinkedList(n.nextSibling) && n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n } else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n if (node.next === null) {\n this.tail = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n } else {\n this.tail = null;\n }\n } else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n } else {\n this.tail = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n constructor() {\n __publicField(this, \"frozen\", false);\n __publicField(this, \"locked\", false);\n __publicField(this, \"texts\", []);\n __publicField(this, \"attributes\", []);\n __publicField(this, \"attributeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"removes\", []);\n __publicField(this, \"mapRemoves\", []);\n __publicField(this, \"movedMap\", {});\n /**\n * the browser MutationObserver emits multiple mutations after\n * a delay for performance reasons, making tracing added nodes hard\n * in our `processMutations` callback function.\n * For example, if we append an element el_1 into body, and then append\n * another element el_2 into el_1, these two mutations may be passed to the\n * callback function together when the two operations were done.\n * Generally we need to trace child nodes of newly added nodes, but in this\n * case if we count el_2 as el_1's child node in the first mutation record,\n * then we will count el_2 again in the second mutation record which was\n * duplicated.\n * To avoid of duplicate counting added nodes, we use a Set to store\n * added nodes and its child nodes during iterate mutation records. Then\n * collect added nodes from the Set which have no duplicate copy. But\n * this also causes newly added nodes will not be serialized with id ASAP,\n * which means all the id related calculation should be lazy too.\n */\n __publicField(this, \"addedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"movedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"droppedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"removesSubTreeCache\", /* @__PURE__ */ new Set());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"blockClass\");\n __publicField(this, \"blockSelector\");\n __publicField(this, \"maskTextClass\");\n __publicField(this, \"maskTextSelector\");\n __publicField(this, \"inlineStylesheet\");\n __publicField(this, \"maskInputOptions\");\n __publicField(this, \"maskTextFn\");\n __publicField(this, \"maskInputFn\");\n __publicField(this, \"keepIframeSrcFn\");\n __publicField(this, \"recordCanvas\");\n __publicField(this, \"inlineImages\");\n __publicField(this, \"slimDOMOptions\");\n __publicField(this, \"dataURLOptions\");\n __publicField(this, \"doc\");\n __publicField(this, \"mirror\");\n __publicField(this, \"iframeManager\");\n __publicField(this, \"stylesheetManager\");\n __publicField(this, \"shadowDomManager\");\n __publicField(this, \"canvasManager\");\n __publicField(this, \"processedNodeManager\");\n __publicField(this, \"unattachedDoc\");\n __publicField(this, \"canvasManagerReleased\", false);\n __publicField(this, \"processMutations\", (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n });\n __publicField(this, \"emit\", () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addedIds = /* @__PURE__ */ new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n const parent = index.parentNode(n);\n if (!parent || !inDom(n) || parent.tagName === \"TEXTAREA\") {\n return;\n }\n const parentId = isShadowRoot(parent) ? this.mirror.getId(getShadowHost(n)) : this.mirror.getId(parent);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n const sn = serializeNodeWithId(n, {\n doc: this.doc,\n mirror: this.mirror,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n maskTextClass: this.maskTextClass,\n maskTextSelector: this.maskTextSelector,\n skipChild: true,\n newlyAddedElement: true,\n inlineStylesheet: this.inlineStylesheet,\n maskInputOptions: this.maskInputOptions,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n dataURLOptions: this.dataURLOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isSerializedIframe(currentN, this.mirror)) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(\n currentN\n );\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(index.shadowRoot(n), this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n this.iframeManager.attachIframe(iframe, childSn);\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n onIframeListenerRegistered: (iframe, disposer) => {\n this.iframeManager.registerLoadListenerDisposer(iframe, disposer);\n },\n onStylesheetLoad: (link, childSn) => {\n this.stylesheetManager.attachLinkElement(link, childSn);\n }\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn\n });\n addedIds.add(sn.id);\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removesSubTreeCache, n, this.mirror) && !this.movedSet.has(index.parentNode(n))) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) && !isParentRemoved(this.removesSubTreeCache, n, this.mirror)) {\n pushAdd(n);\n } else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n } else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(index.parentNode(candidate.value));\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n let tailNode = addList.tail;\n while (tailNode) {\n const _node = tailNode;\n tailNode = tailNode.previous;\n if (_node) {\n const parentId = this.mirror.getId(index.parentNode(_node.value));\n const nextId = getNextId(_node.value);\n if (nextId === -1) continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n } else {\n const unhandledNode = _node.value;\n const parent = index.parentNode(unhandledNode);\n if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = index.host(parent);\n const parentId2 = this.mirror.getId(shadowHost);\n if (parentId2 !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts.map((text) => {\n const n = text.node;\n const parent = index.parentNode(n);\n if (parent && parent.tagName === \"TEXTAREA\") {\n this.genTextAreaValueMutation(parent);\n }\n return {\n id: this.mirror.getId(n),\n value: text.value\n };\n }).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes.map((attribute) => {\n const { attributes } = attribute;\n if (typeof attributes.style === \"string\") {\n const diffAsStr = JSON.stringify(attribute.styleDiff);\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n if (diffAsStr.length < attributes.style.length) {\n if ((diffAsStr + unchangedAsStr).split(\"var(\").length === attributes.style.split(\"var(\").length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes\n };\n }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds\n };\n if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.removesSubTreeCache = /* @__PURE__ */ new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n });\n __publicField(this, \"bufferBelongsToIframe\", (iframeEl) => {\n return this.doc === iframeEl.contentDocument;\n });\n __publicField(this, \"genTextAreaValueMutation\", (textarea) => {\n let item = this.attributeMap.get(textarea);\n if (!item) {\n item = {\n node: textarea,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(textarea, item);\n }\n const value = Array.from(\n index.childNodes(textarea),\n (cn) => index.textContent(cn) || \"\"\n ).join(\"\");\n item.attributes.value = maskInputValue({\n element: textarea,\n maskInputOptions: this.maskInputOptions,\n tagName: textarea.tagName,\n type: getInputType(textarea),\n value,\n maskInputFn: this.maskInputFn\n });\n });\n __publicField(this, \"processMutation\", (m) => {\n if (isIgnored(m.target, this.mirror, this.slimDOMOptions)) {\n return;\n }\n switch (m.type) {\n case \"characterData\": {\n const value = index.textContent(m.target);\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n true\n // checkAncestors\n ) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\\S]/g, \"*\") : value,\n node: m.target\n });\n }\n break;\n }\n case \"attributes\": {\n const target = m.target;\n let attributeName = m.attributeName;\n let value = m.target.getAttribute(attributeName);\n if (attributeName === \"value\") {\n const type = getInputType(target);\n value = maskInputValue({\n element: target,\n maskInputOptions: this.maskInputOptions,\n tagName: target.tagName,\n type,\n value,\n maskInputFn: this.maskInputFn\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === \"IFRAME\" && attributeName === \"src\" && !this.keepIframeSrcFn(value)) {\n if (!target.contentDocument) {\n attributeName = \"rr_src\";\n } else {\n return;\n }\n }\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(m.target, item);\n }\n if (attributeName === \"type\" && target.tagName === \"INPUT\" && (m.oldValue || \"\").toLowerCase() === \"password\") {\n target.setAttribute(\"data-rr-is-password\", \"true\");\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(\n this.doc,\n toLowerCase(target.tagName),\n toLowerCase(attributeName),\n value,\n target,\n this.dataURLOptions\n );\n if (attributeName === \"style\") {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc = document.implementation.createHTMLDocument();\n } catch (e) {\n this.unattachedDoc = this.doc;\n }\n }\n const old = this.unattachedDoc.createElement(\"span\");\n if (m.oldValue) {\n old.style.cssText = m.oldValue;\n }\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === \"\") {\n item.styleDiff[pname] = newValue;\n } else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\n } else {\n item._unchangedStyles[pname] = [newValue, newPriority];\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === \"\") {\n item.styleDiff[pname] = false;\n }\n }\n } else if (attributeName === \"open\" && target.tagName === \"DIALOG\") {\n if (target.matches(\"dialog:modal\")) {\n item.attributes[\"rr_open_mode\"] = \"modal\";\n } else {\n item.attributes[\"rr_open_mode\"] = \"non-modal\";\n }\n }\n }\n break;\n }\n case \"childList\": {\n if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\n return;\n if (m.target.tagName === \"TEXTAREA\") {\n this.genTextAreaValueMutation(m.target);\n return;\n }\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target) ? this.mirror.getId(index.host(m.target)) : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || isIgnored(n, this.mirror, this.slimDOMOptions) || !isSerialized(n, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n } else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) && this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n } else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0\n });\n processRemoves(n, this.removesSubTreeCache);\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n });\n /**\n * Make sure you check if `n`'s parent is blocked before calling this function\n * */\n __publicField(this, \"genAdds\", (n, target) => {\n if (this.processedNodeManager.inOtherBuffer(n, this)) return;\n if (this.addedSet.has(n) || this.movedSet.has(n)) return;\n if (this.mirror.hasNode(n)) {\n if (isIgnored(n, this.mirror, this.slimDOMOptions)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && this.mirror.hasNode(target)) {\n targetId = this.mirror.getId(target);\n }\n if (targetId && targetId !== -1) {\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\n }\n } else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\n index.childNodes(n).forEach((childN) => this.genAdds(childN));\n if (hasShadowRoot(n)) {\n index.childNodes(index.shadowRoot(n)).forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n);\n });\n }\n }\n });\n }\n init(options) {\n [\n \"mutationCb\",\n \"blockClass\",\n \"blockSelector\",\n \"maskTextClass\",\n \"maskTextSelector\",\n \"inlineStylesheet\",\n \"maskInputOptions\",\n \"maskTextFn\",\n \"maskInputFn\",\n \"keepIframeSrcFn\",\n \"recordCanvas\",\n \"inlineImages\",\n \"slimDOMOptions\",\n \"dataURLOptions\",\n \"doc\",\n \"mirror\",\n \"iframeManager\",\n \"stylesheetManager\",\n \"shadowDomManager\",\n \"canvasManager\",\n \"processedNodeManager\"\n ].forEach((key) => {\n this[key] = options[key];\n });\n this.canvasManager.acquire();\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.releaseCanvasManager();\n }\n // Releases at most once even if reset() runs twice (iframe pagehide + stop). Separate from\n // reset() so shadow-root teardown can release without re-entering shadowDomManager.reset().\n releaseCanvasManager() {\n if (this.canvasManagerReleased) {\n return;\n }\n this.canvasManagerReleased = true;\n this.canvasManager.reset();\n }\n bufferDoc() {\n return this.doc;\n }\n destroy() {\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n index.childNodes(n).forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction processRemoves(n, cache) {\n const queue = [n];\n while (queue.length) {\n const next = queue.pop();\n if (cache.has(next)) continue;\n cache.add(next);\n index.childNodes(next).forEach((n2) => queue.push(n2));\n }\n return;\n}\nfunction isParentRemoved(removes, n, mirror2) {\n if (removes.size === 0) return false;\n return _isParentRemoved(removes, n);\n}\nfunction _isParentRemoved(removes, n, _mirror2) {\n const node = index.parentNode(n);\n if (!node) return false;\n return removes.has(node);\n}\nfunction isAncestorInSet(set, n) {\n if (set.size === 0) return false;\n return _isAncestorInSet(set, n);\n}\nfunction _isAncestorInSet(set, n) {\n const parent = index.parentNode(n);\n if (!parent) {\n return false;\n }\n if (set.has(parent)) {\n return true;\n }\n return _isAncestorInSet(set, parent);\n}\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = void 0;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = ((...rest) => {\n try {\n return cb(...rest);\n } catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return;\n }\n throw error;\n }\n });\n return rrwebWrapped;\n};\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if (\"composedPath\" in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n } else if (\"path\" in event && event.path.length) {\n return event.path[0];\n }\n } catch {\n }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n const observer = new (mutationObserverCtor())(\n callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer))\n );\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true\n });\n return { observer, buffer: mutationBuffer };\n}\nfunction initMoveObserver({\n mousemoveCb,\n sampling,\n doc,\n mirror: mirror2\n}) {\n if (sampling.mousemove === false) {\n return () => {\n };\n }\n const threshold = typeof sampling.mousemove === \"number\" ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === \"number\" ? sampling.mousemoveCallback : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle(\n callbackWrapper(\n (source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(\n positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }),\n source\n );\n positions = [];\n timeBaseline = null;\n }\n ),\n callbackThreshold\n );\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror2.getId(target),\n timeOffset: nowTimestamp() - timeBaseline\n });\n wrappedCb(\n typeof DragEvent !== \"undefined\" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove\n );\n }),\n threshold,\n {\n trailing: false\n }\n )\n );\n const handlers = [\n on(\"mousemove\", updatePosition, doc),\n on(\"touchmove\", updatePosition, doc),\n on(\"drag\", updatePosition, doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({\n mouseInteractionCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n sampling\n}) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;\n const handlers = [];\n let currentPointerType = null;\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n let pointerType = null;\n let thisEventKey = eventKey;\n if (\"pointerType\" in event) {\n switch (event.pointerType) {\n case \"mouse\":\n pointerType = PointerTypes.Mouse;\n break;\n case \"touch\":\n pointerType = PointerTypes.Touch;\n break;\n case \"pen\":\n pointerType = PointerTypes.Pen;\n break;\n }\n if (pointerType === PointerTypes.Touch) {\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n thisEventKey = \"TouchStart\";\n } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = \"TouchEnd\";\n }\n } else if (pointerType === PointerTypes.Pen) ;\n } else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if (thisEventKey.startsWith(\"Touch\") && pointerType === PointerTypes.Touch || thisEventKey.startsWith(\"Mouse\") && pointerType === PointerTypes.Mouse) {\n pointerType = null;\n }\n } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror2.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[thisEventKey],\n id,\n x: clientX,\n y: clientY,\n ...pointerType !== null && { pointerType }\n });\n };\n };\n Object.keys(MouseInteractions).filter(\n (key) => Number.isNaN(Number(key)) && !key.endsWith(\"_Departed\") && disableMap[key] !== false\n ).forEach((eventKey) => {\n let eventName = toLowerCase(eventKey);\n const handler = getHandler(eventKey);\n if (window.PointerEvent) {\n switch (MouseInteractions[eventKey]) {\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n eventName = eventName.replace(\n \"mouse\",\n \"pointer\"\n );\n break;\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n return;\n }\n }\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({\n scrollCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n sampling\n}) {\n const lastEmitted = /* @__PURE__ */ new Map();\n const emitScrollPosition = (evt) => {\n const target = getEventTarget(evt);\n if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n const id = mirror2.getId(target);\n let x;\n let y;\n if (target === doc && doc.defaultView) {\n const scrollLeftTop = getWindowScroll(doc.defaultView);\n x = scrollLeftTop.left;\n y = scrollLeftTop.top;\n } else {\n x = target.scrollLeft;\n y = target.scrollTop;\n }\n const key = `${x},${y}`;\n if (lastEmitted.get(id) === key) {\n return;\n }\n lastEmitted.set(id, key);\n scrollCb({ id, x, y });\n };\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => emitScrollPosition(evt)),\n sampling.scroll || 100\n )\n );\n const handlers = [on(\"scroll\", updatePosition, doc)];\n if (\"onscrollend\" in doc) {\n handlers.push(on(\"scrollend\", callbackWrapper(emitScrollPosition), doc));\n }\n return () => handlers.forEach((h) => h());\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(\n throttle(\n callbackWrapper(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height)\n });\n lastH = height;\n lastW = width;\n }\n }),\n 200\n )\n );\n return on(\"resize\", updateDimension, win);\n}\nfunction findAndRemoveIframeBuffer(iframeEl, knownDocs) {\n for (let i = mutationBuffers.length - 1; i >= 0; i--) {\n const buf = mutationBuffers[i];\n if (!buf) continue;\n let match = buf.bufferBelongsToIframe(iframeEl);\n if (!match && knownDocs && knownDocs.has(buf.bufferDoc())) {\n match = true;\n }\n if (match) {\n buf.reset();\n mutationBuffers.splice(i, 1);\n }\n }\n}\nconst INPUT_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"];\nconst lastInputValueMap = /* @__PURE__ */ new WeakMap();\nfunction initInputObserver({\n inputCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n ignoreClass,\n ignoreSelector,\n maskInputOptions,\n maskInputFn,\n sampling,\n userTriggeredOnInput\n}) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const userTriggered = event.isTrusted;\n const tagName = target && target.tagName;\n if (target && tagName === \"OPTION\") {\n target = index.parentElement(target);\n }\n if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {\n return;\n }\n let text = target.value;\n let isChecked = false;\n const type = getInputType(target) || \"\";\n if (type === \"radio\" || type === \"checkbox\") {\n isChecked = target.checked;\n } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {\n text = maskInputValue({\n element: target,\n maskInputOptions,\n tagName,\n type,\n value: text,\n maskInputFn\n });\n }\n cbWithDedup(\n target,\n userTriggeredOnInput ? { text, isChecked, userTriggered } : { text, isChecked }\n );\n const name = target.name;\n if (type === \"radio\" && name && isChecked) {\n doc.querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`).forEach((el) => {\n if (el !== target) {\n const text2 = el.value;\n cbWithDedup(\n el,\n userTriggeredOnInput ? { text: text2, isChecked: !isChecked, userTriggered: false } : { text: text2, isChecked: !isChecked }\n );\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue || lastInputValue.text !== v.text || lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror2.getId(target);\n callbackWrapper(inputCb)({\n ...v,\n id\n });\n }\n }\n const events = sampling.input === \"last\" ? [\"change\"] : [\"input\", \"change\"];\n const handlers = events.map(\n (eventName) => on(eventName, callbackWrapper(eventHandler), doc)\n );\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n currentWindow.HTMLInputElement.prototype,\n \"value\"\n );\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, \"value\"],\n [currentWindow.HTMLInputElement.prototype, \"checked\"],\n [currentWindow.HTMLSelectElement.prototype, \"value\"],\n [currentWindow.HTMLTextAreaElement.prototype, \"value\"],\n // Some UI library use selectedIndex to set select value\n [currentWindow.HTMLSelectElement.prototype, \"selectedIndex\"],\n [currentWindow.HTMLOptionElement.prototype, \"selected\"]\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(\n ...hookProperties.map(\n (p) => hookSetter(\n p[0],\n p[1],\n {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false\n // userTriggered to false as this could well be programmatic\n });\n }\n },\n false,\n currentWindow\n )\n )\n );\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if (hasNestedCSSRule(\"CSSGroupingRule\") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule(\"CSSMediaRule\") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule(\"CSSSupportsRule\") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule(\"CSSConditionRule\") && childRule.parentRule instanceof CSSConditionRule) {\n const rules = Array.from(\n childRule.parentRule.cssRules\n );\n const index2 = rules.indexOf(childRule);\n pos.unshift(index2);\n return recurse(childRule.parentRule, pos);\n } else if (childRule.parentStyleSheet) {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index2 = rules.indexOf(childRule);\n pos.unshift(index2);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror2, styleMirror) {\n let id, styleId;\n if (!sheet) return {};\n if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);\n else styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => {\n };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [{ rule, index: index2 }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2 = this.cssRules.length) {\n const rule = `${selector} { ${styleBlock} }`;\n return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule, index2]);\n };\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [{ index: index2 }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n win.CSSStyleSheet.prototype.removeRule = function(index2) {\n return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index2]);\n };\n let replace;\n if (win.CSSStyleSheet.prototype.replace) {\n replace = win.CSSStyleSheet.prototype.replace;\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replace: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n let replaceSync;\n if (win.CSSStyleSheet.prototype.replaceSync) {\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replaceSync: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule(\"CSSGroupingRule\")) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n } else {\n if (canMonkeyPatchNestedCSSRule(\"CSSMediaRule\")) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSConditionRule\")) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSSupportsRule\")) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n insertRule: type.prototype.insertRule,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n deleteRule: type.prototype.deleteRule\n };\n type.prototype.insertRule = new Proxy(\n unmodifiedFunctions[typeKey].insertRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index2 || 0\n // defaults to 0\n ]\n }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n type.prototype.deleteRule = new Proxy(\n unmodifiedFunctions[typeKey].deleteRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index2] }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n replace && (win.CSSStyleSheet.prototype.replace = replace);\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initAdoptedStyleSheetObserver({\n mirror: mirror2,\n stylesheetManager\n}, host2) {\n var _a2, _b, _c;\n let hostId = null;\n if (host2.nodeName === \"#document\") hostId = mirror2.getId(host2);\n else hostId = mirror2.getId(index.host(host2));\n const patchTarget = host2.nodeName === \"#document\" ? (_a2 = host2.defaultView) == null ? void 0 : _a2.Document : (_c = (_b = host2.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;\n const originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(\n patchTarget == null ? void 0 : patchTarget.prototype,\n \"adoptedStyleSheets\"\n ) : void 0;\n if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host2, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n var _a3;\n return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);\n },\n set(sheets) {\n var _a3;\n const result = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n } catch (e) {\n }\n }\n return result;\n }\n });\n return callbackWrapper(() => {\n Object.defineProperty(host2, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n get: originalPropertyDescriptor.get,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n set: originalPropertyDescriptor.set\n });\n });\n}\nfunction initStyleDeclarationObserver({\n styleDeclarationCb,\n mirror: mirror2,\n ignoreCSSAttributes,\n stylesheetManager\n}, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n var _a2;\n const [property, value, priority] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return setProperty.apply(thisArg, [property, value, priority]);\n }\n const { id, styleId } = getIdAndStyleId(\n (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n var _a2;\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(\n (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({\n mediaInteractionCb,\n blockClass,\n blockSelector,\n mirror: mirror2,\n sampling,\n doc\n}) {\n const handler = callbackWrapper(\n (type) => throttle(\n callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n const { currentTime, volume, muted, playbackRate, loop } = target;\n mediaInteractionCb({\n type,\n id: mirror2.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate,\n loop\n });\n }),\n sampling.media || 500\n )\n );\n const handlers = [\n on(\"play\", handler(MediaInteractions.Play), doc),\n on(\"pause\", handler(MediaInteractions.Pause), doc),\n on(\"seeked\", handler(MediaInteractions.Seeked), doc),\n on(\"volumechange\", handler(MediaInteractions.VolumeChange), doc),\n on(\"ratechange\", handler(MediaInteractions.RateChange), doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => {\n };\n }\n const handlers = [];\n const fontMap = /* @__PURE__ */ new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(\n family,\n source,\n descriptors\n );\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== \"string\",\n descriptors,\n fontSource: typeof source === \"string\" ? source : JSON.stringify(Array.from(new Uint8Array(source)))\n });\n return fontFace;\n };\n const restoreHandler = patch(\n doc.fonts,\n \"add\",\n function(original) {\n return function(fontFace) {\n setTimeout(\n callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }),\n 0\n );\n return original.apply(this, [fontFace]);\n };\n }\n );\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initSelectionObserver(param) {\n const { doc, mirror: mirror2, blockClass, blockSelector, selectionCb } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i = 0; i < count; i++) {\n const range = selection.getRangeAt(i);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);\n if (blocked) continue;\n ranges.push({\n start: mirror2.getId(startContainer),\n startOffset,\n end: mirror2.getId(endContainer),\n endOffset\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on(\"selectionchange\", updateSelection);\n}\nfunction initCustomElementObserver({\n doc,\n customElementCb\n}) {\n const win = doc.defaultView;\n if (!win || !win.customElements) return () => {\n };\n const restoreHandler = patch(\n win.customElements,\n \"define\",\n function(original) {\n return function(name, constructor, options) {\n try {\n customElementCb({\n define: {\n name\n }\n });\n } catch (e) {\n console.warn(`Custom element callback failed for ${name}`);\n }\n return original.apply(this, [name, constructor, options]);\n };\n }\n );\n return restoreHandler;\n}\nfunction mergeHooks(o, hooks) {\n const {\n mutationCb,\n mousemoveCb,\n mouseInteractionCb,\n scrollCb,\n viewportResizeCb,\n inputCb,\n mediaInteractionCb,\n styleSheetRuleCb,\n styleDeclarationCb,\n canvasMutationCb,\n fontCb,\n selectionCb,\n customElementCb\n } = o;\n o.mutationCb = (...p) => {\n if (hooks.mutation) {\n hooks.mutation(...p);\n }\n mutationCb(...p);\n };\n o.mousemoveCb = (...p) => {\n if (hooks.mousemove) {\n hooks.mousemove(...p);\n }\n mousemoveCb(...p);\n };\n o.mouseInteractionCb = (...p) => {\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction(...p);\n }\n mouseInteractionCb(...p);\n };\n o.scrollCb = (...p) => {\n if (hooks.scroll) {\n hooks.scroll(...p);\n }\n scrollCb(...p);\n };\n o.viewportResizeCb = (...p) => {\n if (hooks.viewportResize) {\n hooks.viewportResize(...p);\n }\n viewportResizeCb(...p);\n };\n o.inputCb = (...p) => {\n if (hooks.input) {\n hooks.input(...p);\n }\n inputCb(...p);\n };\n o.mediaInteractionCb = (...p) => {\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction(...p);\n }\n mediaInteractionCb(...p);\n };\n o.styleSheetRuleCb = (...p) => {\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule(...p);\n }\n styleSheetRuleCb(...p);\n };\n o.styleDeclarationCb = (...p) => {\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration(...p);\n }\n styleDeclarationCb(...p);\n };\n o.canvasMutationCb = (...p) => {\n if (hooks.canvasMutation) {\n hooks.canvasMutation(...p);\n }\n canvasMutationCb(...p);\n };\n o.fontCb = (...p) => {\n if (hooks.font) {\n hooks.font(...p);\n }\n fontCb(...p);\n };\n o.selectionCb = (...p) => {\n if (hooks.selection) {\n hooks.selection(...p);\n }\n selectionCb(...p);\n };\n o.customElementCb = (...c) => {\n if (hooks.customElement) {\n hooks.customElement(...c);\n }\n customElementCb(...c);\n };\n}\nfunction initObservers(o, hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n mergeHooks(o, hooks);\n let mutationObserver;\n let mutationBuffer;\n if (o.recordDOM) {\n const result = initMutationObserver(o, o.doc);\n mutationObserver = result.observer;\n mutationBuffer = result.buffer;\n }\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o, {\n win: currentWindow\n });\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n let styleSheetObserver = () => {\n };\n let adoptedStyleSheetObserver = () => {\n };\n let styleDeclarationObserver = () => {\n };\n let fontObserver = () => {\n };\n if (o.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow\n });\n if (o.collectFonts) {\n fontObserver = initFontObserver(o);\n }\n }\n const selectionObserver = initSelectionObserver(o);\n const customElementObserver = initCustomElementObserver(o);\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(\n plugin.observer(plugin.callback, currentWindow, plugin.options)\n );\n }\n return callbackWrapper(() => {\n if (mutationBuffer) {\n mutationBuffer.destroy();\n mutationBuffer.reset();\n const index2 = mutationBuffers.indexOf(mutationBuffer);\n if (index2 !== -1) {\n mutationBuffers.splice(index2, 1);\n }\n }\n mutationObserver == null ? void 0 : mutationObserver.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n adoptedStyleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n selectionObserver();\n customElementObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== \"undefined\";\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(\n typeof window[prop] !== \"undefined\" && // Note: Generally, this check _shouldn't_ be necessary\n // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n window[prop].prototype && \"insertRule\" in window[prop].prototype && \"deleteRule\" in window[prop].prototype\n );\n}\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n __publicField(this, \"iframeIdToRemoteIdMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"iframeRemoteIdToIdMap\", /* @__PURE__ */ new WeakMap());\n this.generateIdFn = generateIdFn;\n }\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n let id = idToRemoteIdMap.get(remoteId);\n if (!id) {\n id = this.generateIdFn();\n idToRemoteIdMap.set(remoteId, id);\n remoteIdToIdMap.set(id, remoteId);\n }\n return id;\n }\n getIds(iframe, remoteId) {\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return remoteId.map(\n (id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)\n );\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== \"number\") return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId) return -1;\n return remoteId;\n }\n getRemoteIds(iframe, ids) {\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n }\n reset(iframe) {\n if (!iframe) {\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n return;\n }\n this.iframeIdToRemoteIdMap.delete(iframe);\n this.iframeRemoteIdToIdMap.delete(iframe);\n }\n getIdToRemoteIdMap(iframe) {\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n if (!idToRemoteIdMap) {\n idToRemoteIdMap = /* @__PURE__ */ new Map();\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n }\n return idToRemoteIdMap;\n }\n getRemoteIdToIdMap(iframe) {\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n if (!remoteIdToIdMap) {\n remoteIdToIdMap = /* @__PURE__ */ new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\nclass IframeManager {\n constructor(options) {\n __publicField(this, \"iframes\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"crossOriginIframeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"crossOriginIframeMirror\", new CrossOriginIframeMirror(genId));\n __publicField(this, \"crossOriginIframeStyleMirror\");\n __publicField(this, \"crossOriginIframeRootIdMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"mirror\");\n __publicField(this, \"mutationCb\");\n __publicField(this, \"wrappedEmit\");\n __publicField(this, \"loadListener\");\n __publicField(this, \"pageHideListener\");\n __publicField(this, \"stylesheetManager\");\n __publicField(this, \"recordCrossOriginIframes\");\n __publicField(this, \"messageHandler\");\n // Strong Map — keys pin Windows; every entry must be deleted on detach.\n __publicField(this, \"nestedIframeListeners\", /* @__PURE__ */ new Map());\n // Originals captured per iframe so cleanup survives iframe.src swaps.\n __publicField(this, \"attachedWindows\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"attachedDocuments\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"attachedIframes\", /* @__PURE__ */ new Map());\n // Set per element — one iframe collects multiple disposers across loads.\n __publicField(this, \"loadListenerDisposers\", /* @__PURE__ */ new WeakMap());\n // Fallback for iframes removed before first load — mirror entry is gone\n // by then, but we still need the element to dispose its load listener.\n __publicField(this, \"iframeElementsById\", /* @__PURE__ */ new Map());\n // Set per element — same multi-load reasoning as loadListenerDisposers.\n __publicField(this, \"pageHideHandlers\", /* @__PURE__ */ new WeakMap());\n this.mutationCb = options.mutationCb;\n this.wrappedEmit = options.wrappedEmit;\n this.stylesheetManager = options.stylesheetManager;\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n this.stylesheetManager.styleMirror.generateId.bind(\n this.stylesheetManager.styleMirror\n )\n );\n this.mirror = options.mirror;\n this.messageHandler = this.handleMessage.bind(this);\n if (this.recordCrossOriginIframes) {\n window.addEventListener(\"message\", this.messageHandler);\n }\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n if (iframeEl.contentWindow)\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n }\n registerLoadListenerDisposer(iframeEl, disposer) {\n let bucket = this.loadListenerDisposers.get(iframeEl);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n this.loadListenerDisposers.set(iframeEl, bucket);\n }\n bucket.add(disposer);\n const id = this.mirror.getId(iframeEl);\n if (id !== -1) this.iframeElementsById.set(id, iframeEl);\n }\n // Used by the record-loop to distinguish reparenting from removal.\n getIframeElementById(iframeId) {\n var _a2;\n return ((_a2 = this.attachedIframes.get(iframeId)) == null ? void 0 : _a2.element) ?? this.iframeElementsById.get(iframeId) ?? null;\n }\n // Drops the id mapping for a moved iframe; element-keyed state survives.\n forgetIframeId(iframeId) {\n this.attachedIframes.delete(iframeId);\n this.iframeElementsById.delete(iframeId);\n }\n disposeLoadListeners(iframeEl) {\n const bucket = this.loadListenerDisposers.get(iframeEl);\n if (!bucket) return;\n bucket.forEach((d) => callSafely(d));\n this.loadListenerDisposers.delete(iframeEl);\n }\n removePageHideListener(iframeEl) {\n const bucket = this.pageHideHandlers.get(iframeEl);\n if (!bucket) return;\n bucket.forEach(({ win, handler }) => {\n callSafely(() => win.removeEventListener(\"pagehide\", handler));\n });\n this.pageHideHandlers.delete(iframeEl);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n addPageHideListener(cb) {\n this.pageHideListener = cb;\n }\n removeLoadListener() {\n this.loadListener = void 0;\n }\n trackIframeContent(iframeEl, content) {\n const iframeId = this.mirror.getId(iframeEl);\n this.attachedIframes.set(iframeId, { element: iframeEl, content });\n return iframeId;\n }\n attachIframe(iframeEl, childSn) {\n var _a2;\n const iframeId = this.trackIframeContent(iframeEl, childSn);\n if (iframeEl.contentDocument) {\n let docs = this.attachedDocuments.get(iframeEl);\n if (!docs) {\n docs = /* @__PURE__ */ new Set();\n this.attachedDocuments.set(iframeEl, docs);\n }\n docs.add(iframeEl.contentDocument);\n }\n this.mutationCb({\n adds: [\n {\n parentId: iframeId,\n nextId: null,\n node: childSn\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n const win = iframeEl.contentWindow;\n if (this.recordCrossOriginIframes && win && !this.nestedIframeListeners.has(win)) {\n const nestedHandler = this.handleMessage.bind(this);\n callSafely(() => {\n win.addEventListener(\"message\", nestedHandler);\n this.nestedIframeListeners.set(win, nestedHandler);\n let wins = this.attachedWindows.get(iframeEl);\n if (!wins) {\n wins = /* @__PURE__ */ new Set();\n this.attachedWindows.set(iframeEl, wins);\n }\n wins.add(win);\n });\n }\n callSafely(() => {\n const pageHideWindow = iframeEl.contentWindow;\n if (!pageHideWindow) return;\n let bucket = this.pageHideHandlers.get(iframeEl);\n if (bucket) {\n for (const entry of bucket) {\n if (entry.win === pageHideWindow) return;\n }\n }\n const handler = () => {\n var _a3;\n (_a3 = this.pageHideListener) == null ? void 0 : _a3.call(this, iframeEl);\n if (iframeEl.contentDocument) {\n this.mirror.removeNodeFromMap(iframeEl.contentDocument);\n }\n if (iframeEl.contentWindow) {\n this.crossOriginIframeMap.delete(iframeEl.contentWindow);\n }\n };\n pageHideWindow.addEventListener(\"pagehide\", handler);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n this.pageHideHandlers.set(iframeEl, bucket);\n }\n bucket.add({ win: pageHideWindow, handler });\n });\n (_a2 = this.loadListener) == null ? void 0 : _a2.call(this, iframeEl);\n if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(\n iframeEl.contentDocument.adoptedStyleSheets,\n this.mirror.getId(iframeEl.contentDocument)\n );\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== \"rrweb\" || // To filter out the rrweb messages which are forwarded by some sites.\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow) return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl) return;\n const transformedEvent = this.transformCrossOriginEvent(\n iframeEl,\n crossOriginMessageEvent.data.event\n );\n if (transformedEvent)\n this.wrappedEmit(\n transformedEvent,\n crossOriginMessageEvent.data.isCheckout\n );\n }\n transformCrossOriginEvent(iframeEl, e) {\n var _a2;\n switch (e.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e.data.node, iframeEl);\n const rootId = e.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e.data.node, rootId);\n this.trackIframeContent(iframeEl, e.data.node);\n return {\n timestamp: e.timestamp,\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: e.data.node\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n }\n };\n }\n case EventType.Meta:\n case EventType.Load:\n case EventType.DomContentLoaded: {\n return false;\n }\n case EventType.Plugin: {\n return e;\n }\n case EventType.Custom: {\n this.replaceIds(\n e.data.payload,\n iframeEl,\n [\"id\", \"parentId\", \"previousId\", \"nextId\"]\n );\n return e;\n }\n case EventType.IncrementalSnapshot: {\n switch (e.data.source) {\n case IncrementalSource.Mutation: {\n e.data.adds.forEach((n) => {\n this.replaceIds(n, iframeEl, [\n \"parentId\",\n \"nextId\",\n \"previousId\"\n ]);\n this.replaceIdOnNode(n.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n.node, rootId);\n });\n e.data.removes.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"parentId\", \"id\"]);\n });\n e.data.attributes.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"id\"]);\n });\n e.data.texts.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"id\"]);\n });\n return e;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, [\"id\"]);\n });\n return e;\n }\n case IncrementalSource.ViewportResize: {\n return false;\n }\n case IncrementalSource.MediaInteraction:\n case IncrementalSource.MouseInteraction:\n case IncrementalSource.Scroll:\n case IncrementalSource.CanvasMutation:\n case IncrementalSource.Input: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n return e;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e.data, iframeEl, [\"styleId\"]);\n return e;\n }\n case IncrementalSource.Font: {\n return e;\n }\n case IncrementalSource.Selection: {\n e.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, [\"start\", \"end\"]);\n });\n return e;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e.data, iframeEl, [\"styleIds\"]);\n (_a2 = e.data.styles) == null ? void 0 : _a2.forEach((style) => {\n this.replaceStyleIds(style, iframeEl, [\"styleId\"]);\n });\n return e;\n }\n }\n }\n }\n return false;\n }\n replace(iframeMirror, obj, iframeEl, keys) {\n for (const key of keys) {\n if (!Array.isArray(obj[key]) && typeof obj[key] !== \"number\") continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(\n iframeEl,\n obj[key]\n );\n } else {\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n }\n }\n return obj;\n }\n replaceIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n }\n replaceStyleIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n }\n replaceIdOnNode(node, iframeEl) {\n this.replaceIds(node, iframeEl, [\"id\", \"rootId\"]);\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.replaceIdOnNode(child, iframeEl);\n });\n }\n }\n patchRootIdOnNode(node, rootId) {\n if (node.type !== NodeType.Document && !node.rootId) node.rootId = rootId;\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\n }\n }\n removeIframeById(iframeId) {\n const entry = this.attachedIframes.get(iframeId);\n const iframe = (entry == null ? void 0 : entry.element) || this.iframeElementsById.get(iframeId) || this.mirror.getNode(iframeId);\n this.iframeElementsById.delete(iframeId);\n if (iframe) {\n const win = iframe.contentWindow;\n const capturedWins = this.attachedWindows.get(iframe);\n if (capturedWins) {\n capturedWins.forEach((capturedWin) => {\n const handler = this.nestedIframeListeners.get(capturedWin);\n if (handler) {\n callSafely(\n () => capturedWin.removeEventListener(\"message\", handler)\n );\n this.nestedIframeListeners.delete(capturedWin);\n }\n this.crossOriginIframeMap.delete(capturedWin);\n });\n this.attachedWindows.delete(iframe);\n }\n if (win && this.nestedIframeListeners.has(win)) {\n const handler = this.nestedIframeListeners.get(win);\n callSafely(() => win.removeEventListener(\"message\", handler));\n this.nestedIframeListeners.delete(win);\n }\n if (win) {\n this.crossOriginIframeMap.delete(win);\n }\n this.iframes.delete(iframe);\n this.disposeLoadListeners(iframe);\n this.removePageHideListener(iframe);\n const capturedDocs = this.attachedDocuments.get(iframe);\n if (capturedDocs) {\n capturedDocs.forEach((doc) => {\n callSafely(() => this.mirror.removeNodeFromMap(doc));\n });\n callSafely(() => findAndRemoveIframeBuffer(iframe, capturedDocs));\n this.attachedDocuments.delete(iframe);\n }\n }\n if (entry) {\n this.attachedIframes.delete(iframeId);\n }\n }\n // Catches iframes removed inside a removed subtree (only the\n // ancestor's id appears in m.removes).\n cleanupDetachedIframes() {\n if (this.attachedIframes.size === 0) return;\n const orphaned = [];\n this.attachedIframes.forEach((_entry, iframeId) => {\n if (!this.mirror.has(iframeId)) {\n orphaned.push(iframeId);\n }\n });\n orphaned.forEach((iframeId) => this.removeIframeById(iframeId));\n }\n reattachIframes() {\n this.attachedIframes.forEach(({ content }, iframeId) => {\n if (!this.mirror.has(iframeId)) {\n this.attachedIframes.delete(iframeId);\n return;\n }\n this.mutationCb({\n adds: [\n {\n parentId: iframeId,\n nextId: null,\n node: content\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n });\n }\n destroy() {\n if (this.recordCrossOriginIframes) {\n window.removeEventListener(\"message\", this.messageHandler);\n }\n this.nestedIframeListeners.forEach((handler, contentWindow) => {\n callSafely(() => contentWindow.removeEventListener(\"message\", handler));\n });\n this.nestedIframeListeners.clear();\n const tracked = /* @__PURE__ */ new Set();\n this.iframeElementsById.forEach((el) => tracked.add(el));\n this.attachedIframes.forEach(({ element }) => tracked.add(element));\n tracked.forEach((iframe) => {\n this.disposeLoadListeners(iframe);\n this.removePageHideListener(iframe);\n });\n this.crossOriginIframeMirror.reset();\n this.crossOriginIframeStyleMirror.reset();\n this.attachedIframes.clear();\n this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();\n this.iframes = /* @__PURE__ */ new WeakMap();\n this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n this.loadListenerDisposers = /* @__PURE__ */ new WeakMap();\n this.pageHideHandlers = /* @__PURE__ */ new WeakMap();\n this.attachedDocuments = /* @__PURE__ */ new WeakMap();\n this.attachedWindows = /* @__PURE__ */ new WeakMap();\n this.iframeElementsById = /* @__PURE__ */ new Map();\n }\n}\nclass ShadowDomManager {\n constructor(options) {\n __publicField(this, \"shadowDoms\", /* @__PURE__ */ new WeakSet());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"scrollCb\");\n __publicField(this, \"bypassOptions\");\n __publicField(this, \"mirror\");\n __publicField(this, \"restoreHandlers\", []);\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n this.init();\n }\n init() {\n this.reset();\n this.patchAttachShadow(Element, document);\n }\n addShadowRoot(shadowRoot2, doc) {\n if (!isNativeShadowDom(shadowRoot2)) return;\n if (this.shadowDoms.has(shadowRoot2)) return;\n this.shadowDoms.add(shadowRoot2);\n const { observer, buffer } = initMutationObserver(\n {\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this\n },\n shadowRoot2\n );\n this.restoreHandlers.push(() => {\n observer.disconnect();\n buffer.destroy();\n buffer.releaseCanvasManager();\n const index2 = mutationBuffers.indexOf(buffer);\n if (index2 !== -1) {\n mutationBuffers.splice(index2, 1);\n }\n });\n this.restoreHandlers.push(\n initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n doc: shadowRoot2,\n mirror: this.mirror\n })\n );\n setTimeout(() => {\n if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(\n shadowRoot2.adoptedStyleSheets,\n this.mirror.getId(index.host(shadowRoot2))\n );\n this.restoreHandlers.push(\n initAdoptedStyleSheetObserver(\n {\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager\n },\n shadowRoot2\n )\n );\n }, 0);\n }\n /**\n * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n */\n observeAttachShadow(iframeElement) {\n if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;\n this.patchAttachShadow(\n iframeElement.contentWindow.Element,\n iframeElement.contentDocument\n );\n }\n /**\n * Patch 'attachShadow' to observe newly added shadow doms.\n */\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(\n patch(\n element.prototype,\n \"attachShadow\",\n function(original) {\n return function(option) {\n const sRoot = original.call(this, option);\n const shadowRootEl = index.shadowRoot(this);\n if (shadowRootEl && inDom(this))\n manager.addShadowRoot(shadowRootEl, doc);\n return sRoot;\n };\n }\n )\n );\n }\n reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n } catch (e) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n }\n}\nvar chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = \"\";\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n return base64;\n};\nconst canvasVarMap = /* @__PURE__ */ new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = canvasVarMap.get(ctx);\n if (!contextMap) {\n contextMap = /* @__PURE__ */ new Map();\n canvasVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === \"object\"))\n return;\n const name = value.constructor.name;\n const list = variableListFor(ctx, name);\n let index2 = list.indexOf(value);\n if (index2 === -1) {\n index2 = list.length;\n list.push(value);\n }\n return index2;\n};\nfunction serializeArg(value, win, ctx, dataURLOptions) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n } else if (value === null) {\n return value;\n } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)]\n };\n } else if (\n // SharedArrayBuffer disabled on most browsers due to spectre.\n // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n // value instanceof SharedArrayBuffer ||\n value instanceof ArrayBuffer\n ) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64\n };\n } else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx, dataURLOptions),\n value.byteOffset,\n value.byteLength\n ]\n };\n } else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof HTMLCanvasElement) {\n const name = \"HTMLImageElement\";\n const src = value.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.data, win, ctx, dataURLOptions),\n value.width,\n value.height\n ]\n };\n } else if (isInstanceOfWebGLObject(value, win) || typeof value === \"object\") {\n const name = value.constructor.name;\n const index2 = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index: index2\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx, dataURLOptions) => {\n return args.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n \"WebGLActiveInfo\",\n \"WebGLBuffer\",\n \"WebGLFramebuffer\",\n \"WebGLProgram\",\n \"WebGLRenderbuffer\",\n \"WebGLShader\",\n \"WebGLShaderPrecisionFormat\",\n \"WebGLTexture\",\n \"WebGLUniformLocation\",\n \"WebGLVertexArrayObject\",\n // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.\n \"WebGLVertexArrayObjectOES\"\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter(\n (name) => typeof win[name] === \"function\"\n );\n return Boolean(\n supportedWebGLConstructorNames.find(\n (name) => value instanceof win[name]\n )\n );\n};\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector, dataURLOptions) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(\n win.CanvasRenderingContext2D.prototype\n );\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n win.CanvasRenderingContext2D.prototype,\n prop,\n function(original) {\n return function(...args) {\n if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\n setTimeout(() => {\n const recordArgs = serializeArgs(\n args,\n win,\n this,\n dataURLOptions\n );\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: recordArgs\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(\n win.CanvasRenderingContext2D.prototype,\n prop,\n {\n set(v) {\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: [v],\n setter: true\n });\n }\n }\n );\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nconst WEBGL_CONTEXT_NAMES = [\"webgl\", \"webgl2\"];\nfunction getNormalizedContextName(contextType) {\n return contextType === \"experimental-webgl\" ? \"webgl\" : contextType;\n}\nfunction getRequiredWebGPUTextureUsage(win) {\n const textureUsage = win.GPUTextureUsage;\n if (!textureUsage) {\n return null;\n }\n return textureUsage.COPY_SRC | textureUsage.RENDER_ATTACHMENT;\n}\nfunction getCanvasFromWebGPUContext(context) {\n const { canvas } = context;\n if (!canvas || typeof canvas !== \"object\") {\n return null;\n }\n return canvas;\n}\nfunction isCanvasNode(canvas) {\n return \"nodeType\" in canvas;\n}\nfunction initCanvasWebGPUContextObserver(win, blockClass, blockSelector) {\n const GPUCanvasContext = win.GPUCanvasContext;\n if (!(GPUCanvasContext == null ? void 0 : GPUCanvasContext.prototype) || typeof GPUCanvasContext.prototype.configure !== \"function\") {\n return;\n }\n return patch(\n GPUCanvasContext.prototype,\n \"configure\",\n function(original) {\n return function(configuration) {\n const canvas = getCanvasFromWebGPUContext(this);\n if (!canvas || isCanvasNode(canvas) && isBlocked(canvas, blockClass, blockSelector, true)) {\n return original.call(this, configuration);\n }\n if (isCanvasNode(canvas) && !(\"__context\" in canvas)) {\n canvas.__context = \"webgpu\";\n }\n const requiredUsage = getRequiredWebGPUTextureUsage(win);\n if (requiredUsage === null || !configuration) {\n return original.call(this, configuration);\n }\n return original.call(this, {\n ...configuration,\n // WebGPU does not implicitly keep RENDER_ATTACHMENT when usage is set,\n // so include both flags needed for drawing and snapshot reads.\n usage: typeof configuration.usage === \"number\" ? configuration.usage | requiredUsage : requiredUsage\n });\n };\n }\n );\n}\nfunction initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {\n const handlers = [];\n try {\n if (setPreserveDrawingBufferToTrue) {\n const restoreWebGPUConfigureHandler = initCanvasWebGPUContextObserver(\n win,\n blockClass,\n blockSelector\n );\n if (restoreWebGPUConfigureHandler) {\n handlers.push(restoreWebGPUConfigureHandler);\n }\n }\n const restoreHandler = patch(\n win.HTMLCanvasElement.prototype,\n \"getContext\",\n function(original) {\n return function(contextType, ...args) {\n const ctxName = getNormalizedContextName(contextType);\n if (!isBlocked(this, blockClass, blockSelector, true)) {\n if (!(\"__context\" in this)) this.__context = ctxName;\n if (setPreserveDrawingBufferToTrue && WEBGL_CONTEXT_NAMES.includes(ctxName)) {\n if (args[0] && typeof args[0] === \"object\") {\n const contextAttributes = args[0];\n if (!contextAttributes.preserveDrawingBuffer) {\n contextAttributes.preserveDrawingBuffer = true;\n }\n } else {\n args.splice(0, 1, {\n preserveDrawingBuffer: true\n });\n }\n }\n }\n return original.apply(this, [contextType, ...args]);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n console.error(\"failed to patch HTMLCanvasElement.prototype.getContext\");\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win, dataURLOptions) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n if (\n //prop.startsWith('get') || // e.g. getProgramParameter, but too risky\n [\n \"isContextLost\",\n \"canvas\",\n \"drawingBufferWidth\",\n \"drawingBufferHeight\"\n ].includes(prop)\n ) {\n continue;\n }\n try {\n if (typeof prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n prototype,\n prop,\n function(original) {\n return function(...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, this);\n if (\"tagName\" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {\n const recordArgs = serializeArgs(args, win, this, dataURLOptions);\n const mutation = {\n type,\n property: prop,\n args: recordArgs\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v],\n setter: true\n });\n }\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, dataURLOptions) {\n const handlers = [];\n if (typeof win.WebGLRenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGLRenderingContext.prototype,\n CanvasContext.WebGL,\n cb,\n blockClass,\n blockSelector,\n win,\n dataURLOptions\n )\n );\n }\n if (typeof win.WebGL2RenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGL2RenderingContext.prototype,\n CanvasContext.WebGL2,\n cb,\n blockClass,\n blockSelector,\n win,\n dataURLOptions\n )\n );\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nconst jsContent = '(function() {\\n \"use strict\";\\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\\n var lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\\n for (var i = 0; i < chars.length; i++) {\\n lookup[chars.charCodeAt(i)] = i;\\n }\\n var encode = function(arraybuffer) {\\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = \"\";\\n for (i2 = 0; i2 < len; i2 += 3) {\\n base64 += chars[bytes[i2] >> 2];\\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\\n base64 += chars[bytes[i2 + 2] & 63];\\n }\\n if (len % 3 === 2) {\\n base64 = base64.substring(0, base64.length - 1) + \"=\";\\n } else if (len % 3 === 1) {\\n base64 = base64.substring(0, base64.length - 2) + \"==\";\\n }\\n return base64;\\n };\\n const lastFingerprintMap = /* @__PURE__ */ new Map();\\n const transparentBlobMap = /* @__PURE__ */ new Map();\\n function fnv1aHash(buffer) {\\n const view = new Uint8Array(buffer);\\n let hash = 2166136261;\\n for (let i2 = 0; i2 < view.length; i2++) {\\n hash ^= view[i2];\\n hash = hash * 16777619 | 0;\\n }\\n return (hash >>> 0).toString(16);\\n }\\n async function getTransparentBlobFor(width, height, dataURLOptions) {\\n const id = `${width}-${height}`;\\n if (\"OffscreenCanvas\" in globalThis) {\\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\\n const offscreen = new OffscreenCanvas(width, height);\\n offscreen.getContext(\"2d\");\\n const blob = await offscreen.convertToBlob(dataURLOptions);\\n const arrayBuffer = await blob.arrayBuffer();\\n const base64 = encode(arrayBuffer);\\n transparentBlobMap.set(id, base64);\\n return base64;\\n } else {\\n return \"\";\\n }\\n }\\n const worker = self;\\n let reusableCanvas = null;\\n let reusableCtx = null;\\n worker.onmessage = async function(e) {\\n if (\"OffscreenCanvas\" in globalThis) {\\n const { id, bitmap, width, height, displayWidth, displayHeight, dataURLOptions } = e.data;\\n try {\\n const transparentBase64 = getTransparentBlobFor(\\n width,\\n height,\\n dataURLOptions\\n );\\n if (!reusableCanvas || reusableCanvas.width !== width || reusableCanvas.height !== height) {\\n reusableCanvas = new OffscreenCanvas(width, height);\\n reusableCtx = reusableCanvas.getContext(\"2d\");\\n }\\n reusableCtx.clearRect(0, 0, width, height);\\n reusableCtx.drawImage(bitmap, 0, 0);\\n bitmap.close();\\n const blob = await reusableCanvas.convertToBlob(dataURLOptions);\\n const type = blob.type;\\n const arrayBuffer = await blob.arrayBuffer();\\n const fingerprint = fnv1aHash(arrayBuffer);\\n if (!lastFingerprintMap.has(id)) {\\n const base642 = encode(arrayBuffer);\\n if (await transparentBase64 === base642) {\\n lastFingerprintMap.set(id, fingerprint);\\n return worker.postMessage({ id });\\n }\\n lastFingerprintMap.set(id, fingerprint);\\n worker.postMessage({ id, type, base64: base642, displayWidth, displayHeight });\\n return;\\n }\\n if (lastFingerprintMap.get(id) === fingerprint)\\n return worker.postMessage({ id });\\n const base64 = encode(arrayBuffer);\\n worker.postMessage({ id, type, base64, displayWidth, displayHeight });\\n lastFingerprintMap.set(id, fingerprint);\\n } catch {\\n worker.postMessage({ id });\\n }\\n } else {\\n e.data.bitmap.close();\\n return worker.postMessage({ id: e.data.id });\\n }\\n };\\n})();\\n//# sourceMappingURL=image-bitmap-data-url-worker-CSpkoNCs.js.map\\n';\nconst blob = typeof self !== \"undefined\" && self.Blob && new Blob([jsContent], { type: \"text/javascript;charset=utf-8\" });\nfunction WorkerWrapper(options) {\n let objURL;\n try {\n objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);\n if (!objURL) throw \"\";\n const worker = new Worker(objURL, {\n name: options == null ? void 0 : options.name\n });\n worker.addEventListener(\"error\", () => {\n (self.URL || self.webkitURL).revokeObjectURL(objURL);\n });\n return worker;\n } catch (e) {\n return new Worker(\n \"data:text/javascript;charset=utf-8,\" + encodeURIComponent(jsContent),\n {\n name: options == null ? void 0 : options.name\n }\n );\n } finally {\n objURL && (self.URL || self.webkitURL).revokeObjectURL(objURL);\n }\n}\nconst MIN_CANVAS_RESOLUTION_SCALE = 0.1;\nclass CanvasManager {\n constructor(options) {\n __publicField(this, \"pendingCanvasMutations\", /* @__PURE__ */ new Map());\n __publicField(this, \"rafStamps\", { latestId: 0, invokeId: null });\n __publicField(this, \"mirror\");\n __publicField(this, \"mutationCb\");\n __publicField(this, \"resetObservers\");\n __publicField(this, \"frozen\", false);\n __publicField(this, \"locked\", false);\n __publicField(this, \"rafIdTimestamp\", null);\n __publicField(this, \"rafIdFlush\", null);\n __publicField(this, \"refCount\", 0);\n __publicField(this, \"torndown\", false);\n __publicField(this, \"processMutation\", (target, mutation) => {\n const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n });\n const {\n sampling = \"all\",\n win,\n blockClass,\n blockSelector,\n recordCanvas,\n dataURLOptions,\n resolutionScale\n } = options;\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (recordCanvas && sampling === \"all\")\n this.initCanvasMutationObserver(\n win,\n blockClass,\n blockSelector,\n dataURLOptions\n );\n if (recordCanvas && typeof sampling === \"number\")\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\n dataURLOptions,\n resolutionScale\n });\n }\n // Shared by the main document and every iframe/shadow-root observer, so reference-count\n // teardown: a single root cleaning up must not unpatch getContext / stop the FPS loop globally.\n acquire() {\n this.refCount += 1;\n }\n reset() {\n if (this.refCount > 0) {\n this.refCount -= 1;\n }\n if (this.refCount > 0) {\n return;\n }\n this.teardown();\n }\n teardown() {\n if (this.torndown) {\n return;\n }\n this.torndown = true;\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n if (this.rafIdTimestamp !== null) {\n cancelAnimationFrame(this.rafIdTimestamp);\n this.rafIdTimestamp = null;\n }\n if (this.rafIdFlush !== null) {\n cancelAnimationFrame(this.rafIdFlush);\n this.rafIdFlush = null;\n }\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {\n if (!(\"OffscreenCanvas\" in win)) {\n return;\n }\n const scale = typeof options.resolutionScale === \"number\" && Number.isFinite(options.resolutionScale) ? Math.min(\n 1,\n Math.max(MIN_CANVAS_RESOLUTION_SCALE, options.resolutionScale)\n ) : 1;\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n true\n );\n const snapshotInProgressMap = /* @__PURE__ */ new Map();\n const worker = new WorkerWrapper();\n worker.onmessage = (e) => {\n const { id } = e.data;\n snapshotInProgressMap.set(id, false);\n if (!(\"base64\" in e.data)) return;\n const { base64, type, displayWidth, displayHeight } = e.data;\n const dw = displayWidth;\n const dh = displayHeight;\n this.mutationCb({\n id,\n type: CanvasContext[\"2D\"],\n commands: [\n {\n property: \"clearRect\",\n // wipe canvas\n args: [0, 0, dw, dh]\n },\n {\n property: \"drawImage\",\n // draws (semi-transparent) image, stretched to display size\n args: [\n {\n rr_type: \"ImageBitmap\",\n args: [\n {\n rr_type: \"Blob\",\n data: [{ rr_type: \"ArrayBuffer\", base64 }],\n type\n }\n ]\n },\n 0,\n 0,\n dw,\n dh\n ]\n }\n ],\n displayWidth: dw,\n displayHeight: dh\n });\n };\n const timeBetweenSnapshots = 1e3 / fps;\n let lastSnapshotTime = 0;\n let rafId;\n const getCanvas = () => {\n const matchedCanvas = [];\n const searchCanvas = (haystack) => {\n try {\n haystack.querySelectorAll(\"canvas\").forEach((canvas) => {\n if (!isBlocked(canvas, blockClass, blockSelector, true)) {\n matchedCanvas.push(canvas);\n }\n });\n haystack.querySelectorAll(\"*\").forEach((elem) => {\n if (elem.shadowRoot) {\n searchCanvas(elem.shadowRoot);\n }\n });\n } catch {\n }\n };\n searchCanvas(win.document);\n return matchedCanvas;\n };\n const takeCanvasSnapshots = (timestamp) => {\n if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n return;\n }\n lastSnapshotTime = timestamp;\n getCanvas().forEach(async (canvas) => {\n var _a2, _b;\n const id = this.mirror.getId(canvas);\n if (snapshotInProgressMap.get(id)) return;\n if (canvas.width === 0 || canvas.height === 0) return;\n snapshotInProgressMap.set(id, true);\n try {\n if ([\"webgl\", \"webgl2\"].includes(canvas.__context)) {\n const context = canvas.getContext(\n canvas.__context\n );\n if ((_a2 = context == null ? void 0 : context.isContextLost) == null ? void 0 : _a2.call(context)) {\n snapshotInProgressMap.set(id, false);\n return;\n }\n if (((_b = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _b.preserveDrawingBuffer) === false) {\n context.clear(context.COLOR_BUFFER_BIT);\n }\n }\n const displayWidth = canvas.clientWidth || canvas.width;\n const displayHeight = canvas.clientHeight || canvas.height;\n const captureWidth = Math.max(1, Math.round(displayWidth * scale));\n const captureHeight = Math.max(1, Math.round(displayHeight * scale));\n const bitmap = await createImageBitmap(\n canvas,\n // only ask for a quality resampling filter when we're actually downscaling;\n // at full resolution this keeps capture identical to before.\n scale < 1 ? {\n resizeWidth: captureWidth,\n resizeHeight: captureHeight,\n resizeQuality: \"medium\"\n } : { resizeWidth: captureWidth, resizeHeight: captureHeight }\n );\n worker.postMessage(\n {\n id,\n bitmap,\n width: captureWidth,\n height: captureHeight,\n displayWidth,\n displayHeight,\n dataURLOptions: options.dataURLOptions\n },\n [bitmap]\n );\n } catch {\n snapshotInProgressMap.set(id, false);\n }\n });\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n };\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n this.resetObservers = () => {\n canvasContextReset();\n cancelAnimationFrame(rafId);\n };\n }\n initCanvasMutationObserver(win, blockClass, blockSelector, dataURLOptions) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n false\n );\n const canvas2DReset = initCanvas2DMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector,\n dataURLOptions\n );\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector,\n dataURLOptions\n );\n this.resetObservers = () => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n }\n startPendingCanvasMutationFlusher() {\n this.rafIdFlush = requestAnimationFrame(\n () => this.flushPendingCanvasMutations()\n );\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n };\n this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach(\n (_values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n }\n );\n this.rafIdFlush = requestAnimationFrame(\n () => this.flushPendingCanvasMutations()\n );\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1) return;\n const values = valuesWithType.map((value) => {\n const { type: type2, ...rest } = value;\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\nclass StylesheetManager {\n constructor(options) {\n __publicField(this, \"trackedLinkElements\", /* @__PURE__ */ new WeakSet());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"adoptedStyleSheetCb\");\n __publicField(this, \"styleMirror\", new StyleSheetMirror());\n this.mutationCb = options.mutationCb;\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n }\n attachLinkElement(linkEl, childSn) {\n if (\"_cssText\" in childSn.attributes)\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: childSn.id,\n attributes: childSn.attributes\n }\n ]\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl)) return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0) return;\n const adoptedStyleSheetData = {\n id: hostId,\n styleIds: []\n };\n const styles = [];\n for (const sheet of sheets) {\n let styleId;\n if (!this.styleMirror.has(sheet)) {\n styleId = this.styleMirror.add(sheet);\n styles.push({\n styleId,\n rules: Array.from(sheet.rules || CSSRule, (r, index2) => ({\n rule: stringifyRule(r, sheet.href),\n index: index2\n }))\n });\n } else styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n resetStylesheetLoadTracking();\n }\n // TODO: take snapshot on stylesheet reload by applying event listener\n trackStylesheetInLinkElement(_linkEl) {\n }\n}\nclass ProcessedNodeManager {\n constructor() {\n __publicField(this, \"nodeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"active\", false);\n }\n inOtherBuffer(node, thisBuffer) {\n const buffers = this.nodeMap.get(node);\n return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);\n }\n add(node, buffer) {\n if (!this.active) {\n this.active = true;\n requestAnimationFrame(() => {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));\n }\n destroy() {\n }\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nlet canvasManager;\nlet recording = false;\ntry {\n if (Array.from([1], (x) => x * 2)[0] !== 2) {\n const cleanFrame = document.createElement(\"iframe\");\n document.body.appendChild(cleanFrame);\n Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;\n document.body.removeChild(cleanFrame);\n }\n} catch (err) {\n console.debug(\"Unable to override Array.from\", err);\n}\nconst mirror = createMirror();\nfunction record(options = {}) {\n const {\n emit,\n checkoutEveryNms,\n checkoutEveryNth,\n blockClass = \"rr-block\",\n blockSelector = null,\n ignoreClass = \"rr-ignore\",\n ignoreSelector = null,\n maskTextClass = \"rr-mask\",\n maskTextSelector = null,\n inlineStylesheet = true,\n maskAllInputs,\n maskInputOptions: _maskInputOptions,\n slimDOMOptions: _slimDOMOptions,\n maskInputFn,\n maskTextFn,\n hooks,\n packFn,\n sampling = {},\n dataURLOptions: _dataURLOptions = {},\n canvasResolutionScale,\n mousemoveWait,\n recordDOM = true,\n recordCanvas = false,\n recordCrossOriginIframes = false,\n recordAfter = options.recordAfter === \"DOMContentLoaded\" ? options.recordAfter : \"load\",\n userTriggeredOnInput = false,\n collectFonts = false,\n inlineImages = false,\n plugins,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([]),\n errorHandler: errorHandler2\n } = options;\n registerErrorHandler(errorHandler2);\n const dataURLOptions = {\n type: \"image/webp\",\n quality: 0.4,\n maxBase64ImageLength: 1048576,\n ..._dataURLOptions\n };\n const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n } catch (e) {\n passEmitsToParent = true;\n }\n }\n if (inEmittingFrame && !emit) {\n throw new Error(\"emit function is required\");\n }\n if (!inEmittingFrame && !passEmitsToParent) {\n return () => {\n };\n }\n if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };\n const slimDOMOptions = slimDOMDefaults(\n _slimDOMOptions !== void 0 ? _slimDOMOptions : false\n );\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const iframeObserverCleanups = /* @__PURE__ */ new Map();\n let runAndDetachIframeCleanup;\n let cleanupDetachedIframeObservers;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn && // Disable packing events which will be emitted to parent frames.\n !passEmitsToParent) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (r, isCheckout) => {\n var _a2;\n const e = r;\n e.timestamp = nowTimestamp();\n if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e.type !== EventType.FullSnapshot && !(e.type === EventType.IncrementalSnapshot && e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n emit == null ? void 0 : emit(eventProcessor(e), isCheckout);\n } else if (passEmitsToParent) {\n const message = {\n type: \"rrweb\",\n event: eventProcessor(e),\n origin: window.location.origin,\n isCheckout\n };\n window.parent.postMessage(message, \"*\");\n }\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n } else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation && e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms && e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n if (m.removes && m.removes.length > 0) {\n const addedIds = m.adds.length > 0 ? new Set(m.adds.map((add) => add.node.id)) : null;\n const addedIframeElements = /* @__PURE__ */ new Set();\n if (m.adds.length > 0) {\n for (const add of m.adds) {\n const node = mirror.getNode(add.node.id);\n if (node && node.nodeName === \"IFRAME\") {\n addedIframeElements.add(node);\n }\n }\n }\n m.removes.forEach(({ id }) => {\n if (addedIds && addedIds.has(id)) return;\n const removedIframe = iframeManager.getIframeElementById(id);\n if (removedIframe && addedIframeElements.has(removedIframe)) {\n iframeManager.forgetIframeId(id);\n return;\n }\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(id);\n iframeManager.removeIframeById(id);\n });\n cleanupDetachedIframeObservers == null ? void 0 : cleanupDetachedIframeObservers();\n iframeManager.cleanupDetachedIframes();\n }\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n ...m\n }\n });\n };\n const wrappedScrollEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Scroll,\n ...p\n }\n });\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n });\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a\n }\n });\n const stylesheetManager = new StylesheetManager({\n mutationCb: wrappedMutationEmit,\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit\n });\n const iframeManager = new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager,\n recordCrossOriginIframes,\n wrappedEmit\n });\n for (const plugin of plugins || []) {\n if (plugin.getMirror)\n plugin.getMirror({\n nodeMirror: mirror,\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror\n });\n }\n const processedNodeManager = new ProcessedNodeManager();\n canvasManager = new CanvasManager({\n recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass,\n blockSelector,\n mirror,\n sampling: sampling.canvas,\n dataURLOptions,\n resolutionScale: canvasResolutionScale\n });\n const shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n dataURLOptions,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n stylesheetManager,\n canvasManager,\n keepIframeSrcFn,\n processedNodeManager\n },\n mirror\n });\n takeFullSnapshot = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit(\n {\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight()\n }\n },\n isCheckout\n );\n stylesheetManager.reset();\n shadowDomManager.init();\n mutationBuffers.forEach((buf) => buf.lock());\n const node = snapshot(document, {\n mirror,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOM: slimDOMOptions,\n dataURLOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isSerializedIframe(n, mirror)) {\n iframeManager.addIframe(n);\n }\n if (isSerializedStylesheet(n, mirror)) {\n stylesheetManager.trackLinkElement(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(index.shadowRoot(n), document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n onIframeListenerRegistered: (iframe, disposer) => {\n iframeManager.registerLoadListenerDisposer(iframe, disposer);\n },\n onStylesheetLoad: (linkEl, childSn) => {\n stylesheetManager.attachLinkElement(linkEl, childSn);\n },\n keepIframeSrcFn\n });\n if (!node) {\n return console.warn(\"Failed to snapshot the document\");\n }\n wrappedEmit(\n {\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: getWindowScroll(window)\n }\n },\n isCheckout\n );\n mutationBuffers.forEach((buf) => buf.unlock());\n if (recordCrossOriginIframes) {\n iframeManager.reattachIframes();\n }\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n stylesheetManager.adoptStyleSheets(\n document.adoptedStyleSheets,\n mirror.getId(document)\n );\n };\n try {\n const handlers = [];\n runAndDetachIframeCleanup = (iframeId) => {\n const cleanups = iframeObserverCleanups.get(iframeId);\n if (!cleanups) return;\n cleanups.forEach((cleanup) => {\n callSafely(cleanup);\n const idx = handlers.indexOf(cleanup);\n if (idx !== -1) handlers.splice(idx, 1);\n });\n iframeObserverCleanups.delete(iframeId);\n };\n cleanupDetachedIframeObservers = () => {\n for (const [iframeId] of iframeObserverCleanups) {\n const iframe = mirror.getNode(iframeId);\n if (!iframe) {\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n continue;\n }\n try {\n if (!iframe.contentDocument || !iframe.contentDocument.defaultView) {\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n }\n } catch {\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n }\n }\n };\n const observe = (doc) => {\n var _a2;\n return callbackWrapper(initObservers)(\n {\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions\n }\n }),\n mouseInteractionCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MouseInteraction,\n ...d\n }\n }),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.ViewportResize,\n ...d\n }\n }),\n inputCb: (v) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v\n }\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p\n }\n }),\n styleSheetRuleCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r\n }\n }),\n styleDeclarationCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r\n }\n }),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Font,\n ...p\n }\n }),\n selectionCb: (p) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Selection,\n ...p\n }\n });\n },\n customElementCb: (c) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c\n }\n });\n },\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskTextClass,\n maskTextSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordDOM,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskInputFn,\n maskTextFn,\n keepIframeSrcFn,\n blockSelector,\n slimDOMOptions,\n dataURLOptions,\n mirror,\n iframeManager,\n stylesheetManager,\n shadowDomManager,\n processedNodeManager,\n canvasManager,\n ignoreCSSAttributes,\n plugins: ((_a2 = plugins == null ? void 0 : plugins.filter((p) => p.observer)) == null ? void 0 : _a2.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload\n }\n })\n }))) || []\n },\n hooks\n );\n };\n const loadListener = (iframeEl) => {\n try {\n const iframeId = mirror.getId(iframeEl);\n const cleanup = observe(iframeEl.contentDocument);\n handlers.push(cleanup);\n if (iframeId !== -1) {\n let bucket = iframeObserverCleanups.get(iframeId);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n iframeObserverCleanups.set(iframeId, bucket);\n }\n bucket.add(cleanup);\n }\n } catch (error) {\n console.warn(error);\n }\n };\n iframeManager.addLoadListener(loadListener);\n iframeManager.addPageHideListener((iframeEl) => {\n const iframeId = mirror.getId(iframeEl);\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n findAndRemoveIframeBuffer(iframeEl);\n });\n let lastFullscreenId = -1;\n const emitFullscreen = (payload) => wrappedEmit({\n type: EventType.Custom,\n data: { tag: FullscreenCustomEventTag, payload }\n });\n const emitFullscreenChange = () => {\n const doc = document;\n const fullscreenEl = doc.fullscreenElement ?? doc.webkitFullscreenElement ?? doc.mozFullScreenElement ?? doc.msFullscreenElement ?? null;\n const id = fullscreenEl ? mirror.getId(fullscreenEl) : -1;\n if (id === lastFullscreenId) return;\n if (lastFullscreenId !== -1) {\n emitFullscreen({ id: lastFullscreenId, enter: false });\n }\n lastFullscreenId = id;\n if (id !== -1) {\n emitFullscreen({ id, enter: true });\n }\n };\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n handlers.push(on(\"fullscreenchange\", emitFullscreenChange));\n handlers.push(on(\"webkitfullscreenchange\", emitFullscreenChange));\n handlers.push(on(\"mozfullscreenchange\", emitFullscreenChange));\n handlers.push(on(\"MSFullscreenChange\", emitFullscreenChange));\n recording = true;\n };\n if ([\"interactive\", \"complete\"].includes(document.readyState)) {\n init();\n } else {\n handlers.push(\n on(\"DOMContentLoaded\", () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {}\n });\n if (recordAfter === \"DOMContentLoaded\") init();\n })\n );\n handlers.push(\n on(\n \"load\",\n () => {\n wrappedEmit({\n type: EventType.Load,\n data: {}\n });\n if (recordAfter === \"load\") init();\n },\n window\n )\n );\n }\n return () => {\n handlers.forEach((h) => callSafely(h));\n processedNodeManager.destroy();\n iframeManager.removeLoadListener();\n iframeManager.destroy();\n iframeObserverCleanups.clear();\n mirror.reset();\n recording = false;\n unregisterErrorHandler();\n };\n } catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = (tag, payload) => {\n if (!recording) {\n throw new Error(\"please add custom event after start recording\");\n }\n wrappedEmit({\n type: EventType.Custom,\n data: {\n tag,\n payload\n }\n });\n};\nrecord.freezePage = () => {\n mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n if (!recording) {\n throw new Error(\"please take full snapshot after start recording\");\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\nexport {\n record,\n resetMaxDepthState,\n wasMaxDepthReached\n};\n//# sourceMappingURL=rrweb-record.js.map\n","var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nclass StackFrame {\n constructor(obj) {\n __publicField(this, \"fileName\");\n __publicField(this, \"functionName\");\n __publicField(this, \"lineNumber\");\n __publicField(this, \"columnNumber\");\n this.fileName = obj.fileName || \"\";\n this.functionName = obj.functionName || \"\";\n this.lineNumber = obj.lineNumber;\n this.columnNumber = obj.columnNumber;\n }\n toString() {\n const lineNumber = this.lineNumber || \"\";\n const columnNumber = this.columnNumber || \"\";\n if (this.functionName)\n return `${this.functionName} (${this.fileName}:${lineNumber}:${columnNumber})`;\n return `${this.fileName}:${lineNumber}:${columnNumber}`;\n }\n}\nconst FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/;\nconst CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+:\\d+|\\(native\\))/m;\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code])?$/;\nconst ErrorStackParser = {\n /**\n * Given an Error object, extract the most information from it.\n */\n parse: function(error) {\n if (!error) {\n return [];\n }\n if (\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n typeof error.stacktrace !== \"undefined\" || // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n typeof error[\"opera#sourceloc\"] !== \"undefined\"\n ) {\n return this.parseOpera(\n error\n );\n } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {\n return this.parseV8OrIE(error);\n } else if (error.stack) {\n return this.parseFFOrSafari(error);\n } else {\n return [];\n }\n },\n // Separate line and column numbers from a string of the form: (URI:Line:Column)\n extractLocation: function(urlLike) {\n if (urlLike.indexOf(\":\") === -1) {\n return [urlLike];\n }\n const regExp = /(.+?)(?::(\\d+))?(?::(\\d+))?$/;\n const parts = regExp.exec(urlLike.replace(/[()]/g, \"\"));\n if (!parts) throw new Error(`Cannot parse given url: ${urlLike}`);\n return [parts[1], parts[2] || void 0, parts[3] || void 0];\n },\n parseV8OrIE: function(error) {\n const filtered = error.stack.split(\"\\n\").filter(function(line) {\n return !!line.match(CHROME_IE_STACK_REGEXP);\n }, this);\n return filtered.map(function(line) {\n if (line.indexOf(\"(eval \") > -1) {\n line = line.replace(/eval code/g, \"eval\").replace(/(\\(eval at [^()]*)|(\\),.*$)/g, \"\");\n }\n let sanitizedLine = line.replace(/^\\s+/, \"\").replace(/\\(eval code/g, \"(\");\n const location = sanitizedLine.match(/ (\\((.+):(\\d+):(\\d+)\\)$)/);\n sanitizedLine = location ? sanitizedLine.replace(location[0], \"\") : sanitizedLine;\n const tokens = sanitizedLine.split(/\\s+/).slice(1);\n const locationParts = this.extractLocation(\n location ? location[1] : tokens.pop()\n );\n const functionName = tokens.join(\" \") || void 0;\n const fileName = [\"eval\", \"<anonymous>\"].indexOf(locationParts[0]) > -1 ? void 0 : locationParts[0];\n return new StackFrame({\n functionName,\n fileName,\n lineNumber: locationParts[1],\n columnNumber: locationParts[2]\n });\n }, this);\n },\n parseFFOrSafari: function(error) {\n const filtered = error.stack.split(\"\\n\").filter(function(line) {\n return !line.match(SAFARI_NATIVE_CODE_REGEXP);\n }, this);\n return filtered.map(function(line) {\n if (line.indexOf(\" > eval\") > -1) {\n line = line.replace(\n / line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g,\n \":$1\"\n );\n }\n if (line.indexOf(\"@\") === -1 && line.indexOf(\":\") === -1) {\n return new StackFrame({\n functionName: line\n });\n } else {\n const functionNameRegex = /((.*\".+\"[^@]*)?[^@]*)(?:@)/;\n const matches = line.match(functionNameRegex);\n const functionName = matches && matches[1] ? matches[1] : void 0;\n const locationParts = this.extractLocation(\n line.replace(functionNameRegex, \"\")\n );\n return new StackFrame({\n functionName,\n fileName: locationParts[0],\n lineNumber: locationParts[1],\n columnNumber: locationParts[2]\n });\n }\n }, this);\n },\n parseOpera: function(e) {\n if (!e.stacktrace || e.message.indexOf(\"\\n\") > -1 && e.message.split(\"\\n\").length > e.stacktrace.split(\"\\n\").length) {\n return this.parseOpera9(e);\n } else if (!e.stack) {\n return this.parseOpera10(e);\n } else {\n return this.parseOpera11(e);\n }\n },\n parseOpera9: function(e) {\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n const lines = e.message.split(\"\\n\");\n const result = [];\n for (let i = 2, len = lines.length; i < len; i += 2) {\n const match = lineRE.exec(lines[i]);\n if (match) {\n result.push(\n new StackFrame({\n fileName: match[2],\n lineNumber: parseFloat(match[1])\n })\n );\n }\n }\n return result;\n },\n parseOpera10: function(e) {\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n const lines = e.stacktrace.split(\"\\n\");\n const result = [];\n for (let i = 0, len = lines.length; i < len; i += 2) {\n const match = lineRE.exec(lines[i]);\n if (match) {\n result.push(\n new StackFrame({\n functionName: match[3] || void 0,\n fileName: match[2],\n lineNumber: parseFloat(match[1])\n })\n );\n }\n }\n return result;\n },\n // Opera 10.65+ Error.stack very similar to FF/Safari\n parseOpera11: function(error) {\n const filtered = error.stack.split(\"\\n\").filter(function(line) {\n return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);\n }, this);\n return filtered.map(function(line) {\n const tokens = line.split(\"@\");\n const locationParts = this.extractLocation(tokens.pop());\n const functionCall = tokens.shift() || \"\";\n const functionName = functionCall.replace(/<anonymous function(: (\\w+))?>/, \"$2\").replace(/\\([^)]*\\)/g, \"\") || void 0;\n return new StackFrame({\n functionName,\n fileName: locationParts[0],\n lineNumber: locationParts[1],\n columnNumber: locationParts[2]\n });\n }, this);\n }\n};\nfunction pathToSelector(node) {\n if (!node || !node.outerHTML) {\n return \"\";\n }\n let path = \"\";\n while (node.parentElement) {\n let name = node.localName;\n if (!name) {\n break;\n }\n name = name.toLowerCase();\n const parent = node.parentElement;\n const domSiblings = [];\n if (parent.children && parent.children.length > 0) {\n for (let i = 0; i < parent.children.length; i++) {\n const sibling = parent.children[i];\n if (sibling.localName && sibling.localName.toLowerCase) {\n if (sibling.localName.toLowerCase() === name) {\n domSiblings.push(sibling);\n }\n }\n }\n }\n if (domSiblings.length > 1) {\n name += `:eq(${domSiblings.indexOf(node)})`;\n }\n path = name + (path ? \">\" + path : \"\");\n node = parent;\n }\n return path;\n}\nfunction isArray(obj) {\n return Array.isArray(obj);\n}\nfunction isObject(obj) {\n return typeof obj === \"object\" && obj !== null && !isArray(obj);\n}\nfunction isObjTooDeep(obj, limit) {\n if (limit === 0) {\n return true;\n }\n const keys = Object.keys(obj);\n for (const key of keys) {\n if (isObject(obj[key]) && isObjTooDeep(obj[key], limit - 1)) {\n return true;\n }\n }\n return false;\n}\nfunction stringify(obj, stringifyOptions) {\n const options = {\n numOfKeysLimit: 50,\n depthOfLimit: 4\n };\n Object.assign(options, stringifyOptions);\n const stack = [];\n const keys = [];\n return JSON.stringify(\n obj,\n function(key, value) {\n if (stack.length > 0) {\n const thisPos = stack.indexOf(this);\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n if (~stack.indexOf(value)) {\n if (stack[0] === value) {\n value = \"[Circular ~]\";\n } else {\n value = \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\n }\n }\n } else {\n stack.push(value);\n }\n if (value === null) return value;\n if (value === void 0) return \"undefined\";\n if (shouldIgnore(value)) {\n return toString(value);\n }\n if (typeof value === \"bigint\") {\n return value.toString() + \"n\";\n }\n if (value instanceof Event) {\n const eventResult = {};\n for (const eventKey in value) {\n const eventValue = value[eventKey];\n if (isArray(eventValue)) {\n eventResult[eventKey] = pathToSelector(\n eventValue.length ? eventValue[0] : null\n );\n } else {\n eventResult[eventKey] = eventValue;\n }\n }\n return eventResult;\n } else if (value instanceof Node) {\n if (value instanceof HTMLElement) {\n return value ? value.outerHTML : \"\";\n }\n return value.nodeName;\n } else if (value instanceof Error) {\n return value.stack ? value.stack + \"\\nEnd of stack for Error object\" : value.name + \": \" + value.message;\n }\n return value;\n }\n );\n function shouldIgnore(_obj) {\n if (isObject(_obj) && Object.keys(_obj).length > options.numOfKeysLimit) {\n return true;\n }\n if (typeof _obj === \"function\") {\n return true;\n }\n if (isObject(_obj) && isObjTooDeep(_obj, options.depthOfLimit)) {\n return true;\n }\n return false;\n }\n function toString(_obj) {\n let str = _obj.toString();\n if (options.stringLengthLimit && str.length > options.stringLengthLimit) {\n str = `${str.slice(0, options.stringLengthLimit)}...`;\n }\n return str;\n }\n}\nconst defaultLogOptions = {\n level: [\n \"assert\",\n \"clear\",\n \"count\",\n \"countReset\",\n \"debug\",\n \"dir\",\n \"dirxml\",\n \"error\",\n \"group\",\n \"groupCollapsed\",\n \"groupEnd\",\n \"info\",\n \"log\",\n \"table\",\n \"time\",\n \"timeEnd\",\n \"timeLog\",\n \"trace\",\n \"warn\"\n ],\n lengthThreshold: 1e3,\n logger: \"console\"\n};\nfunction initLogObserver(cb, win, options) {\n const logOptions = options ? Object.assign({}, defaultLogOptions, options) : defaultLogOptions;\n const loggerType = logOptions.logger;\n if (!loggerType) {\n return () => {\n };\n }\n let logger;\n if (typeof loggerType === \"string\") {\n logger = win[loggerType];\n } else {\n logger = loggerType;\n }\n let logCount = 0;\n let inStack = false;\n const cancelHandlers = [];\n if (logOptions.level.includes(\"error\")) {\n const errorHandler = (event) => {\n const message = event.message, error = event.error;\n const trace = ErrorStackParser.parse(error).map(\n (stackFrame) => stackFrame.toString()\n );\n const payload = [stringify(message, logOptions.stringifyOptions)];\n cb({\n level: \"error\",\n trace,\n payload\n });\n };\n win.addEventListener(\"error\", errorHandler);\n cancelHandlers.push(() => {\n win.removeEventListener(\"error\", errorHandler);\n });\n const unhandledrejectionHandler = (event) => {\n let error;\n let payload;\n if (event.reason instanceof Error) {\n error = event.reason;\n payload = [\n stringify(\n `Uncaught (in promise) ${error.name}: ${error.message}`,\n logOptions.stringifyOptions\n )\n ];\n } else {\n error = new Error();\n payload = [\n stringify(\"Uncaught (in promise)\", logOptions.stringifyOptions),\n stringify(event.reason, logOptions.stringifyOptions)\n ];\n }\n const trace = ErrorStackParser.parse(error).map(\n (stackFrame) => stackFrame.toString()\n );\n cb({\n level: \"error\",\n trace,\n payload\n });\n };\n win.addEventListener(\"unhandledrejection\", unhandledrejectionHandler);\n cancelHandlers.push(() => {\n win.removeEventListener(\"unhandledrejection\", unhandledrejectionHandler);\n });\n }\n for (const levelType of logOptions.level) {\n cancelHandlers.push(replace(logger, levelType));\n }\n return () => {\n cancelHandlers.forEach((h) => h());\n };\n function replace(_logger, level) {\n if (!_logger[level]) {\n return () => {\n };\n }\n return patch(\n _logger,\n level,\n (original) => {\n return (...args) => {\n original.apply(this, args);\n if (level === \"assert\" && !!args[0]) {\n return;\n }\n if (inStack) {\n return;\n }\n inStack = true;\n try {\n const trace = ErrorStackParser.parse(new Error()).map((stackFrame) => stackFrame.toString()).splice(1);\n const argsForPayload = level === \"assert\" ? args.slice(1) : args;\n const payload = argsForPayload.map(\n (s) => stringify(s, logOptions.stringifyOptions)\n );\n logCount++;\n if (logCount < logOptions.lengthThreshold) {\n cb({\n level,\n trace,\n payload\n });\n } else if (logCount === logOptions.lengthThreshold) {\n cb({\n level: \"warn\",\n trace: [],\n payload: [\n stringify(\"The number of log records reached the threshold.\")\n ]\n });\n }\n } catch (error) {\n original(\"rrweb logger error:\", error, ...args);\n } finally {\n inStack = false;\n }\n };\n }\n );\n }\n}\nconst PLUGIN_NAME = \"rrweb/console@1\";\nconst getRecordConsolePlugin = (options) => ({\n name: PLUGIN_NAME,\n observer: initLogObserver,\n options\n});\nexport {\n PLUGIN_NAME,\n getRecordConsolePlugin\n};\n//# sourceMappingURL=rrweb-plugin-console-record.js.map\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ExternalIntegrationKind,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n SessionStartReason,\n} from '../types'\nimport type {\n ConversationsRemoteConfig,\n GetMessagesResponse,\n GetTicketsOptions,\n GetTicketsResponse,\n MarkAsReadResponse,\n RestoreFromTokenResponse,\n RequestRestoreLinkResponse,\n SendMessageResponse,\n UserProvidedTraits,\n} from '../posthog-conversations-types'\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\nimport { eventWithTime } from '../extensions/replay/types/rrweb-types'\nimport { ErrorTracking } from '@posthog/core'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis & {\n /*\n * Main PostHog instance\n */\n posthog: any\n\n /*\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n */\n __PosthogExtensions__?: PostHogExtensions\n\n /**\n * When loading remote config, we assign it to this global configuration\n * for ease of sharing it with the rest of the SDK\n */\n _POSTHOG_REMOTE_CONFIG?: Record<\n string,\n {\n config: RemoteConfig\n siteApps: SiteAppLoader[]\n }\n >\n\n /**\n * If this is set on the window, our logger will log to the console\n * for ease of debugging. Used for testing purposes only.\n *\n * @see {Config.DEBUG} from config.ts\n */\n POSTHOG_DEBUG: any\n\n // Exposed by the browser\n doNotTrack: any\n\n // See entrypoints/customizations.full.ts\n posthogCustomizations: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/exception-autocapture.ts\n *\n * @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead\n */\n posthogErrorWrappingFunctions: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrweb` instead\n */\n rrweb: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead\n */\n rrwebConsoleRecord: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead\n */\n getRecordNetworkPlugin: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/web-vitals.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead\n */\n postHogWebVitalsCallbacks: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/tracing-headers.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead\n */\n postHogTracingHeadersPatchFns: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/surveys.ts\n *\n * @deprecated use `__PosthogExtensions__.generateSurveys` instead\n */\n extendPostHogWithSurveys: any\n\n /*\n * These are used to handle our toolbar state.\n * @see {Toolbar} from extensions/toolbar.ts\n */\n ph_load_toolbar: any\n ph_load_editor: any\n ph_toolbar_state: any\n } & Record<`__$$ph_site_app_${string}`, any>\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration'\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'web-vitals-with-attribution'\n | 'recorder'\n | 'lazy-recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'logs'\n | 'conversations'\n | 'product-tours'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n | ExternalExtensionKind\n\nexport interface LazyLoadedSessionRecordingInterface {\n start: (startReason?: SessionStartReason) => void\n stop: () => void\n discard: () => void\n sessionId: string\n status: SessionRecordingStatus\n onRRwebEmit: (rawEvent: eventWithTime) => void\n log: (message: string, level: 'log' | 'warn' | 'error') => void\n sdkDebugProperties: Properties\n overrideLinkedFlag: () => void\n overrideSampling: () => void\n overrideTrigger: (triggerType: TriggerType) => void\n isStarted: boolean\n tryAddCustomEvent(tag: string, payload: any): boolean\n}\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\nexport interface LazyLoadedConversationsInterface {\n // Widget control\n show: () => void\n hide: () => void\n isVisible: () => boolean\n\n // Lifecycle\n reset: () => void\n\n // Identity verification\n setIdentity: () => void\n clearIdentity: () => void\n\n // API methods\n sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise<SendMessageResponse>\n getMessages: (ticketId?: string, after?: string) => Promise<GetMessagesResponse>\n markAsRead: (ticketId?: string) => Promise<MarkAsReadResponse>\n getTickets: (options?: GetTicketsOptions) => Promise<GetTicketsResponse>\n requestRestoreLink: (email: string) => Promise<RequestRestoreLinkResponse>\n restoreFromToken: (restoreToken: string) => Promise<RestoreFromTokenResponse>\n restoreFromUrlToken: () => Promise<RestoreFromTokenResponse | null>\n getCurrentTicketId: () => string | null\n getWidgetSessionId: () => string\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n }\n rrweb?: { record: any; version: string; wasMaxDepthReached?: () => boolean; resetMaxDepthState?: () => void }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined\n generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined\n logs?: {\n initializeLogs?: (posthog: PostHog) => any | undefined\n }\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n /**\n * @deprecated\n *\n * this was introduced briefly, it is now always a no-op and only kept for backwards compatibility\n */\n loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks']\n tracingHeadersPatchFns?: {\n _patchFetch: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n _patchXHR: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n integrations?: {\n [K in ExternalIntegrationKind]?: { start: (posthog: PostHog) => void; stop: () => void }\n }\n initSessionRecording?: (ph: PostHog) => LazyLoadedSessionRecordingInterface\n initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\n// React Native polyfills for posthog-js compatibility\nif (typeof self === 'undefined') {\n ;(global as any).self = global\n}\nif (typeof File === 'undefined') {\n ;(global as any).File = function () {}\n}\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const CompressionStream = global?.CompressionStream\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n","import { window } from './globals'\n\n// When angular patches functions they pass the above `isNativeFunction` check (at least the MutationObserver)\nexport const isAngularZonePresent = (): boolean => {\n return !!(window as any).Zone\n}\n\nexport const isDocument = (x: unknown): x is Document => {\n // eslint-disable-next-line posthog-js/no-direct-document-check\n return x instanceof Document\n}\n","import Config from '../config'\nimport { isUndefined } from '@posthog/core'\nimport { assignableWindow, window } from './globals'\nimport type { Logger } from '@posthog/core'\n\ntype CreateLoggerOptions = {\n debugEnabled?: boolean\n}\n\ntype PosthogJsLogger = Omit<Logger, 'createLogger'> & {\n _log: (level: 'debug' | 'log' | 'warn' | 'error', ...args: any[]) => void\n uninitializedWarning: (methodName: string) => void\n createLogger: (prefix: string, options?: CreateLoggerOptions) => PosthogJsLogger\n}\n\nconst _createLogger = (prefix: string, { debugEnabled }: CreateLoggerOptions = {}): PosthogJsLogger => {\n const logger: PosthogJsLogger = {\n _log: (level: 'debug' | 'log' | 'warn' | 'error', ...args: any[]) => {\n if (\n window &&\n (Config.DEBUG || assignableWindow.POSTHOG_DEBUG || debugEnabled) &&\n !isUndefined(window.console) &&\n window.console\n ) {\n const consoleLog =\n '__rrweb_original__' in window.console[level]\n ? (window.console[level] as any)['__rrweb_original__']\n : window.console[level]\n\n // eslint-disable-next-line no-console\n consoleLog(prefix, ...args)\n }\n },\n\n debug: (...args: any[]) => {\n logger._log('debug', ...args)\n },\n\n info: (...args: any[]) => {\n logger._log('log', ...args)\n },\n\n warn: (...args: any[]) => {\n logger._log('warn', ...args)\n },\n\n error: (...args: any[]) => {\n logger._log('error', ...args)\n },\n\n critical: (...args: any[]) => {\n // Critical errors are always logged to the console\n // eslint-disable-next-line no-console\n console.error(prefix, ...args)\n },\n\n uninitializedWarning: (methodName: string) => {\n logger.error(`You must initialize PostHog before calling ${methodName}`)\n },\n\n createLogger: (additionalPrefix: string, options?: CreateLoggerOptions) =>\n _createLogger(`${prefix} ${additionalPrefix}`, options),\n }\n return logger\n}\n\nexport const logger = _createLogger('[PostHog.js]')\n\nexport const createLogger = logger.createLogger\n","import { each } from './'\n\nimport { isArray, isFile, isUndefined } from '@posthog/core'\nimport { logger } from './logger'\nimport { document } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n const location = document?.createElement('a')\n if (isUndefined(location)) {\n return null\n }\n\n location.href = url\n return location\n}\n\nexport const formDataToQuery = function (formdata: Record<string, any> | FormData, arg_separator = '&'): string {\n let use_val: string\n let use_key: string\n const tph_arr: string[] = []\n\n each(formdata, function (val: File | string | undefined, key: string | undefined) {\n // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n return\n }\n\n use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n use_key = encodeURIComponent(key)\n tph_arr[tph_arr.length] = use_key + '=' + use_val\n })\n\n return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n const withoutHash: string = url.split('#')[0] || ''\n\n // Split only on the first ? to sort problem out for those with multiple ?s\n // and then remove them\n const queryParams: string = withoutHash.split(/\\?(.*)/)[1] || ''\n const cleanedQueryParams = queryParams.replace(/^\\?+/g, '')\n\n const queryParts = cleanedQueryParams.split('&')\n let keyValuePair\n\n for (let i = 0; i < queryParts.length; i++) {\n const parts = queryParts[i].split('=')\n if (parts[0] === param) {\n keyValuePair = parts\n break\n }\n }\n\n if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n return ''\n } else {\n let result = keyValuePair[1]\n try {\n result = decodeURIComponent(result)\n } catch {\n logger.error('Skipping decoding for malformed query param: ' + result)\n }\n return result.replace(/\\+/g, ' ')\n }\n}\n\n// replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,\n// including preserving malformed text in most cases\nexport const maskQueryParams = function <T extends string | undefined>(\n url: T,\n maskedParams: string[] | undefined,\n mask: string\n): T extends string ? string : undefined {\n if (!url || !maskedParams || !maskedParams.length) {\n return url as any\n }\n\n const splitHash = url.split('#')\n const withoutHash: string = splitHash[0] || ''\n const hash = splitHash[1]\n\n const splitQuery: string[] = withoutHash.split('?')\n const queryString: string = splitQuery[1]\n const urlWithoutQueryAndHash: string = splitQuery[0]\n const queryParts = (queryString || '').split('&')\n\n // use an array of strings rather than an object to preserve ordering and duplicates\n const paramStrings: string[] = []\n\n for (let i = 0; i < queryParts.length; i++) {\n const keyValuePair = queryParts[i].split('=')\n if (!isArray(keyValuePair)) {\n continue\n } else if (maskedParams.includes(keyValuePair[0])) {\n paramStrings.push(keyValuePair[0] + '=' + mask)\n } else {\n paramStrings.push(queryParts[i])\n }\n }\n\n let result = urlWithoutQueryAndHash\n if (queryString != null) {\n result += '?' + paramStrings.join('&')\n }\n if (hash != null) {\n result += '#' + hash\n }\n\n return result as any\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n const matches = hash.match(new RegExp(param + '=([^&]*)'))\n return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n return localDomains.includes(location.hostname)\n}\n","import { PostHogConfig, Properties } from '../types'\nimport { logger } from './logger'\nimport { isFormData, isNullish, isNumber, isString, hasOwnProperty, isArray } from '@posthog/core'\n\nexport function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined {\n for (let i = 0; i < value.length; i++) {\n if (predicate(value[i])) {\n return value[i]\n }\n }\n return undefined\n}\n\nexport function eachArray<E = any>(obj: E[] | null | undefined, iterator: (value: E, key: number) => void): void {\n if (isArray(obj)) {\n obj.forEach(iterator)\n }\n}\n\nexport function each(obj: any, iterator: (value: any, key: any) => void): void {\n if (isNullish(obj)) {\n return\n }\n if (isArray(obj)) {\n obj.forEach(iterator)\n return\n }\n if (isFormData(obj)) {\n obj.forEach((val: any, key: any) => iterator(val, key))\n return\n }\n for (const key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n iterator(obj[key], key)\n }\n }\n}\n\nexport const extend = function (obj: Record<string, any>, ...args: Record<string, any>[]): Record<string, any> {\n for (const source of args) {\n for (const prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop]\n }\n }\n }\n return obj\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries<T = any>(obj: Record<string, T>): [string, T][] {\n const ownProps = Object.keys(obj)\n let i = ownProps.length\n const resArray = new Array(i) // preallocate the Array\n\n while (i--) {\n resArray[i] = [ownProps[i], obj[ownProps[i]]]\n }\n return resArray\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n try {\n return fn()\n } catch {\n return undefined\n }\n}\n\nexport const safewrap = function <F extends (...args: any[]) => any = (...args: any[]) => any>(f: F): F {\n return function (...args) {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return f.apply(this, args)\n } catch (e) {\n logger.critical(\n 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n )\n logger.critical(e)\n }\n } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n for (let i = 0; i < functions.length; i++) {\n klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n const ret: Properties = {}\n each(p, function (v, k) {\n if ((isString(v) && v.length > 0) || isNumber(v)) {\n ret[k] = v\n }\n })\n return ret\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy<T extends Record<string, any> = Record<string, any>>(\n value: T,\n customizer?: <K extends keyof T = keyof T>(value: T[K], key?: K) => T[K]\n): T | undefined {\n const COPY_IN_PROGRESS_SET = new Set()\n\n function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n COPY_IN_PROGRESS_SET.add(value)\n let result: T\n\n if (isArray(value)) {\n result = [] as any as T\n eachArray(value, (it) => {\n result.push(internalDeepCircularCopy(it))\n })\n } else {\n result = {} as T\n each(value, (val, key) => {\n if (!COPY_IN_PROGRESS_SET.has(val)) {\n ;(result as any)[key] = internalDeepCircularCopy(val, key)\n }\n })\n }\n return result\n }\n return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings<T extends Record<string, any> = Record<string, any>>(\n object: T,\n maxStringLength: number\n): T {\n return deepCircularCopy(object, (value: any) => {\n if (isString(value)) {\n return (value as string).slice(0, maxStringLength)\n }\n return value\n }) as T\n}\n\n// NOTE: Update PostHogConfig docs if you change this list\n// We will not try to catch all bullets here, but we should make an effort to catch the most common ones\n// You should be highly against adding more to this list, because ultimately customers can configure\n// their `cross_subdomain_cookie` setting to anything they want.\nconst EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app']\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n const hostname = documentLocation?.hostname\n\n if (!isString(hostname)) {\n return false\n }\n // split and slice isn't a great way to match arbitrary domains,\n // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n // for the hostname\n const lastTwoParts = hostname.split('.').slice(-2).join('.')\n\n for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {\n if (lastTwoParts === excluded) {\n return false\n }\n }\n\n return true\n}\n\n// Use this instead of element.addEventListener to avoid eslint errors\n// this properly implements the default options for passive event listeners\nexport function addEventListener(\n element: Window | Document | Element | undefined,\n event: string,\n callback: EventListener,\n options?: AddEventListenerOptions\n): void {\n const { capture = false, passive = true } = options ?? {}\n\n // This is the only place where we are allowed to call this function\n // because the whole idea is that we should be calling this instead of the built-in one\n // eslint-disable-next-line posthog-js/no-add-event-listener\n element?.addEventListener(event, callback, { capture, passive })\n}\n\n/**\n * Helper to migrate deprecated config fields to new field names with appropriate warnings\n * @param config - The config object to check\n * @param newField - The new field name to use\n * @param oldField - The deprecated field name to check for\n * @param defaultValue - The default value if neither field is set\n * @param loggerInstance - Optional logger instance for deprecation warnings\n * @returns The value to use (new field takes precedence over old field)\n */\nexport function migrateConfigField<T>(\n config: Record<string, any>,\n newField: string,\n oldField: string,\n defaultValue: T,\n loggerInstance?: { warn: (message: string) => void }\n): T {\n const hasNewField = newField in config && !isNullish(config[newField])\n const hasOldField = oldField in config && !isNullish(config[oldField])\n\n if (hasNewField) {\n return config[newField]\n }\n\n if (hasOldField) {\n if (loggerInstance) {\n loggerInstance.warn(\n `Config field '${oldField}' is deprecated. Please use '${newField}' instead. ` +\n `The old field will be removed in a future major version.`\n )\n }\n return config[oldField]\n }\n\n return defaultValue\n}\n\nconst TOOLBAR_INTERNAL_INSTANCE_NAME = 'ph_toolbar_internal'\n\nexport function isToolbarInstance(config: Pick<PostHogConfig, 'name'>): boolean {\n return config.name === TOOLBAR_INTERNAL_INSTANCE_NAME\n}\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\nimport { isFunction } from '@posthog/core'\n\nexport function patch(\n source: { [key: string]: any },\n name: string,\n replacement: (...args: unknown[]) => unknown\n): () => void {\n try {\n if (!(name in source)) {\n return () => {\n //\n }\n }\n\n const original = source[name] as () => unknown\n const wrapped = replacement(original)\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (isFunction(wrapped)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n wrapped.prototype = wrapped.prototype || {}\n Object.defineProperties(wrapped, {\n __posthog_wrapped__: {\n enumerable: false,\n value: true,\n },\n })\n }\n\n source[name] = wrapped\n\n return () => {\n if (source[name] === wrapped) {\n source[name] = original\n }\n }\n } catch {\n return () => {\n //\n }\n // This can throw when multiple instrumentation layers try to wrap the same global object,\n // such as XMLHttpRequest, and redefine the same non-configurable wrapper marker.\n }\n}\n","import { NetworkRecordOptions } from '../../../types'\n\nfunction hostnameFromURL(url: string | URL | RequestInfo): string | null {\n try {\n if (typeof url === 'string') {\n return new URL(url).hostname\n }\n if ('url' in url) {\n return new URL(url.url).hostname\n }\n return url.hostname\n } catch {\n return null\n }\n}\n\nexport function isHostOnDenyList(url: string | URL | Request, options: NetworkRecordOptions) {\n const hostname = hostnameFromURL(url)\n const defaultNotDenied = { hostname, isHostDenied: false }\n\n if (!options.payloadHostDenyList?.length || !hostname?.trim().length) {\n return defaultNotDenied\n }\n\n for (const deny of options.payloadHostDenyList) {\n if (hostname.endsWith(deny)) {\n return { hostname, isHostDenied: true }\n }\n }\n\n return defaultNotDenied\n}\n","import { CapturedNetworkRequest, NetworkRecordOptions, PostHogConfig } from '../../../types'\nimport { isFunction, isNullish, isString, isUndefined } from '@posthog/core'\nimport { convertToURL } from '../../../utils/request-utils'\nimport { logger } from '../../../utils/logger'\nimport { shouldCaptureValue } from '../../../autocapture-utils'\nimport { each } from '../../../utils'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\n\nconst REDACTED = 'redacted'\n\nexport const defaultNetworkOptions: Required<NetworkRecordOptions> = {\n initiatorTypes: [\n 'audio',\n 'beacon',\n 'body',\n 'css',\n 'early-hint',\n 'embed',\n 'fetch',\n 'frame',\n 'iframe',\n 'icon',\n 'image',\n 'img',\n 'input',\n 'link',\n 'navigation',\n 'object',\n 'ping',\n 'script',\n 'track',\n 'video',\n 'xmlhttprequest',\n ],\n maskRequestFn: (data: CapturedNetworkRequest) => data,\n recordHeaders: false,\n recordBody: false,\n recordInitialRequests: false,\n recordPerformance: false,\n performanceEntryTypeToObserve: [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n ],\n payloadSizeLimitBytes: 1000000,\n payloadHostDenyList: [\n '.lr-ingest.io',\n '.ingest.sentry.io',\n '.clarity.ms',\n // NB no leading dot here\n // GA4/gtag beacons go to *.google-analytics.com; with Google Signals on they also hit\n // analytics.google.com (region1.analytics.google.com/g/collect), so deny both\n 'google-analytics.com',\n 'analytics.google.com',\n // New Relic browser agent (bam + bam-cell)\n 'nr-data.net',\n // Datadog browser RUM intake\n 'datadoghq.com',\n 'datadoghq.eu',\n 'ddog-gov.com',\n // other third-party analytics / session-replay vendors whose telemetry has no replay value\n 'segment.io',\n 'rudderstack.com',\n 'amplitude.com',\n 'mixpanel.com',\n // Hotjar uses both .com and .io for data collection\n 'hotjar.com',\n 'hotjar.io',\n 'fullstory.com',\n ],\n}\n\nconst HEADER_DENY_LIST = [\n 'authorization',\n 'x-forwarded-for',\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'x-api-key',\n 'x-real-ip',\n 'remote-addr',\n 'forwarded',\n 'proxy-authorization',\n 'x-csrf-token',\n 'x-csrftoken',\n 'x-xsrf-token',\n]\n\nconst PAYLOAD_CONTENT_DENY_LIST = [\n 'password',\n 'secret',\n 'passwd',\n 'api_key',\n 'apikey',\n 'auth',\n 'credentials',\n 'mysql_pwd',\n 'privatekey',\n 'private_key',\n 'token',\n]\n\n// we always remove headers on the deny list because we never want to capture this sensitive data\nconst removeAuthorizationHeader = (data: CapturedNetworkRequest): CapturedNetworkRequest => {\n const headers = data.requestHeaders\n if (!isNullish(headers)) {\n each(Object.keys(headers ?? {}), (header) => {\n if (HEADER_DENY_LIST.includes(header.toLowerCase())) {\n headers[header] = REDACTED\n }\n })\n }\n return data\n}\n\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', '/e/', '/i/']\n// want to ignore posthog paths when capturing requests, or we can get trapped in a loop\n// because calls to PostHog would be reported using a call to PostHog which would be reported....\nconst ignorePostHogPaths = (\n data: CapturedNetworkRequest,\n apiHostConfig: PostHogConfig['api_host']\n): CapturedNetworkRequest | undefined => {\n const url = convertToURL(data.name)\n\n // we need to account for api host config as e.g. pathname could be /ingest/s/ and we want to ignore that\n let replaceValue = apiHostConfig.indexOf('http') === 0 ? convertToURL(apiHostConfig)?.pathname : apiHostConfig\n if (replaceValue === '/') {\n replaceValue = ''\n }\n const pathname = url?.pathname.replace(replaceValue || '', '')\n\n if (url && pathname && POSTHOG_PATHS_TO_IGNORE.some((path) => pathname.indexOf(path) === 0)) {\n return undefined\n }\n return data\n}\n\nfunction estimateBytes(payload: string): number {\n return new Blob([payload]).size\n}\n\nfunction enforcePayloadSizeLimit(\n payload: string | null | undefined,\n headers: Record<string, any> | undefined,\n limit: number,\n description: string\n): string | null | undefined {\n if (isNullish(payload)) {\n return payload\n }\n\n let requestContentLength: string | number = headers?.['content-length'] || estimateBytes(payload)\n if (isString(requestContentLength)) {\n requestContentLength = parseInt(requestContentLength)\n }\n\n if (requestContentLength > limit) {\n return LOGGER_PREFIX + ` ${description} body too large to record (${requestContentLength} bytes)`\n }\n\n return payload\n}\n\n// people can have arbitrarily large payloads on their site, but we don't want to ingest them\nconst limitPayloadSize = (\n options: NetworkRecordOptions\n): ((data: CapturedNetworkRequest | undefined) => CapturedNetworkRequest | undefined) => {\n // the smallest of 1MB or the specified limit if there is one\n const limit = Math.min(1000000, options.payloadSizeLimitBytes ?? 1000000)\n\n return (data) => {\n if (data?.requestBody) {\n data.requestBody = enforcePayloadSizeLimit(data.requestBody, data.requestHeaders, limit, 'Request')\n }\n\n if (data?.responseBody) {\n data.responseBody = enforcePayloadSizeLimit(data.responseBody, data.responseHeaders, limit, 'Response')\n }\n\n return data\n }\n}\n\nfunction scrubPayload(payload: string | null | undefined, label: 'Request' | 'Response'): string | null | undefined {\n if (isNullish(payload)) {\n return payload\n }\n let scrubbed = payload\n\n if (!shouldCaptureValue(scrubbed, false)) {\n scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED\n }\n each(PAYLOAD_CONTENT_DENY_LIST, (text) => {\n if (scrubbed?.length && scrubbed?.indexOf(text) !== -1) {\n scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED + ' as might contain: ' + text\n }\n })\n\n return scrubbed\n}\n\nfunction scrubPayloads(capturedRequest: CapturedNetworkRequest | undefined): CapturedNetworkRequest | undefined {\n if (isUndefined(capturedRequest)) {\n return undefined\n }\n\n capturedRequest.requestBody = scrubPayload(capturedRequest.requestBody, 'Request')\n capturedRequest.responseBody = scrubPayload(capturedRequest.responseBody, 'Response')\n\n return capturedRequest\n}\n\n/**\n * whether a maskRequestFn is provided or not,\n * we ensure that we remove the denied header from requests\n * we _never_ want to record that header by accident\n * if someone complains then we'll add an opt-in to let them override it\n */\nexport const buildNetworkRequestOptions = (\n instanceConfig: PostHogConfig,\n remoteNetworkOptions: Pick<\n NetworkRecordOptions,\n 'recordHeaders' | 'recordBody' | 'recordPerformance' | 'payloadHostDenyList'\n >\n): NetworkRecordOptions => {\n const config: NetworkRecordOptions = {\n payloadSizeLimitBytes: defaultNetworkOptions.payloadSizeLimitBytes,\n performanceEntryTypeToObserve: [...defaultNetworkOptions.performanceEntryTypeToObserve],\n payloadHostDenyList: [\n ...(remoteNetworkOptions.payloadHostDenyList || []),\n ...defaultNetworkOptions.payloadHostDenyList,\n ],\n }\n // client can always disable despite remote options\n const canRecordHeaders =\n instanceConfig.session_recording.recordHeaders === false ? false : remoteNetworkOptions.recordHeaders\n const canRecordBody =\n instanceConfig.session_recording.recordBody === false ? false : remoteNetworkOptions.recordBody\n const canRecordPerformance =\n instanceConfig.capture_performance === false ? false : remoteNetworkOptions.recordPerformance\n\n const payloadLimiter = limitPayloadSize(config)\n\n const enforcedCleaningFn: NetworkRecordOptions['maskRequestFn'] = (d: CapturedNetworkRequest) =>\n payloadLimiter(ignorePostHogPaths(removeAuthorizationHeader(d), instanceConfig.api_host))\n\n const hasDeprecatedMaskFunction = isFunction(instanceConfig.session_recording.maskNetworkRequestFn)\n\n if (hasDeprecatedMaskFunction && isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)) {\n logger.warn(\n 'Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.'\n )\n }\n\n if (hasDeprecatedMaskFunction) {\n instanceConfig.session_recording.maskCapturedNetworkRequestFn = (data: CapturedNetworkRequest) => {\n const cleanedURL = instanceConfig.session_recording.maskNetworkRequestFn!({ url: data.name })\n return {\n ...data,\n name: cleanedURL?.url,\n } as CapturedNetworkRequest\n }\n }\n\n config.maskRequestFn = isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)\n ? (data) => {\n const cleanedRequest = enforcedCleaningFn(data)\n return cleanedRequest\n ? (instanceConfig.session_recording.maskCapturedNetworkRequestFn?.(cleanedRequest) ?? undefined)\n : undefined\n }\n : (data) => scrubPayloads(enforcedCleaningFn(data))\n\n return {\n ...defaultNetworkOptions,\n ...config,\n recordHeaders: canRecordHeaders,\n recordBody: canRecordBody,\n recordPerformance: canRecordPerformance,\n recordInitialRequests: canRecordPerformance,\n }\n}\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n/// <reference lib=\"dom\" />\n\n// rrweb/network@1 code starts\n// most of what is below here will be removed when rrweb release their code for this\n// see https://github.com/rrweb-io/rrweb/pull/1105\n\n// NB adopted from https://github.com/rrweb-io/rrweb/pull/1105 which looks like it will be accepted into rrweb\n// however, in the PR, it throws when the performance observer data is not available\n// and assumes it is running in a browser with the Request API (i.e. not IE11)\n// copying here so that we can use it before rrweb adopt it\n\nimport type { IWindow, listenerHandler, RecordPlugin } from '../types/rrweb-types'\nimport { CapturedNetworkRequest, Headers, InitiatorType, NetworkRecordOptions } from '../../../types'\nimport {\n isArray,\n isBoolean,\n isFormData,\n isFunction,\n isNull,\n isNullish,\n isString,\n isUndefined,\n isObject,\n} from '@posthog/core'\nimport { isDocument } from '../../../utils/type-utils'\nimport { createLogger } from '../../../utils/logger'\nimport { formDataToQuery } from '../../../utils/request-utils'\nimport { patch } from '../rrweb-plugins/patch'\nimport { isHostOnDenyList } from '../../../extensions/replay/external/denylist'\nimport { defaultNetworkOptions } from './config'\n\nconst logger = createLogger('[Recorder]')\n\nexport type NetworkData = {\n requests: CapturedNetworkRequest[]\n isInitial?: boolean\n}\n\ntype networkCallback = (data: NetworkData) => void\n\nconst isNavigationTiming = (entry: PerformanceEntry): entry is PerformanceNavigationTiming =>\n entry.entryType === 'navigation'\nconst isResourceTiming = (entry: PerformanceEntry): entry is PerformanceResourceTiming => entry.entryType === 'resource'\n\ntype ObservedPerformanceEntry = (PerformanceNavigationTiming | PerformanceResourceTiming) & {\n responseStatus?: number\n}\n\nexport function findLast<T>(array: Array<T>, predicate: (value: T) => boolean): T | undefined {\n const length = array.length\n for (let i = length - 1; i >= 0; i -= 1) {\n if (predicate(array[i])) {\n return array[i]\n }\n }\n return undefined\n}\n\nfunction initPerformanceObserver(cb: networkCallback, win: IWindow, options: Required<NetworkRecordOptions>) {\n // if we are only observing timings then we could have a single observer for all types, with buffer true,\n // but we are going to filter by initiatorType _if we are wrapping fetch and xhr as the wrapped functions\n // will deal with those.\n // so we have a block which captures requests from before fetch/xhr is wrapped\n // these are marked `isInitial` so playback can display them differently if needed\n // they will never have method/status/headers/body because they are pre-wrapping that provides that\n if (options.recordInitialRequests) {\n const initialPerformanceEntries = win.performance\n .getEntries()\n .filter(\n (entry): entry is ObservedPerformanceEntry =>\n isNavigationTiming(entry) ||\n (isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType as InitiatorType))\n )\n cb({\n requests: initialPerformanceEntries.flatMap((entry) =>\n prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {}, isInitial: true })\n ),\n isInitial: true,\n })\n }\n const observer = new win.PerformanceObserver((entries) => {\n // if recordBody or recordHeaders is true then we don't want to record fetch or xhr here\n // as the wrapped functions will do that. Otherwise, this filter becomes a noop\n // because we do want to record them here\n const wrappedInitiatorFilter = (entry: ObservedPerformanceEntry) =>\n options.recordBody || options.recordHeaders\n ? entry.initiatorType !== 'xmlhttprequest' && entry.initiatorType !== 'fetch'\n : true\n\n const performanceEntries = entries.getEntries().filter(\n (entry): entry is ObservedPerformanceEntry =>\n isNavigationTiming(entry) ||\n (isResourceTiming(entry) &&\n options.initiatorTypes.includes(entry.initiatorType as InitiatorType) &&\n // TODO if we are _only_ capturing timing we don't want to filter initiator here\n wrappedInitiatorFilter(entry))\n )\n\n cb({\n requests: performanceEntries.flatMap((entry) =>\n prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {} })\n ),\n })\n })\n // compat checked earlier\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) =>\n options.performanceEntryTypeToObserve.includes(x)\n )\n // initial records are gathered above, so we don't need to observe and buffer each type separately\n observer.observe({ entryTypes })\n return () => {\n observer.disconnect()\n }\n}\n\nfunction shouldRecordHeaders(type: 'request' | 'response', recordHeaders: NetworkRecordOptions['recordHeaders']) {\n return !!recordHeaders && (isBoolean(recordHeaders) || recordHeaders[type])\n}\n\nfunction isRequest(value: unknown): value is Request {\n if (typeof Request === 'undefined') {\n return false\n }\n if (value instanceof Request) {\n return true\n }\n try {\n return Object.prototype.toString.call(value) === '[object Request]'\n } catch {\n return false\n }\n}\n\n// binary/asset bodies are large and useless for replay debugging (and capturing an image body\n// duplicates what the recording already shows), so we never record them even when recordBody is on\nexport const NEVER_RECORD_BODY_CONTENT_TYPES = [\n 'image/',\n 'video/',\n 'audio/',\n 'font/',\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'application/wasm',\n]\n\nexport function shouldRecordBody({\n type,\n recordBody,\n headers,\n url,\n}: {\n type: 'request' | 'response'\n headers: Headers\n url: string | URL | RequestInfo\n recordBody: NetworkRecordOptions['recordBody']\n}) {\n function matchesContentType(contentTypes: string[]) {\n const contentTypeHeader = Object.keys(headers).find((key) => key.toLowerCase() === 'content-type')\n const contentType = contentTypeHeader && headers[contentTypeHeader]\n return contentTypes.some((ct) => contentType?.toLowerCase().includes(ct))\n }\n\n /**\n * particularly in canvas applications we see many requests to blob URLs\n * e.g. blob:https://video_url\n * these blob/object URLs are local to the browser, we can never capture that body\n * so we can just return false here\n */\n function isBlobURL(url: string | URL | RequestInfo) {\n try {\n if (typeof url === 'string') {\n return url.startsWith('blob:')\n }\n if (url instanceof URL) {\n return url.protocol === 'blob:'\n }\n if (isRequest(url)) {\n return isBlobURL(url.url)\n }\n return false\n } catch {\n return false\n }\n }\n if (!recordBody) return false\n if (isBlobURL(url)) return false\n // never record binary/asset bodies, regardless of the recordBody setting\n if (matchesContentType(NEVER_RECORD_BODY_CONTENT_TYPES)) return false\n if (isBoolean(recordBody)) return true\n if (isArray(recordBody)) return matchesContentType(recordBody)\n const recordBodyType = recordBody[type]\n if (isBoolean(recordBodyType)) return recordBodyType\n return matchesContentType(recordBodyType)\n}\n\nasync function getRequestPerformanceEntry(\n win: IWindow,\n initiatorType: string,\n url: string,\n start?: number,\n end?: number,\n attempt = 0\n): Promise<PerformanceResourceTiming | null> {\n if (attempt > 10) {\n logger.warn('Failed to get performance entry for request', { url, initiatorType })\n return null\n }\n const urlPerformanceEntries = win.performance.getEntriesByName(url) as PerformanceResourceTiming[]\n const performanceEntry = findLast(\n urlPerformanceEntries,\n (entry) =>\n isResourceTiming(entry) &&\n entry.initiatorType === initiatorType &&\n (isUndefined(start) || entry.startTime >= start) &&\n (isUndefined(end) || entry.startTime <= end)\n )\n if (!performanceEntry) {\n await new Promise((resolve) => setTimeout(resolve, 50 * attempt))\n return getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt + 1)\n }\n return performanceEntry\n}\n\n/**\n * According to MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response\n * xhr response is typed as any but can be an ArrayBuffer, a Blob, a Document, a JavaScript object,\n * or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.\n *\n * XHR request body is Document | XMLHttpRequestBodyInit | null | undefined\n */\nfunction _tryReadXHRBody({\n body,\n options,\n url,\n}: {\n body: Document | XMLHttpRequestBodyInit | any | null | undefined\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): string | null {\n if (isNullish(body)) {\n return null\n }\n\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return hostname + ' is in deny list'\n }\n\n if (isString(body)) {\n return body\n }\n\n if (isDocument(body)) {\n return body.textContent\n }\n\n if (isFormData(body)) {\n return formDataToQuery(body)\n }\n\n if (isObject(body)) {\n try {\n return JSON.stringify(body)\n } catch {\n return '[SessionReplay] Failed to stringify response object'\n }\n }\n\n return '[SessionReplay] Cannot read body of type ' + toString.call(body)\n}\n\nfunction initXhrObserver(cb: networkCallback, win: IWindow, options: Required<NetworkRecordOptions>): listenerHandler {\n if (!options.initiatorTypes.includes('xmlhttprequest')) {\n return () => {\n //\n }\n }\n const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n const restorePatch = patch(\n win.XMLHttpRequest.prototype,\n 'open',\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n (originalOpen: typeof XMLHttpRequest.prototype.open) => {\n return function (\n method: string,\n url: string | URL,\n async = true,\n username?: string | null,\n password?: string | null\n ) {\n // because this function is returned in its actual context `this` _is_ an XMLHttpRequest\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const xhr = this as XMLHttpRequest\n\n // check IE earlier than this, we only initialize if Request is present\n // eslint-disable-next-line compat/compat\n const req = new Request(url)\n const networkRequest: Partial<CapturedNetworkRequest> = {}\n let start: number | undefined\n let end: number | undefined\n\n const requestHeaders: Headers = {}\n const originalSetRequestHeader = xhr.setRequestHeader.bind(xhr)\n xhr.setRequestHeader = (header: string, value: string) => {\n requestHeaders[header] = value\n return originalSetRequestHeader(header, value)\n }\n if (recordRequestHeaders) {\n networkRequest.requestHeaders = requestHeaders\n }\n\n const originalSend = xhr.send.bind(xhr)\n xhr.send = (body) => {\n if (\n shouldRecordBody({\n type: 'request',\n headers: requestHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.requestBody = _tryReadXHRBody({ body, options, url })\n }\n start = win.performance.now()\n return originalSend(body)\n }\n\n // Cleanup function to remove all event listeners and prevent memory leaks\n const cleanup = () => {\n xhr.removeEventListener('readystatechange', readyStateListener)\n xhr.removeEventListener('error', cleanup)\n xhr.removeEventListener('abort', cleanup)\n xhr.removeEventListener('timeout', cleanup)\n }\n\n const readyStateListener = () => {\n if (xhr.readyState !== xhr.DONE) {\n return\n }\n\n // Clean up all listeners immediately when done to prevent memory leaks\n cleanup()\n\n end = win.performance.now()\n const responseHeaders: Headers = {}\n const rawHeaders = xhr.getAllResponseHeaders()\n const headers = rawHeaders.trim().split(/[\\r\\n]+/)\n headers.forEach((line) => {\n const parts = line.split(': ')\n const header = parts.shift()\n const value = parts.join(': ')\n if (header) {\n responseHeaders[header] = value\n }\n })\n if (recordResponseHeaders) {\n networkRequest.responseHeaders = responseHeaders\n }\n if (\n shouldRecordBody({\n type: 'response',\n headers: responseHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.responseBody = _tryReadXHRBody({ body: xhr.response, options, url })\n }\n getRequestPerformanceEntry(win, 'xmlhttprequest', req.url, start, end)\n .then((entry) => {\n const requests = prepareRequest({\n entry,\n method: method,\n status: xhr?.status,\n networkRequest,\n start,\n end,\n url: url.toString(),\n initiatorType: 'xmlhttprequest',\n })\n cb({ requests })\n })\n .catch(() => {\n //\n })\n }\n\n // This is very tricky code, and making it passive won't bring many performance benefits,\n // so let's ignore the rule here.\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('readystatechange', readyStateListener)\n // Also clean up on error, abort, and timeout to prevent memory leaks\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('error', cleanup)\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('abort', cleanup)\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('timeout', cleanup)\n\n originalOpen.call(xhr, method, url.toString(), async, username, password)\n }\n }\n )\n return () => {\n restorePatch()\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry | null): event is PerformanceResourceTiming =>\n !isNull(event) && (event.entryType === 'navigation' || event.entryType === 'resource')\n\nfunction prepareRequest({\n entry,\n method,\n status,\n networkRequest,\n isInitial,\n start,\n end,\n url,\n initiatorType,\n}: {\n entry: PerformanceResourceTiming | null\n method: string | undefined\n status: number | undefined\n networkRequest: Partial<CapturedNetworkRequest>\n isInitial?: boolean\n start?: number\n end?: number\n // if there is no performance observer entry, we still need to know the url\n url?: string\n // if there is no performance observer entry, we can provide the initiatorType\n initiatorType?: string\n}): CapturedNetworkRequest[] {\n start = entry ? entry.startTime : start\n end = entry ? entry.responseEnd : end\n\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n // use timeOrigin if we really can't gather a start time\n const timestamp = Math.floor(timeOrigin + (start || 0))\n\n const entryJSON = entry ? entry.toJSON() : { name: url }\n\n const requests: CapturedNetworkRequest[] = [\n {\n ...entryJSON,\n startTime: isUndefined(start) ? undefined : Math.round(start),\n endTime: isUndefined(end) ? undefined : Math.round(end),\n timeOrigin,\n timestamp,\n method: method,\n initiatorType: initiatorType ? initiatorType : entry ? (entry.initiatorType as InitiatorType) : undefined,\n status,\n requestHeaders: networkRequest.requestHeaders,\n requestBody: networkRequest.requestBody,\n responseHeaders: networkRequest.responseHeaders,\n responseBody: networkRequest.responseBody,\n isInitial,\n },\n ]\n\n if (exposesServerTiming(entry)) {\n for (const timing of entry.serverTiming || []) {\n requests.push({\n timeOrigin,\n timestamp,\n startTime: Math.round(entry.startTime),\n name: timing.name,\n duration: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n entryType: 'serverTiming',\n })\n }\n }\n\n return requests\n}\n\nconst contentTypePrefixDenyList = ['video/', 'audio/']\n\nfunction _checkForCannotReadResponseBody({\n r,\n options,\n url,\n}: {\n r: Response\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): string | null {\n if (r.headers.get('Transfer-Encoding') === 'chunked') {\n return 'Chunked Transfer-Encoding is not supported'\n }\n\n // `get` and `has` are case-insensitive\n // but return the header value with the casing that was supplied\n const contentType = r.headers.get('Content-Type')?.toLowerCase()\n const contentTypeIsDenied = contentTypePrefixDenyList.some((prefix) => contentType?.startsWith(prefix))\n if (contentType && contentTypeIsDenied) {\n return `Content-Type ${contentType} is not supported`\n }\n\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return hostname + ' is in deny list'\n }\n\n return null\n}\n\nfunction isReadableStreamBody(body: unknown): body is ReadableStream<Uint8Array> {\n return isObject(body) && isFunction(body.getReader) && isFunction(body.tee)\n}\n\nfunction _tryReadBody(r: Request | Response): Promise<string> {\n // there are now already multiple places where we're using Promise...\n // eslint-disable-next-line compat/compat\n return new Promise((resolve) => {\n const timeout = setTimeout(() => resolve('[SessionReplay] Timeout while trying to read body'), 500)\n try {\n r.clone()\n .text()\n .then(\n (txt) => resolve(txt),\n (reason) => resolve('[SessionReplay] Failed to read body: ' + reason)\n )\n .finally(() => clearTimeout(timeout))\n } catch {\n clearTimeout(timeout)\n resolve('[SessionReplay] Failed to read body')\n }\n })\n}\n\nasync function _tryReadRequestBody({\n r,\n options,\n url,\n}: {\n r: Request\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): Promise<string> {\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return Promise.resolve(hostname + ' is in deny list')\n }\n\n return _tryReadBody(r)\n}\n\nasync function _tryReadResponseBody({\n r,\n options,\n url,\n}: {\n r: Response\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): Promise<string> {\n const cannotReadBodyReason: string | null = _checkForCannotReadResponseBody({ r, options, url })\n if (!isNull(cannotReadBodyReason)) {\n return Promise.resolve(cannotReadBodyReason)\n }\n\n return _tryReadBody(r)\n}\n\nfunction initFetchObserver(\n cb: networkCallback,\n win: IWindow,\n options: Required<NetworkRecordOptions>\n): listenerHandler {\n if (!options.initiatorTypes.includes('fetch')) {\n return () => {\n //\n }\n }\n const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const restorePatch = patch(win, 'fetch', (originalFetch: typeof fetch) => {\n return async function (url: URL | RequestInfo, init?: RequestInit | undefined) {\n // check IE earlier than this, we only initialize if Request is present\n // eslint-disable-next-line compat/compat\n const req = new Request(url, init)\n let res: Response | undefined\n const networkRequest: Partial<CapturedNetworkRequest> = {}\n let start: number | undefined\n let end: number | undefined\n\n try {\n const requestHeaders: Headers = {}\n req.headers.forEach((value: string, header: string | number) => {\n requestHeaders[header] = value\n })\n if (recordRequestHeaders) {\n networkRequest.requestHeaders = requestHeaders\n }\n // Check the caller-supplied body, not req.body: Request normalizes all non-null bodies\n // to a ReadableStream, but only an original ReadableStream would be locked by req.clone().text().\n const requestBodyIsReadableStream = isReadableStreamBody(init?.body)\n if (\n !requestBodyIsReadableStream &&\n shouldRecordBody({\n type: 'request',\n headers: requestHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.requestBody = await _tryReadRequestBody({ r: req, options, url })\n }\n\n start = win.performance.now()\n // Use `req` for recording metadata/body only. For fetch(url, init), do not pass this internally-created\n // Request downstream: it exposes request.body as a ReadableStream, and wrappers that forward that body\n // can trigger Safari's \"ReadableStream uploading is not supported\" error. For fetch(Request), we must\n // pass the cloned Request because constructing `req` may consume the original Request body.\n res = isRequest(url) ? await originalFetch(req) : await originalFetch(url, init)\n end = win.performance.now()\n\n const responseHeaders: Headers = {}\n res.headers.forEach((value: string, header: string | number) => {\n responseHeaders[header] = value\n })\n if (recordResponseHeaders) {\n networkRequest.responseHeaders = responseHeaders\n }\n if (\n shouldRecordBody({\n type: 'response',\n headers: responseHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.responseBody = await _tryReadResponseBody({ r: res, options, url })\n }\n\n return res\n } finally {\n getRequestPerformanceEntry(win, 'fetch', req.url, start, end)\n .then((entry) => {\n const requests = prepareRequest({\n entry,\n method: req.method,\n status: res?.status,\n networkRequest,\n start,\n end,\n url: req.url,\n initiatorType: 'fetch',\n })\n cb({ requests })\n })\n .catch(() => {\n //\n })\n }\n }\n })\n return () => {\n restorePatch()\n }\n}\n\nlet initialisedHandler: listenerHandler | null = null\n\nfunction initNetworkObserver(\n callback: networkCallback,\n win: IWindow, // top window or in an iframe\n options: NetworkRecordOptions\n): listenerHandler {\n if (!('performance' in win)) {\n return () => {\n //\n }\n }\n\n if (initialisedHandler) {\n logger.warn('Network observer already initialised, doing nothing')\n return () => {\n // the first caller should already have this handler and will be responsible for teardown\n }\n }\n\n const networkOptions = (\n options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions\n ) as Required<NetworkRecordOptions>\n\n const cb: networkCallback = (data) => {\n const requests: CapturedNetworkRequest[] = []\n data.requests.forEach((request) => {\n const maskedRequest = networkOptions.maskRequestFn(request)\n if (maskedRequest) {\n requests.push(maskedRequest)\n }\n })\n\n if (requests.length > 0) {\n callback({ ...data, requests })\n }\n }\n const performanceObserver = initPerformanceObserver(cb, win, networkOptions)\n\n // only wrap fetch and xhr if headers or body are being recorded\n let xhrObserver: listenerHandler = () => {}\n let fetchObserver: listenerHandler = () => {}\n if (networkOptions.recordHeaders || networkOptions.recordBody) {\n xhrObserver = initXhrObserver(cb, win, networkOptions)\n fetchObserver = initFetchObserver(cb, win, networkOptions)\n }\n\n initialisedHandler = () => {\n performanceObserver()\n xhrObserver()\n fetchObserver()\n initialisedHandler = null\n }\n return initialisedHandler\n}\n\n// use the plugin name so that when this functionality is adopted into rrweb\n// we can remove this plugin and use the core functionality with the same data\nexport const NETWORK_PLUGIN_NAME = 'rrweb/network@1'\n\n// TODO how should this be typed?\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nexport const getRecordNetworkPlugin: (options?: NetworkRecordOptions) => RecordPlugin = (options) => {\n return {\n name: NETWORK_PLUGIN_NAME,\n observer: initNetworkObserver,\n options: options,\n }\n}\n\n// rrweb/networ@1 ends\n","// This file is kept only for backwards compatibility.\n// In almost every case, if you are manually importing a file you should use posthog-recorder instead.\n\nimport { record as rrwebRecord, wasMaxDepthReached, resetMaxDepthState } from '@posthog/rrweb-record'\nimport { getRecordConsolePlugin } from '@posthog/rrweb-plugin-console-record'\nimport { getRecordNetworkPlugin } from '../extensions/replay/external/network-plugin'\nimport { assignableWindow } from '../utils/globals'\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.rrwebPlugins = { getRecordConsolePlugin, getRecordNetworkPlugin }\nassignableWindow.__PosthogExtensions__.rrweb = {\n record: rrwebRecord,\n version: 'v2',\n wasMaxDepthReached,\n resetMaxDepthState,\n}\n\n// we used to put all of these items directly on window, and now we put it on __PosthogExtensions__\n// but that means that old clients which lazily load this extension are looking in the wrong place\n// yuck,\n// so we also put them directly on the window\n// when 1.161.1 is the oldest version seen in production we can remove this\nassignableWindow.rrweb = { record: rrwebRecord, version: 'v2' }\nassignableWindow.rrwebConsoleRecord = { getRecordConsolePlugin }\nassignableWindow.getRecordNetworkPlugin = getRecordNetworkPlugin\n\nexport default rrwebRecord\n"],"names":["_a","EventType","EventType2","IncrementalSource","IncrementalSource2","MouseInteractions","MouseInteractions2","PointerTypes","PointerTypes2","CanvasContext","CanvasContext2","MediaInteractions","MediaInteractions2","NodeType","NodeType2","_a2","_b","_c","_d","_a3","source","name","replacement","original","wrapped","prototype","Object","defineProperties","__rrweb_original__","enumerable","value","_unused","ObjProto","type_utils_hasOwnProperty","hasOwnProperty","type_utils_toString","toString","isArray","Array","obj","call","isFunction","x","isObject","isUndefined","isString","isNull","isNullish","isBoolean","isFormData","FormData","win","window","undefined","global","globalThis","self","File","XMLHttpRequest","assignableWindow","isDocument","Document","_createLogger","prefix","_temp","debugEnabled","logger","_log","level","POSTHOG_DEBUG","console","consoleLog","_len","arguments","length","args","_key","debug","_len2","_key2","info","_len3","_key3","warn","_len4","_key4","error","_len5","_key5","critical","_len6","_key6","uninitializedWarning","methodName","createLogger","additionalPrefix","options","formDataToQuery","formdata","arg_separator","use_val","use_key","tph_arr","iterator","forEach","val","key","each","encodeURIComponent","join","patch","__posthog_wrapped__","isHostOnDenyList","url","_options$payloadHostD","hostname","URL","hostnameFromURL","defaultNotDenied","isHostDenied","payloadHostDenyList","trim","deny","endsWith","defaultNetworkOptions","initiatorTypes","maskRequestFn","data","recordHeaders","recordBody","recordInitialRequests","recordPerformance","performanceEntryTypeToObserve","payloadSizeLimitBytes","isNavigationTiming","entry","entryType","isResourceTiming","shouldRecordHeaders","type","isRequest","Request","NEVER_RECORD_BODY_CONTENT_TYPES","shouldRecordBody","_ref","headers","matchesContentType","contentTypes","contentTypeHeader","keys","find","toLowerCase","contentType","some","ct","includes","isBlobURL","startsWith","protocol","_unused2","recordBodyType","getRequestPerformanceEntry","_x","_x2","_x3","_x4","_x5","_x6","_getRequestPerformanceEntry","apply","this","_asyncToGenerator","initiatorType","start","end","attempt","performanceEntry","array","predicate","i","startTime","findLast","performance","getEntriesByName","Promise","resolve","setTimeout","_tryReadXHRBody","_ref2","body","textContent","JSON","stringify","_unused3","exposesServerTiming","event","prepareRequest","_ref3","method","status","networkRequest","isInitial","responseEnd","timeOrigin","Math","floor","Date","now","timestamp","requests","_extends","toJSON","round","endTime","requestHeaders","requestBody","responseHeaders","responseBody","timing","serverTiming","push","duration","contentTypePrefixDenyList","_tryReadBody","r","timeout","clone","text","then","txt","reason","finally","clearTimeout","_unused4","_tryReadRequestBody2","_ref5","_tryReadResponseBody2","_ref6","cannotReadBodyReason","_ref4","_r$headers$get","get","contentTypeIsDenied","_checkForCannotReadResponseBody","initialisedHandler","initNetworkObserver","callback","networkOptions","assign","cb","request","maskedRequest","performanceObserver","initialPerformanceEntries","getEntries","filter","flatMap","observer","PerformanceObserver","entries","performanceEntries","wrappedInitiatorFilter","entryTypes","supportedEntryTypes","observe","disconnect","initPerformanceObserver","xhrObserver","fetchObserver","recordRequestHeaders","recordResponseHeaders","restorePatch","originalOpen","async","username","password","xhr","req","originalSetRequestHeader","setRequestHeader","bind","header","originalSend","send","cleanup","removeEventListener","readyStateListener","readyState","DONE","getAllResponseHeaders","split","line","parts","shift","response","catch","addEventListener","initXhrObserver","originalFetch","_ref7","init","res","getReader","tee","_x7","_tryReadRequestBody","_x8","_tryReadResponseBody","_res","_x9","_x0","initFetchObserver","getRecordNetworkPlugin","__PosthogExtensions__","rrwebPlugins","getRecordConsolePlugin","rrweb","record","rrwebRecord","version","wasMaxDepthReached","resetMaxDepthState","rrwebConsoleRecord"],"mappings":"ijBAAAA,mKAAIC,EAA6B,CAACC,IAChCA,EAAWA,EAA6B,iBAAI,GAAK,mBACjDA,EAAWA,EAAiB,KAAI,GAAK,OACrCA,EAAWA,EAAyB,aAAI,GAAK,eAC7CA,EAAWA,EAAgC,oBAAI,GAAK,sBACpDA,EAAWA,EAAiB,KAAI,GAAK,OACrCA,EAAWA,EAAmB,OAAI,GAAK,SACvCA,EAAWA,EAAmB,OAAI,GAAK,SAChCA,GARwB,CAS9BD,GAAa,CAAA,GAEZE,EAAqC,CAACC,IACxCA,EAAmBA,EAA6B,SAAI,GAAK,WACzDA,EAAmBA,EAA8B,UAAI,GAAK,YAC1DA,EAAmBA,EAAqC,iBAAI,GAAK,mBACjEA,EAAmBA,EAA2B,OAAI,GAAK,SACvDA,EAAmBA,EAAmC,eAAI,GAAK,iBAC/DA,EAAmBA,EAA0B,MAAI,GAAK,QACtDA,EAAmBA,EAA8B,UAAI,GAAK,YAC1DA,EAAmBA,EAAqC,iBAAI,GAAK,mBACjEA,EAAmBA,EAAmC,eAAI,GAAK,iBAC/DA,EAAmBA,EAAmC,eAAI,GAAK,iBAC/DA,EAAmBA,EAAyB,KAAI,IAAM,OACtDA,EAAmBA,EAAwB,IAAI,IAAM,MACrDA,EAAmBA,EAAyB,KAAI,IAAM,OACtDA,EAAmBA,EAAqC,iBAAI,IAAM,mBAClEA,EAAmBA,EAA8B,UAAI,IAAM,Y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,GACpDsD,MAAM7F,IAAU,IAAA6K,EACPnG,EAAWb,GAAe,CAC5B7D,QACA+D,OAAQ+E,EAAI/E,OACZC,OAAW,OAAL6G,EAAEP,QAAG,EAAHO,EAAK7G,OACbC,iBACA3B,QACAC,MACA7D,IAAKoK,EAAIpK,IACT2D,cAAe,UAEnB6E,EAAG,CAAExC,YAAW,IAEnBsF,OAAM,QAGf,CACJ,IAAC,OAAA,SAAAc,EAAAC,GAAA,OAAAX,EAAAlI,MAAAC,KAAAjG,UAAA,CAAA,CA9ED,KAgFJ,MAAO,KACHsM,GAAc,CAEtB,CA8CwBwC,CAAkB9D,EAAItM,EAAKoM,IAG/CH,GAAqBA,KACjBQ,IACAe,IACAC,IACAxB,GAAqB,IAAI,CAGjC,CAIO,IAKMoE,GAA4ExN,IAC9E,CACH3E,KAP2B,kBAQ3B4O,SAAUZ,GACVrJ,QAASA,IChvBjBrC,GAAiB8P,sBAAwB9P,GAAiB8P,uBAAyB,CAAA,EACnF9P,GAAiB8P,sBAAsBC,aAAe,CAAEC,0BAAwBH,2BAChF7P,GAAiB8P,sBAAsBG,MAAQ,CAC3CC,OAAQC,GACRC,QAAS,KACTC,0BACAC,kBAAAA,iBAQJtQ,GAAiBiQ,MAAQ,CAAEC,OAAQC,GAAaC,QAAS,MACzDpQ,GAAiBuQ,mBAAqB,CAAEP,2BACxChQ,GAAiB6P,uBAAyBA"}
|
|
1
|
+
{"version":3,"file":"recorder-v2.js","sources":["../../rrweb/record/dist/rrweb-record.js","../../rrweb/plugins/rrweb-plugin-console-record/dist/rrweb-plugin-console-record.js","../../core/dist/utils/type-utils.mjs","../src/utils/globals.ts","../src/utils/type-utils.ts","../src/utils/logger.ts","../src/utils/request-utils.ts","../src/utils/index.ts","../src/extensions/replay/rrweb-plugins/patch.ts","../src/extensions/replay/external/denylist.ts","../src/extensions/replay/external/config.ts","../src/extensions/replay/external/network-plugin.ts","../src/entrypoints/recorder.ts"],"sourcesContent":["var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar _a;\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nconst FullscreenCustomEventTag = \"rrweb/fullscreen\";\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {\n MediaInteractions2[MediaInteractions2[\"Play\"] = 0] = \"Play\";\n MediaInteractions2[MediaInteractions2[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions2[MediaInteractions2[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions2[MediaInteractions2[\"VolumeChange\"] = 3] = \"VolumeChange\";\n MediaInteractions2[MediaInteractions2[\"RateChange\"] = 4] = \"RateChange\";\n return MediaInteractions2;\n})(MediaInteractions || {});\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType || {});\nconst testableAccessors = {\n Node: [\"childNodes\", \"parentNode\", \"parentElement\", \"textContent\"],\n ShadowRoot: [\"host\", \"styleSheets\"],\n Element: [\"shadowRoot\"],\n MutationObserver: []\n};\nconst testableMethods = {\n Node: [\"contains\", \"getRootNode\"],\n ShadowRoot: [\"getSelection\"],\n Element: [\"querySelector\", \"querySelectorAll\"],\n MutationObserver: [\"constructor\"]\n};\nconst untaintedBasePrototype = {};\nfunction angularZoneUnpatchedAlternative(key) {\n var _a2, _b;\n const angularUnpatchedVersionSymbol = (_b = (_a2 = globalThis == null ? void 0 : globalThis.Zone) == null ? void 0 : _a2.__symbol__) == null ? void 0 : _b.call(_a2, key);\n if (angularUnpatchedVersionSymbol && globalThis[angularUnpatchedVersionSymbol]) {\n return globalThis[angularUnpatchedVersionSymbol];\n } else {\n return void 0;\n }\n}\nfunction getUntaintedPrototype(key) {\n if (untaintedBasePrototype[key])\n return untaintedBasePrototype[key];\n const candidate = angularZoneUnpatchedAlternative(key) || globalThis[key];\n const defaultPrototype = candidate.prototype;\n const accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;\n const isUntaintedAccessors = Boolean(\n accessorNames && // @ts-expect-error 2345\n accessorNames.every(\n (accessor) => {\n var _a2, _b;\n return Boolean(\n (_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes(\"[native code]\")\n );\n }\n )\n );\n const methodNames = key in testableMethods ? testableMethods[key] : void 0;\n const isUntaintedMethods = Boolean(\n methodNames && methodNames.every(\n // @ts-expect-error 2345\n (method) => {\n var _a2;\n return typeof defaultPrototype[method] === \"function\" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes(\"[native code]\"));\n }\n )\n );\n if (isUntaintedAccessors && isUntaintedMethods) {\n untaintedBasePrototype[key] = candidate.prototype;\n return candidate.prototype;\n }\n const iframeEl = document.createElement(\"iframe\");\n try {\n document.body.appendChild(iframeEl);\n const win = iframeEl.contentWindow;\n if (!win) return candidate.prototype;\n const untaintedObject = win[key].prototype;\n if (!untaintedObject) return defaultPrototype;\n return untaintedBasePrototype[key] = untaintedObject;\n } catch {\n return defaultPrototype;\n } finally {\n if (iframeEl.parentNode) {\n document.body.removeChild(iframeEl);\n }\n }\n}\nconst untaintedAccessorCache = {};\nfunction getUntaintedAccessor(key, instance, accessor) {\n var _a2;\n const cacheKey = `${key}.${String(accessor)}`;\n if (untaintedAccessorCache[cacheKey])\n return untaintedAccessorCache[cacheKey].call(\n instance\n );\n const untaintedPrototype = getUntaintedPrototype(key);\n const untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(\n untaintedPrototype,\n accessor\n )) == null ? void 0 : _a2.get;\n if (!untaintedAccessor) return instance[accessor];\n untaintedAccessorCache[cacheKey] = untaintedAccessor;\n return untaintedAccessor.call(instance);\n}\nconst untaintedMethodCache = {};\nfunction getUntaintedMethod(key, instance, method) {\n const cacheKey = `${key}.${String(method)}`;\n if (untaintedMethodCache[cacheKey])\n return untaintedMethodCache[cacheKey].bind(\n instance\n );\n const untaintedPrototype = getUntaintedPrototype(key);\n const untaintedMethod = untaintedPrototype[method];\n if (typeof untaintedMethod !== \"function\") return instance[method];\n untaintedMethodCache[cacheKey] = untaintedMethod;\n return untaintedMethod.bind(instance);\n}\nfunction childNodes(n) {\n return getUntaintedAccessor(\"Node\", n, \"childNodes\");\n}\nfunction parentNode(n) {\n return getUntaintedAccessor(\"Node\", n, \"parentNode\");\n}\nfunction parentElement(n) {\n return getUntaintedAccessor(\"Node\", n, \"parentElement\");\n}\nfunction textContent(n) {\n return getUntaintedAccessor(\"Node\", n, \"textContent\");\n}\nfunction contains(n, other) {\n return getUntaintedMethod(\"Node\", n, \"contains\")(other);\n}\nfunction getRootNode(n) {\n return getUntaintedMethod(\"Node\", n, \"getRootNode\")();\n}\nfunction host(n) {\n if (!n || !(\"host\" in n)) return null;\n return getUntaintedAccessor(\"ShadowRoot\", n, \"host\");\n}\nfunction styleSheets(n) {\n return n.styleSheets;\n}\nfunction shadowRoot(n) {\n if (!n || !(\"shadowRoot\" in n)) return null;\n return getUntaintedAccessor(\"Element\", n, \"shadowRoot\");\n}\nfunction querySelector(n, selectors) {\n return getUntaintedMethod(\"Element\", n, \"querySelector\")(selectors);\n}\nfunction querySelectorAll(n, selectors) {\n return getUntaintedMethod(\"Element\", n, \"querySelectorAll\")(selectors);\n}\nfunction mutationObserverCtor() {\n return getUntaintedPrototype(\"MutationObserver\").constructor;\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nconst index = {\n childNodes,\n parentNode,\n parentElement,\n textContent,\n contains,\n getRootNode,\n host,\n styleSheets,\n shadowRoot,\n querySelector,\n querySelectorAll,\n mutationObserver: mutationObserverCtor,\n patch\n};\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const hostEl = (\n // anchor and textarea elements also have a `host` property\n // but only shadow roots have a `mode` property\n n && \"host\" in n && \"mode\" in n && index.host(n) || null\n );\n return Boolean(\n hostEl && \"shadowRoot\" in hostEl && index.shadowRoot(hostEl) === n\n );\n}\nfunction isNativeShadowDom(shadowRoot2) {\n return Object.prototype.toString.call(shadowRoot2) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n cssText = cssText.replace(\n /\\sbackground-clip:\\s*text;/g,\n \" -webkit-background-clip: text; background-clip: text;\"\n );\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3) return cssText;\n const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === \"\") {\n statement.push(`layer`);\n } else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(\" \") + \";\";\n}\nfunction hasEmptyShorthandLonghand(css) {\n return /(?:^|[\\s;{}])-?[a-zA-Z][\\w-]*\\s*:\\s*;/.test(css);\n}\nfunction stringifyStylesheet(s) {\n try {\n const rules = s.rules || s.cssRules;\n if (!rules) {\n return null;\n }\n let sheetHref = s.href;\n if (!sheetHref && s.ownerNode) {\n sheetHref = s.ownerNode.baseURI;\n }\n const stringifiedRules = Array.from(\n rules,\n (rule) => stringifyRule(rule, sheetHref)\n ).join(\"\");\n return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);\n } catch (error) {\n return null;\n }\n}\nfunction stringifyRule(rule, sheetHref) {\n var _a2;\n if (isCSSImportRule(rule)) {\n let importStringified;\n try {\n importStringified = // for same-origin stylesheets,\n // we can access the imported stylesheet rules directly\n stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n escapeImportStatement(rule);\n } catch (error) {\n importStringified = rule.cssText;\n }\n try {\n if (importStringified && ((_a2 = rule.styleSheet) == null ? void 0 : _a2.href)) {\n return absolutifyURLs(importStringified, rule.styleSheet.href);\n }\n } catch {\n }\n return importStringified;\n } else {\n let ruleStringified = rule.cssText;\n if (isCSSStyleRule(rule) && rule.selectorText.includes(\":\")) {\n ruleStringified = fixSafariColons(ruleStringified);\n }\n if (sheetHref) {\n return absolutifyURLs(ruleStringified, sheetHref);\n }\n return ruleStringified;\n }\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n return \"selectorText\" in rule;\n}\nclass Mirror {\n constructor() {\n __publicField(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n) {\n var _a2;\n if (!n) return -1;\n const id = (_a2 = this.getMeta(n)) == null ? void 0 : _a2.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n) {\n return this.nodeMetaMap.get(n) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n) {\n const id = this.getId(n);\n this.idNodeMap.delete(id);\n if (n.childNodes) {\n n.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n if (isElement(n)) {\n const shadowRootEl = index.shadowRoot(n);\n if (shadowRootEl) {\n this.removeNodeFromMap(shadowRootEl);\n }\n if (n.nodeName === \"IFRAME\" && n.contentDocument) {\n this.removeNodeFromMap(\n n.contentDocument\n );\n }\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n);\n this.nodeMetaMap.set(n, meta);\n }\n replace(id, n) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n, meta);\n }\n this.idNodeMap.set(id, n);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction createMirror() {\n return new Mirror();\n}\nfunction maskInputValue({\n element,\n maskInputOptions,\n tagName,\n type,\n value,\n maskInputFn\n}) {\n let text = value || \"\";\n const actualType = type && toLowerCase(type);\n if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {\n if (maskInputFn) {\n text = maskInputFn(text, element);\n } else {\n text = \"*\".repeat(text.length);\n }\n }\n return text;\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n const pixelBuffer = new Uint32Array(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n originalGetImageData.call(\n ctx,\n x,\n y,\n Math.min(chunkSize, canvas.width - x),\n Math.min(chunkSize, canvas.height - y)\n ).data.buffer\n );\n if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n toLowerCase(type)\n ) : null;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n } catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return (match == null ? void 0 : match[1]) ?? null;\n}\nfunction extractOrigin(url) {\n let origin = \"\";\n if (url.indexOf(\"//\") > -1) {\n origin = url.split(\"/\").slice(0, 3).join(\"/\");\n } else {\n origin = url.split(\"/\")[0];\n }\n origin = origin.split(\"?\")[0];\n return origin;\n}\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absolutifyURLs(cssText, href) {\n return (cssText || \"\").replace(\n URL_IN_CSS_REF,\n (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || \"\";\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === \"/\") {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split(\"/\");\n const parts = filePath.split(\"/\");\n stack.pop();\n for (const part of parts) {\n if (part === \".\") {\n continue;\n } else if (part === \"..\") {\n stack.pop();\n } else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join(\"/\")}${maybeQuote})`;\n }\n );\n}\nconst STRIPED_PLACEHOLDER_SVG = \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxkZWZzPgogICAgPHBhdHRlcm4gaWQ9InN0cmlwZXMiIHBhdHRlcm5Vbml0cz0idXNlclNwYWNlT25Vc2UiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+CiAgICAgIDxyZWN0IHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iYmxhY2siLz4KICAgICAgPHBhdGggZD0iTTggMEgxNkwwIDE2VjhMOCAwWiIgZmlsbD0iIzJEMkQyRCIvPgogICAgICA8cGF0aCBkPSJNMTYgOFYxNkg4TDE2IDhaIiBmaWxsPSIjMkQyRDJEIi8+CiAgICA8L3BhdHRlcm4+CiAgPC9kZWZzPgogIDxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjc3RyaXBlcykiLz4KPC9zdmc+Cg==\";\nconst MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION = 4096;\nfunction recompressBase64Image(img, dataURL, type, quality) {\n if (!img.complete || img.naturalWidth === 0) {\n return dataURL;\n }\n if (img.naturalWidth > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION || img.naturalHeight > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION) {\n return dataURL;\n }\n try {\n const canvas = document.createElement(\"canvas\");\n canvas.width = img.naturalWidth;\n canvas.height = img.naturalHeight;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n return dataURL;\n }\n ctx.drawImage(img, 0, 0);\n const recompressed = canvas.toDataURL(type || \"image/webp\", quality ?? 0.4);\n return recompressed;\n } catch (err) {\n return dataURL;\n }\n}\nfunction checkDataURLSize(dataURL, maxLength) {\n if (!maxLength || dataURL.length <= maxLength) {\n return dataURL;\n }\n return STRIPED_PLACEHOLDER_SVG;\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return \"form\";\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return \"div\";\n }\n return processedTagName;\n}\nlet canvasService;\nlet canvasCtx;\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === \"\") {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars2;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars2 = match[0];\n pos += chars2.length;\n return chars2;\n }\n return \"\";\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === \",\") {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n } else {\n let descriptorsStr = \"\";\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c = attributeValue.charAt(pos);\n if (c === \"\") {\n output.push((url + descriptorsStr).trim());\n break;\n } else if (!inParens) {\n if (c === \",\") {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n } else if (c === \"(\") {\n inParens = true;\n }\n } else {\n if (c === \")\") {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === \"\") {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a = cachedDocument.get(doc);\n if (!a) {\n a = doc.createElement(\"a\");\n cachedDocument.set(doc, a);\n }\n if (!customHref) {\n customHref = \"\";\n } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n return customHref;\n }\n a.setAttribute(\"href\", customHref);\n return a.href;\n}\nfunction capDataURLSize(dataURL, dataURLOptions) {\n if (dataURLOptions == null ? void 0 : dataURLOptions.maxBase64ImageLength) {\n return checkDataURLSize(dataURL, dataURLOptions.maxBase64ImageLength);\n }\n return dataURL;\n}\nfunction transformAttribute(doc, tagName, name, value, element, dataURLOptions) {\n var _a2;\n if (!value) {\n return value;\n }\n if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n if (tagName === \"link\" && element) {\n const sheetHref = (_a2 = element.sheet) == null ? void 0 : _a2.href;\n if (sheetHref) {\n return sheetHref;\n }\n }\n const transformedValue = absoluteToDoc(doc, value);\n if (transformedValue.startsWith(\"data:\")) {\n if (tagName === \"img\" && element) {\n let processedDataURL = transformedValue;\n if ((dataURLOptions == null ? void 0 : dataURLOptions.type) || (dataURLOptions == null ? void 0 : dataURLOptions.quality) !== void 0) {\n processedDataURL = recompressBase64Image(\n element,\n transformedValue,\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n return capDataURLSize(processedDataURL, dataURLOptions);\n }\n if (tagName === \"image\") {\n return capDataURLSize(transformedValue, dataURLOptions);\n }\n }\n return transformedValue;\n } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n const transformedValue = absoluteToDoc(doc, value);\n if (tagName === \"image\" && transformedValue.startsWith(\"data:\")) {\n return capDataURLSize(transformedValue, dataURLOptions);\n }\n return transformedValue;\n } else if (name === \"background\" && (tagName === \"table\" || tagName === \"td\" || tagName === \"th\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"srcset\") {\n return getAbsoluteSrcsetString(doc, value);\n } else if (name === \"style\") {\n return absolutifyURLs(value, getHref(doc));\n } else if (tagName === \"object\" && name === \"data\") {\n return absoluteToDoc(doc, value);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return (tagName === \"video\" || tagName === \"audio\") && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector) {\n try {\n if (typeof blockClass === \"string\") {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n } else {\n for (let eIndex = element.classList.length; eIndex--; ) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n } catch (e) {\n }\n return false;\n}\nfunction classMatchesRegex(node, regex, checkAncestors) {\n if (!node) return false;\n if (node.nodeType !== node.ELEMENT_NODE) {\n if (!checkAncestors) return false;\n return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n }\n for (let eIndex = node.classList.length; eIndex--; ) {\n const className = node.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n if (!checkAncestors) return false;\n return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, checkAncestors) {\n let el;\n if (isElement(node)) {\n el = node;\n if (!index.childNodes(el).length) {\n return false;\n }\n } else if (index.parentElement(node) === null) {\n return false;\n } else {\n el = index.parentElement(node);\n }\n try {\n if (typeof maskTextClass === \"string\") {\n if (checkAncestors) {\n if (el.closest(`.${maskTextClass}`)) return true;\n } else {\n if (el.classList.contains(maskTextClass)) return true;\n }\n } else {\n if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;\n }\n if (maskTextSelector) {\n if (checkAncestors) {\n if (el.closest(maskTextSelector)) return true;\n } else {\n if (el.matches(maskTextSelector)) return true;\n }\n }\n } catch (e) {\n }\n return false;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const noop = () => {\n };\n const win = iframeEl.contentWindow;\n if (!win) {\n return noop;\n }\n let readyState;\n try {\n readyState = win.document.readyState;\n } catch (error) {\n return noop;\n }\n const onSubsequentLoad = () => listener();\n if (readyState !== \"complete\") {\n let fired = false;\n let timer = null;\n const fireOnce = () => {\n if (fired) return;\n fired = true;\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n iframeEl.removeEventListener(\"load\", onInitialLoad);\n iframeEl.addEventListener(\"load\", onSubsequentLoad);\n listener();\n };\n const onInitialLoad = () => fireOnce();\n timer = setTimeout(fireOnce, iframeLoadTimeout);\n iframeEl.addEventListener(\"load\", onInitialLoad);\n return () => {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n if (fired) {\n iframeEl.removeEventListener(\"load\", onSubsequentLoad);\n } else {\n fired = true;\n iframeEl.removeEventListener(\"load\", onInitialLoad);\n }\n };\n }\n const blankUrl = \"about:blank\";\n let winLocationHref;\n try {\n winLocationHref = win.location.href;\n } catch {\n return noop;\n }\n if (winLocationHref !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n const initialTimer = setTimeout(listener, 0);\n iframeEl.addEventListener(\"load\", onSubsequentLoad);\n return () => {\n clearTimeout(initialTimer);\n iframeEl.removeEventListener(\"load\", onSubsequentLoad);\n };\n }\n iframeEl.addEventListener(\"load\", onSubsequentLoad);\n return () => {\n iframeEl.removeEventListener(\"load\", onSubsequentLoad);\n };\n}\nconst stylesheetLoadTracked = /* @__PURE__ */ new Map();\nfunction resetStylesheetLoadTracking() {\n stylesheetLoadTracked.forEach((controller) => controller.abort());\n stylesheetLoadTracked.clear();\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n if (stylesheetLoadTracked.has(link)) return;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n } catch (error) {\n return;\n }\n if (styleSheetLoaded) return;\n const controller = new AbortController();\n let fired = false;\n const fire = () => {\n if (fired) return;\n fired = true;\n try {\n listener();\n } finally {\n stylesheetLoadTracked.delete(link);\n controller.abort();\n }\n };\n const timer = setTimeout(fire, styleSheetLoadTimeout);\n controller.signal.addEventListener(\"abort\", () => clearTimeout(timer), {\n once: true\n });\n link.addEventListener(\"load\", fire, {\n signal: controller.signal,\n once: true\n });\n stylesheetLoadTracked.set(link, controller);\n}\nfunction serializeNode(n, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n inlineStylesheet,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false\n } = options;\n const rootId = getRootId(doc, mirror2);\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== \"CSS1Compat\") {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode\n // probably \"BackCompat\"\n };\n } else {\n return {\n type: NodeType.Document,\n childNodes: []\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId\n };\n case n.ELEMENT_NODE:\n return serializeElementNode(n, {\n doc,\n blockClass,\n blockSelector,\n inlineStylesheet,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId\n });\n case n.TEXT_NODE:\n return serializeTextNode(n, {\n doc,\n needsMask,\n maskTextFn,\n rootId\n });\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: \"\",\n rootId\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: index.textContent(n) || \"\",\n rootId\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror2) {\n if (!mirror2.hasNode(doc)) return void 0;\n const docId = mirror2.getId(doc);\n return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n, options) {\n var _a2;\n const { needsMask, maskTextFn, rootId } = options;\n const parent = index.parentNode(n);\n const parentTagName = parent && parent.tagName;\n let text = index.textContent(n);\n const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n if (isStyle && text) {\n try {\n if (n.nextSibling || n.previousSibling) {\n } else if ((_a2 = parent.sheet) == null ? void 0 : _a2.cssRules) {\n const stringified = stringifyStylesheet(\n parent.sheet\n );\n if (stringified && !hasEmptyShorthandLonghand(stringified)) {\n text = stringified;\n }\n }\n } catch (err) {\n console.warn(\n `Cannot get CSS styles from text's parentNode. Error: ${err}`,\n n\n );\n }\n text = absolutifyURLs(text, getHref(options.doc));\n }\n if (isScript) {\n text = \"SCRIPT_PLACEHOLDER\";\n }\n if (!isStyle && !isScript && text && needsMask) {\n text = maskTextFn ? maskTextFn(text, index.parentElement(n)) : text.replace(/[\\S]/g, \"*\");\n }\n return {\n type: NodeType.Text,\n textContent: text || \"\",\n isStyle,\n rootId\n };\n}\nfunction findStylesheet(doc, href) {\n return Array.from(doc.styleSheets).find((s) => s.href === href);\n}\nfunction hrefFrom(n) {\n return n.href;\n}\nfunction serializeElementNode(n, options) {\n var _a2, _b, _c;\n const {\n doc,\n blockClass,\n blockSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n rootId\n } = options;\n const needBlock = _isBlockedElement(n, blockClass, blockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n const len = n.attributes.length;\n for (let i = 0; i < len; i++) {\n const attr = n.attributes[i];\n if (!ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes[attr.name] = transformAttribute(\n doc,\n tagName,\n toLowerCase(attr.name),\n attr.value,\n n,\n dataURLOptions\n );\n }\n }\n if (tagName === \"link\" && inlineStylesheet) {\n let stylesheet = n.sheet;\n if (!stylesheet) {\n const href = hrefFrom(n);\n if (href) {\n stylesheet = findStylesheet(doc, href);\n if (!stylesheet && href.includes(\".css\")) {\n const rootDomain = window.location.origin;\n const stylesheetPath = href.replace(window.location.href, \"\");\n const potentialStylesheetHref = rootDomain + \"/\" + stylesheetPath;\n stylesheet = findStylesheet(doc, potentialStylesheetHref);\n }\n }\n }\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = cssText;\n }\n }\n if (tagName === \"style\" && n.sheet && // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n !(n.innerText || index.textContent(n) || \"\").trim().length) {\n const cssText = stringifyStylesheet(\n n.sheet\n );\n if (cssText) {\n attributes._cssText = cssText;\n }\n }\n if (tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\") {\n const value = n.value;\n const checked = n.checked;\n if (attributes.type !== \"radio\" && attributes.type !== \"checkbox\" && attributes.type !== \"submit\" && attributes.type !== \"button\" && value) {\n attributes.value = maskInputValue({\n element: n,\n type: getInputType(n),\n tagName,\n value,\n maskInputOptions,\n maskInputFn\n });\n } else if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === \"option\") {\n if (n.selected && !maskInputOptions[\"select\"]) {\n attributes.selected = true;\n } else {\n delete attributes.selected;\n }\n }\n if (tagName === \"dialog\" && n.open) {\n try {\n attributes.rr_open_mode = n.matches(\"dialog:modal\") ? \"modal\" : \"non-modal\";\n } catch {\n attributes.rr_open_mode = \"modal\";\n attributes.ph_rr_could_not_detect_modal = true;\n }\n }\n if (tagName === \"canvas\" && recordCanvas) {\n if (n.__context === \"2d\") {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n } else if (!(\"__context\" in n)) {\n const canvasDataURL = n.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n const blankCanvas = doc.createElement(\"canvas\");\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === \"img\" && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement(\"canvas\");\n canvasCtx = canvasService.getContext(\"2d\");\n }\n const image = n;\n const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"<unknown-src>\";\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener(\"load\", recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n } catch (err) {\n if (image.crossOrigin !== \"anonymous\") {\n image.crossOrigin = \"anonymous\";\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n return;\n } else {\n console.warn(\n `Cannot inline img src=${imageSrc}! Error: ${err}`\n );\n }\n }\n if (image.crossOrigin === \"anonymous\") {\n priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n }\n };\n if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n }\n if (tagName === \"audio\" || tagName === \"video\") {\n const mediaAttributes = attributes;\n mediaAttributes.rr_mediaState = n.paused ? \"paused\" : \"played\";\n mediaAttributes.rr_mediaCurrentTime = n.currentTime;\n mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;\n mediaAttributes.rr_mediaMuted = n.muted;\n mediaAttributes.rr_mediaLoop = n.loop;\n mediaAttributes.rr_mediaVolume = n.volume;\n }\n if (!newlyAddedElement) {\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height, left, top } = n.getBoundingClientRect();\n const computed = (_a2 = doc.defaultView) == null ? void 0 : _a2.getComputedStyle(n);\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n rr_left: `${Math.floor(left + (((_b = doc.defaultView) == null ? void 0 : _b.scrollX) || 0))}px`,\n rr_top: `${Math.floor(top + (((_c = doc.defaultView) == null ? void 0 : _c.scrollY) || 0))}px`\n };\n if (computed) {\n attributes.rr_position = computed.position || \"static\";\n if (computed.transform && computed.transform !== \"none\") {\n attributes.rr_transform = computed.transform;\n }\n if (computed.display && computed.display.startsWith(\"inline\")) {\n attributes.rr_display = computed.display;\n }\n }\n }\n if (tagName === \"iframe\" && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName)) isCustomElement = true;\n } catch (e) {\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || void 0,\n needBlock,\n rootId,\n isCustom: isCustomElement\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === void 0 || maybeAttr === null) {\n return \"\";\n } else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n } else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script && // script tag\n (sn.tagName === \"script\" || // (module)preload link\n sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" && sn.attributes.as === \"script\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n return true;\n } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n /^msapplication-tile(image|color)$/\n ) || lowerIfExists(sn.attributes.name) === \"application-name\" || [\"icon\", \"apple-touch-icon\", \"shortcut icon\"].includes(\n lowerIfExists(sn.attributes.rel)\n )))) {\n return true;\n } else if (sn.tagName === \"meta\") {\n if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n return true;\n } else if (slimDOMOptions.headMetaRobots && [\"robots\", \"googlebot\", \"bingbot\"].includes(\n lowerIfExists(sn.attributes.name)\n )) {\n return true;\n } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n return true;\n } else if (slimDOMOptions.headMetaAuthorship && ([\"author\", \"generator\", \"framework\", \"publisher\", \"progid\"].includes(\n lowerIfExists(sn.attributes.name)\n ) || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n } else if (slimDOMOptions.headMetaVerification && [\n \"google-site-verification\",\n \"yandex-verification\",\n \"csrf-token\",\n \"p:domain_verify\",\n \"verify-v1\",\n \"verification\",\n \"shopify-checkout-api-token\"\n ].includes(lowerIfExists(sn.attributes.name))) {\n return true;\n }\n }\n }\n return false;\n}\nconst DEFAULT_MAX_DEPTH = 50;\nlet _maxDepthWarned = false;\nlet _maxDepthReached = false;\nfunction wasMaxDepthReached() {\n return _maxDepthReached;\n}\nfunction resetMaxDepthState() {\n _maxDepthReached = false;\n _maxDepthWarned = false;\n}\nfunction serializeNodeWithId(n, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n skipChild = false,\n inlineStylesheet = true,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions = {},\n inlineImages = false,\n recordCanvas = false,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout = 5e3,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout = 5e3,\n keepIframeSrcFn = () => false,\n newlyAddedElement = false,\n depth = 0,\n maxDepth = DEFAULT_MAX_DEPTH\n } = options;\n let { needsMask } = options;\n let { preserveWhiteSpace = true } = options;\n if (depth >= maxDepth) {\n _maxDepthReached = true;\n if (!_maxDepthWarned) {\n _maxDepthWarned = true;\n console.warn(\n `[rrweb-snapshot] DOM tree depth exceeded max depth of ${maxDepth}. Children beyond this depth will not be recorded. This may indicate deeply nested DOM structures.`\n );\n }\n return null;\n }\n if (!needsMask) {\n const checkAncestors = needsMask === void 0;\n needsMask = needMaskingText(\n n,\n maskTextClass,\n maskTextSelector,\n checkAncestors\n );\n }\n const _serializedNode = serializeNode(n, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement\n });\n if (!_serializedNode) {\n console.warn(n, \"not serialized\");\n return null;\n }\n let id;\n if (mirror2.hasNode(n)) {\n id = mirror2.getId(n);\n } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.isStyle && // codeql[js/polynomial-redos] Bounded DOM text node; worst case is recorder slowdown, no exploit.\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n id = IGNORED_NODE;\n } else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n mirror2.add(n, serializedNode);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n const shadowRootEl = index.shadowRoot(n);\n if (shadowRootEl && isNativeShadowDom(shadowRootEl))\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {\n if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === \"head\") {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n depth: depth + 1,\n maxDepth\n };\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"textarea\" && serializedNode.attributes.value !== void 0) ;\n else {\n for (const childN of Array.from(index.childNodes(n))) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n let shadowRootEl = null;\n if (isElement(n) && (shadowRootEl = index.shadowRoot(n))) {\n for (const childN of Array.from(index.childNodes(shadowRootEl))) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(shadowRootEl) && (serializedChildNode.isShadow = true);\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n const parent = index.parentNode(n);\n if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"iframe\") {\n const iframeDisposer = onceIframeLoaded(\n n,\n () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n depth: depth + 1,\n maxDepth\n });\n if (serializedIframeNode) {\n onIframeLoad(\n n,\n serializedIframeNode\n );\n }\n }\n },\n iframeLoadTimeout\n );\n onIframeListenerRegistered == null ? void 0 : onIframeListenerRegistered(n, iframeDisposer);\n }\n if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"link\" && serializedNode.attributes.rel === \"stylesheet\") {\n onceStylesheetLoaded(\n n,\n () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n needsMask,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n depth,\n maxDepth\n });\n if (serializedLinkNode) {\n onStylesheetLoad(\n n,\n serializedLinkNode\n );\n }\n }\n },\n stylesheetLoadTimeout\n );\n }\n return serializedNode;\n}\nfunction slimDOMDefaults(slimDOM) {\n if (slimDOM === true || slimDOM === \"all\") {\n return {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: slimDOM === \"all\",\n headMetaDescKeywords: slimDOM === \"all\",\n headTitleMutations: slimDOM === \"all\"\n };\n }\n if (slimDOM === false) {\n return {};\n }\n return slimDOM;\n}\nfunction snapshot(n, options) {\n const {\n mirror: mirror2 = new Mirror(),\n blockClass = \"rr-block\",\n blockSelector = null,\n maskTextClass = \"rr-mask\",\n maskTextSelector = null,\n inlineStylesheet = true,\n inlineImages = false,\n recordCanvas = false,\n maskAllInputs = false,\n maskTextFn,\n maskInputFn,\n slimDOM = false,\n dataURLOptions,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn = () => false,\n maxDepth\n } = options || {};\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n } : maskAllInputs === false ? {\n password: true\n } : maskAllInputs;\n const slimDOMOptions = slimDOMDefaults(slimDOM);\n return serializeNodeWithId(n, {\n doc: n,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onIframeListenerRegistered,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n maxDepth\n });\n}\nclass BaseRRNode {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n constructor(..._args) {\n __publicField(this, \"parentElement\", null);\n __publicField(this, \"parentNode\", null);\n __publicField(this, \"ownerDocument\");\n __publicField(this, \"firstChild\", null);\n __publicField(this, \"lastChild\", null);\n __publicField(this, \"previousSibling\", null);\n __publicField(this, \"nextSibling\", null);\n __publicField(this, \"ELEMENT_NODE\", 1);\n __publicField(this, \"TEXT_NODE\", 3);\n // corresponding nodeType value of standard HTML Node\n __publicField(this, \"nodeType\");\n __publicField(this, \"nodeName\");\n __publicField(this, \"RRNodeType\");\n }\n get childNodes() {\n const childNodes2 = [];\n let childIterator = this.firstChild;\n while (childIterator) {\n childNodes2.push(childIterator);\n childIterator = childIterator.nextSibling;\n }\n return childNodes2;\n }\n contains(node) {\n if (!(node instanceof BaseRRNode)) return false;\n else if (node.ownerDocument !== this.ownerDocument) return false;\n else if (node === this) return true;\n while (node.parentNode) {\n if (node.parentNode === this) return true;\n node = node.parentNode;\n }\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n appendChild(_newChild) {\n throw new Error(\n `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n insertBefore(_newChild, _refChild) {\n throw new Error(\n `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n removeChild(_node) {\n throw new Error(\n `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`\n );\n }\n toString() {\n return \"RRNode\";\n }\n}\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nfunction callSafely(fn) {\n try {\n fn();\n } catch (error) {\n if (!(error instanceof DOMException && error.name === \"SecurityError\")) {\n throw error;\n }\n }\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = \"Please stop import mirror directly. Instead of that,\\r\\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\r\\nor you can use record.mirror to access the mirror instance during recording.\";\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n};\nif (typeof window !== \"undefined\" && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === \"map\") {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function(...args) {\n const now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n const remaining = wait - (now - previous);\n const context = this;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(\n target,\n key,\n isRevoked ? d : {\n set(value) {\n setTimeout(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n }\n }\n );\n return () => hookSetter(target, key, original || {}, true);\n}\nlet nowTimestamp = Date.now;\nif (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {\n nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\n}\nfunction getWindowScroll(win) {\n var _a2, _b, _c, _d;\n const doc = win.document;\n return {\n left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc.documentElement.scrollLeft || (doc == null ? void 0 : doc.body) && ((_a2 = index.parentElement(doc.body)) == null ? void 0 : _a2.scrollLeft) || ((_b = doc == null ? void 0 : doc.body) == null ? void 0 : _b.scrollLeft) || 0,\n top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || (doc == null ? void 0 : doc.body) && ((_c = index.parentElement(doc.body)) == null ? void 0 : _c.scrollTop) || ((_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.scrollTop) || 0\n };\n}\nfunction getWindowHeight() {\n return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;\n}\nfunction getWindowWidth() {\n return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;\n}\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n const el = node.nodeType === node.ELEMENT_NODE ? node : index.parentElement(node);\n return el;\n}\nfunction isBlocked(node, blockClass, blockSelector, checkAncestors) {\n if (!node) {\n return false;\n }\n const el = closestElementOfNode(node);\n if (!el) {\n return false;\n }\n try {\n if (typeof blockClass === \"string\") {\n if (el.classList.contains(blockClass)) return true;\n if (checkAncestors && el.closest(\".\" + blockClass) !== null) return true;\n } else {\n if (classMatchesRegex(el, blockClass, checkAncestors)) return true;\n }\n } catch (e) {\n }\n if (blockSelector) {\n if (el.matches(blockSelector)) return true;\n if (checkAncestors && el.closest(blockSelector) !== null) return true;\n }\n return false;\n}\nfunction isSerialized(n, mirror2) {\n return mirror2.getId(n) !== -1;\n}\nfunction isIgnored(n, mirror2, slimDOMOptions) {\n if (n.tagName === \"TITLE\" && slimDOMOptions.headTitleMutations) {\n return true;\n }\n return mirror2.getId(n) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror2) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror2.getId(target);\n if (!mirror2.has(id)) {\n return true;\n }\n const parent = index.parentNode(target);\n if (parent && parent.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!parent) {\n return true;\n }\n return isAncestorRemoved(parent, mirror2);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if (\"NodeList\" in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype.forEach;\n }\n if (\"DOMTokenList\" in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype.forEach;\n }\n}\nfunction isSerializedIframe(n, mirror2) {\n return Boolean(n.nodeName === \"IFRAME\" && mirror2.getMeta(n));\n}\nfunction isSerializedStylesheet(n, mirror2) {\n return Boolean(\n n.nodeName === \"LINK\" && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute(\"rel\") === \"stylesheet\" && mirror2.getMeta(n)\n );\n}\nfunction hasShadowRoot(n) {\n if (!n) return false;\n if (n instanceof BaseRRNode && \"shadowRoot\" in n) {\n return Boolean(n.shadowRoot);\n }\n return Boolean(index.shadowRoot(n));\n}\nclass StyleSheetMirror {\n constructor() {\n __publicField(this, \"id\", 1);\n __publicField(this, \"styleIDMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"idStyleMap\", /* @__PURE__ */ new Map());\n }\n getId(stylesheet) {\n return this.styleIDMap.get(stylesheet) ?? -1;\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n /**\n * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n */\n add(stylesheet, id) {\n if (this.has(stylesheet)) return this.getId(stylesheet);\n let newId;\n if (id === void 0) {\n newId = this.id++;\n } else newId = id;\n this.styleIDMap.set(stylesheet, newId);\n this.idStyleMap.set(newId, stylesheet);\n return newId;\n }\n getStyle(id) {\n return this.idStyleMap.get(id) || null;\n }\n reset() {\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n) {\n var _a2;\n let shadowHost = null;\n if (\"getRootNode\" in n && ((_a2 = index.getRootNode(n)) == null ? void 0 : _a2.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && index.host(index.getRootNode(n)))\n shadowHost = index.host(index.getRootNode(n));\n return shadowHost;\n}\nfunction getRootShadowHost(n) {\n let rootShadowHost = n;\n let shadowHost;\n while (shadowHost = getShadowHost(rootShadowHost))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n) {\n const doc = n.ownerDocument;\n if (!doc) return false;\n const shadowHost = getRootShadowHost(n);\n return index.contains(doc, shadowHost);\n}\nfunction inDom(n) {\n const doc = n.ownerDocument;\n if (!doc) return false;\n return index.contains(doc, n) || shadowHostInDom(n);\n}\nfunction isNodeInLinkedList(n) {\n return \"__ln\" in n;\n}\nclass DoubleLinkedList {\n constructor() {\n __publicField(this, \"length\", 0);\n __publicField(this, \"head\", null);\n __publicField(this, \"tail\", null);\n }\n get(position) {\n if (position >= this.length) {\n throw new Error(\"Position outside of list range\");\n }\n let current = this.head;\n for (let index2 = 0; index2 < position; index2++) {\n current = (current == null ? void 0 : current.next) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n } else if (n.nextSibling && isNodeInLinkedList(n.nextSibling) && n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n } else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n if (node.next === null) {\n this.tail = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n } else {\n this.tail = null;\n }\n } else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n } else {\n this.tail = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n constructor() {\n __publicField(this, \"frozen\", false);\n __publicField(this, \"locked\", false);\n __publicField(this, \"texts\", []);\n __publicField(this, \"attributes\", []);\n __publicField(this, \"attributeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"removes\", []);\n __publicField(this, \"mapRemoves\", []);\n __publicField(this, \"movedMap\", {});\n /**\n * the browser MutationObserver emits multiple mutations after\n * a delay for performance reasons, making tracing added nodes hard\n * in our `processMutations` callback function.\n * For example, if we append an element el_1 into body, and then append\n * another element el_2 into el_1, these two mutations may be passed to the\n * callback function together when the two operations were done.\n * Generally we need to trace child nodes of newly added nodes, but in this\n * case if we count el_2 as el_1's child node in the first mutation record,\n * then we will count el_2 again in the second mutation record which was\n * duplicated.\n * To avoid of duplicate counting added nodes, we use a Set to store\n * added nodes and its child nodes during iterate mutation records. Then\n * collect added nodes from the Set which have no duplicate copy. But\n * this also causes newly added nodes will not be serialized with id ASAP,\n * which means all the id related calculation should be lazy too.\n */\n __publicField(this, \"addedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"movedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"droppedSet\", /* @__PURE__ */ new Set());\n __publicField(this, \"removesSubTreeCache\", /* @__PURE__ */ new Set());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"blockClass\");\n __publicField(this, \"blockSelector\");\n __publicField(this, \"maskTextClass\");\n __publicField(this, \"maskTextSelector\");\n __publicField(this, \"inlineStylesheet\");\n __publicField(this, \"maskInputOptions\");\n __publicField(this, \"maskTextFn\");\n __publicField(this, \"maskInputFn\");\n __publicField(this, \"keepIframeSrcFn\");\n __publicField(this, \"recordCanvas\");\n __publicField(this, \"inlineImages\");\n __publicField(this, \"slimDOMOptions\");\n __publicField(this, \"dataURLOptions\");\n __publicField(this, \"doc\");\n __publicField(this, \"mirror\");\n __publicField(this, \"iframeManager\");\n __publicField(this, \"stylesheetManager\");\n __publicField(this, \"shadowDomManager\");\n __publicField(this, \"canvasManager\");\n __publicField(this, \"processedNodeManager\");\n __publicField(this, \"unattachedDoc\");\n __publicField(this, \"canvasManagerReleased\", false);\n __publicField(this, \"processMutations\", (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n });\n __publicField(this, \"emit\", () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addedIds = /* @__PURE__ */ new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n const parent = index.parentNode(n);\n if (!parent || !inDom(n) || parent.tagName === \"TEXTAREA\") {\n return;\n }\n const parentId = isShadowRoot(parent) ? this.mirror.getId(getShadowHost(n)) : this.mirror.getId(parent);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n const sn = serializeNodeWithId(n, {\n doc: this.doc,\n mirror: this.mirror,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n maskTextClass: this.maskTextClass,\n maskTextSelector: this.maskTextSelector,\n skipChild: true,\n newlyAddedElement: true,\n inlineStylesheet: this.inlineStylesheet,\n maskInputOptions: this.maskInputOptions,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n dataURLOptions: this.dataURLOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isSerializedIframe(currentN, this.mirror)) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(\n currentN\n );\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(index.shadowRoot(n), this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n this.iframeManager.attachIframe(iframe, childSn);\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n onIframeListenerRegistered: (iframe, disposer) => {\n this.iframeManager.registerLoadListenerDisposer(iframe, disposer);\n },\n onStylesheetLoad: (link, childSn) => {\n this.stylesheetManager.attachLinkElement(link, childSn);\n }\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn\n });\n addedIds.add(sn.id);\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removesSubTreeCache, n, this.mirror) && !this.movedSet.has(index.parentNode(n))) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) && !isParentRemoved(this.removesSubTreeCache, n, this.mirror)) {\n pushAdd(n);\n } else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n } else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(index.parentNode(candidate.value));\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n let tailNode = addList.tail;\n while (tailNode) {\n const _node = tailNode;\n tailNode = tailNode.previous;\n if (_node) {\n const parentId = this.mirror.getId(index.parentNode(_node.value));\n const nextId = getNextId(_node.value);\n if (nextId === -1) continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n } else {\n const unhandledNode = _node.value;\n const parent = index.parentNode(unhandledNode);\n if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = index.host(parent);\n const parentId2 = this.mirror.getId(shadowHost);\n if (parentId2 !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts.map((text) => {\n const n = text.node;\n const parent = index.parentNode(n);\n if (parent && parent.tagName === \"TEXTAREA\") {\n this.genTextAreaValueMutation(parent);\n }\n return {\n id: this.mirror.getId(n),\n value: text.value\n };\n }).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes.map((attribute) => {\n const { attributes } = attribute;\n if (typeof attributes.style === \"string\") {\n const diffAsStr = JSON.stringify(attribute.styleDiff);\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n if (diffAsStr.length < attributes.style.length) {\n if ((diffAsStr + unchangedAsStr).split(\"var(\").length === attributes.style.split(\"var(\").length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes\n };\n }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds\n };\n if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.removesSubTreeCache = /* @__PURE__ */ new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n });\n __publicField(this, \"bufferBelongsToIframe\", (iframeEl) => {\n return this.doc === iframeEl.contentDocument;\n });\n __publicField(this, \"genTextAreaValueMutation\", (textarea) => {\n let item = this.attributeMap.get(textarea);\n if (!item) {\n item = {\n node: textarea,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(textarea, item);\n }\n const value = Array.from(\n index.childNodes(textarea),\n (cn) => index.textContent(cn) || \"\"\n ).join(\"\");\n item.attributes.value = maskInputValue({\n element: textarea,\n maskInputOptions: this.maskInputOptions,\n tagName: textarea.tagName,\n type: getInputType(textarea),\n value,\n maskInputFn: this.maskInputFn\n });\n });\n __publicField(this, \"processMutation\", (m) => {\n if (isIgnored(m.target, this.mirror, this.slimDOMOptions)) {\n return;\n }\n switch (m.type) {\n case \"characterData\": {\n const value = index.textContent(m.target);\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n true\n // checkAncestors\n ) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\\S]/g, \"*\") : value,\n node: m.target\n });\n }\n break;\n }\n case \"attributes\": {\n const target = m.target;\n let attributeName = m.attributeName;\n let value = m.target.getAttribute(attributeName);\n if (attributeName === \"value\") {\n const type = getInputType(target);\n value = maskInputValue({\n element: target,\n maskInputOptions: this.maskInputOptions,\n tagName: target.tagName,\n type,\n value,\n maskInputFn: this.maskInputFn\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === \"IFRAME\" && attributeName === \"src\" && !this.keepIframeSrcFn(value)) {\n if (!target.contentDocument) {\n attributeName = \"rr_src\";\n } else {\n return;\n }\n }\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(m.target, item);\n }\n if (attributeName === \"type\" && target.tagName === \"INPUT\" && (m.oldValue || \"\").toLowerCase() === \"password\") {\n target.setAttribute(\"data-rr-is-password\", \"true\");\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(\n this.doc,\n toLowerCase(target.tagName),\n toLowerCase(attributeName),\n value,\n target,\n this.dataURLOptions\n );\n if (attributeName === \"style\") {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc = document.implementation.createHTMLDocument();\n } catch (e) {\n this.unattachedDoc = this.doc;\n }\n }\n const old = this.unattachedDoc.createElement(\"span\");\n if (m.oldValue) {\n old.style.cssText = m.oldValue;\n }\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === \"\") {\n item.styleDiff[pname] = newValue;\n } else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\n } else {\n item._unchangedStyles[pname] = [newValue, newPriority];\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === \"\") {\n item.styleDiff[pname] = false;\n }\n }\n } else if (attributeName === \"open\" && target.tagName === \"DIALOG\") {\n if (target.matches(\"dialog:modal\")) {\n item.attributes[\"rr_open_mode\"] = \"modal\";\n } else {\n item.attributes[\"rr_open_mode\"] = \"non-modal\";\n }\n }\n }\n break;\n }\n case \"childList\": {\n if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\n return;\n if (m.target.tagName === \"TEXTAREA\") {\n this.genTextAreaValueMutation(m.target);\n return;\n }\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target) ? this.mirror.getId(index.host(m.target)) : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || isIgnored(n, this.mirror, this.slimDOMOptions) || !isSerialized(n, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n } else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) && this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n } else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0\n });\n processRemoves(n, this.removesSubTreeCache);\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n });\n /**\n * Make sure you check if `n`'s parent is blocked before calling this function\n * */\n __publicField(this, \"genAdds\", (n, target) => {\n if (this.processedNodeManager.inOtherBuffer(n, this)) return;\n if (this.addedSet.has(n) || this.movedSet.has(n)) return;\n if (this.mirror.hasNode(n)) {\n if (isIgnored(n, this.mirror, this.slimDOMOptions)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && this.mirror.hasNode(target)) {\n targetId = this.mirror.getId(target);\n }\n if (targetId && targetId !== -1) {\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\n }\n } else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\n index.childNodes(n).forEach((childN) => this.genAdds(childN));\n if (hasShadowRoot(n)) {\n index.childNodes(index.shadowRoot(n)).forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n);\n });\n }\n }\n });\n }\n init(options) {\n [\n \"mutationCb\",\n \"blockClass\",\n \"blockSelector\",\n \"maskTextClass\",\n \"maskTextSelector\",\n \"inlineStylesheet\",\n \"maskInputOptions\",\n \"maskTextFn\",\n \"maskInputFn\",\n \"keepIframeSrcFn\",\n \"recordCanvas\",\n \"inlineImages\",\n \"slimDOMOptions\",\n \"dataURLOptions\",\n \"doc\",\n \"mirror\",\n \"iframeManager\",\n \"stylesheetManager\",\n \"shadowDomManager\",\n \"canvasManager\",\n \"processedNodeManager\"\n ].forEach((key) => {\n this[key] = options[key];\n });\n this.canvasManager.acquire();\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.releaseCanvasManager();\n }\n // Releases at most once even if reset() runs twice (iframe pagehide + stop). Separate from\n // reset() so shadow-root teardown can release without re-entering shadowDomManager.reset().\n releaseCanvasManager() {\n if (this.canvasManagerReleased) {\n return;\n }\n this.canvasManagerReleased = true;\n this.canvasManager.reset();\n }\n bufferDoc() {\n return this.doc;\n }\n destroy() {\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n index.childNodes(n).forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction processRemoves(n, cache) {\n const queue = [n];\n while (queue.length) {\n const next = queue.pop();\n if (cache.has(next)) continue;\n cache.add(next);\n index.childNodes(next).forEach((n2) => queue.push(n2));\n }\n return;\n}\nfunction isParentRemoved(removes, n, mirror2) {\n if (removes.size === 0) return false;\n return _isParentRemoved(removes, n);\n}\nfunction _isParentRemoved(removes, n, _mirror2) {\n const node = index.parentNode(n);\n if (!node) return false;\n return removes.has(node);\n}\nfunction isAncestorInSet(set, n) {\n if (set.size === 0) return false;\n return _isAncestorInSet(set, n);\n}\nfunction _isAncestorInSet(set, n) {\n const parent = index.parentNode(n);\n if (!parent) {\n return false;\n }\n if (set.has(parent)) {\n return true;\n }\n return _isAncestorInSet(set, parent);\n}\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = void 0;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = ((...rest) => {\n try {\n return cb(...rest);\n } catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return;\n }\n throw error;\n }\n });\n return rrwebWrapped;\n};\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if (\"composedPath\" in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n } else if (\"path\" in event && event.path.length) {\n return event.path[0];\n }\n } catch {\n }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n const observer = new (mutationObserverCtor())(\n callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer))\n );\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true\n });\n return { observer, buffer: mutationBuffer };\n}\nfunction initMoveObserver({\n mousemoveCb,\n sampling,\n doc,\n mirror: mirror2\n}) {\n if (sampling.mousemove === false) {\n return () => {\n };\n }\n const threshold = typeof sampling.mousemove === \"number\" ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === \"number\" ? sampling.mousemoveCallback : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle(\n callbackWrapper(\n (source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(\n positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }),\n source\n );\n positions = [];\n timeBaseline = null;\n }\n ),\n callbackThreshold\n );\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror2.getId(target),\n timeOffset: nowTimestamp() - timeBaseline\n });\n wrappedCb(\n typeof DragEvent !== \"undefined\" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove\n );\n }),\n threshold,\n {\n trailing: false\n }\n )\n );\n const handlers = [\n on(\"mousemove\", updatePosition, doc),\n on(\"touchmove\", updatePosition, doc),\n on(\"drag\", updatePosition, doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({\n mouseInteractionCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n sampling\n}) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;\n const handlers = [];\n let currentPointerType = null;\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n let pointerType = null;\n let thisEventKey = eventKey;\n if (\"pointerType\" in event) {\n switch (event.pointerType) {\n case \"mouse\":\n pointerType = PointerTypes.Mouse;\n break;\n case \"touch\":\n pointerType = PointerTypes.Touch;\n break;\n case \"pen\":\n pointerType = PointerTypes.Pen;\n break;\n }\n if (pointerType === PointerTypes.Touch) {\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n thisEventKey = \"TouchStart\";\n } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = \"TouchEnd\";\n }\n } else if (pointerType === PointerTypes.Pen) ;\n } else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if (thisEventKey.startsWith(\"Touch\") && pointerType === PointerTypes.Touch || thisEventKey.startsWith(\"Mouse\") && pointerType === PointerTypes.Mouse) {\n pointerType = null;\n }\n } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror2.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[thisEventKey],\n id,\n x: clientX,\n y: clientY,\n ...pointerType !== null && { pointerType }\n });\n };\n };\n Object.keys(MouseInteractions).filter(\n (key) => Number.isNaN(Number(key)) && !key.endsWith(\"_Departed\") && disableMap[key] !== false\n ).forEach((eventKey) => {\n let eventName = toLowerCase(eventKey);\n const handler = getHandler(eventKey);\n if (window.PointerEvent) {\n switch (MouseInteractions[eventKey]) {\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n eventName = eventName.replace(\n \"mouse\",\n \"pointer\"\n );\n break;\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n return;\n }\n }\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({\n scrollCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n sampling\n}) {\n const lastEmitted = /* @__PURE__ */ new Map();\n const emitScrollPosition = (evt) => {\n const target = getEventTarget(evt);\n if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n const id = mirror2.getId(target);\n let x;\n let y;\n if (target === doc && doc.defaultView) {\n const scrollLeftTop = getWindowScroll(doc.defaultView);\n x = scrollLeftTop.left;\n y = scrollLeftTop.top;\n } else {\n x = target.scrollLeft;\n y = target.scrollTop;\n }\n const key = `${x},${y}`;\n if (lastEmitted.get(id) === key) {\n return;\n }\n lastEmitted.set(id, key);\n scrollCb({ id, x, y });\n };\n const updatePosition = callbackWrapper(\n throttle(\n callbackWrapper((evt) => emitScrollPosition(evt)),\n sampling.scroll || 100\n )\n );\n const handlers = [on(\"scroll\", updatePosition, doc)];\n if (\"onscrollend\" in doc) {\n handlers.push(on(\"scrollend\", callbackWrapper(emitScrollPosition), doc));\n }\n return () => handlers.forEach((h) => h());\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(\n throttle(\n callbackWrapper(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height)\n });\n lastH = height;\n lastW = width;\n }\n }),\n 200\n )\n );\n return on(\"resize\", updateDimension, win);\n}\nfunction findAndRemoveIframeBuffer(iframeEl, knownDocs) {\n for (let i = mutationBuffers.length - 1; i >= 0; i--) {\n const buf = mutationBuffers[i];\n if (!buf) continue;\n let match = buf.bufferBelongsToIframe(iframeEl);\n if (!match && knownDocs && knownDocs.has(buf.bufferDoc())) {\n match = true;\n }\n if (match) {\n buf.reset();\n mutationBuffers.splice(i, 1);\n }\n }\n}\nconst INPUT_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"];\nconst lastInputValueMap = /* @__PURE__ */ new WeakMap();\nfunction initInputObserver({\n inputCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n ignoreClass,\n ignoreSelector,\n maskInputOptions,\n maskInputFn,\n sampling,\n userTriggeredOnInput\n}) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const userTriggered = event.isTrusted;\n const tagName = target && target.tagName;\n if (target && tagName === \"OPTION\") {\n target = index.parentElement(target);\n }\n if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {\n return;\n }\n let text = target.value;\n let isChecked = false;\n const type = getInputType(target) || \"\";\n if (type === \"radio\" || type === \"checkbox\") {\n isChecked = target.checked;\n } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {\n text = maskInputValue({\n element: target,\n maskInputOptions,\n tagName,\n type,\n value: text,\n maskInputFn\n });\n }\n cbWithDedup(\n target,\n userTriggeredOnInput ? { text, isChecked, userTriggered } : { text, isChecked }\n );\n const name = target.name;\n if (type === \"radio\" && name && isChecked) {\n doc.querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`).forEach((el) => {\n if (el !== target) {\n const text2 = el.value;\n cbWithDedup(\n el,\n userTriggeredOnInput ? { text: text2, isChecked: !isChecked, userTriggered: false } : { text: text2, isChecked: !isChecked }\n );\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue || lastInputValue.text !== v.text || lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror2.getId(target);\n callbackWrapper(inputCb)({\n ...v,\n id\n });\n }\n }\n const events = sampling.input === \"last\" ? [\"change\"] : [\"input\", \"change\"];\n const handlers = events.map(\n (eventName) => on(eventName, callbackWrapper(eventHandler), doc)\n );\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n currentWindow.HTMLInputElement.prototype,\n \"value\"\n );\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, \"value\"],\n [currentWindow.HTMLInputElement.prototype, \"checked\"],\n [currentWindow.HTMLSelectElement.prototype, \"value\"],\n [currentWindow.HTMLTextAreaElement.prototype, \"value\"],\n // Some UI library use selectedIndex to set select value\n [currentWindow.HTMLSelectElement.prototype, \"selectedIndex\"],\n [currentWindow.HTMLOptionElement.prototype, \"selected\"]\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(\n ...hookProperties.map(\n (p) => hookSetter(\n p[0],\n p[1],\n {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false\n // userTriggered to false as this could well be programmatic\n });\n }\n },\n false,\n currentWindow\n )\n )\n );\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if (hasNestedCSSRule(\"CSSGroupingRule\") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule(\"CSSMediaRule\") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule(\"CSSSupportsRule\") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule(\"CSSConditionRule\") && childRule.parentRule instanceof CSSConditionRule) {\n const rules = Array.from(\n childRule.parentRule.cssRules\n );\n const index2 = rules.indexOf(childRule);\n pos.unshift(index2);\n return recurse(childRule.parentRule, pos);\n } else if (childRule.parentStyleSheet) {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index2 = rules.indexOf(childRule);\n pos.unshift(index2);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror2, styleMirror) {\n let id, styleId;\n if (!sheet) return {};\n if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);\n else styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => {\n };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [{ rule, index: index2 }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2 = this.cssRules.length) {\n const rule = `${selector} { ${styleBlock} }`;\n return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule, index2]);\n };\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [{ index: index2 }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n win.CSSStyleSheet.prototype.removeRule = function(index2) {\n return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index2]);\n };\n let replace;\n if (win.CSSStyleSheet.prototype.replace) {\n replace = win.CSSStyleSheet.prototype.replace;\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replace: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n let replaceSync;\n if (win.CSSStyleSheet.prototype.replaceSync) {\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replaceSync: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule(\"CSSGroupingRule\")) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n } else {\n if (canMonkeyPatchNestedCSSRule(\"CSSMediaRule\")) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSConditionRule\")) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSSupportsRule\")) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n insertRule: type.prototype.insertRule,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n deleteRule: type.prototype.deleteRule\n };\n type.prototype.insertRule = new Proxy(\n unmodifiedFunctions[typeKey].insertRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index2 || 0\n // defaults to 0\n ]\n }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n type.prototype.deleteRule = new Proxy(\n unmodifiedFunctions[typeKey].deleteRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index2] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index2] }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n replace && (win.CSSStyleSheet.prototype.replace = replace);\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initAdoptedStyleSheetObserver({\n mirror: mirror2,\n stylesheetManager\n}, host2) {\n var _a2, _b, _c;\n let hostId = null;\n if (host2.nodeName === \"#document\") hostId = mirror2.getId(host2);\n else hostId = mirror2.getId(index.host(host2));\n const patchTarget = host2.nodeName === \"#document\" ? (_a2 = host2.defaultView) == null ? void 0 : _a2.Document : (_c = (_b = host2.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;\n const originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(\n patchTarget == null ? void 0 : patchTarget.prototype,\n \"adoptedStyleSheets\"\n ) : void 0;\n if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host2, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n var _a3;\n return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);\n },\n set(sheets) {\n var _a3;\n const result = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n } catch (e) {\n }\n }\n return result;\n }\n });\n return callbackWrapper(() => {\n Object.defineProperty(host2, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n get: originalPropertyDescriptor.get,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n set: originalPropertyDescriptor.set\n });\n });\n}\nfunction initStyleDeclarationObserver({\n styleDeclarationCb,\n mirror: mirror2,\n ignoreCSSAttributes,\n stylesheetManager\n}, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n var _a2;\n const [property, value, priority] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return setProperty.apply(thisArg, [property, value, priority]);\n }\n const { id, styleId } = getIdAndStyleId(\n (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n var _a2;\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(\n (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({\n mediaInteractionCb,\n blockClass,\n blockSelector,\n mirror: mirror2,\n sampling,\n doc\n}) {\n const handler = callbackWrapper(\n (type) => throttle(\n callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n return;\n }\n const { currentTime, volume, muted, playbackRate, loop } = target;\n mediaInteractionCb({\n type,\n id: mirror2.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate,\n loop\n });\n }),\n sampling.media || 500\n )\n );\n const handlers = [\n on(\"play\", handler(MediaInteractions.Play), doc),\n on(\"pause\", handler(MediaInteractions.Pause), doc),\n on(\"seeked\", handler(MediaInteractions.Seeked), doc),\n on(\"volumechange\", handler(MediaInteractions.VolumeChange), doc),\n on(\"ratechange\", handler(MediaInteractions.RateChange), doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => {\n };\n }\n const handlers = [];\n const fontMap = /* @__PURE__ */ new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(\n family,\n source,\n descriptors\n );\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== \"string\",\n descriptors,\n fontSource: typeof source === \"string\" ? source : JSON.stringify(Array.from(new Uint8Array(source)))\n });\n return fontFace;\n };\n const restoreHandler = patch(\n doc.fonts,\n \"add\",\n function(original) {\n return function(fontFace) {\n setTimeout(\n callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }),\n 0\n );\n return original.apply(this, [fontFace]);\n };\n }\n );\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initSelectionObserver(param) {\n const { doc, mirror: mirror2, blockClass, blockSelector, selectionCb } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i = 0; i < count; i++) {\n const range = selection.getRangeAt(i);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);\n if (blocked) continue;\n ranges.push({\n start: mirror2.getId(startContainer),\n startOffset,\n end: mirror2.getId(endContainer),\n endOffset\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on(\"selectionchange\", updateSelection);\n}\nfunction initCustomElementObserver({\n doc,\n customElementCb\n}) {\n const win = doc.defaultView;\n if (!win || !win.customElements) return () => {\n };\n const restoreHandler = patch(\n win.customElements,\n \"define\",\n function(original) {\n return function(name, constructor, options) {\n try {\n customElementCb({\n define: {\n name\n }\n });\n } catch (e) {\n console.warn(`Custom element callback failed for ${name}`);\n }\n return original.apply(this, [name, constructor, options]);\n };\n }\n );\n return restoreHandler;\n}\nfunction mergeHooks(o, hooks) {\n const {\n mutationCb,\n mousemoveCb,\n mouseInteractionCb,\n scrollCb,\n viewportResizeCb,\n inputCb,\n mediaInteractionCb,\n styleSheetRuleCb,\n styleDeclarationCb,\n canvasMutationCb,\n fontCb,\n selectionCb,\n customElementCb\n } = o;\n o.mutationCb = (...p) => {\n if (hooks.mutation) {\n hooks.mutation(...p);\n }\n mutationCb(...p);\n };\n o.mousemoveCb = (...p) => {\n if (hooks.mousemove) {\n hooks.mousemove(...p);\n }\n mousemoveCb(...p);\n };\n o.mouseInteractionCb = (...p) => {\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction(...p);\n }\n mouseInteractionCb(...p);\n };\n o.scrollCb = (...p) => {\n if (hooks.scroll) {\n hooks.scroll(...p);\n }\n scrollCb(...p);\n };\n o.viewportResizeCb = (...p) => {\n if (hooks.viewportResize) {\n hooks.viewportResize(...p);\n }\n viewportResizeCb(...p);\n };\n o.inputCb = (...p) => {\n if (hooks.input) {\n hooks.input(...p);\n }\n inputCb(...p);\n };\n o.mediaInteractionCb = (...p) => {\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction(...p);\n }\n mediaInteractionCb(...p);\n };\n o.styleSheetRuleCb = (...p) => {\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule(...p);\n }\n styleSheetRuleCb(...p);\n };\n o.styleDeclarationCb = (...p) => {\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration(...p);\n }\n styleDeclarationCb(...p);\n };\n o.canvasMutationCb = (...p) => {\n if (hooks.canvasMutation) {\n hooks.canvasMutation(...p);\n }\n canvasMutationCb(...p);\n };\n o.fontCb = (...p) => {\n if (hooks.font) {\n hooks.font(...p);\n }\n fontCb(...p);\n };\n o.selectionCb = (...p) => {\n if (hooks.selection) {\n hooks.selection(...p);\n }\n selectionCb(...p);\n };\n o.customElementCb = (...c) => {\n if (hooks.customElement) {\n hooks.customElement(...c);\n }\n customElementCb(...c);\n };\n}\nfunction initObservers(o, hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n mergeHooks(o, hooks);\n let mutationObserver;\n let mutationBuffer;\n if (o.recordDOM) {\n const result = initMutationObserver(o, o.doc);\n mutationObserver = result.observer;\n mutationBuffer = result.buffer;\n }\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o, {\n win: currentWindow\n });\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n let styleSheetObserver = () => {\n };\n let adoptedStyleSheetObserver = () => {\n };\n let styleDeclarationObserver = () => {\n };\n let fontObserver = () => {\n };\n if (o.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow\n });\n if (o.collectFonts) {\n fontObserver = initFontObserver(o);\n }\n }\n const selectionObserver = initSelectionObserver(o);\n const customElementObserver = initCustomElementObserver(o);\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(\n plugin.observer(plugin.callback, currentWindow, plugin.options)\n );\n }\n return callbackWrapper(() => {\n if (mutationBuffer) {\n mutationBuffer.destroy();\n mutationBuffer.reset();\n const index2 = mutationBuffers.indexOf(mutationBuffer);\n if (index2 !== -1) {\n mutationBuffers.splice(index2, 1);\n }\n }\n mutationObserver == null ? void 0 : mutationObserver.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n adoptedStyleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n selectionObserver();\n customElementObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== \"undefined\";\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(\n typeof window[prop] !== \"undefined\" && // Note: Generally, this check _shouldn't_ be necessary\n // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n window[prop].prototype && \"insertRule\" in window[prop].prototype && \"deleteRule\" in window[prop].prototype\n );\n}\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n __publicField(this, \"iframeIdToRemoteIdMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"iframeRemoteIdToIdMap\", /* @__PURE__ */ new WeakMap());\n this.generateIdFn = generateIdFn;\n }\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n let id = idToRemoteIdMap.get(remoteId);\n if (!id) {\n id = this.generateIdFn();\n idToRemoteIdMap.set(remoteId, id);\n remoteIdToIdMap.set(id, remoteId);\n }\n return id;\n }\n getIds(iframe, remoteId) {\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return remoteId.map(\n (id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)\n );\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== \"number\") return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId) return -1;\n return remoteId;\n }\n getRemoteIds(iframe, ids) {\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n }\n reset(iframe) {\n if (!iframe) {\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n return;\n }\n this.iframeIdToRemoteIdMap.delete(iframe);\n this.iframeRemoteIdToIdMap.delete(iframe);\n }\n getIdToRemoteIdMap(iframe) {\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n if (!idToRemoteIdMap) {\n idToRemoteIdMap = /* @__PURE__ */ new Map();\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n }\n return idToRemoteIdMap;\n }\n getRemoteIdToIdMap(iframe) {\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n if (!remoteIdToIdMap) {\n remoteIdToIdMap = /* @__PURE__ */ new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\nclass IframeManager {\n constructor(options) {\n __publicField(this, \"iframes\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"crossOriginIframeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"crossOriginIframeMirror\", new CrossOriginIframeMirror(genId));\n __publicField(this, \"crossOriginIframeStyleMirror\");\n __publicField(this, \"crossOriginIframeRootIdMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"mirror\");\n __publicField(this, \"mutationCb\");\n __publicField(this, \"wrappedEmit\");\n __publicField(this, \"loadListener\");\n __publicField(this, \"pageHideListener\");\n __publicField(this, \"stylesheetManager\");\n __publicField(this, \"recordCrossOriginIframes\");\n __publicField(this, \"messageHandler\");\n // Strong Map — keys pin Windows; every entry must be deleted on detach.\n __publicField(this, \"nestedIframeListeners\", /* @__PURE__ */ new Map());\n // Originals captured per iframe so cleanup survives iframe.src swaps.\n __publicField(this, \"attachedWindows\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"attachedDocuments\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"attachedIframes\", /* @__PURE__ */ new Map());\n // Set per element — one iframe collects multiple disposers across loads.\n __publicField(this, \"loadListenerDisposers\", /* @__PURE__ */ new WeakMap());\n // Fallback for iframes removed before first load — mirror entry is gone\n // by then, but we still need the element to dispose its load listener.\n __publicField(this, \"iframeElementsById\", /* @__PURE__ */ new Map());\n // Set per element — same multi-load reasoning as loadListenerDisposers.\n __publicField(this, \"pageHideHandlers\", /* @__PURE__ */ new WeakMap());\n this.mutationCb = options.mutationCb;\n this.wrappedEmit = options.wrappedEmit;\n this.stylesheetManager = options.stylesheetManager;\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n this.stylesheetManager.styleMirror.generateId.bind(\n this.stylesheetManager.styleMirror\n )\n );\n this.mirror = options.mirror;\n this.messageHandler = this.handleMessage.bind(this);\n if (this.recordCrossOriginIframes) {\n window.addEventListener(\"message\", this.messageHandler);\n }\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n if (iframeEl.contentWindow)\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n }\n registerLoadListenerDisposer(iframeEl, disposer) {\n let bucket = this.loadListenerDisposers.get(iframeEl);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n this.loadListenerDisposers.set(iframeEl, bucket);\n }\n bucket.add(disposer);\n const id = this.mirror.getId(iframeEl);\n if (id !== -1) this.iframeElementsById.set(id, iframeEl);\n }\n // Used by the record-loop to distinguish reparenting from removal.\n getIframeElementById(iframeId) {\n var _a2;\n return ((_a2 = this.attachedIframes.get(iframeId)) == null ? void 0 : _a2.element) ?? this.iframeElementsById.get(iframeId) ?? null;\n }\n // Drops the id mapping for a moved iframe; element-keyed state survives.\n forgetIframeId(iframeId) {\n this.attachedIframes.delete(iframeId);\n this.iframeElementsById.delete(iframeId);\n }\n disposeLoadListeners(iframeEl) {\n const bucket = this.loadListenerDisposers.get(iframeEl);\n if (!bucket) return;\n bucket.forEach((d) => callSafely(d));\n this.loadListenerDisposers.delete(iframeEl);\n }\n removePageHideListener(iframeEl) {\n const bucket = this.pageHideHandlers.get(iframeEl);\n if (!bucket) return;\n bucket.forEach(({ win, handler }) => {\n callSafely(() => win.removeEventListener(\"pagehide\", handler));\n });\n this.pageHideHandlers.delete(iframeEl);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n addPageHideListener(cb) {\n this.pageHideListener = cb;\n }\n removeLoadListener() {\n this.loadListener = void 0;\n }\n trackIframeContent(iframeEl, content) {\n const iframeId = this.mirror.getId(iframeEl);\n this.attachedIframes.set(iframeId, { element: iframeEl, content });\n return iframeId;\n }\n attachIframe(iframeEl, childSn) {\n var _a2;\n const iframeId = this.trackIframeContent(iframeEl, childSn);\n if (iframeEl.contentDocument) {\n let docs = this.attachedDocuments.get(iframeEl);\n if (!docs) {\n docs = /* @__PURE__ */ new Set();\n this.attachedDocuments.set(iframeEl, docs);\n }\n docs.add(iframeEl.contentDocument);\n }\n this.mutationCb({\n adds: [\n {\n parentId: iframeId,\n nextId: null,\n node: childSn\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n const win = iframeEl.contentWindow;\n if (this.recordCrossOriginIframes && win && !this.nestedIframeListeners.has(win)) {\n const nestedHandler = this.handleMessage.bind(this);\n callSafely(() => {\n win.addEventListener(\"message\", nestedHandler);\n this.nestedIframeListeners.set(win, nestedHandler);\n let wins = this.attachedWindows.get(iframeEl);\n if (!wins) {\n wins = /* @__PURE__ */ new Set();\n this.attachedWindows.set(iframeEl, wins);\n }\n wins.add(win);\n });\n }\n callSafely(() => {\n const pageHideWindow = iframeEl.contentWindow;\n if (!pageHideWindow) return;\n let bucket = this.pageHideHandlers.get(iframeEl);\n if (bucket) {\n for (const entry of bucket) {\n if (entry.win === pageHideWindow) return;\n }\n }\n const handler = () => {\n var _a3;\n (_a3 = this.pageHideListener) == null ? void 0 : _a3.call(this, iframeEl);\n if (iframeEl.contentDocument) {\n this.mirror.removeNodeFromMap(iframeEl.contentDocument);\n }\n if (iframeEl.contentWindow) {\n this.crossOriginIframeMap.delete(iframeEl.contentWindow);\n }\n };\n pageHideWindow.addEventListener(\"pagehide\", handler);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n this.pageHideHandlers.set(iframeEl, bucket);\n }\n bucket.add({ win: pageHideWindow, handler });\n });\n (_a2 = this.loadListener) == null ? void 0 : _a2.call(this, iframeEl);\n if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(\n iframeEl.contentDocument.adoptedStyleSheets,\n this.mirror.getId(iframeEl.contentDocument)\n );\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== \"rrweb\" || // To filter out the rrweb messages which are forwarded by some sites.\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow) return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl) return;\n const transformedEvent = this.transformCrossOriginEvent(\n iframeEl,\n crossOriginMessageEvent.data.event\n );\n if (transformedEvent)\n this.wrappedEmit(\n transformedEvent,\n crossOriginMessageEvent.data.isCheckout\n );\n }\n transformCrossOriginEvent(iframeEl, e) {\n var _a2;\n switch (e.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e.data.node, iframeEl);\n const rootId = e.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e.data.node, rootId);\n this.trackIframeContent(iframeEl, e.data.node);\n return {\n timestamp: e.timestamp,\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: e.data.node\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n }\n };\n }\n case EventType.Meta:\n case EventType.Load:\n case EventType.DomContentLoaded: {\n return false;\n }\n case EventType.Plugin: {\n return e;\n }\n case EventType.Custom: {\n this.replaceIds(\n e.data.payload,\n iframeEl,\n [\"id\", \"parentId\", \"previousId\", \"nextId\"]\n );\n return e;\n }\n case EventType.IncrementalSnapshot: {\n switch (e.data.source) {\n case IncrementalSource.Mutation: {\n e.data.adds.forEach((n) => {\n this.replaceIds(n, iframeEl, [\n \"parentId\",\n \"nextId\",\n \"previousId\"\n ]);\n this.replaceIdOnNode(n.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n.node, rootId);\n });\n e.data.removes.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"parentId\", \"id\"]);\n });\n e.data.attributes.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"id\"]);\n });\n e.data.texts.forEach((n) => {\n this.replaceIds(n, iframeEl, [\"id\"]);\n });\n return e;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, [\"id\"]);\n });\n return e;\n }\n case IncrementalSource.ViewportResize: {\n return false;\n }\n case IncrementalSource.MediaInteraction:\n case IncrementalSource.MouseInteraction:\n case IncrementalSource.Scroll:\n case IncrementalSource.CanvasMutation:\n case IncrementalSource.Input: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n return e;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e.data, iframeEl, [\"styleId\"]);\n return e;\n }\n case IncrementalSource.Font: {\n return e;\n }\n case IncrementalSource.Selection: {\n e.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, [\"start\", \"end\"]);\n });\n return e;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e.data, iframeEl, [\"styleIds\"]);\n (_a2 = e.data.styles) == null ? void 0 : _a2.forEach((style) => {\n this.replaceStyleIds(style, iframeEl, [\"styleId\"]);\n });\n return e;\n }\n }\n }\n }\n return false;\n }\n replace(iframeMirror, obj, iframeEl, keys) {\n for (const key of keys) {\n if (!Array.isArray(obj[key]) && typeof obj[key] !== \"number\") continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(\n iframeEl,\n obj[key]\n );\n } else {\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n }\n }\n return obj;\n }\n replaceIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n }\n replaceStyleIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n }\n replaceIdOnNode(node, iframeEl) {\n this.replaceIds(node, iframeEl, [\"id\", \"rootId\"]);\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.replaceIdOnNode(child, iframeEl);\n });\n }\n }\n patchRootIdOnNode(node, rootId) {\n if (node.type !== NodeType.Document && !node.rootId) node.rootId = rootId;\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\n }\n }\n removeIframeById(iframeId) {\n const entry = this.attachedIframes.get(iframeId);\n const iframe = (entry == null ? void 0 : entry.element) || this.iframeElementsById.get(iframeId) || this.mirror.getNode(iframeId);\n this.iframeElementsById.delete(iframeId);\n if (iframe) {\n const win = iframe.contentWindow;\n const capturedWins = this.attachedWindows.get(iframe);\n if (capturedWins) {\n capturedWins.forEach((capturedWin) => {\n const handler = this.nestedIframeListeners.get(capturedWin);\n if (handler) {\n callSafely(\n () => capturedWin.removeEventListener(\"message\", handler)\n );\n this.nestedIframeListeners.delete(capturedWin);\n }\n this.crossOriginIframeMap.delete(capturedWin);\n });\n this.attachedWindows.delete(iframe);\n }\n if (win && this.nestedIframeListeners.has(win)) {\n const handler = this.nestedIframeListeners.get(win);\n callSafely(() => win.removeEventListener(\"message\", handler));\n this.nestedIframeListeners.delete(win);\n }\n if (win) {\n this.crossOriginIframeMap.delete(win);\n }\n this.iframes.delete(iframe);\n this.disposeLoadListeners(iframe);\n this.removePageHideListener(iframe);\n const capturedDocs = this.attachedDocuments.get(iframe);\n if (capturedDocs) {\n capturedDocs.forEach((doc) => {\n callSafely(() => this.mirror.removeNodeFromMap(doc));\n });\n callSafely(() => findAndRemoveIframeBuffer(iframe, capturedDocs));\n this.attachedDocuments.delete(iframe);\n }\n }\n if (entry) {\n this.attachedIframes.delete(iframeId);\n }\n }\n // Catches iframes removed inside a removed subtree (only the\n // ancestor's id appears in m.removes).\n cleanupDetachedIframes() {\n if (this.attachedIframes.size === 0) return;\n const orphaned = [];\n this.attachedIframes.forEach((_entry, iframeId) => {\n if (!this.mirror.has(iframeId)) {\n orphaned.push(iframeId);\n }\n });\n orphaned.forEach((iframeId) => this.removeIframeById(iframeId));\n }\n reattachIframes() {\n this.attachedIframes.forEach(({ content }, iframeId) => {\n if (!this.mirror.has(iframeId)) {\n this.attachedIframes.delete(iframeId);\n return;\n }\n this.mutationCb({\n adds: [\n {\n parentId: iframeId,\n nextId: null,\n node: content\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n });\n }\n destroy() {\n if (this.recordCrossOriginIframes) {\n window.removeEventListener(\"message\", this.messageHandler);\n }\n this.nestedIframeListeners.forEach((handler, contentWindow) => {\n callSafely(() => contentWindow.removeEventListener(\"message\", handler));\n });\n this.nestedIframeListeners.clear();\n const tracked = /* @__PURE__ */ new Set();\n this.iframeElementsById.forEach((el) => tracked.add(el));\n this.attachedIframes.forEach(({ element }) => tracked.add(element));\n tracked.forEach((iframe) => {\n this.disposeLoadListeners(iframe);\n this.removePageHideListener(iframe);\n });\n this.crossOriginIframeMirror.reset();\n this.crossOriginIframeStyleMirror.reset();\n this.attachedIframes.clear();\n this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();\n this.iframes = /* @__PURE__ */ new WeakMap();\n this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n this.loadListenerDisposers = /* @__PURE__ */ new WeakMap();\n this.pageHideHandlers = /* @__PURE__ */ new WeakMap();\n this.attachedDocuments = /* @__PURE__ */ new WeakMap();\n this.attachedWindows = /* @__PURE__ */ new WeakMap();\n this.iframeElementsById = /* @__PURE__ */ new Map();\n }\n}\nclass ShadowDomManager {\n constructor(options) {\n __publicField(this, \"shadowDoms\", /* @__PURE__ */ new WeakSet());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"scrollCb\");\n __publicField(this, \"bypassOptions\");\n __publicField(this, \"mirror\");\n __publicField(this, \"restoreHandlers\", []);\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n this.init();\n }\n init() {\n this.reset();\n this.patchAttachShadow(Element, document);\n }\n addShadowRoot(shadowRoot2, doc) {\n if (!isNativeShadowDom(shadowRoot2)) return;\n if (this.shadowDoms.has(shadowRoot2)) return;\n this.shadowDoms.add(shadowRoot2);\n const { observer, buffer } = initMutationObserver(\n {\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this\n },\n shadowRoot2\n );\n this.restoreHandlers.push(() => {\n observer.disconnect();\n buffer.destroy();\n buffer.releaseCanvasManager();\n const index2 = mutationBuffers.indexOf(buffer);\n if (index2 !== -1) {\n mutationBuffers.splice(index2, 1);\n }\n });\n this.restoreHandlers.push(\n initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n doc: shadowRoot2,\n mirror: this.mirror\n })\n );\n setTimeout(() => {\n if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(\n shadowRoot2.adoptedStyleSheets,\n this.mirror.getId(index.host(shadowRoot2))\n );\n this.restoreHandlers.push(\n initAdoptedStyleSheetObserver(\n {\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager\n },\n shadowRoot2\n )\n );\n }, 0);\n }\n /**\n * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n */\n observeAttachShadow(iframeElement) {\n if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;\n this.patchAttachShadow(\n iframeElement.contentWindow.Element,\n iframeElement.contentDocument\n );\n }\n /**\n * Patch 'attachShadow' to observe newly added shadow doms.\n */\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(\n patch(\n element.prototype,\n \"attachShadow\",\n function(original) {\n return function(option) {\n const sRoot = original.call(this, option);\n const shadowRootEl = index.shadowRoot(this);\n if (shadowRootEl && inDom(this))\n manager.addShadowRoot(shadowRootEl, doc);\n return sRoot;\n };\n }\n )\n );\n }\n reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n } catch (e) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n }\n}\nvar chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = \"\";\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n return base64;\n};\nconst canvasVarMap = /* @__PURE__ */ new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = canvasVarMap.get(ctx);\n if (!contextMap) {\n contextMap = /* @__PURE__ */ new Map();\n canvasVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === \"object\"))\n return;\n const name = value.constructor.name;\n const list = variableListFor(ctx, name);\n let index2 = list.indexOf(value);\n if (index2 === -1) {\n index2 = list.length;\n list.push(value);\n }\n return index2;\n};\nfunction serializeArg(value, win, ctx, dataURLOptions) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n } else if (value === null) {\n return value;\n } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)]\n };\n } else if (\n // SharedArrayBuffer disabled on most browsers due to spectre.\n // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n // value instanceof SharedArrayBuffer ||\n value instanceof ArrayBuffer\n ) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64\n };\n } else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx, dataURLOptions),\n value.byteOffset,\n value.byteLength\n ]\n };\n } else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof HTMLCanvasElement) {\n const name = \"HTMLImageElement\";\n const src = value.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n return {\n rr_type: name,\n src\n };\n } else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.data, win, ctx, dataURLOptions),\n value.width,\n value.height\n ]\n };\n } else if (isInstanceOfWebGLObject(value, win) || typeof value === \"object\") {\n const name = value.constructor.name;\n const index2 = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index: index2\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx, dataURLOptions) => {\n return args.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n \"WebGLActiveInfo\",\n \"WebGLBuffer\",\n \"WebGLFramebuffer\",\n \"WebGLProgram\",\n \"WebGLRenderbuffer\",\n \"WebGLShader\",\n \"WebGLShaderPrecisionFormat\",\n \"WebGLTexture\",\n \"WebGLUniformLocation\",\n \"WebGLVertexArrayObject\",\n // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.\n \"WebGLVertexArrayObjectOES\"\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter(\n (name) => typeof win[name] === \"function\"\n );\n return Boolean(\n supportedWebGLConstructorNames.find(\n (name) => value instanceof win[name]\n )\n );\n};\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector, dataURLOptions) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(\n win.CanvasRenderingContext2D.prototype\n );\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n win.CanvasRenderingContext2D.prototype,\n prop,\n function(original) {\n return function(...args) {\n if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\n setTimeout(() => {\n const recordArgs = serializeArgs(\n args,\n win,\n this,\n dataURLOptions\n );\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: recordArgs\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(\n win.CanvasRenderingContext2D.prototype,\n prop,\n {\n set(v) {\n cb(this.canvas, {\n type: CanvasContext[\"2D\"],\n property: prop,\n args: [v],\n setter: true\n });\n }\n }\n );\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nconst WEBGL_CONTEXT_NAMES = [\"webgl\", \"webgl2\"];\nfunction getNormalizedContextName(contextType) {\n return contextType === \"experimental-webgl\" ? \"webgl\" : contextType;\n}\nfunction getRequiredWebGPUTextureUsage(win) {\n const textureUsage = win.GPUTextureUsage;\n if (!textureUsage) {\n return null;\n }\n return textureUsage.COPY_SRC | textureUsage.RENDER_ATTACHMENT;\n}\nfunction getCanvasFromWebGPUContext(context) {\n const { canvas } = context;\n if (!canvas || typeof canvas !== \"object\") {\n return null;\n }\n return canvas;\n}\nfunction isCanvasNode(canvas) {\n return \"nodeType\" in canvas;\n}\nfunction initCanvasWebGPUContextObserver(win, blockClass, blockSelector) {\n const GPUCanvasContext = win.GPUCanvasContext;\n if (!(GPUCanvasContext == null ? void 0 : GPUCanvasContext.prototype) || typeof GPUCanvasContext.prototype.configure !== \"function\") {\n return;\n }\n return patch(\n GPUCanvasContext.prototype,\n \"configure\",\n function(original) {\n return function(configuration) {\n const canvas = getCanvasFromWebGPUContext(this);\n if (!canvas || isCanvasNode(canvas) && isBlocked(canvas, blockClass, blockSelector, true)) {\n return original.call(this, configuration);\n }\n if (isCanvasNode(canvas) && !(\"__context\" in canvas)) {\n canvas.__context = \"webgpu\";\n }\n const requiredUsage = getRequiredWebGPUTextureUsage(win);\n if (requiredUsage === null || !configuration) {\n return original.call(this, configuration);\n }\n return original.call(this, {\n ...configuration,\n // WebGPU does not implicitly keep RENDER_ATTACHMENT when usage is set,\n // so include both flags needed for drawing and snapshot reads.\n usage: typeof configuration.usage === \"number\" ? configuration.usage | requiredUsage : requiredUsage\n });\n };\n }\n );\n}\nfunction initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {\n const handlers = [];\n try {\n if (setPreserveDrawingBufferToTrue) {\n const restoreWebGPUConfigureHandler = initCanvasWebGPUContextObserver(\n win,\n blockClass,\n blockSelector\n );\n if (restoreWebGPUConfigureHandler) {\n handlers.push(restoreWebGPUConfigureHandler);\n }\n }\n const restoreHandler = patch(\n win.HTMLCanvasElement.prototype,\n \"getContext\",\n function(original) {\n return function(contextType, ...args) {\n const ctxName = getNormalizedContextName(contextType);\n if (!isBlocked(this, blockClass, blockSelector, true)) {\n if (!(\"__context\" in this)) this.__context = ctxName;\n if (setPreserveDrawingBufferToTrue && WEBGL_CONTEXT_NAMES.includes(ctxName)) {\n if (args[0] && typeof args[0] === \"object\") {\n const contextAttributes = args[0];\n if (!contextAttributes.preserveDrawingBuffer) {\n contextAttributes.preserveDrawingBuffer = true;\n }\n } else {\n args.splice(0, 1, {\n preserveDrawingBuffer: true\n });\n }\n }\n }\n return original.apply(this, [contextType, ...args]);\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n console.error(\"failed to patch HTMLCanvasElement.prototype.getContext\");\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win, dataURLOptions) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n if (\n //prop.startsWith('get') || // e.g. getProgramParameter, but too risky\n [\n \"isContextLost\",\n \"canvas\",\n \"drawingBufferWidth\",\n \"drawingBufferHeight\"\n ].includes(prop)\n ) {\n continue;\n }\n try {\n if (typeof prototype[prop] !== \"function\") {\n continue;\n }\n const restoreHandler = patch(\n prototype,\n prop,\n function(original) {\n return function(...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, this);\n if (\"tagName\" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {\n const recordArgs = serializeArgs(args, win, this, dataURLOptions);\n const mutation = {\n type,\n property: prop,\n args: recordArgs\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n }\n );\n handlers.push(restoreHandler);\n } catch {\n const hookHandler = hookSetter(prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v],\n setter: true\n });\n }\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, dataURLOptions) {\n const handlers = [];\n if (typeof win.WebGLRenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGLRenderingContext.prototype,\n CanvasContext.WebGL,\n cb,\n blockClass,\n blockSelector,\n win,\n dataURLOptions\n )\n );\n }\n if (typeof win.WebGL2RenderingContext !== \"undefined\") {\n handlers.push(\n ...patchGLPrototype(\n win.WebGL2RenderingContext.prototype,\n CanvasContext.WebGL2,\n cb,\n blockClass,\n blockSelector,\n win,\n dataURLOptions\n )\n );\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\nconst jsContent = '(function() {\\n \"use strict\";\\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\\n var lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\\n for (var i = 0; i < chars.length; i++) {\\n lookup[chars.charCodeAt(i)] = i;\\n }\\n var encode = function(arraybuffer) {\\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = \"\";\\n for (i2 = 0; i2 < len; i2 += 3) {\\n base64 += chars[bytes[i2] >> 2];\\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\\n base64 += chars[bytes[i2 + 2] & 63];\\n }\\n if (len % 3 === 2) {\\n base64 = base64.substring(0, base64.length - 1) + \"=\";\\n } else if (len % 3 === 1) {\\n base64 = base64.substring(0, base64.length - 2) + \"==\";\\n }\\n return base64;\\n };\\n const lastFingerprintMap = /* @__PURE__ */ new Map();\\n const transparentBlobMap = /* @__PURE__ */ new Map();\\n function fnv1aHash(buffer) {\\n const view = new Uint8Array(buffer);\\n let hash = 2166136261;\\n for (let i2 = 0; i2 < view.length; i2++) {\\n hash ^= view[i2];\\n hash = hash * 16777619 | 0;\\n }\\n return (hash >>> 0).toString(16);\\n }\\n async function getTransparentBlobFor(width, height, dataURLOptions) {\\n const id = `${width}-${height}`;\\n if (\"OffscreenCanvas\" in globalThis) {\\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\\n const offscreen = new OffscreenCanvas(width, height);\\n offscreen.getContext(\"2d\");\\n const blob = await offscreen.convertToBlob(dataURLOptions);\\n const arrayBuffer = await blob.arrayBuffer();\\n const base64 = encode(arrayBuffer);\\n transparentBlobMap.set(id, base64);\\n return base64;\\n } else {\\n return \"\";\\n }\\n }\\n const worker = self;\\n let reusableCanvas = null;\\n let reusableCtx = null;\\n worker.onmessage = async function(e) {\\n if (\"OffscreenCanvas\" in globalThis) {\\n const { id, bitmap, width, height, displayWidth, displayHeight, dataURLOptions } = e.data;\\n try {\\n const transparentBase64 = getTransparentBlobFor(\\n width,\\n height,\\n dataURLOptions\\n );\\n if (!reusableCanvas || reusableCanvas.width !== width || reusableCanvas.height !== height) {\\n reusableCanvas = new OffscreenCanvas(width, height);\\n reusableCtx = reusableCanvas.getContext(\"2d\");\\n }\\n reusableCtx.clearRect(0, 0, width, height);\\n reusableCtx.drawImage(bitmap, 0, 0);\\n bitmap.close();\\n const blob = await reusableCanvas.convertToBlob(dataURLOptions);\\n const type = blob.type;\\n const arrayBuffer = await blob.arrayBuffer();\\n const fingerprint = fnv1aHash(arrayBuffer);\\n if (!lastFingerprintMap.has(id)) {\\n const base642 = encode(arrayBuffer);\\n if (await transparentBase64 === base642) {\\n lastFingerprintMap.set(id, fingerprint);\\n return worker.postMessage({ id });\\n }\\n lastFingerprintMap.set(id, fingerprint);\\n worker.postMessage({ id, type, base64: base642, displayWidth, displayHeight });\\n return;\\n }\\n if (lastFingerprintMap.get(id) === fingerprint)\\n return worker.postMessage({ id });\\n const base64 = encode(arrayBuffer);\\n worker.postMessage({ id, type, base64, displayWidth, displayHeight });\\n lastFingerprintMap.set(id, fingerprint);\\n } catch {\\n worker.postMessage({ id });\\n }\\n } else {\\n e.data.bitmap.close();\\n return worker.postMessage({ id: e.data.id });\\n }\\n };\\n})();\\n//# sourceMappingURL=image-bitmap-data-url-worker-CSpkoNCs.js.map\\n';\nconst blob = typeof self !== \"undefined\" && self.Blob && new Blob([jsContent], { type: \"text/javascript;charset=utf-8\" });\nfunction WorkerWrapper(options) {\n let objURL;\n try {\n objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);\n if (!objURL) throw \"\";\n const worker = new Worker(objURL, {\n name: options == null ? void 0 : options.name\n });\n worker.addEventListener(\"error\", () => {\n (self.URL || self.webkitURL).revokeObjectURL(objURL);\n });\n return worker;\n } catch (e) {\n return new Worker(\n \"data:text/javascript;charset=utf-8,\" + encodeURIComponent(jsContent),\n {\n name: options == null ? void 0 : options.name\n }\n );\n } finally {\n objURL && (self.URL || self.webkitURL).revokeObjectURL(objURL);\n }\n}\nconst MIN_CANVAS_RESOLUTION_SCALE = 0.1;\nclass CanvasManager {\n constructor(options) {\n __publicField(this, \"pendingCanvasMutations\", /* @__PURE__ */ new Map());\n __publicField(this, \"rafStamps\", { latestId: 0, invokeId: null });\n __publicField(this, \"mirror\");\n __publicField(this, \"mutationCb\");\n __publicField(this, \"resetObservers\");\n __publicField(this, \"frozen\", false);\n __publicField(this, \"locked\", false);\n __publicField(this, \"rafIdTimestamp\", null);\n __publicField(this, \"rafIdFlush\", null);\n __publicField(this, \"refCount\", 0);\n __publicField(this, \"torndown\", false);\n __publicField(this, \"processMutation\", (target, mutation) => {\n const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n });\n const {\n sampling = \"all\",\n win,\n blockClass,\n blockSelector,\n recordCanvas,\n dataURLOptions,\n resolutionScale\n } = options;\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (recordCanvas && sampling === \"all\")\n this.initCanvasMutationObserver(\n win,\n blockClass,\n blockSelector,\n dataURLOptions\n );\n if (recordCanvas && typeof sampling === \"number\")\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\n dataURLOptions,\n resolutionScale\n });\n }\n // Shared by the main document and every iframe/shadow-root observer, so reference-count\n // teardown: a single root cleaning up must not unpatch getContext / stop the FPS loop globally.\n acquire() {\n this.refCount += 1;\n }\n reset() {\n if (this.refCount > 0) {\n this.refCount -= 1;\n }\n if (this.refCount > 0) {\n return;\n }\n this.teardown();\n }\n teardown() {\n if (this.torndown) {\n return;\n }\n this.torndown = true;\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n if (this.rafIdTimestamp !== null) {\n cancelAnimationFrame(this.rafIdTimestamp);\n this.rafIdTimestamp = null;\n }\n if (this.rafIdFlush !== null) {\n cancelAnimationFrame(this.rafIdFlush);\n this.rafIdFlush = null;\n }\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {\n if (!(\"OffscreenCanvas\" in win)) {\n return;\n }\n const scale = typeof options.resolutionScale === \"number\" && Number.isFinite(options.resolutionScale) ? Math.min(\n 1,\n Math.max(MIN_CANVAS_RESOLUTION_SCALE, options.resolutionScale)\n ) : 1;\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n true\n );\n const snapshotInProgressMap = /* @__PURE__ */ new Map();\n const worker = new WorkerWrapper();\n worker.onmessage = (e) => {\n const { id } = e.data;\n snapshotInProgressMap.set(id, false);\n if (!(\"base64\" in e.data)) return;\n const { base64, type, displayWidth, displayHeight } = e.data;\n const dw = displayWidth;\n const dh = displayHeight;\n this.mutationCb({\n id,\n type: CanvasContext[\"2D\"],\n commands: [\n {\n property: \"clearRect\",\n // wipe canvas\n args: [0, 0, dw, dh]\n },\n {\n property: \"drawImage\",\n // draws (semi-transparent) image, stretched to display size\n args: [\n {\n rr_type: \"ImageBitmap\",\n args: [\n {\n rr_type: \"Blob\",\n data: [{ rr_type: \"ArrayBuffer\", base64 }],\n type\n }\n ]\n },\n 0,\n 0,\n dw,\n dh\n ]\n }\n ],\n displayWidth: dw,\n displayHeight: dh\n });\n };\n const timeBetweenSnapshots = 1e3 / fps;\n let lastSnapshotTime = 0;\n let rafId;\n const getCanvas = () => {\n const matchedCanvas = [];\n const searchCanvas = (haystack) => {\n try {\n haystack.querySelectorAll(\"canvas\").forEach((canvas) => {\n if (!isBlocked(canvas, blockClass, blockSelector, true)) {\n matchedCanvas.push(canvas);\n }\n });\n haystack.querySelectorAll(\"*\").forEach((elem) => {\n if (elem.shadowRoot) {\n searchCanvas(elem.shadowRoot);\n }\n });\n } catch {\n }\n };\n searchCanvas(win.document);\n return matchedCanvas;\n };\n const takeCanvasSnapshots = (timestamp) => {\n if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n return;\n }\n lastSnapshotTime = timestamp;\n getCanvas().forEach(async (canvas) => {\n var _a2, _b;\n const id = this.mirror.getId(canvas);\n if (snapshotInProgressMap.get(id)) return;\n if (canvas.width === 0 || canvas.height === 0) return;\n snapshotInProgressMap.set(id, true);\n try {\n if ([\"webgl\", \"webgl2\"].includes(canvas.__context)) {\n const context = canvas.getContext(\n canvas.__context\n );\n if ((_a2 = context == null ? void 0 : context.isContextLost) == null ? void 0 : _a2.call(context)) {\n snapshotInProgressMap.set(id, false);\n return;\n }\n if (((_b = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _b.preserveDrawingBuffer) === false) {\n context.clear(context.COLOR_BUFFER_BIT);\n }\n }\n const displayWidth = canvas.clientWidth || canvas.width;\n const displayHeight = canvas.clientHeight || canvas.height;\n const captureWidth = Math.max(1, Math.round(displayWidth * scale));\n const captureHeight = Math.max(1, Math.round(displayHeight * scale));\n const bitmap = await createImageBitmap(\n canvas,\n // only ask for a quality resampling filter when we're actually downscaling;\n // at full resolution this keeps capture identical to before.\n scale < 1 ? {\n resizeWidth: captureWidth,\n resizeHeight: captureHeight,\n resizeQuality: \"medium\"\n } : { resizeWidth: captureWidth, resizeHeight: captureHeight }\n );\n worker.postMessage(\n {\n id,\n bitmap,\n width: captureWidth,\n height: captureHeight,\n displayWidth,\n displayHeight,\n dataURLOptions: options.dataURLOptions\n },\n [bitmap]\n );\n } catch {\n snapshotInProgressMap.set(id, false);\n }\n });\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n };\n rafId = requestAnimationFrame(takeCanvasSnapshots);\n this.resetObservers = () => {\n canvasContextReset();\n cancelAnimationFrame(rafId);\n };\n }\n initCanvasMutationObserver(win, blockClass, blockSelector, dataURLOptions) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n const canvasContextReset = initCanvasContextObserver(\n win,\n blockClass,\n blockSelector,\n false\n );\n const canvas2DReset = initCanvas2DMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector,\n dataURLOptions\n );\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n this.processMutation.bind(this),\n win,\n blockClass,\n blockSelector,\n dataURLOptions\n );\n this.resetObservers = () => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n }\n startPendingCanvasMutationFlusher() {\n this.rafIdFlush = requestAnimationFrame(\n () => this.flushPendingCanvasMutations()\n );\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n };\n this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach(\n (_values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n }\n );\n this.rafIdFlush = requestAnimationFrame(\n () => this.flushPendingCanvasMutations()\n );\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1) return;\n const values = valuesWithType.map((value) => {\n const { type: type2, ...rest } = value;\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\nclass StylesheetManager {\n constructor(options) {\n __publicField(this, \"trackedLinkElements\", /* @__PURE__ */ new WeakSet());\n __publicField(this, \"mutationCb\");\n __publicField(this, \"adoptedStyleSheetCb\");\n __publicField(this, \"styleMirror\", new StyleSheetMirror());\n this.mutationCb = options.mutationCb;\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n }\n attachLinkElement(linkEl, childSn) {\n if (\"_cssText\" in childSn.attributes)\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: childSn.id,\n attributes: childSn.attributes\n }\n ]\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl)) return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0) return;\n const adoptedStyleSheetData = {\n id: hostId,\n styleIds: []\n };\n const styles = [];\n for (const sheet of sheets) {\n let styleId;\n if (!this.styleMirror.has(sheet)) {\n styleId = this.styleMirror.add(sheet);\n styles.push({\n styleId,\n rules: Array.from(sheet.rules || CSSRule, (r, index2) => ({\n rule: stringifyRule(r, sheet.href),\n index: index2\n }))\n });\n } else styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n resetStylesheetLoadTracking();\n }\n // TODO: take snapshot on stylesheet reload by applying event listener\n trackStylesheetInLinkElement(_linkEl) {\n }\n}\nclass ProcessedNodeManager {\n constructor() {\n __publicField(this, \"nodeMap\", /* @__PURE__ */ new WeakMap());\n __publicField(this, \"active\", false);\n }\n inOtherBuffer(node, thisBuffer) {\n const buffers = this.nodeMap.get(node);\n return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);\n }\n add(node, buffer) {\n if (!this.active) {\n this.active = true;\n requestAnimationFrame(() => {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));\n }\n destroy() {\n }\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nlet canvasManager;\nlet recording = false;\ntry {\n if (Array.from([1], (x) => x * 2)[0] !== 2) {\n const cleanFrame = document.createElement(\"iframe\");\n document.body.appendChild(cleanFrame);\n Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;\n document.body.removeChild(cleanFrame);\n }\n} catch (err) {\n console.debug(\"Unable to override Array.from\", err);\n}\nconst mirror = createMirror();\nfunction record(options = {}) {\n const {\n emit,\n checkoutEveryNms,\n checkoutEveryNth,\n blockClass = \"rr-block\",\n blockSelector = null,\n ignoreClass = \"rr-ignore\",\n ignoreSelector = null,\n maskTextClass = \"rr-mask\",\n maskTextSelector = null,\n inlineStylesheet = true,\n maskAllInputs,\n maskInputOptions: _maskInputOptions,\n slimDOMOptions: _slimDOMOptions,\n maskInputFn,\n maskTextFn,\n hooks,\n packFn,\n sampling = {},\n dataURLOptions: _dataURLOptions = {},\n canvasResolutionScale,\n mousemoveWait,\n recordDOM = true,\n recordCanvas = false,\n recordCrossOriginIframes = false,\n recordAfter = options.recordAfter === \"DOMContentLoaded\" ? options.recordAfter : \"load\",\n userTriggeredOnInput = false,\n collectFonts = false,\n inlineImages = false,\n plugins,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([]),\n errorHandler: errorHandler2\n } = options;\n registerErrorHandler(errorHandler2);\n const dataURLOptions = {\n type: \"image/webp\",\n quality: 0.4,\n maxBase64ImageLength: 1048576,\n ..._dataURLOptions\n };\n const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n } catch (e) {\n passEmitsToParent = true;\n }\n }\n if (inEmittingFrame && !emit) {\n throw new Error(\"emit function is required\");\n }\n if (!inEmittingFrame && !passEmitsToParent) {\n return () => {\n };\n }\n if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };\n const slimDOMOptions = slimDOMDefaults(\n _slimDOMOptions !== void 0 ? _slimDOMOptions : false\n );\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const iframeObserverCleanups = /* @__PURE__ */ new Map();\n let runAndDetachIframeCleanup;\n let cleanupDetachedIframeObservers;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn && // Disable packing events which will be emitted to parent frames.\n !passEmitsToParent) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (r, isCheckout) => {\n var _a2;\n const e = r;\n e.timestamp = nowTimestamp();\n if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e.type !== EventType.FullSnapshot && !(e.type === EventType.IncrementalSnapshot && e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n emit == null ? void 0 : emit(eventProcessor(e), isCheckout);\n } else if (passEmitsToParent) {\n const message = {\n type: \"rrweb\",\n event: eventProcessor(e),\n origin: window.location.origin,\n isCheckout\n };\n window.parent.postMessage(message, \"*\");\n }\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n } else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation && e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms && e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n if (m.removes && m.removes.length > 0) {\n const addedIds = m.adds.length > 0 ? new Set(m.adds.map((add) => add.node.id)) : null;\n const addedIframeElements = /* @__PURE__ */ new Set();\n if (m.adds.length > 0) {\n for (const add of m.adds) {\n const node = mirror.getNode(add.node.id);\n if (node && node.nodeName === \"IFRAME\") {\n addedIframeElements.add(node);\n }\n }\n }\n m.removes.forEach(({ id }) => {\n if (addedIds && addedIds.has(id)) return;\n const removedIframe = iframeManager.getIframeElementById(id);\n if (removedIframe && addedIframeElements.has(removedIframe)) {\n iframeManager.forgetIframeId(id);\n return;\n }\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(id);\n iframeManager.removeIframeById(id);\n });\n cleanupDetachedIframeObservers == null ? void 0 : cleanupDetachedIframeObservers();\n iframeManager.cleanupDetachedIframes();\n }\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n ...m\n }\n });\n };\n const wrappedScrollEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Scroll,\n ...p\n }\n });\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n });\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a\n }\n });\n const stylesheetManager = new StylesheetManager({\n mutationCb: wrappedMutationEmit,\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit\n });\n const iframeManager = new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager,\n recordCrossOriginIframes,\n wrappedEmit\n });\n for (const plugin of plugins || []) {\n if (plugin.getMirror)\n plugin.getMirror({\n nodeMirror: mirror,\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror\n });\n }\n const processedNodeManager = new ProcessedNodeManager();\n canvasManager = new CanvasManager({\n recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass,\n blockSelector,\n mirror,\n sampling: sampling.canvas,\n dataURLOptions,\n resolutionScale: canvasResolutionScale\n });\n const shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n dataURLOptions,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n stylesheetManager,\n canvasManager,\n keepIframeSrcFn,\n processedNodeManager\n },\n mirror\n });\n takeFullSnapshot = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit(\n {\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight()\n }\n },\n isCheckout\n );\n stylesheetManager.reset();\n shadowDomManager.init();\n mutationBuffers.forEach((buf) => buf.lock());\n const node = snapshot(document, {\n mirror,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOM: slimDOMOptions,\n dataURLOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isSerializedIframe(n, mirror)) {\n iframeManager.addIframe(n);\n }\n if (isSerializedStylesheet(n, mirror)) {\n stylesheetManager.trackLinkElement(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(index.shadowRoot(n), document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n onIframeListenerRegistered: (iframe, disposer) => {\n iframeManager.registerLoadListenerDisposer(iframe, disposer);\n },\n onStylesheetLoad: (linkEl, childSn) => {\n stylesheetManager.attachLinkElement(linkEl, childSn);\n },\n keepIframeSrcFn\n });\n if (!node) {\n return console.warn(\"Failed to snapshot the document\");\n }\n wrappedEmit(\n {\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: getWindowScroll(window)\n }\n },\n isCheckout\n );\n mutationBuffers.forEach((buf) => buf.unlock());\n if (recordCrossOriginIframes) {\n iframeManager.reattachIframes();\n }\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n stylesheetManager.adoptStyleSheets(\n document.adoptedStyleSheets,\n mirror.getId(document)\n );\n };\n try {\n const handlers = [];\n runAndDetachIframeCleanup = (iframeId) => {\n const cleanups = iframeObserverCleanups.get(iframeId);\n if (!cleanups) return;\n cleanups.forEach((cleanup) => {\n callSafely(cleanup);\n const idx = handlers.indexOf(cleanup);\n if (idx !== -1) handlers.splice(idx, 1);\n });\n iframeObserverCleanups.delete(iframeId);\n };\n cleanupDetachedIframeObservers = () => {\n for (const [iframeId] of iframeObserverCleanups) {\n const iframe = mirror.getNode(iframeId);\n if (!iframe) {\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n continue;\n }\n try {\n if (!iframe.contentDocument || !iframe.contentDocument.defaultView) {\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n }\n } catch {\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n }\n }\n };\n const observe = (doc) => {\n var _a2;\n return callbackWrapper(initObservers)(\n {\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions\n }\n }),\n mouseInteractionCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MouseInteraction,\n ...d\n }\n }),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.ViewportResize,\n ...d\n }\n }),\n inputCb: (v) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v\n }\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p\n }\n }),\n styleSheetRuleCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r\n }\n }),\n styleDeclarationCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r\n }\n }),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Font,\n ...p\n }\n }),\n selectionCb: (p) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Selection,\n ...p\n }\n });\n },\n customElementCb: (c) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c\n }\n });\n },\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskTextClass,\n maskTextSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordDOM,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskInputFn,\n maskTextFn,\n keepIframeSrcFn,\n blockSelector,\n slimDOMOptions,\n dataURLOptions,\n mirror,\n iframeManager,\n stylesheetManager,\n shadowDomManager,\n processedNodeManager,\n canvasManager,\n ignoreCSSAttributes,\n plugins: ((_a2 = plugins == null ? void 0 : plugins.filter((p) => p.observer)) == null ? void 0 : _a2.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload\n }\n })\n }))) || []\n },\n hooks\n );\n };\n const loadListener = (iframeEl) => {\n try {\n const iframeId = mirror.getId(iframeEl);\n const cleanup = observe(iframeEl.contentDocument);\n handlers.push(cleanup);\n if (iframeId !== -1) {\n let bucket = iframeObserverCleanups.get(iframeId);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n iframeObserverCleanups.set(iframeId, bucket);\n }\n bucket.add(cleanup);\n }\n } catch (error) {\n console.warn(error);\n }\n };\n iframeManager.addLoadListener(loadListener);\n iframeManager.addPageHideListener((iframeEl) => {\n const iframeId = mirror.getId(iframeEl);\n runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n findAndRemoveIframeBuffer(iframeEl);\n });\n let lastFullscreenId = -1;\n const emitFullscreen = (payload) => wrappedEmit({\n type: EventType.Custom,\n data: { tag: FullscreenCustomEventTag, payload }\n });\n const emitFullscreenChange = () => {\n const doc = document;\n const fullscreenEl = doc.fullscreenElement ?? doc.webkitFullscreenElement ?? doc.mozFullScreenElement ?? doc.msFullscreenElement ?? null;\n const id = fullscreenEl ? mirror.getId(fullscreenEl) : -1;\n if (id === lastFullscreenId) return;\n if (lastFullscreenId !== -1) {\n emitFullscreen({ id: lastFullscreenId, enter: false });\n }\n lastFullscreenId = id;\n if (id !== -1) {\n emitFullscreen({ id, enter: true });\n }\n };\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n handlers.push(on(\"fullscreenchange\", emitFullscreenChange));\n handlers.push(on(\"webkitfullscreenchange\", emitFullscreenChange));\n handlers.push(on(\"mozfullscreenchange\", emitFullscreenChange));\n handlers.push(on(\"MSFullscreenChange\", emitFullscreenChange));\n recording = true;\n };\n if ([\"interactive\", \"complete\"].includes(document.readyState)) {\n init();\n } else {\n handlers.push(\n on(\"DOMContentLoaded\", () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {}\n });\n if (recordAfter === \"DOMContentLoaded\") init();\n })\n );\n handlers.push(\n on(\n \"load\",\n () => {\n wrappedEmit({\n type: EventType.Load,\n data: {}\n });\n if (recordAfter === \"load\") init();\n },\n window\n )\n );\n }\n return () => {\n handlers.forEach((h) => callSafely(h));\n processedNodeManager.destroy();\n iframeManager.removeLoadListener();\n iframeManager.destroy();\n iframeObserverCleanups.clear();\n mirror.reset();\n recording = false;\n unregisterErrorHandler();\n };\n } catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = (tag, payload) => {\n if (!recording) {\n throw new Error(\"please add custom event after start recording\");\n }\n wrappedEmit({\n type: EventType.Custom,\n data: {\n tag,\n payload\n }\n });\n};\nrecord.freezePage = () => {\n mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n if (!recording) {\n throw new Error(\"please take full snapshot after start recording\");\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\nexport {\n record,\n resetMaxDepthState,\n wasMaxDepthReached\n};\n//# sourceMappingURL=rrweb-record.js.map\n","var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nclass StackFrame {\n constructor(obj) {\n __publicField(this, \"fileName\");\n __publicField(this, \"functionName\");\n __publicField(this, \"lineNumber\");\n __publicField(this, \"columnNumber\");\n this.fileName = obj.fileName || \"\";\n this.functionName = obj.functionName || \"\";\n this.lineNumber = obj.lineNumber;\n this.columnNumber = obj.columnNumber;\n }\n toString() {\n const lineNumber = this.lineNumber || \"\";\n const columnNumber = this.columnNumber || \"\";\n if (this.functionName)\n return `${this.functionName} (${this.fileName}:${lineNumber}:${columnNumber})`;\n return `${this.fileName}:${lineNumber}:${columnNumber}`;\n }\n}\nconst FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/;\nconst CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+:\\d+|\\(native\\))/m;\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code])?$/;\nconst ErrorStackParser = {\n /**\n * Given an Error object, extract the most information from it.\n */\n parse: function(error) {\n if (!error) {\n return [];\n }\n if (\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n typeof error.stacktrace !== \"undefined\" || // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n typeof error[\"opera#sourceloc\"] !== \"undefined\"\n ) {\n return this.parseOpera(\n error\n );\n } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {\n return this.parseV8OrIE(error);\n } else if (error.stack) {\n return this.parseFFOrSafari(error);\n } else {\n return [];\n }\n },\n // Separate line and column numbers from a string of the form: (URI:Line:Column)\n extractLocation: function(urlLike) {\n if (urlLike.indexOf(\":\") === -1) {\n return [urlLike];\n }\n const regExp = /(.+?)(?::(\\d+))?(?::(\\d+))?$/;\n const parts = regExp.exec(urlLike.replace(/[()]/g, \"\"));\n if (!parts) throw new Error(`Cannot parse given url: ${urlLike}`);\n return [parts[1], parts[2] || void 0, parts[3] || void 0];\n },\n parseV8OrIE: function(error) {\n const filtered = error.stack.split(\"\\n\").filter(function(line) {\n return !!line.match(CHROME_IE_STACK_REGEXP);\n }, this);\n return filtered.map(function(line) {\n if (line.indexOf(\"(eval \") > -1) {\n line = line.replace(/eval code/g, \"eval\").replace(/(\\(eval at [^()]*)|(\\),.*$)/g, \"\");\n }\n let sanitizedLine = line.replace(/^\\s+/, \"\").replace(/\\(eval code/g, \"(\");\n const location = sanitizedLine.match(/ (\\((.+):(\\d+):(\\d+)\\)$)/);\n sanitizedLine = location ? sanitizedLine.replace(location[0], \"\") : sanitizedLine;\n const tokens = sanitizedLine.split(/\\s+/).slice(1);\n const locationParts = this.extractLocation(\n location ? location[1] : tokens.pop()\n );\n const functionName = tokens.join(\" \") || void 0;\n const fileName = [\"eval\", \"<anonymous>\"].indexOf(locationParts[0]) > -1 ? void 0 : locationParts[0];\n return new StackFrame({\n functionName,\n fileName,\n lineNumber: locationParts[1],\n columnNumber: locationParts[2]\n });\n }, this);\n },\n parseFFOrSafari: function(error) {\n const filtered = error.stack.split(\"\\n\").filter(function(line) {\n return !line.match(SAFARI_NATIVE_CODE_REGEXP);\n }, this);\n return filtered.map(function(line) {\n if (line.indexOf(\" > eval\") > -1) {\n line = line.replace(\n / line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g,\n \":$1\"\n );\n }\n if (line.indexOf(\"@\") === -1 && line.indexOf(\":\") === -1) {\n return new StackFrame({\n functionName: line\n });\n } else {\n const functionNameRegex = /((.*\".+\"[^@]*)?[^@]*)(?:@)/;\n const matches = line.match(functionNameRegex);\n const functionName = matches && matches[1] ? matches[1] : void 0;\n const locationParts = this.extractLocation(\n line.replace(functionNameRegex, \"\")\n );\n return new StackFrame({\n functionName,\n fileName: locationParts[0],\n lineNumber: locationParts[1],\n columnNumber: locationParts[2]\n });\n }\n }, this);\n },\n parseOpera: function(e) {\n if (!e.stacktrace || e.message.indexOf(\"\\n\") > -1 && e.message.split(\"\\n\").length > e.stacktrace.split(\"\\n\").length) {\n return this.parseOpera9(e);\n } else if (!e.stack) {\n return this.parseOpera10(e);\n } else {\n return this.parseOpera11(e);\n }\n },\n parseOpera9: function(e) {\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n const lines = e.message.split(\"\\n\");\n const result = [];\n for (let i = 2, len = lines.length; i < len; i += 2) {\n const match = lineRE.exec(lines[i]);\n if (match) {\n result.push(\n new StackFrame({\n fileName: match[2],\n lineNumber: parseFloat(match[1])\n })\n );\n }\n }\n return result;\n },\n parseOpera10: function(e) {\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n const lines = e.stacktrace.split(\"\\n\");\n const result = [];\n for (let i = 0, len = lines.length; i < len; i += 2) {\n const match = lineRE.exec(lines[i]);\n if (match) {\n result.push(\n new StackFrame({\n functionName: match[3] || void 0,\n fileName: match[2],\n lineNumber: parseFloat(match[1])\n })\n );\n }\n }\n return result;\n },\n // Opera 10.65+ Error.stack very similar to FF/Safari\n parseOpera11: function(error) {\n const filtered = error.stack.split(\"\\n\").filter(function(line) {\n return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);\n }, this);\n return filtered.map(function(line) {\n const tokens = line.split(\"@\");\n const locationParts = this.extractLocation(tokens.pop());\n const functionCall = tokens.shift() || \"\";\n const functionName = functionCall.replace(/<anonymous function(: (\\w+))?>/, \"$2\").replace(/\\([^)]*\\)/g, \"\") || void 0;\n return new StackFrame({\n functionName,\n fileName: locationParts[0],\n lineNumber: locationParts[1],\n columnNumber: locationParts[2]\n });\n }, this);\n }\n};\nfunction pathToSelector(node) {\n if (!node || !node.outerHTML) {\n return \"\";\n }\n let path = \"\";\n while (node.parentElement) {\n let name = node.localName;\n if (!name) {\n break;\n }\n name = name.toLowerCase();\n const parent = node.parentElement;\n const domSiblings = [];\n if (parent.children && parent.children.length > 0) {\n for (let i = 0; i < parent.children.length; i++) {\n const sibling = parent.children[i];\n if (sibling.localName && sibling.localName.toLowerCase) {\n if (sibling.localName.toLowerCase() === name) {\n domSiblings.push(sibling);\n }\n }\n }\n }\n if (domSiblings.length > 1) {\n name += `:eq(${domSiblings.indexOf(node)})`;\n }\n path = name + (path ? \">\" + path : \"\");\n node = parent;\n }\n return path;\n}\nfunction isArray(obj) {\n return Array.isArray(obj);\n}\nfunction isObject(obj) {\n return typeof obj === \"object\" && obj !== null && !isArray(obj);\n}\nfunction isObjTooDeep(obj, limit) {\n if (limit === 0) {\n return true;\n }\n const keys = Object.keys(obj);\n for (const key of keys) {\n if (isObject(obj[key]) && isObjTooDeep(obj[key], limit - 1)) {\n return true;\n }\n }\n return false;\n}\nfunction stringify(obj, stringifyOptions) {\n const options = {\n numOfKeysLimit: 50,\n depthOfLimit: 4\n };\n Object.assign(options, stringifyOptions);\n const stack = [];\n const keys = [];\n return JSON.stringify(\n obj,\n function(key, value) {\n if (stack.length > 0) {\n const thisPos = stack.indexOf(this);\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n if (~stack.indexOf(value)) {\n if (stack[0] === value) {\n value = \"[Circular ~]\";\n } else {\n value = \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\n }\n }\n } else {\n stack.push(value);\n }\n if (value === null) return value;\n if (value === void 0) return \"undefined\";\n if (shouldIgnore(value)) {\n return toString(value);\n }\n if (typeof value === \"bigint\") {\n return value.toString() + \"n\";\n }\n if (value instanceof Event) {\n const eventResult = {};\n for (const eventKey in value) {\n const eventValue = value[eventKey];\n if (isArray(eventValue)) {\n eventResult[eventKey] = pathToSelector(\n eventValue.length ? eventValue[0] : null\n );\n } else {\n eventResult[eventKey] = eventValue;\n }\n }\n return eventResult;\n } else if (value instanceof Node) {\n if (value instanceof HTMLElement) {\n return value ? value.outerHTML : \"\";\n }\n return value.nodeName;\n } else if (value instanceof Error) {\n return value.stack ? value.stack + \"\\nEnd of stack for Error object\" : value.name + \": \" + value.message;\n }\n return value;\n }\n );\n function shouldIgnore(_obj) {\n if (isObject(_obj) && Object.keys(_obj).length > options.numOfKeysLimit) {\n return true;\n }\n if (typeof _obj === \"function\") {\n return true;\n }\n if (isObject(_obj) && isObjTooDeep(_obj, options.depthOfLimit)) {\n return true;\n }\n return false;\n }\n function toString(_obj) {\n let str = _obj.toString();\n if (options.stringLengthLimit && str.length > options.stringLengthLimit) {\n str = `${str.slice(0, options.stringLengthLimit)}...`;\n }\n return str;\n }\n}\nconst defaultLogOptions = {\n level: [\n \"assert\",\n \"clear\",\n \"count\",\n \"countReset\",\n \"debug\",\n \"dir\",\n \"dirxml\",\n \"error\",\n \"group\",\n \"groupCollapsed\",\n \"groupEnd\",\n \"info\",\n \"log\",\n \"table\",\n \"time\",\n \"timeEnd\",\n \"timeLog\",\n \"trace\",\n \"warn\"\n ],\n lengthThreshold: 1e3,\n logger: \"console\"\n};\nfunction initLogObserver(cb, win, options) {\n const logOptions = options ? Object.assign({}, defaultLogOptions, options) : defaultLogOptions;\n const loggerType = logOptions.logger;\n if (!loggerType) {\n return () => {\n };\n }\n let logger;\n if (typeof loggerType === \"string\") {\n logger = win[loggerType];\n } else {\n logger = loggerType;\n }\n let logCount = 0;\n let inStack = false;\n const cancelHandlers = [];\n if (logOptions.level.includes(\"error\")) {\n const errorHandler = (event) => {\n const message = event.message, error = event.error;\n const trace = ErrorStackParser.parse(error).map(\n (stackFrame) => stackFrame.toString()\n );\n const payload = [stringify(message, logOptions.stringifyOptions)];\n cb({\n level: \"error\",\n trace,\n payload\n });\n };\n win.addEventListener(\"error\", errorHandler);\n cancelHandlers.push(() => {\n win.removeEventListener(\"error\", errorHandler);\n });\n const unhandledrejectionHandler = (event) => {\n let error;\n let payload;\n if (event.reason instanceof Error) {\n error = event.reason;\n payload = [\n stringify(\n `Uncaught (in promise) ${error.name}: ${error.message}`,\n logOptions.stringifyOptions\n )\n ];\n } else {\n error = new Error();\n payload = [\n stringify(\"Uncaught (in promise)\", logOptions.stringifyOptions),\n stringify(event.reason, logOptions.stringifyOptions)\n ];\n }\n const trace = ErrorStackParser.parse(error).map(\n (stackFrame) => stackFrame.toString()\n );\n cb({\n level: \"error\",\n trace,\n payload\n });\n };\n win.addEventListener(\"unhandledrejection\", unhandledrejectionHandler);\n cancelHandlers.push(() => {\n win.removeEventListener(\"unhandledrejection\", unhandledrejectionHandler);\n });\n }\n for (const levelType of logOptions.level) {\n cancelHandlers.push(replace(logger, levelType));\n }\n return () => {\n cancelHandlers.forEach((h) => h());\n };\n function replace(_logger, level) {\n if (!_logger[level]) {\n return () => {\n };\n }\n return patch(\n _logger,\n level,\n (original) => {\n return (...args) => {\n original.apply(this, args);\n if (level === \"assert\" && !!args[0]) {\n return;\n }\n if (inStack) {\n return;\n }\n inStack = true;\n try {\n const trace = ErrorStackParser.parse(new Error()).map((stackFrame) => stackFrame.toString()).splice(1);\n const argsForPayload = level === \"assert\" ? args.slice(1) : args;\n const payload = argsForPayload.map(\n (s) => stringify(s, logOptions.stringifyOptions)\n );\n logCount++;\n if (logCount < logOptions.lengthThreshold) {\n cb({\n level,\n trace,\n payload\n });\n } else if (logCount === logOptions.lengthThreshold) {\n cb({\n level: \"warn\",\n trace: [],\n payload: [\n stringify(\"The number of log records reached the threshold.\")\n ]\n });\n }\n } catch (error) {\n original(\"rrweb logger error:\", error, ...args);\n } finally {\n inStack = false;\n }\n };\n }\n );\n }\n}\nconst PLUGIN_NAME = \"rrweb/console@1\";\nconst getRecordConsolePlugin = (options) => ({\n name: PLUGIN_NAME,\n observer: initLogObserver,\n options\n});\nexport {\n PLUGIN_NAME,\n getRecordConsolePlugin\n};\n//# sourceMappingURL=rrweb-plugin-console-record.js.map\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ExternalIntegrationKind,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n SessionStartReason,\n} from '../types'\nimport type {\n ConversationsRemoteConfig,\n GetMessagesResponse,\n GetTicketsOptions,\n GetTicketsResponse,\n MarkAsReadResponse,\n RestoreFromTokenResponse,\n RequestRestoreLinkResponse,\n SendMessageResponse,\n UserProvidedTraits,\n} from '../posthog-conversations-types'\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\nimport { eventWithTime } from '../extensions/replay/types/rrweb-types'\nimport { ErrorTracking } from '@posthog/core'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis & {\n /*\n * Main PostHog instance\n */\n posthog: any\n\n /*\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n */\n __PosthogExtensions__?: PostHogExtensions\n\n /**\n * When loading remote config, we assign it to this global configuration\n * for ease of sharing it with the rest of the SDK\n */\n _POSTHOG_REMOTE_CONFIG?: Record<\n string,\n {\n config: RemoteConfig\n siteApps: SiteAppLoader[]\n }\n >\n\n /**\n * If this is set on the window, our logger will log to the console\n * for ease of debugging. Used for testing purposes only.\n *\n * @see {Config.DEBUG} from config.ts\n */\n POSTHOG_DEBUG: any\n\n // Exposed by the browser\n doNotTrack: any\n\n // See entrypoints/customizations.full.ts\n posthogCustomizations: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/exception-autocapture.ts\n *\n * @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead\n */\n posthogErrorWrappingFunctions: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrweb` instead\n */\n rrweb: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead\n */\n rrwebConsoleRecord: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead\n */\n getRecordNetworkPlugin: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/web-vitals.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead\n */\n postHogWebVitalsCallbacks: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/tracing-headers.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead\n */\n postHogTracingHeadersPatchFns: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/surveys.ts\n *\n * @deprecated use `__PosthogExtensions__.generateSurveys` instead\n */\n extendPostHogWithSurveys: any\n\n /*\n * These are used to handle our toolbar state.\n * @see {Toolbar} from extensions/toolbar.ts\n */\n ph_load_toolbar: any\n ph_load_editor: any\n ph_toolbar_state: any\n } & Record<`__$$ph_site_app_${string}`, any>\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration'\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'web-vitals-with-attribution'\n | 'recorder'\n | 'lazy-recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'logs'\n | 'conversations'\n | 'product-tours'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n | ExternalExtensionKind\n\nexport interface LazyLoadedSessionRecordingInterface {\n start: (startReason?: SessionStartReason) => void\n stop: () => void\n discard: () => void\n sessionId: string\n status: SessionRecordingStatus\n onRRwebEmit: (rawEvent: eventWithTime) => void\n log: (message: string, level: 'log' | 'warn' | 'error') => void\n sdkDebugProperties: Properties\n overrideLinkedFlag: () => void\n overrideSampling: () => void\n overrideTrigger: (triggerType: TriggerType) => void\n isStarted: boolean\n tryAddCustomEvent(tag: string, payload: any): boolean\n}\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\nexport interface LazyLoadedConversationsInterface {\n // Widget control\n show: () => void\n hide: () => void\n isVisible: () => boolean\n\n // Lifecycle\n reset: () => void\n\n // Identity verification\n setIdentity: () => void\n clearIdentity: () => void\n\n // API methods\n sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise<SendMessageResponse>\n getMessages: (ticketId?: string, after?: string) => Promise<GetMessagesResponse>\n markAsRead: (ticketId?: string) => Promise<MarkAsReadResponse>\n getTickets: (options?: GetTicketsOptions) => Promise<GetTicketsResponse>\n requestRestoreLink: (email: string) => Promise<RequestRestoreLinkResponse>\n restoreFromToken: (restoreToken: string) => Promise<RestoreFromTokenResponse>\n restoreFromUrlToken: () => Promise<RestoreFromTokenResponse | null>\n getCurrentTicketId: () => string | null\n getWidgetSessionId: () => string\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n }\n rrweb?: { record: any; version: string; wasMaxDepthReached?: () => boolean; resetMaxDepthState?: () => void }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined\n generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined\n logs?: {\n initializeLogs?: (posthog: PostHog) => any | undefined\n }\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n /**\n * @deprecated\n *\n * this was introduced briefly, it is now always a no-op and only kept for backwards compatibility\n */\n loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks']\n tracingHeadersPatchFns?: {\n _patchFetch: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n _patchXHR: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n integrations?: {\n [K in ExternalIntegrationKind]?: { start: (posthog: PostHog) => void; stop: () => void }\n }\n initSessionRecording?: (ph: PostHog) => LazyLoadedSessionRecordingInterface\n initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\n// React Native polyfills for posthog-js compatibility\nif (typeof self === 'undefined') {\n ;(global as any).self = global\n}\nif (typeof File === 'undefined') {\n ;(global as any).File = function () {}\n}\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const CompressionStream = global?.CompressionStream\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n","import { window } from './globals'\n\n// When angular patches functions they pass the above `isNativeFunction` check (at least the MutationObserver)\nexport const isAngularZonePresent = (): boolean => {\n return !!(window as any).Zone\n}\n\nexport const isDocument = (x: unknown): x is Document => {\n // eslint-disable-next-line posthog-js/no-direct-document-check\n return x instanceof Document\n}\n","import Config from '../config'\nimport { isUndefined } from '@posthog/core'\nimport { assignableWindow, window } from './globals'\nimport type { Logger } from '@posthog/core'\n\ntype CreateLoggerOptions = {\n debugEnabled?: boolean\n}\n\ntype PosthogJsLogger = Omit<Logger, 'createLogger'> & {\n _log: (level: 'debug' | 'log' | 'warn' | 'error', ...args: any[]) => void\n uninitializedWarning: (methodName: string) => void\n createLogger: (prefix: string, options?: CreateLoggerOptions) => PosthogJsLogger\n}\n\nconst _createLogger = (prefix: string, { debugEnabled }: CreateLoggerOptions = {}): PosthogJsLogger => {\n const logger: PosthogJsLogger = {\n _log: (level: 'debug' | 'log' | 'warn' | 'error', ...args: any[]) => {\n if (\n window &&\n (Config.DEBUG || assignableWindow.POSTHOG_DEBUG || debugEnabled) &&\n !isUndefined(window.console) &&\n window.console\n ) {\n const consoleLog =\n '__rrweb_original__' in window.console[level]\n ? (window.console[level] as any)['__rrweb_original__']\n : window.console[level]\n\n // eslint-disable-next-line no-console\n consoleLog(prefix, ...args)\n }\n },\n\n debug: (...args: any[]) => {\n logger._log('debug', ...args)\n },\n\n info: (...args: any[]) => {\n logger._log('log', ...args)\n },\n\n warn: (...args: any[]) => {\n logger._log('warn', ...args)\n },\n\n error: (...args: any[]) => {\n logger._log('error', ...args)\n },\n\n critical: (...args: any[]) => {\n // Critical errors are always logged to the console\n // eslint-disable-next-line no-console\n console.error(prefix, ...args)\n },\n\n uninitializedWarning: (methodName: string) => {\n logger.error(`You must initialize PostHog before calling ${methodName}`)\n },\n\n createLogger: (additionalPrefix: string, options?: CreateLoggerOptions) =>\n _createLogger(`${prefix} ${additionalPrefix}`, options),\n }\n return logger\n}\n\nexport const logger = _createLogger('[PostHog.js]')\n\nexport const createLogger = logger.createLogger\n","import { each } from './'\n\nimport { isArray, isFile, isUndefined } from '@posthog/core'\nimport { logger } from './logger'\nimport { document } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n const location = document?.createElement('a')\n if (isUndefined(location)) {\n return null\n }\n\n location.href = url\n return location\n}\n\nexport const formDataToQuery = function (formdata: Record<string, any> | FormData, arg_separator = '&'): string {\n let use_val: string\n let use_key: string\n const tph_arr: string[] = []\n\n each(formdata, function (val: File | string | undefined, key: string | undefined) {\n // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n return\n }\n\n use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n use_key = encodeURIComponent(key)\n tph_arr[tph_arr.length] = use_key + '=' + use_val\n })\n\n return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n const withoutHash: string = url.split('#')[0] || ''\n\n // Split only on the first ? to sort problem out for those with multiple ?s\n // and then remove them\n const queryParams: string = withoutHash.split(/\\?(.*)/)[1] || ''\n const cleanedQueryParams = queryParams.replace(/^\\?+/g, '')\n\n const queryParts = cleanedQueryParams.split('&')\n let keyValuePair\n\n for (let i = 0; i < queryParts.length; i++) {\n const parts = queryParts[i].split('=')\n if (parts[0] === param) {\n keyValuePair = parts\n break\n }\n }\n\n if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n return ''\n } else {\n let result = keyValuePair[1]\n try {\n result = decodeURIComponent(result)\n } catch {\n logger.error('Skipping decoding for malformed query param: ' + result)\n }\n return result.replace(/\\+/g, ' ')\n }\n}\n\n// replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,\n// including preserving malformed text in most cases\nexport const maskQueryParams = function <T extends string | undefined>(\n url: T,\n maskedParams: string[] | undefined,\n mask: string\n): T extends string ? string : undefined {\n if (!url || !maskedParams || !maskedParams.length) {\n return url as any\n }\n\n const splitHash = url.split('#')\n const withoutHash: string = splitHash[0] || ''\n const hash = splitHash[1]\n\n const splitQuery: string[] = withoutHash.split('?')\n const queryString: string = splitQuery[1]\n const urlWithoutQueryAndHash: string = splitQuery[0]\n const queryParts = (queryString || '').split('&')\n\n // use an array of strings rather than an object to preserve ordering and duplicates\n const paramStrings: string[] = []\n\n for (let i = 0; i < queryParts.length; i++) {\n const keyValuePair = queryParts[i].split('=')\n if (!isArray(keyValuePair)) {\n continue\n } else if (maskedParams.includes(keyValuePair[0])) {\n paramStrings.push(keyValuePair[0] + '=' + mask)\n } else {\n paramStrings.push(queryParts[i])\n }\n }\n\n let result = urlWithoutQueryAndHash\n if (queryString != null) {\n result += '?' + paramStrings.join('&')\n }\n if (hash != null) {\n result += '#' + hash\n }\n\n return result as any\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n const matches = hash.match(new RegExp(param + '=([^&]*)'))\n return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n return localDomains.includes(location.hostname)\n}\n","import { PostHogConfig, Properties } from '../types'\nimport { logger } from './logger'\nimport { isFormData, isNullish, isNumber, isString, hasOwnProperty, isArray } from '@posthog/core'\n\nexport function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined {\n for (let i = 0; i < value.length; i++) {\n if (predicate(value[i])) {\n return value[i]\n }\n }\n return undefined\n}\n\nexport function eachArray<E = any>(obj: E[] | null | undefined, iterator: (value: E, key: number) => void): void {\n if (isArray(obj)) {\n obj.forEach(iterator)\n }\n}\n\nexport function each(obj: any, iterator: (value: any, key: any) => void): void {\n if (isNullish(obj)) {\n return\n }\n if (isArray(obj)) {\n obj.forEach(iterator)\n return\n }\n if (isFormData(obj)) {\n obj.forEach((val: any, key: any) => iterator(val, key))\n return\n }\n for (const key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n iterator(obj[key], key)\n }\n }\n}\n\nexport const extend = function (obj: Record<string, any>, ...args: Record<string, any>[]): Record<string, any> {\n for (const source of args) {\n for (const prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop]\n }\n }\n }\n return obj\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries<T = any>(obj: Record<string, T>): [string, T][] {\n const ownProps = Object.keys(obj)\n let i = ownProps.length\n const resArray = new Array(i) // preallocate the Array\n\n while (i--) {\n resArray[i] = [ownProps[i], obj[ownProps[i]]]\n }\n return resArray\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n try {\n return fn()\n } catch {\n return undefined\n }\n}\n\nexport const safewrap = function <F extends (...args: any[]) => any = (...args: any[]) => any>(f: F): F {\n return function (...args) {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return f.apply(this, args)\n } catch (e) {\n logger.critical(\n 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n )\n logger.critical(e)\n }\n } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n for (let i = 0; i < functions.length; i++) {\n klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n const ret: Properties = {}\n each(p, function (v, k) {\n if ((isString(v) && v.length > 0) || isNumber(v)) {\n ret[k] = v\n }\n })\n return ret\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy<T extends Record<string, any> = Record<string, any>>(\n value: T,\n customizer?: <K extends keyof T = keyof T>(value: T[K], key?: K) => T[K]\n): T | undefined {\n const COPY_IN_PROGRESS_SET = new Set()\n\n function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n COPY_IN_PROGRESS_SET.add(value)\n let result: T\n\n if (isArray(value)) {\n result = [] as any as T\n eachArray(value, (it) => {\n result.push(internalDeepCircularCopy(it))\n })\n } else {\n result = {} as T\n each(value, (val, key) => {\n if (!COPY_IN_PROGRESS_SET.has(val)) {\n ;(result as any)[key] = internalDeepCircularCopy(val, key)\n }\n })\n }\n return result\n }\n return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings<T extends Record<string, any> = Record<string, any>>(\n object: T,\n maxStringLength: number\n): T {\n return deepCircularCopy(object, (value: any) => {\n if (isString(value)) {\n return (value as string).slice(0, maxStringLength)\n }\n return value\n }) as T\n}\n\n// NOTE: Update PostHogConfig docs if you change this list\n// We will not try to catch all bullets here, but we should make an effort to catch the most common ones\n// You should be highly against adding more to this list, because ultimately customers can configure\n// their `cross_subdomain_cookie` setting to anything they want.\nconst EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app']\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n const hostname = documentLocation?.hostname\n\n if (!isString(hostname)) {\n return false\n }\n // split and slice isn't a great way to match arbitrary domains,\n // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n // for the hostname\n const lastTwoParts = hostname.split('.').slice(-2).join('.')\n\n for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {\n if (lastTwoParts === excluded) {\n return false\n }\n }\n\n return true\n}\n\n// Use this instead of element.addEventListener to avoid eslint errors\n// this properly implements the default options for passive event listeners\nexport function addEventListener(\n element: Window | Document | Element | undefined,\n event: string,\n callback: EventListener,\n options?: AddEventListenerOptions\n): void {\n const { capture = false, passive = true } = options ?? {}\n\n // This is the only place where we are allowed to call this function\n // because the whole idea is that we should be calling this instead of the built-in one\n // eslint-disable-next-line posthog-js/no-add-event-listener\n element?.addEventListener(event, callback, { capture, passive })\n}\n\n/**\n * Helper to migrate deprecated config fields to new field names with appropriate warnings\n * @param config - The config object to check\n * @param newField - The new field name to use\n * @param oldField - The deprecated field name to check for\n * @param defaultValue - The default value if neither field is set\n * @param loggerInstance - Optional logger instance for deprecation warnings\n * @returns The value to use (new field takes precedence over old field)\n */\nexport function migrateConfigField<T>(\n config: Record<string, any>,\n newField: string,\n oldField: string,\n defaultValue: T,\n loggerInstance?: { warn: (message: string) => void }\n): T {\n const hasNewField = newField in config && !isNullish(config[newField])\n const hasOldField = oldField in config && !isNullish(config[oldField])\n\n if (hasNewField) {\n return config[newField]\n }\n\n if (hasOldField) {\n if (loggerInstance) {\n loggerInstance.warn(\n `Config field '${oldField}' is deprecated. Please use '${newField}' instead. ` +\n `The old field will be removed in a future major version.`\n )\n }\n return config[oldField]\n }\n\n return defaultValue\n}\n\nconst TOOLBAR_INTERNAL_INSTANCE_NAME = 'ph_toolbar_internal'\n\nexport function isToolbarInstance(config: Pick<PostHogConfig, 'name'>): boolean {\n return config.name === TOOLBAR_INTERNAL_INSTANCE_NAME\n}\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\nimport { isFunction } from '@posthog/core'\n\nexport function patch(\n source: { [key: string]: any },\n name: string,\n replacement: (...args: unknown[]) => unknown\n): () => void {\n try {\n if (!(name in source)) {\n return () => {\n //\n }\n }\n\n const original = source[name] as () => unknown\n const wrapped = replacement(original)\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (isFunction(wrapped)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n wrapped.prototype = wrapped.prototype || {}\n Object.defineProperties(wrapped, {\n __posthog_wrapped__: {\n enumerable: false,\n value: true,\n },\n })\n }\n\n source[name] = wrapped\n\n return () => {\n if (source[name] === wrapped) {\n source[name] = original\n }\n }\n } catch {\n return () => {\n //\n }\n // This can throw when multiple instrumentation layers try to wrap the same global object,\n // such as XMLHttpRequest, and redefine the same non-configurable wrapper marker.\n }\n}\n","import { NetworkRecordOptions } from '../../../types'\n\nfunction hostnameFromURL(url: string | URL | RequestInfo): string | null {\n try {\n if (typeof url === 'string') {\n return new URL(url).hostname\n }\n if ('url' in url) {\n return new URL(url.url).hostname\n }\n return url.hostname\n } catch {\n return null\n }\n}\n\nexport function isHostOnDenyList(url: string | URL | Request, options: NetworkRecordOptions) {\n const hostname = hostnameFromURL(url)\n const defaultNotDenied = { hostname, isHostDenied: false }\n\n if (!options.payloadHostDenyList?.length || !hostname?.trim().length) {\n return defaultNotDenied\n }\n\n for (const deny of options.payloadHostDenyList) {\n if (hostname.endsWith(deny)) {\n return { hostname, isHostDenied: true }\n }\n }\n\n return defaultNotDenied\n}\n","import { CapturedNetworkRequest, NetworkRecordOptions, PostHogConfig } from '../../../types'\nimport { isFunction, isNullish, isString, isUndefined } from '@posthog/core'\nimport { convertToURL } from '../../../utils/request-utils'\nimport { logger } from '../../../utils/logger'\nimport { shouldCaptureValue } from '../../../autocapture-utils'\nimport { each } from '../../../utils'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\n\nconst REDACTED = 'redacted'\n\nexport const defaultNetworkOptions: Required<NetworkRecordOptions> = {\n initiatorTypes: [\n 'audio',\n 'beacon',\n 'body',\n 'css',\n 'early-hint',\n 'embed',\n 'fetch',\n 'frame',\n 'iframe',\n 'icon',\n 'image',\n 'img',\n 'input',\n 'link',\n 'navigation',\n 'object',\n 'ping',\n 'script',\n 'track',\n 'video',\n 'xmlhttprequest',\n ],\n maskRequestFn: (data: CapturedNetworkRequest) => data,\n recordHeaders: false,\n recordBody: false,\n recordInitialRequests: false,\n recordPerformance: false,\n performanceEntryTypeToObserve: [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n ],\n payloadSizeLimitBytes: 1000000,\n payloadHostDenyList: [\n '.lr-ingest.io',\n '.ingest.sentry.io',\n '.clarity.ms',\n // NB no leading dot here\n // GA4/gtag beacons go to *.google-analytics.com; with Google Signals on they also hit\n // analytics.google.com (region1.analytics.google.com/g/collect), so deny both\n 'google-analytics.com',\n 'analytics.google.com',\n // New Relic browser agent (bam + bam-cell)\n 'nr-data.net',\n // Datadog browser RUM intake\n 'datadoghq.com',\n 'datadoghq.eu',\n 'ddog-gov.com',\n // other third-party analytics / session-replay vendors whose telemetry has no replay value\n 'segment.io',\n 'rudderstack.com',\n 'amplitude.com',\n 'mixpanel.com',\n // Hotjar uses both .com and .io for data collection\n 'hotjar.com',\n 'hotjar.io',\n 'fullstory.com',\n ],\n}\n\nconst HEADER_DENY_LIST = [\n 'authorization',\n 'x-forwarded-for',\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'x-api-key',\n 'x-real-ip',\n 'remote-addr',\n 'forwarded',\n 'proxy-authorization',\n 'x-csrf-token',\n 'x-csrftoken',\n 'x-xsrf-token',\n]\n\nconst PAYLOAD_CONTENT_DENY_LIST = [\n 'password',\n 'secret',\n 'passwd',\n 'api_key',\n 'apikey',\n 'auth',\n 'credentials',\n 'mysql_pwd',\n 'privatekey',\n 'private_key',\n 'token',\n]\n\n// substrings that mark a header as credential-bearing - catches custom names\n// (e.g. x-gist-encoded-user-token) that aren't in the exact deny list above\nconst HEADER_DENY_SUBSTRINGS = [\n 'auth',\n 'token',\n 'secret',\n 'session',\n 'api-key',\n 'apikey',\n 'api_key',\n 'credential',\n 'password',\n 'passwd',\n 'cookie',\n 'csrf',\n 'xsrf',\n]\n\nconst isDeniedHeader = (header: string): boolean => {\n const lower = header.toLowerCase()\n return HEADER_DENY_LIST.includes(lower) || HEADER_DENY_SUBSTRINGS.some((s) => lower.includes(s))\n}\n\nconst redactDeniedHeaders = (headers: CapturedNetworkRequest['requestHeaders']): void => {\n if (!isNullish(headers)) {\n each(Object.keys(headers), (header) => {\n if (isDeniedHeader(header)) {\n headers[header] = REDACTED\n }\n })\n }\n}\n\n// we always remove headers on the deny list because we never want to capture this sensitive data.\n// applies to both request and response headers (e.g. set-cookie is a response header)\nconst removeAuthorizationHeader = (data: CapturedNetworkRequest): CapturedNetworkRequest => {\n redactDeniedHeaders(data.requestHeaders)\n redactDeniedHeaders(data.responseHeaders)\n return data\n}\n\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', '/e/', '/i/']\n// want to ignore posthog paths when capturing requests, or we can get trapped in a loop\n// because calls to PostHog would be reported using a call to PostHog which would be reported....\nconst ignorePostHogPaths = (\n data: CapturedNetworkRequest,\n apiHostConfig: PostHogConfig['api_host']\n): CapturedNetworkRequest | undefined => {\n const url = convertToURL(data.name)\n\n // we need to account for api host config as e.g. pathname could be /ingest/s/ and we want to ignore that\n let replaceValue = apiHostConfig.indexOf('http') === 0 ? convertToURL(apiHostConfig)?.pathname : apiHostConfig\n if (replaceValue === '/') {\n replaceValue = ''\n }\n const pathname = url?.pathname.replace(replaceValue || '', '')\n\n if (url && pathname && POSTHOG_PATHS_TO_IGNORE.some((path) => pathname.indexOf(path) === 0)) {\n return undefined\n }\n return data\n}\n\nfunction estimateBytes(payload: string): number {\n return new Blob([payload]).size\n}\n\nfunction enforcePayloadSizeLimit(\n payload: string | null | undefined,\n headers: Record<string, any> | undefined,\n limit: number,\n description: string\n): string | null | undefined {\n if (isNullish(payload)) {\n return payload\n }\n\n let requestContentLength: string | number = headers?.['content-length'] || estimateBytes(payload)\n if (isString(requestContentLength)) {\n requestContentLength = parseInt(requestContentLength)\n }\n\n if (requestContentLength > limit) {\n return LOGGER_PREFIX + ` ${description} body too large to record (${requestContentLength} bytes)`\n }\n\n return payload\n}\n\n// people can have arbitrarily large payloads on their site, but we don't want to ingest them\nconst limitPayloadSize = (\n options: NetworkRecordOptions\n): ((data: CapturedNetworkRequest | undefined) => CapturedNetworkRequest | undefined) => {\n // the smallest of 1MB or the specified limit if there is one\n const limit = Math.min(1000000, options.payloadSizeLimitBytes ?? 1000000)\n\n return (data) => {\n if (data?.requestBody) {\n data.requestBody = enforcePayloadSizeLimit(data.requestBody, data.requestHeaders, limit, 'Request')\n }\n\n if (data?.responseBody) {\n data.responseBody = enforcePayloadSizeLimit(data.responseBody, data.responseHeaders, limit, 'Response')\n }\n\n return data\n }\n}\n\nfunction scrubPayload(payload: string | null | undefined, label: 'Request' | 'Response'): string | null | undefined {\n if (isNullish(payload)) {\n return payload\n }\n let scrubbed = payload\n\n if (!shouldCaptureValue(scrubbed, false)) {\n scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED\n }\n each(PAYLOAD_CONTENT_DENY_LIST, (text) => {\n if (scrubbed?.length && scrubbed?.indexOf(text) !== -1) {\n scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED + ' as might contain: ' + text\n }\n })\n\n return scrubbed\n}\n\nfunction scrubPayloads(capturedRequest: CapturedNetworkRequest | undefined): CapturedNetworkRequest | undefined {\n if (isUndefined(capturedRequest)) {\n return undefined\n }\n\n capturedRequest.requestBody = scrubPayload(capturedRequest.requestBody, 'Request')\n capturedRequest.responseBody = scrubPayload(capturedRequest.responseBody, 'Response')\n\n return capturedRequest\n}\n\n/**\n * whether a maskRequestFn is provided or not,\n * we ensure that we remove the denied header from requests\n * we _never_ want to record that header by accident\n * if someone complains then we'll add an opt-in to let them override it\n */\nexport const buildNetworkRequestOptions = (\n instanceConfig: PostHogConfig,\n remoteNetworkOptions: Pick<\n NetworkRecordOptions,\n 'recordHeaders' | 'recordBody' | 'recordPerformance' | 'payloadHostDenyList'\n >\n): NetworkRecordOptions => {\n const config: NetworkRecordOptions = {\n payloadSizeLimitBytes: defaultNetworkOptions.payloadSizeLimitBytes,\n performanceEntryTypeToObserve: [...defaultNetworkOptions.performanceEntryTypeToObserve],\n payloadHostDenyList: [\n ...(remoteNetworkOptions.payloadHostDenyList || []),\n ...defaultNetworkOptions.payloadHostDenyList,\n ],\n }\n // client can always disable despite remote options\n const canRecordHeaders =\n instanceConfig.session_recording.recordHeaders === false ? false : remoteNetworkOptions.recordHeaders\n const canRecordBody =\n instanceConfig.session_recording.recordBody === false ? false : remoteNetworkOptions.recordBody\n const canRecordPerformance =\n instanceConfig.capture_performance === false ? false : remoteNetworkOptions.recordPerformance\n\n const payloadLimiter = limitPayloadSize(config)\n\n const enforcedCleaningFn: NetworkRecordOptions['maskRequestFn'] = (d: CapturedNetworkRequest) =>\n payloadLimiter(ignorePostHogPaths(removeAuthorizationHeader(d), instanceConfig.api_host))\n\n const hasDeprecatedMaskFunction = isFunction(instanceConfig.session_recording.maskNetworkRequestFn)\n\n if (hasDeprecatedMaskFunction && isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)) {\n logger.warn(\n 'Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.'\n )\n }\n\n if (hasDeprecatedMaskFunction) {\n instanceConfig.session_recording.maskCapturedNetworkRequestFn = (data: CapturedNetworkRequest) => {\n const cleanedURL = instanceConfig.session_recording.maskNetworkRequestFn!({ url: data.name })\n return {\n ...data,\n name: cleanedURL?.url,\n } as CapturedNetworkRequest\n }\n }\n\n config.maskRequestFn = isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)\n ? (data) => {\n const cleanedRequest = enforcedCleaningFn(data)\n return cleanedRequest\n ? (instanceConfig.session_recording.maskCapturedNetworkRequestFn?.(cleanedRequest) ?? undefined)\n : undefined\n }\n : (data) => scrubPayloads(enforcedCleaningFn(data))\n\n return {\n ...defaultNetworkOptions,\n ...config,\n recordHeaders: canRecordHeaders,\n recordBody: canRecordBody,\n recordPerformance: canRecordPerformance,\n recordInitialRequests: canRecordPerformance,\n }\n}\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n/// <reference lib=\"dom\" />\n\n// rrweb/network@1 code starts\n// most of what is below here will be removed when rrweb release their code for this\n// see https://github.com/rrweb-io/rrweb/pull/1105\n\n// NB adopted from https://github.com/rrweb-io/rrweb/pull/1105 which looks like it will be accepted into rrweb\n// however, in the PR, it throws when the performance observer data is not available\n// and assumes it is running in a browser with the Request API (i.e. not IE11)\n// copying here so that we can use it before rrweb adopt it\n\nimport type { IWindow, listenerHandler, RecordPlugin } from '../types/rrweb-types'\nimport { CapturedNetworkRequest, Headers, InitiatorType, NetworkRecordOptions } from '../../../types'\nimport {\n isArray,\n isBoolean,\n isFormData,\n isFunction,\n isNull,\n isNullish,\n isString,\n isUndefined,\n isObject,\n} from '@posthog/core'\nimport { isDocument } from '../../../utils/type-utils'\nimport { createLogger } from '../../../utils/logger'\nimport { formDataToQuery } from '../../../utils/request-utils'\nimport { patch } from '../rrweb-plugins/patch'\nimport { isHostOnDenyList } from '../../../extensions/replay/external/denylist'\nimport { defaultNetworkOptions } from './config'\n\nconst logger = createLogger('[Recorder]')\n\nexport type NetworkData = {\n requests: CapturedNetworkRequest[]\n isInitial?: boolean\n}\n\ntype networkCallback = (data: NetworkData) => void\n\nconst isNavigationTiming = (entry: PerformanceEntry): entry is PerformanceNavigationTiming =>\n entry.entryType === 'navigation'\nconst isResourceTiming = (entry: PerformanceEntry): entry is PerformanceResourceTiming => entry.entryType === 'resource'\n\ntype ObservedPerformanceEntry = (PerformanceNavigationTiming | PerformanceResourceTiming) & {\n responseStatus?: number\n}\n\nexport function findLast<T>(array: Array<T>, predicate: (value: T) => boolean): T | undefined {\n const length = array.length\n for (let i = length - 1; i >= 0; i -= 1) {\n if (predicate(array[i])) {\n return array[i]\n }\n }\n return undefined\n}\n\nfunction initPerformanceObserver(cb: networkCallback, win: IWindow, options: Required<NetworkRecordOptions>) {\n // if we are only observing timings then we could have a single observer for all types, with buffer true,\n // but we are going to filter by initiatorType _if we are wrapping fetch and xhr as the wrapped functions\n // will deal with those.\n // so we have a block which captures requests from before fetch/xhr is wrapped\n // these are marked `isInitial` so playback can display them differently if needed\n // they will never have method/status/headers/body because they are pre-wrapping that provides that\n if (options.recordInitialRequests) {\n const initialPerformanceEntries = win.performance\n .getEntries()\n .filter(\n (entry): entry is ObservedPerformanceEntry =>\n isNavigationTiming(entry) ||\n (isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType as InitiatorType))\n )\n cb({\n requests: initialPerformanceEntries.flatMap((entry) =>\n prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {}, isInitial: true })\n ),\n isInitial: true,\n })\n }\n const observer = new win.PerformanceObserver((entries) => {\n // if recordBody or recordHeaders is true then we don't want to record fetch or xhr here\n // as the wrapped functions will do that. Otherwise, this filter becomes a noop\n // because we do want to record them here\n const wrappedInitiatorFilter = (entry: ObservedPerformanceEntry) =>\n options.recordBody || options.recordHeaders\n ? entry.initiatorType !== 'xmlhttprequest' && entry.initiatorType !== 'fetch'\n : true\n\n const performanceEntries = entries.getEntries().filter(\n (entry): entry is ObservedPerformanceEntry =>\n isNavigationTiming(entry) ||\n (isResourceTiming(entry) &&\n options.initiatorTypes.includes(entry.initiatorType as InitiatorType) &&\n // TODO if we are _only_ capturing timing we don't want to filter initiator here\n wrappedInitiatorFilter(entry))\n )\n\n cb({\n requests: performanceEntries.flatMap((entry) =>\n prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {} })\n ),\n })\n })\n // compat checked earlier\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) =>\n options.performanceEntryTypeToObserve.includes(x)\n )\n // initial records are gathered above, so we don't need to observe and buffer each type separately\n observer.observe({ entryTypes })\n return () => {\n observer.disconnect()\n }\n}\n\nfunction shouldRecordHeaders(type: 'request' | 'response', recordHeaders: NetworkRecordOptions['recordHeaders']) {\n return !!recordHeaders && (isBoolean(recordHeaders) || recordHeaders[type])\n}\n\nfunction isRequest(value: unknown): value is Request {\n if (typeof Request === 'undefined') {\n return false\n }\n if (value instanceof Request) {\n return true\n }\n try {\n return Object.prototype.toString.call(value) === '[object Request]'\n } catch {\n return false\n }\n}\n\n// binary/asset bodies are large and useless for replay debugging (and capturing an image body\n// duplicates what the recording already shows), so we never record them even when recordBody is on\nexport const NEVER_RECORD_BODY_CONTENT_TYPES = [\n 'image/',\n 'video/',\n 'audio/',\n 'font/',\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'application/wasm',\n]\n\nexport function shouldRecordBody({\n type,\n recordBody,\n headers,\n url,\n}: {\n type: 'request' | 'response'\n headers: Headers\n url: string | URL | RequestInfo\n recordBody: NetworkRecordOptions['recordBody']\n}) {\n function matchesContentType(contentTypes: string[]) {\n const contentTypeHeader = Object.keys(headers).find((key) => key.toLowerCase() === 'content-type')\n const contentType = contentTypeHeader && headers[contentTypeHeader]\n return contentTypes.some((ct) => contentType?.toLowerCase().includes(ct))\n }\n\n /**\n * particularly in canvas applications we see many requests to blob URLs\n * e.g. blob:https://video_url\n * these blob/object URLs are local to the browser, we can never capture that body\n * so we can just return false here\n */\n function isBlobURL(url: string | URL | RequestInfo) {\n try {\n if (typeof url === 'string') {\n return url.startsWith('blob:')\n }\n if (url instanceof URL) {\n return url.protocol === 'blob:'\n }\n if (isRequest(url)) {\n return isBlobURL(url.url)\n }\n return false\n } catch {\n return false\n }\n }\n if (!recordBody) return false\n if (isBlobURL(url)) return false\n // never record binary/asset bodies, regardless of the recordBody setting\n if (matchesContentType(NEVER_RECORD_BODY_CONTENT_TYPES)) return false\n if (isBoolean(recordBody)) return true\n if (isArray(recordBody)) return matchesContentType(recordBody)\n const recordBodyType = recordBody[type]\n if (isBoolean(recordBodyType)) return recordBodyType\n return matchesContentType(recordBodyType)\n}\n\nasync function getRequestPerformanceEntry(\n win: IWindow,\n initiatorType: string,\n url: string,\n start?: number,\n end?: number,\n attempt = 0\n): Promise<PerformanceResourceTiming | null> {\n if (attempt > 10) {\n logger.warn('Failed to get performance entry for request', { url, initiatorType })\n return null\n }\n const urlPerformanceEntries = win.performance.getEntriesByName(url) as PerformanceResourceTiming[]\n const performanceEntry = findLast(\n urlPerformanceEntries,\n (entry) =>\n isResourceTiming(entry) &&\n entry.initiatorType === initiatorType &&\n (isUndefined(start) || entry.startTime >= start) &&\n (isUndefined(end) || entry.startTime <= end)\n )\n if (!performanceEntry) {\n await new Promise((resolve) => setTimeout(resolve, 50 * attempt))\n return getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt + 1)\n }\n return performanceEntry\n}\n\n/**\n * According to MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response\n * xhr response is typed as any but can be an ArrayBuffer, a Blob, a Document, a JavaScript object,\n * or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.\n *\n * XHR request body is Document | XMLHttpRequestBodyInit | null | undefined\n */\nfunction _tryReadXHRBody({\n body,\n options,\n url,\n}: {\n body: Document | XMLHttpRequestBodyInit | any | null | undefined\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): string | null {\n if (isNullish(body)) {\n return null\n }\n\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return hostname + ' is in deny list'\n }\n\n if (isString(body)) {\n return body\n }\n\n if (isDocument(body)) {\n return body.textContent\n }\n\n if (isFormData(body)) {\n return formDataToQuery(body)\n }\n\n if (isObject(body)) {\n try {\n return JSON.stringify(body)\n } catch {\n return '[SessionReplay] Failed to stringify response object'\n }\n }\n\n return '[SessionReplay] Cannot read body of type ' + toString.call(body)\n}\n\nfunction initXhrObserver(cb: networkCallback, win: IWindow, options: Required<NetworkRecordOptions>): listenerHandler {\n if (!options.initiatorTypes.includes('xmlhttprequest')) {\n return () => {\n //\n }\n }\n const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n const restorePatch = patch(\n win.XMLHttpRequest.prototype,\n 'open',\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n (originalOpen: typeof XMLHttpRequest.prototype.open) => {\n return function (\n method: string,\n url: string | URL,\n async = true,\n username?: string | null,\n password?: string | null\n ) {\n // because this function is returned in its actual context `this` _is_ an XMLHttpRequest\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const xhr = this as XMLHttpRequest\n\n // check IE earlier than this, we only initialize if Request is present\n // eslint-disable-next-line compat/compat\n const req = new Request(url)\n const networkRequest: Partial<CapturedNetworkRequest> = {}\n let start: number | undefined\n let end: number | undefined\n\n const requestHeaders: Headers = {}\n const originalSetRequestHeader = xhr.setRequestHeader.bind(xhr)\n xhr.setRequestHeader = (header: string, value: string) => {\n requestHeaders[header] = value\n return originalSetRequestHeader(header, value)\n }\n if (recordRequestHeaders) {\n networkRequest.requestHeaders = requestHeaders\n }\n\n const originalSend = xhr.send.bind(xhr)\n xhr.send = (body) => {\n if (\n shouldRecordBody({\n type: 'request',\n headers: requestHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.requestBody = _tryReadXHRBody({ body, options, url })\n }\n start = win.performance.now()\n return originalSend(body)\n }\n\n // Cleanup function to remove all event listeners and prevent memory leaks\n const cleanup = () => {\n xhr.removeEventListener('readystatechange', readyStateListener)\n xhr.removeEventListener('error', cleanup)\n xhr.removeEventListener('abort', cleanup)\n xhr.removeEventListener('timeout', cleanup)\n }\n\n const readyStateListener = () => {\n if (xhr.readyState !== xhr.DONE) {\n return\n }\n\n // Clean up all listeners immediately when done to prevent memory leaks\n cleanup()\n\n end = win.performance.now()\n const responseHeaders: Headers = {}\n const rawHeaders = xhr.getAllResponseHeaders()\n const headers = rawHeaders.trim().split(/[\\r\\n]+/)\n headers.forEach((line) => {\n const parts = line.split(': ')\n const header = parts.shift()\n const value = parts.join(': ')\n if (header) {\n responseHeaders[header] = value\n }\n })\n if (recordResponseHeaders) {\n networkRequest.responseHeaders = responseHeaders\n }\n if (\n shouldRecordBody({\n type: 'response',\n headers: responseHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.responseBody = _tryReadXHRBody({ body: xhr.response, options, url })\n }\n getRequestPerformanceEntry(win, 'xmlhttprequest', req.url, start, end)\n .then((entry) => {\n const requests = prepareRequest({\n entry,\n method: method,\n status: xhr?.status,\n networkRequest,\n start,\n end,\n url: url.toString(),\n initiatorType: 'xmlhttprequest',\n })\n cb({ requests })\n })\n .catch(() => {\n //\n })\n }\n\n // This is very tricky code, and making it passive won't bring many performance benefits,\n // so let's ignore the rule here.\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('readystatechange', readyStateListener)\n // Also clean up on error, abort, and timeout to prevent memory leaks\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('error', cleanup)\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('abort', cleanup)\n // eslint-disable-next-line posthog-js/no-add-event-listener\n xhr.addEventListener('timeout', cleanup)\n\n originalOpen.call(xhr, method, url.toString(), async, username, password)\n }\n }\n )\n return () => {\n restorePatch()\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry | null): event is PerformanceResourceTiming =>\n !isNull(event) && (event.entryType === 'navigation' || event.entryType === 'resource')\n\nfunction prepareRequest({\n entry,\n method,\n status,\n networkRequest,\n isInitial,\n start,\n end,\n url,\n initiatorType,\n}: {\n entry: PerformanceResourceTiming | null\n method: string | undefined\n status: number | undefined\n networkRequest: Partial<CapturedNetworkRequest>\n isInitial?: boolean\n start?: number\n end?: number\n // if there is no performance observer entry, we still need to know the url\n url?: string\n // if there is no performance observer entry, we can provide the initiatorType\n initiatorType?: string\n}): CapturedNetworkRequest[] {\n start = entry ? entry.startTime : start\n end = entry ? entry.responseEnd : end\n\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n // use timeOrigin if we really can't gather a start time\n const timestamp = Math.floor(timeOrigin + (start || 0))\n\n const entryJSON = entry ? entry.toJSON() : { name: url }\n\n const requests: CapturedNetworkRequest[] = [\n {\n ...entryJSON,\n startTime: isUndefined(start) ? undefined : Math.round(start),\n endTime: isUndefined(end) ? undefined : Math.round(end),\n timeOrigin,\n timestamp,\n method: method,\n initiatorType: initiatorType ? initiatorType : entry ? (entry.initiatorType as InitiatorType) : undefined,\n status,\n requestHeaders: networkRequest.requestHeaders,\n requestBody: networkRequest.requestBody,\n responseHeaders: networkRequest.responseHeaders,\n responseBody: networkRequest.responseBody,\n isInitial,\n },\n ]\n\n if (exposesServerTiming(entry)) {\n for (const timing of entry.serverTiming || []) {\n requests.push({\n timeOrigin,\n timestamp,\n startTime: Math.round(entry.startTime),\n name: timing.name,\n duration: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n entryType: 'serverTiming',\n })\n }\n }\n\n return requests\n}\n\nconst contentTypePrefixDenyList = ['video/', 'audio/']\n\nfunction _checkForCannotReadResponseBody({\n r,\n options,\n url,\n}: {\n r: Response\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): string | null {\n if (r.headers.get('Transfer-Encoding') === 'chunked') {\n return 'Chunked Transfer-Encoding is not supported'\n }\n\n // `get` and `has` are case-insensitive\n // but return the header value with the casing that was supplied\n const contentType = r.headers.get('Content-Type')?.toLowerCase()\n const contentTypeIsDenied = contentTypePrefixDenyList.some((prefix) => contentType?.startsWith(prefix))\n if (contentType && contentTypeIsDenied) {\n return `Content-Type ${contentType} is not supported`\n }\n\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return hostname + ' is in deny list'\n }\n\n return null\n}\n\nfunction isReadableStreamBody(body: unknown): body is ReadableStream<Uint8Array> {\n return isObject(body) && isFunction(body.getReader) && isFunction(body.tee)\n}\n\nfunction _tryReadBody(r: Request | Response): Promise<string> {\n // there are now already multiple places where we're using Promise...\n // eslint-disable-next-line compat/compat\n return new Promise((resolve) => {\n const timeout = setTimeout(() => resolve('[SessionReplay] Timeout while trying to read body'), 500)\n try {\n r.clone()\n .text()\n .then(\n (txt) => resolve(txt),\n (reason) => resolve('[SessionReplay] Failed to read body: ' + reason)\n )\n .finally(() => clearTimeout(timeout))\n } catch {\n clearTimeout(timeout)\n resolve('[SessionReplay] Failed to read body')\n }\n })\n}\n\nasync function _tryReadRequestBody({\n r,\n options,\n url,\n}: {\n r: Request\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): Promise<string> {\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return Promise.resolve(hostname + ' is in deny list')\n }\n\n return _tryReadBody(r)\n}\n\nasync function _tryReadResponseBody({\n r,\n options,\n url,\n}: {\n r: Response\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): Promise<string> {\n const cannotReadBodyReason: string | null = _checkForCannotReadResponseBody({ r, options, url })\n if (!isNull(cannotReadBodyReason)) {\n return Promise.resolve(cannotReadBodyReason)\n }\n\n return _tryReadBody(r)\n}\n\nfunction initFetchObserver(\n cb: networkCallback,\n win: IWindow,\n options: Required<NetworkRecordOptions>\n): listenerHandler {\n if (!options.initiatorTypes.includes('fetch')) {\n return () => {\n //\n }\n }\n const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const restorePatch = patch(win, 'fetch', (originalFetch: typeof fetch) => {\n return async function (url: URL | RequestInfo, init?: RequestInit | undefined) {\n // check IE earlier than this, we only initialize if Request is present\n // eslint-disable-next-line compat/compat\n const req = new Request(url, init)\n let res: Response | undefined\n const networkRequest: Partial<CapturedNetworkRequest> = {}\n let start: number | undefined\n let end: number | undefined\n\n try {\n const requestHeaders: Headers = {}\n req.headers.forEach((value: string, header: string | number) => {\n requestHeaders[header] = value\n })\n if (recordRequestHeaders) {\n networkRequest.requestHeaders = requestHeaders\n }\n // Check the caller-supplied body, not req.body: Request normalizes all non-null bodies\n // to a ReadableStream, but only an original ReadableStream would be locked by req.clone().text().\n const requestBodyIsReadableStream = isReadableStreamBody(init?.body)\n if (\n !requestBodyIsReadableStream &&\n shouldRecordBody({\n type: 'request',\n headers: requestHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.requestBody = await _tryReadRequestBody({ r: req, options, url })\n }\n\n start = win.performance.now()\n // Use `req` for recording metadata/body only. For fetch(url, init), do not pass this internally-created\n // Request downstream: it exposes request.body as a ReadableStream, and wrappers that forward that body\n // can trigger Safari's \"ReadableStream uploading is not supported\" error. For fetch(Request), we must\n // pass the cloned Request because constructing `req` may consume the original Request body.\n res = isRequest(url) ? await originalFetch(req) : await originalFetch(url, init)\n end = win.performance.now()\n\n const responseHeaders: Headers = {}\n res.headers.forEach((value: string, header: string | number) => {\n responseHeaders[header] = value\n })\n if (recordResponseHeaders) {\n networkRequest.responseHeaders = responseHeaders\n }\n if (\n shouldRecordBody({\n type: 'response',\n headers: responseHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.responseBody = await _tryReadResponseBody({ r: res, options, url })\n }\n\n return res\n } finally {\n getRequestPerformanceEntry(win, 'fetch', req.url, start, end)\n .then((entry) => {\n const requests = prepareRequest({\n entry,\n method: req.method,\n status: res?.status,\n networkRequest,\n start,\n end,\n url: req.url,\n initiatorType: 'fetch',\n })\n cb({ requests })\n })\n .catch(() => {\n //\n })\n }\n }\n })\n return () => {\n restorePatch()\n }\n}\n\nlet initialisedHandler: listenerHandler | null = null\n\nfunction initNetworkObserver(\n callback: networkCallback,\n win: IWindow, // top window or in an iframe\n options: NetworkRecordOptions\n): listenerHandler {\n if (!('performance' in win)) {\n return () => {\n //\n }\n }\n\n if (initialisedHandler) {\n logger.warn('Network observer already initialised, doing nothing')\n return () => {\n // the first caller should already have this handler and will be responsible for teardown\n }\n }\n\n const networkOptions = (\n options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions\n ) as Required<NetworkRecordOptions>\n\n const cb: networkCallback = (data) => {\n const requests: CapturedNetworkRequest[] = []\n data.requests.forEach((request) => {\n const maskedRequest = networkOptions.maskRequestFn(request)\n if (maskedRequest) {\n requests.push(maskedRequest)\n }\n })\n\n if (requests.length > 0) {\n callback({ ...data, requests })\n }\n }\n const performanceObserver = initPerformanceObserver(cb, win, networkOptions)\n\n // only wrap fetch and xhr if headers or body are being recorded\n let xhrObserver: listenerHandler = () => {}\n let fetchObserver: listenerHandler = () => {}\n if (networkOptions.recordHeaders || networkOptions.recordBody) {\n xhrObserver = initXhrObserver(cb, win, networkOptions)\n fetchObserver = initFetchObserver(cb, win, networkOptions)\n }\n\n initialisedHandler = () => {\n performanceObserver()\n xhrObserver()\n fetchObserver()\n initialisedHandler = null\n }\n return initialisedHandler\n}\n\n// use the plugin name so that when this functionality is adopted into rrweb\n// we can remove this plugin and use the core functionality with the same data\nexport const NETWORK_PLUGIN_NAME = 'rrweb/network@1'\n\n// TODO how should this be typed?\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nexport const getRecordNetworkPlugin: (options?: NetworkRecordOptions) => RecordPlugin = (options) => {\n return {\n name: NETWORK_PLUGIN_NAME,\n observer: initNetworkObserver,\n options: options,\n }\n}\n\n// rrweb/networ@1 ends\n","// This file is kept only for backwards compatibility.\n// In almost every case, if you are manually importing a file you should use posthog-recorder instead.\n\nimport { record as rrwebRecord, wasMaxDepthReached, resetMaxDepthState } from '@posthog/rrweb-record'\nimport { getRecordConsolePlugin } from '@posthog/rrweb-plugin-console-record'\nimport { getRecordNetworkPlugin } from '../extensions/replay/external/network-plugin'\nimport { assignableWindow } from '../utils/globals'\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.rrwebPlugins = { getRecordConsolePlugin, getRecordNetworkPlugin }\nassignableWindow.__PosthogExtensions__.rrweb = {\n record: rrwebRecord,\n version: 'v2',\n wasMaxDepthReached,\n resetMaxDepthState,\n}\n\n// we used to put all of these items directly on window, and now we put it on __PosthogExtensions__\n// but that means that old clients which lazily load this extension are looking in the wrong place\n// yuck,\n// so we also put them directly on the window\n// when 1.161.1 is the oldest version seen in production we can remove this\nassignableWindow.rrweb = { record: rrwebRecord, version: 'v2' }\nassignableWindow.rrwebConsoleRecord = { getRecordConsolePlugin }\nassignableWindow.getRecordNetworkPlugin = getRecordNetworkPlugin\n\nexport default rrwebRecord\n"],"names":["_a","EventType","EventType2","IncrementalSource","IncrementalSource2","MouseInteractions","MouseInteractions2","PointerTypes","PointerTypes2","CanvasContext","CanvasContext2","MediaInteractions","MediaInteractions2","NodeType","NodeType2","_a2","_b","_c","_d","_a3","source","name","replacement","original","wrapped","prototype","Object","defineProperties","__rrweb_original__","enumerable","value","_unused","ObjProto","type_utils_hasOwnProperty","hasOwnProperty","type_utils_toString","toString","isArray","Array","obj","call","isFunction","x","isObject","isUndefined","isString","isNull","isNullish","isBoolean","isFormData","FormData","win","window","undefined","global","globalThis","self","File","XMLHttpRequest","assignableWindow","isDocument","Document","_createLogger","prefix","_temp","debugEnabled","logger","_log","level","POSTHOG_DEBUG","console","consoleLog","_len","arguments","length","args","_key","debug","_len2","_key2","info","_len3","_key3","warn","_len4","_key4","error","_len5","_key5","critical","_len6","_key6","uninitializedWarning","methodName","createLogger","additionalPrefix","options","formDataToQuery","formdata","arg_separator","use_val","use_key","tph_arr","iterator","forEach","val","key","each","encodeURIComponent","join","patch","__posthog_wrapped__","isHostOnDenyList","url","_options$payloadHostD","hostname","URL","hostnameFromURL","defaultNotDenied","isHostDenied","payloadHostDenyList","trim","deny","endsWith","defaultNetworkOptions","initiatorTypes","maskRequestFn","data","recordHeaders","recordBody","recordInitialRequests","recordPerformance","performanceEntryTypeToObserve","payloadSizeLimitBytes","isNavigationTiming","entry","entryType","isResourceTiming","shouldRecordHeaders","type","isRequest","Request","NEVER_RECORD_BODY_CONTENT_TYPES","shouldRecordBody","_ref","headers","matchesContentType","contentTypes","contentTypeHeader","keys","find","toLowerCase","contentType","some","ct","includes","isBlobURL","startsWith","protocol","_unused2","recordBodyType","getRequestPerformanceEntry","_x","_x2","_x3","_x4","_x5","_x6","_getRequestPerformanceEntry","apply","this","_asyncToGenerator","initiatorType","start","end","attempt","performanceEntry","array","predicate","i","startTime","findLast","performance","getEntriesByName","Promise","resolve","setTimeout","_tryReadXHRBody","_ref2","body","textContent","JSON","stringify","_unused3","exposesServerTiming","event","prepareRequest","_ref3","method","status","networkRequest","isInitial","responseEnd","timeOrigin","Math","floor","Date","now","timestamp","requests","_extends","toJSON","round","endTime","requestHeaders","requestBody","responseHeaders","responseBody","timing","serverTiming","push","duration","contentTypePrefixDenyList","_tryReadBody","r","timeout","clone","text","then","txt","reason","finally","clearTimeout","_unused4","_tryReadRequestBody2","_ref5","_tryReadResponseBody2","_ref6","cannotReadBodyReason","_ref4","_r$headers$get","get","contentTypeIsDenied","_checkForCannotReadResponseBody","initialisedHandler","initNetworkObserver","callback","networkOptions","assign","cb","request","maskedRequest","performanceObserver","initialPerformanceEntries","getEntries","filter","flatMap","observer","PerformanceObserver","entries","performanceEntries","wrappedInitiatorFilter","entryTypes","supportedEntryTypes","observe","disconnect","initPerformanceObserver","xhrObserver","fetchObserver","recordRequestHeaders","recordResponseHeaders","restorePatch","originalOpen","async","username","password","xhr","req","originalSetRequestHeader","setRequestHeader","bind","header","originalSend","send","cleanup","removeEventListener","readyStateListener","readyState","DONE","getAllResponseHeaders","split","line","parts","shift","response","catch","addEventListener","initXhrObserver","originalFetch","_ref7","init","res","getReader","tee","_x7","_tryReadRequestBody","_x8","_tryReadResponseBody","_res","_x9","_x0","initFetchObserver","getRecordNetworkPlugin","__PosthogExtensions__","rrwebPlugins","getRecordConsolePlugin","rrweb","record","rrwebRecord","version","wasMaxDepthReached","resetMaxDepthState","rrwebConsoleRecord"],"mappings":"ijBAAAA,mKAAIC,EAA6B,CAACC,IAChCA,EAAWA,EAA6B,iBAAI,GAAK,mBACjDA,EAAWA,EAAiB,KAAI,GAAK,OACrCA,EAAWA,EAAyB,aAAI,GAAK,eAC7CA,EAAWA,EAAgC,oBAAI,GAAK,sBACpDA,EAAWA,EAAiB,KAAI,GAAK,OACrCA,EAAWA,EAAmB,OAAI,GAAK,SACvCA,EAAWA,EAAmB,OAAI,GAAK,SAChCA,GARwB,CAS9BD,GAAa,CAAA,GAEZE,EAAqC,CAACC,IACxCA,EAAmBA,EAA6B,SAAI,GAAK,WACzDA,EAAmBA,EAA8B,UAAI,GAAK,YAC1DA,EAAmBA,EAAqC,iBAAI,GA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