{
  "version": 3,
  "sources": ["../../types/dist/rrweb-types.js", "../../utils/dist/rrweb-utils.js", "../../rrweb-snapshot/src/utils.ts", "../../rrweb-snapshot/src/snapshot.ts", "../../rrdom/src/document.ts", "../../rrweb/src/utils.ts", "../../rrweb/src/record/mutation.ts", "../../rrweb/src/record/error-handler.ts", "../../rrweb/src/record/observer.ts", "../../rrweb/src/record/cross-origin-iframe-mirror.ts", "../../rrweb/src/record/iframe-manager.ts", "../../rrweb/src/record/shadow-dom-manager.ts", "../../../node_modules/.pnpm/base64-arraybuffer@1.0.2/node_modules/base64-arraybuffer/dist/base64-arraybuffer.es5.js", "../../rrweb/src/record/observers/canvas/serialize-args.ts", "../../rrweb/src/record/observers/canvas/2d.ts", "../../rrweb/src/record/observers/canvas/canvas.ts", "../../rrweb/src/record/observers/canvas/webgl.ts", "../../rrweb/src/record/observers/canvas/canvas-manager.ts", "../../rrweb/src/record/stylesheet-manager.ts", "../../rrweb/src/record/processed-node-manager.ts", "../../rrweb/src/record/index.ts"],
  "sourcesContent": ["var 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 || {});\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 ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n  ReplayerEvents2[\"Start\"] = \"start\";\n  ReplayerEvents2[\"Pause\"] = \"pause\";\n  ReplayerEvents2[\"Resume\"] = \"resume\";\n  ReplayerEvents2[\"Resize\"] = \"resize\";\n  ReplayerEvents2[\"Finish\"] = \"finish\";\n  ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n  ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n  ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n  ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n  ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n  ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n  ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n  ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n  ReplayerEvents2[\"Flush\"] = \"flush\";\n  ReplayerEvents2[\"StateChange\"] = \"state-change\";\n  ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n  ReplayerEvents2[\"Destroy\"] = \"destroy\";\n  return ReplayerEvents2;\n})(ReplayerEvents || {});\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 || {});\nexport {\n  CanvasContext,\n  EventType,\n  IncrementalSource,\n  MediaInteractions,\n  MouseInteractions,\n  NodeType,\n  PointerTypes,\n  ReplayerEvents\n};\n//# sourceMappingURL=rrweb-types.js.map\n", "const 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 _a, _b;\n  const angularUnpatchedVersionSymbol = (_b = (_a = globalThis == null ? void 0 : globalThis.Zone) == null ? void 0 : _a.__symbol__) == null ? void 0 : _b.call(_a, 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 _a, _b;\n        return Boolean(\n          (_b = (_a = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a.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 _a;\n        return typeof defaultPrototype[method] === \"function\" && ((_a = defaultPrototype[method]) == null ? void 0 : _a.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 _a;\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 = (_a = Object.getOwnPropertyDescriptor(\n    untaintedPrototype,\n    accessor\n  )) == null ? void 0 : _a.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};\nexport {\n  childNodes,\n  contains,\n  index as default,\n  getRootNode,\n  getUntaintedAccessor,\n  getUntaintedMethod,\n  getUntaintedPrototype,\n  host,\n  mutationObserverCtor,\n  parentElement,\n  parentNode,\n  patch,\n  querySelector,\n  querySelectorAll,\n  shadowRoot,\n  styleSheets,\n  textContent\n};\n//# sourceMappingURL=rrweb-utils.js.map\n", "import type {\n  idNodeMap,\n  MaskInputFn,\n  MaskInputOptions,\n  nodeMetaMap,\n} from './types';\n\nimport { NodeType } from '@posthog/rrweb-types';\nimport type {\n  IMirror,\n  serializedNodeWithId,\n  serializedNode,\n  documentNode,\n  documentTypeNode,\n  textNode,\n  elementNode,\n} from '@posthog/rrweb-types';\nimport dom from '@posthog/rrweb-utils';\n\nexport function isElement(n: Node): n is Element {\n  return n.nodeType === n.ELEMENT_NODE;\n}\n\nexport function isShadowRoot(n: Node): n is ShadowRoot {\n  const hostEl: Element | null =\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 && dom.host(n as ShadowRoot)) || null;\n  return Boolean(\n    hostEl && 'shadowRoot' in hostEl && dom.shadowRoot(hostEl) === n,\n  );\n}\n\n/**\n * To fix the issue https://github.com/rrweb-io/rrweb/issues/933.\n * Some websites use polyfilled shadow dom and this function is used to detect this situation.\n */\nexport function isNativeShadowDom(shadowRoot: ShadowRoot): boolean {\n  return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\n}\n\n/**\n * Browsers sometimes destructively modify the css rules they receive.\n * This function tries to rectify the modifications the browser made to make it more cross platform compatible.\n * @param cssText - output of `CSSStyleRule.cssText`\n * @returns `cssText` with browser inconsistencies fixed.\n */\nfunction fixBrowserCompatibilityIssuesInCSS(cssText: string): string {\n  /**\n   * Chrome outputs `-webkit-background-clip` as `background-clip` in `CSSStyleRule.cssText`.\n   * But then Chrome ignores `background-clip` as css input.\n   * Re-introduce `-webkit-background-clip` to fix this issue.\n   */\n  if (\n    cssText.includes(' background-clip: text;') &&\n    !cssText.includes(' -webkit-background-clip: text;')\n  ) {\n    cssText = cssText.replace(\n      /\\sbackground-clip:\\s*text;/g,\n      ' -webkit-background-clip: text; background-clip: text;',\n    );\n  }\n  return cssText;\n}\n\n// Remove this declaration once typescript has added `CSSImportRule.supportsText` to the lib.\ndeclare interface CSSImportRule extends CSSRule {\n  readonly href: string;\n  readonly layerName: string | null;\n  readonly media: MediaList;\n  readonly styleSheet: CSSStyleSheet;\n  /**\n   * experimental API, currently only supported in firefox\n   * https://developer.mozilla.org/en-US/docs/Web/API/CSSImportRule/supportsText\n   */\n  readonly supportsText?: string | null;\n}\n\n/**\n * Browsers sometimes incorrectly escape `@import` on `.cssText` statements.\n * This function tries to correct the escaping.\n * more info: https://bugs.chromium.org/p/chromium/issues/detail?id=1472259\n * @param cssImportRule\n * @returns `cssText` with browser inconsistencies fixed, or null if not applicable.\n */\nexport function escapeImportStatement(rule: CSSImportRule): string {\n  const { cssText } = rule;\n  if (cssText.split('\"').length < 3) return cssText;\n\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}\n\nexport function stringifyStylesheet(s: CSSStyleSheet): string | null {\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      // an inline <style> element\n      sheetHref = s.ownerNode.baseURI;\n    }\n    const stringifiedRules = Array.from(rules, (rule: CSSRule) =>\n      stringifyRule(rule, sheetHref),\n    ).join('');\n    return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);\n  } catch (error) {\n    return null;\n  }\n}\n\nexport function stringifyRule(rule: CSSRule, sheetHref: string | null): string {\n  if (isCSSImportRule(rule)) {\n    let importStringified;\n    try {\n      importStringified =\n        // for same-origin stylesheets,\n        // we can access the imported stylesheet rules directly\n        stringifyStylesheet(rule.styleSheet) ||\n        // work around browser issues with the raw string `@import url(...)` statement\n        escapeImportStatement(rule);\n    } catch (error) {\n      importStringified = rule.cssText;\n    }\n    // if importStringified is not null,\n    // there should be a stylesheet and a rule here,\n    // but we avoid errors in this method by checking for null\n    // see https://github.com/rrweb-io/rrweb/pull/1686\n    try {\n      if (importStringified && rule.styleSheet?.href) {\n        // url()s within the imported stylesheet are relative to _that_ sheet's href\n        return absolutifyURLs(importStringified, rule.styleSheet.href);\n      }\n    } catch {\n      // swallow this, we'll return null\n    }\n    return importStringified;\n  } else {\n    let ruleStringified = rule.cssText;\n    if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\n      // Safari does not escape selectors with : properly\n      // see https://bugs.webkit.org/show_bug.cgi?id=184604\n      ruleStringified = fixSafariColons(ruleStringified);\n    }\n    if (sheetHref) {\n      return absolutifyURLs(ruleStringified, sheetHref);\n    }\n    return ruleStringified;\n  }\n}\n\nexport function fixSafariColons(cssStringified: string): string {\n  // Replace e.g. [aa:bb] with [aa\\\\:bb]\n  const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n  return cssStringified.replace(regex, '$1\\\\$2');\n}\n\nexport function isCSSImportRule(rule: CSSRule): rule is CSSImportRule {\n  return 'styleSheet' in rule;\n}\n\nexport function isCSSStyleRule(rule: CSSRule): rule is CSSStyleRule {\n  return 'selectorText' in rule;\n}\n\nexport class Mirror implements IMirror<Node> {\n  private idNodeMap: idNodeMap = new Map();\n  private nodeMetaMap: nodeMetaMap = new WeakMap();\n\n  getId(n: Node | undefined | null): number {\n    if (!n) return -1;\n\n    const id = this.getMeta(n)?.id;\n\n    // if n is not a serialized Node, use -1 as its id.\n    return id ?? -1;\n  }\n\n  getNode(id: number): Node | null {\n    return this.idNodeMap.get(id) || null;\n  }\n\n  getIds(): number[] {\n    return Array.from(this.idNodeMap.keys());\n  }\n\n  getMeta(n: Node): serializedNodeWithId | null {\n    return this.nodeMetaMap.get(n) || null;\n  }\n\n  // removes the node from idNodeMap\n  // doesn't remove the node from nodeMetaMap\n  removeNodeFromMap(n: Node) {\n    const id = this.getId(n);\n    this.idNodeMap.delete(id);\n\n    if (n.childNodes) {\n      n.childNodes.forEach((childNode) =>\n        this.removeNodeFromMap(childNode as unknown as Node),\n      );\n    }\n\n    if (isElement(n)) {\n      const shadowRootEl = dom.shadowRoot(n);\n      if (shadowRootEl) {\n        this.removeNodeFromMap(shadowRootEl as unknown as Node);\n      }\n\n      if (n.nodeName === 'IFRAME' && (n as HTMLIFrameElement).contentDocument) {\n        this.removeNodeFromMap(\n          (n as HTMLIFrameElement).contentDocument as unknown as Node,\n        );\n      }\n    }\n  }\n  has(id: number): boolean {\n    return this.idNodeMap.has(id);\n  }\n\n  hasNode(node: Node): boolean {\n    return this.nodeMetaMap.has(node);\n  }\n\n  add(n: Node, meta: serializedNodeWithId) {\n    const id = meta.id;\n    this.idNodeMap.set(id, n);\n    this.nodeMetaMap.set(n, meta);\n  }\n\n  replace(id: number, n: Node) {\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\n  reset() {\n    this.idNodeMap = new Map();\n    this.nodeMetaMap = new WeakMap();\n  }\n}\n\nexport function createMirror(): Mirror {\n  return new Mirror();\n}\n\nexport function maskInputValue({\n  element,\n  maskInputOptions,\n  tagName,\n  type,\n  value,\n  maskInputFn,\n}: {\n  element: HTMLElement;\n  maskInputOptions: MaskInputOptions;\n  tagName: string;\n  type: string | null;\n  value: string | null;\n  maskInputFn?: MaskInputFn;\n}): string {\n  let text = value || '';\n  const actualType = type && toLowerCase(type);\n\n  if (\n    maskInputOptions[tagName.toLowerCase() as keyof MaskInputOptions] ||\n    (actualType && maskInputOptions[actualType as keyof MaskInputOptions])\n  ) {\n    if (maskInputFn) {\n      text = maskInputFn(text, element);\n    } else {\n      text = '*'.repeat(text.length);\n    }\n  }\n  return text;\n}\n\nexport function toLowerCase<T extends string>(str: T): Lowercase<T> {\n  return str.toLowerCase() as unknown as Lowercase<T>;\n}\n\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\ntype PatchedGetImageData = {\n  [ORIGINAL_ATTRIBUTE_NAME]: CanvasImageData['getImageData'];\n} & CanvasImageData['getImageData'];\n\nexport function is2DCanvasBlank(canvas: HTMLCanvasElement): boolean {\n  const ctx = canvas.getContext('2d');\n  if (!ctx) return true;\n\n  const chunkSize = 50;\n\n  // get chunks of the canvas and check if it is blank\n  for (let x = 0; x < canvas.width; x += chunkSize) {\n    for (let y = 0; y < canvas.height; y += chunkSize) {\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      const getImageData = ctx.getImageData as PatchedGetImageData;\n      const originalGetImageData =\n        ORIGINAL_ATTRIBUTE_NAME in getImageData\n          ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n          : getImageData;\n      // by getting the canvas in chunks we avoid an expensive\n      // `getImageData` call that retrieves everything\n      // even if we can already tell from the first chunk(s) that\n      // the canvas isn't blank\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}\n\nexport function isNodeMetaEqual(a: serializedNode, b: serializedNode): boolean {\n  if (!a || !b || a.type !== b.type) return false;\n  if (a.type === NodeType.Document)\n    return a.compatMode === (b as documentNode).compatMode;\n  else if (a.type === NodeType.DocumentType)\n    return (\n      a.name === (b as documentTypeNode).name &&\n      a.publicId === (b as documentTypeNode).publicId &&\n      a.systemId === (b as documentTypeNode).systemId\n    );\n  else if (\n    a.type === NodeType.Comment ||\n    a.type === NodeType.Text ||\n    a.type === NodeType.CDATA\n  )\n    return a.textContent === (b as textNode).textContent;\n  else if (a.type === NodeType.Element)\n    return (\n      a.tagName === (b as elementNode).tagName &&\n      JSON.stringify(a.attributes) ===\n        JSON.stringify((b as elementNode).attributes) &&\n      a.isSVG === (b as elementNode).isSVG &&\n      a.needBlock === (b as elementNode).needBlock\n    );\n  return false;\n}\n\n/**\n * Get the type of an input element.\n * This takes care of the case where a password input is changed to a text input.\n * In this case, we continue to consider this of type password, in order to avoid leaking sensitive data\n * where passwords should be masked.\n */\nexport function getInputType(element: HTMLElement): Lowercase<string> | null {\n  // when omitting the type of input element(e.g. <input />), the type is treated as text\n  const type = (element as HTMLInputElement).type;\n\n  return element.hasAttribute('data-rr-is-password')\n    ? 'password'\n    : type\n    ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n      toLowerCase(type)\n    : null;\n}\n\n/**\n * Extracts the file extension from an a path, considering search parameters and fragments.\n * @param path - Path to file\n * @param baseURL - [optional] Base URL of the page, used to resolve relative paths. Defaults to current page URL.\n */\nexport function extractFileExtension(\n  path: string,\n  baseURL?: string,\n): string | null {\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?.[1] ?? null;\n}\n\nfunction extractOrigin(url: string): string {\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}\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;\nexport function absolutifyURLs(cssText: string | null, href: string): string {\n  return (cssText || '').replace(\n    URL_IN_CSS_REF,\n    (\n      origin: string,\n      quote1: string,\n      path1: string,\n      quote2: string,\n      path2: string,\n      path3: string,\n    ) => {\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}${\n          extractOrigin(href) + filePath\n        }${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}\n\nconst STRIPED_PLACEHOLDER_SVG =\n  'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxkZWZzPgogICAgPHBhdHRlcm4gaWQ9InN0cmlwZXMiIHBhdHRlcm5Vbml0cz0idXNlclNwYWNlT25Vc2UiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+CiAgICAgIDxyZWN0IHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iYmxhY2siLz4KICAgICAgPHBhdGggZD0iTTggMEgxNkwwIDE2VjhMOCAwWiIgZmlsbD0iIzJEMkQyRCIvPgogICAgICA8cGF0aCBkPSJNMTYgOFYxNkg4TDE2IDhaIiBmaWxsPSIjMkQyRDJEIi8+CiAgICA8L3BhdHRlcm4+CiAgPC9kZWZzPgogIDxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjc3RyaXBlcykiLz4KPC9zdmc+Cg==';\n\nconst MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION = 4096;\n\nexport function recompressBase64Image(\n  img: HTMLImageElement,\n  dataURL: string,\n  type?: string,\n  quality?: number,\n): string {\n  if (!img.complete || img.naturalWidth === 0) {\n    return dataURL;\n  }\n\n  // don't recompress very large images to avoid performance issues\n  if (\n    img.naturalWidth > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION ||\n    img.naturalHeight > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION\n  ) {\n    return dataURL;\n  }\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\n    if (!ctx) {\n      return dataURL;\n    }\n\n    ctx.drawImage(img, 0, 0);\n    const recompressed = canvas.toDataURL(type || 'image/webp', quality ?? 0.4);\n\n    return recompressed;\n  } catch (err) {\n    return dataURL;\n  }\n}\n\nexport function checkDataURLSize(\n  dataURL: string,\n  maxLength: number | undefined,\n): string {\n  if (!maxLength || dataURL.length <= maxLength) {\n    return dataURL;\n  }\n\n  return STRIPED_PLACEHOLDER_SVG;\n}\n", "import type {\n  MaskInputOptions,\n  SlimDOMOptions,\n  MaskTextFn,\n  MaskInputFn,\n  KeepIframeSrcFn,\n  ICanvas,\n  DialogAttributes,\n} from './types';\nimport { NodeType } from '@posthog/rrweb-types';\nimport type {\n  serializedNode,\n  serializedNodeWithId,\n  serializedElementNodeWithId,\n  elementNode,\n  attributes,\n  mediaAttributes,\n  DataURLOptions,\n} from '@posthog/rrweb-types';\nimport {\n  Mirror,\n  is2DCanvasBlank,\n  isElement,\n  isShadowRoot,\n  maskInputValue,\n  isNativeShadowDom,\n  stringifyStylesheet,\n  getInputType,\n  toLowerCase,\n  extractFileExtension,\n  checkDataURLSize,\n  recompressBase64Image,\n  absolutifyURLs,\n} from './utils';\nimport dom from '@posthog/rrweb-utils';\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\n\nexport const IGNORED_NODE = -2;\n\nexport function genId(): number {\n  return _id++;\n}\n\nfunction getValidTagName(element: HTMLElement): Lowercase<string> {\n  if (element instanceof HTMLFormElement) {\n    return 'form';\n  }\n\n  const processedTagName = toLowerCase(element.tagName);\n\n  if (tagNameRegex.test(processedTagName)) {\n    // if the tag name is odd and we cannot extract\n    // anything from the string, then we return a\n    // generic div\n    return 'div';\n  }\n\n  return processedTagName;\n}\n\nlet canvasService: HTMLCanvasElement | null;\nlet canvasCtx: CanvasRenderingContext2D | null;\n\n// eslint-disable-next-line no-control-regex\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/; // Don't use \\s, to avoid matching non-breaking space\n// eslint-disable-next-line no-control-regex\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\n\nfunction getAbsoluteSrcsetString(doc: Document, attributeValue: string) {\n  /*\n    run absoluteToDoc over every url in the srcset\n\n    this is adapted from https://github.com/albell/parse-srcset/\n    without the parsing of the descriptors (we return these as-is)\n    parce-srcset is in turn based on\n    https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute\n  */\n  if (attributeValue.trim() === '') {\n    return attributeValue;\n  }\n\n  let pos = 0;\n\n  function collectCharacters(regEx: RegExp) {\n    let chars: string;\n    const match = regEx.exec(attributeValue.substring(pos));\n    if (match) {\n      chars = match[0];\n      pos += chars.length;\n      return chars;\n    }\n    return '';\n  }\n\n  const output = [];\n  // eslint-disable-next-line no-constant-condition\n  while (true) {\n    collectCharacters(SRCSET_COMMAS_OR_SPACES);\n    if (pos >= attributeValue.length) {\n      break;\n    }\n    // don't split on commas within urls\n    let url = collectCharacters(SRCSET_NOT_SPACES);\n    if (url.slice(-1) === ',') {\n      // aside: according to spec more than one comma at the end is a parse error, but we ignore that\n      url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n      // the trailing comma splits the srcset, so the interpretion is that\n      // another url will follow, and the descriptor is empty\n      output.push(url);\n    } else {\n      let descriptorsStr = '';\n      url = absoluteToDoc(doc, url);\n      let inParens = false;\n      // eslint-disable-next-line no-constant-condition\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; // parse the next url\n          } else if (c === '(') {\n            inParens = true;\n          }\n        } else {\n          // in parenthesis; ignore commas\n          // (parenthesis may be supported by future additions to spec)\n          if (c === ')') {\n            inParens = false;\n          }\n        }\n        descriptorsStr += c;\n        pos += 1;\n      }\n    }\n  }\n  return output.join(', ');\n}\n\nconst cachedDocument = new WeakMap<Document, HTMLAnchorElement>();\n\nexport function absoluteToDoc(doc: Document, attributeValue: string): string {\n  if (!attributeValue || attributeValue.trim() === '') {\n    return attributeValue;\n  }\n\n  return getHref(doc, attributeValue);\n}\n\nfunction isSVGElement(el: Element): boolean {\n  return Boolean(el.tagName === 'svg' || (el as SVGElement).ownerSVGElement);\n}\n\nfunction getHref(doc: Document, customHref?: string) {\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  // note: using `new URL` is slower. See #1434 or https://jsbench.me/uqlud17rxo/1\n  a.setAttribute('href', customHref);\n  return a.href;\n}\n\nexport function transformAttribute(\n  doc: Document,\n  tagName: Lowercase<string>,\n  name: Lowercase<string>,\n  value: string | null,\n  element?: HTMLElement,\n  dataURLOptions?: DataURLOptions,\n): string | null {\n  if (!value) {\n    return value;\n  }\n\n  // relative path in attribute\n  if (\n    name === 'src' ||\n    (name === 'href' && !(tagName === 'use' && value[0] === '#'))\n  ) {\n    // href starts with a # is an id pointer for svg\n    const transformedValue = absoluteToDoc(doc, value);\n\n    if (tagName === 'img' && transformedValue.startsWith('data:') && element) {\n      const img = element as HTMLImageElement;\n\n      let processedDataURL = transformedValue;\n\n      if (dataURLOptions?.type || dataURLOptions?.quality !== undefined) {\n        processedDataURL = recompressBase64Image(\n          img,\n          transformedValue,\n          dataURLOptions.type,\n          dataURLOptions.quality,\n        );\n      }\n\n      if (dataURLOptions?.maxBase64ImageLength) {\n        processedDataURL = checkDataURLSize(\n          processedDataURL,\n          dataURLOptions.maxBase64ImageLength,\n        );\n      }\n\n      return processedDataURL;\n    }\n\n    return transformedValue;\n  } else if (name === 'xlink:href' && value[0] !== '#') {\n    // xlink:href starts with # is an id pointer\n    return absoluteToDoc(doc, value);\n  } else if (\n    name === 'background' &&\n    (tagName === 'table' || tagName === 'td' || tagName === 'th')\n  ) {\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\n  return value;\n}\n\nexport function ignoreAttribute(\n  tagName: string,\n  name: string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  _value: unknown,\n): boolean {\n  return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\n}\n\nexport function _isBlockedElement(\n  element: HTMLElement,\n  blockClass: string | RegExp,\n  blockSelector: string | null,\n): boolean {\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  }\n\n  return false;\n}\n\nexport function classMatchesRegex(\n  node: Node | null,\n  regex: RegExp,\n  checkAncestors: boolean,\n): boolean {\n  if (!node) return false;\n  if (node.nodeType !== node.ELEMENT_NODE) {\n    if (!checkAncestors) return false;\n    return classMatchesRegex(dom.parentNode(node), regex, checkAncestors);\n  }\n\n  for (let eIndex = (node as HTMLElement).classList.length; eIndex--; ) {\n    const className = (node as HTMLElement).classList[eIndex];\n    if (regex.test(className)) {\n      return true;\n    }\n  }\n  if (!checkAncestors) return false;\n  return classMatchesRegex(dom.parentNode(node), regex, checkAncestors);\n}\n\nexport function needMaskingText(\n  node: Node,\n  maskTextClass: string | RegExp,\n  maskTextSelector: string | null,\n  checkAncestors: boolean,\n): boolean {\n  let el: Element;\n  if (isElement(node)) {\n    el = node;\n    if (!dom.childNodes(el).length) {\n      // optimisation: we can avoid any of the below checks on leaf elements\n      // as masking is applied to child text nodes only\n      return false;\n    }\n  } else if (dom.parentElement(node) === null) {\n    // should warn? maybe a text node isn't attached to a parent node yet?\n    return false;\n  } else {\n    el = dom.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  }\n  return false;\n}\n\n// https://stackoverflow.com/a/36155560\nfunction onceIframeLoaded(\n  iframeEl: HTMLIFrameElement,\n  listener: () => unknown,\n  iframeLoadTimeout: number,\n) {\n  const win = iframeEl.contentWindow;\n  if (!win) {\n    return;\n  }\n  // document is loading\n  let fired = false;\n\n  let readyState: DocumentReadyState;\n  try {\n    readyState = win.document.readyState;\n  } catch (error) {\n    return;\n  }\n  if (readyState !== 'complete') {\n    const timer = setTimeout(() => {\n      if (!fired) {\n        listener();\n        fired = true;\n      }\n    }, iframeLoadTimeout);\n    iframeEl.addEventListener('load', () => {\n      clearTimeout(timer);\n      fired = true;\n      listener();\n    });\n    return;\n  }\n  // check blank frame for Chrome\n  const blankUrl = 'about:blank';\n  if (\n    win.location.href !== blankUrl ||\n    iframeEl.src === blankUrl ||\n    iframeEl.src === ''\n  ) {\n    // iframe was already loaded, make sure we wait to trigger the listener\n    // till _after_ the mutation that found this iframe has had time to process\n    setTimeout(listener, 0);\n\n    return iframeEl.addEventListener('load', listener); // keep listing for future loads\n  }\n  // use default listener\n  iframeEl.addEventListener('load', listener);\n}\n\nfunction onceStylesheetLoaded(\n  link: HTMLLinkElement,\n  listener: () => unknown,\n  styleSheetLoadTimeout: number,\n) {\n  let fired = false;\n  let styleSheetLoaded: StyleSheet | null;\n  try {\n    styleSheetLoaded = link.sheet;\n  } catch (error) {\n    return;\n  }\n\n  if (styleSheetLoaded) return;\n\n  const timer = setTimeout(() => {\n    if (!fired) {\n      listener();\n      fired = true;\n    }\n  }, styleSheetLoadTimeout);\n\n  link.addEventListener('load', () => {\n    clearTimeout(timer);\n    fired = true;\n    listener();\n  });\n}\n\nfunction serializeNode(\n  n: Node,\n  options: {\n    doc: Document;\n    mirror: Mirror;\n    blockClass: string | RegExp;\n    blockSelector: string | null;\n    needsMask: boolean;\n    inlineStylesheet: boolean;\n    maskInputOptions: MaskInputOptions;\n    maskTextFn: MaskTextFn | undefined;\n    maskInputFn: MaskInputFn | undefined;\n    dataURLOptions?: DataURLOptions;\n    inlineImages: boolean;\n    recordCanvas: boolean;\n    keepIframeSrcFn: KeepIframeSrcFn;\n    /**\n     * `newlyAddedElement: true` skips scrollTop and scrollLeft check\n     */\n    newlyAddedElement?: boolean;\n  },\n): serializedNode | false {\n  const {\n    doc,\n    mirror,\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  // Only record root id when document object is not the base document\n  const rootId = getRootId(doc, mirror);\n  switch (n.nodeType) {\n    case n.DOCUMENT_NODE:\n      if ((n as Document).compatMode !== 'CSS1Compat') {\n        return {\n          type: NodeType.Document,\n          childNodes: [],\n          compatMode: (n as Document).compatMode, // 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 as DocumentType).name,\n        publicId: (n as DocumentType).publicId,\n        systemId: (n as DocumentType).systemId,\n        rootId,\n      };\n    case n.ELEMENT_NODE:\n      return serializeElementNode(n as HTMLElement, {\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 as Text, {\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: dom.textContent(n as Comment) || '',\n        rootId,\n      };\n    default:\n      return false;\n  }\n}\n\nfunction getRootId(doc: Document, mirror: Mirror): number | undefined {\n  if (!mirror.hasNode(doc)) return undefined;\n  const docId = mirror.getId(doc);\n  return docId === 1 ? undefined : docId;\n}\n\nfunction serializeTextNode(\n  n: Text,\n  options: {\n    doc: Document;\n    needsMask: boolean;\n    maskTextFn: MaskTextFn | undefined;\n    rootId: number | undefined;\n  },\n): serializedNode {\n  const { needsMask, maskTextFn, rootId } = options;\n  // The parent node may not be a html element which has a tagName attribute.\n  // So just let it be undefined which is ok in this use case.\n  const parent = dom.parentNode(n);\n  const parentTagName = parent && (parent as HTMLElement).tagName;\n  let text = dom.textContent(n);\n  const isStyle = parentTagName === 'STYLE' ? true : undefined;\n  const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n  if (isStyle && text) {\n    try {\n      // try to read style sheet\n      if (n.nextSibling || n.previousSibling) {\n        // This is not the only child of the stylesheet.\n        // We can't read all of the sheet's .cssRules and expect them\n        // to _only_ include the current rule(s) added by the text node.\n        // So we'll be conservative and keep textContent as-is.\n      } else if ((parent as HTMLStyleElement).sheet?.cssRules) {\n        text = stringifyStylesheet((parent as HTMLStyleElement).sheet!);\n      }\n    } catch (err) {\n      console.warn(\n        `Cannot get CSS styles from text's parentNode. Error: ${err as string}`,\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\n      ? maskTextFn(text, dom.parentElement(n))\n      : text.replace(/[\\S]/g, '*');\n  }\n\n  return {\n    type: NodeType.Text,\n    textContent: text || '',\n    isStyle,\n    rootId,\n  };\n}\n\nfunction findStylesheet(doc: Document, href: string) {\n  return Array.from(doc.styleSheets).find((s) => s.href === href);\n}\n\n/**\n * in production, we've seen elements like\n * `<link type=\"text/css\" rel=\"stylesheet\" id=\"dark-mode-custom-link\"></link>`\n * while HTMLLinkElement suggests an href is always present\n * the w3c spec is less specific\n * and regardless we've seen at least one instance of this in the wild\n * let's be defensive and make sure this is typed as possibly undefined\n */\nfunction hrefFrom(n: unknown): string | undefined {\n  return (n as HTMLLinkElement).href;\n}\n\nfunction serializeElementNode(\n  n: HTMLElement,\n  options: {\n    doc: Document;\n    blockClass: string | RegExp;\n    blockSelector: string | null;\n    inlineStylesheet: boolean;\n    maskInputOptions: MaskInputOptions;\n    maskInputFn: MaskInputFn | undefined;\n    dataURLOptions?: DataURLOptions;\n    inlineImages: boolean;\n    recordCanvas: boolean;\n    keepIframeSrcFn: KeepIframeSrcFn;\n    /**\n     * `newlyAddedElement: true` skips scrollTop and scrollLeft check\n     */\n    newlyAddedElement?: boolean;\n    rootId: number | undefined;\n  },\n): serializedNode | false {\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: 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  // remote css\n  if (tagName === 'link' && inlineStylesheet) {\n    //TODO: maybe replace this `.styleSheets` with original one\n    const href: string | undefined = hrefFrom(n);\n    if (href) {\n      let 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      let cssText: string | null = 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  }\n  // dynamic stylesheet\n  if (\n    tagName === 'style' &&\n    (n as HTMLStyleElement).sheet &&\n    // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n    !(n.innerText || dom.textContent(n) || '').trim().length\n  ) {\n    const cssText = stringifyStylesheet(\n      (n as HTMLStyleElement).sheet as CSSStyleSheet,\n    );\n    if (cssText) {\n      attributes._cssText = cssText;\n    }\n  }\n  // form fields\n  if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {\n    const value = (n as HTMLInputElement | HTMLTextAreaElement).value;\n    const checked = (n as HTMLInputElement).checked;\n    if (\n      attributes.type !== 'radio' &&\n      attributes.type !== 'checkbox' &&\n      attributes.type !== 'submit' &&\n      attributes.type !== 'button' &&\n      value\n    ) {\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 as HTMLOptionElement).selected && !maskInputOptions['select']) {\n      attributes.selected = true;\n    } else {\n      // ignore the html attribute (which corresponds to DOM (n as HTMLOptionElement).defaultSelected)\n      // if it's already been changed\n      delete attributes.selected;\n    }\n  }\n\n  if (tagName === 'dialog' && (n as HTMLDialogElement).open) {\n    // register what type of dialog is this\n    // `modal` or `non-modal`\n    // this is used to trigger `showModal()` or `show()` on replay (outside of rrweb-snapshot, in rrweb)\n    try {\n      (attributes as DialogAttributes).rr_open_mode = n.matches('dialog:modal')\n        ? 'modal'\n        : 'non-modal';\n    } catch {\n      // likely this is safari not able to deal with the `:modal` selector\n      // we can't detect whether the dialog is modal or non-modal open, so have to guess\n      // hopefully this is only safari 15.4 and 15.5\n      attributes.rr_open_mode = 'modal';\n      attributes.ph_rr_could_not_detect_modal = true;\n    }\n  }\n\n  // canvas image data\n  if (tagName === 'canvas' && recordCanvas) {\n    if ((n as ICanvas).__context === '2d') {\n      // only record this on 2d canvas\n      if (!is2DCanvasBlank(n as HTMLCanvasElement)) {\n        attributes.rr_dataURL = (n as HTMLCanvasElement).toDataURL(\n          dataURLOptions.type,\n          dataURLOptions.quality,\n        );\n      }\n    } else if (!('__context' in n)) {\n      // context is unknown, better not call getContext to trigger it\n      const canvasDataURL = (n as HTMLCanvasElement).toDataURL(\n        dataURLOptions.type,\n        dataURLOptions.quality,\n      );\n\n      // create blank canvas of same dimensions\n      const blankCanvas = doc.createElement('canvas');\n      blankCanvas.width = (n as HTMLCanvasElement).width;\n      blankCanvas.height = (n as HTMLCanvasElement).height;\n      const blankCanvasDataURL = blankCanvas.toDataURL(\n        dataURLOptions.type,\n        dataURLOptions.quality,\n      );\n\n      // no need to save dataURL if it's the same as blank canvas\n      if (canvasDataURL !== blankCanvasDataURL) {\n        attributes.rr_dataURL = canvasDataURL;\n      }\n    }\n  }\n  // save image offline\n  if (tagName === 'img' && inlineImages) {\n    if (!canvasService) {\n      canvasService = doc.createElement('canvas');\n      canvasCtx = canvasService.getContext('2d');\n    }\n    const image = n as HTMLImageElement;\n    const imageSrc: string =\n      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(); // too early due to image reload\n          else image.addEventListener('load', recordInlineImage);\n          return;\n        } else {\n          console.warn(\n            `Cannot inline img src=${imageSrc}! Error: ${err as string}`,\n          );\n        }\n      }\n      if (image.crossOrigin === 'anonymous') {\n        priorCrossOrigin\n          ? (attributes.crossOrigin = priorCrossOrigin)\n          : image.removeAttribute('crossorigin');\n      }\n    };\n    // The image content may not have finished loading yet.\n    if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n    else image.addEventListener('load', recordInlineImage);\n  }\n  // media elements\n  if (tagName === 'audio' || tagName === 'video') {\n    const mediaAttributes = attributes as mediaAttributes;\n    mediaAttributes.rr_mediaState = (n as HTMLMediaElement).paused\n      ? 'paused'\n      : 'played';\n    mediaAttributes.rr_mediaCurrentTime = (n as HTMLMediaElement).currentTime;\n    mediaAttributes.rr_mediaPlaybackRate = (n as HTMLMediaElement).playbackRate;\n    mediaAttributes.rr_mediaMuted = (n as HTMLMediaElement).muted;\n    mediaAttributes.rr_mediaLoop = (n as HTMLMediaElement).loop;\n    mediaAttributes.rr_mediaVolume = (n as HTMLMediaElement).volume;\n  }\n  // Scroll\n  if (!newlyAddedElement) {\n    // `scrollTop` and `scrollLeft` are expensive calls because they trigger reflow.\n    // Since `scrollTop` & `scrollLeft` are always 0 when an element is added to the DOM.\n    // And scrolls also get picked up by rrweb's ScrollObserver\n    // So we can safely skip the `scrollTop/Left` calls for newly added elements\n    if (n.scrollLeft) {\n      attributes.rr_scrollLeft = n.scrollLeft;\n    }\n    if (n.scrollTop) {\n      attributes.rr_scrollTop = n.scrollTop;\n    }\n  }\n  // block element\n  if (needBlock) {\n    const { width, height, left, top } = n.getBoundingClientRect();\n    attributes = {\n      class: attributes.class,\n      rr_width: `${width}px`,\n      rr_height: `${height}px`,\n      rr_left: `${Math.floor(left + (doc.defaultView?.scrollX || 0))}px`,\n      rr_top: `${Math.floor(top + (doc.defaultView?.scrollY || 0))}px`,\n    };\n  }\n  // iframe\n  if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src as string)) {\n    if (!(n as HTMLIFrameElement).contentDocument) {\n      // we can't record it directly as we can't see into it\n      // preserve the src attribute so a decision can be taken at replay time\n      attributes.rr_src = attributes.src;\n    }\n    delete attributes.src; // prevent auto loading\n  }\n\n  let isCustomElement: true | undefined;\n  try {\n    if (customElements.get(tagName)) isCustomElement = true;\n  } catch (e) {\n    // In case old browsers don't support customElements\n  }\n\n  return {\n    type: NodeType.Element,\n    tagName,\n    attributes,\n    childNodes: [],\n    isSVG: isSVGElement(n as Element) || undefined,\n    needBlock,\n    rootId,\n    isCustom: isCustomElement,\n  };\n}\n\nfunction lowerIfExists(\n  maybeAttr: string | number | boolean | undefined | null,\n): string {\n  if (maybeAttr === undefined || maybeAttr === null) {\n    return '';\n  } else {\n    return (maybeAttr as string).toLowerCase();\n  }\n}\n\nfunction slimDOMExcluded(\n  sn: serializedNode,\n  slimDOMOptions: SlimDOMOptions,\n): boolean {\n  if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n    // TODO: convert IE conditional comments to real nodes\n    return true;\n  } else if (sn.type === NodeType.Element) {\n    if (\n      slimDOMOptions.script &&\n      // script tag\n      (sn.tagName === 'script' ||\n        // (module)preload link\n        (sn.tagName === 'link' &&\n          ((sn.attributes.rel === 'preload' && sn.attributes.as === 'script') ||\n            sn.attributes.rel === 'modulepreload')) ||\n        // prefetch link\n        (sn.tagName === 'link' &&\n          sn.attributes.rel === 'prefetch' &&\n          typeof sn.attributes.href === 'string' &&\n          extractFileExtension(sn.attributes.href) === 'js'))\n    ) {\n      return true;\n    } else if (\n      slimDOMOptions.headFavicon &&\n      ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n        (sn.tagName === 'meta' &&\n          (lowerIfExists(sn.attributes.name).match(\n            /^msapplication-tile(image|color)$/,\n          ) ||\n            lowerIfExists(sn.attributes.name) === 'application-name' ||\n            ['icon', 'apple-touch-icon', 'shortcut icon'].includes(\n              lowerIfExists(sn.attributes.rel),\n            ))))\n    ) {\n      return true;\n    } else if (sn.tagName === 'meta') {\n      if (\n        slimDOMOptions.headMetaDescKeywords &&\n        lowerIfExists(sn.attributes.name).match(/^description|keywords$/)\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaSocial &&\n        (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n          lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n          lowerIfExists(sn.attributes.name) === 'pinterest')\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaRobots &&\n        ['robots', 'googlebot', 'bingbot'].includes(\n          lowerIfExists(sn.attributes.name),\n        )\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaHttpEquiv &&\n        sn.attributes['http-equiv'] !== undefined\n      ) {\n        // e.g. X-UA-Compatible, Content-Type, Content-Language,\n        // cache-control, X-Translated-By\n        return true;\n      } else if (\n        slimDOMOptions.headMetaAuthorship &&\n        (['author', 'generator', 'framework', 'publisher', 'progid'].includes(\n          lowerIfExists(sn.attributes.name),\n        ) ||\n          lowerIfExists(sn.attributes.property).match(/^article:/) ||\n          lowerIfExists(sn.attributes.property).match(/^product:/))\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaVerification &&\n        [\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      ) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nexport const DEFAULT_MAX_DEPTH = 50;\n\nlet _maxDepthWarned = false;\nlet _maxDepthReached = false;\n\nexport function wasMaxDepthReached(): boolean {\n  return _maxDepthReached;\n}\n\nexport function resetMaxDepthState(): void {\n  _maxDepthReached = false;\n  _maxDepthWarned = false;\n}\n\nexport function serializeNodeWithId(\n  n: Node,\n  options: {\n    doc: Document;\n    mirror: Mirror;\n    blockClass: string | RegExp;\n    blockSelector: string | null;\n    maskTextClass: string | RegExp;\n    maskTextSelector: string | null;\n    skipChild: boolean;\n    inlineStylesheet: boolean;\n    newlyAddedElement?: boolean;\n    maskInputOptions?: MaskInputOptions;\n    needsMask?: boolean;\n    maskTextFn: MaskTextFn | undefined;\n    maskInputFn: MaskInputFn | undefined;\n    slimDOMOptions: SlimDOMOptions;\n    dataURLOptions?: DataURLOptions;\n    keepIframeSrcFn?: KeepIframeSrcFn;\n    inlineImages?: boolean;\n    recordCanvas?: boolean;\n    preserveWhiteSpace?: boolean;\n    onSerialize?: (n: Node) => unknown;\n    onIframeLoad?: (\n      iframeNode: HTMLIFrameElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    iframeLoadTimeout?: number;\n    onStylesheetLoad?: (\n      linkNode: HTMLLinkElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    stylesheetLoadTimeout?: number;\n    depth?: number;\n    maxDepth?: number;\n    onMaxDepthReached?: () => void;\n  },\n): serializedNodeWithId | null {\n  const {\n    doc,\n    mirror,\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 = 5000,\n    onStylesheetLoad,\n    stylesheetLoadTimeout = 5000,\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\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}. ` +\n          `Children beyond this depth will not be recorded. ` +\n          `This may indicate deeply nested DOM structures.`,\n      );\n    }\n    return null;\n  }\n\n  if (!needsMask) {\n    // perf: if needsMask = true, children won't also need to check\n    const checkAncestors = needsMask === undefined; // if false, we've already checked ancestors\n    needsMask = needMaskingText(\n      n as Element,\n      maskTextClass,\n      maskTextSelector,\n      checkAncestors,\n    );\n  }\n\n  const _serializedNode = serializeNode(n, {\n    doc,\n    mirror,\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    // TODO: dev only\n    console.warn(n, 'not serialized');\n    return null;\n  }\n\n  let id: number | undefined;\n  if (mirror.hasNode(n)) {\n    // Reuse the previous id\n    id = mirror.getId(n);\n  } else if (\n    slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n    (!preserveWhiteSpace &&\n      _serializedNode.type === NodeType.Text &&\n      !_serializedNode.isStyle &&\n      !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)\n  ) {\n    id = IGNORED_NODE;\n  } else {\n    id = genId();\n  }\n\n  const serializedNode = Object.assign(_serializedNode, { id });\n  // add IGNORED_NODE to mirror to track nextSiblings\n  mirror.add(n, serializedNode);\n\n  if (id === IGNORED_NODE) {\n    return null; // slimDOM\n  }\n\n  if (onSerialize) {\n    onSerialize(n);\n  }\n  let recordChild = !skipChild;\n  if (serializedNode.type === NodeType.Element) {\n    recordChild = recordChild && !serializedNode.needBlock;\n    // this property was not needed in replay side\n    delete serializedNode.needBlock;\n    const shadowRootEl = dom.shadowRoot(n);\n    if (shadowRootEl && isNativeShadowDom(shadowRootEl))\n      serializedNode.isShadowHost = true;\n  }\n  if (\n    (serializedNode.type === NodeType.Document ||\n      serializedNode.type === NodeType.Element) &&\n    recordChild\n  ) {\n    if (\n      slimDOMOptions.headWhitespace &&\n      serializedNode.type === NodeType.Element &&\n      serializedNode.tagName === 'head'\n      // would impede performance: || getComputedStyle(n)['white-space'] === 'normal'\n    ) {\n      preserveWhiteSpace = false;\n    }\n    const bypassOptions = {\n      doc,\n      mirror,\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      onStylesheetLoad,\n      stylesheetLoadTimeout,\n      keepIframeSrcFn,\n      depth: depth + 1,\n      maxDepth,\n    };\n\n    if (\n      serializedNode.type === NodeType.Element &&\n      serializedNode.tagName === 'textarea' &&\n      (serializedNode as elementNode).attributes.value !== undefined\n    ) {\n      // value parameter in DOM reflects the correct value, so ignore childNode\n    } else {\n      for (const childN of Array.from(dom.childNodes(n))) {\n        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n        if (serializedChildNode) {\n          serializedNode.childNodes.push(serializedChildNode);\n        }\n      }\n    }\n\n    let shadowRootEl: ShadowRoot | null = null;\n    if (isElement(n) && (shadowRootEl = dom.shadowRoot(n))) {\n      for (const childN of Array.from(dom.childNodes(shadowRootEl))) {\n        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n        if (serializedChildNode) {\n          isNativeShadowDom(shadowRootEl) &&\n            (serializedChildNode.isShadow = true);\n          serializedNode.childNodes.push(serializedChildNode);\n        }\n      }\n    }\n  }\n\n  const parent = dom.parentNode(n);\n  if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {\n    serializedNode.isShadow = true;\n  }\n\n  if (\n    serializedNode.type === NodeType.Element &&\n    serializedNode.tagName === 'iframe'\n  ) {\n    onceIframeLoaded(\n      n as HTMLIFrameElement,\n      () => {\n        const iframeDoc = (n as HTMLIFrameElement).contentDocument;\n        if (iframeDoc && onIframeLoad) {\n          const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n            doc: iframeDoc,\n            mirror,\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: depth + 1,\n            maxDepth,\n          });\n\n          if (serializedIframeNode) {\n            onIframeLoad(\n              n as HTMLIFrameElement,\n              serializedIframeNode as serializedElementNodeWithId,\n            );\n          }\n        }\n      },\n      iframeLoadTimeout,\n    );\n  }\n\n  // <link rel=stylesheet href=...>\n  if (\n    serializedNode.type === NodeType.Element &&\n    serializedNode.tagName === 'link' &&\n    typeof serializedNode.attributes.rel === 'string' &&\n    (serializedNode.attributes.rel === 'stylesheet' ||\n      (serializedNode.attributes.rel === 'preload' &&\n        typeof serializedNode.attributes.href === 'string' &&\n        extractFileExtension(serializedNode.attributes.href) === 'css'))\n  ) {\n    onceStylesheetLoaded(\n      n as HTMLLinkElement,\n      () => {\n        if (onStylesheetLoad) {\n          const serializedLinkNode = serializeNodeWithId(n, {\n            doc,\n            mirror,\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\n          if (serializedLinkNode) {\n            onStylesheetLoad(\n              n as HTMLLinkElement,\n              serializedLinkNode as serializedElementNodeWithId,\n            );\n          }\n        }\n      },\n      stylesheetLoadTimeout,\n    );\n  }\n\n  return serializedNode;\n}\n\nexport function slimDOMDefaults(\n  slimDOM: 'all' | boolean | SlimDOMOptions,\n): SlimDOMOptions {\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}\n\nfunction snapshot(\n  n: Document,\n  options?: {\n    mirror?: Mirror;\n    blockClass?: string | RegExp;\n    blockSelector?: string | null;\n    maskTextClass?: string | RegExp;\n    maskTextSelector?: string | null;\n    inlineStylesheet?: boolean;\n    maskAllInputs?: boolean | MaskInputOptions;\n    maskTextFn?: MaskTextFn;\n    maskInputFn?: MaskInputFn;\n    slimDOM?: 'all' | boolean | SlimDOMOptions;\n    dataURLOptions?: DataURLOptions;\n    inlineImages?: boolean;\n    recordCanvas?: boolean;\n    preserveWhiteSpace?: boolean;\n    onSerialize?: (n: Node) => unknown;\n    onIframeLoad?: (\n      iframeNode: HTMLIFrameElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    iframeLoadTimeout?: number;\n    onStylesheetLoad?: (\n      linkNode: HTMLLinkElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    stylesheetLoadTimeout?: number;\n    keepIframeSrcFn?: KeepIframeSrcFn;\n    maxDepth?: number;\n  },\n): serializedNodeWithId | null {\n  const {\n    mirror = 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    onStylesheetLoad,\n    stylesheetLoadTimeout,\n    keepIframeSrcFn = () => false,\n    maxDepth,\n  } = options || {};\n  const maskInputOptions: MaskInputOptions =\n    maskAllInputs === true\n      ? {\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        }\n      : maskAllInputs === false\n      ? {\n          password: true,\n        }\n      : maskAllInputs;\n  const slimDOMOptions: SlimDOMOptions = slimDOMDefaults(slimDOM);\n  return serializeNodeWithId(n, {\n    doc: n,\n    mirror,\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    onStylesheetLoad,\n    stylesheetLoadTimeout,\n    keepIframeSrcFn,\n    newlyAddedElement: false,\n    maxDepth,\n  });\n}\n\nexport function visitSnapshot(\n  node: serializedNodeWithId,\n  onVisit: (node: serializedNodeWithId) => unknown,\n) {\n  function walk(current: serializedNodeWithId) {\n    onVisit(current);\n    if (\n      current.type === NodeType.Document ||\n      current.type === NodeType.Element\n    ) {\n      current.childNodes.forEach(walk);\n    }\n  }\n\n  walk(node);\n}\n\nexport function cleanupSnapshot() {\n  // allow a new recording to start numbering nodes from scratch\n  _id = 1;\n}\n\nexport default snapshot;\n", "import { NodeType as RRNodeType } from '@posthog/rrweb-types';\nimport { parseCSSText, camelize, toCSSText } from './style';\nexport interface IRRNode {\n  parentElement: IRRNode | null;\n  parentNode: IRRNode | null;\n  ownerDocument: IRRDocument;\n  readonly childNodes: IRRNode[];\n  readonly ELEMENT_NODE: number;\n  readonly TEXT_NODE: number;\n  // corresponding nodeType value of standard HTML Node\n  readonly nodeType: number;\n  readonly nodeName: string; // https://dom.spec.whatwg.org/#dom-node-nodename\n  readonly RRNodeType: RRNodeType;\n\n  firstChild: IRRNode | null;\n\n  lastChild: IRRNode | null;\n\n  previousSibling: IRRNode | null;\n\n  nextSibling: IRRNode | null;\n\n  // If the node is a document or a doctype, textContent returns null.\n  textContent: string | null;\n\n  contains(node: IRRNode): boolean;\n\n  appendChild(newChild: IRRNode): IRRNode;\n\n  insertBefore(newChild: IRRNode, refChild: IRRNode | null): IRRNode;\n\n  removeChild(node: IRRNode): IRRNode;\n\n  toString(): string;\n}\nexport interface IRRDocument extends IRRNode {\n  documentElement: IRRElement | null;\n\n  body: IRRElement | null;\n\n  head: IRRElement | null;\n\n  implementation: IRRDocument;\n\n  firstElementChild: IRRElement | null;\n\n  readonly nodeName: '#document';\n\n  compatMode: 'BackCompat' | 'CSS1Compat';\n\n  createDocument(\n    _namespace: string | null,\n    _qualifiedName: string | null,\n    _doctype?: DocumentType | null,\n  ): IRRDocument;\n\n  createDocumentType(\n    qualifiedName: string,\n    publicId: string,\n    systemId: string,\n  ): IRRDocumentType;\n\n  createElement(tagName: string): IRRElement;\n\n  createElementNS(_namespaceURI: string, qualifiedName: string): IRRElement;\n\n  createTextNode(data: string): IRRText;\n\n  createComment(data: string): IRRComment;\n\n  createCDATASection(data: string): IRRCDATASection;\n\n  open(): void;\n\n  close(): void;\n\n  write(content: string): void;\n}\nexport interface IRRElement extends IRRNode {\n  tagName: string;\n  attributes: Record<string, string>;\n  shadowRoot: IRRElement | null;\n  scrollLeft?: number;\n  scrollTop?: number;\n  id: string;\n  className: string;\n  classList: ClassList;\n  style: CSSStyleDeclaration;\n\n  attachShadow(init: ShadowRootInit): IRRElement;\n\n  getAttribute(name: string): string | null;\n\n  setAttribute(name: string, attribute: string): void;\n\n  setAttributeNS(\n    namespace: string | null,\n    qualifiedName: string,\n    value: string,\n  ): void;\n\n  removeAttribute(name: string): void;\n\n  dispatchEvent(event: Event): boolean;\n}\nexport interface IRRDocumentType extends IRRNode {\n  readonly name: string;\n  readonly publicId: string;\n  readonly systemId: string;\n}\nexport interface IRRText extends IRRNode {\n  readonly nodeName: '#text';\n  data: string;\n}\nexport interface IRRComment extends IRRNode {\n  readonly nodeName: '#comment';\n  data: string;\n}\nexport interface IRRCDATASection extends IRRNode {\n  readonly nodeName: '#cdata-section';\n  data: string;\n}\n\n/**\n * This is designed as an abstract class so it should never be instantiated.\n */\nexport abstract class BaseRRNode implements IRRNode {\n  public parentElement: IRRNode | null = null;\n  public parentNode: IRRNode | null = null;\n  public ownerDocument!: IRRDocument;\n  public firstChild: IRRNode | null = null;\n  public lastChild: IRRNode | null = null;\n  public previousSibling: IRRNode | null = null;\n  public nextSibling: IRRNode | null = null;\n\n  public abstract textContent: string | null;\n\n  public readonly ELEMENT_NODE: number = NodeType.ELEMENT_NODE;\n  public readonly TEXT_NODE: number = NodeType.TEXT_NODE;\n  // corresponding nodeType value of standard HTML Node\n  public readonly nodeType!: number;\n  public readonly nodeName!: string;\n  public readonly RRNodeType!: RRNodeType;\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n  constructor(..._args: any[]) {\n    //\n  }\n\n  public get childNodes(): IRRNode[] {\n    const childNodes: IRRNode[] = [];\n    let childIterator: IRRNode | null = this.firstChild;\n    while (childIterator) {\n      childNodes.push(childIterator);\n      childIterator = childIterator.nextSibling;\n    }\n    return childNodes;\n  }\n\n  public contains(node: IRRNode) {\n    if (!(node instanceof BaseRRNode)) return false;\n    else if (node.ownerDocument !== this.ownerDocument) return false;\n    else if (node === this) return true;\n\n    while (node.parentNode) {\n      if (node.parentNode === this) return true;\n      node = node.parentNode;\n    }\n    return false;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public appendChild(_newChild: IRRNode): IRRNode {\n    throw new Error(\n      `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`,\n    );\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public insertBefore(_newChild: IRRNode, _refChild: IRRNode | null): IRRNode {\n    throw new Error(\n      `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`,\n    );\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public removeChild(_node: IRRNode): IRRNode {\n    throw new Error(\n      `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`,\n    );\n  }\n\n  public toString(): string {\n    return 'RRNode';\n  }\n}\n\nexport class BaseRRDocument extends BaseRRNode implements IRRDocument {\n  public readonly nodeType: number = NodeType.DOCUMENT_NODE;\n  public readonly nodeName = '#document' as const;\n  public readonly compatMode: 'BackCompat' | 'CSS1Compat' = 'CSS1Compat';\n  public readonly RRNodeType = RRNodeType.Document;\n  public textContent: string | null = null;\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor(...args: any[]) {\n    super(args);\n    this.ownerDocument = this;\n  }\n\n  public get documentElement(): IRRElement | null {\n    return (\n      (this.childNodes.find(\n        (node) =>\n          node.RRNodeType === RRNodeType.Element &&\n          (node as IRRElement).tagName === 'HTML',\n      ) as IRRElement) || null\n    );\n  }\n\n  public get body(): IRRElement | null {\n    return (\n      (this.documentElement?.childNodes.find(\n        (node) =>\n          node.RRNodeType === RRNodeType.Element &&\n          (node as IRRElement).tagName === 'BODY',\n      ) as IRRElement) || null\n    );\n  }\n\n  public get head(): IRRElement | null {\n    return (\n      (this.documentElement?.childNodes.find(\n        (node) =>\n          node.RRNodeType === RRNodeType.Element &&\n          (node as IRRElement).tagName === 'HEAD',\n      ) as IRRElement) || null\n    );\n  }\n\n  public get implementation(): IRRDocument {\n    return this;\n  }\n\n  public get firstElementChild(): IRRElement | null {\n    return this.documentElement;\n  }\n\n  public appendChild(newChild: IRRNode): IRRNode {\n    const nodeType = newChild.RRNodeType;\n    if (\n      nodeType === RRNodeType.Element ||\n      nodeType === RRNodeType.DocumentType\n    ) {\n      if (this.childNodes.some((s) => s.RRNodeType === nodeType)) {\n        throw new Error(\n          `RRDomException: Failed to execute 'appendChild' on 'RRNode': Only one ${\n            nodeType === RRNodeType.Element ? 'RRElement' : 'RRDoctype'\n          } on RRDocument allowed.`,\n        );\n      }\n    }\n\n    const child = appendChild(this, newChild);\n    child.parentElement = null;\n    return child;\n  }\n\n  public insertBefore(newChild: IRRNode, refChild: IRRNode | null): IRRNode {\n    const nodeType = newChild.RRNodeType;\n    if (\n      nodeType === RRNodeType.Element ||\n      nodeType === RRNodeType.DocumentType\n    ) {\n      if (this.childNodes.some((s) => s.RRNodeType === nodeType)) {\n        throw new Error(\n          `RRDomException: Failed to execute 'insertBefore' on 'RRNode': Only one ${\n            nodeType === RRNodeType.Element ? 'RRElement' : 'RRDoctype'\n          } on RRDocument allowed.`,\n        );\n      }\n    }\n\n    const child = insertBefore(this, newChild, refChild);\n    child.parentElement = null;\n    return child;\n  }\n\n  public removeChild(node: IRRNode): IRRNode {\n    return removeChild(this, node);\n  }\n\n  public open() {\n    this.firstChild = null;\n    this.lastChild = null;\n  }\n\n  public close() {\n    //\n  }\n\n  /**\n   * Adhoc implementation for setting xhtml namespace in rebuilt.ts (rrweb-snapshot).\n   * There are two lines used this function:\n   * 1. doc.write('\\<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"\"\\>')\n   * 2. doc.write('\\<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"\"\\>')\n   */\n  public write(content: string) {\n    let publicId;\n    if (\n      content ===\n      '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"\">'\n    )\n      publicId = '-//W3C//DTD XHTML 1.0 Transitional//EN';\n    else if (\n      content ===\n      '<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"\">'\n    )\n      publicId = '-//W3C//DTD HTML 4.0 Transitional//EN';\n    if (publicId) {\n      const doctype = this.createDocumentType('html', publicId, '');\n      this.open();\n      this.appendChild(doctype);\n    }\n  }\n\n  createDocument(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _namespace: string | null,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _qualifiedName: string | null,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _doctype?: DocumentType | null,\n  ): IRRDocument {\n    return new BaseRRDocument();\n  }\n\n  createDocumentType(\n    qualifiedName: string,\n    publicId: string,\n    systemId: string,\n  ): IRRDocumentType {\n    const doctype = new BaseRRDocumentType(qualifiedName, publicId, systemId);\n    doctype.ownerDocument = this;\n    return doctype;\n  }\n\n  createElement(tagName: string): IRRElement {\n    const element = new BaseRRElement(tagName);\n    element.ownerDocument = this;\n    return element;\n  }\n\n  createElementNS(_namespaceURI: string, qualifiedName: string): IRRElement {\n    return this.createElement(qualifiedName);\n  }\n\n  createTextNode(data: string): IRRText {\n    const text = new BaseRRText(data);\n    text.ownerDocument = this;\n    return text;\n  }\n\n  createComment(data: string): IRRComment {\n    const comment = new BaseRRComment(data);\n    comment.ownerDocument = this;\n    return comment;\n  }\n\n  createCDATASection(data: string): IRRCDATASection {\n    const CDATASection = new BaseRRCDATASection(data);\n    CDATASection.ownerDocument = this;\n    return CDATASection;\n  }\n\n  toString() {\n    return 'RRDocument';\n  }\n}\n\nexport class BaseRRDocumentType extends BaseRRNode implements IRRDocumentType {\n  public readonly nodeType: number = NodeType.DOCUMENT_TYPE_NODE;\n  public readonly RRNodeType = RRNodeType.DocumentType;\n  declare readonly nodeName: string;\n  public readonly name: string;\n  public readonly publicId: string;\n  public readonly systemId: string;\n  public textContent: string | null = null;\n\n  constructor(qualifiedName: string, publicId: string, systemId: string) {\n    super();\n    this.name = qualifiedName;\n    this.publicId = publicId;\n    this.systemId = systemId;\n    this.nodeName = qualifiedName;\n  }\n\n  toString() {\n    return 'RRDocumentType';\n  }\n}\n\nexport class BaseRRElement extends BaseRRNode implements IRRElement {\n  public readonly nodeType: number = NodeType.ELEMENT_NODE;\n  public readonly RRNodeType = RRNodeType.Element;\n  declare readonly nodeName: string;\n  public tagName: string;\n  public attributes: Record<string, string> = {};\n  public shadowRoot: IRRElement | null = null;\n  public scrollLeft?: number;\n  public scrollTop?: number;\n\n  constructor(tagName: string) {\n    super();\n    this.tagName = tagName.toUpperCase();\n    this.nodeName = tagName.toUpperCase();\n  }\n\n  public get textContent(): string {\n    let result = '';\n    this.childNodes.forEach((node) => (result += node.textContent));\n    return result;\n  }\n\n  public set textContent(textContent: string) {\n    this.firstChild = null;\n    this.lastChild = null;\n    this.appendChild(this.ownerDocument.createTextNode(textContent));\n  }\n\n  public get classList(): ClassList {\n    return new ClassList(\n      this.attributes.class as string | undefined,\n      (newClassName) => {\n        this.attributes.class = newClassName;\n      },\n    );\n  }\n\n  public get id() {\n    return this.attributes.id || '';\n  }\n\n  public get className() {\n    return this.attributes.class || '';\n  }\n\n  public get style() {\n    const style = (\n      this.attributes.style ? parseCSSText(this.attributes.style) : {}\n    ) as CSSStyleDeclaration;\n    const hyphenateRE = /\\B([A-Z])/g;\n    style.setProperty = (\n      name: string,\n      value: string | null,\n      priority?: string | null,\n    ) => {\n      if (hyphenateRE.test(name)) return;\n      const normalizedName = camelize(name);\n      if (!value) delete style[normalizedName];\n      else style[normalizedName] = value;\n      if (priority === 'important') style[normalizedName] += ' !important';\n      this.attributes.style = toCSSText(style);\n    };\n    style.removeProperty = (name: string) => {\n      if (hyphenateRE.test(name)) return '';\n      const normalizedName = camelize(name);\n      const value = style[normalizedName] || '';\n      delete style[normalizedName];\n      this.attributes.style = toCSSText(style);\n      return value;\n    };\n    return style;\n  }\n\n  public getAttribute(name: string): string | null {\n    if (this.attributes[name] === undefined) return null;\n    return this.attributes[name];\n  }\n\n  public setAttribute(name: string, attribute: string) {\n    this.attributes[name] = attribute;\n  }\n\n  public setAttributeNS(\n    _namespace: string | null,\n    qualifiedName: string,\n    value: string,\n  ): void {\n    this.setAttribute(qualifiedName, value);\n  }\n\n  public removeAttribute(name: string) {\n    delete this.attributes[name];\n  }\n\n  public appendChild(newChild: IRRNode): IRRNode {\n    return appendChild(this, newChild);\n  }\n\n  public insertBefore(newChild: IRRNode, refChild: IRRNode | null): IRRNode {\n    return insertBefore(this, newChild, refChild);\n  }\n\n  public removeChild(node: IRRNode): IRRNode {\n    return removeChild(this, node);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public attachShadow(_init: ShadowRootInit): IRRElement {\n    const shadowRoot = this.ownerDocument.createElement('SHADOWROOT');\n    this.shadowRoot = shadowRoot;\n    return shadowRoot;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public dispatchEvent(_event: Event) {\n    return true;\n  }\n\n  toString() {\n    let attributeString = '';\n    for (const attribute in this.attributes) {\n      attributeString += `${attribute}=\"${this.attributes[attribute]}\" `;\n    }\n    return `${this.tagName} ${attributeString}`;\n  }\n}\n\nexport class BaseRRMediaElement extends BaseRRElement {\n  public currentTime?: number;\n  public volume?: number;\n  public paused?: boolean;\n  public muted?: boolean;\n  public playbackRate?: number;\n  public loop?: boolean;\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  attachShadow(_init: ShadowRootInit): IRRElement {\n    throw new Error(\n      `RRDomException: Failed to execute 'attachShadow' on 'RRElement': This RRElement does not support attachShadow`,\n    );\n  }\n  public play() {\n    this.paused = false;\n  }\n  public pause() {\n    this.paused = true;\n  }\n}\n\nexport class BaseRRDialogElement extends BaseRRElement {\n  public readonly tagName = 'DIALOG' as const;\n  public readonly nodeName = 'DIALOG' as const;\n\n  get isModal() {\n    return this.getAttribute('rr_open_mode') === 'modal';\n  }\n  get open() {\n    return this.getAttribute('open') !== null;\n  }\n  public close() {\n    this.removeAttribute('open');\n    this.removeAttribute('rr_open_mode');\n  }\n  public show() {\n    this.setAttribute('open', '');\n    this.setAttribute('rr_open_mode', 'non-modal');\n  }\n  public showModal() {\n    this.setAttribute('open', '');\n    this.setAttribute('rr_open_mode', 'modal');\n  }\n}\n\nexport class BaseRRText extends BaseRRNode implements IRRText {\n  public readonly nodeType: number = NodeType.TEXT_NODE;\n  public readonly nodeName = '#text' as const;\n  public readonly RRNodeType = RRNodeType.Text;\n  public data: string;\n\n  constructor(data: string) {\n    super();\n    this.data = data;\n  }\n\n  public get textContent(): string {\n    return this.data;\n  }\n\n  public set textContent(textContent: string) {\n    this.data = textContent;\n  }\n\n  toString() {\n    return `RRText text=${JSON.stringify(this.data)}`;\n  }\n}\n\nexport class BaseRRComment extends BaseRRNode implements IRRComment {\n  public readonly nodeType: number = NodeType.COMMENT_NODE;\n  public readonly nodeName = '#comment' as const;\n  public readonly RRNodeType = RRNodeType.Comment;\n  public data: string;\n\n  constructor(data: string) {\n    super();\n    this.data = data;\n  }\n\n  public get textContent(): string {\n    return this.data;\n  }\n\n  public set textContent(textContent: string) {\n    this.data = textContent;\n  }\n\n  toString() {\n    return `RRComment text=${JSON.stringify(this.data)}`;\n  }\n}\n\nexport class BaseRRCDATASection extends BaseRRNode implements IRRCDATASection {\n  public readonly nodeName = '#cdata-section' as const;\n  public readonly nodeType: number = NodeType.CDATA_SECTION_NODE;\n  public readonly RRNodeType = RRNodeType.CDATA;\n  public data: string;\n\n  constructor(data: string) {\n    super();\n    this.data = data;\n  }\n\n  public get textContent(): string {\n    return this.data;\n  }\n\n  public set textContent(textContent: string) {\n    this.data = textContent;\n  }\n\n  toString() {\n    return `RRCDATASection data=${JSON.stringify(this.data)}`;\n  }\n}\n\nexport class ClassList {\n  private onChange: ((newClassText: string) => void) | undefined;\n  classes: string[] = [];\n\n  constructor(\n    classText?: string,\n    onChange?: ((newClassText: string) => void) | undefined,\n  ) {\n    if (classText) {\n      const classes = classText.trim().split(/\\s+/);\n      this.classes.push(...classes);\n    }\n    this.onChange = onChange;\n  }\n\n  add = (...classNames: string[]) => {\n    for (const item of classNames) {\n      const className = String(item);\n      if (this.classes.indexOf(className) >= 0) continue;\n      this.classes.push(className);\n    }\n    this.onChange && this.onChange(this.classes.join(' '));\n  };\n\n  remove = (...classNames: string[]) => {\n    this.classes = this.classes.filter(\n      (item) => classNames.indexOf(item) === -1,\n    );\n    this.onChange && this.onChange(this.classes.join(' '));\n  };\n}\n\nexport type CSSStyleDeclaration = Record<string, string> & {\n  setProperty: (\n    name: string,\n    value: string | null,\n    priority?: string | null,\n  ) => void;\n  removeProperty: (name: string) => string;\n};\n\nfunction appendChild(parent: IRRNode, newChild: IRRNode) {\n  if (newChild.parentNode) newChild.parentNode.removeChild(newChild);\n\n  if (parent.lastChild) {\n    parent.lastChild.nextSibling = newChild;\n    newChild.previousSibling = parent.lastChild;\n  } else {\n    parent.firstChild = newChild;\n    newChild.previousSibling = null;\n  }\n  parent.lastChild = newChild;\n  newChild.nextSibling = null;\n  newChild.parentNode = parent;\n  newChild.parentElement = parent;\n  newChild.ownerDocument = parent.ownerDocument;\n  return newChild;\n}\n\nfunction insertBefore(\n  parent: IRRNode,\n  newChild: IRRNode,\n  refChild: IRRNode | null,\n) {\n  if (!refChild) return appendChild(parent, newChild);\n\n  if (refChild.parentNode !== parent)\n    throw new Error(\n      \"Failed to execute 'insertBefore' on 'RRNode': The RRNode before which the new node is to be inserted is not a child of this RRNode.\",\n    );\n\n  if (newChild === refChild) return newChild;\n  if (newChild.parentNode) newChild.parentNode.removeChild(newChild);\n\n  newChild.previousSibling = refChild.previousSibling;\n  refChild.previousSibling = newChild;\n  newChild.nextSibling = refChild;\n\n  if (newChild.previousSibling) newChild.previousSibling.nextSibling = newChild;\n  else parent.firstChild = newChild;\n\n  newChild.parentElement = parent;\n  newChild.parentNode = parent;\n  newChild.ownerDocument = parent.ownerDocument;\n  return newChild;\n}\n\nfunction removeChild(parent: IRRNode, child: IRRNode) {\n  if (child.parentNode !== parent)\n    throw new Error(\n      \"Failed to execute 'removeChild' on 'RRNode': The RRNode to be removed is not a child of this RRNode.\",\n    );\n  if (child.previousSibling)\n    child.previousSibling.nextSibling = child.nextSibling;\n  else parent.firstChild = child.nextSibling;\n  if (child.nextSibling)\n    child.nextSibling.previousSibling = child.previousSibling;\n  else parent.lastChild = child.previousSibling;\n  child.previousSibling = null;\n  child.nextSibling = null;\n  child.parentElement = null;\n  child.parentNode = null;\n  return child;\n}\n\n// Enumerate nodeType value of standard HTML Node.\nexport enum NodeType {\n  PLACEHOLDER, // This isn't a node type. Enum type value starts from zero but NodeType value starts from 1.\n  ELEMENT_NODE,\n  ATTRIBUTE_NODE,\n  TEXT_NODE,\n  CDATA_SECTION_NODE,\n  ENTITY_REFERENCE_NODE,\n  ENTITY_NODE,\n  PROCESSING_INSTRUCTION_NODE,\n  COMMENT_NODE,\n  DOCUMENT_NODE,\n  DOCUMENT_TYPE_NODE,\n  DOCUMENT_FRAGMENT_NODE,\n}\n", "import type {\n  throttleOptions,\n  listenerHandler,\n  hookResetter,\n  blockClass,\n  addedNodeMutation,\n  DocumentDimension,\n  IWindow,\n  DeprecatedMirror,\n  textMutation,\n  IMirror,\n} from '@posthog/rrweb-types';\nimport type { Mirror, SlimDOMOptions } from '@posthog/rrweb-snapshot';\nimport {\n  isShadowRoot,\n  IGNORED_NODE,\n  classMatchesRegex,\n} from '@posthog/rrweb-snapshot';\nimport { RRNode, RRIFrameElement, BaseRRNode } from '@posthog/rrdom';\nimport dom from '@posthog/rrweb-utils';\n\nexport function on(\n  type: string,\n  fn: EventListenerOrEventListenerObject,\n  target: Document | IWindow = document,\n): listenerHandler {\n  const options = { capture: true, passive: true };\n  target.addEventListener(type, fn, options);\n  return () => target.removeEventListener(type, fn, options);\n}\n\n// https://github.com/rrweb-io/rrweb/pull/1695\n// If an iframe is initially same-origin and observed, but later its\n// location changes to a cross-origin URL (e.g. via document.location\n// or a redirect), accessing properties on its contentWindow throws a\n// SecurityError. This applies to cleanup calls like removeEventListener\n// as well as the handler callbacks returned by `on()` above.\nexport function callSafely(fn: () => void): void {\n  try {\n    fn();\n  } catch (error) {\n    if (!(error instanceof DOMException && error.name === 'SecurityError')) {\n      throw error;\n    }\n  }\n}\n\n// https://github.com/rrweb-io/rrweb/pull/407\nconst DEPARTED_MIRROR_ACCESS_WARNING =\n  'Please stop import mirror directly. Instead of that,' +\n  '\\r\\n' +\n  'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n  '\\r\\n' +\n  'or you can use record.mirror to access the mirror instance during recording.';\n/** @deprecated */\nexport let _mirror: DeprecatedMirror = {\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      // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n      return Reflect.get(target, prop, receiver);\n    },\n  });\n}\n\n// copy from underscore and modified\nexport function throttle<T>(\n  func: (arg: T) => void,\n  wait: number,\n  options: throttleOptions = {},\n) {\n  let timeout: ReturnType<typeof setTimeout> | null = null;\n  let previous = 0;\n  return function (...args: T[]) {\n    const now = Date.now();\n    if (!previous && options.leading === false) {\n      previous = now;\n    }\n    const remaining = wait - (now - previous);\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-this-alias\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}\n\nexport function hookSetter<T>(\n  target: T,\n  key: string | number | symbol,\n  d: PropertyDescriptor,\n  isRevoked?: boolean,\n  win = window,\n): hookResetter {\n  const original = win.Object.getOwnPropertyDescriptor(target, key);\n  win.Object.defineProperty(\n    target,\n    key,\n    isRevoked\n      ? d\n      : {\n          set(value) {\n            // put hooked setter into event loop to avoid of set latency\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}\n\n// guard against old third party libraries which redefine Date.now\nlet nowTimestamp = Date.now;\n\nif (!(/*@__PURE__*/ /[1-9][0-9]{12}/.test(Date.now().toString()))) {\n  // they have already redefined it! use a fallback\n  nowTimestamp = () => new Date().getTime();\n}\nexport { nowTimestamp };\n\nexport function getWindowScroll(win: Window) {\n  const doc = win.document;\n  return {\n    left: doc.scrollingElement\n      ? doc.scrollingElement.scrollLeft\n      : win.pageXOffset !== undefined\n      ? win.pageXOffset\n      : doc.documentElement.scrollLeft ||\n        (doc?.body && dom.parentElement(doc.body)?.scrollLeft) ||\n        doc?.body?.scrollLeft ||\n        0,\n    top: doc.scrollingElement\n      ? doc.scrollingElement.scrollTop\n      : win.pageYOffset !== undefined\n      ? win.pageYOffset\n      : doc?.documentElement.scrollTop ||\n        (doc?.body && dom.parentElement(doc.body)?.scrollTop) ||\n        doc?.body?.scrollTop ||\n        0,\n  };\n}\n\nexport function getWindowHeight(): number {\n  return (\n    window.innerHeight ||\n    (document.documentElement && document.documentElement.clientHeight) ||\n    (document.body && document.body.clientHeight)\n  );\n}\n\nexport function getWindowWidth(): number {\n  return (\n    window.innerWidth ||\n    (document.documentElement && document.documentElement.clientWidth) ||\n    (document.body && document.body.clientWidth)\n  );\n}\n\n/**\n * Returns the given node as an HTMLElement if it is one, otherwise the parent node as an HTMLElement\n * @param node - node to check\n * @returns HTMLElement or null\n */\n\nexport function closestElementOfNode(node: Node | null): HTMLElement | null {\n  if (!node) {\n    return null;\n  }\n  const el: HTMLElement | null =\n    node.nodeType === node.ELEMENT_NODE\n      ? (node as HTMLElement)\n      : dom.parentElement(node);\n  return el;\n}\n\n/**\n * Checks if the given element set to be blocked by rrweb\n * @param node - node to check\n * @param blockClass - class name to check\n * @param blockSelector - css selectors to check\n * @param checkAncestors - whether to search through parent nodes for the block class\n * @returns true/false if the node was blocked or not\n */\nexport function isBlocked(\n  node: Node | null,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  checkAncestors: boolean,\n): boolean {\n  if (!node) {\n    return false;\n  }\n  const el = closestElementOfNode(node);\n\n  if (!el) {\n    return false;\n  }\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    // 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}\n\nexport function isSerialized(n: Node, mirror: Mirror): boolean {\n  return mirror.getId(n) !== -1;\n}\n\nexport function isIgnored(\n  n: Node,\n  mirror: Mirror,\n  slimDOMOptions: SlimDOMOptions,\n): boolean {\n  if ((n as Element).tagName === 'TITLE' && slimDOMOptions.headTitleMutations) {\n    // we do this check here but not in rrweb-snapshot\n    // to block mutations/animations on the title.\n    // the headTitleMutations option isn't intended to block recording of the initial value\n    return true;\n  }\n  // The main part of the slimDOM check happens in\n  // rrweb-snapshot::serializeNodeWithId\n  return mirror.getId(n) === IGNORED_NODE;\n}\n\nexport function isAncestorRemoved(target: Node, mirror: Mirror): boolean {\n  if (isShadowRoot(target)) {\n    return false;\n  }\n  const id = mirror.getId(target);\n  if (!mirror.has(id)) {\n    return true;\n  }\n  const parent = dom.parentNode(target);\n  if (parent && parent.nodeType === target.DOCUMENT_NODE) {\n    return false;\n  }\n  // if the root is not document, it means the node is not in the DOM tree anymore\n  if (!parent) {\n    return true;\n  }\n  return isAncestorRemoved(parent, mirror);\n}\n\nexport function legacy_isTouchEvent(\n  event: MouseEvent | TouchEvent | PointerEvent,\n): event is TouchEvent {\n  return Boolean((event as TouchEvent).changedTouches);\n}\n\nexport function polyfill(win = window) {\n  if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    win.NodeList.prototype.forEach = Array.prototype\n      .forEach as unknown as NodeList['forEach'];\n  }\n\n  if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    win.DOMTokenList.prototype.forEach = Array.prototype\n      .forEach as unknown as DOMTokenList['forEach'];\n  }\n}\n\ntype ResolveTree = {\n  value: addedNodeMutation;\n  children: ResolveTree[];\n  parent: ResolveTree | null;\n};\n\nexport function queueToResolveTrees(queue: addedNodeMutation[]): ResolveTree[] {\n  const queueNodeMap: Record<number, ResolveTree> = {};\n  const putIntoMap = (\n    m: addedNodeMutation,\n    parent: ResolveTree | null,\n  ): ResolveTree => {\n    const nodeInTree: ResolveTree = {\n      value: m,\n      parent,\n      children: [],\n    };\n    queueNodeMap[m.node.id] = nodeInTree;\n    return nodeInTree;\n  };\n\n  const queueNodeTrees: ResolveTree[] = [];\n  for (const mutation of queue) {\n    const { nextId, parentId } = mutation;\n    if (nextId && nextId in queueNodeMap) {\n      const nextInTree = queueNodeMap[nextId];\n      if (nextInTree.parent) {\n        const idx = nextInTree.parent.children.indexOf(nextInTree);\n        nextInTree.parent.children.splice(\n          idx,\n          0,\n          putIntoMap(mutation, nextInTree.parent),\n        );\n      } else {\n        const idx = queueNodeTrees.indexOf(nextInTree);\n        queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\n      }\n      continue;\n    }\n    if (parentId in queueNodeMap) {\n      const parentInTree = queueNodeMap[parentId];\n      parentInTree.children.push(putIntoMap(mutation, parentInTree));\n      continue;\n    }\n    queueNodeTrees.push(putIntoMap(mutation, null));\n  }\n\n  return queueNodeTrees;\n}\n\nexport function iterateResolveTree(\n  tree: ResolveTree,\n  cb: (mutation: addedNodeMutation) => unknown,\n) {\n  cb(tree.value);\n  /**\n   * The resolve tree was designed to reflect the DOM layout,\n   * but we need append next sibling first, so we do a reverse\n   * loop here.\n   */\n  for (let i = tree.children.length - 1; i >= 0; i--) {\n    iterateResolveTree(tree.children[i], cb);\n  }\n}\n\nexport type AppendedIframe = {\n  mutationInQueue: addedNodeMutation;\n  builtNode: HTMLIFrameElement | RRIFrameElement;\n};\n\nexport function isSerializedIframe<TNode extends Node | RRNode>(\n  n: TNode,\n  mirror: IMirror<TNode>,\n): boolean {\n  return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\n}\n\nexport function isSerializedStylesheet<TNode extends Node | RRNode>(\n  n: TNode,\n  mirror: IMirror<TNode>,\n): boolean {\n  return Boolean(\n    n.nodeName === 'LINK' &&\n      n.nodeType === n.ELEMENT_NODE &&\n      (n as HTMLElement).getAttribute &&\n      (n as HTMLElement).getAttribute('rel') === 'stylesheet' &&\n      mirror.getMeta(n),\n  );\n}\n\nexport function getBaseDimension(\n  node: Node,\n  rootIframe: Node,\n): DocumentDimension {\n  const frameElement = node.ownerDocument?.defaultView?.frameElement;\n  if (!frameElement || frameElement === rootIframe) {\n    return {\n      x: 0,\n      y: 0,\n      relativeScale: 1,\n      absoluteScale: 1,\n    };\n  }\n\n  const frameDimension = frameElement.getBoundingClientRect();\n  const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\n  // the iframe element may have a scale transform\n  const relativeScale = frameDimension.height / frameElement.clientHeight;\n  return {\n    x:\n      frameDimension.x * frameBaseDimension.relativeScale +\n      frameBaseDimension.x,\n    y:\n      frameDimension.y * frameBaseDimension.relativeScale +\n      frameBaseDimension.y,\n    relativeScale,\n    absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\n  };\n}\n\nexport function hasShadowRoot<T extends Node | RRNode>(\n  n: T,\n): n is T & { shadowRoot: ShadowRoot } {\n  if (!n) return false;\n  if (n instanceof BaseRRNode && 'shadowRoot' in n) {\n    return Boolean(n.shadowRoot);\n  }\n  return Boolean(dom.shadowRoot(n as unknown as Element));\n}\n\nexport function getNestedRule(\n  rules: CSSRuleList,\n  position: number[],\n): CSSGroupingRule | null {\n  const rule = rules?.[position[0]] as CSSGroupingRule | null;\n  if (!rule) {\n    return null;\n  }\n  if (position.length === 1) {\n    return rule;\n  } else {\n    return getNestedRule(rule.cssRules, position.slice(1));\n  }\n}\n\nexport function getPositionsAndIndex(nestedIndex: number[]) {\n  const positions = [...nestedIndex];\n  const index = positions.pop();\n  return { positions, index };\n}\n\n/**\n * Returns the latest mutation in the queue for each node.\n * @param mutations - mutations The text mutations to filter.\n * @returns The filtered text mutations.\n */\nexport function uniqueTextMutations(mutations: textMutation[]): textMutation[] {\n  const idSet = new Set<number>();\n  const uniqueMutations: textMutation[] = [];\n\n  for (let i = mutations.length; i--; ) {\n    const mutation = mutations[i];\n    if (!idSet.has(mutation.id)) {\n      uniqueMutations.push(mutation);\n      idSet.add(mutation.id);\n    }\n  }\n\n  return uniqueMutations;\n}\n\nexport class StyleSheetMirror {\n  private id = 1;\n  private styleIDMap = new WeakMap<CSSStyleSheet, number>();\n  private idStyleMap = new Map<number, CSSStyleSheet>();\n\n  getId(stylesheet: CSSStyleSheet): number {\n    return this.styleIDMap.get(stylesheet) ?? -1;\n  }\n\n  has(stylesheet: CSSStyleSheet): boolean {\n    return this.styleIDMap.has(stylesheet);\n  }\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: CSSStyleSheet, id?: number): number {\n    if (this.has(stylesheet)) return this.getId(stylesheet);\n    let newId: number;\n    if (id === undefined) {\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\n  getStyle(id: number): CSSStyleSheet | null {\n    return this.idStyleMap.get(id) || null;\n  }\n\n  reset(): void {\n    this.styleIDMap = new WeakMap();\n    this.idStyleMap = new Map();\n    this.id = 1;\n  }\n\n  generateId(): number {\n    return this.id++;\n  }\n}\n\n/**\n * Get the direct shadow host of a node in shadow dom. Returns null if it is not in a shadow dom.\n */\nexport function getShadowHost(n: Node): Element | null {\n  let shadowHost: Element | null = null;\n  if (\n    'getRootNode' in n &&\n    dom.getRootNode(n)?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\n    dom.host(dom.getRootNode(n) as ShadowRoot)\n  )\n    shadowHost = dom.host(dom.getRootNode(n) as ShadowRoot);\n  return shadowHost;\n}\n\n/**\n * Get the root shadow host of a node in nested shadow doms. Returns the node itself if it is not in a shadow dom.\n */\nexport function getRootShadowHost(n: Node): Node {\n  let rootShadowHost: Node = n;\n\n  let shadowHost: Element | null;\n  // If n is in a nested shadow dom.\n  while ((shadowHost = getShadowHost(rootShadowHost)))\n    rootShadowHost = shadowHost;\n\n  return rootShadowHost;\n}\n\nexport function shadowHostInDom(n: Node): boolean {\n  const doc = n.ownerDocument;\n  if (!doc) return false;\n  const shadowHost = getRootShadowHost(n);\n  return dom.contains(doc, shadowHost);\n}\n\nexport function inDom(n: Node): boolean {\n  const doc = n.ownerDocument;\n  if (!doc) return false;\n  return dom.contains(doc, n) || shadowHostInDom(n);\n}\n", "import {\n  serializeNodeWithId,\n  transformAttribute,\n  IGNORED_NODE,\n  ignoreAttribute,\n  isShadowRoot,\n  needMaskingText,\n  maskInputValue,\n  Mirror,\n  isNativeShadowDom,\n  getInputType,\n  toLowerCase,\n} from '@posthog/rrweb-snapshot';\nimport type { observerParam, MutationBufferParam } from '../types';\nimport type {\n  mutationRecord,\n  textCursor,\n  attributeCursor,\n  removedNodeMutation,\n  addedNodeMutation,\n  Optional,\n} from '@posthog/rrweb-types';\nimport {\n  isBlocked,\n  isAncestorRemoved,\n  isIgnored,\n  isSerialized,\n  hasShadowRoot,\n  isSerializedIframe,\n  isSerializedStylesheet,\n  inDom,\n  getShadowHost,\n  closestElementOfNode,\n} from '../utils';\nimport dom from '@posthog/rrweb-utils';\n\ntype DoubleLinkedListNode = {\n  previous: DoubleLinkedListNode | null;\n  next: DoubleLinkedListNode | null;\n  value: NodeInLinkedList;\n};\ntype NodeInLinkedList = Node & {\n  __ln: DoubleLinkedListNode;\n};\n\nfunction isNodeInLinkedList(n: Node | NodeInLinkedList): n is NodeInLinkedList {\n  return '__ln' in n;\n}\n\nclass DoubleLinkedList {\n  public length = 0;\n  public head: DoubleLinkedListNode | null = null;\n  public tail: DoubleLinkedListNode | null = null;\n\n  public get(position: number) {\n    if (position >= this.length) {\n      throw new Error('Position outside of list range');\n    }\n\n    let current = this.head;\n    for (let index = 0; index < position; index++) {\n      current = current?.next || null;\n    }\n    return current;\n  }\n\n  public addNode(n: Node) {\n    const node: DoubleLinkedListNode = {\n      value: n as NodeInLinkedList,\n      previous: null,\n      next: null,\n    };\n    (n as NodeInLinkedList).__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      n.nextSibling &&\n      isNodeInLinkedList(n.nextSibling) &&\n      n.nextSibling.__ln.previous\n    ) {\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\n  public removeNode(n: NodeInLinkedList) {\n    const current = n.__ln;\n    if (!this.head) {\n      return;\n    }\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 as Optional<NodeInLinkedList, '__ln'>).__ln;\n    }\n    this.length--;\n  }\n}\n\nconst moveKey = (id: number, parentId: number) => `${id}@${parentId}`;\n\n/**\n * controls behaviour of a MutationObserver\n */\nexport default class MutationBuffer {\n  private frozen = false;\n  private locked = false;\n\n  private texts: textCursor[] = [];\n  private attributes: attributeCursor[] = [];\n  private attributeMap = new WeakMap<Node, attributeCursor>();\n  private removes: removedNodeMutation[] = [];\n  private mapRemoves: Node[] = [];\n\n  private movedMap: Record<string, true> = {};\n\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  private addedSet = new Set<Node>();\n  private movedSet = new Set<Node>();\n  private droppedSet = new Set<Node>();\n  private removesSubTreeCache = new Set<Node>();\n\n  private mutationCb: observerParam['mutationCb'];\n  private blockClass: observerParam['blockClass'];\n  private blockSelector: observerParam['blockSelector'];\n  private maskTextClass: observerParam['maskTextClass'];\n  private maskTextSelector: observerParam['maskTextSelector'];\n  private inlineStylesheet: observerParam['inlineStylesheet'];\n  private maskInputOptions: observerParam['maskInputOptions'];\n  private maskTextFn: observerParam['maskTextFn'];\n  private maskInputFn: observerParam['maskInputFn'];\n  private keepIframeSrcFn: observerParam['keepIframeSrcFn'];\n  private recordCanvas: observerParam['recordCanvas'];\n  private inlineImages: observerParam['inlineImages'];\n  private slimDOMOptions: observerParam['slimDOMOptions'];\n  private dataURLOptions: observerParam['dataURLOptions'];\n  private doc: observerParam['doc'];\n  private mirror: observerParam['mirror'];\n  private iframeManager: observerParam['iframeManager'];\n  private stylesheetManager: observerParam['stylesheetManager'];\n  private shadowDomManager: observerParam['shadowDomManager'];\n  private canvasManager: observerParam['canvasManager'];\n  private processedNodeManager: observerParam['processedNodeManager'];\n  private unattachedDoc: HTMLDocument;\n\n  public init(options: MutationBufferParam) {\n    (\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      ] as const\n    ).forEach((key) => {\n      // just a type trick, the runtime result is correct\n      this[key] = options[key] as never;\n    });\n  }\n\n  public freeze() {\n    this.frozen = true;\n    this.canvasManager.freeze();\n  }\n\n  public unfreeze() {\n    this.frozen = false;\n    this.canvasManager.unfreeze();\n    this.emit();\n  }\n\n  public isFrozen() {\n    return this.frozen;\n  }\n\n  public lock() {\n    this.locked = true;\n    this.canvasManager.lock();\n  }\n\n  public unlock() {\n    this.locked = false;\n    this.canvasManager.unlock();\n    this.emit();\n  }\n\n  public reset() {\n    this.shadowDomManager.reset();\n    this.canvasManager.reset();\n  }\n\n  public destroy() {\n    while (this.mapRemoves.length) {\n      this.mirror.removeNodeFromMap(this.mapRemoves.shift()!);\n    }\n  }\n\n  public processMutations = (mutations: mutationRecord[]) => {\n    mutations.forEach(this.processMutation); // adds mutations to the buffer\n    this.emit(); // clears buffer if not locked/frozen\n  };\n\n  public emit = () => {\n    if (this.frozen || this.locked) {\n      return;\n    }\n\n    // delay any modification of the mirror until this function\n    // so that the mirror for takeFullSnapshot doesn't get mutated while it's event is being processed\n\n    const adds: addedNodeMutation[] = [];\n    const addedIds = new Set<number>();\n\n    /**\n     * Sometimes child node may be pushed before its newly added\n     * parent, so we init a queue to store these nodes.\n     */\n    const addList = new DoubleLinkedList();\n    const getNextId = (n: Node): number | null => {\n      let ns: Node | null = n;\n      let nextId: number | null = IGNORED_NODE; // slimDOM: ignored\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: Node) => {\n      const parent = dom.parentNode(n);\n      if (!parent || !inDom(n) || (parent as Element).tagName === 'TEXTAREA') {\n        return;\n      }\n      const parentId = isShadowRoot(parent)\n        ? this.mirror.getId(getShadowHost(n))\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 as HTMLIFrameElement);\n          }\n          if (isSerializedStylesheet(currentN, this.mirror)) {\n            this.stylesheetManager.trackLinkElement(\n              currentN as HTMLLinkElement,\n            );\n          }\n          if (hasShadowRoot(n)) {\n            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n            this.shadowDomManager.addShadowRoot(dom.shadowRoot(n)!, this.doc);\n          }\n        },\n        onIframeLoad: (iframe, childSn) => {\n          this.iframeManager.attachIframe(iframe, childSn);\n          this.shadowDomManager.observeAttachShadow(iframe);\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\n    while (this.mapRemoves.length) {\n      this.mirror.removeNodeFromMap(this.mapRemoves.shift()!);\n    }\n\n    for (const n of this.movedSet) {\n      if (\n        isParentRemoved(this.removesSubTreeCache, n, this.mirror) &&\n        !this.movedSet.has(dom.parentNode(n)!)\n      ) {\n        continue;\n      }\n      pushAdd(n);\n    }\n\n    for (const n of this.addedSet) {\n      if (\n        !isAncestorInSet(this.droppedSet, n) &&\n        !isParentRemoved(this.removesSubTreeCache, n, this.mirror)\n      ) {\n        pushAdd(n);\n      } else if (isAncestorInSet(this.movedSet, n)) {\n        pushAdd(n);\n      } else {\n        this.droppedSet.add(n);\n      }\n    }\n\n    let candidate: DoubleLinkedListNode | null = null;\n    while (addList.length) {\n      let node: DoubleLinkedListNode | null = null;\n      if (candidate) {\n        const parentId = this.mirror.getId(dom.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          // ensure _node is defined before attempting to find value\n          if (_node) {\n            const parentId = this.mirror.getId(dom.parentNode(_node.value));\n            const nextId = getNextId(_node.value);\n\n            if (nextId === -1) continue;\n            // nextId !== -1 && parentId !== -1\n            else if (parentId !== -1) {\n              node = _node;\n              break;\n            }\n            // nextId !== -1 && parentId === -1 This branch can happen if the node is the child of shadow root\n            else {\n              const unhandledNode = _node.value;\n              const parent = dom.parentNode(unhandledNode);\n              // If the node is the direct child of a shadow root, we treat the shadow host as its parent node.\n              if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n                const shadowHost = dom.host(parent as ShadowRoot);\n                const parentId = this.mirror.getId(shadowHost);\n                if (parentId !== -1) {\n                  node = _node;\n                  break;\n                }\n              }\n            }\n          }\n        }\n      }\n      if (!node) {\n        /**\n         * If all nodes in queue could not find a serialized parent,\n         * it may be a bug or corner case. We need to escape the\n         * dead while loop at once.\n         */\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\n    const payload = {\n      texts: this.texts\n        .map((text) => {\n          const n = text.node;\n          const parent = dom.parentNode(n);\n          if (parent && (parent as Element).tagName === 'TEXTAREA') {\n            // the node is being ignored as it isn't in the mirror, so shift mutation to attributes on parent textarea\n            this.genTextAreaValueMutation(parent as HTMLTextAreaElement);\n          }\n          return {\n            id: this.mirror.getId(n),\n            value: text.value,\n          };\n        })\n        // no need to include them on added elements, as they have just been serialized with up to date attribubtes\n        .filter((text) => !addedIds.has(text.id))\n        // text mutation's id was not in the mirror map means the target node has been removed\n        .filter((text) => this.mirror.has(text.id)),\n      attributes: this.attributes\n        .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            // check if the style diff is actually shorter than the regular string based mutation\n            // (which was the whole point of #464 'compact style mutation').\n            if (diffAsStr.length < attributes.style.length) {\n              // also: CSSOM fails badly when var() is present on shorthand properties, so only proceed with\n              // the compact style mutation if these have all been accounted for\n              if (\n                (diffAsStr + unchangedAsStr).split('var(').length ===\n                attributes.style.split('var(').length\n              ) {\n                attributes.style = attribute.styleDiff;\n              }\n            }\n          }\n          return {\n            id: this.mirror.getId(attribute.node),\n            attributes: attributes,\n          };\n        })\n        // no need to include them on added elements, as they have just been serialized with up to date attribubtes\n        .filter((attribute) => !addedIds.has(attribute.id))\n        // attribute mutation's id was not in the mirror map means the target node has been removed\n        .filter((attribute) => this.mirror.has(attribute.id)),\n      removes: this.removes,\n      adds,\n    };\n    // payload may be empty if the mutations happened in some blocked elements\n    if (\n      !payload.texts.length &&\n      !payload.attributes.length &&\n      !payload.removes.length &&\n      !payload.adds.length\n    ) {\n      return;\n    }\n\n    // reset\n    this.texts = [];\n    this.attributes = [];\n    this.attributeMap = new WeakMap<Node, attributeCursor>();\n    this.removes = [];\n    this.addedSet = new Set<Node>();\n    this.movedSet = new Set<Node>();\n    this.droppedSet = new Set<Node>();\n    this.removesSubTreeCache = new Set<Node>();\n    this.movedMap = {};\n\n    this.mutationCb(payload);\n  };\n\n  public bufferBelongsToIframe = (iframeEl: HTMLIFrameElement) => {\n    return this.doc === iframeEl.contentDocument;\n  };\n\n  private genTextAreaValueMutation = (textarea: HTMLTextAreaElement) => {\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      dom.childNodes(textarea),\n      (cn) => dom.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\n  private processMutation = (m: mutationRecord) => {\n    if (isIgnored(m.target, this.mirror, this.slimDOMOptions)) {\n      return;\n    }\n    switch (m.type) {\n      case 'characterData': {\n        const value = dom.textContent(m.target);\n\n        if (\n          !isBlocked(m.target, this.blockClass, this.blockSelector, false) &&\n          value !== m.oldValue\n        ) {\n          this.texts.push({\n            value:\n              needMaskingText(\n                m.target,\n                this.maskTextClass,\n                this.maskTextSelector,\n                true, // checkAncestors\n              ) && value\n                ? this.maskTextFn\n                  ? this.maskTextFn(value, closestElementOfNode(m.target))\n                  : value.replace(/[\\S]/g, '*')\n                : value,\n            node: m.target,\n          });\n        }\n        break;\n      }\n      case 'attributes': {\n        const target = m.target as HTMLElement;\n        let attributeName = m.attributeName as string;\n        let value = (m.target as HTMLElement).getAttribute(attributeName);\n\n        if (attributeName === 'value') {\n          const type = getInputType(target);\n\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 (\n          isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\n          value === m.oldValue\n        ) {\n          return;\n        }\n\n        let item = this.attributeMap.get(m.target);\n        if (\n          target.tagName === 'IFRAME' &&\n          attributeName === 'src' &&\n          !this.keepIframeSrcFn(value as string)\n        ) {\n          if (!(target as HTMLIFrameElement).contentDocument) {\n            // we can't record it directly as we can't see into it\n            // preserve the src attribute so a decision can be taken at replay time\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\n        // Keep this property on inputs that used to be password inputs\n        // This is used to ensure we do not unmask value when using e.g. a \"Show password\" type button\n        if (\n          attributeName === 'type' &&\n          target.tagName === 'INPUT' &&\n          (m.oldValue || '').toLowerCase() === 'password'\n        ) {\n          target.setAttribute('data-rr-is-password', 'true');\n        }\n\n        if (!ignoreAttribute(target.tagName, attributeName, value)) {\n          // overwrite attribute if the mutations was triggered in same time\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                // avoid upsetting original document from a Content Security point of view\n                this.unattachedDoc =\n                  document.implementation.createHTMLDocument();\n              } catch (e) {\n                // fallback to more direct method\n                this.unattachedDoc = this.doc;\n              }\n            }\n            const old = this.unattachedDoc.createElement('span');\n            if (m.oldValue) {\n              old.setAttribute('style', 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 (\n                newValue !== old.style.getPropertyValue(pname) ||\n                newPriority !== old.style.getPropertyPriority(pname)\n              ) {\n                if (newPriority === '') {\n                  item.styleDiff[pname] = newValue;\n                } else {\n                  item.styleDiff[pname] = [newValue, newPriority];\n                }\n              } else {\n                // for checking\n                item._unchangedStyles[pname] = [newValue, newPriority];\n              }\n            }\n            for (const pname of Array.from(old.style)) {\n              if (target.style.getPropertyValue(pname) === '') {\n                // \"if not set, returns the empty string\"\n                item.styleDiff[pname] = false; // delete\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        /**\n         * Parent is blocked, ignore all child mutations\n         */\n        if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\n          return;\n\n        if ((m.target as Element).tagName === 'TEXTAREA') {\n          // children would be ignored in genAdds as they aren't in the mirror\n          this.genTextAreaValueMutation(m.target as HTMLTextAreaElement);\n          return; // any removedNodes won't have been in mirror either\n        }\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)\n            ? this.mirror.getId(dom.host(m.target))\n            : this.mirror.getId(m.target);\n          if (\n            isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\n            isIgnored(n, this.mirror, this.slimDOMOptions) ||\n            !isSerialized(n, this.mirror)\n          ) {\n            return;\n          }\n          // removed node has not been serialized yet, just remove it from the Set\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            /**\n             * If target was newly added and removed child node was\n             * not serialized, it means the child node has been removed\n             * before callback fired, so we can ignore it because\n             * newly added node will be serialized without child nodes.\n             * TODO: verify this\n             */\n          } else if (isAncestorRemoved(m.target, this.mirror)) {\n            /**\n             * If parent id was not in the mirror map any more, it\n             * means the parent node has already been removed. So\n             * the node is also removed which we do not need to track\n             * and replay.\n             */\n          } else if (\n            this.movedSet.has(n) &&\n            this.movedMap[moveKey(nodeId, parentId)]\n          ) {\n            deepDelete(this.movedSet, n);\n          } else {\n            this.removes.push({\n              parentId,\n              id: nodeId,\n              isShadow:\n                isShadowRoot(m.target) && isNativeShadowDom(m.target)\n                  ? true\n                  : undefined,\n            });\n            processRemoves(n, this.removesSubTreeCache);\n          }\n          this.mapRemoves.push(n);\n        });\n        break;\n      }\n      default:\n        break;\n    }\n  };\n\n  /**\n   * Make sure you check if `n`'s parent is blocked before calling this function\n   * */\n  private genAdds = (n: Node, target?: Node) => {\n    // this node was already recorded in other buffer, ignore it\n    if (this.processedNodeManager.inOtherBuffer(n, this)) return;\n\n    // if n is added to set, there is no need to travel it and its' children again\n    if (this.addedSet.has(n) || this.movedSet.has(n)) return;\n\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: number | null = 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\n    // if this node is blocked `serializeNode` will turn it into a placeholder element\n    // but we have to remove it's children otherwise they will be added as placeholders too\n    if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\n      dom.childNodes(n).forEach((childN) => this.genAdds(childN));\n      if (hasShadowRoot(n)) {\n        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n        dom.childNodes(dom.shadowRoot(n)!).forEach((childN) => {\n          this.processedNodeManager.add(childN, this);\n          this.genAdds(childN, n);\n        });\n      }\n    }\n  };\n}\n\n/**\n * Some utils to handle the mutation observer DOM records.\n * It should be more clear to extend the native data structure\n * like Set and Map, but currently Typescript does not support\n * that.\n */\nfunction deepDelete(addsSet: Set<Node>, n: Node) {\n  addsSet.delete(n);\n  dom.childNodes(n).forEach((childN) => deepDelete(addsSet, childN));\n}\n\nfunction processRemoves(n: Node, cache: Set<Node>) {\n  const queue = [n];\n\n  while (queue.length) {\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    const next = queue.pop()!;\n    if (cache.has(next)) continue;\n    cache.add(next);\n    dom.childNodes(next).forEach((n) => queue.push(n));\n  }\n\n  return;\n}\n\nfunction isParentRemoved(removes: Set<Node>, n: Node, mirror: Mirror): boolean {\n  if (removes.size === 0) return false;\n  return _isParentRemoved(removes, n, mirror);\n}\n\nfunction _isParentRemoved(\n  removes: Set<Node>,\n  n: Node,\n  _mirror: Mirror,\n): boolean {\n  const node: ParentNode | null = dom.parentNode(n);\n  if (!node) return false;\n  return removes.has(node);\n}\n\nfunction isAncestorInSet(set: Set<Node>, n: Node): boolean {\n  if (set.size === 0) return false;\n  return _isAncestorInSet(set, n);\n}\n\nfunction _isAncestorInSet(set: Set<Node>, n: Node): boolean {\n  const parent = dom.parentNode(n);\n  if (!parent) {\n    return false;\n  }\n  if (set.has(parent)) {\n    return true;\n  }\n  return _isAncestorInSet(set, parent);\n}\n", "import type { ErrorHandler } from '../types';\n\ntype Callback = (...args: unknown[]) => unknown;\n\nlet errorHandler: ErrorHandler | undefined;\n\nexport function registerErrorHandler(handler: ErrorHandler | undefined) {\n  errorHandler = handler;\n}\n\nexport function unregisterErrorHandler() {\n  errorHandler = undefined;\n}\n\n/**\n * Wrap callbacks in a wrapper that allows to pass errors to a configured `errorHandler` method.\n */\nexport const callbackWrapper = <T extends Callback>(cb: T): T => {\n  if (!errorHandler) {\n    return cb;\n  }\n\n  const rrwebWrapped = ((...rest: unknown[]) => {\n    try {\n      return cb(...rest);\n    } catch (error) {\n      if (errorHandler && errorHandler(error) === true) {\n        return;\n      }\n\n      throw error;\n    }\n  }) as unknown as T;\n\n  return rrwebWrapped;\n};\n", "import {\n  type MaskInputOptions,\n  maskInputValue,\n  Mirror,\n  getInputType,\n  toLowerCase,\n} from '@posthog/rrweb-snapshot';\nimport type { FontFaceSet } from 'css-font-loading-module';\nimport {\n  throttle,\n  on,\n  hookSetter,\n  getWindowScroll,\n  getWindowHeight,\n  getWindowWidth,\n  isBlocked,\n  legacy_isTouchEvent,\n  StyleSheetMirror,\n  nowTimestamp,\n} from '../utils';\nimport { patch } from '@posthog/rrweb-utils';\nimport type { observerParam, MutationBufferParam } from '../types';\nimport {\n  IncrementalSource,\n  MouseInteractions,\n  PointerTypes,\n  MediaInteractions,\n} from '@posthog/rrweb-types';\nimport type {\n  mutationCallBack,\n  mousemoveCallBack,\n  mousePosition,\n  mouseInteractionCallBack,\n  listenerHandler,\n  scrollCallback,\n  styleSheetRuleCallback,\n  viewportResizeCallback,\n  inputValue,\n  inputCallback,\n  hookResetter,\n  hooksParam,\n  Arguments,\n  mediaInteractionCallback,\n  canvasMutationCallback,\n  fontCallback,\n  fontParam,\n  styleDeclarationCallback,\n  IWindow,\n  SelectionRange,\n  selectionCallback,\n  customElementCallback,\n} from '@posthog/rrweb-types';\nimport MutationBuffer from './mutation';\nimport { callbackWrapper } from './error-handler';\nimport dom, { mutationObserverCtor } from '@posthog/rrweb-utils';\n\nexport const mutationBuffers: MutationBuffer[] = [];\n\n// Event.path is non-standard and used in some older browsers\ntype NonStandardEvent = Omit<Event, 'composedPath'> & {\n  path: EventTarget[];\n};\n\nfunction getEventTarget(event: Event | NonStandardEvent): EventTarget | null {\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    // fallback to `event.target` below\n  }\n\n  return event && event.target;\n}\n\nexport function initMutationObserver(\n  options: MutationBufferParam,\n  rootEl: Node,\n): { observer: MutationObserver; buffer: MutationBuffer } {\n  const mutationBuffer = new MutationBuffer();\n  mutationBuffers.push(mutationBuffer);\n  // see mutation.ts for details\n  mutationBuffer.init(options);\n  const observer = new (mutationObserverCtor() as new (\n    callback: MutationCallback,\n  ) => MutationObserver)(\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}\n\nfunction initMoveObserver({\n  mousemoveCb,\n  sampling,\n  doc,\n  mirror,\n}: observerParam): listenerHandler {\n  if (sampling.mousemove === false) {\n    return () => {\n      //\n    };\n  }\n\n  const threshold =\n    typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n  const callbackThreshold =\n    typeof sampling.mousemoveCallback === 'number'\n      ? sampling.mousemoveCallback\n      : 500;\n\n  let positions: mousePosition[] = [];\n  let timeBaseline: number | null;\n  const wrappedCb = throttle(\n    callbackWrapper(\n      (\n        source:\n          | IncrementalSource.MouseMove\n          | IncrementalSource.TouchMove\n          | IncrementalSource.Drag,\n      ) => {\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<MouseEvent | TouchEvent | DragEvent>(\n      callbackWrapper((evt) => {\n        const target = getEventTarget(evt);\n        // 'legacy' here as we could switch to https://developer.mozilla.org/en-US/docs/Web/API/Element/pointermove_event\n        const { clientX, clientY } = legacy_isTouchEvent(evt)\n          ? evt.changedTouches[0]\n          : evt;\n        if (!timeBaseline) {\n          timeBaseline = nowTimestamp();\n        }\n        positions.push({\n          x: clientX,\n          y: clientY,\n          id: mirror.getId(target as Node),\n          timeOffset: nowTimestamp() - timeBaseline,\n        });\n        // it is possible DragEvent is undefined even on devices\n        // that support event 'drag'\n        wrappedCb(\n          typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n            ? IncrementalSource.Drag\n            : evt instanceof MouseEvent\n            ? IncrementalSource.MouseMove\n            : 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}\n\nfunction initMouseInteractionObserver({\n  mouseInteractionCb,\n  doc,\n  mirror,\n  blockClass,\n  blockSelector,\n  sampling,\n}: observerParam): listenerHandler {\n  if (sampling.mouseInteraction === false) {\n    return () => {\n      //\n    };\n  }\n  const disableMap: Record<string, boolean | undefined> =\n    sampling.mouseInteraction === true ||\n    sampling.mouseInteraction === undefined\n      ? {}\n      : sampling.mouseInteraction;\n\n  const handlers: listenerHandler[] = [];\n  let currentPointerType: PointerTypes | null = null;\n  const getHandler = (eventKey: keyof typeof MouseInteractions) => {\n    return (event: MouseEvent | TouchEvent | PointerEvent) => {\n      const target = getEventTarget(event) as Node;\n      if (isBlocked(target, blockClass, blockSelector, true)) {\n        return;\n      }\n      let pointerType: PointerTypes | null = 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            // we are actually listening on 'pointerdown'\n            thisEventKey = 'TouchStart';\n          } else if (\n            MouseInteractions[eventKey] === MouseInteractions.MouseUp\n          ) {\n            // we are actually listening on 'pointerup'\n            thisEventKey = 'TouchEnd';\n          }\n        } else if (pointerType === PointerTypes.Pen) {\n          // TODO: these will get incorrectly emitted as MouseDown/MouseUp\n        }\n      } else if (legacy_isTouchEvent(event)) {\n        pointerType = PointerTypes.Touch;\n      }\n      if (pointerType !== null) {\n        currentPointerType = pointerType;\n        if (\n          (thisEventKey.startsWith('Touch') &&\n            pointerType === PointerTypes.Touch) ||\n          (thisEventKey.startsWith('Mouse') &&\n            pointerType === PointerTypes.Mouse)\n        ) {\n          // don't output redundant info\n          pointerType = null;\n        }\n      } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n        pointerType = currentPointerType;\n        currentPointerType = null; // cleanup as we've used it\n      }\n      const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n      if (!e) {\n        return;\n      }\n      const id = mirror.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)\n    .filter(\n      (key) =>\n        Number.isNaN(Number(key)) &&\n        !key.endsWith('_Departed') &&\n        disableMap[key] !== false,\n    )\n    .forEach((eventKey: keyof typeof MouseInteractions) => {\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            ) as unknown as typeof eventName;\n            break;\n          case MouseInteractions.TouchStart:\n          case MouseInteractions.TouchEnd:\n            // these are handled by pointerdown/pointerup\n            return;\n        }\n      }\n      handlers.push(on(eventName, handler, doc));\n    });\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\nexport function initScrollObserver({\n  scrollCb,\n  doc,\n  mirror,\n  blockClass,\n  blockSelector,\n  sampling,\n}: Pick<\n  observerParam,\n  'scrollCb' | 'doc' | 'mirror' | 'blockClass' | 'blockSelector' | 'sampling'\n>): listenerHandler {\n  const updatePosition = callbackWrapper(\n    throttle<UIEvent>(\n      callbackWrapper((evt) => {\n        const target = getEventTarget(evt);\n        if (\n          !target ||\n          isBlocked(target as Node, blockClass, blockSelector, true)\n        ) {\n          return;\n        }\n        const id = mirror.getId(target as Node);\n        if (target === doc && doc.defaultView) {\n          const scrollLeftTop = getWindowScroll(doc.defaultView);\n          scrollCb({\n            id,\n            x: scrollLeftTop.left,\n            y: scrollLeftTop.top,\n          });\n        } else {\n          scrollCb({\n            id,\n            x: (target as HTMLElement).scrollLeft,\n            y: (target as HTMLElement).scrollTop,\n          });\n        }\n      }),\n      sampling.scroll || 100,\n    ),\n  );\n  return on('scroll', updatePosition, doc);\n}\n\nfunction initViewportResizeObserver(\n  { viewportResizeCb }: observerParam,\n  { win }: { win: IWindow },\n): listenerHandler {\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}\n\nexport function findAndRemoveIframeBuffer(iframeEl: HTMLIFrameElement) {\n  for (let i = mutationBuffers.length - 1; i >= 0; i--) {\n    const buf = mutationBuffers[i];\n    if (buf.bufferBelongsToIframe(iframeEl)) {\n      buf.reset();\n      mutationBuffers.splice(i, 1);\n    }\n  }\n}\n\nexport const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap: WeakMap<EventTarget, inputValue> = new WeakMap();\nfunction initInputObserver({\n  inputCb,\n  doc,\n  mirror,\n  blockClass,\n  blockSelector,\n  ignoreClass,\n  ignoreSelector,\n  maskInputOptions,\n  maskInputFn,\n  sampling,\n  userTriggeredOnInput,\n}: observerParam): listenerHandler {\n  function eventHandler(event: Event) {\n    let target = getEventTarget(event) as HTMLElement | null;\n    const userTriggered = event.isTrusted;\n    const tagName = target && target.tagName;\n\n    /**\n     * If a site changes the value 'selected' of an option element, the value of its parent element, usually a select element, will be changed as well.\n     * We can treat this change as a value change of the select element the current target belongs to.\n     */\n    if (target && tagName === 'OPTION') {\n      target = dom.parentElement(target);\n    }\n    if (\n      !target ||\n      !tagName ||\n      INPUT_TAGS.indexOf(tagName) < 0 ||\n      isBlocked(target as Node, blockClass, blockSelector, true)\n    ) {\n      return;\n    }\n\n    if (\n      target.classList.contains(ignoreClass) ||\n      (ignoreSelector && target.matches(ignoreSelector))\n    ) {\n      return;\n    }\n    let text = (target as HTMLInputElement).value;\n    let isChecked = false;\n    const type: Lowercase<string> = getInputType(target) || '';\n\n    if (type === 'radio' || type === 'checkbox') {\n      isChecked = (target as HTMLInputElement).checked;\n    } else if (\n      maskInputOptions[tagName.toLowerCase() as keyof MaskInputOptions] ||\n      maskInputOptions[type as keyof MaskInputOptions]\n    ) {\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\n        ? { text, isChecked, userTriggered }\n        : { text, isChecked },\n    );\n    // if a radio was checked\n    // the other radios with the same name attribute will be unchecked.\n    const name: string | undefined = (target as HTMLInputElement).name;\n    if (type === 'radio' && name && isChecked) {\n      doc\n        .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n        .forEach((el) => {\n          if (el !== target) {\n            const text = (el as HTMLInputElement).value;\n            cbWithDedup(\n              el,\n              userTriggeredOnInput\n                ? { text, isChecked: !isChecked, userTriggered: false }\n                : { text, isChecked: !isChecked },\n            );\n          }\n        });\n    }\n  }\n  function cbWithDedup(target: EventTarget, v: inputValue) {\n    const lastInputValue = lastInputValueMap.get(target);\n    if (\n      !lastInputValue ||\n      lastInputValue.text !== v.text ||\n      lastInputValue.isChecked !== v.isChecked\n    ) {\n      lastInputValueMap.set(target, v);\n      const id = mirror.getId(target as Node);\n      callbackWrapper(inputCb)({\n        ...v,\n        id,\n      });\n    }\n  }\n  const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n  const handlers: Array<listenerHandler | hookResetter> = 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: Array<[HTMLElement, string]> = [\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((p) =>\n        hookSetter<HTMLElement>(\n          p[0],\n          p[1],\n          {\n            set() {\n              // mock to a normal event\n              callbackWrapper(eventHandler)({\n                target: this as EventTarget,\n                isTrusted: false, // userTriggered to false as this could well be programmatic\n              } as Event);\n            },\n          },\n          false,\n          currentWindow,\n        ),\n      ),\n    );\n  }\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\ntype GroupingCSSRule =\n  | CSSGroupingRule\n  | CSSMediaRule\n  | CSSSupportsRule\n  | CSSConditionRule;\ntype GroupingCSSRuleTypes =\n  | typeof CSSGroupingRule\n  | typeof CSSMediaRule\n  | typeof CSSSupportsRule\n  | typeof CSSConditionRule;\n\nfunction getNestedCSSRulePositions(rule: CSSRule): number[] {\n  const positions: number[] = [];\n  function recurse(childRule: CSSRule, pos: number[]) {\n    if (\n      (hasNestedCSSRule('CSSGroupingRule') &&\n        childRule.parentRule instanceof CSSGroupingRule) ||\n      (hasNestedCSSRule('CSSMediaRule') &&\n        childRule.parentRule instanceof CSSMediaRule) ||\n      (hasNestedCSSRule('CSSSupportsRule') &&\n        childRule.parentRule instanceof CSSSupportsRule) ||\n      (hasNestedCSSRule('CSSConditionRule') &&\n        childRule.parentRule instanceof CSSConditionRule)\n    ) {\n      const rules = Array.from(\n        (childRule.parentRule as GroupingCSSRule).cssRules,\n      );\n      const index = rules.indexOf(childRule);\n      pos.unshift(index);\n      return recurse(childRule.parentRule, pos);\n    } else if (childRule.parentStyleSheet) {\n      const rules = Array.from(childRule.parentStyleSheet.cssRules);\n      const index = rules.indexOf(childRule);\n      pos.unshift(index);\n    }\n    return pos;\n  }\n  return recurse(rule, positions);\n}\n\n/**\n * For StyleSheets in Element, this function retrieves id of its host element.\n * For adopted StyleSheets, this function retrieves its styleId from a styleMirror.\n */\nfunction getIdAndStyleId(\n  sheet: CSSStyleSheet | undefined | null,\n  mirror: Mirror,\n  styleMirror: StyleSheetMirror,\n): {\n  styleId?: number;\n  id?: number;\n} {\n  let id, styleId;\n  if (!sheet) return {};\n  if (sheet.ownerNode) id = mirror.getId(sheet.ownerNode as Node);\n  else styleId = styleMirror.getId(sheet);\n  return {\n    styleId,\n    id,\n  };\n}\n\nfunction initStyleSheetObserver(\n  { styleSheetRuleCb, mirror, stylesheetManager }: observerParam,\n  { win }: { win: IWindow },\n): listenerHandler {\n  if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n    // If, for whatever reason, CSSStyleSheet is not available, we skip the observation of stylesheets.\n    return () => {\n      // Do nothing\n    };\n  }\n\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const insertRule = win.CSSStyleSheet.prototype.insertRule;\n  win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n    apply: callbackWrapper(\n      (\n        target: typeof insertRule,\n        thisArg: CSSStyleSheet,\n        argumentsList: [string, number | undefined],\n      ) => {\n        const [rule, index] = argumentsList;\n\n        const { id, styleId } = getIdAndStyleId(\n          thisArg,\n          mirror,\n          stylesheetManager.styleMirror,\n        );\n\n        if ((id && id !== -1) || (styleId && styleId !== -1)) {\n          styleSheetRuleCb({\n            id,\n            styleId,\n            adds: [{ rule, index }],\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      },\n    ),\n  });\n\n  // Support for deprecated addRule method\n  win.CSSStyleSheet.prototype.addRule = function (\n    this: CSSStyleSheet,\n    selector: string,\n    styleBlock: string,\n    index: number = this.cssRules.length,\n  ) {\n    const rule = `${selector} { ${styleBlock} }`;\n    return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule, index]);\n  };\n\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n  win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n    apply: callbackWrapper(\n      (\n        target: typeof deleteRule,\n        thisArg: CSSStyleSheet,\n        argumentsList: [number],\n      ) => {\n        const [index] = argumentsList;\n\n        const { id, styleId } = getIdAndStyleId(\n          thisArg,\n          mirror,\n          stylesheetManager.styleMirror,\n        );\n\n        if ((id && id !== -1) || (styleId && styleId !== -1)) {\n          styleSheetRuleCb({\n            id,\n            styleId,\n            removes: [{ index }],\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      },\n    ),\n  });\n\n  // Support for deprecated removeRule method\n  win.CSSStyleSheet.prototype.removeRule = function (\n    this: CSSStyleSheet,\n    index: number,\n  ) {\n    return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index]);\n  };\n\n  let replace: (text: string) => Promise<CSSStyleSheet>;\n\n  if (win.CSSStyleSheet.prototype.replace) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    replace = win.CSSStyleSheet.prototype.replace;\n    win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n      apply: callbackWrapper(\n        (\n          target: typeof replace,\n          thisArg: CSSStyleSheet,\n          argumentsList: [string],\n        ) => {\n          const [text] = argumentsList;\n\n          const { id, styleId } = getIdAndStyleId(\n            thisArg,\n            mirror,\n            stylesheetManager.styleMirror,\n          );\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\n  let replaceSync: (text: string) => void;\n  if (win.CSSStyleSheet.prototype.replaceSync) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n    win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n      apply: callbackWrapper(\n        (\n          target: typeof replaceSync,\n          thisArg: CSSStyleSheet,\n          argumentsList: [string],\n        ) => {\n          const [text] = argumentsList;\n\n          const { id, styleId } = getIdAndStyleId(\n            thisArg,\n            mirror,\n            stylesheetManager.styleMirror,\n          );\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\n  const supportedNestedCSSRuleTypes: {\n    [key: string]: GroupingCSSRuleTypes;\n  } = {};\n  if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n    supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n  } else {\n    // Some browsers (Safari) don't support CSSGroupingRule\n    // https://caniuse.com/?search=cssgroupingrule\n    // fall back to monkey patching classes that would have inherited from CSSGroupingRule\n\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\n  const unmodifiedFunctions: {\n    [key: string]: {\n      insertRule: (rule: string, index?: number) => number;\n      deleteRule: (index: number) => void;\n    };\n  } = {};\n\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\n    type.prototype.insertRule = new Proxy(\n      unmodifiedFunctions[typeKey].insertRule,\n      {\n        apply: callbackWrapper(\n          (\n            target: typeof insertRule,\n            thisArg: CSSRule,\n            argumentsList: [string, number | undefined],\n          ) => {\n            const [rule, index] = argumentsList;\n\n            const { id, styleId } = getIdAndStyleId(\n              thisArg.parentStyleSheet,\n              mirror,\n              stylesheetManager.styleMirror,\n            );\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                      index || 0, // defaults to 0\n                    ],\n                  },\n                ],\n              });\n            }\n            return target.apply(thisArg, argumentsList);\n          },\n        ),\n      },\n    );\n\n    type.prototype.deleteRule = new Proxy(\n      unmodifiedFunctions[typeKey].deleteRule,\n      {\n        apply: callbackWrapper(\n          (\n            target: typeof deleteRule,\n            thisArg: CSSRule,\n            argumentsList: [number],\n          ) => {\n            const [index] = argumentsList;\n\n            const { id, styleId } = getIdAndStyleId(\n              thisArg.parentStyleSheet,\n              mirror,\n              stylesheetManager.styleMirror,\n            );\n\n            if ((id && id !== -1) || (styleId && styleId !== -1)) {\n              styleSheetRuleCb({\n                id,\n                styleId,\n                removes: [\n                  { index: [...getNestedCSSRulePositions(thisArg), index] },\n                ],\n              });\n            }\n            return target.apply(thisArg, argumentsList);\n          },\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}\n\nexport function initAdoptedStyleSheetObserver(\n  {\n    mirror,\n    stylesheetManager,\n  }: Pick<observerParam, 'mirror' | 'stylesheetManager'>,\n  host: Document | ShadowRoot,\n): listenerHandler {\n  let hostId: number | null = null;\n  // host of adoptedStyleSheets is outermost document or IFrame's document\n  if (host.nodeName === '#document') hostId = mirror.getId(host);\n  // The host is a ShadowRoot.\n  else hostId = mirror.getId(dom.host(host as ShadowRoot));\n\n  const patchTarget =\n    host.nodeName === '#document'\n      ? (host as Document).defaultView?.Document\n      : host.ownerDocument?.defaultView?.ShadowRoot;\n  const originalPropertyDescriptor = patchTarget?.prototype\n    ? Object.getOwnPropertyDescriptor(\n        patchTarget?.prototype,\n        'adoptedStyleSheets',\n      )\n    : undefined;\n  if (\n    hostId === null ||\n    hostId === -1 ||\n    !patchTarget ||\n    !originalPropertyDescriptor\n  )\n    return () => {\n      //\n    };\n\n  // Patch adoptedStyleSheets by overriding the original one.\n  Object.defineProperty(host, 'adoptedStyleSheets', {\n    configurable: originalPropertyDescriptor.configurable,\n    enumerable: originalPropertyDescriptor.enumerable,\n    get(): CSSStyleSheet[] {\n      return originalPropertyDescriptor.get?.call(this) as CSSStyleSheet[];\n    },\n    set(sheets: CSSStyleSheet[]) {\n      const result = originalPropertyDescriptor.set?.call(this, sheets);\n      if (hostId !== null && hostId !== -1) {\n        try {\n          stylesheetManager.adoptStyleSheets(sheets, hostId);\n        } catch (e) {\n          // for safety\n        }\n      }\n      return result;\n    },\n  });\n\n  return callbackWrapper(() => {\n    Object.defineProperty(host, '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}\n\nfunction initStyleDeclarationObserver(\n  {\n    styleDeclarationCb,\n    mirror,\n    ignoreCSSAttributes,\n    stylesheetManager,\n  }: observerParam,\n  { win }: { win: IWindow },\n): listenerHandler {\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n  win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n    apply: callbackWrapper(\n      (\n        target: typeof setProperty,\n        thisArg: CSSStyleDeclaration,\n        argumentsList: [string, string, string],\n      ) => {\n        const [property, value, priority] = argumentsList;\n\n        // ignore this mutation if we do not care about this css attribute\n        if (ignoreCSSAttributes.has(property)) {\n          return setProperty.apply(thisArg, [property, value, priority]);\n        }\n        const { id, styleId } = getIdAndStyleId(\n          thisArg.parentRule?.parentStyleSheet,\n          mirror,\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\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n  win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n    apply: callbackWrapper(\n      (\n        target: typeof removeProperty,\n        thisArg: CSSStyleDeclaration,\n        argumentsList: [string],\n      ) => {\n        const [property] = argumentsList;\n\n        // ignore this mutation if we do not care about this css attribute\n        if (ignoreCSSAttributes.has(property)) {\n          return removeProperty.apply(thisArg, [property]);\n        }\n        const { id, styleId } = getIdAndStyleId(\n          thisArg.parentRule?.parentStyleSheet,\n          mirror,\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\n  return callbackWrapper(() => {\n    win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n    win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n  });\n}\n\nfunction initMediaInteractionObserver({\n  mediaInteractionCb,\n  blockClass,\n  blockSelector,\n  mirror,\n  sampling,\n  doc,\n}: observerParam): listenerHandler {\n  const handler = callbackWrapper((type: MediaInteractions) =>\n    throttle(\n      callbackWrapper((event: Event) => {\n        const target = getEventTarget(event);\n        if (\n          !target ||\n          isBlocked(target as Node, blockClass, blockSelector, true)\n        ) {\n          return;\n        }\n        const { currentTime, volume, muted, playbackRate, loop } =\n          target as HTMLMediaElement;\n        mediaInteractionCb({\n          type,\n          id: mirror.getId(target as Node),\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}\n\nfunction initFontObserver({ fontCb, doc }: observerParam): listenerHandler {\n  const win = doc.defaultView as IWindow;\n  if (!win) {\n    return () => {\n      //\n    };\n  }\n\n  const handlers: listenerHandler[] = [];\n\n  const fontMap = new WeakMap<FontFace, fontParam>();\n\n  const originalFontFace = win.FontFace;\n  win.FontFace = function FontFace(\n    family: string,\n    source: string | ArrayBufferLike,\n    descriptors?: FontFaceDescriptors,\n  ) {\n    const fontFace = new originalFontFace(\n      family,\n      source as string | BufferSource,\n      descriptors,\n    );\n    fontMap.set(fontFace, {\n      family,\n      buffer: typeof source !== 'string',\n      descriptors,\n      fontSource:\n        typeof source === 'string'\n          ? source\n          : JSON.stringify(Array.from(new Uint8Array(source))),\n    });\n    return fontFace;\n  } as unknown as typeof FontFace;\n\n  const restoreHandler = patch(\n    doc.fonts,\n    'add',\n    function (original: (font: FontFace) => void) {\n      return function (this: FontFaceSet, fontFace: 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\n  handlers.push(() => {\n    win.FontFace = originalFontFace;\n  });\n  handlers.push(restoreHandler);\n\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\nfunction initSelectionObserver(param: observerParam): listenerHandler {\n  const { doc, mirror, blockClass, blockSelector, selectionCb } = param;\n  let collapsed = true;\n\n  const updateSelection = callbackWrapper(() => {\n    const selection = doc.getSelection();\n\n    if (!selection || (collapsed && selection?.isCollapsed)) return;\n\n    collapsed = selection.isCollapsed || false;\n\n    const ranges: SelectionRange[] = [];\n    const count = selection.rangeCount || 0;\n\n    for (let i = 0; i < count; i++) {\n      const range = selection.getRangeAt(i);\n\n      const { startContainer, startOffset, endContainer, endOffset } = range;\n\n      const blocked =\n        isBlocked(startContainer, blockClass, blockSelector, true) ||\n        isBlocked(endContainer, blockClass, blockSelector, true);\n\n      if (blocked) continue;\n\n      ranges.push({\n        start: mirror.getId(startContainer),\n        startOffset,\n        end: mirror.getId(endContainer),\n        endOffset,\n      });\n    }\n\n    selectionCb({ ranges });\n  });\n\n  updateSelection();\n\n  return on('selectionchange', updateSelection);\n}\n\nfunction initCustomElementObserver({\n  doc,\n  customElementCb,\n}: observerParam): listenerHandler {\n  const win = doc.defaultView as IWindow;\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  if (!win || !win.customElements) return () => {};\n  const restoreHandler = patch(\n    win.customElements,\n    'define',\n    function (\n      original: (\n        name: string,\n        constructor: CustomElementConstructor,\n        options?: ElementDefinitionOptions,\n      ) => void,\n    ) {\n      return function (\n        name: string,\n        constructor: CustomElementConstructor,\n        options?: ElementDefinitionOptions,\n      ) {\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}\n\nfunction mergeHooks(o: observerParam, hooks: hooksParam) {\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: Arguments<mutationCallBack>) => {\n    if (hooks.mutation) {\n      hooks.mutation(...p);\n    }\n    mutationCb(...p);\n  };\n  o.mousemoveCb = (...p: Arguments<mousemoveCallBack>) => {\n    if (hooks.mousemove) {\n      hooks.mousemove(...p);\n    }\n    mousemoveCb(...p);\n  };\n  o.mouseInteractionCb = (...p: Arguments<mouseInteractionCallBack>) => {\n    if (hooks.mouseInteraction) {\n      hooks.mouseInteraction(...p);\n    }\n    mouseInteractionCb(...p);\n  };\n  o.scrollCb = (...p: Arguments<scrollCallback>) => {\n    if (hooks.scroll) {\n      hooks.scroll(...p);\n    }\n    scrollCb(...p);\n  };\n  o.viewportResizeCb = (...p: Arguments<viewportResizeCallback>) => {\n    if (hooks.viewportResize) {\n      hooks.viewportResize(...p);\n    }\n    viewportResizeCb(...p);\n  };\n  o.inputCb = (...p: Arguments<inputCallback>) => {\n    if (hooks.input) {\n      hooks.input(...p);\n    }\n    inputCb(...p);\n  };\n  o.mediaInteractionCb = (...p: Arguments<mediaInteractionCallback>) => {\n    if (hooks.mediaInteaction) {\n      hooks.mediaInteaction(...p);\n    }\n    mediaInteractionCb(...p);\n  };\n  o.styleSheetRuleCb = (...p: Arguments<styleSheetRuleCallback>) => {\n    if (hooks.styleSheetRule) {\n      hooks.styleSheetRule(...p);\n    }\n    styleSheetRuleCb(...p);\n  };\n  o.styleDeclarationCb = (...p: Arguments<styleDeclarationCallback>) => {\n    if (hooks.styleDeclaration) {\n      hooks.styleDeclaration(...p);\n    }\n    styleDeclarationCb(...p);\n  };\n  o.canvasMutationCb = (...p: Arguments<canvasMutationCallback>) => {\n    if (hooks.canvasMutation) {\n      hooks.canvasMutation(...p);\n    }\n    canvasMutationCb(...p);\n  };\n  o.fontCb = (...p: Arguments<fontCallback>) => {\n    if (hooks.font) {\n      hooks.font(...p);\n    }\n    fontCb(...p);\n  };\n  o.selectionCb = (...p: Arguments<selectionCallback>) => {\n    if (hooks.selection) {\n      hooks.selection(...p);\n    }\n    selectionCb(...p);\n  };\n  o.customElementCb = (...c: Arguments<customElementCallback>) => {\n    if (hooks.customElement) {\n      hooks.customElement(...c);\n    }\n    customElementCb(...c);\n  };\n}\n\nexport function initObservers(\n  o: observerParam,\n  hooks: hooksParam = {},\n): listenerHandler {\n  const currentWindow = o.doc.defaultView; // basically document.window\n  if (!currentWindow) {\n    return () => {\n      //\n    };\n  }\n\n  mergeHooks(o, hooks);\n  let mutationObserver: MutationObserver | undefined;\n  let mutationBuffer: MutationBuffer | undefined;\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\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let styleSheetObserver = () => {};\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let adoptedStyleSheetObserver = () => {};\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let styleDeclarationObserver = () => {};\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let fontObserver = () => {};\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\n  // plugins\n  const pluginHandlers: listenerHandler[] = [];\n  for (const plugin of o.plugins) {\n    pluginHandlers.push(\n      plugin.observer(plugin.callback, currentWindow, plugin.options),\n    );\n  }\n\n  return callbackWrapper(() => {\n    // Clean up this observer's mutation buffer\n    if (mutationBuffer) {\n      mutationBuffer.destroy();\n      mutationBuffer.reset();\n      // Remove only this buffer from the global array\n      const index = mutationBuffers.indexOf(mutationBuffer);\n      if (index !== -1) {\n        mutationBuffers.splice(index, 1);\n      }\n    }\n    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}\n\ntype CSSGroupingProp =\n  | 'CSSGroupingRule'\n  | 'CSSMediaRule'\n  | 'CSSSupportsRule'\n  | 'CSSConditionRule';\n\nfunction hasNestedCSSRule(prop: CSSGroupingProp): boolean {\n  return typeof window[prop] !== 'undefined';\n}\n\nfunction canMonkeyPatchNestedCSSRule(prop: CSSGroupingProp): boolean {\n  return Boolean(\n    typeof window[prop] !== 'undefined' &&\n      // 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 &&\n      'insertRule' in window[prop].prototype &&\n      'deleteRule' in window[prop].prototype,\n  );\n}\n", "import type { ICrossOriginIframeMirror } from '@posthog/rrweb-types';\nexport default class CrossOriginIframeMirror\n  implements ICrossOriginIframeMirror\n{\n  private iframeIdToRemoteIdMap: WeakMap<\n    HTMLIFrameElement,\n    Map<number, number>\n  > = new WeakMap();\n  private iframeRemoteIdToIdMap: WeakMap<\n    HTMLIFrameElement,\n    Map<number, number>\n  > = new WeakMap();\n\n  constructor(private generateIdFn: () => number) {}\n\n  getId(\n    iframe: HTMLIFrameElement,\n    remoteId: number,\n    idToRemoteMap?: Map<number, number>,\n    remoteToIdMap?: Map<number, number>,\n  ): number {\n    const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n    const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n\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\n  getIds(iframe: HTMLIFrameElement, remoteId: number[]): number[] {\n    const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n    return remoteId.map((id) =>\n      this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap),\n    );\n  }\n\n  getRemoteId(\n    iframe: HTMLIFrameElement,\n    id: number,\n    map?: Map<number, number>,\n  ): number {\n    const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n\n    if (typeof id !== 'number') return id;\n\n    const remoteId = remoteIdToIdMap.get(id);\n    if (!remoteId) return -1;\n    return remoteId;\n  }\n\n  getRemoteIds(iframe: HTMLIFrameElement, ids: number[]): number[] {\n    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n\n    return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n  }\n\n  reset(iframe?: HTMLIFrameElement) {\n    if (!iframe) {\n      this.iframeIdToRemoteIdMap = new WeakMap();\n      this.iframeRemoteIdToIdMap = new WeakMap();\n      return;\n    }\n    this.iframeIdToRemoteIdMap.delete(iframe);\n    this.iframeRemoteIdToIdMap.delete(iframe);\n  }\n\n  private getIdToRemoteIdMap(iframe: HTMLIFrameElement) {\n    let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n    if (!idToRemoteIdMap) {\n      idToRemoteIdMap = new Map();\n      this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n    }\n    return idToRemoteIdMap;\n  }\n\n  private getRemoteIdToIdMap(iframe: HTMLIFrameElement) {\n    let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n    if (!remoteIdToIdMap) {\n      remoteIdToIdMap = new Map();\n      this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n    }\n    return remoteIdToIdMap;\n  }\n}\n", "import type { Mirror } from '@posthog/rrweb-snapshot';\nimport { genId } from '@posthog/rrweb-snapshot';\nimport type { CrossOriginIframeMessageEvent } from '../types';\nimport { callSafely } from '../utils';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror';\nimport { EventType, NodeType, IncrementalSource } from '@posthog/rrweb-types';\nimport type {\n  eventWithTime,\n  eventWithoutTime,\n  serializedNodeWithId,\n  mutationCallBack,\n} from '@posthog/rrweb-types';\nimport type { StylesheetManager } from './stylesheet-manager';\n\nexport class IframeManager {\n  private iframes: WeakMap<HTMLIFrameElement, true> = new WeakMap();\n  private crossOriginIframeMap: WeakMap<MessageEventSource, HTMLIFrameElement> =\n    new WeakMap();\n  public crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n  public crossOriginIframeStyleMirror: CrossOriginIframeMirror;\n  public crossOriginIframeRootIdMap: WeakMap<HTMLIFrameElement, number> =\n    new WeakMap();\n  private mirror: Mirror;\n  private mutationCb: mutationCallBack;\n  private wrappedEmit: (e: eventWithoutTime, isCheckout?: boolean) => void;\n  private loadListener?: (iframeEl: HTMLIFrameElement) => unknown;\n  private pageHideListener?: (iframeEl: HTMLIFrameElement) => unknown;\n  private stylesheetManager: StylesheetManager;\n  private recordCrossOriginIframes: boolean;\n  private messageHandler: (message: MessageEvent) => void;\n  // Map window to handler for cleanup - windows are browser-owned and won't prevent GC\n  private nestedIframeListeners: Map<Window, (message: MessageEvent) => void> =\n    new Map();\n  private attachedIframes: Map<\n    number,\n    { element: HTMLIFrameElement; content: serializedNodeWithId }\n  > = new Map();\n\n  constructor(options: {\n    mirror: Mirror;\n    mutationCb: mutationCallBack;\n    stylesheetManager: StylesheetManager;\n    recordCrossOriginIframes: boolean;\n    wrappedEmit: (e: eventWithoutTime, isCheckout?: boolean) => void;\n  }) {\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\n  public addIframe(iframeEl: HTMLIFrameElement) {\n    this.iframes.set(iframeEl, true);\n    if (iframeEl.contentWindow)\n      this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n  }\n\n  public addLoadListener(cb: (iframeEl: HTMLIFrameElement) => unknown) {\n    this.loadListener = cb;\n  }\n\n  public addPageHideListener(cb: (iframeEl: HTMLIFrameElement) => unknown) {\n    this.pageHideListener = cb;\n  }\n\n  public removeLoadListener() {\n    this.loadListener = undefined;\n  }\n\n  private trackIframeContent(\n    iframeEl: HTMLIFrameElement,\n    content: serializedNodeWithId,\n  ): number {\n    const iframeId = this.mirror.getId(iframeEl);\n    this.attachedIframes.set(iframeId, { element: iframeEl, content });\n    return iframeId;\n  }\n\n  public attachIframe(\n    iframeEl: HTMLIFrameElement,\n    childSn: serializedNodeWithId,\n  ) {\n    const iframeId = this.trackIframeContent(iframeEl, childSn);\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\n    // Receive messages (events) coming from cross-origin iframes that are nested in this same-origin iframe.\n    const win = iframeEl.contentWindow;\n    if (\n      this.recordCrossOriginIframes &&\n      win &&\n      !this.nestedIframeListeners.has(win)\n    ) {\n      const nestedHandler = this.handleMessage.bind(this);\n      this.nestedIframeListeners.set(win, nestedHandler);\n      win.addEventListener('message', nestedHandler);\n    }\n\n    iframeEl.contentWindow?.addEventListener('pagehide', () => {\n      this.pageHideListener?.(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\n    this.loadListener?.(iframeEl);\n\n    if (\n      iframeEl.contentDocument &&\n      iframeEl.contentDocument.adoptedStyleSheets &&\n      iframeEl.contentDocument.adoptedStyleSheets.length > 0\n    )\n      this.stylesheetManager.adoptStyleSheets(\n        iframeEl.contentDocument.adoptedStyleSheets,\n        this.mirror.getId(iframeEl.contentDocument),\n      );\n  }\n  private handleMessage(message: MessageEvent | CrossOriginIframeMessageEvent) {\n    const crossOriginMessageEvent = message as CrossOriginIframeMessageEvent;\n    if (\n      crossOriginMessageEvent.data.type !== 'rrweb' ||\n      // To filter out the rrweb messages which are forwarded by some sites.\n      crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin\n    )\n      return;\n\n    const iframeSourceWindow = message.source;\n    if (!iframeSourceWindow) return;\n\n    const iframeEl = this.crossOriginIframeMap.get(message.source);\n    if (!iframeEl) return;\n\n    const transformedEvent = this.transformCrossOriginEvent(\n      iframeEl,\n      crossOriginMessageEvent.data.event,\n    );\n\n    if (transformedEvent)\n      this.wrappedEmit(\n        transformedEvent,\n        crossOriginMessageEvent.data.isCheckout,\n      );\n  }\n\n  private transformCrossOriginEvent(\n    iframeEl: HTMLIFrameElement,\n    e: eventWithTime,\n  ): eventWithTime | false {\n    switch (e.type) {\n      case EventType.FullSnapshot: {\n        this.crossOriginIframeMirror.reset(iframeEl);\n        this.crossOriginIframeStyleMirror.reset(iframeEl);\n        /**\n         * Replaces the original id of the iframe with a new set of unique ids\n         */\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 as {\n            id?: unknown;\n            parentId?: unknown;\n            previousId?: unknown;\n            nextId?: unknown;\n          },\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            // can safely ignore these events\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            // fine as-is no modification needed\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            e.data.styles?.forEach((style) => {\n              this.replaceStyleIds(style, iframeEl, ['styleId']);\n            });\n            return e;\n          }\n        }\n      }\n    }\n    return false;\n  }\n\n  private replace<T extends Record<string, unknown>>(\n    iframeMirror: CrossOriginIframeMirror,\n    obj: T,\n    iframeEl: HTMLIFrameElement,\n    keys: Array<keyof T>,\n  ): T {\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] as number[],\n        ) as T[keyof T];\n      } else {\n        (obj[key] as number) = iframeMirror.getId(iframeEl, obj[key] as number);\n      }\n    }\n\n    return obj;\n  }\n\n  private replaceIds<T extends Record<string, unknown>>(\n    obj: T,\n    iframeEl: HTMLIFrameElement,\n    keys: Array<keyof T>,\n  ): T {\n    return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n  }\n\n  private replaceStyleIds<T extends Record<string, unknown>>(\n    obj: T,\n    iframeEl: HTMLIFrameElement,\n    keys: Array<keyof T>,\n  ): T {\n    return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n  }\n\n  private replaceIdOnNode(\n    node: serializedNodeWithId,\n    iframeEl: HTMLIFrameElement,\n  ) {\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\n  private patchRootIdOnNode(node: serializedNodeWithId, rootId: number) {\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\n  public removeIframeById(iframeId: number) {\n    const entry = this.attachedIframes.get(iframeId);\n    const iframe =\n      entry?.element ||\n      (this.mirror.getNode(iframeId) as HTMLIFrameElement | null);\n\n    if (iframe) {\n      const win = iframe.contentWindow;\n\n      // Clean up nested iframe listeners if they exist\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\n      // Clean up WeakMaps to allow GC of the iframe element\n      if (win) {\n        this.crossOriginIframeMap.delete(win);\n      }\n      this.iframes.delete(iframe);\n    }\n\n    // Always clean up attachedIframes if entry exists\n    if (entry) {\n      this.attachedIframes.delete(iframeId);\n    }\n  }\n\n  public reattachIframes() {\n    this.attachedIframes.forEach(({ content }, iframeId) => {\n      // Verify the iframe ID is still in the mirror (still being tracked by rrweb)\n      // If removed, the mirror would have been cleaned up via removeNodeFromMap()\n      if (!this.mirror.has(iframeId)) {\n        this.attachedIframes.delete(iframeId);\n        return;\n      }\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\n  public destroy() {\n    if (this.recordCrossOriginIframes) {\n      window.removeEventListener('message', this.messageHandler);\n    }\n\n    // Clean up nested iframe listeners\n    this.nestedIframeListeners.forEach((handler, contentWindow) => {\n      callSafely(() => contentWindow.removeEventListener('message', handler));\n    });\n    this.nestedIframeListeners.clear();\n\n    this.crossOriginIframeMirror.reset();\n    this.crossOriginIframeStyleMirror.reset();\n    this.attachedIframes.clear();\n\n    this.crossOriginIframeMap = new WeakMap();\n    this.iframes = new WeakMap();\n    this.crossOriginIframeRootIdMap = new WeakMap();\n  }\n}\n", "import type { MutationBufferParam } from '../types';\nimport type {\n  mutationCallBack,\n  scrollCallback,\n  SamplingStrategy,\n} from '@posthog/rrweb-types';\nimport {\n  initMutationObserver,\n  initScrollObserver,\n  initAdoptedStyleSheetObserver,\n  mutationBuffers,\n} from './observer';\nimport { inDom } from '../utils';\nimport type { Mirror } from '@posthog/rrweb-snapshot';\nimport { isNativeShadowDom } from '@posthog/rrweb-snapshot';\nimport dom, { patch } from '@posthog/rrweb-utils';\n\ntype BypassOptions = Omit<\n  MutationBufferParam,\n  'doc' | 'mutationCb' | 'mirror' | 'shadowDomManager'\n> & {\n  sampling: SamplingStrategy;\n};\n\nexport class ShadowDomManager {\n  private shadowDoms = new WeakSet<ShadowRoot>();\n  private mutationCb: mutationCallBack;\n  private scrollCb: scrollCallback;\n  private bypassOptions: BypassOptions;\n  private mirror: Mirror;\n  private restoreHandlers: (() => void)[] = [];\n\n  constructor(options: {\n    mutationCb: mutationCallBack;\n    scrollCb: scrollCallback;\n    bypassOptions: BypassOptions;\n    mirror: Mirror;\n  }) {\n    this.mutationCb = options.mutationCb;\n    this.scrollCb = options.scrollCb;\n    this.bypassOptions = options.bypassOptions;\n    this.mirror = options.mirror;\n\n    this.init();\n  }\n\n  public init() {\n    this.reset();\n    // Patch 'attachShadow' to observe newly added shadow doms.\n    this.patchAttachShadow(Element, document);\n  }\n\n  public addShadowRoot(shadowRoot: ShadowRoot, doc: Document) {\n    if (!isNativeShadowDom(shadowRoot)) return;\n    if (this.shadowDoms.has(shadowRoot)) return;\n    this.shadowDoms.add(shadowRoot);\n    const { observer, buffer } = initMutationObserver(\n      {\n        ...this.bypassOptions,\n        doc,\n        mutationCb: this.mutationCb,\n        mirror: this.mirror,\n        shadowDomManager: this,\n      },\n      shadowRoot,\n    );\n    this.restoreHandlers.push(() => {\n      observer.disconnect();\n      buffer.destroy();\n      const index = mutationBuffers.indexOf(buffer);\n      if (index !== -1) {\n        mutationBuffers.splice(index, 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: shadowRoot as unknown as Document,\n        mirror: this.mirror,\n      }),\n    );\n    // Defer this to avoid adoptedStyleSheet events being created before the full snapshot is created or attachShadow action is recorded.\n    setTimeout(() => {\n      if (\n        shadowRoot.adoptedStyleSheets &&\n        shadowRoot.adoptedStyleSheets.length > 0\n      )\n        this.bypassOptions.stylesheetManager.adoptStyleSheets(\n          shadowRoot.adoptedStyleSheets,\n          this.mirror.getId(dom.host(shadowRoot)),\n        );\n      this.restoreHandlers.push(\n        initAdoptedStyleSheetObserver(\n          {\n            mirror: this.mirror,\n            stylesheetManager: this.bypassOptions.stylesheetManager,\n          },\n          shadowRoot,\n        ),\n      );\n    }, 0);\n  }\n\n  /**\n   * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n   */\n  public observeAttachShadow(iframeElement: HTMLIFrameElement) {\n    if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;\n\n    this.patchAttachShadow(\n      (\n        iframeElement.contentWindow as Window & {\n          Element: { prototype: Element };\n        }\n      ).Element,\n      iframeElement.contentDocument,\n    );\n  }\n\n  /**\n   * Patch 'attachShadow' to observe newly added shadow doms.\n   */\n  private patchAttachShadow(\n    element: {\n      prototype: Element;\n    },\n    doc: Document,\n  ) {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const manager = this;\n    this.restoreHandlers.push(\n      patch(\n        element.prototype,\n        'attachShadow',\n        function (original: (init: ShadowRootInit) => ShadowRoot) {\n          return function (this: Element, option: ShadowRootInit) {\n            const sRoot = original.call(this, option);\n            // For the shadow dom elements in the document, monitor their dom mutations.\n            // For shadow dom elements that aren't in the document yet,\n            // we start monitoring them once their shadow dom host is appended to the document.\n            const shadowRootEl = dom.shadowRoot(this);\n            if (shadowRootEl && inDom(this))\n              manager.addShadowRoot(shadowRootEl, doc);\n            return sRoot;\n          };\n        },\n      ),\n    );\n  }\n\n  public reset() {\n    this.restoreHandlers.forEach((handler) => {\n      try {\n        handler();\n      } catch (e) {\n        //\n      }\n    });\n    this.restoreHandlers = [];\n    this.shadowDoms = new WeakSet();\n  }\n}\n", "/*\n * base64-arraybuffer 1.0.2 <https://github.com/niklasvh/base64-arraybuffer>\n * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>\n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\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    }\n    else if (len % 3 === 1) {\n        base64 = base64.substring(0, base64.length - 2) + '==';\n    }\n    return base64;\n};\nvar decode = function (base64) {\n    var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n    if (base64[base64.length - 1] === '=') {\n        bufferLength--;\n        if (base64[base64.length - 2] === '=') {\n            bufferLength--;\n        }\n    }\n    var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n    for (i = 0; i < len; i += 4) {\n        encoded1 = lookup[base64.charCodeAt(i)];\n        encoded2 = lookup[base64.charCodeAt(i + 1)];\n        encoded3 = lookup[base64.charCodeAt(i + 2)];\n        encoded4 = lookup[base64.charCodeAt(i + 3)];\n        bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n        bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n        bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n    }\n    return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n", "import { encode } from 'base64-arraybuffer';\nimport type { IWindow, CanvasArg, DataURLOptions } from '@posthog/rrweb-types';\n\n// TODO: unify with `replay/webgl.ts`\ntype CanvasVarMap = Map<string, unknown[]>;\nconst canvasVarMap: Map<RenderingContext, CanvasVarMap> = new Map();\nexport function variableListFor(ctx: RenderingContext, ctor: string) {\n  let contextMap = canvasVarMap.get(ctx);\n  if (!contextMap) {\n    contextMap = new Map();\n    canvasVarMap.set(ctx, contextMap);\n  }\n  if (!contextMap.has(ctor)) {\n    contextMap.set(ctor, []);\n  }\n  return contextMap.get(ctor) as unknown[];\n}\n\nexport const saveWebGLVar = (\n  value: unknown,\n  win: IWindow,\n  ctx: RenderingContext,\n): number | void => {\n  if (\n    !value ||\n    !(isInstanceOfWebGLObject(value, win) || typeof value === 'object')\n  )\n    return;\n\n  const name = value.constructor.name;\n  const list = variableListFor(ctx, name);\n  let index = list.indexOf(value);\n\n  if (index === -1) {\n    index = list.length;\n    list.push(value);\n  }\n  return index;\n};\n\n// from webgl-recorder: https://github.com/evanw/webgl-recorder/blob/bef0e65596e981ee382126587e2dcbe0fc7748e2/webgl-recorder.js#L50-L77\nexport function serializeArg(\n  value: unknown,\n  win: IWindow,\n  ctx: RenderingContext,\n  dataURLOptions: DataURLOptions,\n): CanvasArg {\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 (\n    value instanceof Float32Array ||\n    value instanceof Float64Array ||\n    value instanceof Int32Array ||\n    value instanceof Uint32Array ||\n    value instanceof Uint8Array ||\n    value instanceof Uint16Array ||\n    value instanceof Int16Array ||\n    value instanceof Int8Array ||\n    value instanceof Uint8ClampedArray\n  ) {\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 as 'ArrayBuffer';\n    const base64 = encode(value);\n\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    // TODO: move `toDataURL` to web worker if possible\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 (value instanceof Blob) {\n    //   const name = value.constructor.name;\n    //   return {\n    //     rr_type: name,\n    //     data: [serializeArg(await value.arrayBuffer(), win, ctx, dataURLOptions)],\n    //     type: value.type,\n    //   };\n  } else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\n    const name = value.constructor.name;\n    const index = saveWebGLVar(value, win, ctx) as number;\n\n    return {\n      rr_type: name,\n      index: index,\n    };\n  }\n\n  return value as unknown as CanvasArg;\n}\n\nexport const serializeArgs = (\n  args: Array<unknown>,\n  win: IWindow,\n  ctx: RenderingContext,\n  dataURLOptions: DataURLOptions,\n) => {\n  return args.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n};\n\nexport const isInstanceOfWebGLObject = (\n  value: unknown,\n  win: IWindow,\n): value is\n  | WebGLActiveInfo\n  | WebGLBuffer\n  | WebGLFramebuffer\n  | WebGLProgram\n  | WebGLRenderbuffer\n  | WebGLShader\n  | WebGLShaderPrecisionFormat\n  | WebGLTexture\n  | WebGLUniformLocation\n  | WebGLVertexArrayObject => {\n  const webGLConstructorNames: string[] = [\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: string) => typeof win[name as keyof Window] === 'function',\n  );\n  return Boolean(\n    supportedWebGLConstructorNames.find(\n      (name: string) => value instanceof win[name as keyof Window],\n    ),\n  );\n};\n", "import {\n  type blockClass,\n  CanvasContext,\n  type canvasManagerMutationCallback,\n  type IWindow,\n  type listenerHandler,\n  type DataURLOptions,\n} from '@posthog/rrweb-types';\nimport { hookSetter, isBlocked } from '../../../utils';\nimport { patch } from '@posthog/rrweb-utils';\nimport { serializeArgs } from './serialize-args';\n\nexport default function initCanvas2DMutationObserver(\n  cb: canvasManagerMutationCallback,\n  win: IWindow,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  dataURLOptions: DataURLOptions,\n): listenerHandler {\n  const handlers: listenerHandler[] = [];\n  const props2D = Object.getOwnPropertyNames(\n    win.CanvasRenderingContext2D.prototype,\n  );\n  for (const prop of props2D) {\n    try {\n      if (\n        typeof win.CanvasRenderingContext2D.prototype[\n          prop as keyof CanvasRenderingContext2D\n        ] !== 'function'\n      ) {\n        continue;\n      }\n      const restoreHandler = patch(\n        win.CanvasRenderingContext2D.prototype,\n        prop,\n        function (\n          original: (\n            this: CanvasRenderingContext2D,\n            ...args: unknown[]\n          ) => void,\n        ) {\n          return function (\n            this: CanvasRenderingContext2D,\n            ...args: Array<unknown>\n          ) {\n            if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\n              // Using setTimeout as toDataURL can be heavy\n              // and we'd rather not block the main thread\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<CanvasRenderingContext2D>(\n        win.CanvasRenderingContext2D.prototype,\n        prop,\n        {\n          set(v) {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\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}\n", "import type { ICanvas } from '@posthog/rrweb-snapshot';\nimport type {\n  blockClass,\n  IWindow,\n  listenerHandler,\n} from '@posthog/rrweb-types';\nimport { isBlocked } from '../../../utils';\nimport { patch } from '@posthog/rrweb-utils';\n\nfunction getNormalizedContextName(contextType: string) {\n  return contextType === 'experimental-webgl' ? 'webgl' : contextType;\n}\n\nexport default function initCanvasContextObserver(\n  win: IWindow,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  setPreserveDrawingBufferToTrue: boolean,\n): listenerHandler {\n  const handlers: listenerHandler[] = [];\n  try {\n    const restoreHandler = patch(\n      win.HTMLCanvasElement.prototype,\n      'getContext',\n      function (\n        original: (\n          this: ICanvas | HTMLCanvasElement,\n          contextType: string,\n          ...args: Array<unknown>\n        ) => void,\n      ) {\n        return function (\n          this: ICanvas | HTMLCanvasElement,\n          contextType: string,\n          ...args: Array<unknown>\n        ) {\n          if (!isBlocked(this, blockClass, blockSelector, true)) {\n            const ctxName = getNormalizedContextName(contextType);\n            if (!('__context' in this)) (this as ICanvas).__context = ctxName;\n\n            if (\n              setPreserveDrawingBufferToTrue &&\n              ['webgl', 'webgl2'].includes(ctxName)\n            ) {\n              if (args[0] && typeof args[0] === 'object') {\n                const contextAttributes = args[0] as WebGLContextAttributes;\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}\n", "import {\n  type blockClass,\n  CanvasContext,\n  type canvasManagerMutationCallback,\n  type canvasMutationWithType,\n  type IWindow,\n  type listenerHandler,\n  type DataURLOptions,\n} from '@posthog/rrweb-types';\nimport { hookSetter, isBlocked } from '../../../utils';\nimport { patch } from '@posthog/rrweb-utils';\nimport { saveWebGLVar, serializeArgs } from './serialize-args';\n\nfunction patchGLPrototype(\n  prototype: WebGLRenderingContext | WebGL2RenderingContext,\n  type: CanvasContext,\n  cb: canvasManagerMutationCallback,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  win: IWindow,\n  dataURLOptions: DataURLOptions,\n): listenerHandler[] {\n  const handlers: listenerHandler[] = [];\n\n  const props = Object.getOwnPropertyNames(prototype);\n\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      // skip read only propery/functions\n      continue;\n    }\n    try {\n      if (typeof prototype[prop as keyof typeof prototype] !== 'function') {\n        continue;\n      }\n      const restoreHandler = patch(\n        prototype,\n        prop,\n        function (\n          original: (this: typeof prototype, ...args: Array<unknown>) => void,\n        ) {\n          return function (this: typeof prototype, ...args: Array<unknown>) {\n            const result = original.apply(this, args);\n            saveWebGLVar(result, win, this);\n            if (\n              'tagName' in this.canvas &&\n              !isBlocked(this.canvas, blockClass, blockSelector, true)\n            ) {\n              const recordArgs = serializeArgs(args, win, this, dataURLOptions);\n              const mutation: canvasMutationWithType = {\n                type,\n                property: prop,\n                args: recordArgs,\n              };\n              // TODO: this could potentially also be an OffscreenCanvas as well as HTMLCanvasElement\n              cb(this.canvas, mutation);\n            }\n\n            return result;\n          };\n        },\n      );\n      handlers.push(restoreHandler);\n    } catch {\n      const hookHandler = hookSetter<typeof prototype>(prototype, prop, {\n        set(v) {\n          // TODO: this could potentially also be an OffscreenCanvas as well as HTMLCanvasElement\n          // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n          cb(this.canvas as HTMLCanvasElement, {\n            type,\n            property: prop,\n            args: [v],\n            setter: true,\n          });\n        },\n      });\n      handlers.push(hookHandler);\n    }\n  }\n\n  return handlers;\n}\n\nexport default function initCanvasWebGLMutationObserver(\n  cb: canvasManagerMutationCallback,\n  win: IWindow,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  dataURLOptions: DataURLOptions,\n): listenerHandler {\n  const handlers: listenerHandler[] = [];\n\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\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\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\n", "import type { ICanvas, Mirror } from '@posthog/rrweb-snapshot';\nimport type {\n  blockClass,\n  canvasManagerMutationCallback,\n  canvasMutationCallback,\n  canvasMutationCommand,\n  canvasMutationWithType,\n  IWindow,\n  listenerHandler,\n  CanvasArg,\n  DataURLOptions,\n} from '@posthog/rrweb-types';\nimport { isBlocked } from '../../../utils';\nimport { CanvasContext } from '@posthog/rrweb-types';\nimport initCanvas2DMutationObserver from './2d';\nimport initCanvasContextObserver from './canvas';\nimport initCanvasWebGLMutationObserver from './webgl';\nimport ImageBitmapDataURLWorker from '../../workers/image-bitmap-data-url-worker?worker&inline';\nimport type { ImageBitmapDataURLRequestWorker } from '../../workers/image-bitmap-data-url-worker';\n\nexport type RafStamps = { latestId: number; invokeId: number | null };\n\ntype pendingCanvasMutationsMap = Map<\n  HTMLCanvasElement,\n  canvasMutationWithType[]\n>;\n\nexport class CanvasManager {\n  private pendingCanvasMutations: pendingCanvasMutationsMap = new Map();\n  private rafStamps: RafStamps = { latestId: 0, invokeId: null };\n  private mirror: Mirror;\n\n  private mutationCb: canvasMutationCallback;\n  private resetObservers?: listenerHandler;\n  private frozen = false;\n  private locked = false;\n  private rafIdTimestamp: number | null = null;\n  private rafIdFlush: number | null = null;\n\n  public reset() {\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\n  public freeze() {\n    this.frozen = true;\n  }\n\n  public unfreeze() {\n    this.frozen = false;\n  }\n\n  public lock() {\n    this.locked = true;\n  }\n\n  public unlock() {\n    this.locked = false;\n  }\n\n  constructor(options: {\n    recordCanvas: boolean;\n    mutationCb: canvasMutationCallback;\n    win: IWindow;\n    blockClass: blockClass;\n    blockSelector: string | null;\n    mirror: Mirror;\n    sampling?: 'all' | number;\n    dataURLOptions: DataURLOptions;\n  }) {\n    const {\n      sampling = 'all',\n      win,\n      blockClass,\n      blockSelector,\n      recordCanvas,\n      dataURLOptions,\n    } = options;\n    this.mutationCb = options.mutationCb;\n    this.mirror = options.mirror;\n\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      });\n  }\n\n  private processMutation: canvasManagerMutationCallback = (\n    target,\n    mutation,\n  ) => {\n    const newFrame =\n      this.rafStamps.invokeId &&\n      this.rafStamps.latestId !== this.rafStamps.invokeId;\n    if (newFrame || !this.rafStamps.invokeId)\n      this.rafStamps.invokeId = this.rafStamps.latestId;\n\n    if (!this.pendingCanvasMutations.has(target)) {\n      this.pendingCanvasMutations.set(target, []);\n    }\n\n    this.pendingCanvasMutations.get(target)!.push(mutation);\n  };\n\n  private initCanvasFPSObserver(\n    fps: number,\n    win: IWindow,\n    blockClass: blockClass,\n    blockSelector: string | null,\n    options: {\n      dataURLOptions: DataURLOptions;\n    },\n  ) {\n    if (!('OffscreenCanvas' in win)) {\n      return;\n    }\n\n    const canvasContextReset = initCanvasContextObserver(\n      win,\n      blockClass,\n      blockSelector,\n      true,\n    );\n    const snapshotInProgressMap: Map<number, boolean> = new Map();\n    const worker =\n      new ImageBitmapDataURLWorker() as ImageBitmapDataURLRequestWorker;\n    worker.onmessage = (e) => {\n      const { id } = e.data;\n      snapshotInProgressMap.set(id, false);\n\n      if (!('base64' in e.data)) return;\n\n      const { base64, type, width, height } = e.data;\n      this.mutationCb({\n        id,\n        type: CanvasContext['2D'],\n        commands: [\n          {\n            property: 'clearRect', // wipe canvas\n            args: [0, 0, width, height],\n          },\n          {\n            property: 'drawImage', // draws (semi-transparent) image\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              } as CanvasArg,\n              0,\n              0,\n            ],\n          },\n        ],\n        displayWidth: width,\n        displayHeight: height,\n      });\n    };\n\n    const timeBetweenSnapshots = 1000 / fps;\n    let lastSnapshotTime = 0;\n    let rafId: number;\n\n    const getCanvas = (): HTMLCanvasElement[] => {\n      const matchedCanvas: HTMLCanvasElement[] = [];\n      const searchCanvas = (haystack: ParentNode) => {\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      };\n      searchCanvas(win.document);\n      return matchedCanvas;\n    };\n\n    const takeCanvasSnapshots = (timestamp: DOMHighResTimeStamp) => {\n      if (\n        lastSnapshotTime &&\n        timestamp - lastSnapshotTime < timeBetweenSnapshots\n      ) {\n        rafId = requestAnimationFrame(takeCanvasSnapshots);\n        return;\n      }\n      lastSnapshotTime = timestamp;\n\n      getCanvas()\n        // eslint-disable-next-line @typescript-eslint/no-misused-promises\n        .forEach(async (canvas: HTMLCanvasElement) => {\n          const id = this.mirror.getId(canvas);\n          if (snapshotInProgressMap.get(id)) return;\n\n          // The browser throws if the canvas is 0 in size\n          // Uncaught (in promise) DOMException: Failed to execute 'createImageBitmap' on 'Window': The source image width is 0.\n          // Assuming the same happens with height\n          if (canvas.width === 0 || canvas.height === 0) return;\n\n          snapshotInProgressMap.set(id, true);\n          try {\n            if (['webgl', 'webgl2'].includes((canvas as ICanvas).__context)) {\n              // if the canvas hasn't been modified recently,\n              // its contents won't be in memory and `createImageBitmap`\n              // will return a transparent imageBitmap\n\n              const context = canvas.getContext(\n                (canvas as ICanvas).__context,\n              ) as WebGLRenderingContext | WebGL2RenderingContext | null;\n              if (\n                context?.getContextAttributes()?.preserveDrawingBuffer === false\n              ) {\n                // Hack to load canvas back into memory so `createImageBitmap` can grab it's contents.\n                // Context: https://twitter.com/Juice10/status/1499775271758704643\n                // Preferably we set `preserveDrawingBuffer` to true, but that's not always possible,\n                // especially when canvas is loaded before rrweb.\n                // This hack can wipe the background color of the canvas in the (unlikely) event that\n                // the canvas background was changed but clear was not called directly afterwards.\n                // Example of this hack having negative side effect: https://visgl.github.io/react-map-gl/examples/layers\n                context.clear(context.COLOR_BUFFER_BIT);\n              }\n            }\n            // createImageBitmap throws if resizing to 0\n            // Fallback to intrinsic size if canvas has not yet rendered\n            const width = canvas.clientWidth || canvas.width;\n            const height = canvas.clientHeight || canvas.height;\n            const bitmap = await createImageBitmap(canvas, {\n              resizeWidth: width,\n              resizeHeight: height,\n            });\n            worker.postMessage(\n              {\n                id,\n                bitmap,\n                width: width,\n                height: height,\n                dataURLOptions: options.dataURLOptions,\n              },\n              [bitmap],\n            );\n          } catch {\n            snapshotInProgressMap.set(id, false);\n          }\n        });\n      rafId = requestAnimationFrame(takeCanvasSnapshots);\n    };\n\n    rafId = requestAnimationFrame(takeCanvasSnapshots);\n\n    this.resetObservers = () => {\n      canvasContextReset();\n      cancelAnimationFrame(rafId);\n    };\n  }\n\n  private initCanvasMutationObserver(\n    win: IWindow,\n    blockClass: blockClass,\n    blockSelector: string | null,\n    dataURLOptions: DataURLOptions,\n  ): void {\n    this.startRAFTimestamping();\n    this.startPendingCanvasMutationFlusher();\n\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\n    const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n      this.processMutation.bind(this),\n      win,\n      blockClass,\n      blockSelector,\n      dataURLOptions,\n    );\n\n    this.resetObservers = () => {\n      canvasContextReset();\n      canvas2DReset();\n      canvasWebGL1and2Reset();\n    };\n  }\n\n  private startPendingCanvasMutationFlusher() {\n    this.rafIdFlush = requestAnimationFrame(() =>\n      this.flushPendingCanvasMutations(),\n    );\n  }\n\n  private startRAFTimestamping() {\n    const setLatestRAFTimestamp = (timestamp: DOMHighResTimeStamp) => {\n      this.rafStamps.latestId = timestamp;\n      this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n    };\n    this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n  }\n\n  flushPendingCanvasMutations() {\n    this.pendingCanvasMutations.forEach(\n      (_values: canvasMutationCommand[], canvas: HTMLCanvasElement) => {\n        const id = this.mirror.getId(canvas);\n        this.flushPendingCanvasMutationFor(canvas, id);\n      },\n    );\n    this.rafIdFlush = requestAnimationFrame(() =>\n      this.flushPendingCanvasMutations(),\n    );\n  }\n\n  flushPendingCanvasMutationFor(canvas: HTMLCanvasElement, id: number) {\n    if (this.frozen || this.locked) {\n      return;\n    }\n\n    const valuesWithType = this.pendingCanvasMutations.get(canvas);\n    if (!valuesWithType || id === -1) return;\n\n    const values = valuesWithType.map((value) => {\n      const { type, ...rest } = value;\n      return rest;\n    });\n    const { type } = valuesWithType[0];\n\n    this.mutationCb({ id, type, commands: values });\n\n    this.pendingCanvasMutations.delete(canvas);\n  }\n}\n", "import { stringifyRule } from '@posthog/rrweb-snapshot';\nimport type {\n  elementNode,\n  serializedNodeWithId,\n  adoptedStyleSheetCallback,\n  adoptedStyleSheetParam,\n  attributeMutation,\n  mutationCallBack,\n} from '@posthog/rrweb-types';\nimport { StyleSheetMirror } from '../utils';\n\nexport class StylesheetManager {\n  private trackedLinkElements: WeakSet<HTMLLinkElement> = new WeakSet();\n  private mutationCb: mutationCallBack;\n  private adoptedStyleSheetCb: adoptedStyleSheetCallback;\n  public styleMirror = new StyleSheetMirror();\n\n  constructor(options: {\n    mutationCb: mutationCallBack;\n    adoptedStyleSheetCb: adoptedStyleSheetCallback;\n  }) {\n    this.mutationCb = options.mutationCb;\n    this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n  }\n\n  public attachLinkElement(\n    linkEl: HTMLLinkElement,\n    childSn: serializedNodeWithId,\n  ) {\n    if ('_cssText' in (childSn as elementNode).attributes)\n      this.mutationCb({\n        adds: [],\n        removes: [],\n        texts: [],\n        attributes: [\n          {\n            id: childSn.id,\n            attributes: (childSn as elementNode)\n              .attributes as attributeMutation['attributes'],\n          },\n        ],\n      });\n\n    this.trackLinkElement(linkEl);\n  }\n\n  public trackLinkElement(linkEl: HTMLLinkElement) {\n    if (this.trackedLinkElements.has(linkEl)) return;\n\n    this.trackedLinkElements.add(linkEl);\n    this.trackStylesheetInLinkElement(linkEl);\n  }\n\n  public adoptStyleSheets(\n    sheets: CSSStyleSheet[] | readonly CSSStyleSheet[],\n    hostId: number,\n  ) {\n    if (sheets.length === 0) return;\n    const adoptedStyleSheetData: adoptedStyleSheetParam = {\n      id: hostId,\n      styleIds: [] as number[],\n    };\n    const styles: NonNullable<adoptedStyleSheetParam['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, index) => ({\n            rule: stringifyRule(r, sheet.href),\n            index,\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\n  public reset() {\n    this.styleMirror.reset();\n    this.trackedLinkElements = new WeakSet();\n  }\n\n  // TODO: take snapshot on stylesheet reload by applying event listener\n  private trackStylesheetInLinkElement(_linkEl: HTMLLinkElement) {\n    // linkEl.addEventListener('load', () => {\n    //   // re-loaded, maybe take another snapshot?\n    // });\n  }\n}\n", "import type MutationBuffer from './mutation';\n\n/**\n * Keeps a log of nodes that could show up in multiple mutation buffer but shouldn't be handled twice.\n */\nexport default class ProcessedNodeManager {\n  private nodeMap: WeakMap<Node, Set<MutationBuffer>> = new WeakMap();\n\n  private active = false;\n\n  public inOtherBuffer(node: Node, thisBuffer: MutationBuffer) {\n    const buffers = this.nodeMap.get(node);\n    return (\n      buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer)\n    );\n  }\n\n  public add(node: Node, buffer: MutationBuffer) {\n    if (!this.active) {\n      this.active = true;\n      requestAnimationFrame(() => {\n        this.nodeMap = new WeakMap();\n        this.active = false;\n      });\n    }\n    this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\n  }\n\n  public destroy() {\n    // cleanup no longer needed\n  }\n}\n", "import {\n  snapshot,\n  type MaskInputOptions,\n  slimDOMDefaults,\n  createMirror,\n} from '@posthog/rrweb-snapshot';\nimport {\n  initObservers,\n  mutationBuffers,\n  findAndRemoveIframeBuffer,\n} from './observer';\nimport {\n  on,\n  callSafely,\n  getWindowWidth,\n  getWindowHeight,\n  getWindowScroll,\n  polyfill,\n  hasShadowRoot,\n  isSerializedIframe,\n  isSerializedStylesheet,\n  nowTimestamp,\n} from '../utils';\nimport type { recordOptions } from '../types';\nimport {\n  EventType,\n  type eventWithoutTime,\n  type eventWithTime,\n  IncrementalSource,\n  type listenerHandler,\n  type mutationCallbackParam,\n  type scrollCallback,\n  type canvasMutationParam,\n  type adoptedStyleSheetParam,\n} from '@posthog/rrweb-types';\nimport type { CrossOriginIframeMessageEventContent } from '../types';\nimport { IframeManager } from './iframe-manager';\nimport { ShadowDomManager } from './shadow-dom-manager';\nimport { CanvasManager } from './observers/canvas/canvas-manager';\nimport { StylesheetManager } from './stylesheet-manager';\nimport ProcessedNodeManager from './processed-node-manager';\nimport {\n  callbackWrapper,\n  registerErrorHandler,\n  unregisterErrorHandler,\n} from './error-handler';\nimport dom from '@posthog/rrweb-utils';\n\nlet wrappedEmit!: (e: eventWithoutTime, isCheckout?: boolean) => void;\n\nlet takeFullSnapshot!: (isCheckout?: boolean) => void;\nlet canvasManager!: CanvasManager;\nlet recording = false;\n\n// Multiple tools (i.e. MooTools, Prototype.js) override Array.from and drop support for the 2nd parameter\n// Try to pull a clean implementation from a newly created iframe\ntry {\n  if (Array.from([1], (x) => x * 2)[0] !== 2) {\n    const cleanFrame = document.createElement('iframe');\n    document.body.appendChild(cleanFrame);\n    // eslint-disable-next-line @typescript-eslint/unbound-method -- Array.from is static and doesn't rely on binding\n    Array.from = cleanFrame.contentWindow?.Array.from || Array.from;\n    document.body.removeChild(cleanFrame);\n  }\n} catch (err) {\n  console.debug('Unable to override Array.from', err);\n}\n\nconst mirror = createMirror();\nfunction record<T = eventWithTime>(\n  options: recordOptions<T> = {},\n): listenerHandler | undefined {\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    mousemoveWait,\n    recordDOM = true,\n    recordCanvas = false,\n    recordCrossOriginIframes = false,\n    recordAfter = options.recordAfter === 'DOMContentLoaded'\n      ? options.recordAfter\n      : 'load',\n    userTriggeredOnInput = false,\n    collectFonts = false,\n    inlineImages = false,\n    plugins,\n    keepIframeSrcFn = () => false,\n    ignoreCSSAttributes = new Set([]),\n    errorHandler,\n  } = options;\n\n  registerErrorHandler(errorHandler);\n\n  const dataURLOptions = {\n    type: 'image/webp',\n    quality: 0.4,\n    maxBase64ImageLength: 1048576,\n    ..._dataURLOptions,\n  };\n\n  const inEmittingFrame = recordCrossOriginIframes\n    ? window.parent === window\n    : true;\n\n  let passEmitsToParent = false;\n  if (!inEmittingFrame) {\n    try {\n      // throws if parent is cross-origin\n      if (window.parent.document) {\n        passEmitsToParent = false; // if parent is same origin we collect iframe events from the parent\n      }\n    } catch (e) {\n      passEmitsToParent = true;\n    }\n  }\n\n  // runtime checks for user options\n  if (inEmittingFrame && !emit) {\n    throw new Error('emit function is required');\n  }\n  if (!inEmittingFrame && !passEmitsToParent) {\n    return () => {\n      /* no-op since in this case we don't need to record anything from this frame in particular */\n    };\n  }\n  // move departed options to new options\n  if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n    sampling.mousemove = mousemoveWait;\n  }\n\n  // reset mirror in case `record` this was called earlier\n  mirror.reset();\n\n  const maskInputOptions: MaskInputOptions =\n    maskAllInputs === true\n      ? {\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        }\n      : _maskInputOptions !== undefined\n      ? _maskInputOptions\n      : { password: true };\n\n  const slimDOMOptions = slimDOMDefaults(\n    _slimDOMOptions !== undefined ? _slimDOMOptions : false,\n  );\n\n  polyfill();\n\n  let lastFullSnapshotEvent: eventWithTime;\n  let incrementalSnapshotCount = 0;\n  // Track observer cleanup functions for individual iframes to prevent memory leaks\n  const iframeObserverCleanups = new Map<number, listenerHandler>();\n\n  function cleanupDetachedIframeObservers() {\n    for (const [iframeId, cleanup] of iframeObserverCleanups) {\n      const iframe = mirror.getNode(iframeId) as HTMLIFrameElement | null;\n\n      if (!iframe) {\n        cleanup();\n        iframeObserverCleanups.delete(iframeId);\n        continue;\n      }\n\n      try {\n        // Check if iframe is detached or its content is no longer accessible\n        if (!iframe.contentDocument || !iframe.contentDocument.defaultView) {\n          cleanup();\n          iframeObserverCleanups.delete(iframeId);\n        }\n      } catch {\n        // Cross-origin: contentDocument access throws, cleanup anyway\n        cleanup();\n        iframeObserverCleanups.delete(iframeId);\n      }\n    }\n  }\n\n  const eventProcessor = (e: eventWithTime): T => {\n    for (const plugin of plugins || []) {\n      if (plugin.eventProcessor) {\n        e = plugin.eventProcessor(e);\n      }\n    }\n    if (\n      packFn &&\n      // Disable packing events which will be emitted to parent frames.\n      !passEmitsToParent\n    ) {\n      e = packFn(e) as unknown as eventWithTime;\n    }\n    return e as unknown as T;\n  };\n  wrappedEmit = (r: eventWithoutTime, isCheckout?: boolean) => {\n    const e = r as eventWithTime;\n    e.timestamp = nowTimestamp();\n    if (\n      mutationBuffers[0]?.isFrozen() &&\n      e.type !== EventType.FullSnapshot &&\n      !(\n        e.type === EventType.IncrementalSnapshot &&\n        e.data.source === IncrementalSource.Mutation\n      )\n    ) {\n      // we've got a user initiated event so first we need to apply\n      // all DOM changes that have been buffering during paused state\n      mutationBuffers.forEach((buf) => buf.unfreeze());\n    }\n\n    if (inEmittingFrame) {\n      emit?.(eventProcessor(e), isCheckout);\n    } else if (passEmitsToParent) {\n      const message: CrossOriginIframeMessageEventContent<T> = {\n        type: 'rrweb',\n        event: eventProcessor(e),\n        origin: window.location.origin,\n        isCheckout,\n      };\n      window.parent.postMessage(message, '*');\n    }\n\n    if (e.type === EventType.FullSnapshot) {\n      lastFullSnapshotEvent = e;\n      incrementalSnapshotCount = 0;\n    } else if (e.type === EventType.IncrementalSnapshot) {\n      // attach iframe should be considered as full snapshot\n      if (\n        e.data.source === IncrementalSource.Mutation &&\n        e.data.isAttachIframe\n      ) {\n        return;\n      }\n\n      incrementalSnapshotCount++;\n      const exceedCount =\n        checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n      const exceedTime =\n        checkoutEveryNms &&\n        e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n      if (exceedCount || exceedTime) {\n        takeFullSnapshot(true);\n      }\n    }\n  };\n\n  const wrappedMutationEmit = (m: mutationCallbackParam) => {\n    // Clean up removed iframes from the attachedIframes Map to prevent memory leaks\n    // Only clean up iframes that are actually being removed, not moved\n    // (moved iframes appear in both removes and adds)\n    if (recordCrossOriginIframes && m.removes && m.removes.length > 0) {\n      // Only create the Set if there are adds to check against\n      const addedIds =\n        m.adds.length > 0 ? new Set(m.adds.map((add) => add.node.id)) : null;\n      m.removes.forEach(({ id }) => {\n        // Only remove if not being re-added (i.e., actually removed, not moved)\n        if (!addedIds || !addedIds.has(id)) {\n          // Disconnect observers for this iframe to prevent memory leaks\n          const cleanup = iframeObserverCleanups.get(id);\n          if (cleanup) {\n            cleanup();\n            iframeObserverCleanups.delete(id);\n          }\n          iframeManager.removeIframeById(id);\n        }\n      });\n\n      // Safety net: cleanup any iframes that have become detached or inaccessible\n      cleanupDetachedIframeObservers();\n    }\n\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.Mutation,\n        ...m,\n      },\n    });\n  };\n  const wrappedScrollEmit: scrollCallback = (p) =>\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.Scroll,\n        ...p,\n      },\n    });\n  const wrappedCanvasMutationEmit = (p: canvasMutationParam) =>\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.CanvasMutation,\n        ...p,\n      },\n    });\n\n  const wrappedAdoptedStyleSheetEmit = (a: adoptedStyleSheetParam) =>\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.AdoptedStyleSheet,\n        ...a,\n      },\n    });\n\n  const stylesheetManager = new StylesheetManager({\n    mutationCb: wrappedMutationEmit,\n    adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\n  });\n\n  const iframeManager = new IframeManager({\n    mirror,\n    mutationCb: wrappedMutationEmit,\n    stylesheetManager: stylesheetManager,\n    recordCrossOriginIframes,\n    wrappedEmit,\n  });\n\n  /**\n   * Exposes mirror to the plugins\n   */\n  for (const plugin of plugins || []) {\n    if (plugin.getMirror)\n      plugin.getMirror({\n        nodeMirror: mirror,\n        crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n        crossOriginIframeStyleMirror:\n          iframeManager.crossOriginIframeStyleMirror,\n      });\n  }\n\n  const processedNodeManager = new ProcessedNodeManager();\n\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  });\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\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\n    // When we take a full snapshot, old tracked StyleSheets need to be removed.\n    stylesheetManager.reset();\n\n    shadowDomManager.init();\n\n    mutationBuffers.forEach((buf) => buf.lock()); // don't allow any mirror modifications during snapshotting\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 as HTMLIFrameElement);\n        }\n        if (isSerializedStylesheet(n, mirror)) {\n          stylesheetManager.trackLinkElement(n as HTMLLinkElement);\n        }\n        if (hasShadowRoot(n)) {\n          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n          shadowDomManager.addShadowRoot(dom.shadowRoot(n as Node)!, document);\n        }\n      },\n      onIframeLoad: (iframe, childSn) => {\n        iframeManager.attachIframe(iframe, childSn);\n        shadowDomManager.observeAttachShadow(iframe);\n      },\n      onStylesheetLoad: (linkEl, childSn) => {\n        stylesheetManager.attachLinkElement(linkEl, childSn);\n      },\n      keepIframeSrcFn,\n    });\n\n    if (!node) {\n      return console.warn('Failed to snapshot the document');\n    }\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()); // generate & emit any mutations that happened during snapshotting, as can now apply against the newly built mirror\n\n    if (recordCrossOriginIframes) {\n      iframeManager.reattachIframes();\n    }\n\n    // Some old browsers don't support adoptedStyleSheets.\n    if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n      stylesheetManager.adoptStyleSheets(\n        document.adoptedStyleSheets,\n        mirror.getId(document),\n      );\n  };\n\n  try {\n    const handlers: listenerHandler[] = [];\n\n    const observe = (doc: Document) => {\n      return callbackWrapper(initObservers)(\n        {\n          mutationCb: wrappedMutationEmit,\n          mousemoveCb: (positions, source) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source,\n                positions,\n              },\n            }),\n          mouseInteractionCb: (d) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.MouseInteraction,\n                ...d,\n              },\n            }),\n          scrollCb: wrappedScrollEmit,\n          viewportResizeCb: (d) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.ViewportResize,\n                ...d,\n              },\n            }),\n          inputCb: (v) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.Input,\n                ...v,\n              },\n            }),\n          mediaInteractionCb: (p) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.MediaInteraction,\n                ...p,\n              },\n            }),\n          styleSheetRuleCb: (r) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.StyleSheetRule,\n                ...r,\n              },\n            }),\n          styleDeclarationCb: (r) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.StyleDeclaration,\n                ...r,\n              },\n            }),\n          canvasMutationCb: wrappedCanvasMutationEmit,\n          fontCb: (p) =>\n            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:\n            plugins\n              ?.filter((p) => p.observer)\n              ?.map((p) => ({\n                observer: p.observer!,\n                options: p.options,\n                callback: (payload: object) =>\n                  wrappedEmit({\n                    type: EventType.Plugin,\n                    data: {\n                      plugin: p.name,\n                      payload,\n                    },\n                  }),\n              })) || [],\n        },\n        hooks,\n      );\n    };\n\n    const loadListener = (iframeEl: HTMLIFrameElement) => {\n      try {\n        const iframeId = mirror.getId(iframeEl);\n        const cleanup = observe(iframeEl.contentDocument!);\n        handlers.push(cleanup);\n        // Store cleanup function so we can disconnect this iframe's observers when it's removed\n        if (iframeId !== -1) {\n          iframeObserverCleanups.set(iframeId, cleanup);\n        }\n      } catch (error) {\n        // TODO: handle internal error\n        console.warn(error);\n      }\n    };\n    iframeManager.addLoadListener(loadListener);\n\n    iframeManager.addPageHideListener((iframeEl) => {\n      const iframeId = mirror.getId(iframeEl);\n      const cleanup = iframeObserverCleanups.get(iframeId);\n      if (cleanup) {\n        cleanup();\n        iframeObserverCleanups.delete(iframeId);\n      }\n      findAndRemoveIframeBuffer(iframeEl);\n    });\n\n    const init = () => {\n      takeFullSnapshot();\n      handlers.push(observe(document));\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    // TODO: handle internal error\n    console.warn(error);\n  }\n}\n\nrecord.addCustomEvent = <T>(tag: string, payload: T) => {\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};\n\nrecord.freezePage = () => {\n  mutationBuffers.forEach((buf) => buf.freeze());\n};\n\nrecord.takeFullSnapshot = (isCheckout?: boolean) => {\n  if (!recording) {\n    throw new Error('please take full snapshot after start recording');\n  }\n  takeFullSnapshot(isCheckout);\n};\n\nrecord.mirror = mirror;\n\nexport default record;\n"],
  "mappings": ";w1BAAA,IAAIA,GAA8BC,IAChCA,EAAWA,EAAW,iBAAsB,CAAC,EAAI,mBACjDA,EAAWA,EAAW,KAAU,CAAC,EAAI,OACrCA,EAAWA,EAAW,aAAkB,CAAC,EAAI,eAC7CA,EAAWA,EAAW,oBAAyB,CAAC,EAAI,sBACpDA,EAAWA,EAAW,KAAU,CAAC,EAAI,OACrCA,EAAWA,EAAW,OAAY,CAAC,EAA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AY,EACd,EACA,MAAI,CAAC,cAAe,UAAU,EAAE,SAAS,SAAS,UAAU,EAC1DqC,EAAA,GAEAtQ,EAAS,KACPrH,EAAG,mBAAoB,IAAM,CAC3BmV,EAAY,CACV,KAAMrnB,EAAU,iBAChB,KAAM,CAAA,CAAC,CACR,EACGqoB,IAAgB,oBAAoBwB,EAAA,CAC1C,CAAC,CAAA,EAEHtQ,EAAS,KACPrH,EACE,OACA,IAAM,CACJmV,EAAY,CACV,KAAMrnB,EAAU,KAChB,KAAM,CAAA,CAAC,CACR,EACGqoB,IAAgB,QAAQwB,EAAA,CAC9B,EACA,MAAA,CACF,GAGG,IAAM,CACXtQ,EAAS,QAASW,GAAM7H,GAAW6H,CAAC,CAAC,EACrCuP,GAAqB,QAAA,EACrBJ,EAAc,mBAAA,EACdA,EAAc,QAAA,EACdT,GAAuB,MAAA,EACvB1b,EAAO,MAAA,EACPsa,GAAY,GACZxP,GAAA,CACF,CACF,OAAS9S,EAAO,CAEd,QAAQ,KAAKA,CAAK,CACpB,CACF,CAEAwiB,GAAO,eAAiB,CAAIoC,EAAa1T,IAAe,CACtD,GAAI,CAACoR,GACH,MAAM,IAAI,MAAM,+CAA+C,EAEjEH,EAAY,CACV,KAAMrnB,EAAU,OAChB,KAAM,CACJ,IAAA8pB,EACA,QAAA1T,CAAA,CACF,CACD,CACH,EAEAsR,GAAO,WAAa,IAAM,CACxBtP,EAAgB,QAASwC,GAAQA,EAAI,OAAA,CAAQ,CAC/C,EAEA8M,GAAO,iBAAoBsB,GAAyB,CAClD,GAAI,CAACxB,GACH,MAAM,IAAI,MAAM,iDAAiD,EAEnEF,GAAiB0B,CAAU,CAC7B,EAEAtB,GAAO,OAASxa",
  "names": ["EventType", "EventType2", "IncrementalSource", "IncrementalSource2", "MouseInteractions", "MouseInteractions2", "PointerTypes", "PointerTypes2", "CanvasContext", "CanvasContext2", "MediaInteractions", "MediaInteractions2", "NodeType", "NodeType2", "testableAccessors", "testableMethods", "untaintedBasePrototype", "angularZoneUnpatchedAlternative", "key", "_a", "_b", "angularUnpatchedVersionSymbol", "getUntaintedPrototype", "candidate", "defaultPrototype", "accessorNames", "isUntaintedAccessors", "accessor", "methodNames", "isUntaintedMethods", "method", "iframeEl", "win", "untaintedObject", "e", "untaintedAccessorCache", "getUntaintedAccessor", "instance", "cacheKey", "untaintedPrototype", "untaintedAccessor", "untaintedMethodCache", "getUntaintedMethod", "untaintedMethod", "childNodes", "n", "parentNode", "parentElement", "textContent", "contains", "other", "getRootNode", "host", "styleSheets", "shadowRoot", "querySelector", "selectors", "querySelectorAll", "mutationObserverCtor", "patch", "source", "name", "replacement", "original", "wrapped", "index", "isElement", "isShadowRoot", "hostEl", "dom", "isNativeShadowDom", "fixBrowserCompatibilityIssuesInCSS", "cssText", "escapeImportStatement", "rule", "statement", "stringifyStylesheet", "s", "rules", "sheetHref", "stringifiedRules", "stringifyRule", "error", "isCSSImportRule", "importStringified", "absolutifyURLs", "ruleStringified", "isCSSStyleRule", "fixSafariColons", "cssStringified", "regex", "Mirror", "__publicField", "id", "childNode", "shadowRootEl", "node", "meta", "oldNode", "createMirror", "maskInputValue", "element", "maskInputOptions", "tagName", "type", "value", "maskInputFn", "text", "actualType", "toLowerCase", "str", "ORIGINAL_ATTRIBUTE_NAME", "is2DCanvasBlank", "canvas", "ctx", "chunkSize", "x", "y", "getImageData", "originalGetImageData", "pixel", "getInputType", "extractFileExtension", "path", "baseURL", "url", "err", "match", "extractOrigin", "origin", "URL_IN_CSS_REF", "URL_PROTOCOL_MATCH", "URL_WWW_MATCH", "DATA_URI", "href", "quote1", "path1", "quote2", "path2", "path3", "filePath", "maybeQuote", "stack", "parts", "part", "STRIPED_PLACEHOLDER_SVG", "MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION", "recompressBase64Image", "img", "dataURL", "quality", "checkDataURLSize", "maxLength", "_id", "tagNameRegex", "IGNORED_NODE", "genId", "getValidTagName", "processedTagName", "canvasService", "canvasCtx", "SRCSET_NOT_SPACES", "SRCSET_COMMAS_OR_SPACES", "getAbsoluteSrcsetString", "doc", "attributeValue", "pos", "collectCharacters", "regEx", "chars", "output", "absoluteToDoc", "descriptorsStr", "inParens", "c", "cachedDocument", "getHref", "isSVGElement", "el", "customHref", "a", "transformAttribute", "dataURLOptions", "transformedValue", "processedDataURL", "ignoreAttribute", "_value", "_isBlockedElement", "blockClass", "blockSelector", "eIndex", "className", "classMatchesRegex", "checkAncestors", "needMaskingText", "maskTextClass", "maskTextSelector", "onceIframeLoaded", "listener", "iframeLoadTimeout", "fired", "readyState", "timer", "blankUrl", "onceStylesheetLoaded", "link", "styleSheetLoadTimeout", "styleSheetLoaded", "serializeNode", "options", "mirror", "needsMask", "inlineStylesheet", "maskTextFn", "inlineImages", "recordCanvas", "keepIframeSrcFn", "newlyAddedElement", "rootId", "getRootId", "serializeElementNode", "serializeTextNode", "docId", "parent", "parentTagName", "isStyle", "isScript", "findStylesheet", "hrefFrom", "needBlock", "attributes", "len", "i", "attr", "stylesheet", "rootDomain", "stylesheetPath", "potentialStylesheetHref", "checked", "canvasDataURL", "blankCanvas", "blankCanvasDataURL", "image", "imageSrc", "priorCrossOrigin", "recordInlineImage", "mediaAttributes", "width", "height", "left", "top", "isCustomElement", "lowerIfExists", "maybeAttr", "slimDOMExcluded", "sn", "slimDOMOptions", "DEFAULT_MAX_DEPTH", "_maxDepthWarned", "_maxDepthReached", "wasMaxDepthReached", "resetMaxDepthState", "serializeNodeWithId", "skipChild", "onSerialize", "onIframeLoad", "onStylesheetLoad", "stylesheetLoadTimeout", "depth", "maxDepth", "preserveWhiteSpace", "_serializedNode", "serializedNode", "recordChild", "bypassOptions", "childN", "serializedChildNode", "iframeDoc", "serializedIframeNode", "serializedLinkNode", "slimDOMDefaults", "slimDOM", "snapshot", "maskAllInputs", "BaseRRNode", "_args", "childIterator", "_newChild", "_refChild", "_node", "on", "fn", "target", "callSafely", "DEPARTED_MIRROR_ACCESS_WARNING", "_mirror", "prop", "receiver", "throttle", "func", "wait", "timeout", "previous", "args", "now", "remaining", "context", "hookSetter", "d", "isRevoked", "nowTimestamp", "getWindowScroll", "_d", "getWindowHeight", "getWindowWidth", "closestElementOfNode", "isBlocked", "isSerialized", "isIgnored", "isAncestorRemoved", "legacy_isTouchEvent", "event", "polyfill", "isSerializedIframe", "isSerializedStylesheet", "hasShadowRoot", "StyleSheetMirror", "newId", "getShadowHost", "shadowHost", "getRootShadowHost", "rootShadowHost", "shadowHostInDom", "inDom", "isNodeInLinkedList", "DoubleLinkedList", "position", "current", "moveKey", "parentId", "MutationBuffer", "mutations", "adds", "addedIds", "addList", "getNextId", "ns", "nextId", "pushAdd", "currentN", "iframe", "childSn", "isParentRemoved", "isAncestorInSet", "tailNode", "unhandledNode", "payload", "attribute", "diffAsStr", "unchangedAsStr", "textarea", "item", "cn", "m", "attributeName", "old", "pname", "newValue", "newPriority", "nodeId", "deepDelete", "processRemoves", "targetId", "addsSet", "cache", "queue", "next", "removes", "_isParentRemoved", "set", "_isAncestorInSet", "errorHandler", "registerErrorHandler", "handler", "unregisterErrorHandler", "callbackWrapper", "cb", "rest", "mutationBuffers", "getEventTarget", "initMutationObserver", "rootEl", "mutationBuffer", "observer", "initMoveObserver", "mousemoveCb", "sampling", "threshold", "callbackThreshold", "positions", "timeBaseline", "wrappedCb", "totalOffset", "updatePosition", "evt", "clientX", "clientY", "handlers", "initMouseInteractionObserver", "mouseInteractionCb", "disableMap", "currentPointerType", "getHandler", "eventKey", "pointerType", "thisEventKey", "__spreadValues", "eventName", "h", "initScrollObserver", "scrollCb", "scrollLeftTop", "initViewportResizeObserver", "viewportResizeCb", "lastH", "lastW", "updateDimension", "findAndRemoveIframeBuffer", "buf", "INPUT_TAGS", "lastInputValueMap", "initInputObserver", "inputCb", "ignoreClass", "ignoreSelector", "userTriggeredOnInput", "eventHandler", "userTriggered", "isChecked", "cbWithDedup", "v", "lastInputValue", "__spreadProps", "currentWindow", "propertyDescriptor", "hookProperties", "p", "getNestedCSSRulePositions", "recurse", "childRule", "hasNestedCSSRule", "getIdAndStyleId", "sheet", "styleMirror", "styleId", "initStyleSheetObserver", "styleSheetRuleCb", "stylesheetManager", "insertRule", "thisArg", "argumentsList", "selector", "styleBlock", "deleteRule", "replace", "replaceSync", "supportedNestedCSSRuleTypes", "canMonkeyPatchNestedCSSRule", "unmodifiedFunctions", "typeKey", "initAdoptedStyleSheetObserver", "hostId", "patchTarget", "_c", "originalPropertyDescriptor", "sheets", "result", "initStyleDeclarationObserver", "styleDeclarationCb", "ignoreCSSAttributes", "setProperty", "property", "priority", "removeProperty", "initMediaInteractionObserver", "mediaInteractionCb", "currentTime", "volume", "muted", "playbackRate", "loop", "initFontObserver", "fontCb", "fontMap", "originalFontFace", "family", "descriptors", "fontFace", "restoreHandler", "initSelectionObserver", "param", "selectionCb", "collapsed", "updateSelection", "selection", "ranges", "count", "range", "startContainer", "startOffset", "endContainer", "endOffset", "initCustomElementObserver", "customElementCb", "constructor", "mergeHooks", "o", "hooks", "mutationCb", "canvasMutationCb", "initObservers", "mutationObserver", "mousemoveHandler", "mouseInteractionHandler", "scrollHandler", "viewportResizeHandler", "inputHandler", "mediaInteractionHandler", "styleSheetObserver", "adoptedStyleSheetObserver", "styleDeclarationObserver", "fontObserver", "selectionObserver", "customElementObserver", "pluginHandlers", "plugin", "CrossOriginIframeMirror", "generateIdFn", "remoteId", "idToRemoteMap", "remoteToIdMap", "idToRemoteIdMap", "remoteIdToIdMap", "map", "ids", "IframeManager", "content", "iframeId", "nestedHandler", "message", "crossOriginMessageEvent", "transformedEvent", "style", "iframeMirror", "obj", "keys", "child", "entry", "contentWindow", "ShadowDomManager", "buffer", "iframeElement", "manager", "option", "sRoot", "lookup", "encode", "arraybuffer", "bytes", "base64", "canvasVarMap", "variableListFor", "ctor", "contextMap", "saveWebGLVar", "isInstanceOfWebGLObject", "list", "serializeArg", "arg", "src", "serializeArgs", "initCanvas2DMutationObserver", "props2D", "recordArgs", "hookHandler", "getNormalizedContextName", "contextType", "initCanvasContextObserver", "setPreserveDrawingBufferToTrue", "ctxName", "contextAttributes", "patchGLPrototype", "prototype", "props", "mutation", "initCanvasWebGLMutationObserver", "CanvasManager", "fps", "canvasContextReset", "snapshotInProgressMap", "worker", "ImageBitmapDataURLWorker", "timeBetweenSnapshots", "lastSnapshotTime", "rafId", "getCanvas", "matchedCanvas", "searchCanvas", "haystack", "elem", "takeCanvasSnapshots", "timestamp", "bitmap", "canvas2DReset", "canvasWebGL1and2Reset", "setLatestRAFTimestamp", "_values", "valuesWithType", "values", "__objRest", "StylesheetManager", "linkEl", "adoptedStyleSheetData", "styles", "r", "_linkEl", "ProcessedNodeManager", "thisBuffer", "buffers", "wrappedEmit", "takeFullSnapshot", "canvasManager", "recording", "cleanFrame", "record", "emit", "checkoutEveryNms", "checkoutEveryNth", "_maskInputOptions", "_slimDOMOptions", "packFn", "_dataURLOptions", "mousemoveWait", "recordDOM", "recordCrossOriginIframes", "recordAfter", "collectFonts", "plugins", "inEmittingFrame", "passEmitsToParent", "lastFullSnapshotEvent", "incrementalSnapshotCount", "iframeObserverCleanups", "cleanupDetachedIframeObservers", "cleanup", "eventProcessor", "isCheckout", "exceedCount", "exceedTime", "wrappedMutationEmit", "add", "iframeManager", "wrappedScrollEmit", "wrappedCanvasMutationEmit", "wrappedAdoptedStyleSheetEmit", "processedNodeManager", "shadowDomManager", "observe", "loadListener", "init", "tag"]
}
