{"version":3,"file":"posthog-recorder.js","sources":["../../rrweb/record/dist/rrweb-record.js","../../rrweb/plugins/rrweb-plugin-console-record/dist/rrweb-plugin-console-record.js","../src/utils/globals.ts","../../core/dist/gzip.mjs","../../core/dist/utils/string-utils.mjs","../../core/dist/utils/type-utils.mjs","../../core/dist/utils/number-utils.mjs","../../core/dist/utils/bucketed-rate-limiter.mjs","../../core/dist/utils/index.mjs","../src/utils/type-utils.ts","../src/config.ts","../src/utils/logger.ts","../src/utils/index.ts","../src/utils/request-utils.ts","../src/extensions/replay/rrweb-plugins/patch.ts","../src/extensions/replay/external/denylist.ts","../src/utils/url-targeting-utils.ts","../src/constants.ts","../src/autocapture-utils.ts","../src/extensions/replay/external/config.ts","../src/extensions/replay/external/network-plugin.ts","../src/extensions/replay/types/rrweb-types.ts","../src/extensions/replay/external/triggerMatching.ts","../src/extensions/replay/external/sessionrecording-utils.ts","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fflate/0.4.8/3d6bb6f51514b78f73eff8bf58c4fef7e18a9483e0eef595f39f3a49c6c31e1d/node_modules/fflate/esm/browser.js","../src/extensions/replay/external/mutation-throttler.ts","../src/extensions/replay/external/flushed-size-tracker.ts","../src/extensions/sampling.ts","../src/utils/regex-utils.ts","../src/utils/property-utils.ts","../src/extensions/replay/external/recording-strategies.ts","../src/uuidv7.ts","../src/utils/event-utils.ts","../src/extensions/replay/external/lazy-loaded-session-recorder.ts","../src/entrypoints/posthog-recorder.ts"],"sourcesContent":["var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar _a;\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n  EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n  EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n  EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n  EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n  EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n  EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n  EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n  return EventType2;\n})(EventType || {});\nconst FullscreenCustomEventTag = \"rrweb/fullscreen\";\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n  IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n  IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n  IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n  IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n  IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n  IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n  IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n  IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n  IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n  IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n  IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n  IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n  IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n  IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n  IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n  IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n  IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n  return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n  MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n  MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n  MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n  MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n  MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n  MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n  MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n  MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n  MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n  MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n  MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n  return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n  PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n  PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n  PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n  return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n  CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n  CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n  CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n  return CanvasContext2;\n})(CanvasContext || {});\nvar MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {\n  MediaInteractions2[MediaInteractions2[\"Play\"] = 0] = \"Play\";\n  MediaInteractions2[MediaInteractions2[\"Pause\"] = 1] = \"Pause\";\n  MediaInteractions2[MediaInteractions2[\"Seeked\"] = 2] = \"Seeked\";\n  MediaInteractions2[MediaInteractions2[\"VolumeChange\"] = 3] = \"VolumeChange\";\n  MediaInteractions2[MediaInteractions2[\"RateChange\"] = 4] = \"RateChange\";\n  return MediaInteractions2;\n})(MediaInteractions || {});\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n  NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n  NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n  NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n  NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n  NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n  NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n  return NodeType2;\n})(NodeType || {});\nconst testableAccessors = {\n  Node: [\"childNodes\", \"parentNode\", \"parentElement\", \"textContent\"],\n  ShadowRoot: [\"host\", \"styleSheets\"],\n  Element: [\"shadowRoot\"],\n  MutationObserver: []\n};\nconst testableMethods = {\n  Node: [\"contains\", \"getRootNode\"],\n  ShadowRoot: [\"getSelection\"],\n  Element: [\"querySelector\", \"querySelectorAll\"],\n  MutationObserver: [\"constructor\"]\n};\nconst untaintedBasePrototype = {};\nfunction angularZoneUnpatchedAlternative(key) {\n  var _a2, _b;\n  const angularUnpatchedVersionSymbol = (_b = (_a2 = globalThis == null ? void 0 : globalThis.Zone) == null ? void 0 : _a2.__symbol__) == null ? void 0 : _b.call(_a2, key);\n  if (angularUnpatchedVersionSymbol && globalThis[angularUnpatchedVersionSymbol]) {\n    return globalThis[angularUnpatchedVersionSymbol];\n  } else {\n    return void 0;\n  }\n}\nfunction getUntaintedPrototype(key) {\n  if (untaintedBasePrototype[key])\n    return untaintedBasePrototype[key];\n  const candidate = angularZoneUnpatchedAlternative(key) || globalThis[key];\n  const defaultPrototype = candidate.prototype;\n  const accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;\n  const isUntaintedAccessors = Boolean(\n    accessorNames && // @ts-expect-error 2345\n    accessorNames.every(\n      (accessor) => {\n        var _a2, _b;\n        return Boolean(\n          (_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes(\"[native code]\")\n        );\n      }\n    )\n  );\n  const methodNames = key in testableMethods ? testableMethods[key] : void 0;\n  const isUntaintedMethods = Boolean(\n    methodNames && methodNames.every(\n      // @ts-expect-error 2345\n      (method) => {\n        var _a2;\n        return typeof defaultPrototype[method] === \"function\" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes(\"[native code]\"));\n      }\n    )\n  );\n  if (isUntaintedAccessors && isUntaintedMethods) {\n    untaintedBasePrototype[key] = candidate.prototype;\n    return candidate.prototype;\n  }\n  const iframeEl = document.createElement(\"iframe\");\n  iframeEl.style.display = \"none\";\n  let keepIframeAttached = false;\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    if (isSafari()) {\n      iframeEl.classList.add(\"rr-block\", \"ph-no-capture\");\n      iframeEl.setAttribute(\"__rrwebUntaintedPrototype\", key);\n      keepIframeAttached = true;\n    }\n    return untaintedBasePrototype[key] = untaintedObject;\n  } catch {\n    return defaultPrototype;\n  } finally {\n    if (!keepIframeAttached && iframeEl.parentNode) {\n      document.body.removeChild(iframeEl);\n    }\n  }\n}\nfunction isSafari() {\n  const ua = navigator.userAgent;\n  return ua.includes(\"Safari\") && !ua.includes(\"Chrome\");\n}\nconst untaintedAccessorCache = {};\nfunction getUntaintedAccessor(key, instance, accessor) {\n  var _a2;\n  const cacheKey = `${key}.${String(accessor)}`;\n  if (untaintedAccessorCache[cacheKey])\n    return untaintedAccessorCache[cacheKey].call(\n      instance\n    );\n  const untaintedPrototype = getUntaintedPrototype(key);\n  const untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(\n    untaintedPrototype,\n    accessor\n  )) == null ? void 0 : _a2.get;\n  if (!untaintedAccessor) return instance[accessor];\n  untaintedAccessorCache[cacheKey] = untaintedAccessor;\n  return untaintedAccessor.call(instance);\n}\nconst untaintedMethodCache = {};\nfunction getUntaintedMethod(key, instance, method) {\n  const cacheKey = `${key}.${String(method)}`;\n  if (untaintedMethodCache[cacheKey])\n    return untaintedMethodCache[cacheKey].bind(\n      instance\n    );\n  const untaintedPrototype = getUntaintedPrototype(key);\n  const untaintedMethod = untaintedPrototype[method];\n  if (typeof untaintedMethod !== \"function\") return instance[method];\n  untaintedMethodCache[cacheKey] = untaintedMethod;\n  return untaintedMethod.bind(instance);\n}\nfunction childNodes(n) {\n  return getUntaintedAccessor(\"Node\", n, \"childNodes\");\n}\nfunction parentNode(n) {\n  return getUntaintedAccessor(\"Node\", n, \"parentNode\");\n}\nfunction parentElement(n) {\n  return getUntaintedAccessor(\"Node\", n, \"parentElement\");\n}\nfunction textContent(n) {\n  return getUntaintedAccessor(\"Node\", n, \"textContent\");\n}\nfunction contains(n, other) {\n  return getUntaintedMethod(\"Node\", n, \"contains\")(other);\n}\nfunction getRootNode(n) {\n  return getUntaintedMethod(\"Node\", n, \"getRootNode\")();\n}\nfunction host(n) {\n  if (!n || !(\"host\" in n)) return null;\n  return getUntaintedAccessor(\"ShadowRoot\", n, \"host\");\n}\nfunction styleSheets(n) {\n  return n.styleSheets;\n}\nfunction shadowRoot(n) {\n  if (!n || !(\"shadowRoot\" in n)) return null;\n  return getUntaintedAccessor(\"Element\", n, \"shadowRoot\");\n}\nfunction querySelector(n, selectors) {\n  return getUntaintedMethod(\"Element\", n, \"querySelector\")(selectors);\n}\nfunction querySelectorAll(n, selectors) {\n  return getUntaintedMethod(\"Element\", n, \"querySelectorAll\")(selectors);\n}\nfunction mutationObserverCtor() {\n  return getUntaintedPrototype(\"MutationObserver\").constructor;\n}\nfunction isFunction(value) {\n  return typeof value === \"function\";\n}\nfunction patch(source, name, replacement) {\n  try {\n    if (!(name in source)) {\n      return () => {\n      };\n    }\n    const original = source[name];\n    const layer = {\n      next: original\n    };\n    const callNext = function(...args) {\n      return layer.next.apply(this, args);\n    };\n    const wrapped = replacement(callNext);\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        __rrweb_layer__: {\n          enumerable: false,\n          value: layer\n        }\n      });\n    }\n    source[name] = wrapped;\n    return () => {\n      if (source[name] === wrapped) {\n        source[name] = layer.next;\n        return;\n      }\n      let current = source[name];\n      while (isFunction(current) && current.__rrweb_layer__) {\n        const currentLayer = current.__rrweb_layer__;\n        if (currentLayer.next === wrapped) {\n          currentLayer.next = layer.next;\n          return;\n        }\n        current = currentLayer.next;\n      }\n    };\n  } catch {\n    return () => {\n    };\n  }\n}\nconst index = {\n  childNodes,\n  parentNode,\n  parentElement,\n  textContent,\n  contains,\n  getRootNode,\n  host,\n  styleSheets,\n  shadowRoot,\n  querySelector,\n  querySelectorAll,\n  mutationObserver: mutationObserverCtor,\n  patch\n};\nfunction isElement(n) {\n  return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n  const hostEl = (\n    // anchor and textarea elements also have a `host` property\n    // but only shadow roots have a `mode` property\n    n && \"host\" in n && \"mode\" in n && index.host(n) || null\n  );\n  return Boolean(\n    hostEl && \"shadowRoot\" in hostEl && index.shadowRoot(hostEl) === n\n  );\n}\nfunction isNativeShadowDom(shadowRoot2) {\n  return Object.prototype.toString.call(shadowRoot2) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n  if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n    cssText = cssText.replace(\n      /\\sbackground-clip:\\s*text;/g,\n      \" -webkit-background-clip: text; background-clip: text;\"\n    );\n  }\n  return cssText;\n}\nfunction escapeImportStatement(rule) {\n  const { cssText } = rule;\n  if (cssText.split('\"').length < 3) return cssText;\n  const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n  if (rule.layerName === \"\") {\n    statement.push(`layer`);\n  } else if (rule.layerName) {\n    statement.push(`layer(${rule.layerName})`);\n  }\n  if (rule.supportsText) {\n    statement.push(`supports(${rule.supportsText})`);\n  }\n  if (rule.media.length) {\n    statement.push(rule.media.mediaText);\n  }\n  return statement.join(\" \") + \";\";\n}\nfunction hasEmptyShorthandLonghand(css) {\n  return /(?:^|[\\s;{}])-?[a-zA-Z][\\w-]*\\s*:\\s*;/.test(css);\n}\nfunction stringifyStylesheet(s) {\n  try {\n    const rules = s.rules || s.cssRules;\n    if (!rules) {\n      return null;\n    }\n    let sheetHref = s.href;\n    if (!sheetHref && s.ownerNode) {\n      sheetHref = s.ownerNode.baseURI;\n    }\n    const stringifiedRules = Array.from(\n      rules,\n      (rule) => stringifyRule(rule, sheetHref)\n    ).join(\"\");\n    return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);\n  } catch (error) {\n    return null;\n  }\n}\nfunction stringifyRule(rule, sheetHref) {\n  var _a2;\n  if (isCSSImportRule(rule)) {\n    let importStringified;\n    try {\n      importStringified = // for same-origin stylesheets,\n      // we can access the imported stylesheet rules directly\n      stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n      escapeImportStatement(rule);\n    } catch (error) {\n      importStringified = rule.cssText;\n    }\n    try {\n      if (importStringified && ((_a2 = rule.styleSheet) == null ? void 0 : _a2.href)) {\n        return absolutifyURLs(importStringified, rule.styleSheet.href);\n      }\n    } catch {\n    }\n    return importStringified;\n  } else {\n    let ruleStringified = rule.cssText;\n    if (isCSSStyleRule(rule) && rule.selectorText.includes(\":\")) {\n      ruleStringified = fixSafariColons(ruleStringified);\n    }\n    if (sheetHref) {\n      return absolutifyURLs(ruleStringified, sheetHref);\n    }\n    return ruleStringified;\n  }\n}\nfunction fixSafariColons(cssStringified) {\n  const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n  return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n  return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n  return \"selectorText\" in rule;\n}\nclass Mirror {\n  constructor() {\n    __publicField(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n    __publicField(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n  }\n  getId(n) {\n    var _a2;\n    if (!n) return -1;\n    const id = (_a2 = this.getMeta(n)) == null ? void 0 : _a2.id;\n    return id ?? -1;\n  }\n  getNode(id) {\n    return this.idNodeMap.get(id) || null;\n  }\n  getIds() {\n    return Array.from(this.idNodeMap.keys());\n  }\n  getMeta(n) {\n    return this.nodeMetaMap.get(n) || null;\n  }\n  // removes the node from idNodeMap\n  // doesn't remove the node from nodeMetaMap\n  removeNodeFromMap(n) {\n    const id = this.getId(n);\n    this.idNodeMap.delete(id);\n    if (n.childNodes) {\n      n.childNodes.forEach(\n        (childNode) => this.removeNodeFromMap(childNode)\n      );\n    }\n    if (isElement(n)) {\n      const shadowRootEl = index.shadowRoot(n);\n      if (shadowRootEl) {\n        this.removeNodeFromMap(shadowRootEl);\n      }\n      if (n.nodeName === \"IFRAME\" && n.contentDocument) {\n        this.removeNodeFromMap(\n          n.contentDocument\n        );\n      }\n    }\n  }\n  has(id) {\n    return this.idNodeMap.has(id);\n  }\n  hasNode(node) {\n    return this.nodeMetaMap.has(node);\n  }\n  add(n, meta) {\n    const id = meta.id;\n    this.idNodeMap.set(id, n);\n    this.nodeMetaMap.set(n, meta);\n  }\n  replace(id, n) {\n    const oldNode = this.getNode(id);\n    if (oldNode) {\n      const meta = this.nodeMetaMap.get(oldNode);\n      if (meta) this.nodeMetaMap.set(n, meta);\n    }\n    this.idNodeMap.set(id, n);\n  }\n  reset() {\n    this.idNodeMap = /* @__PURE__ */ new Map();\n    this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n  }\n}\nfunction createMirror() {\n  return new Mirror();\n}\nfunction maskInputValue({\n  element,\n  maskInputOptions,\n  tagName,\n  type,\n  value,\n  maskInputFn\n}) {\n  let text = value || \"\";\n  const actualType = type && toLowerCase(type);\n  if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {\n    if (maskInputFn) {\n      text = maskInputFn(text, element);\n    } else {\n      text = \"*\".repeat(text.length);\n    }\n  }\n  return text;\n}\nfunction toLowerCase(str) {\n  return str.toLowerCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) return true;\n  const chunkSize = 50;\n  for (let x = 0; x < canvas.width; x += chunkSize) {\n    for (let y = 0; y < canvas.height; y += chunkSize) {\n      const getImageData = ctx.getImageData;\n      const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n      const pixelBuffer = new Uint32Array(\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n        originalGetImageData.call(\n          ctx,\n          x,\n          y,\n          Math.min(chunkSize, canvas.width - x),\n          Math.min(chunkSize, canvas.height - y)\n        ).data.buffer\n      );\n      if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n    }\n  }\n  return true;\n}\nfunction getInputType(element) {\n  const type = element.type;\n  return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n    toLowerCase(type)\n  ) : null;\n}\nfunction extractFileExtension(path, baseURL) {\n  let url;\n  try {\n    url = new URL(path, baseURL ?? window.location.href);\n  } catch (err) {\n    return null;\n  }\n  const regex = /\\.([0-9a-z]+)(?:$)/i;\n  const match = url.pathname.match(regex);\n  return (match == null ? void 0 : match[1]) ?? null;\n}\nfunction extractOrigin(url) {\n  let origin = \"\";\n  if (url.indexOf(\"//\") > -1) {\n    origin = url.split(\"/\").slice(0, 3).join(\"/\");\n  } else {\n    origin = url.split(\"/\")[0];\n  }\n  origin = origin.split(\"?\")[0];\n  return origin;\n}\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absolutifyURLs(cssText, href) {\n  return (cssText || \"\").replace(\n    URL_IN_CSS_REF,\n    (origin, quote1, path1, quote2, path2, path3) => {\n      const filePath = path1 || path2 || path3;\n      const maybeQuote = quote1 || quote2 || \"\";\n      if (!filePath) {\n        return origin;\n      }\n      if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n        return `url(${maybeQuote}${filePath}${maybeQuote})`;\n      }\n      if (DATA_URI.test(filePath)) {\n        return `url(${maybeQuote}${filePath}${maybeQuote})`;\n      }\n      if (filePath[0] === \"/\") {\n        return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n      }\n      const stack = href.split(\"/\");\n      const parts = filePath.split(\"/\");\n      stack.pop();\n      for (const part of parts) {\n        if (part === \".\") {\n          continue;\n        } else if (part === \"..\") {\n          stack.pop();\n        } else {\n          stack.push(part);\n        }\n      }\n      return `url(${maybeQuote}${stack.join(\"/\")}${maybeQuote})`;\n    }\n  );\n}\nconst STRIPED_PLACEHOLDER_SVG = \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxkZWZzPgogICAgPHBhdHRlcm4gaWQ9InN0cmlwZXMiIHBhdHRlcm5Vbml0cz0idXNlclNwYWNlT25Vc2UiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+CiAgICAgIDxyZWN0IHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iYmxhY2siLz4KICAgICAgPHBhdGggZD0iTTggMEgxNkwwIDE2VjhMOCAwWiIgZmlsbD0iIzJEMkQyRCIvPgogICAgICA8cGF0aCBkPSJNMTYgOFYxNkg4TDE2IDhaIiBmaWxsPSIjMkQyRDJEIi8+CiAgICA8L3BhdHRlcm4+CiAgPC9kZWZzPgogIDxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjc3RyaXBlcykiLz4KPC9zdmc+Cg==\";\nconst MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION = 4096;\nfunction recompressBase64Image(img, dataURL, type, quality) {\n  if (!img.complete || img.naturalWidth === 0) {\n    return dataURL;\n  }\n  if (img.naturalWidth > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION || img.naturalHeight > MAX_IMAGE_DIMENSION_FOR_RECOMPRESSION) {\n    return dataURL;\n  }\n  try {\n    const canvas = document.createElement(\"canvas\");\n    canvas.width = img.naturalWidth;\n    canvas.height = img.naturalHeight;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) {\n      return dataURL;\n    }\n    ctx.drawImage(img, 0, 0);\n    const recompressed = canvas.toDataURL(type || \"image/webp\", quality ?? 0.4);\n    return recompressed;\n  } catch (err) {\n    return dataURL;\n  }\n}\nfunction checkDataURLSize(dataURL, maxLength) {\n  if (!maxLength || dataURL.length <= maxLength) {\n    return dataURL;\n  }\n  return STRIPED_PLACEHOLDER_SVG;\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n  return _id++;\n}\nfunction getValidTagName(element) {\n  if (element instanceof HTMLFormElement) {\n    return \"form\";\n  }\n  const processedTagName = toLowerCase(element.tagName);\n  if (tagNameRegex.test(processedTagName)) {\n    return \"div\";\n  }\n  return processedTagName;\n}\nlet canvasService;\nlet canvasCtx;\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n  if (attributeValue.trim() === \"\") {\n    return attributeValue;\n  }\n  let pos = 0;\n  function collectCharacters(regEx) {\n    let chars2;\n    const match = regEx.exec(attributeValue.substring(pos));\n    if (match) {\n      chars2 = match[0];\n      pos += chars2.length;\n      return chars2;\n    }\n    return \"\";\n  }\n  const output = [];\n  while (true) {\n    collectCharacters(SRCSET_COMMAS_OR_SPACES);\n    if (pos >= attributeValue.length) {\n      break;\n    }\n    let url = collectCharacters(SRCSET_NOT_SPACES);\n    if (url.slice(-1) === \",\") {\n      url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n      output.push(url);\n    } else {\n      let descriptorsStr = \"\";\n      url = absoluteToDoc(doc, url);\n      let inParens = false;\n      while (true) {\n        const c = attributeValue.charAt(pos);\n        if (c === \"\") {\n          output.push((url + descriptorsStr).trim());\n          break;\n        } else if (!inParens) {\n          if (c === \",\") {\n            pos += 1;\n            output.push((url + descriptorsStr).trim());\n            break;\n          } else if (c === \"(\") {\n            inParens = true;\n          }\n        } else {\n          if (c === \")\") {\n            inParens = false;\n          }\n        }\n        descriptorsStr += c;\n        pos += 1;\n      }\n    }\n  }\n  return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n  if (!attributeValue || attributeValue.trim() === \"\") {\n    return attributeValue;\n  }\n  return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n  return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n  let a = cachedDocument.get(doc);\n  if (!a) {\n    a = doc.createElement(\"a\");\n    cachedDocument.set(doc, a);\n  }\n  if (!customHref) {\n    customHref = \"\";\n  } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n    return customHref;\n  }\n  a.setAttribute(\"href\", customHref);\n  return a.href;\n}\nfunction capDataURLSize(dataURL, dataURLOptions) {\n  if (dataURLOptions == null ? void 0 : dataURLOptions.maxBase64ImageLength) {\n    return checkDataURLSize(dataURL, dataURLOptions.maxBase64ImageLength);\n  }\n  return dataURL;\n}\nfunction transformAttribute(doc, tagName, name, value, element, dataURLOptions) {\n  var _a2;\n  if (!value) {\n    return value;\n  }\n  if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n    if (tagName === \"link\" && element) {\n      const sheetHref = (_a2 = element.sheet) == null ? void 0 : _a2.href;\n      if (sheetHref) {\n        return sheetHref;\n      }\n    }\n    const transformedValue = absoluteToDoc(doc, value);\n    if (transformedValue.startsWith(\"data:\")) {\n      if (tagName === \"img\" && element) {\n        let processedDataURL = transformedValue;\n        if ((dataURLOptions == null ? void 0 : dataURLOptions.type) || (dataURLOptions == null ? void 0 : dataURLOptions.quality) !== void 0) {\n          processedDataURL = recompressBase64Image(\n            element,\n            transformedValue,\n            dataURLOptions.type,\n            dataURLOptions.quality\n          );\n        }\n        return capDataURLSize(processedDataURL, dataURLOptions);\n      }\n      if (tagName === \"image\") {\n        return capDataURLSize(transformedValue, dataURLOptions);\n      }\n    }\n    return transformedValue;\n  } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n    const transformedValue = absoluteToDoc(doc, value);\n    if (tagName === \"image\" && transformedValue.startsWith(\"data:\")) {\n      return capDataURLSize(transformedValue, dataURLOptions);\n    }\n    return transformedValue;\n  } else if (name === \"background\" && (tagName === \"table\" || tagName === \"td\" || tagName === \"th\")) {\n    return absoluteToDoc(doc, value);\n  } else if (name === \"srcset\") {\n    return getAbsoluteSrcsetString(doc, value);\n  } else if (name === \"style\") {\n    return absolutifyURLs(value, getHref(doc));\n  } else if (tagName === \"object\" && name === \"data\") {\n    return absoluteToDoc(doc, value);\n  }\n  return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n  return (tagName === \"video\" || tagName === \"audio\") && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector) {\n  try {\n    if (typeof blockClass === \"string\") {\n      if (element.classList.contains(blockClass)) {\n        return true;\n      }\n    } else {\n      for (let eIndex = element.classList.length; eIndex--; ) {\n        const className = element.classList[eIndex];\n        if (blockClass.test(className)) {\n          return true;\n        }\n      }\n    }\n    if (blockSelector) {\n      return element.matches(blockSelector);\n    }\n  } catch (e) {\n  }\n  return false;\n}\nfunction classMatchesRegex(node, regex, checkAncestors) {\n  if (!node) return false;\n  if (node.nodeType !== node.ELEMENT_NODE) {\n    if (!checkAncestors) return false;\n    return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n  }\n  for (let eIndex = node.classList.length; eIndex--; ) {\n    const className = node.classList[eIndex];\n    if (regex.test(className)) {\n      return true;\n    }\n  }\n  if (!checkAncestors) return false;\n  return classMatchesRegex(index.parentNode(node), regex, checkAncestors);\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, checkAncestors) {\n  let el;\n  if (isElement(node)) {\n    el = node;\n    if (!index.childNodes(el).length) {\n      return false;\n    }\n  } else if (index.parentElement(node) === null) {\n    return false;\n  } else {\n    el = index.parentElement(node);\n  }\n  try {\n    if (typeof maskTextClass === \"string\") {\n      if (checkAncestors) {\n        if (el.closest(`.${maskTextClass}`)) return true;\n      } else {\n        if (el.classList.contains(maskTextClass)) return true;\n      }\n    } else {\n      if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;\n    }\n    if (maskTextSelector) {\n      if (checkAncestors) {\n        if (el.closest(maskTextSelector)) return true;\n      } else {\n        if (el.matches(maskTextSelector)) return true;\n      }\n    }\n  } catch (e) {\n  }\n  return false;\n}\nfunction removeEventListenerSafely$1(target, type, listener) {\n  const removeEventListener = target.removeEventListener;\n  if (typeof removeEventListener !== \"function\") return;\n  removeEventListener.call(target, type, listener);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n  const noop = () => {\n  };\n  const win = iframeEl.contentWindow;\n  if (!win) {\n    return noop;\n  }\n  let readyState;\n  try {\n    readyState = win.document.readyState;\n  } catch (error) {\n    return noop;\n  }\n  const onSubsequentLoad = () => listener();\n  if (readyState !== \"complete\") {\n    let fired = false;\n    let timer = null;\n    const fireOnce = () => {\n      if (fired) return;\n      fired = true;\n      if (timer !== null) {\n        clearTimeout(timer);\n        timer = null;\n      }\n      removeEventListenerSafely$1(iframeEl, \"load\", onInitialLoad);\n      iframeEl.addEventListener(\"load\", onSubsequentLoad);\n      listener();\n    };\n    const onInitialLoad = () => fireOnce();\n    timer = setTimeout(fireOnce, iframeLoadTimeout);\n    iframeEl.addEventListener(\"load\", onInitialLoad);\n    return () => {\n      if (timer !== null) {\n        clearTimeout(timer);\n        timer = null;\n      }\n      if (fired) {\n        removeEventListenerSafely$1(iframeEl, \"load\", onSubsequentLoad);\n      } else {\n        fired = true;\n        removeEventListenerSafely$1(iframeEl, \"load\", onInitialLoad);\n      }\n    };\n  }\n  const blankUrl = \"about:blank\";\n  let winLocationHref;\n  try {\n    winLocationHref = win.location.href;\n  } catch {\n    return noop;\n  }\n  if (winLocationHref !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n    const initialTimer = setTimeout(listener, 0);\n    iframeEl.addEventListener(\"load\", onSubsequentLoad);\n    return () => {\n      clearTimeout(initialTimer);\n      removeEventListenerSafely$1(iframeEl, \"load\", onSubsequentLoad);\n    };\n  }\n  iframeEl.addEventListener(\"load\", onSubsequentLoad);\n  return () => {\n    removeEventListenerSafely$1(iframeEl, \"load\", onSubsequentLoad);\n  };\n}\nconst stylesheetLoadTracked = /* @__PURE__ */ new Map();\nfunction resetStylesheetLoadTracking() {\n  stylesheetLoadTracked.forEach((controller) => controller.abort());\n  stylesheetLoadTracked.clear();\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n  if (stylesheetLoadTracked.has(link)) return;\n  let styleSheetLoaded;\n  try {\n    styleSheetLoaded = link.sheet;\n  } catch (error) {\n    return;\n  }\n  if (styleSheetLoaded) return;\n  const controller = new AbortController();\n  let fired = false;\n  const fire = () => {\n    if (fired) return;\n    fired = true;\n    try {\n      listener();\n    } finally {\n      stylesheetLoadTracked.delete(link);\n      controller.abort();\n    }\n  };\n  const timer = setTimeout(fire, styleSheetLoadTimeout);\n  controller.signal.addEventListener(\"abort\", () => clearTimeout(timer), {\n    once: true\n  });\n  link.addEventListener(\"load\", fire, {\n    signal: controller.signal,\n    once: true\n  });\n  stylesheetLoadTracked.set(link, controller);\n}\nfunction serializeNode(n, options) {\n  const {\n    doc,\n    mirror: mirror2,\n    blockClass,\n    blockSelector,\n    needsMask,\n    inlineStylesheet,\n    maskInputOptions = {},\n    maskTextFn,\n    maskInputFn,\n    dataURLOptions = {},\n    inlineImages,\n    recordCanvas,\n    keepIframeSrcFn,\n    newlyAddedElement = false\n  } = options;\n  const rootId = getRootId(doc, mirror2);\n  switch (n.nodeType) {\n    case n.DOCUMENT_NODE:\n      if (n.compatMode !== \"CSS1Compat\") {\n        return {\n          type: NodeType.Document,\n          childNodes: [],\n          compatMode: n.compatMode\n          // probably \"BackCompat\"\n        };\n      } else {\n        return {\n          type: NodeType.Document,\n          childNodes: []\n        };\n      }\n    case n.DOCUMENT_TYPE_NODE:\n      return {\n        type: NodeType.DocumentType,\n        name: n.name,\n        publicId: n.publicId,\n        systemId: n.systemId,\n        rootId\n      };\n    case n.ELEMENT_NODE:\n      return serializeElementNode(n, {\n        doc,\n        blockClass,\n        blockSelector,\n        inlineStylesheet,\n        maskInputOptions,\n        maskInputFn,\n        dataURLOptions,\n        inlineImages,\n        recordCanvas,\n        keepIframeSrcFn,\n        newlyAddedElement,\n        rootId\n      });\n    case n.TEXT_NODE:\n      return serializeTextNode(n, {\n        doc,\n        needsMask,\n        maskTextFn,\n        rootId\n      });\n    case n.CDATA_SECTION_NODE:\n      return {\n        type: NodeType.CDATA,\n        textContent: \"\",\n        rootId\n      };\n    case n.COMMENT_NODE:\n      return {\n        type: NodeType.Comment,\n        textContent: index.textContent(n) || \"\",\n        rootId\n      };\n    default:\n      return false;\n  }\n}\nfunction getRootId(doc, mirror2) {\n  if (!mirror2.hasNode(doc)) return void 0;\n  const docId = mirror2.getId(doc);\n  return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n, options) {\n  var _a2;\n  const { needsMask, maskTextFn, rootId } = options;\n  const parent = index.parentNode(n);\n  const parentTagName = parent && parent.tagName;\n  let text = index.textContent(n);\n  const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n  const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n  if (isStyle && text) {\n    try {\n      if (n.nextSibling || n.previousSibling) {\n      } else if ((_a2 = parent.sheet) == null ? void 0 : _a2.cssRules) {\n        const stringified = stringifyStylesheet(\n          parent.sheet\n        );\n        if (stringified && !hasEmptyShorthandLonghand(stringified)) {\n          text = stringified;\n        }\n      }\n    } catch (err) {\n      console.warn(\n        `Cannot get CSS styles from text's parentNode. Error: ${err}`,\n        n\n      );\n    }\n    text = absolutifyURLs(text, getHref(options.doc));\n  }\n  if (isScript) {\n    text = \"SCRIPT_PLACEHOLDER\";\n  }\n  if (!isStyle && !isScript && text && needsMask) {\n    text = maskTextFn ? maskTextFn(text, index.parentElement(n)) : text.replace(/[\\S]/g, \"*\");\n  }\n  return {\n    type: NodeType.Text,\n    textContent: text || \"\",\n    isStyle,\n    rootId\n  };\n}\nfunction findStylesheet(doc, href) {\n  return Array.from(doc.styleSheets).find((s) => s.href === href);\n}\nfunction hrefFrom(n) {\n  return n.href;\n}\nfunction serializeElementNode(n, options) {\n  var _a2, _b, _c;\n  const {\n    doc,\n    blockClass,\n    blockSelector,\n    inlineStylesheet,\n    maskInputOptions = {},\n    maskInputFn,\n    dataURLOptions = {},\n    inlineImages,\n    recordCanvas,\n    keepIframeSrcFn,\n    newlyAddedElement = false,\n    rootId\n  } = options;\n  const needBlock = _isBlockedElement(n, blockClass, blockSelector);\n  const tagName = getValidTagName(n);\n  let attributes = {};\n  const len = n.attributes.length;\n  for (let i = 0; i < len; i++) {\n    const attr = n.attributes[i];\n    if (!ignoreAttribute(tagName, attr.name, attr.value)) {\n      attributes[attr.name] = transformAttribute(\n        doc,\n        tagName,\n        toLowerCase(attr.name),\n        attr.value,\n        n,\n        dataURLOptions\n      );\n    }\n  }\n  if (tagName === \"link\" && inlineStylesheet) {\n    let stylesheet = n.sheet;\n    if (!stylesheet) {\n      const href = hrefFrom(n);\n      if (href) {\n        stylesheet = findStylesheet(doc, href);\n        if (!stylesheet && href.includes(\".css\")) {\n          const rootDomain = window.location.origin;\n          const stylesheetPath = href.replace(window.location.href, \"\");\n          const potentialStylesheetHref = rootDomain + \"/\" + stylesheetPath;\n          stylesheet = findStylesheet(doc, potentialStylesheetHref);\n        }\n      }\n    }\n    let cssText = null;\n    if (stylesheet) {\n      cssText = stringifyStylesheet(stylesheet);\n    }\n    if (cssText) {\n      delete attributes.rel;\n      delete attributes.href;\n      attributes._cssText = cssText;\n    }\n  }\n  if (tagName === \"style\" && n.sheet && // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n  !(n.innerText || index.textContent(n) || \"\").trim().length) {\n    const cssText = stringifyStylesheet(\n      n.sheet\n    );\n    if (cssText) {\n      attributes._cssText = cssText;\n    }\n  }\n  if (tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\") {\n    const value = n.value;\n    const checked = n.checked;\n    if (attributes.type !== \"radio\" && attributes.type !== \"checkbox\" && attributes.type !== \"submit\" && attributes.type !== \"button\" && value) {\n      attributes.value = maskInputValue({\n        element: n,\n        type: getInputType(n),\n        tagName,\n        value,\n        maskInputOptions,\n        maskInputFn\n      });\n    } else if (checked) {\n      attributes.checked = checked;\n    }\n  }\n  if (tagName === \"option\") {\n    if (n.selected && !maskInputOptions[\"select\"]) {\n      attributes.selected = true;\n    } else {\n      delete attributes.selected;\n    }\n  }\n  if (tagName === \"dialog\" && n.open) {\n    try {\n      attributes.rr_open_mode = n.matches(\"dialog:modal\") ? \"modal\" : \"non-modal\";\n    } catch {\n      attributes.rr_open_mode = \"modal\";\n      attributes.ph_rr_could_not_detect_modal = true;\n    }\n  }\n  if (tagName === \"canvas\" && recordCanvas) {\n    if (n.__context === \"2d\") {\n      if (!is2DCanvasBlank(n)) {\n        attributes.rr_dataURL = n.toDataURL(\n          dataURLOptions.type,\n          dataURLOptions.quality\n        );\n      }\n    } else if (!(\"__context\" in n)) {\n      const canvasDataURL = n.toDataURL(\n        dataURLOptions.type,\n        dataURLOptions.quality\n      );\n      const blankCanvas = doc.createElement(\"canvas\");\n      blankCanvas.width = n.width;\n      blankCanvas.height = n.height;\n      const blankCanvasDataURL = blankCanvas.toDataURL(\n        dataURLOptions.type,\n        dataURLOptions.quality\n      );\n      if (canvasDataURL !== blankCanvasDataURL) {\n        attributes.rr_dataURL = canvasDataURL;\n      }\n    }\n  }\n  if (tagName === \"img\" && inlineImages) {\n    if (!canvasService) {\n      canvasService = doc.createElement(\"canvas\");\n      canvasCtx = canvasService.getContext(\"2d\");\n    }\n    const image = n;\n    const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"<unknown-src>\";\n    const priorCrossOrigin = image.crossOrigin;\n    const recordInlineImage = () => {\n      removeEventListenerSafely$1(image, \"load\", recordInlineImage);\n      try {\n        canvasService.width = image.naturalWidth;\n        canvasService.height = image.naturalHeight;\n        canvasCtx.drawImage(image, 0, 0);\n        attributes.rr_dataURL = canvasService.toDataURL(\n          dataURLOptions.type,\n          dataURLOptions.quality\n        );\n      } catch (err) {\n        if (image.crossOrigin !== \"anonymous\") {\n          image.crossOrigin = \"anonymous\";\n          if (image.complete && image.naturalWidth !== 0)\n            recordInlineImage();\n          else image.addEventListener(\"load\", recordInlineImage);\n          return;\n        } else {\n          console.warn(\n            `Cannot inline img src=${imageSrc}! Error: ${err}`\n          );\n        }\n      }\n      if (image.crossOrigin === \"anonymous\") {\n        priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n      }\n    };\n    if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n    else image.addEventListener(\"load\", recordInlineImage);\n  }\n  if (tagName === \"audio\" || tagName === \"video\") {\n    const mediaAttributes = attributes;\n    mediaAttributes.rr_mediaState = n.paused ? \"paused\" : \"played\";\n    mediaAttributes.rr_mediaCurrentTime = n.currentTime;\n    mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;\n    mediaAttributes.rr_mediaMuted = n.muted;\n    mediaAttributes.rr_mediaLoop = n.loop;\n    mediaAttributes.rr_mediaVolume = n.volume;\n  }\n  if (!newlyAddedElement) {\n    if (n.scrollLeft) {\n      attributes.rr_scrollLeft = n.scrollLeft;\n    }\n    if (n.scrollTop) {\n      attributes.rr_scrollTop = n.scrollTop;\n    }\n  }\n  if (needBlock) {\n    const { width, height, left, top } = n.getBoundingClientRect();\n    const computed = (_a2 = doc.defaultView) == null ? void 0 : _a2.getComputedStyle(n);\n    attributes = {\n      class: attributes.class,\n      rr_width: `${width}px`,\n      rr_height: `${height}px`,\n      rr_left: `${Math.floor(left + (((_b = doc.defaultView) == null ? void 0 : _b.scrollX) || 0))}px`,\n      rr_top: `${Math.floor(top + (((_c = doc.defaultView) == null ? void 0 : _c.scrollY) || 0))}px`\n    };\n    if (computed) {\n      attributes.rr_position = computed.position || \"static\";\n      if (computed.transform && computed.transform !== \"none\") {\n        attributes.rr_transform = computed.transform;\n      }\n      if (computed.display && computed.display.startsWith(\"inline\")) {\n        attributes.rr_display = computed.display;\n      }\n    }\n  }\n  if (tagName === \"iframe\" && !keepIframeSrcFn(attributes.src)) {\n    if (!n.contentDocument) {\n      attributes.rr_src = attributes.src;\n    }\n    delete attributes.src;\n  }\n  let isCustomElement;\n  try {\n    if (customElements.get(tagName)) isCustomElement = true;\n  } catch (e) {\n  }\n  return {\n    type: NodeType.Element,\n    tagName,\n    attributes,\n    childNodes: [],\n    isSVG: isSVGElement(n) || void 0,\n    needBlock,\n    rootId,\n    isCustom: isCustomElement\n  };\n}\nfunction lowerIfExists(maybeAttr) {\n  if (maybeAttr === void 0 || maybeAttr === null) {\n    return \"\";\n  } else {\n    return maybeAttr.toLowerCase();\n  }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n  if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n    return true;\n  } else if (sn.type === NodeType.Element) {\n    if (slimDOMOptions.script && // script tag\n    (sn.tagName === \"script\" || // (module)preload link\n    sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" && sn.attributes.as === \"script\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n    sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n      return true;\n    } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n      /^msapplication-tile(image|color)$/\n    ) || lowerIfExists(sn.attributes.name) === \"application-name\" || [\"icon\", \"apple-touch-icon\", \"shortcut icon\"].includes(\n      lowerIfExists(sn.attributes.rel)\n    )))) {\n      return true;\n    } else if (sn.tagName === \"meta\") {\n      if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n        return true;\n      } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n      lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n        return true;\n      } else if (slimDOMOptions.headMetaRobots && [\"robots\", \"googlebot\", \"bingbot\"].includes(\n        lowerIfExists(sn.attributes.name)\n      )) {\n        return true;\n      } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n        return true;\n      } else if (slimDOMOptions.headMetaAuthorship && ([\"author\", \"generator\", \"framework\", \"publisher\", \"progid\"].includes(\n        lowerIfExists(sn.attributes.name)\n      ) || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n        return true;\n      } else if (slimDOMOptions.headMetaVerification && [\n        \"google-site-verification\",\n        \"yandex-verification\",\n        \"csrf-token\",\n        \"p:domain_verify\",\n        \"verify-v1\",\n        \"verification\",\n        \"shopify-checkout-api-token\"\n      ].includes(lowerIfExists(sn.attributes.name))) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\nconst DEFAULT_MAX_DEPTH = 50;\nlet _maxDepthWarned = false;\nlet _maxDepthReached = false;\nfunction wasMaxDepthReached() {\n  return _maxDepthReached;\n}\nfunction resetMaxDepthState() {\n  _maxDepthReached = false;\n  _maxDepthWarned = false;\n}\nfunction serializeNodeWithId(n, options) {\n  const {\n    doc,\n    mirror: mirror2,\n    blockClass,\n    blockSelector,\n    maskTextClass,\n    maskTextSelector,\n    skipChild = false,\n    inlineStylesheet = true,\n    maskInputOptions = {},\n    maskTextFn,\n    maskInputFn,\n    slimDOMOptions,\n    dataURLOptions = {},\n    inlineImages = false,\n    recordCanvas = false,\n    onSerialize,\n    onIframeLoad,\n    iframeLoadTimeout = 5e3,\n    onIframeListenerRegistered,\n    onStylesheetLoad,\n    stylesheetLoadTimeout = 5e3,\n    keepIframeSrcFn = () => false,\n    newlyAddedElement = false,\n    depth = 0,\n    maxDepth = DEFAULT_MAX_DEPTH\n  } = options;\n  let { needsMask } = options;\n  let { preserveWhiteSpace = true } = options;\n  if (depth >= maxDepth) {\n    _maxDepthReached = true;\n    if (!_maxDepthWarned) {\n      _maxDepthWarned = true;\n      console.warn(\n        `[rrweb-snapshot] DOM tree depth exceeded max depth of ${maxDepth}. Children beyond this depth will not be recorded. This may indicate deeply nested DOM structures.`\n      );\n    }\n    return null;\n  }\n  if (!needsMask) {\n    const checkAncestors = needsMask === void 0;\n    needsMask = needMaskingText(\n      n,\n      maskTextClass,\n      maskTextSelector,\n      checkAncestors\n    );\n  }\n  const _serializedNode = serializeNode(n, {\n    doc,\n    mirror: mirror2,\n    blockClass,\n    blockSelector,\n    needsMask,\n    inlineStylesheet,\n    maskInputOptions,\n    maskTextFn,\n    maskInputFn,\n    dataURLOptions,\n    inlineImages,\n    recordCanvas,\n    keepIframeSrcFn,\n    newlyAddedElement\n  });\n  if (!_serializedNode) {\n    console.warn(n, \"not serialized\");\n    return null;\n  }\n  let id;\n  if (mirror2.hasNode(n)) {\n    id = mirror2.getId(n);\n  } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.isStyle && // codeql[js/polynomial-redos] Bounded DOM text node; worst case is recorder slowdown, no exploit.\n  !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n    id = IGNORED_NODE;\n  } else {\n    id = genId();\n  }\n  const serializedNode = Object.assign(_serializedNode, { id });\n  mirror2.add(n, serializedNode);\n  if (id === IGNORED_NODE) {\n    return null;\n  }\n  if (onSerialize) {\n    onSerialize(n);\n  }\n  let recordChild = !skipChild;\n  if (serializedNode.type === NodeType.Element) {\n    recordChild = recordChild && !serializedNode.needBlock;\n    delete serializedNode.needBlock;\n    const shadowRootEl = index.shadowRoot(n);\n    if (shadowRootEl && isNativeShadowDom(shadowRootEl))\n      serializedNode.isShadowHost = true;\n  }\n  if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {\n    if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === \"head\") {\n      preserveWhiteSpace = false;\n    }\n    const bypassOptions = {\n      doc,\n      mirror: mirror2,\n      blockClass,\n      blockSelector,\n      needsMask,\n      maskTextClass,\n      maskTextSelector,\n      skipChild,\n      inlineStylesheet,\n      maskInputOptions,\n      maskTextFn,\n      maskInputFn,\n      slimDOMOptions,\n      dataURLOptions,\n      inlineImages,\n      recordCanvas,\n      preserveWhiteSpace,\n      onSerialize,\n      onIframeLoad,\n      iframeLoadTimeout,\n      onIframeListenerRegistered,\n      onStylesheetLoad,\n      stylesheetLoadTimeout,\n      keepIframeSrcFn,\n      depth: depth + 1,\n      maxDepth\n    };\n    if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"textarea\" && serializedNode.attributes.value !== void 0) ;\n    else {\n      for (const childN of Array.from(index.childNodes(n))) {\n        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n        if (serializedChildNode) {\n          serializedNode.childNodes.push(serializedChildNode);\n        }\n      }\n    }\n    let shadowRootEl = null;\n    if (isElement(n) && (shadowRootEl = index.shadowRoot(n))) {\n      for (const childN of Array.from(index.childNodes(shadowRootEl))) {\n        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n        if (serializedChildNode) {\n          isNativeShadowDom(shadowRootEl) && (serializedChildNode.isShadow = true);\n          serializedNode.childNodes.push(serializedChildNode);\n        }\n      }\n    }\n  }\n  const parent = index.parentNode(n);\n  if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {\n    serializedNode.isShadow = true;\n  }\n  if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"iframe\") {\n    const iframeDisposer = onceIframeLoaded(\n      n,\n      () => {\n        const iframeDoc = n.contentDocument;\n        if (iframeDoc && onIframeLoad) {\n          const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n            doc: iframeDoc,\n            mirror: mirror2,\n            blockClass,\n            blockSelector,\n            needsMask,\n            maskTextClass,\n            maskTextSelector,\n            skipChild: false,\n            inlineStylesheet,\n            maskInputOptions,\n            maskTextFn,\n            maskInputFn,\n            slimDOMOptions,\n            dataURLOptions,\n            inlineImages,\n            recordCanvas,\n            preserveWhiteSpace,\n            onSerialize,\n            onIframeLoad,\n            iframeLoadTimeout,\n            onIframeListenerRegistered,\n            onStylesheetLoad,\n            stylesheetLoadTimeout,\n            keepIframeSrcFn,\n            depth: depth + 1,\n            maxDepth\n          });\n          if (serializedIframeNode) {\n            onIframeLoad(\n              n,\n              serializedIframeNode\n            );\n          }\n        }\n      },\n      iframeLoadTimeout\n    );\n    onIframeListenerRegistered == null ? void 0 : onIframeListenerRegistered(n, iframeDisposer);\n  }\n  if (serializedNode.type === NodeType.Element && serializedNode.tagName === \"link\" && serializedNode.attributes.rel === \"stylesheet\") {\n    onceStylesheetLoaded(\n      n,\n      () => {\n        if (onStylesheetLoad) {\n          const serializedLinkNode = serializeNodeWithId(n, {\n            doc,\n            mirror: mirror2,\n            blockClass,\n            blockSelector,\n            needsMask,\n            maskTextClass,\n            maskTextSelector,\n            skipChild: false,\n            inlineStylesheet,\n            maskInputOptions,\n            maskTextFn,\n            maskInputFn,\n            slimDOMOptions,\n            dataURLOptions,\n            inlineImages,\n            recordCanvas,\n            preserveWhiteSpace,\n            onSerialize,\n            onIframeLoad,\n            iframeLoadTimeout,\n            onStylesheetLoad,\n            stylesheetLoadTimeout,\n            keepIframeSrcFn,\n            depth,\n            maxDepth\n          });\n          if (serializedLinkNode) {\n            onStylesheetLoad(\n              n,\n              serializedLinkNode\n            );\n          }\n        }\n      },\n      stylesheetLoadTimeout\n    );\n  }\n  return serializedNode;\n}\nfunction slimDOMDefaults(slimDOM) {\n  if (slimDOM === true || slimDOM === \"all\") {\n    return {\n      script: true,\n      comment: true,\n      headFavicon: true,\n      headWhitespace: true,\n      headMetaSocial: true,\n      headMetaRobots: true,\n      headMetaHttpEquiv: true,\n      headMetaVerification: true,\n      headMetaAuthorship: slimDOM === \"all\",\n      headMetaDescKeywords: slimDOM === \"all\",\n      headTitleMutations: slimDOM === \"all\"\n    };\n  }\n  if (slimDOM === false) {\n    return {};\n  }\n  return slimDOM;\n}\nfunction snapshot(n, options) {\n  const {\n    mirror: mirror2 = new Mirror(),\n    blockClass = \"rr-block\",\n    blockSelector = null,\n    maskTextClass = \"rr-mask\",\n    maskTextSelector = null,\n    inlineStylesheet = true,\n    inlineImages = false,\n    recordCanvas = false,\n    maskAllInputs = false,\n    maskTextFn,\n    maskInputFn,\n    slimDOM = false,\n    dataURLOptions,\n    preserveWhiteSpace,\n    onSerialize,\n    onIframeLoad,\n    iframeLoadTimeout,\n    onIframeListenerRegistered,\n    onStylesheetLoad,\n    stylesheetLoadTimeout,\n    keepIframeSrcFn = () => false,\n    maxDepth\n  } = options || {};\n  const maskInputOptions = maskAllInputs === true ? {\n    color: true,\n    date: true,\n    \"datetime-local\": true,\n    email: true,\n    month: true,\n    number: true,\n    range: true,\n    search: true,\n    tel: true,\n    text: true,\n    time: true,\n    url: true,\n    week: true,\n    textarea: true,\n    select: true,\n    password: true\n  } : maskAllInputs === false ? {\n    password: true\n  } : maskAllInputs;\n  const slimDOMOptions = slimDOMDefaults(slimDOM);\n  return serializeNodeWithId(n, {\n    doc: n,\n    mirror: mirror2,\n    blockClass,\n    blockSelector,\n    maskTextClass,\n    maskTextSelector,\n    skipChild: false,\n    inlineStylesheet,\n    maskInputOptions,\n    maskTextFn,\n    maskInputFn,\n    slimDOMOptions,\n    dataURLOptions,\n    inlineImages,\n    recordCanvas,\n    preserveWhiteSpace,\n    onSerialize,\n    onIframeLoad,\n    iframeLoadTimeout,\n    onIframeListenerRegistered,\n    onStylesheetLoad,\n    stylesheetLoadTimeout,\n    keepIframeSrcFn,\n    newlyAddedElement: false,\n    maxDepth\n  });\n}\nclass BaseRRNode {\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n  constructor(..._args) {\n    __publicField(this, \"parentElement\", null);\n    __publicField(this, \"parentNode\", null);\n    __publicField(this, \"ownerDocument\");\n    __publicField(this, \"firstChild\", null);\n    __publicField(this, \"lastChild\", null);\n    __publicField(this, \"previousSibling\", null);\n    __publicField(this, \"nextSibling\", null);\n    __publicField(this, \"ELEMENT_NODE\", 1);\n    __publicField(this, \"TEXT_NODE\", 3);\n    // corresponding nodeType value of standard HTML Node\n    __publicField(this, \"nodeType\");\n    __publicField(this, \"nodeName\");\n    __publicField(this, \"RRNodeType\");\n  }\n  get childNodes() {\n    const childNodes2 = [];\n    let childIterator = this.firstChild;\n    while (childIterator) {\n      childNodes2.push(childIterator);\n      childIterator = childIterator.nextSibling;\n    }\n    return childNodes2;\n  }\n  contains(node) {\n    if (!(node instanceof BaseRRNode)) return false;\n    else if (node.ownerDocument !== this.ownerDocument) return false;\n    else if (node === this) return true;\n    while (node.parentNode) {\n      if (node.parentNode === this) return true;\n      node = node.parentNode;\n    }\n    return false;\n  }\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  appendChild(_newChild) {\n    throw new Error(\n      `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`\n    );\n  }\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  insertBefore(_newChild, _refChild) {\n    throw new Error(\n      `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`\n    );\n  }\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  removeChild(_node) {\n    throw new Error(\n      `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`\n    );\n  }\n  toString() {\n    return \"RRNode\";\n  }\n}\nfunction on(type, fn, target = document) {\n  const options = { capture: true, passive: true };\n  target.addEventListener(type, fn, options);\n  return () => removeEventListenerSafely(target, type, fn, options);\n}\nfunction removeEventListenerSafely(target, type, fn, options) {\n  callSafely(() => {\n    const removeEventListener = target.removeEventListener;\n    if (typeof removeEventListener !== \"function\") {\n      return;\n    }\n    if (options === void 0) {\n      removeEventListener.call(target, type, fn);\n      return;\n    }\n    removeEventListener.call(target, type, fn, options);\n  });\n}\nfunction callSafely(fn) {\n  try {\n    fn();\n  } catch (error) {\n    if (!(error instanceof DOMException && error.name === \"SecurityError\")) {\n      throw error;\n    }\n  }\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = \"Please stop import mirror directly. Instead of that,\\r\\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\r\\nor you can use record.mirror to access the mirror instance during recording.\";\nlet _mirror = {\n  map: {},\n  getId() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n    return -1;\n  },\n  getNode() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n    return null;\n  },\n  removeNodeFromMap() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n  },\n  has() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n    return false;\n  },\n  reset() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n  }\n};\nif (typeof window !== \"undefined\" && window.Proxy && window.Reflect) {\n  _mirror = new Proxy(_mirror, {\n    get(target, prop, receiver) {\n      if (prop === \"map\") {\n        console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n      }\n      return Reflect.get(target, prop, receiver);\n    }\n  });\n}\nfunction throttle(func, wait, options = {}) {\n  let timeout = null;\n  let previous = 0;\n  return function(...args) {\n    const now = Date.now();\n    if (!previous && options.leading === false) {\n      previous = now;\n    }\n    const remaining = wait - (now - previous);\n    const context = this;\n    if (remaining <= 0 || remaining > wait) {\n      if (timeout) {\n        clearTimeout(timeout);\n        timeout = null;\n      }\n      previous = now;\n      func.apply(context, args);\n    } else if (!timeout && options.trailing !== false) {\n      timeout = setTimeout(() => {\n        previous = options.leading === false ? 0 : Date.now();\n        timeout = null;\n        func.apply(context, args);\n      }, remaining);\n    }\n  };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n  const original = win.Object.getOwnPropertyDescriptor(target, key);\n  win.Object.defineProperty(\n    target,\n    key,\n    isRevoked ? d : {\n      set(value) {\n        setTimeout(() => {\n          try {\n            d.set.call(this, value);\n          } catch {\n          }\n        }, 0);\n        if (original && original.set) {\n          original.set.call(this, value);\n        }\n      }\n    }\n  );\n  return () => hookSetter(target, key, original || {}, true);\n}\nlet nowTimestamp = Date.now;\nif (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {\n  nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\n}\nfunction getWindowScroll(win) {\n  var _a2, _b, _c, _d;\n  const doc = win.document;\n  return {\n    left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc.documentElement.scrollLeft || (doc == null ? void 0 : doc.body) && ((_a2 = index.parentElement(doc.body)) == null ? void 0 : _a2.scrollLeft) || ((_b = doc == null ? void 0 : doc.body) == null ? void 0 : _b.scrollLeft) || 0,\n    top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || (doc == null ? void 0 : doc.body) && ((_c = index.parentElement(doc.body)) == null ? void 0 : _c.scrollTop) || ((_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.scrollTop) || 0\n  };\n}\nfunction getWindowHeight() {\n  return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;\n}\nfunction getWindowWidth() {\n  return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;\n}\nfunction closestElementOfNode(node) {\n  if (!node) {\n    return null;\n  }\n  const el = node.nodeType === node.ELEMENT_NODE ? node : index.parentElement(node);\n  return el;\n}\nfunction isBlocked(node, blockClass, blockSelector, checkAncestors) {\n  if (!node) {\n    return false;\n  }\n  const el = closestElementOfNode(node);\n  if (!el) {\n    return false;\n  }\n  try {\n    if (typeof blockClass === \"string\") {\n      if (el.classList.contains(blockClass)) return true;\n      if (checkAncestors && el.closest(\".\" + blockClass) !== null) return true;\n    } else {\n      if (classMatchesRegex(el, blockClass, checkAncestors)) return true;\n    }\n  } catch (e) {\n  }\n  if (blockSelector) {\n    if (el.matches(blockSelector)) return true;\n    if (checkAncestors && el.closest(blockSelector) !== null) return true;\n  }\n  return false;\n}\nfunction isSerialized(n, mirror2) {\n  return mirror2.getId(n) !== -1;\n}\nfunction isIgnored(n, mirror2, slimDOMOptions) {\n  if (n.tagName === \"TITLE\" && slimDOMOptions.headTitleMutations) {\n    return true;\n  }\n  return mirror2.getId(n) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror2) {\n  if (isShadowRoot(target)) {\n    return false;\n  }\n  const id = mirror2.getId(target);\n  if (!mirror2.has(id)) {\n    return true;\n  }\n  const parent = index.parentNode(target);\n  if (parent && parent.nodeType === target.DOCUMENT_NODE) {\n    return false;\n  }\n  if (!parent) {\n    return true;\n  }\n  return isAncestorRemoved(parent, mirror2);\n}\nfunction legacy_isTouchEvent(event) {\n  return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n  if (\"NodeList\" in win && !win.NodeList.prototype.forEach) {\n    win.NodeList.prototype.forEach = Array.prototype.forEach;\n  }\n  if (\"DOMTokenList\" in win && !win.DOMTokenList.prototype.forEach) {\n    win.DOMTokenList.prototype.forEach = Array.prototype.forEach;\n  }\n}\nfunction isSerializedIframe(n, mirror2) {\n  return Boolean(n.nodeName === \"IFRAME\" && mirror2.getMeta(n));\n}\nfunction isSerializedStylesheet(n, mirror2) {\n  return Boolean(\n    n.nodeName === \"LINK\" && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute(\"rel\") === \"stylesheet\" && mirror2.getMeta(n)\n  );\n}\nfunction hasShadowRoot(n) {\n  if (!n) return false;\n  if (n instanceof BaseRRNode && \"shadowRoot\" in n) {\n    return Boolean(n.shadowRoot);\n  }\n  return Boolean(index.shadowRoot(n));\n}\nclass StyleSheetMirror {\n  constructor() {\n    __publicField(this, \"id\", 1);\n    __publicField(this, \"styleIDMap\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"idStyleMap\", /* @__PURE__ */ new Map());\n  }\n  getId(stylesheet) {\n    return this.styleIDMap.get(stylesheet) ?? -1;\n  }\n  has(stylesheet) {\n    return this.styleIDMap.has(stylesheet);\n  }\n  /**\n   * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n   */\n  add(stylesheet, id) {\n    if (this.has(stylesheet)) return this.getId(stylesheet);\n    let newId;\n    if (id === void 0) {\n      newId = this.id++;\n    } else newId = id;\n    this.styleIDMap.set(stylesheet, newId);\n    this.idStyleMap.set(newId, stylesheet);\n    return newId;\n  }\n  getStyle(id) {\n    return this.idStyleMap.get(id) || null;\n  }\n  reset() {\n    this.styleIDMap = /* @__PURE__ */ new WeakMap();\n    this.idStyleMap = /* @__PURE__ */ new Map();\n    this.id = 1;\n  }\n  generateId() {\n    return this.id++;\n  }\n}\nfunction getShadowHost(n) {\n  var _a2;\n  let shadowHost = null;\n  if (\"getRootNode\" in n && ((_a2 = index.getRootNode(n)) == null ? void 0 : _a2.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && index.host(index.getRootNode(n)))\n    shadowHost = index.host(index.getRootNode(n));\n  return shadowHost;\n}\nfunction getRootShadowHost(n) {\n  let rootShadowHost = n;\n  let shadowHost;\n  while (shadowHost = getShadowHost(rootShadowHost))\n    rootShadowHost = shadowHost;\n  return rootShadowHost;\n}\nfunction shadowHostInDom(n) {\n  const doc = n.ownerDocument;\n  if (!doc) return false;\n  const shadowHost = getRootShadowHost(n);\n  return index.contains(doc, shadowHost);\n}\nfunction inDom(n) {\n  const doc = n.ownerDocument;\n  if (!doc) return false;\n  return index.contains(doc, n) || shadowHostInDom(n);\n}\nfunction isNodeInLinkedList(n) {\n  return \"__ln\" in n;\n}\nclass DoubleLinkedList {\n  constructor() {\n    __publicField(this, \"length\", 0);\n    __publicField(this, \"head\", null);\n    __publicField(this, \"tail\", null);\n  }\n  get(position) {\n    if (position >= this.length) {\n      throw new Error(\"Position outside of list range\");\n    }\n    let current = this.head;\n    for (let index2 = 0; index2 < position; index2++) {\n      current = (current == null ? void 0 : current.next) || null;\n    }\n    return current;\n  }\n  addNode(n) {\n    const node = {\n      value: n,\n      previous: null,\n      next: null\n    };\n    n.__ln = node;\n    if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n      const current = n.previousSibling.__ln.next;\n      node.next = current;\n      node.previous = n.previousSibling.__ln;\n      n.previousSibling.__ln.next = node;\n      if (current) {\n        current.previous = node;\n      }\n    } else if (n.nextSibling && isNodeInLinkedList(n.nextSibling) && n.nextSibling.__ln.previous) {\n      const current = n.nextSibling.__ln.previous;\n      node.previous = current;\n      node.next = n.nextSibling.__ln;\n      n.nextSibling.__ln.previous = node;\n      if (current) {\n        current.next = node;\n      }\n    } else {\n      if (this.head) {\n        this.head.previous = node;\n      }\n      node.next = this.head;\n      this.head = node;\n    }\n    if (node.next === null) {\n      this.tail = node;\n    }\n    this.length++;\n  }\n  removeNode(n) {\n    const current = n.__ln;\n    if (!this.head) {\n      return;\n    }\n    if (!current.previous) {\n      this.head = current.next;\n      if (this.head) {\n        this.head.previous = null;\n      } else {\n        this.tail = null;\n      }\n    } else {\n      current.previous.next = current.next;\n      if (current.next) {\n        current.next.previous = current.previous;\n      } else {\n        this.tail = current.previous;\n      }\n    }\n    if (n.__ln) {\n      delete n.__ln;\n    }\n    this.length--;\n  }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n  constructor() {\n    __publicField(this, \"frozen\", false);\n    __publicField(this, \"locked\", false);\n    __publicField(this, \"texts\", []);\n    __publicField(this, \"attributes\", []);\n    __publicField(this, \"attributeMap\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"removes\", []);\n    __publicField(this, \"mapRemoves\", []);\n    __publicField(this, \"movedMap\", {});\n    /**\n     * the browser MutationObserver emits multiple mutations after\n     * a delay for performance reasons, making tracing added nodes hard\n     * in our `processMutations` callback function.\n     * For example, if we append an element el_1 into body, and then append\n     * another element el_2 into el_1, these two mutations may be passed to the\n     * callback function together when the two operations were done.\n     * Generally we need to trace child nodes of newly added nodes, but in this\n     * case if we count el_2 as el_1's child node in the first mutation record,\n     * then we will count el_2 again in the second mutation record which was\n     * duplicated.\n     * To avoid of duplicate counting added nodes, we use a Set to store\n     * added nodes and its child nodes during iterate mutation records. Then\n     * collect added nodes from the Set which have no duplicate copy. But\n     * this also causes newly added nodes will not be serialized with id ASAP,\n     * which means all the id related calculation should be lazy too.\n     */\n    __publicField(this, \"addedSet\", /* @__PURE__ */ new Set());\n    __publicField(this, \"movedSet\", /* @__PURE__ */ new Set());\n    __publicField(this, \"droppedSet\", /* @__PURE__ */ new Set());\n    __publicField(this, \"removesSubTreeCache\", /* @__PURE__ */ new Set());\n    __publicField(this, \"mutationCb\");\n    __publicField(this, \"blockClass\");\n    __publicField(this, \"blockSelector\");\n    __publicField(this, \"maskTextClass\");\n    __publicField(this, \"maskTextSelector\");\n    __publicField(this, \"inlineStylesheet\");\n    __publicField(this, \"maskInputOptions\");\n    __publicField(this, \"maskTextFn\");\n    __publicField(this, \"maskInputFn\");\n    __publicField(this, \"keepIframeSrcFn\");\n    __publicField(this, \"recordCanvas\");\n    __publicField(this, \"inlineImages\");\n    __publicField(this, \"slimDOMOptions\");\n    __publicField(this, \"dataURLOptions\");\n    __publicField(this, \"doc\");\n    __publicField(this, \"mirror\");\n    __publicField(this, \"iframeManager\");\n    __publicField(this, \"stylesheetManager\");\n    __publicField(this, \"shadowDomManager\");\n    __publicField(this, \"canvasManager\");\n    __publicField(this, \"processedNodeManager\");\n    __publicField(this, \"unattachedDoc\");\n    __publicField(this, \"canvasManagerReleased\", false);\n    __publicField(this, \"processMutations\", (mutations) => {\n      mutations.forEach(this.processMutation);\n      this.emit();\n    });\n    __publicField(this, \"emit\", () => {\n      if (this.frozen || this.locked) {\n        return;\n      }\n      const adds = [];\n      const addedIds = /* @__PURE__ */ new Set();\n      const addList = new DoubleLinkedList();\n      const getNextId = (n) => {\n        let ns = n;\n        let nextId = IGNORED_NODE;\n        while (nextId === IGNORED_NODE) {\n          ns = ns && ns.nextSibling;\n          nextId = ns && this.mirror.getId(ns);\n        }\n        return nextId;\n      };\n      const pushAdd = (n) => {\n        const parent = index.parentNode(n);\n        if (!parent || !inDom(n) || parent.tagName === \"TEXTAREA\") {\n          return;\n        }\n        const parentId = isShadowRoot(parent) ? this.mirror.getId(getShadowHost(n)) : this.mirror.getId(parent);\n        const nextId = getNextId(n);\n        if (parentId === -1 || nextId === -1) {\n          return addList.addNode(n);\n        }\n        const sn = serializeNodeWithId(n, {\n          doc: this.doc,\n          mirror: this.mirror,\n          blockClass: this.blockClass,\n          blockSelector: this.blockSelector,\n          maskTextClass: this.maskTextClass,\n          maskTextSelector: this.maskTextSelector,\n          skipChild: true,\n          newlyAddedElement: true,\n          inlineStylesheet: this.inlineStylesheet,\n          maskInputOptions: this.maskInputOptions,\n          maskTextFn: this.maskTextFn,\n          maskInputFn: this.maskInputFn,\n          slimDOMOptions: this.slimDOMOptions,\n          dataURLOptions: this.dataURLOptions,\n          recordCanvas: this.recordCanvas,\n          inlineImages: this.inlineImages,\n          onSerialize: (currentN) => {\n            if (isSerializedIframe(currentN, this.mirror)) {\n              this.iframeManager.addIframe(currentN);\n            }\n            if (isSerializedStylesheet(currentN, this.mirror)) {\n              this.stylesheetManager.trackLinkElement(\n                currentN\n              );\n            }\n            if (hasShadowRoot(n)) {\n              this.shadowDomManager.addShadowRoot(index.shadowRoot(n), this.doc);\n            }\n          },\n          onIframeLoad: (iframe, childSn) => {\n            this.iframeManager.attachIframe(iframe, childSn);\n            this.shadowDomManager.observeAttachShadow(iframe);\n          },\n          onIframeListenerRegistered: (iframe, disposer) => {\n            this.iframeManager.registerLoadListenerDisposer(iframe, disposer);\n          },\n          onStylesheetLoad: (link, childSn) => {\n            this.stylesheetManager.attachLinkElement(link, childSn);\n          }\n        });\n        if (sn) {\n          adds.push({\n            parentId,\n            nextId,\n            node: sn\n          });\n          addedIds.add(sn.id);\n        }\n      };\n      while (this.mapRemoves.length) {\n        this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n      }\n      for (const n of this.movedSet) {\n        if (isParentRemoved(this.removesSubTreeCache, n, this.mirror) && !this.movedSet.has(index.parentNode(n))) {\n          continue;\n        }\n        pushAdd(n);\n      }\n      for (const n of this.addedSet) {\n        if (!isAncestorInSet(this.droppedSet, n) && !isParentRemoved(this.removesSubTreeCache, n, this.mirror)) {\n          pushAdd(n);\n        } else if (isAncestorInSet(this.movedSet, n)) {\n          pushAdd(n);\n        } else {\n          this.droppedSet.add(n);\n        }\n      }\n      let candidate = null;\n      while (addList.length) {\n        let node = null;\n        if (candidate) {\n          const parentId = this.mirror.getId(index.parentNode(candidate.value));\n          const nextId = getNextId(candidate.value);\n          if (parentId !== -1 && nextId !== -1) {\n            node = candidate;\n          }\n        }\n        if (!node) {\n          let tailNode = addList.tail;\n          while (tailNode) {\n            const _node = tailNode;\n            tailNode = tailNode.previous;\n            if (_node) {\n              const parentId = this.mirror.getId(index.parentNode(_node.value));\n              const nextId = getNextId(_node.value);\n              if (nextId === -1) continue;\n              else if (parentId !== -1) {\n                node = _node;\n                break;\n              } else {\n                const unhandledNode = _node.value;\n                const parent = index.parentNode(unhandledNode);\n                if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n                  const shadowHost = index.host(parent);\n                  const parentId2 = this.mirror.getId(shadowHost);\n                  if (parentId2 !== -1) {\n                    node = _node;\n                    break;\n                  }\n                }\n              }\n            }\n          }\n        }\n        if (!node) {\n          while (addList.head) {\n            addList.removeNode(addList.head.value);\n          }\n          break;\n        }\n        candidate = node.previous;\n        addList.removeNode(node.value);\n        pushAdd(node.value);\n      }\n      const payload = {\n        texts: this.texts.map((text) => {\n          const n = text.node;\n          const parent = index.parentNode(n);\n          if (parent && parent.tagName === \"TEXTAREA\") {\n            this.genTextAreaValueMutation(parent);\n          }\n          return {\n            id: this.mirror.getId(n),\n            value: text.value\n          };\n        }).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)),\n        attributes: this.attributes.map((attribute) => {\n          const { attributes } = attribute;\n          if (typeof attributes.style === \"string\") {\n            const diffAsStr = JSON.stringify(attribute.styleDiff);\n            const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n            if (diffAsStr.length < attributes.style.length) {\n              if ((diffAsStr + unchangedAsStr).split(\"var(\").length === attributes.style.split(\"var(\").length) {\n                attributes.style = attribute.styleDiff;\n              }\n            }\n          }\n          return {\n            id: this.mirror.getId(attribute.node),\n            attributes\n          };\n        }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)),\n        removes: this.removes,\n        adds\n      };\n      if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {\n        return;\n      }\n      this.texts = [];\n      this.attributes = [];\n      this.attributeMap = /* @__PURE__ */ new WeakMap();\n      this.removes = [];\n      this.addedSet = /* @__PURE__ */ new Set();\n      this.movedSet = /* @__PURE__ */ new Set();\n      this.droppedSet = /* @__PURE__ */ new Set();\n      this.removesSubTreeCache = /* @__PURE__ */ new Set();\n      this.movedMap = {};\n      this.mutationCb(payload);\n    });\n    __publicField(this, \"bufferBelongsToIframe\", (iframeEl) => {\n      return this.doc === iframeEl.contentDocument;\n    });\n    __publicField(this, \"genTextAreaValueMutation\", (textarea) => {\n      let item = this.attributeMap.get(textarea);\n      if (!item) {\n        item = {\n          node: textarea,\n          attributes: {},\n          styleDiff: {},\n          _unchangedStyles: {}\n        };\n        this.attributes.push(item);\n        this.attributeMap.set(textarea, item);\n      }\n      const value = Array.from(\n        index.childNodes(textarea),\n        (cn) => index.textContent(cn) || \"\"\n      ).join(\"\");\n      item.attributes.value = maskInputValue({\n        element: textarea,\n        maskInputOptions: this.maskInputOptions,\n        tagName: textarea.tagName,\n        type: getInputType(textarea),\n        value,\n        maskInputFn: this.maskInputFn\n      });\n    });\n    __publicField(this, \"processMutation\", (m) => {\n      if (isIgnored(m.target, this.mirror, this.slimDOMOptions)) {\n        return;\n      }\n      switch (m.type) {\n        case \"characterData\": {\n          const value = index.textContent(m.target);\n          if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) && value !== m.oldValue) {\n            this.texts.push({\n              value: needMaskingText(\n                m.target,\n                this.maskTextClass,\n                this.maskTextSelector,\n                true\n                // checkAncestors\n              ) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\\S]/g, \"*\") : value,\n              node: m.target\n            });\n          }\n          break;\n        }\n        case \"attributes\": {\n          const target = m.target;\n          let attributeName = m.attributeName;\n          let value = m.target.getAttribute(attributeName);\n          if (attributeName === \"value\") {\n            const type = getInputType(target);\n            value = maskInputValue({\n              element: target,\n              maskInputOptions: this.maskInputOptions,\n              tagName: target.tagName,\n              type,\n              value,\n              maskInputFn: this.maskInputFn\n            });\n          }\n          if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || value === m.oldValue) {\n            return;\n          }\n          let item = this.attributeMap.get(m.target);\n          if (target.tagName === \"IFRAME\" && attributeName === \"src\" && !this.keepIframeSrcFn(value)) {\n            if (!target.contentDocument) {\n              attributeName = \"rr_src\";\n            } else {\n              return;\n            }\n          }\n          if (!item) {\n            item = {\n              node: m.target,\n              attributes: {},\n              styleDiff: {},\n              _unchangedStyles: {}\n            };\n            this.attributes.push(item);\n            this.attributeMap.set(m.target, item);\n          }\n          if (attributeName === \"type\" && target.tagName === \"INPUT\" && (m.oldValue || \"\").toLowerCase() === \"password\") {\n            target.setAttribute(\"data-rr-is-password\", \"true\");\n          }\n          if (!ignoreAttribute(target.tagName, attributeName)) {\n            item.attributes[attributeName] = transformAttribute(\n              this.doc,\n              toLowerCase(target.tagName),\n              toLowerCase(attributeName),\n              value,\n              target,\n              this.dataURLOptions\n            );\n            if (attributeName === \"style\") {\n              if (!this.unattachedDoc) {\n                try {\n                  this.unattachedDoc = document.implementation.createHTMLDocument();\n                } catch (e) {\n                  this.unattachedDoc = this.doc;\n                }\n              }\n              const old = this.unattachedDoc.createElement(\"span\");\n              if (m.oldValue) {\n                old.style.cssText = m.oldValue;\n              }\n              for (const pname of Array.from(target.style)) {\n                const newValue = target.style.getPropertyValue(pname);\n                const newPriority = target.style.getPropertyPriority(pname);\n                if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {\n                  if (newPriority === \"\") {\n                    item.styleDiff[pname] = newValue;\n                  } else {\n                    item.styleDiff[pname] = [newValue, newPriority];\n                  }\n                } else {\n                  item._unchangedStyles[pname] = [newValue, newPriority];\n                }\n              }\n              for (const pname of Array.from(old.style)) {\n                if (target.style.getPropertyValue(pname) === \"\") {\n                  item.styleDiff[pname] = false;\n                }\n              }\n            } else if (attributeName === \"open\" && target.tagName === \"DIALOG\") {\n              if (target.matches(\"dialog:modal\")) {\n                item.attributes[\"rr_open_mode\"] = \"modal\";\n              } else {\n                item.attributes[\"rr_open_mode\"] = \"non-modal\";\n              }\n            }\n          }\n          break;\n        }\n        case \"childList\": {\n          if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\n            return;\n          if (m.target.tagName === \"TEXTAREA\") {\n            this.genTextAreaValueMutation(m.target);\n            return;\n          }\n          m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n          m.removedNodes.forEach((n) => {\n            const nodeId = this.mirror.getId(n);\n            const parentId = isShadowRoot(m.target) ? this.mirror.getId(index.host(m.target)) : this.mirror.getId(m.target);\n            if (isBlocked(m.target, this.blockClass, this.blockSelector, false) || isIgnored(n, this.mirror, this.slimDOMOptions) || !isSerialized(n, this.mirror)) {\n              return;\n            }\n            if (this.addedSet.has(n)) {\n              deepDelete(this.addedSet, n);\n              this.droppedSet.add(n);\n            } else if (this.addedSet.has(m.target) && nodeId === -1) ;\n            else if (isAncestorRemoved(m.target, this.mirror)) ;\n            else if (this.movedSet.has(n) && this.movedMap[moveKey(nodeId, parentId)]) {\n              deepDelete(this.movedSet, n);\n            } else {\n              this.removes.push({\n                parentId,\n                id: nodeId,\n                isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0\n              });\n              processRemoves(n, this.removesSubTreeCache);\n            }\n            this.mapRemoves.push(n);\n          });\n          break;\n        }\n      }\n    });\n    /**\n     * Make sure you check if `n`'s parent is blocked before calling this function\n     * */\n    __publicField(this, \"genAdds\", (n, target) => {\n      if (this.processedNodeManager.inOtherBuffer(n, this)) return;\n      if (this.addedSet.has(n)) {\n        this.addedSet.delete(n);\n        this.addedSet.add(n);\n        return;\n      }\n      if (this.movedSet.has(n)) return;\n      if (this.mirror.hasNode(n)) {\n        if (isIgnored(n, this.mirror, this.slimDOMOptions)) {\n          return;\n        }\n        this.movedSet.add(n);\n        let targetId = null;\n        if (target && this.mirror.hasNode(target)) {\n          targetId = this.mirror.getId(target);\n        }\n        if (targetId && targetId !== -1) {\n          this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\n        }\n      } else {\n        this.addedSet.add(n);\n        this.droppedSet.delete(n);\n      }\n      if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\n        index.childNodes(n).forEach((childN) => this.genAdds(childN));\n        if (hasShadowRoot(n)) {\n          index.childNodes(index.shadowRoot(n)).forEach((childN) => {\n            this.processedNodeManager.add(childN, this);\n            this.genAdds(childN, n);\n          });\n        }\n      }\n    });\n  }\n  init(options) {\n    [\n      \"mutationCb\",\n      \"blockClass\",\n      \"blockSelector\",\n      \"maskTextClass\",\n      \"maskTextSelector\",\n      \"inlineStylesheet\",\n      \"maskInputOptions\",\n      \"maskTextFn\",\n      \"maskInputFn\",\n      \"keepIframeSrcFn\",\n      \"recordCanvas\",\n      \"inlineImages\",\n      \"slimDOMOptions\",\n      \"dataURLOptions\",\n      \"doc\",\n      \"mirror\",\n      \"iframeManager\",\n      \"stylesheetManager\",\n      \"shadowDomManager\",\n      \"canvasManager\",\n      \"processedNodeManager\"\n    ].forEach((key) => {\n      this[key] = options[key];\n    });\n    this.canvasManager.acquire();\n  }\n  freeze() {\n    this.frozen = true;\n    this.canvasManager.freeze();\n  }\n  unfreeze() {\n    this.frozen = false;\n    this.canvasManager.unfreeze();\n    this.emit();\n  }\n  isFrozen() {\n    return this.frozen;\n  }\n  lock() {\n    this.locked = true;\n    this.canvasManager.lock();\n  }\n  unlock() {\n    this.locked = false;\n    this.canvasManager.unlock();\n    this.emit();\n  }\n  reset() {\n    this.releaseCanvasManager();\n  }\n  // Idempotent so teardown can run twice (iframe pagehide + stop); shadow restore handlers call this directly, not reset(), per the recursion-guard unit test.\n  releaseCanvasManager() {\n    if (this.canvasManagerReleased) {\n      return;\n    }\n    this.canvasManagerReleased = true;\n    this.canvasManager.reset();\n  }\n  bufferDoc() {\n    return this.doc;\n  }\n  destroy() {\n    while (this.mapRemoves.length) {\n      this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n    }\n  }\n}\nfunction deepDelete(addsSet, n) {\n  addsSet.delete(n);\n  index.childNodes(n).forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction processRemoves(n, cache) {\n  const queue = [n];\n  while (queue.length) {\n    const next = queue.pop();\n    if (cache.has(next)) continue;\n    cache.add(next);\n    index.childNodes(next).forEach((n2) => queue.push(n2));\n  }\n  return;\n}\nfunction isParentRemoved(removes, n, mirror2) {\n  if (removes.size === 0) return false;\n  return _isParentRemoved(removes, n);\n}\nfunction _isParentRemoved(removes, n, _mirror2) {\n  const node = index.parentNode(n);\n  if (!node) return false;\n  return removes.has(node);\n}\nfunction isAncestorInSet(set, n) {\n  if (set.size === 0) return false;\n  return _isAncestorInSet(set, n);\n}\nfunction _isAncestorInSet(set, n) {\n  const parent = index.parentNode(n);\n  if (!parent) {\n    return false;\n  }\n  if (set.has(parent)) {\n    return true;\n  }\n  return _isAncestorInSet(set, parent);\n}\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n  errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n  errorHandler = void 0;\n}\nconst callbackWrapper = (cb) => {\n  if (!errorHandler) {\n    return cb;\n  }\n  const rrwebWrapped = ((...rest) => {\n    try {\n      return cb(...rest);\n    } catch (error) {\n      if (errorHandler && errorHandler(error) === true) {\n        return;\n      }\n      throw error;\n    }\n  });\n  return rrwebWrapped;\n};\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n  try {\n    if (\"composedPath\" in event) {\n      const path = event.composedPath();\n      if (path.length) {\n        return path[0];\n      }\n    } else if (\"path\" in event && event.path.length) {\n      return event.path[0];\n    }\n  } catch {\n  }\n  return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n  const mutationBuffer = new MutationBuffer();\n  mutationBuffers.push(mutationBuffer);\n  mutationBuffer.init(options);\n  const observer = new (mutationObserverCtor())(\n    callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer))\n  );\n  const mutationObserverInit = {\n    attributes: true,\n    attributeOldValue: true,\n    characterData: true,\n    characterDataOldValue: true,\n    childList: true,\n    subtree: true\n  };\n  if (options.attributeFilter && options.attributeFilter.length > 0) {\n    mutationObserverInit.attributeFilter = options.attributeFilter;\n  }\n  observer.observe(rootEl, mutationObserverInit);\n  return { observer, buffer: mutationBuffer };\n}\nfunction initMoveObserver({\n  mousemoveCb,\n  sampling,\n  doc,\n  mirror: mirror2\n}) {\n  if (sampling.mousemove === false) {\n    return () => {\n    };\n  }\n  const threshold = typeof sampling.mousemove === \"number\" ? sampling.mousemove : 50;\n  const callbackThreshold = typeof sampling.mousemoveCallback === \"number\" ? sampling.mousemoveCallback : 500;\n  let positions = [];\n  let timeBaseline;\n  const wrappedCb = throttle(\n    callbackWrapper(\n      (source) => {\n        const totalOffset = Date.now() - timeBaseline;\n        mousemoveCb(\n          positions.map((p) => {\n            p.timeOffset -= totalOffset;\n            return p;\n          }),\n          source\n        );\n        positions = [];\n        timeBaseline = null;\n      }\n    ),\n    callbackThreshold\n  );\n  const updatePosition = callbackWrapper(\n    throttle(\n      callbackWrapper((evt) => {\n        const target = getEventTarget(evt);\n        const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;\n        if (!timeBaseline) {\n          timeBaseline = nowTimestamp();\n        }\n        positions.push({\n          x: clientX,\n          y: clientY,\n          id: mirror2.getId(target),\n          timeOffset: nowTimestamp() - timeBaseline\n        });\n        wrappedCb(\n          typeof DragEvent !== \"undefined\" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove\n        );\n      }),\n      threshold,\n      {\n        trailing: false\n      }\n    )\n  );\n  const handlers = [\n    on(\"mousemove\", updatePosition, doc),\n    on(\"touchmove\", updatePosition, doc),\n    on(\"drag\", updatePosition, doc)\n  ];\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\nfunction initMouseInteractionObserver({\n  mouseInteractionCb,\n  doc,\n  mirror: mirror2,\n  blockClass,\n  blockSelector,\n  sampling\n}) {\n  if (sampling.mouseInteraction === false) {\n    return () => {\n    };\n  }\n  const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;\n  const handlers = [];\n  let currentPointerType = null;\n  const getHandler = (eventKey) => {\n    return (event) => {\n      const target = getEventTarget(event);\n      if (isBlocked(target, blockClass, blockSelector, true)) {\n        return;\n      }\n      let pointerType = null;\n      let thisEventKey = eventKey;\n      if (\"pointerType\" in event) {\n        switch (event.pointerType) {\n          case \"mouse\":\n            pointerType = PointerTypes.Mouse;\n            break;\n          case \"touch\":\n            pointerType = PointerTypes.Touch;\n            break;\n          case \"pen\":\n            pointerType = PointerTypes.Pen;\n            break;\n        }\n        if (pointerType === PointerTypes.Touch) {\n          if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n            thisEventKey = \"TouchStart\";\n          } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n            thisEventKey = \"TouchEnd\";\n          }\n        } else if (pointerType === PointerTypes.Pen) ;\n      } else if (legacy_isTouchEvent(event)) {\n        pointerType = PointerTypes.Touch;\n      }\n      if (pointerType !== null) {\n        currentPointerType = pointerType;\n        if (thisEventKey.startsWith(\"Touch\") && pointerType === PointerTypes.Touch || thisEventKey.startsWith(\"Mouse\") && pointerType === PointerTypes.Mouse) {\n          pointerType = null;\n        }\n      } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n        pointerType = currentPointerType;\n        currentPointerType = null;\n      }\n      const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n      if (!e) {\n        return;\n      }\n      const id = mirror2.getId(target);\n      const { clientX, clientY } = e;\n      callbackWrapper(mouseInteractionCb)({\n        type: MouseInteractions[thisEventKey],\n        id,\n        x: clientX,\n        y: clientY,\n        ...pointerType !== null && { pointerType }\n      });\n    };\n  };\n  Object.keys(MouseInteractions).filter(\n    (key) => Number.isNaN(Number(key)) && !key.endsWith(\"_Departed\") && disableMap[key] !== false\n  ).forEach((eventKey) => {\n    let eventName = toLowerCase(eventKey);\n    const handler = getHandler(eventKey);\n    if (window.PointerEvent) {\n      switch (MouseInteractions[eventKey]) {\n        case MouseInteractions.MouseDown:\n        case MouseInteractions.MouseUp:\n          eventName = eventName.replace(\n            \"mouse\",\n            \"pointer\"\n          );\n          break;\n        case MouseInteractions.TouchStart:\n        case MouseInteractions.TouchEnd:\n          return;\n      }\n    }\n    handlers.push(on(eventName, handler, doc));\n  });\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\nfunction initScrollObserver({\n  scrollCb,\n  doc,\n  mirror: mirror2,\n  blockClass,\n  blockSelector,\n  sampling\n}) {\n  const lastEmitted = /* @__PURE__ */ new Map();\n  const emitScrollPosition = (evt) => {\n    const target = getEventTarget(evt);\n    if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n      return;\n    }\n    const id = mirror2.getId(target);\n    let x;\n    let y;\n    if (target === doc && doc.defaultView) {\n      const scrollLeftTop = getWindowScroll(doc.defaultView);\n      x = scrollLeftTop.left;\n      y = scrollLeftTop.top;\n    } else {\n      x = target.scrollLeft;\n      y = target.scrollTop;\n    }\n    const key = `${x},${y}`;\n    if (lastEmitted.get(id) === key) {\n      return;\n    }\n    lastEmitted.set(id, key);\n    scrollCb({ id, x, y });\n  };\n  const updatePosition = callbackWrapper(\n    throttle(\n      callbackWrapper((evt) => emitScrollPosition(evt)),\n      sampling.scroll || 100\n    )\n  );\n  const handlers = [on(\"scroll\", updatePosition, doc)];\n  if (\"onscrollend\" in doc) {\n    handlers.push(on(\"scrollend\", callbackWrapper(emitScrollPosition), doc));\n  }\n  return () => handlers.forEach((h) => h());\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n  let lastH = -1;\n  let lastW = -1;\n  const updateDimension = callbackWrapper(\n    throttle(\n      callbackWrapper(() => {\n        const height = getWindowHeight();\n        const width = getWindowWidth();\n        if (lastH !== height || lastW !== width) {\n          viewportResizeCb({\n            width: Number(width),\n            height: Number(height)\n          });\n          lastH = height;\n          lastW = width;\n        }\n      }),\n      200\n    )\n  );\n  return on(\"resize\", updateDimension, win);\n}\nfunction findAndRemoveIframeBuffer(iframeEl, knownDocs) {\n  for (let i = mutationBuffers.length - 1; i >= 0; i--) {\n    const buf = mutationBuffers[i];\n    if (!buf) continue;\n    let match = buf.bufferBelongsToIframe(iframeEl);\n    if (!match && knownDocs && knownDocs.has(buf.bufferDoc())) {\n      match = true;\n    }\n    if (match) {\n      buf.reset();\n      mutationBuffers.splice(i, 1);\n    }\n  }\n}\nconst INPUT_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"];\nconst lastInputValueMap = /* @__PURE__ */ new WeakMap();\nfunction initInputObserver({\n  inputCb,\n  doc,\n  mirror: mirror2,\n  blockClass,\n  blockSelector,\n  ignoreClass,\n  ignoreSelector,\n  maskInputOptions,\n  maskInputFn,\n  sampling,\n  userTriggeredOnInput\n}) {\n  function eventHandler(event) {\n    let target = getEventTarget(event);\n    const userTriggered = event.isTrusted;\n    const tagName = target && target.tagName;\n    if (target && tagName === \"OPTION\") {\n      target = index.parentElement(target);\n    }\n    if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {\n      return;\n    }\n    if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {\n      return;\n    }\n    let text = target.value;\n    let isChecked = false;\n    const type = getInputType(target) || \"\";\n    if (type === \"radio\" || type === \"checkbox\") {\n      isChecked = target.checked;\n    } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {\n      text = maskInputValue({\n        element: target,\n        maskInputOptions,\n        tagName,\n        type,\n        value: text,\n        maskInputFn\n      });\n    }\n    cbWithDedup(\n      target,\n      userTriggeredOnInput ? { text, isChecked, userTriggered } : { text, isChecked }\n    );\n    const name = target.name;\n    if (type === \"radio\" && name && isChecked) {\n      doc.querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`).forEach((el) => {\n        if (el !== target) {\n          const text2 = el.value;\n          cbWithDedup(\n            el,\n            userTriggeredOnInput ? { text: text2, isChecked: !isChecked, userTriggered: false } : { text: text2, isChecked: !isChecked }\n          );\n        }\n      });\n    }\n  }\n  function cbWithDedup(target, v) {\n    const lastInputValue = lastInputValueMap.get(target);\n    if (!lastInputValue || lastInputValue.text !== v.text || lastInputValue.isChecked !== v.isChecked) {\n      lastInputValueMap.set(target, v);\n      const id = mirror2.getId(target);\n      callbackWrapper(inputCb)({\n        ...v,\n        id\n      });\n    }\n  }\n  const events = sampling.input === \"last\" ? [\"change\"] : [\"input\", \"change\"];\n  const handlers = events.map(\n    (eventName) => on(eventName, callbackWrapper(eventHandler), doc)\n  );\n  const currentWindow = doc.defaultView;\n  if (!currentWindow) {\n    return () => {\n      handlers.forEach((h) => h());\n    };\n  }\n  const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n    currentWindow.HTMLInputElement.prototype,\n    \"value\"\n  );\n  const hookProperties = [\n    [currentWindow.HTMLInputElement.prototype, \"value\"],\n    [currentWindow.HTMLInputElement.prototype, \"checked\"],\n    [currentWindow.HTMLSelectElement.prototype, \"value\"],\n    [currentWindow.HTMLTextAreaElement.prototype, \"value\"],\n    // Some UI library use selectedIndex to set select value\n    [currentWindow.HTMLSelectElement.prototype, \"selectedIndex\"],\n    [currentWindow.HTMLOptionElement.prototype, \"selected\"]\n  ];\n  if (propertyDescriptor && propertyDescriptor.set) {\n    handlers.push(\n      ...hookProperties.map(\n        (p) => hookSetter(\n          p[0],\n          p[1],\n          {\n            set() {\n              callbackWrapper(eventHandler)({\n                target: this,\n                isTrusted: false\n                // userTriggered to false as this could well be programmatic\n              });\n            }\n          },\n          false,\n          currentWindow\n        )\n      )\n    );\n  }\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\nfunction getNestedCSSRulePositions(rule) {\n  const positions = [];\n  function recurse(childRule, pos) {\n    if (hasNestedCSSRule(\"CSSGroupingRule\") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule(\"CSSMediaRule\") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule(\"CSSSupportsRule\") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule(\"CSSConditionRule\") && childRule.parentRule instanceof CSSConditionRule) {\n      const rules = Array.from(\n        childRule.parentRule.cssRules\n      );\n      const index2 = rules.indexOf(childRule);\n      pos.unshift(index2);\n      return recurse(childRule.parentRule, pos);\n    } else if (childRule.parentStyleSheet) {\n      const rules = Array.from(childRule.parentStyleSheet.cssRules);\n      const index2 = rules.indexOf(childRule);\n      pos.unshift(index2);\n    }\n    return pos;\n  }\n  return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror2, styleMirror) {\n  let id, styleId;\n  if (!sheet) return {};\n  if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);\n  else styleId = styleMirror.getId(sheet);\n  return {\n    styleId,\n    id\n  };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {\n  if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n    return () => {\n    };\n  }\n  const insertRule = win.CSSStyleSheet.prototype.insertRule;\n  win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n    apply: callbackWrapper(\n      (target, thisArg, argumentsList) => {\n        const [rule, index2] = argumentsList;\n        const { id, styleId } = getIdAndStyleId(\n          thisArg,\n          mirror2,\n          stylesheetManager.styleMirror\n        );\n        if (id && id !== -1 || styleId && styleId !== -1) {\n          styleSheetRuleCb({\n            id,\n            styleId,\n            adds: [{ rule, index: index2 }]\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      }\n    )\n  });\n  win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2 = this.cssRules.length) {\n    const rule = `${selector} { ${styleBlock} }`;\n    return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule, index2]);\n  };\n  const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n  win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n    apply: callbackWrapper(\n      (target, thisArg, argumentsList) => {\n        const [index2] = argumentsList;\n        const { id, styleId } = getIdAndStyleId(\n          thisArg,\n          mirror2,\n          stylesheetManager.styleMirror\n        );\n        if (id && id !== -1 || styleId && styleId !== -1) {\n          styleSheetRuleCb({\n            id,\n            styleId,\n            removes: [{ index: index2 }]\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      }\n    )\n  });\n  win.CSSStyleSheet.prototype.removeRule = function(index2) {\n    return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index2]);\n  };\n  let replace;\n  if (win.CSSStyleSheet.prototype.replace) {\n    replace = win.CSSStyleSheet.prototype.replace;\n    win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n      apply: callbackWrapper(\n        (target, thisArg, argumentsList) => {\n          const [text] = argumentsList;\n          const { id, styleId } = getIdAndStyleId(\n            thisArg,\n            mirror2,\n            stylesheetManager.styleMirror\n          );\n          if (id && id !== -1 || styleId && styleId !== -1) {\n            styleSheetRuleCb({\n              id,\n              styleId,\n              replace: text\n            });\n          }\n          return target.apply(thisArg, argumentsList);\n        }\n      )\n    });\n  }\n  let replaceSync;\n  if (win.CSSStyleSheet.prototype.replaceSync) {\n    replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n    win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n      apply: callbackWrapper(\n        (target, thisArg, argumentsList) => {\n          const [text] = argumentsList;\n          const { id, styleId } = getIdAndStyleId(\n            thisArg,\n            mirror2,\n            stylesheetManager.styleMirror\n          );\n          if (id && id !== -1 || styleId && styleId !== -1) {\n            styleSheetRuleCb({\n              id,\n              styleId,\n              replaceSync: text\n            });\n          }\n          return target.apply(thisArg, argumentsList);\n        }\n      )\n    });\n  }\n  const supportedNestedCSSRuleTypes = {};\n  if (canMonkeyPatchNestedCSSRule(\"CSSGroupingRule\")) {\n    supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n  } else {\n    if (canMonkeyPatchNestedCSSRule(\"CSSMediaRule\")) {\n      supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n    }\n    if (canMonkeyPatchNestedCSSRule(\"CSSConditionRule\")) {\n      supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n    }\n    if (canMonkeyPatchNestedCSSRule(\"CSSSupportsRule\")) {\n      supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n    }\n  }\n  const unmodifiedFunctions = {};\n  Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n    unmodifiedFunctions[typeKey] = {\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      insertRule: type.prototype.insertRule,\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      deleteRule: type.prototype.deleteRule\n    };\n    type.prototype.insertRule = new Proxy(\n      unmodifiedFunctions[typeKey].insertRule,\n      {\n        apply: callbackWrapper(\n          (target, thisArg, argumentsList) => {\n            const [rule, index2] = argumentsList;\n            const { id, styleId } = getIdAndStyleId(\n              thisArg.parentStyleSheet,\n              mirror2,\n              stylesheetManager.styleMirror\n            );\n            if (id && id !== -1 || styleId && styleId !== -1) {\n              styleSheetRuleCb({\n                id,\n                styleId,\n                adds: [\n                  {\n                    rule,\n                    index: [\n                      ...getNestedCSSRulePositions(thisArg),\n                      index2 || 0\n                      // defaults to 0\n                    ]\n                  }\n                ]\n              });\n            }\n            return target.apply(thisArg, argumentsList);\n          }\n        )\n      }\n    );\n    type.prototype.deleteRule = new Proxy(\n      unmodifiedFunctions[typeKey].deleteRule,\n      {\n        apply: callbackWrapper(\n          (target, thisArg, argumentsList) => {\n            const [index2] = argumentsList;\n            const { id, styleId } = getIdAndStyleId(\n              thisArg.parentStyleSheet,\n              mirror2,\n              stylesheetManager.styleMirror\n            );\n            if (id && id !== -1 || styleId && styleId !== -1) {\n              styleSheetRuleCb({\n                id,\n                styleId,\n                removes: [\n                  { index: [...getNestedCSSRulePositions(thisArg), index2] }\n                ]\n              });\n            }\n            return target.apply(thisArg, argumentsList);\n          }\n        )\n      }\n    );\n  });\n  return callbackWrapper(() => {\n    win.CSSStyleSheet.prototype.insertRule = insertRule;\n    win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n    replace && (win.CSSStyleSheet.prototype.replace = replace);\n    replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n    Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n      type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n      type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n    });\n  });\n}\nfunction initAdoptedStyleSheetObserver({\n  mirror: mirror2,\n  stylesheetManager\n}, host2) {\n  var _a2, _b, _c;\n  let hostId = null;\n  if (host2.nodeName === \"#document\") hostId = mirror2.getId(host2);\n  else hostId = mirror2.getId(index.host(host2));\n  const patchTarget = host2.nodeName === \"#document\" ? (_a2 = host2.defaultView) == null ? void 0 : _a2.Document : (_c = (_b = host2.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;\n  const originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(\n    patchTarget == null ? void 0 : patchTarget.prototype,\n    \"adoptedStyleSheets\"\n  ) : void 0;\n  if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)\n    return () => {\n    };\n  Object.defineProperty(host2, \"adoptedStyleSheets\", {\n    configurable: originalPropertyDescriptor.configurable,\n    enumerable: originalPropertyDescriptor.enumerable,\n    get() {\n      var _a3;\n      return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);\n    },\n    set(sheets) {\n      var _a3;\n      let result;\n      try {\n        result = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);\n      } catch (e) {\n        if (!!e && typeof e === \"object\" && e.name === \"NotAllowedError\") {\n          return;\n        }\n        throw e;\n      }\n      if (hostId !== null && hostId !== -1) {\n        try {\n          stylesheetManager.adoptStyleSheets(sheets, hostId);\n        } catch (e) {\n        }\n      }\n      return result;\n    }\n  });\n  return callbackWrapper(() => {\n    Object.defineProperty(host2, \"adoptedStyleSheets\", {\n      configurable: originalPropertyDescriptor.configurable,\n      enumerable: originalPropertyDescriptor.enumerable,\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      get: originalPropertyDescriptor.get,\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      set: originalPropertyDescriptor.set\n    });\n  });\n}\nfunction initStyleDeclarationObserver({\n  styleDeclarationCb,\n  mirror: mirror2,\n  ignoreCSSAttributes,\n  stylesheetManager\n}, { win }) {\n  const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n  win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n    apply: callbackWrapper(\n      (target, thisArg, argumentsList) => {\n        var _a2;\n        const [property, value, priority] = argumentsList;\n        if (ignoreCSSAttributes.has(property)) {\n          return setProperty.apply(thisArg, [property, value, priority]);\n        }\n        const { id, styleId } = getIdAndStyleId(\n          (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n          mirror2,\n          stylesheetManager.styleMirror\n        );\n        if (id && id !== -1 || styleId && styleId !== -1) {\n          styleDeclarationCb({\n            id,\n            styleId,\n            set: {\n              property,\n              value,\n              priority\n            },\n            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n            index: getNestedCSSRulePositions(thisArg.parentRule)\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      }\n    )\n  });\n  const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n  win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n    apply: callbackWrapper(\n      (target, thisArg, argumentsList) => {\n        var _a2;\n        const [property] = argumentsList;\n        if (ignoreCSSAttributes.has(property)) {\n          return removeProperty.apply(thisArg, [property]);\n        }\n        const { id, styleId } = getIdAndStyleId(\n          (_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet,\n          mirror2,\n          stylesheetManager.styleMirror\n        );\n        if (id && id !== -1 || styleId && styleId !== -1) {\n          styleDeclarationCb({\n            id,\n            styleId,\n            remove: {\n              property\n            },\n            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n            index: getNestedCSSRulePositions(thisArg.parentRule)\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      }\n    )\n  });\n  return callbackWrapper(() => {\n    win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n    win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n  });\n}\nfunction initMediaInteractionObserver({\n  mediaInteractionCb,\n  blockClass,\n  blockSelector,\n  mirror: mirror2,\n  sampling,\n  doc\n}) {\n  const handler = callbackWrapper(\n    (type) => throttle(\n      callbackWrapper((event) => {\n        const target = getEventTarget(event);\n        if (!target || isBlocked(target, blockClass, blockSelector, true)) {\n          return;\n        }\n        const { currentTime, volume, muted, playbackRate, loop } = target;\n        mediaInteractionCb({\n          type,\n          id: mirror2.getId(target),\n          currentTime,\n          volume,\n          muted,\n          playbackRate,\n          loop\n        });\n      }),\n      sampling.media || 500\n    )\n  );\n  const handlers = [\n    on(\"play\", handler(MediaInteractions.Play), doc),\n    on(\"pause\", handler(MediaInteractions.Pause), doc),\n    on(\"seeked\", handler(MediaInteractions.Seeked), doc),\n    on(\"volumechange\", handler(MediaInteractions.VolumeChange), doc),\n    on(\"ratechange\", handler(MediaInteractions.RateChange), doc)\n  ];\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\nfunction initFontObserver({ fontCb, doc }) {\n  const win = doc.defaultView;\n  if (!win) {\n    return () => {\n    };\n  }\n  const handlers = [];\n  const fontMap = /* @__PURE__ */ new WeakMap();\n  const originalFontFace = win.FontFace;\n  win.FontFace = function FontFace(family, source, descriptors) {\n    const fontFace = new originalFontFace(\n      family,\n      source,\n      descriptors\n    );\n    fontMap.set(fontFace, {\n      family,\n      buffer: typeof source !== \"string\",\n      descriptors,\n      fontSource: typeof source === \"string\" ? source : JSON.stringify(Array.from(new Uint8Array(source)))\n    });\n    return fontFace;\n  };\n  const restoreHandler = patch(\n    doc.fonts,\n    \"add\",\n    function(original) {\n      return function(fontFace) {\n        setTimeout(\n          callbackWrapper(() => {\n            const p = fontMap.get(fontFace);\n            if (p) {\n              fontCb(p);\n              fontMap.delete(fontFace);\n            }\n          }),\n          0\n        );\n        return original.apply(this, [fontFace]);\n      };\n    }\n  );\n  handlers.push(() => {\n    win.FontFace = originalFontFace;\n  });\n  handlers.push(restoreHandler);\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\nfunction initSelectionObserver(param) {\n  const { doc, mirror: mirror2, blockClass, blockSelector, selectionCb } = param;\n  let collapsed = true;\n  const updateSelection = callbackWrapper(() => {\n    const selection = doc.getSelection();\n    if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;\n    collapsed = selection.isCollapsed || false;\n    const ranges = [];\n    const count = selection.rangeCount || 0;\n    for (let i = 0; i < count; i++) {\n      const range = selection.getRangeAt(i);\n      const { startContainer, startOffset, endContainer, endOffset } = range;\n      const blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);\n      if (blocked) continue;\n      ranges.push({\n        start: mirror2.getId(startContainer),\n        startOffset,\n        end: mirror2.getId(endContainer),\n        endOffset\n      });\n    }\n    selectionCb({ ranges });\n  });\n  updateSelection();\n  return on(\"selectionchange\", updateSelection);\n}\nfunction initCustomElementObserver({\n  doc,\n  customElementCb\n}) {\n  const win = doc.defaultView;\n  if (!win || !win.customElements) return () => {\n  };\n  const restoreHandler = patch(\n    win.customElements,\n    \"define\",\n    function(original) {\n      return function(name, constructor, options) {\n        try {\n          customElementCb({\n            define: {\n              name\n            }\n          });\n        } catch (e) {\n          console.warn(`Custom element callback failed for ${name}`);\n        }\n        return original.apply(this, [name, constructor, options]);\n      };\n    }\n  );\n  return restoreHandler;\n}\nfunction mergeHooks(o, hooks) {\n  const {\n    mutationCb,\n    mousemoveCb,\n    mouseInteractionCb,\n    scrollCb,\n    viewportResizeCb,\n    inputCb,\n    mediaInteractionCb,\n    styleSheetRuleCb,\n    styleDeclarationCb,\n    canvasMutationCb,\n    fontCb,\n    selectionCb,\n    customElementCb\n  } = o;\n  o.mutationCb = (...p) => {\n    if (hooks.mutation) {\n      hooks.mutation(...p);\n    }\n    mutationCb(...p);\n  };\n  o.mousemoveCb = (...p) => {\n    if (hooks.mousemove) {\n      hooks.mousemove(...p);\n    }\n    mousemoveCb(...p);\n  };\n  o.mouseInteractionCb = (...p) => {\n    if (hooks.mouseInteraction) {\n      hooks.mouseInteraction(...p);\n    }\n    mouseInteractionCb(...p);\n  };\n  o.scrollCb = (...p) => {\n    if (hooks.scroll) {\n      hooks.scroll(...p);\n    }\n    scrollCb(...p);\n  };\n  o.viewportResizeCb = (...p) => {\n    if (hooks.viewportResize) {\n      hooks.viewportResize(...p);\n    }\n    viewportResizeCb(...p);\n  };\n  o.inputCb = (...p) => {\n    if (hooks.input) {\n      hooks.input(...p);\n    }\n    inputCb(...p);\n  };\n  o.mediaInteractionCb = (...p) => {\n    if (hooks.mediaInteaction) {\n      hooks.mediaInteaction(...p);\n    }\n    mediaInteractionCb(...p);\n  };\n  o.styleSheetRuleCb = (...p) => {\n    if (hooks.styleSheetRule) {\n      hooks.styleSheetRule(...p);\n    }\n    styleSheetRuleCb(...p);\n  };\n  o.styleDeclarationCb = (...p) => {\n    if (hooks.styleDeclaration) {\n      hooks.styleDeclaration(...p);\n    }\n    styleDeclarationCb(...p);\n  };\n  o.canvasMutationCb = (...p) => {\n    if (hooks.canvasMutation) {\n      hooks.canvasMutation(...p);\n    }\n    canvasMutationCb(...p);\n  };\n  o.fontCb = (...p) => {\n    if (hooks.font) {\n      hooks.font(...p);\n    }\n    fontCb(...p);\n  };\n  o.selectionCb = (...p) => {\n    if (hooks.selection) {\n      hooks.selection(...p);\n    }\n    selectionCb(...p);\n  };\n  o.customElementCb = (...c) => {\n    if (hooks.customElement) {\n      hooks.customElement(...c);\n    }\n    customElementCb(...c);\n  };\n}\nfunction initObservers(o, hooks = {}) {\n  const currentWindow = o.doc.defaultView;\n  if (!currentWindow) {\n    return () => {\n    };\n  }\n  mergeHooks(o, hooks);\n  let mutationObserver;\n  let mutationBuffer;\n  if (o.recordDOM) {\n    const result = initMutationObserver(o, o.doc);\n    mutationObserver = result.observer;\n    mutationBuffer = result.buffer;\n  }\n  const mousemoveHandler = initMoveObserver(o);\n  const mouseInteractionHandler = initMouseInteractionObserver(o);\n  const scrollHandler = initScrollObserver(o);\n  const viewportResizeHandler = initViewportResizeObserver(o, {\n    win: currentWindow\n  });\n  const inputHandler = initInputObserver(o);\n  const mediaInteractionHandler = initMediaInteractionObserver(o);\n  let styleSheetObserver = () => {\n  };\n  let adoptedStyleSheetObserver = () => {\n  };\n  let styleDeclarationObserver = () => {\n  };\n  let fontObserver = () => {\n  };\n  if (o.recordDOM) {\n    styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n    adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n    styleDeclarationObserver = initStyleDeclarationObserver(o, {\n      win: currentWindow\n    });\n    if (o.collectFonts) {\n      fontObserver = initFontObserver(o);\n    }\n  }\n  const selectionObserver = initSelectionObserver(o);\n  const customElementObserver = initCustomElementObserver(o);\n  const pluginHandlers = [];\n  for (const plugin of o.plugins) {\n    pluginHandlers.push(\n      plugin.observer(plugin.callback, currentWindow, plugin.options)\n    );\n  }\n  return callbackWrapper(() => {\n    if (mutationBuffer) {\n      mutationBuffer.destroy();\n      mutationBuffer.reset();\n      const index2 = mutationBuffers.indexOf(mutationBuffer);\n      if (index2 !== -1) {\n        mutationBuffers.splice(index2, 1);\n      }\n    }\n    o.shadowDomManager.resetForDoc(o.doc);\n    mutationObserver == null ? void 0 : mutationObserver.disconnect();\n    mousemoveHandler();\n    mouseInteractionHandler();\n    scrollHandler();\n    viewportResizeHandler();\n    inputHandler();\n    mediaInteractionHandler();\n    styleSheetObserver();\n    adoptedStyleSheetObserver();\n    styleDeclarationObserver();\n    fontObserver();\n    selectionObserver();\n    customElementObserver();\n    pluginHandlers.forEach((h) => h());\n  });\n}\nfunction hasNestedCSSRule(prop) {\n  return typeof window[prop] !== \"undefined\";\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n  return Boolean(\n    typeof window[prop] !== \"undefined\" && // Note: Generally, this check _shouldn't_ be necessary\n    // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n    window[prop].prototype && \"insertRule\" in window[prop].prototype && \"deleteRule\" in window[prop].prototype\n  );\n}\nclass CrossOriginIframeMirror {\n  constructor(generateIdFn) {\n    __publicField(this, \"iframeIdToRemoteIdMap\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"iframeRemoteIdToIdMap\", /* @__PURE__ */ new WeakMap());\n    this.generateIdFn = generateIdFn;\n  }\n  getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n    const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n    const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n    let id = idToRemoteIdMap.get(remoteId);\n    if (!id) {\n      id = this.generateIdFn();\n      idToRemoteIdMap.set(remoteId, id);\n      remoteIdToIdMap.set(id, remoteId);\n    }\n    return id;\n  }\n  getIds(iframe, remoteId) {\n    const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n    return remoteId.map(\n      (id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)\n    );\n  }\n  getRemoteId(iframe, id, map) {\n    const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n    if (typeof id !== \"number\") return id;\n    const remoteId = remoteIdToIdMap.get(id);\n    if (!remoteId) return -1;\n    return remoteId;\n  }\n  getRemoteIds(iframe, ids) {\n    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n    return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n  }\n  reset(iframe) {\n    if (!iframe) {\n      this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n      this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n      return;\n    }\n    this.iframeIdToRemoteIdMap.delete(iframe);\n    this.iframeRemoteIdToIdMap.delete(iframe);\n  }\n  getIdToRemoteIdMap(iframe) {\n    let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n    if (!idToRemoteIdMap) {\n      idToRemoteIdMap = /* @__PURE__ */ new Map();\n      this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n    }\n    return idToRemoteIdMap;\n  }\n  getRemoteIdToIdMap(iframe) {\n    let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n    if (!remoteIdToIdMap) {\n      remoteIdToIdMap = /* @__PURE__ */ new Map();\n      this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n    }\n    return remoteIdToIdMap;\n  }\n}\nclass IframeManager {\n  constructor(options) {\n    __publicField(this, \"iframes\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"crossOriginIframeMap\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"crossOriginIframeMirror\", new CrossOriginIframeMirror(genId));\n    __publicField(this, \"crossOriginIframeStyleMirror\");\n    __publicField(this, \"crossOriginIframeRootIdMap\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"mirror\");\n    __publicField(this, \"mutationCb\");\n    __publicField(this, \"wrappedEmit\");\n    __publicField(this, \"loadListener\");\n    __publicField(this, \"pageHideListener\");\n    __publicField(this, \"stylesheetManager\");\n    __publicField(this, \"recordCrossOriginIframes\");\n    __publicField(this, \"messageHandler\");\n    // Strong Map — keys pin Windows; every entry must be deleted on detach.\n    __publicField(this, \"nestedIframeListeners\", /* @__PURE__ */ new Map());\n    // Originals captured per iframe so cleanup survives iframe.src swaps.\n    __publicField(this, \"attachedWindows\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"attachedDocuments\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"attachedIframes\", /* @__PURE__ */ new Map());\n    // Set per element — one iframe collects multiple disposers across loads.\n    __publicField(this, \"loadListenerDisposers\", /* @__PURE__ */ new WeakMap());\n    // Fallback for iframes removed before first load — mirror entry is gone\n    // by then, but we still need the element to dispose its load listener.\n    __publicField(this, \"iframeElementsById\", /* @__PURE__ */ new Map());\n    // Set per element — same multi-load reasoning as loadListenerDisposers.\n    __publicField(this, \"pageHideHandlers\", /* @__PURE__ */ new WeakMap());\n    this.mutationCb = options.mutationCb;\n    this.wrappedEmit = options.wrappedEmit;\n    this.stylesheetManager = options.stylesheetManager;\n    this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n    this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n      this.stylesheetManager.styleMirror.generateId.bind(\n        this.stylesheetManager.styleMirror\n      )\n    );\n    this.mirror = options.mirror;\n    this.messageHandler = this.handleMessage.bind(this);\n    if (this.recordCrossOriginIframes) {\n      window.addEventListener(\"message\", this.messageHandler);\n    }\n  }\n  addIframe(iframeEl) {\n    this.iframes.set(iframeEl, true);\n    if (iframeEl.contentWindow)\n      this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n  }\n  registerLoadListenerDisposer(iframeEl, disposer) {\n    let bucket = this.loadListenerDisposers.get(iframeEl);\n    if (!bucket) {\n      bucket = /* @__PURE__ */ new Set();\n      this.loadListenerDisposers.set(iframeEl, bucket);\n    }\n    bucket.add(disposer);\n    const id = this.mirror.getId(iframeEl);\n    if (id !== -1) this.iframeElementsById.set(id, iframeEl);\n  }\n  // Used by the record-loop to distinguish reparenting from removal.\n  getIframeElementById(iframeId) {\n    var _a2;\n    return ((_a2 = this.attachedIframes.get(iframeId)) == null ? void 0 : _a2.element) ?? this.iframeElementsById.get(iframeId) ?? null;\n  }\n  // Drops the id mapping for a moved iframe; element-keyed state survives.\n  forgetIframeId(iframeId) {\n    this.attachedIframes.delete(iframeId);\n    this.iframeElementsById.delete(iframeId);\n  }\n  disposeLoadListeners(iframeEl) {\n    const bucket = this.loadListenerDisposers.get(iframeEl);\n    if (!bucket) return;\n    bucket.forEach((d) => callSafely(d));\n    this.loadListenerDisposers.delete(iframeEl);\n  }\n  removePageHideListener(iframeEl) {\n    const bucket = this.pageHideHandlers.get(iframeEl);\n    if (!bucket) return;\n    bucket.forEach(({ win, handler }) => {\n      removeEventListenerSafely(win, \"pagehide\", handler);\n    });\n    this.pageHideHandlers.delete(iframeEl);\n  }\n  addLoadListener(cb) {\n    this.loadListener = cb;\n  }\n  addPageHideListener(cb) {\n    this.pageHideListener = cb;\n  }\n  removeLoadListener() {\n    this.loadListener = void 0;\n  }\n  trackIframeContent(iframeEl, content) {\n    const iframeId = this.mirror.getId(iframeEl);\n    this.attachedIframes.set(iframeId, { element: iframeEl, content });\n    return iframeId;\n  }\n  attachIframe(iframeEl, childSn) {\n    var _a2;\n    const iframeId = this.trackIframeContent(iframeEl, childSn);\n    if (iframeEl.contentDocument) {\n      let docs = this.attachedDocuments.get(iframeEl);\n      if (!docs) {\n        docs = /* @__PURE__ */ new Set();\n        this.attachedDocuments.set(iframeEl, docs);\n      }\n      docs.add(iframeEl.contentDocument);\n    }\n    this.mutationCb({\n      adds: [\n        {\n          parentId: iframeId,\n          nextId: null,\n          node: childSn\n        }\n      ],\n      removes: [],\n      texts: [],\n      attributes: [],\n      isAttachIframe: true\n    });\n    const win = iframeEl.contentWindow;\n    if (this.recordCrossOriginIframes && win && !this.nestedIframeListeners.has(win)) {\n      const nestedHandler = this.handleMessage.bind(this);\n      callSafely(() => {\n        win.addEventListener(\"message\", nestedHandler);\n        this.nestedIframeListeners.set(win, nestedHandler);\n        let wins = this.attachedWindows.get(iframeEl);\n        if (!wins) {\n          wins = /* @__PURE__ */ new Set();\n          this.attachedWindows.set(iframeEl, wins);\n        }\n        wins.add(win);\n      });\n    }\n    callSafely(() => {\n      const pageHideWindow = iframeEl.contentWindow;\n      if (!pageHideWindow) return;\n      let bucket = this.pageHideHandlers.get(iframeEl);\n      if (bucket) {\n        for (const entry of bucket) {\n          if (entry.win === pageHideWindow) return;\n        }\n      }\n      const handler = () => {\n        var _a3;\n        (_a3 = this.pageHideListener) == null ? void 0 : _a3.call(this, iframeEl);\n        if (iframeEl.contentDocument) {\n          this.mirror.removeNodeFromMap(iframeEl.contentDocument);\n        }\n        if (iframeEl.contentWindow) {\n          this.crossOriginIframeMap.delete(iframeEl.contentWindow);\n        }\n      };\n      pageHideWindow.addEventListener(\"pagehide\", handler);\n      if (!bucket) {\n        bucket = /* @__PURE__ */ new Set();\n        this.pageHideHandlers.set(iframeEl, bucket);\n      }\n      bucket.add({ win: pageHideWindow, handler });\n    });\n    (_a2 = this.loadListener) == null ? void 0 : _a2.call(this, iframeEl);\n    if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0)\n      this.stylesheetManager.adoptStyleSheets(\n        iframeEl.contentDocument.adoptedStyleSheets,\n        this.mirror.getId(iframeEl.contentDocument)\n      );\n  }\n  handleMessage(message) {\n    const crossOriginMessageEvent = message;\n    if (crossOriginMessageEvent.data.type !== \"rrweb\" || // To filter out the rrweb messages which are forwarded by some sites.\n    crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n      return;\n    const iframeSourceWindow = message.source;\n    if (!iframeSourceWindow) return;\n    const iframeEl = this.crossOriginIframeMap.get(message.source);\n    if (!iframeEl) return;\n    const transformedEvent = this.transformCrossOriginEvent(\n      iframeEl,\n      crossOriginMessageEvent.data.event\n    );\n    if (transformedEvent)\n      this.wrappedEmit(\n        transformedEvent,\n        crossOriginMessageEvent.data.isCheckout\n      );\n  }\n  transformCrossOriginEvent(iframeEl, e) {\n    var _a2;\n    switch (e.type) {\n      case EventType.FullSnapshot: {\n        this.crossOriginIframeMirror.reset(iframeEl);\n        this.crossOriginIframeStyleMirror.reset(iframeEl);\n        this.replaceIdOnNode(e.data.node, iframeEl);\n        const rootId = e.data.node.id;\n        this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n        this.patchRootIdOnNode(e.data.node, rootId);\n        this.trackIframeContent(iframeEl, e.data.node);\n        return {\n          timestamp: e.timestamp,\n          type: EventType.IncrementalSnapshot,\n          data: {\n            source: IncrementalSource.Mutation,\n            adds: [\n              {\n                parentId: this.mirror.getId(iframeEl),\n                nextId: null,\n                node: e.data.node\n              }\n            ],\n            removes: [],\n            texts: [],\n            attributes: [],\n            isAttachIframe: true\n          }\n        };\n      }\n      case EventType.Meta:\n      case EventType.Load:\n      case EventType.DomContentLoaded: {\n        return false;\n      }\n      case EventType.Plugin: {\n        return e;\n      }\n      case EventType.Custom: {\n        this.replaceIds(\n          e.data.payload,\n          iframeEl,\n          [\"id\", \"parentId\", \"previousId\", \"nextId\"]\n        );\n        return e;\n      }\n      case EventType.IncrementalSnapshot: {\n        switch (e.data.source) {\n          case IncrementalSource.Mutation: {\n            e.data.adds.forEach((n) => {\n              this.replaceIds(n, iframeEl, [\n                \"parentId\",\n                \"nextId\",\n                \"previousId\"\n              ]);\n              this.replaceIdOnNode(n.node, iframeEl);\n              const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n              rootId && this.patchRootIdOnNode(n.node, rootId);\n            });\n            e.data.removes.forEach((n) => {\n              this.replaceIds(n, iframeEl, [\"parentId\", \"id\"]);\n            });\n            e.data.attributes.forEach((n) => {\n              this.replaceIds(n, iframeEl, [\"id\"]);\n            });\n            e.data.texts.forEach((n) => {\n              this.replaceIds(n, iframeEl, [\"id\"]);\n            });\n            return e;\n          }\n          case IncrementalSource.Drag:\n          case IncrementalSource.TouchMove:\n          case IncrementalSource.MouseMove: {\n            e.data.positions.forEach((p) => {\n              this.replaceIds(p, iframeEl, [\"id\"]);\n            });\n            return e;\n          }\n          case IncrementalSource.ViewportResize: {\n            return false;\n          }\n          case IncrementalSource.MediaInteraction:\n          case IncrementalSource.MouseInteraction:\n          case IncrementalSource.Scroll:\n          case IncrementalSource.CanvasMutation:\n          case IncrementalSource.Input: {\n            this.replaceIds(e.data, iframeEl, [\"id\"]);\n            return e;\n          }\n          case IncrementalSource.StyleSheetRule:\n          case IncrementalSource.StyleDeclaration: {\n            this.replaceIds(e.data, iframeEl, [\"id\"]);\n            this.replaceStyleIds(e.data, iframeEl, [\"styleId\"]);\n            return e;\n          }\n          case IncrementalSource.Font: {\n            return e;\n          }\n          case IncrementalSource.Selection: {\n            e.data.ranges.forEach((range) => {\n              this.replaceIds(range, iframeEl, [\"start\", \"end\"]);\n            });\n            return e;\n          }\n          case IncrementalSource.AdoptedStyleSheet: {\n            this.replaceIds(e.data, iframeEl, [\"id\"]);\n            this.replaceStyleIds(e.data, iframeEl, [\"styleIds\"]);\n            (_a2 = e.data.styles) == null ? void 0 : _a2.forEach((style) => {\n              this.replaceStyleIds(style, iframeEl, [\"styleId\"]);\n            });\n            return e;\n          }\n        }\n      }\n    }\n    return false;\n  }\n  replace(iframeMirror, obj, iframeEl, keys) {\n    for (const key of keys) {\n      if (!Array.isArray(obj[key]) && typeof obj[key] !== \"number\") continue;\n      if (Array.isArray(obj[key])) {\n        obj[key] = iframeMirror.getIds(\n          iframeEl,\n          obj[key]\n        );\n      } else {\n        obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n      }\n    }\n    return obj;\n  }\n  replaceIds(obj, iframeEl, keys) {\n    return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n  }\n  replaceStyleIds(obj, iframeEl, keys) {\n    return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n  }\n  replaceIdOnNode(node, iframeEl) {\n    this.replaceIds(node, iframeEl, [\"id\", \"rootId\"]);\n    if (\"childNodes\" in node) {\n      node.childNodes.forEach((child) => {\n        this.replaceIdOnNode(child, iframeEl);\n      });\n    }\n  }\n  patchRootIdOnNode(node, rootId) {\n    if (node.type !== NodeType.Document && !node.rootId) node.rootId = rootId;\n    if (\"childNodes\" in node) {\n      node.childNodes.forEach((child) => {\n        this.patchRootIdOnNode(child, rootId);\n      });\n    }\n  }\n  removeIframeById(iframeId) {\n    const entry = this.attachedIframes.get(iframeId);\n    const iframe = (entry == null ? void 0 : entry.element) || this.iframeElementsById.get(iframeId) || this.mirror.getNode(iframeId);\n    this.iframeElementsById.delete(iframeId);\n    if (iframe) {\n      const win = iframe.contentWindow;\n      const capturedWins = this.attachedWindows.get(iframe);\n      if (capturedWins) {\n        capturedWins.forEach((capturedWin) => {\n          const handler = this.nestedIframeListeners.get(capturedWin);\n          if (handler) {\n            removeEventListenerSafely(capturedWin, \"message\", handler);\n            this.nestedIframeListeners.delete(capturedWin);\n          }\n          this.crossOriginIframeMap.delete(capturedWin);\n        });\n        this.attachedWindows.delete(iframe);\n      }\n      if (win && this.nestedIframeListeners.has(win)) {\n        const handler = this.nestedIframeListeners.get(win);\n        removeEventListenerSafely(win, \"message\", handler);\n        this.nestedIframeListeners.delete(win);\n      }\n      if (win) {\n        this.crossOriginIframeMap.delete(win);\n      }\n      this.iframes.delete(iframe);\n      this.disposeLoadListeners(iframe);\n      this.removePageHideListener(iframe);\n      const capturedDocs = this.attachedDocuments.get(iframe);\n      if (capturedDocs) {\n        capturedDocs.forEach((doc) => {\n          callSafely(() => this.mirror.removeNodeFromMap(doc));\n        });\n        callSafely(() => findAndRemoveIframeBuffer(iframe, capturedDocs));\n        this.attachedDocuments.delete(iframe);\n      }\n    }\n    if (entry) {\n      this.attachedIframes.delete(iframeId);\n    }\n  }\n  // Catches iframes removed inside a removed subtree (only the\n  // ancestor's id appears in m.removes).\n  cleanupDetachedIframes() {\n    if (this.attachedIframes.size === 0) return;\n    const orphaned = [];\n    this.attachedIframes.forEach((_entry, iframeId) => {\n      if (!this.mirror.has(iframeId)) {\n        orphaned.push(iframeId);\n      }\n    });\n    orphaned.forEach((iframeId) => this.removeIframeById(iframeId));\n  }\n  reattachIframes() {\n    this.attachedIframes.forEach(({ content }, iframeId) => {\n      if (!this.mirror.has(iframeId)) {\n        this.attachedIframes.delete(iframeId);\n        return;\n      }\n      this.mutationCb({\n        adds: [\n          {\n            parentId: iframeId,\n            nextId: null,\n            node: content\n          }\n        ],\n        removes: [],\n        texts: [],\n        attributes: [],\n        isAttachIframe: true\n      });\n    });\n  }\n  destroy() {\n    if (this.recordCrossOriginIframes) {\n      removeEventListenerSafely(window, \"message\", this.messageHandler);\n    }\n    this.nestedIframeListeners.forEach((handler, contentWindow) => {\n      removeEventListenerSafely(contentWindow, \"message\", handler);\n    });\n    this.nestedIframeListeners.clear();\n    const tracked = /* @__PURE__ */ new Set();\n    this.iframeElementsById.forEach((el) => tracked.add(el));\n    this.attachedIframes.forEach(({ element }) => tracked.add(element));\n    tracked.forEach((iframe) => {\n      this.disposeLoadListeners(iframe);\n      this.removePageHideListener(iframe);\n    });\n    this.crossOriginIframeMirror.reset();\n    this.crossOriginIframeStyleMirror.reset();\n    this.attachedIframes.clear();\n    this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();\n    this.iframes = /* @__PURE__ */ new WeakMap();\n    this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n    this.loadListenerDisposers = /* @__PURE__ */ new WeakMap();\n    this.pageHideHandlers = /* @__PURE__ */ new WeakMap();\n    this.attachedDocuments = /* @__PURE__ */ new WeakMap();\n    this.attachedWindows = /* @__PURE__ */ new WeakMap();\n    this.iframeElementsById = /* @__PURE__ */ new Map();\n  }\n}\nclass ShadowDomManager {\n  constructor(options) {\n    __publicField(this, \"shadowDoms\", /* @__PURE__ */ new WeakSet());\n    __publicField(this, \"mutationCb\");\n    __publicField(this, \"scrollCb\");\n    __publicField(this, \"bypassOptions\");\n    __publicField(this, \"mirror\");\n    // Handlers are tagged with the document that owns their shadow root so a\n    // single iframe can be torn down without disconnecting the rest of the page.\n    __publicField(this, \"restoreHandlers\", []);\n    this.mutationCb = options.mutationCb;\n    this.scrollCb = options.scrollCb;\n    this.bypassOptions = options.bypassOptions;\n    this.mirror = options.mirror;\n    this.init();\n  }\n  init() {\n    this.reset();\n    this.patchAttachShadow(Element, document);\n  }\n  addShadowRoot(shadowRoot2, doc) {\n    var _a2;\n    if (!isNativeShadowDom(shadowRoot2)) return;\n    if (this.shadowDoms.has(shadowRoot2)) return;\n    this.shadowDoms.add(shadowRoot2);\n    const ownerDoc = ((_a2 = index.host(shadowRoot2)) == null ? void 0 : _a2.ownerDocument) ?? doc;\n    const { observer, buffer } = initMutationObserver(\n      {\n        ...this.bypassOptions,\n        doc: ownerDoc,\n        mutationCb: this.mutationCb,\n        mirror: this.mirror,\n        shadowDomManager: this\n      },\n      shadowRoot2\n    );\n    this.restoreHandlers.push({\n      doc: ownerDoc,\n      handler: () => {\n        observer.disconnect();\n        buffer.destroy();\n        buffer.releaseCanvasManager();\n        const index2 = mutationBuffers.indexOf(buffer);\n        if (index2 !== -1) {\n          mutationBuffers.splice(index2, 1);\n        }\n      }\n    });\n    this.restoreHandlers.push({\n      doc: ownerDoc,\n      handler: initScrollObserver({\n        ...this.bypassOptions,\n        scrollCb: this.scrollCb,\n        // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n        // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n        doc: shadowRoot2,\n        mirror: this.mirror\n      })\n    });\n    setTimeout(() => {\n      if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0)\n        this.bypassOptions.stylesheetManager.adoptStyleSheets(\n          shadowRoot2.adoptedStyleSheets,\n          this.mirror.getId(index.host(shadowRoot2))\n        );\n      this.restoreHandlers.push({\n        doc: ownerDoc,\n        handler: initAdoptedStyleSheetObserver(\n          {\n            mirror: this.mirror,\n            stylesheetManager: this.bypassOptions.stylesheetManager\n          },\n          shadowRoot2\n        )\n      });\n    }, 0);\n  }\n  /**\n   * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n   */\n  observeAttachShadow(iframeElement) {\n    if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;\n    this.patchAttachShadow(\n      iframeElement.contentWindow.Element,\n      iframeElement.contentDocument\n    );\n  }\n  /**\n   * Patch 'attachShadow' to observe newly added shadow doms.\n   */\n  patchAttachShadow(element, doc) {\n    const manager = this;\n    this.restoreHandlers.push({\n      doc,\n      handler: patch(\n        element.prototype,\n        \"attachShadow\",\n        function(original) {\n          return function(option) {\n            const sRoot = original.call(this, option);\n            const shadowRootEl = index.shadowRoot(this);\n            if (shadowRootEl && inDom(this))\n              manager.addShadowRoot(shadowRootEl, doc);\n            return sRoot;\n          };\n        }\n      )\n    });\n  }\n  reset() {\n    this.restoreHandlers.forEach(({ handler }) => {\n      try {\n        handler();\n      } catch (e) {\n      }\n    });\n    this.restoreHandlers = [];\n    this.shadowDoms = /* @__PURE__ */ new WeakSet();\n  }\n  // Tear down only the shadow observers owned by `doc` (e.g. one iframe being removed), leaving the rest of the page's shadow observation intact.\n  resetForDoc(doc) {\n    const remaining = [];\n    for (const entry of this.restoreHandlers) {\n      if (entry.doc === doc) {\n        try {\n          entry.handler();\n        } catch (e) {\n        }\n      } else {\n        remaining.push(entry);\n      }\n    }\n    this.restoreHandlers = remaining;\n  }\n}\nvar chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n  lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function(arraybuffer) {\n  var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = \"\";\n  for (i = 0; i < len; i += 3) {\n    base64 += chars[bytes[i] >> 2];\n    base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n    base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n    base64 += chars[bytes[i + 2] & 63];\n  }\n  if (len % 3 === 2) {\n    base64 = base64.substring(0, base64.length - 1) + \"=\";\n  } else if (len % 3 === 1) {\n    base64 = base64.substring(0, base64.length - 2) + \"==\";\n  }\n  return base64;\n};\nconst canvasVarMap = /* @__PURE__ */ new Map();\nfunction variableListFor(ctx, ctor) {\n  let contextMap = canvasVarMap.get(ctx);\n  if (!contextMap) {\n    contextMap = /* @__PURE__ */ new Map();\n    canvasVarMap.set(ctx, contextMap);\n  }\n  if (!contextMap.has(ctor)) {\n    contextMap.set(ctor, []);\n  }\n  return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n  if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === \"object\"))\n    return;\n  const name = value.constructor.name;\n  const list = variableListFor(ctx, name);\n  let index2 = list.indexOf(value);\n  if (index2 === -1) {\n    index2 = list.length;\n    list.push(value);\n  }\n  return index2;\n};\nfunction serializeArg(value, win, ctx, dataURLOptions) {\n  if (value instanceof Array) {\n    return value.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n  } else if (value === null) {\n    return value;\n  } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {\n    const name = value.constructor.name;\n    return {\n      rr_type: name,\n      args: [Object.values(value)]\n    };\n  } else if (\n    // SharedArrayBuffer disabled on most browsers due to spectre.\n    // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n    // value instanceof SharedArrayBuffer ||\n    value instanceof ArrayBuffer\n  ) {\n    const name = value.constructor.name;\n    const base64 = encode(value);\n    return {\n      rr_type: name,\n      base64\n    };\n  } else if (value instanceof DataView) {\n    const name = value.constructor.name;\n    return {\n      rr_type: name,\n      args: [\n        serializeArg(value.buffer, win, ctx, dataURLOptions),\n        value.byteOffset,\n        value.byteLength\n      ]\n    };\n  } else if (value instanceof HTMLImageElement) {\n    const name = value.constructor.name;\n    const { src } = value;\n    return {\n      rr_type: name,\n      src\n    };\n  } else if (value instanceof HTMLCanvasElement) {\n    const name = \"HTMLImageElement\";\n    const src = value.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n    return {\n      rr_type: name,\n      src\n    };\n  } else if (value instanceof ImageData) {\n    const name = value.constructor.name;\n    return {\n      rr_type: name,\n      args: [\n        serializeArg(value.data, win, ctx, dataURLOptions),\n        value.width,\n        value.height\n      ]\n    };\n  } else if (isInstanceOfWebGLObject(value, win) || typeof value === \"object\") {\n    const name = value.constructor.name;\n    const index2 = saveWebGLVar(value, win, ctx);\n    return {\n      rr_type: name,\n      index: index2\n    };\n  }\n  return value;\n}\nconst serializeArgs = (args, win, ctx, dataURLOptions) => {\n  return args.map((arg) => serializeArg(arg, win, ctx, dataURLOptions));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n  const webGLConstructorNames = [\n    \"WebGLActiveInfo\",\n    \"WebGLBuffer\",\n    \"WebGLFramebuffer\",\n    \"WebGLProgram\",\n    \"WebGLRenderbuffer\",\n    \"WebGLShader\",\n    \"WebGLShaderPrecisionFormat\",\n    \"WebGLTexture\",\n    \"WebGLUniformLocation\",\n    \"WebGLVertexArrayObject\",\n    // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.\n    \"WebGLVertexArrayObjectOES\"\n  ];\n  const supportedWebGLConstructorNames = webGLConstructorNames.filter(\n    (name) => typeof win[name] === \"function\"\n  );\n  return Boolean(\n    supportedWebGLConstructorNames.find(\n      (name) => value instanceof win[name]\n    )\n  );\n};\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector, dataURLOptions) {\n  const handlers = [];\n  const props2D = Object.getOwnPropertyNames(\n    win.CanvasRenderingContext2D.prototype\n  );\n  for (const prop of props2D) {\n    try {\n      if (typeof win.CanvasRenderingContext2D.prototype[prop] !== \"function\") {\n        continue;\n      }\n      const restoreHandler = patch(\n        win.CanvasRenderingContext2D.prototype,\n        prop,\n        function(original) {\n          return function(...args) {\n            if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\n              setTimeout(() => {\n                const recordArgs = serializeArgs(\n                  args,\n                  win,\n                  this,\n                  dataURLOptions\n                );\n                cb(this.canvas, {\n                  type: CanvasContext[\"2D\"],\n                  property: prop,\n                  args: recordArgs\n                });\n              }, 0);\n            }\n            return original.apply(this, args);\n          };\n        }\n      );\n      handlers.push(restoreHandler);\n    } catch {\n      const hookHandler = hookSetter(\n        win.CanvasRenderingContext2D.prototype,\n        prop,\n        {\n          set(v) {\n            cb(this.canvas, {\n              type: CanvasContext[\"2D\"],\n              property: prop,\n              args: [v],\n              setter: true\n            });\n          }\n        }\n      );\n      handlers.push(hookHandler);\n    }\n  }\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\nconst WEBGL_CONTEXT_NAMES = [\"webgl\", \"webgl2\"];\nfunction getNormalizedContextName(contextType) {\n  return contextType === \"experimental-webgl\" ? \"webgl\" : contextType;\n}\nfunction getRequiredWebGPUTextureUsage(win) {\n  const textureUsage = win.GPUTextureUsage;\n  if (!textureUsage) {\n    return null;\n  }\n  return textureUsage.COPY_SRC | textureUsage.RENDER_ATTACHMENT;\n}\nfunction getCanvasFromWebGPUContext(context) {\n  const { canvas } = context;\n  if (!canvas || typeof canvas !== \"object\") {\n    return null;\n  }\n  return canvas;\n}\nfunction isCanvasNode(canvas) {\n  return \"nodeType\" in canvas;\n}\nfunction initCanvasWebGPUContextObserver(win, blockClass, blockSelector) {\n  const GPUCanvasContext = win.GPUCanvasContext;\n  if (!(GPUCanvasContext == null ? void 0 : GPUCanvasContext.prototype) || typeof GPUCanvasContext.prototype.configure !== \"function\") {\n    return;\n  }\n  return patch(\n    GPUCanvasContext.prototype,\n    \"configure\",\n    function(original) {\n      return function(configuration) {\n        const canvas = getCanvasFromWebGPUContext(this);\n        if (!canvas || isCanvasNode(canvas) && isBlocked(canvas, blockClass, blockSelector, true)) {\n          return original.call(this, configuration);\n        }\n        if (isCanvasNode(canvas) && !(\"__context\" in canvas)) {\n          canvas.__context = \"webgpu\";\n        }\n        const requiredUsage = getRequiredWebGPUTextureUsage(win);\n        if (requiredUsage === null || !configuration) {\n          return original.call(this, configuration);\n        }\n        return original.call(this, {\n          ...configuration,\n          // WebGPU does not implicitly keep RENDER_ATTACHMENT when usage is set,\n          // so include both flags needed for drawing and snapshot reads.\n          usage: typeof configuration.usage === \"number\" ? configuration.usage | requiredUsage : requiredUsage\n        });\n      };\n    }\n  );\n}\nfunction initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {\n  const handlers = [];\n  try {\n    if (setPreserveDrawingBufferToTrue) {\n      const restoreWebGPUConfigureHandler = initCanvasWebGPUContextObserver(\n        win,\n        blockClass,\n        blockSelector\n      );\n      if (restoreWebGPUConfigureHandler) {\n        handlers.push(restoreWebGPUConfigureHandler);\n      }\n    }\n    const restoreHandler = patch(\n      win.HTMLCanvasElement.prototype,\n      \"getContext\",\n      function(original) {\n        return function(contextType, ...args) {\n          const ctxName = getNormalizedContextName(contextType);\n          if (!isBlocked(this, blockClass, blockSelector, true)) {\n            if (!(\"__context\" in this)) this.__context = ctxName;\n            if (setPreserveDrawingBufferToTrue && WEBGL_CONTEXT_NAMES.includes(ctxName)) {\n              if (args[0] && typeof args[0] === \"object\") {\n                const contextAttributes = args[0];\n                if (!contextAttributes.preserveDrawingBuffer) {\n                  contextAttributes.preserveDrawingBuffer = true;\n                }\n              } else {\n                args.splice(0, 1, {\n                  preserveDrawingBuffer: true\n                });\n              }\n            }\n          }\n          return original.apply(this, [contextType, ...args]);\n        };\n      }\n    );\n    handlers.push(restoreHandler);\n  } catch {\n    console.error(\"failed to patch HTMLCanvasElement.prototype.getContext\");\n  }\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win, dataURLOptions) {\n  const handlers = [];\n  const props = Object.getOwnPropertyNames(prototype);\n  for (const prop of props) {\n    if (\n      //prop.startsWith('get') ||  // e.g. getProgramParameter, but too risky\n      [\n        \"isContextLost\",\n        \"canvas\",\n        \"drawingBufferWidth\",\n        \"drawingBufferHeight\"\n      ].includes(prop)\n    ) {\n      continue;\n    }\n    try {\n      if (typeof prototype[prop] !== \"function\") {\n        continue;\n      }\n      const restoreHandler = patch(\n        prototype,\n        prop,\n        function(original) {\n          return function(...args) {\n            const result = original.apply(this, args);\n            saveWebGLVar(result, win, this);\n            if (\"tagName\" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {\n              const recordArgs = serializeArgs(args, win, this, dataURLOptions);\n              const mutation = {\n                type,\n                property: prop,\n                args: recordArgs\n              };\n              cb(this.canvas, mutation);\n            }\n            return result;\n          };\n        }\n      );\n      handlers.push(restoreHandler);\n    } catch {\n      const hookHandler = hookSetter(prototype, prop, {\n        set(v) {\n          cb(this.canvas, {\n            type,\n            property: prop,\n            args: [v],\n            setter: true\n          });\n        }\n      });\n      handlers.push(hookHandler);\n    }\n  }\n  return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, dataURLOptions) {\n  const handlers = [];\n  if (typeof win.WebGLRenderingContext !== \"undefined\") {\n    handlers.push(\n      ...patchGLPrototype(\n        win.WebGLRenderingContext.prototype,\n        CanvasContext.WebGL,\n        cb,\n        blockClass,\n        blockSelector,\n        win,\n        dataURLOptions\n      )\n    );\n  }\n  if (typeof win.WebGL2RenderingContext !== \"undefined\") {\n    handlers.push(\n      ...patchGLPrototype(\n        win.WebGL2RenderingContext.prototype,\n        CanvasContext.WebGL2,\n        cb,\n        blockClass,\n        blockSelector,\n        win,\n        dataURLOptions\n      )\n    );\n  }\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\nconst jsContent = '(function() {\\n  \"use strict\";\\n  var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\\n  var lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\\n  for (var i = 0; i < chars.length; i++) {\\n    lookup[chars.charCodeAt(i)] = i;\\n  }\\n  var encode = function(arraybuffer) {\\n    var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = \"\";\\n    for (i2 = 0; i2 < len; i2 += 3) {\\n      base64 += chars[bytes[i2] >> 2];\\n      base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\\n      base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\\n      base64 += chars[bytes[i2 + 2] & 63];\\n    }\\n    if (len % 3 === 2) {\\n      base64 = base64.substring(0, base64.length - 1) + \"=\";\\n    } else if (len % 3 === 1) {\\n      base64 = base64.substring(0, base64.length - 2) + \"==\";\\n    }\\n    return base64;\\n  };\\n  const lastFingerprintMap = /* @__PURE__ */ new Map();\\n  const transparentFingerprintMap = /* @__PURE__ */ new Map();\\n  function hashPixels(data) {\\n    const view = new Uint32Array(\\n      data.buffer,\\n      data.byteOffset,\\n      data.byteLength >>> 2\\n    );\\n    let primaryHash = 2166136261;\\n    let secondaryHash = 2654435769;\\n    for (let i2 = 0; i2 < view.length; i2++) {\\n      primaryHash ^= view[i2];\\n      primaryHash = Math.imul(primaryHash, 16777619);\\n      secondaryHash ^= view[i2];\\n      secondaryHash = Math.imul(secondaryHash, 2246822507);\\n    }\\n    return `${(primaryHash >>> 0).toString(16)}:${(secondaryHash >>> 0).toString(16)}`;\\n  }\\n  function frameFingerprint(width, height, data) {\\n    return `${width}x${height}:${hashPixels(data)}`;\\n  }\\n  function transparentFingerprint(width, height) {\\n    const pixelCount = width * height;\\n    let hash = transparentFingerprintMap.get(pixelCount);\\n    if (hash === void 0) {\\n      hash = hashPixels(new Uint8ClampedArray(pixelCount * 4));\\n      transparentFingerprintMap.set(pixelCount, hash);\\n    }\\n    return `${width}x${height}:${hash}`;\\n  }\\n  const worker = self;\\n  let reusableCanvas = null;\\n  let reusableCtx = null;\\n  worker.onmessage = async function(e) {\\n    if (\"OffscreenCanvas\" in globalThis) {\\n      const {\\n        id,\\n        bitmap,\\n        width,\\n        height,\\n        displayWidth,\\n        displayHeight,\\n        dataURLOptions\\n      } = e.data;\\n      try {\\n        if (!reusableCanvas || reusableCanvas.width !== width || reusableCanvas.height !== height) {\\n          reusableCanvas = new OffscreenCanvas(width, height);\\n          reusableCtx = reusableCanvas.getContext(\"2d\", {\\n            willReadFrequently: true\\n          });\\n        }\\n        const ctx = reusableCtx;\\n        ctx.clearRect(0, 0, width, height);\\n        ctx.drawImage(bitmap, 0, 0);\\n        bitmap.close();\\n        const fingerprint = frameFingerprint(\\n          width,\\n          height,\\n          ctx.getImageData(0, 0, width, height).data\\n        );\\n        const lastFingerprint = lastFingerprintMap.get(id) ?? transparentFingerprint(width, height);\\n        if (fingerprint === lastFingerprint) {\\n          return worker.postMessage({ id });\\n        }\\n        const blob = await reusableCanvas.convertToBlob(dataURLOptions);\\n        const arrayBuffer = await blob.arrayBuffer();\\n        worker.postMessage({\\n          id,\\n          type: blob.type,\\n          base64: encode(arrayBuffer),\\n          // cpu intensive\\n          displayWidth,\\n          displayHeight\\n        });\\n        lastFingerprintMap.set(id, fingerprint);\\n      } catch {\\n        worker.postMessage({ id });\\n      }\\n    } else {\\n      e.data.bitmap.close();\\n      return worker.postMessage({ id: e.data.id });\\n    }\\n  };\\n})();\\n//# sourceMappingURL=image-bitmap-data-url-worker-CZCeNtwG.js.map\\n';\nconst blob = typeof self !== \"undefined\" && self.Blob && new Blob([jsContent], { type: \"text/javascript;charset=utf-8\" });\nfunction WorkerWrapper(options) {\n  let objURL;\n  try {\n    objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);\n    if (!objURL) throw \"\";\n    const worker = new Worker(objURL, {\n      name: options == null ? void 0 : options.name\n    });\n    worker.addEventListener(\"error\", () => {\n      (self.URL || self.webkitURL).revokeObjectURL(objURL);\n    });\n    return worker;\n  } catch (e) {\n    return new Worker(\n      \"data:text/javascript;charset=utf-8,\" + encodeURIComponent(jsContent),\n      {\n        name: options == null ? void 0 : options.name\n      }\n    );\n  } finally {\n    objURL && (self.URL || self.webkitURL).revokeObjectURL(objURL);\n  }\n}\nconst MIN_CANVAS_RESOLUTION_SCALE = 0.1;\nclass CanvasManager {\n  constructor(options) {\n    __publicField(this, \"pendingCanvasMutations\", /* @__PURE__ */ new Map());\n    __publicField(this, \"rafStamps\", { latestId: 0, invokeId: null });\n    __publicField(this, \"mirror\");\n    __publicField(this, \"mutationCb\");\n    __publicField(this, \"resetObservers\");\n    __publicField(this, \"frozen\", false);\n    __publicField(this, \"locked\", false);\n    __publicField(this, \"rafIdTimestamp\", null);\n    __publicField(this, \"rafIdFlush\", null);\n    __publicField(this, \"refCount\", 0);\n    __publicField(this, \"torndown\", false);\n    __publicField(this, \"processMutation\", (target, mutation) => {\n      const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;\n      if (newFrame || !this.rafStamps.invokeId)\n        this.rafStamps.invokeId = this.rafStamps.latestId;\n      if (!this.pendingCanvasMutations.has(target)) {\n        this.pendingCanvasMutations.set(target, []);\n      }\n      this.pendingCanvasMutations.get(target).push(mutation);\n    });\n    const {\n      sampling = \"all\",\n      win,\n      blockClass,\n      blockSelector,\n      recordCanvas,\n      dataURLOptions,\n      resolutionScale\n    } = options;\n    this.mutationCb = options.mutationCb;\n    this.mirror = options.mirror;\n    if (recordCanvas && sampling === \"all\")\n      this.initCanvasMutationObserver(\n        win,\n        blockClass,\n        blockSelector,\n        dataURLOptions\n      );\n    if (recordCanvas && typeof sampling === \"number\")\n      this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\n        dataURLOptions,\n        resolutionScale\n      });\n  }\n  // Shared by the main document and every iframe/shadow-root observer, so reference-count\n  // teardown: a single root cleaning up must not unpatch getContext / stop the FPS loop globally.\n  acquire() {\n    this.refCount += 1;\n  }\n  reset() {\n    if (this.refCount > 0) {\n      this.refCount -= 1;\n    }\n    if (this.refCount > 0) {\n      return;\n    }\n    this.teardown();\n  }\n  teardown() {\n    if (this.torndown) {\n      return;\n    }\n    this.torndown = true;\n    this.pendingCanvasMutations.clear();\n    this.resetObservers && this.resetObservers();\n    if (this.rafIdTimestamp !== null) {\n      cancelAnimationFrame(this.rafIdTimestamp);\n      this.rafIdTimestamp = null;\n    }\n    if (this.rafIdFlush !== null) {\n      cancelAnimationFrame(this.rafIdFlush);\n      this.rafIdFlush = null;\n    }\n  }\n  freeze() {\n    this.frozen = true;\n  }\n  unfreeze() {\n    this.frozen = false;\n  }\n  lock() {\n    this.locked = true;\n  }\n  unlock() {\n    this.locked = false;\n  }\n  initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {\n    if (!(\"OffscreenCanvas\" in win)) {\n      return;\n    }\n    const scale = typeof options.resolutionScale === \"number\" && Number.isFinite(options.resolutionScale) ? Math.min(\n      1,\n      Math.max(MIN_CANVAS_RESOLUTION_SCALE, options.resolutionScale)\n    ) : 1;\n    const canvasContextReset = initCanvasContextObserver(\n      win,\n      blockClass,\n      blockSelector,\n      true\n    );\n    const snapshotInProgressMap = /* @__PURE__ */ new Map();\n    let worker;\n    try {\n      worker = new WorkerWrapper();\n    } catch {\n      return;\n    }\n    let workerErrored = false;\n    worker.onerror = () => {\n      var _a2;\n      workerErrored = true;\n      cancelAnimationFrame(rafId);\n      (_a2 = worker.terminate) == null ? void 0 : _a2.call(worker);\n    };\n    worker.onmessage = (e) => {\n      const { id } = e.data;\n      snapshotInProgressMap.set(id, false);\n      if (!(\"base64\" in e.data)) return;\n      const { base64, type, displayWidth, displayHeight } = e.data;\n      const dw = displayWidth;\n      const dh = displayHeight;\n      this.mutationCb({\n        id,\n        type: CanvasContext[\"2D\"],\n        commands: [\n          {\n            property: \"clearRect\",\n            // wipe canvas\n            args: [0, 0, dw, dh]\n          },\n          {\n            property: \"drawImage\",\n            // draws (semi-transparent) image, stretched to display size\n            args: [\n              {\n                rr_type: \"ImageBitmap\",\n                args: [\n                  {\n                    rr_type: \"Blob\",\n                    data: [{ rr_type: \"ArrayBuffer\", base64 }],\n                    type\n                  }\n                ]\n              },\n              0,\n              0,\n              dw,\n              dh\n            ]\n          }\n        ],\n        displayWidth: dw,\n        displayHeight: dh\n      });\n    };\n    const timeBetweenSnapshots = 1e3 / fps;\n    let lastSnapshotTime = 0;\n    let rafId;\n    const getCanvas = () => {\n      const matchedCanvas = [];\n      const searchCanvas = (haystack) => {\n        try {\n          haystack.querySelectorAll(\"canvas\").forEach((canvas) => {\n            if (!isBlocked(canvas, blockClass, blockSelector, true)) {\n              matchedCanvas.push(canvas);\n            }\n          });\n          haystack.querySelectorAll(\"*\").forEach((elem) => {\n            if (elem.shadowRoot) {\n              searchCanvas(elem.shadowRoot);\n            }\n          });\n        } catch {\n        }\n      };\n      searchCanvas(win.document);\n      return matchedCanvas;\n    };\n    const takeCanvasSnapshots = (timestamp) => {\n      if (workerErrored) {\n        return;\n      }\n      if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {\n        rafId = requestAnimationFrame(takeCanvasSnapshots);\n        return;\n      }\n      lastSnapshotTime = timestamp;\n      getCanvas().forEach(async (canvas) => {\n        var _a2, _b;\n        const id = this.mirror.getId(canvas);\n        if (snapshotInProgressMap.get(id)) return;\n        if (canvas.width === 0 || canvas.height === 0) return;\n        snapshotInProgressMap.set(id, true);\n        try {\n          if ([\"webgl\", \"webgl2\"].includes(canvas.__context)) {\n            const context = canvas.getContext(\n              canvas.__context\n            );\n            if ((_a2 = context == null ? void 0 : context.isContextLost) == null ? void 0 : _a2.call(context)) {\n              snapshotInProgressMap.set(id, false);\n              return;\n            }\n            if (((_b = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _b.preserveDrawingBuffer) === false) {\n              context.clear(context.COLOR_BUFFER_BIT);\n            }\n          }\n          const displayWidth = canvas.clientWidth || canvas.width;\n          const displayHeight = canvas.clientHeight || canvas.height;\n          const captureWidth = Math.max(1, Math.round(displayWidth * scale));\n          const captureHeight = Math.max(1, Math.round(displayHeight * scale));\n          const bitmap = await createImageBitmap(\n            canvas,\n            // only ask for a quality resampling filter when we're actually downscaling;\n            // at full resolution this keeps capture identical to before.\n            scale < 1 ? {\n              resizeWidth: captureWidth,\n              resizeHeight: captureHeight,\n              resizeQuality: \"medium\"\n            } : { resizeWidth: captureWidth, resizeHeight: captureHeight }\n          );\n          worker.postMessage(\n            {\n              id,\n              bitmap,\n              width: captureWidth,\n              height: captureHeight,\n              displayWidth,\n              displayHeight,\n              dataURLOptions: options.dataURLOptions\n            },\n            [bitmap]\n          );\n        } catch {\n          snapshotInProgressMap.set(id, false);\n        }\n      });\n      rafId = requestAnimationFrame(takeCanvasSnapshots);\n    };\n    rafId = requestAnimationFrame(takeCanvasSnapshots);\n    this.resetObservers = () => {\n      canvasContextReset();\n      cancelAnimationFrame(rafId);\n    };\n  }\n  initCanvasMutationObserver(win, blockClass, blockSelector, dataURLOptions) {\n    this.startRAFTimestamping();\n    this.startPendingCanvasMutationFlusher();\n    const canvasContextReset = initCanvasContextObserver(\n      win,\n      blockClass,\n      blockSelector,\n      false\n    );\n    const canvas2DReset = initCanvas2DMutationObserver(\n      this.processMutation.bind(this),\n      win,\n      blockClass,\n      blockSelector,\n      dataURLOptions\n    );\n    const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n      this.processMutation.bind(this),\n      win,\n      blockClass,\n      blockSelector,\n      dataURLOptions\n    );\n    this.resetObservers = () => {\n      canvasContextReset();\n      canvas2DReset();\n      canvasWebGL1and2Reset();\n    };\n  }\n  startPendingCanvasMutationFlusher() {\n    this.rafIdFlush = requestAnimationFrame(\n      () => this.flushPendingCanvasMutations()\n    );\n  }\n  startRAFTimestamping() {\n    const setLatestRAFTimestamp = (timestamp) => {\n      this.rafStamps.latestId = timestamp;\n      this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n    };\n    this.rafIdTimestamp = requestAnimationFrame(setLatestRAFTimestamp);\n  }\n  flushPendingCanvasMutations() {\n    this.pendingCanvasMutations.forEach(\n      (_values, canvas) => {\n        const id = this.mirror.getId(canvas);\n        this.flushPendingCanvasMutationFor(canvas, id);\n      }\n    );\n    this.rafIdFlush = requestAnimationFrame(\n      () => this.flushPendingCanvasMutations()\n    );\n  }\n  flushPendingCanvasMutationFor(canvas, id) {\n    if (this.frozen || this.locked) {\n      return;\n    }\n    const valuesWithType = this.pendingCanvasMutations.get(canvas);\n    if (!valuesWithType || id === -1) return;\n    const values = valuesWithType.map((value) => {\n      const { type: type2, ...rest } = value;\n      return rest;\n    });\n    const { type } = valuesWithType[0];\n    this.mutationCb({ id, type, commands: values });\n    this.pendingCanvasMutations.delete(canvas);\n  }\n}\nclass StylesheetManager {\n  constructor(options) {\n    __publicField(this, \"trackedLinkElements\", /* @__PURE__ */ new WeakSet());\n    __publicField(this, \"mutationCb\");\n    __publicField(this, \"adoptedStyleSheetCb\");\n    __publicField(this, \"styleMirror\", new StyleSheetMirror());\n    this.mutationCb = options.mutationCb;\n    this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n  }\n  attachLinkElement(linkEl, childSn) {\n    if (\"_cssText\" in childSn.attributes)\n      this.mutationCb({\n        adds: [],\n        removes: [],\n        texts: [],\n        attributes: [\n          {\n            id: childSn.id,\n            attributes: childSn.attributes\n          }\n        ]\n      });\n    this.trackLinkElement(linkEl);\n  }\n  trackLinkElement(linkEl) {\n    if (this.trackedLinkElements.has(linkEl)) return;\n    this.trackedLinkElements.add(linkEl);\n    this.trackStylesheetInLinkElement(linkEl);\n  }\n  adoptStyleSheets(sheets, hostId) {\n    if (sheets.length === 0) return;\n    const adoptedStyleSheetData = {\n      id: hostId,\n      styleIds: []\n    };\n    const styles = [];\n    for (const sheet of sheets) {\n      let styleId;\n      if (!this.styleMirror.has(sheet)) {\n        styleId = this.styleMirror.add(sheet);\n        styles.push({\n          styleId,\n          rules: Array.from(sheet.rules || CSSRule, (r, index2) => ({\n            rule: stringifyRule(r, sheet.href),\n            index: index2\n          }))\n        });\n      } else styleId = this.styleMirror.getId(sheet);\n      adoptedStyleSheetData.styleIds.push(styleId);\n    }\n    if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n    this.adoptedStyleSheetCb(adoptedStyleSheetData);\n  }\n  reset() {\n    this.styleMirror.reset();\n    this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n    resetStylesheetLoadTracking();\n  }\n  // TODO: take snapshot on stylesheet reload by applying event listener\n  trackStylesheetInLinkElement(_linkEl) {\n  }\n}\nclass ProcessedNodeManager {\n  constructor() {\n    __publicField(this, \"nodeMap\", /* @__PURE__ */ new WeakMap());\n    __publicField(this, \"active\", false);\n  }\n  inOtherBuffer(node, thisBuffer) {\n    const buffers = this.nodeMap.get(node);\n    return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);\n  }\n  add(node, buffer) {\n    if (!this.active) {\n      this.active = true;\n      requestAnimationFrame(() => {\n        this.nodeMap = /* @__PURE__ */ new WeakMap();\n        this.active = false;\n      });\n    }\n    this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));\n  }\n  destroy() {\n  }\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nlet canvasManager;\nlet recording = false;\ntry {\n  if (Array.from([1], (x) => x * 2)[0] !== 2) {\n    const cleanFrame = document.createElement(\"iframe\");\n    document.body.appendChild(cleanFrame);\n    Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;\n    document.body.removeChild(cleanFrame);\n  }\n} catch (err) {\n  console.debug(\"Unable to override Array.from\", err);\n}\nconst mirror = createMirror();\nconst nonUserInitiatedSources = /* @__PURE__ */ new Set([\n  IncrementalSource.Mutation,\n  IncrementalSource.MediaInteraction,\n  // often automatic e.g. background video loop\n  IncrementalSource.StyleSheetRule,\n  IncrementalSource.CanvasMutation,\n  IncrementalSource.Font,\n  IncrementalSource.Log,\n  IncrementalSource.StyleDeclaration,\n  IncrementalSource.AdoptedStyleSheet\n]);\nfunction record(options = {}) {\n  const {\n    emit,\n    checkoutEveryNms,\n    checkoutEveryNth,\n    blockClass = \"rr-block\",\n    blockSelector = null,\n    ignoreClass = \"rr-ignore\",\n    ignoreSelector = null,\n    maskTextClass = \"rr-mask\",\n    maskTextSelector = null,\n    inlineStylesheet = true,\n    maskAllInputs,\n    maskInputOptions: _maskInputOptions,\n    slimDOMOptions: _slimDOMOptions,\n    maskInputFn,\n    maskTextFn,\n    hooks,\n    packFn,\n    sampling = {},\n    dataURLOptions: _dataURLOptions = {},\n    canvasResolutionScale,\n    mousemoveWait,\n    recordDOM = true,\n    recordCanvas = false,\n    recordCrossOriginIframes = false,\n    recordAfter = options.recordAfter === \"DOMContentLoaded\" ? options.recordAfter : \"load\",\n    userTriggeredOnInput = false,\n    collectFonts = false,\n    inlineImages = false,\n    plugins,\n    keepIframeSrcFn = () => false,\n    ignoreCSSAttributes = /* @__PURE__ */ new Set([]),\n    attributeFilter,\n    errorHandler: errorHandler2\n  } = options;\n  registerErrorHandler(errorHandler2);\n  const dataURLOptions = {\n    type: \"image/webp\",\n    quality: 0.4,\n    maxBase64ImageLength: 1048576,\n    ..._dataURLOptions\n  };\n  const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;\n  let passEmitsToParent = false;\n  if (!inEmittingFrame) {\n    try {\n      if (window.parent.document) {\n        passEmitsToParent = false;\n      }\n    } catch (e) {\n      passEmitsToParent = true;\n    }\n  }\n  if (inEmittingFrame && !emit) {\n    throw new Error(\"emit function is required\");\n  }\n  if (!inEmittingFrame && !passEmitsToParent) {\n    return () => {\n    };\n  }\n  if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {\n    sampling.mousemove = mousemoveWait;\n  }\n  mirror.reset();\n  const maskInputOptions = maskAllInputs === true ? {\n    color: true,\n    date: true,\n    \"datetime-local\": true,\n    email: true,\n    month: true,\n    number: true,\n    range: true,\n    search: true,\n    tel: true,\n    text: true,\n    time: true,\n    url: true,\n    week: true,\n    textarea: true,\n    select: true,\n    password: true\n  } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };\n  const slimDOMOptions = slimDOMDefaults(\n    _slimDOMOptions !== void 0 ? _slimDOMOptions : false\n  );\n  polyfill();\n  let lastFullSnapshotEvent;\n  let incrementalSnapshotCount = 0;\n  const iframeObserverCleanups = /* @__PURE__ */ new Map();\n  let runAndDetachIframeCleanup;\n  let cleanupDetachedIframeObservers;\n  const eventProcessor = (e) => {\n    for (const plugin of plugins || []) {\n      if (plugin.eventProcessor) {\n        e = plugin.eventProcessor(e);\n      }\n    }\n    if (packFn && // Disable packing events which will be emitted to parent frames.\n    !passEmitsToParent) {\n      e = packFn(e);\n    }\n    return e;\n  };\n  wrappedEmit = (r, isCheckout) => {\n    var _a2;\n    const e = r;\n    e.timestamp = nowTimestamp();\n    if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e.type !== EventType.FullSnapshot && !(e.type === EventType.IncrementalSnapshot && nonUserInitiatedSources.has(e.data.source))) {\n      mutationBuffers.forEach((buf) => buf.unfreeze());\n    }\n    if (inEmittingFrame) {\n      emit == null ? void 0 : emit(eventProcessor(e), isCheckout);\n    } else if (passEmitsToParent) {\n      const message = {\n        type: \"rrweb\",\n        event: eventProcessor(e),\n        origin: window.location.origin,\n        isCheckout\n      };\n      window.parent.postMessage(message, \"*\");\n    }\n    if (e.type === EventType.FullSnapshot) {\n      lastFullSnapshotEvent = e;\n      incrementalSnapshotCount = 0;\n    } else if (e.type === EventType.IncrementalSnapshot) {\n      if (e.data.source === IncrementalSource.Mutation && e.data.isAttachIframe) {\n        return;\n      }\n      incrementalSnapshotCount++;\n      const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n      const exceedTime = checkoutEveryNms && e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n      if (exceedCount || exceedTime) {\n        takeFullSnapshot(true);\n      }\n    }\n  };\n  const wrappedMutationEmit = (m) => {\n    if (m.removes && m.removes.length > 0) {\n      const addedIds = m.adds.length > 0 ? new Set(m.adds.map((add) => add.node.id)) : null;\n      const addedIframeElements = /* @__PURE__ */ new Set();\n      if (m.adds.length > 0) {\n        for (const add of m.adds) {\n          const node = mirror.getNode(add.node.id);\n          if (node && node.nodeName === \"IFRAME\") {\n            addedIframeElements.add(node);\n          }\n        }\n      }\n      m.removes.forEach(({ id }) => {\n        if (addedIds && addedIds.has(id)) return;\n        const removedIframe = iframeManager.getIframeElementById(id);\n        if (removedIframe && addedIframeElements.has(removedIframe)) {\n          iframeManager.forgetIframeId(id);\n          return;\n        }\n        runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(id);\n        iframeManager.removeIframeById(id);\n      });\n      cleanupDetachedIframeObservers == null ? void 0 : cleanupDetachedIframeObservers();\n      iframeManager.cleanupDetachedIframes();\n    }\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.Mutation,\n        ...m\n      }\n    });\n  };\n  const wrappedScrollEmit = (p) => wrappedEmit({\n    type: EventType.IncrementalSnapshot,\n    data: {\n      source: IncrementalSource.Scroll,\n      ...p\n    }\n  });\n  const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n    type: EventType.IncrementalSnapshot,\n    data: {\n      source: IncrementalSource.CanvasMutation,\n      ...p\n    }\n  });\n  const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\n    type: EventType.IncrementalSnapshot,\n    data: {\n      source: IncrementalSource.AdoptedStyleSheet,\n      ...a\n    }\n  });\n  const stylesheetManager = new StylesheetManager({\n    mutationCb: wrappedMutationEmit,\n    adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit\n  });\n  const iframeManager = new IframeManager({\n    mirror,\n    mutationCb: wrappedMutationEmit,\n    stylesheetManager,\n    recordCrossOriginIframes,\n    wrappedEmit\n  });\n  for (const plugin of plugins || []) {\n    if (plugin.getMirror)\n      plugin.getMirror({\n        nodeMirror: mirror,\n        crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n        crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror\n      });\n  }\n  const processedNodeManager = new ProcessedNodeManager();\n  canvasManager = new CanvasManager({\n    recordCanvas,\n    mutationCb: wrappedCanvasMutationEmit,\n    win: window,\n    blockClass,\n    blockSelector,\n    mirror,\n    sampling: sampling.canvas,\n    dataURLOptions,\n    resolutionScale: canvasResolutionScale\n  });\n  const shadowDomManager = new ShadowDomManager({\n    mutationCb: wrappedMutationEmit,\n    scrollCb: wrappedScrollEmit,\n    bypassOptions: {\n      blockClass,\n      blockSelector,\n      maskTextClass,\n      maskTextSelector,\n      inlineStylesheet,\n      maskInputOptions,\n      dataURLOptions,\n      maskTextFn,\n      maskInputFn,\n      recordCanvas,\n      inlineImages,\n      sampling,\n      slimDOMOptions,\n      iframeManager,\n      stylesheetManager,\n      canvasManager,\n      keepIframeSrcFn,\n      processedNodeManager,\n      attributeFilter\n    },\n    mirror\n  });\n  takeFullSnapshot = (isCheckout = false) => {\n    if (!recordDOM) {\n      return;\n    }\n    wrappedEmit(\n      {\n        type: EventType.Meta,\n        data: {\n          href: window.location.href,\n          width: getWindowWidth(),\n          height: getWindowHeight()\n        }\n      },\n      isCheckout\n    );\n    stylesheetManager.reset();\n    shadowDomManager.init();\n    mutationBuffers.forEach((buf) => buf.lock());\n    const node = snapshot(document, {\n      mirror,\n      blockClass,\n      blockSelector,\n      maskTextClass,\n      maskTextSelector,\n      inlineStylesheet,\n      maskAllInputs: maskInputOptions,\n      maskTextFn,\n      maskInputFn,\n      slimDOM: slimDOMOptions,\n      dataURLOptions,\n      recordCanvas,\n      inlineImages,\n      onSerialize: (n) => {\n        if (isSerializedIframe(n, mirror)) {\n          iframeManager.addIframe(n);\n        }\n        if (isSerializedStylesheet(n, mirror)) {\n          stylesheetManager.trackLinkElement(n);\n        }\n        if (hasShadowRoot(n)) {\n          shadowDomManager.addShadowRoot(index.shadowRoot(n), document);\n        }\n      },\n      onIframeLoad: (iframe, childSn) => {\n        iframeManager.attachIframe(iframe, childSn);\n        shadowDomManager.observeAttachShadow(iframe);\n      },\n      onIframeListenerRegistered: (iframe, disposer) => {\n        iframeManager.registerLoadListenerDisposer(iframe, disposer);\n      },\n      onStylesheetLoad: (linkEl, childSn) => {\n        stylesheetManager.attachLinkElement(linkEl, childSn);\n      },\n      keepIframeSrcFn\n    });\n    if (!node) {\n      return console.warn(\"Failed to snapshot the document\");\n    }\n    wrappedEmit(\n      {\n        type: EventType.FullSnapshot,\n        data: {\n          node,\n          initialOffset: getWindowScroll(window)\n        }\n      },\n      isCheckout\n    );\n    mutationBuffers.forEach((buf) => buf.unlock());\n    if (recordCrossOriginIframes) {\n      iframeManager.reattachIframes();\n    }\n    if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n      stylesheetManager.adoptStyleSheets(\n        document.adoptedStyleSheets,\n        mirror.getId(document)\n      );\n  };\n  try {\n    const handlers = [];\n    runAndDetachIframeCleanup = (iframeId) => {\n      const cleanups = iframeObserverCleanups.get(iframeId);\n      if (!cleanups) return;\n      cleanups.forEach((cleanup) => {\n        callSafely(cleanup);\n        const idx = handlers.indexOf(cleanup);\n        if (idx !== -1) handlers.splice(idx, 1);\n      });\n      iframeObserverCleanups.delete(iframeId);\n    };\n    cleanupDetachedIframeObservers = () => {\n      for (const [iframeId] of iframeObserverCleanups) {\n        const iframe = mirror.getNode(iframeId);\n        if (!iframe) {\n          runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n          continue;\n        }\n        try {\n          if (!iframe.contentDocument || !iframe.contentDocument.defaultView) {\n            runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n          }\n        } catch {\n          runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n        }\n      }\n    };\n    const observe = (doc) => {\n      var _a2;\n      return callbackWrapper(initObservers)(\n        {\n          mutationCb: wrappedMutationEmit,\n          mousemoveCb: (positions, source) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source,\n              positions\n            }\n          }),\n          mouseInteractionCb: (d) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.MouseInteraction,\n              ...d\n            }\n          }),\n          scrollCb: wrappedScrollEmit,\n          viewportResizeCb: (d) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.ViewportResize,\n              ...d\n            }\n          }),\n          inputCb: (v) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.Input,\n              ...v\n            }\n          }),\n          mediaInteractionCb: (p) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.MediaInteraction,\n              ...p\n            }\n          }),\n          styleSheetRuleCb: (r) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.StyleSheetRule,\n              ...r\n            }\n          }),\n          styleDeclarationCb: (r) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.StyleDeclaration,\n              ...r\n            }\n          }),\n          canvasMutationCb: wrappedCanvasMutationEmit,\n          fontCb: (p) => wrappedEmit({\n            type: EventType.IncrementalSnapshot,\n            data: {\n              source: IncrementalSource.Font,\n              ...p\n            }\n          }),\n          selectionCb: (p) => {\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.Selection,\n                ...p\n              }\n            });\n          },\n          customElementCb: (c) => {\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.CustomElement,\n                ...c\n              }\n            });\n          },\n          blockClass,\n          ignoreClass,\n          ignoreSelector,\n          maskTextClass,\n          maskTextSelector,\n          maskInputOptions,\n          inlineStylesheet,\n          sampling,\n          recordDOM,\n          recordCanvas,\n          inlineImages,\n          userTriggeredOnInput,\n          collectFonts,\n          doc,\n          maskInputFn,\n          maskTextFn,\n          keepIframeSrcFn,\n          blockSelector,\n          slimDOMOptions,\n          dataURLOptions,\n          mirror,\n          iframeManager,\n          stylesheetManager,\n          shadowDomManager,\n          processedNodeManager,\n          canvasManager,\n          ignoreCSSAttributes,\n          attributeFilter,\n          plugins: ((_a2 = plugins == null ? void 0 : plugins.filter((p) => p.observer)) == null ? void 0 : _a2.map((p) => ({\n            observer: p.observer,\n            options: p.options,\n            callback: (payload) => wrappedEmit({\n              type: EventType.Plugin,\n              data: {\n                plugin: p.name,\n                payload\n              }\n            })\n          }))) || []\n        },\n        hooks\n      );\n    };\n    const loadListener = (iframeEl) => {\n      try {\n        const iframeId = mirror.getId(iframeEl);\n        const cleanup = observe(iframeEl.contentDocument);\n        handlers.push(cleanup);\n        if (iframeId !== -1) {\n          let bucket = iframeObserverCleanups.get(iframeId);\n          if (!bucket) {\n            bucket = /* @__PURE__ */ new Set();\n            iframeObserverCleanups.set(iframeId, bucket);\n          }\n          bucket.add(cleanup);\n        }\n      } catch (error) {\n        console.warn(error);\n      }\n    };\n    iframeManager.addLoadListener(loadListener);\n    iframeManager.addPageHideListener((iframeEl) => {\n      const iframeId = mirror.getId(iframeEl);\n      runAndDetachIframeCleanup == null ? void 0 : runAndDetachIframeCleanup(iframeId);\n      findAndRemoveIframeBuffer(iframeEl);\n    });\n    let lastFullscreenId = -1;\n    const emitFullscreen = (payload) => wrappedEmit({\n      type: EventType.Custom,\n      data: { tag: FullscreenCustomEventTag, payload }\n    });\n    const emitFullscreenChange = () => {\n      const doc = document;\n      const fullscreenEl = doc.fullscreenElement ?? doc.webkitFullscreenElement ?? doc.mozFullScreenElement ?? doc.msFullscreenElement ?? null;\n      const id = fullscreenEl ? mirror.getId(fullscreenEl) : -1;\n      if (id === lastFullscreenId) return;\n      if (lastFullscreenId !== -1) {\n        emitFullscreen({ id: lastFullscreenId, enter: false });\n      }\n      lastFullscreenId = id;\n      if (id !== -1) {\n        emitFullscreen({ id, enter: true });\n      }\n    };\n    const init = () => {\n      takeFullSnapshot();\n      handlers.push(observe(document));\n      handlers.push(on(\"fullscreenchange\", emitFullscreenChange));\n      handlers.push(on(\"webkitfullscreenchange\", emitFullscreenChange));\n      handlers.push(on(\"mozfullscreenchange\", emitFullscreenChange));\n      handlers.push(on(\"MSFullscreenChange\", emitFullscreenChange));\n      recording = true;\n    };\n    if ([\"interactive\", \"complete\"].includes(document.readyState)) {\n      init();\n    } else {\n      handlers.push(\n        on(\"DOMContentLoaded\", () => {\n          wrappedEmit({\n            type: EventType.DomContentLoaded,\n            data: {}\n          });\n          if (recordAfter === \"DOMContentLoaded\") init();\n        })\n      );\n      handlers.push(\n        on(\n          \"load\",\n          () => {\n            wrappedEmit({\n              type: EventType.Load,\n              data: {}\n            });\n            if (recordAfter === \"load\") init();\n          },\n          window\n        )\n      );\n    }\n    return () => {\n      handlers.forEach((h) => callSafely(h));\n      processedNodeManager.destroy();\n      iframeManager.removeLoadListener();\n      iframeManager.destroy();\n      iframeObserverCleanups.clear();\n      shadowDomManager.reset();\n      mirror.reset();\n      recording = false;\n      unregisterErrorHandler();\n    };\n  } catch (error) {\n    console.warn(error);\n  }\n}\nrecord.addCustomEvent = (tag, payload) => {\n  if (!recording) {\n    throw new Error(\"please add custom event after start recording\");\n  }\n  wrappedEmit({\n    type: EventType.Custom,\n    data: {\n      tag,\n      payload\n    }\n  });\n};\nrecord.freezePage = () => {\n  mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n  if (!recording) {\n    throw new Error(\"please take full snapshot after start recording\");\n  }\n  takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\nexport {\n  record,\n  resetMaxDepthState,\n  wasMaxDepthReached\n};\n//# sourceMappingURL=rrweb-record.js.map\n","var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nfunction isFunction(value) {\n  return typeof value === \"function\";\n}\nfunction patch(source, name, replacement) {\n  try {\n    if (!(name in source)) {\n      return () => {\n      };\n    }\n    const original = source[name];\n    const layer = {\n      next: original\n    };\n    const callNext = function(...args) {\n      return layer.next.apply(this, args);\n    };\n    const wrapped = replacement(callNext);\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        __rrweb_layer__: {\n          enumerable: false,\n          value: layer\n        }\n      });\n    }\n    source[name] = wrapped;\n    return () => {\n      if (source[name] === wrapped) {\n        source[name] = layer.next;\n        return;\n      }\n      let current = source[name];\n      while (isFunction(current) && current.__rrweb_layer__) {\n        const currentLayer = current.__rrweb_layer__;\n        if (currentLayer.next === wrapped) {\n          currentLayer.next = layer.next;\n          return;\n        }\n        current = currentLayer.next;\n      }\n    };\n  } catch {\n    return () => {\n    };\n  }\n}\nclass StackFrame {\n  constructor(obj) {\n    __publicField(this, \"fileName\");\n    __publicField(this, \"functionName\");\n    __publicField(this, \"lineNumber\");\n    __publicField(this, \"columnNumber\");\n    this.fileName = obj.fileName || \"\";\n    this.functionName = obj.functionName || \"\";\n    this.lineNumber = obj.lineNumber;\n    this.columnNumber = obj.columnNumber;\n  }\n  toString() {\n    const lineNumber = this.lineNumber || \"\";\n    const columnNumber = this.columnNumber || \"\";\n    if (this.functionName)\n      return `${this.functionName} (${this.fileName}:${lineNumber}:${columnNumber})`;\n    return `${this.fileName}:${lineNumber}:${columnNumber}`;\n  }\n}\nconst FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/;\nconst CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+:\\d+|\\(native\\))/m;\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code])?$/;\nconst ErrorStackParser = {\n  /**\n   * Given an Error object, extract the most information from it.\n   */\n  parse: function(error) {\n    if (!error) {\n      return [];\n    }\n    if (\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      typeof error.stacktrace !== \"undefined\" || // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      typeof error[\"opera#sourceloc\"] !== \"undefined\"\n    ) {\n      return this.parseOpera(\n        error\n      );\n    } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {\n      return this.parseV8OrIE(error);\n    } else if (error.stack) {\n      return this.parseFFOrSafari(error);\n    } else {\n      return [];\n    }\n  },\n  // Separate line and column numbers from a string of the form: (URI:Line:Column)\n  extractLocation: function(urlLike) {\n    if (urlLike.indexOf(\":\") === -1) {\n      return [urlLike];\n    }\n    const regExp = /(.+?)(?::(\\d+))?(?::(\\d+))?$/;\n    const parts = regExp.exec(urlLike.replace(/[()]/g, \"\"));\n    if (!parts) throw new Error(`Cannot parse given url: ${urlLike}`);\n    return [parts[1], parts[2] || void 0, parts[3] || void 0];\n  },\n  parseV8OrIE: function(error) {\n    const filtered = error.stack.split(\"\\n\").filter(function(line) {\n      return !!line.match(CHROME_IE_STACK_REGEXP);\n    }, this);\n    return filtered.map(function(line) {\n      if (line.indexOf(\"(eval \") > -1) {\n        line = line.replace(/eval code/g, \"eval\").replace(/(\\(eval at [^()]*)|(\\),.*$)/g, \"\");\n      }\n      let sanitizedLine = line.replace(/^\\s+/, \"\").replace(/\\(eval code/g, \"(\");\n      const location = sanitizedLine.match(/ (\\((.+):(\\d+):(\\d+)\\)$)/);\n      sanitizedLine = location ? sanitizedLine.replace(location[0], \"\") : sanitizedLine;\n      const tokens = sanitizedLine.split(/\\s+/).slice(1);\n      const locationParts = this.extractLocation(\n        location ? location[1] : tokens.pop()\n      );\n      const functionName = tokens.join(\" \") || void 0;\n      const fileName = [\"eval\", \"<anonymous>\"].indexOf(locationParts[0]) > -1 ? void 0 : locationParts[0];\n      return new StackFrame({\n        functionName,\n        fileName,\n        lineNumber: locationParts[1],\n        columnNumber: locationParts[2]\n      });\n    }, this);\n  },\n  parseFFOrSafari: function(error) {\n    const filtered = error.stack.split(\"\\n\").filter(function(line) {\n      return !line.match(SAFARI_NATIVE_CODE_REGEXP);\n    }, this);\n    return filtered.map(function(line) {\n      if (line.indexOf(\" > eval\") > -1) {\n        line = line.replace(\n          / line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g,\n          \":$1\"\n        );\n      }\n      if (line.indexOf(\"@\") === -1 && line.indexOf(\":\") === -1) {\n        return new StackFrame({\n          functionName: line\n        });\n      } else {\n        const functionNameRegex = /((.*\".+\"[^@]*)?[^@]*)(?:@)/;\n        const matches = line.match(functionNameRegex);\n        const functionName = matches && matches[1] ? matches[1] : void 0;\n        const locationParts = this.extractLocation(\n          line.replace(functionNameRegex, \"\")\n        );\n        return new StackFrame({\n          functionName,\n          fileName: locationParts[0],\n          lineNumber: locationParts[1],\n          columnNumber: locationParts[2]\n        });\n      }\n    }, this);\n  },\n  parseOpera: function(e) {\n    if (!e.stacktrace || e.message.indexOf(\"\\n\") > -1 && e.message.split(\"\\n\").length > e.stacktrace.split(\"\\n\").length) {\n      return this.parseOpera9(e);\n    } else if (!e.stack) {\n      return this.parseOpera10(e);\n    } else {\n      return this.parseOpera11(e);\n    }\n  },\n  parseOpera9: function(e) {\n    const lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n    const lines = e.message.split(\"\\n\");\n    const result = [];\n    for (let i = 2, len = lines.length; i < len; i += 2) {\n      const match = lineRE.exec(lines[i]);\n      if (match) {\n        result.push(\n          new StackFrame({\n            fileName: match[2],\n            lineNumber: parseFloat(match[1])\n          })\n        );\n      }\n    }\n    return result;\n  },\n  parseOpera10: function(e) {\n    const lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n    const lines = e.stacktrace.split(\"\\n\");\n    const result = [];\n    for (let i = 0, len = lines.length; i < len; i += 2) {\n      const match = lineRE.exec(lines[i]);\n      if (match) {\n        result.push(\n          new StackFrame({\n            functionName: match[3] || void 0,\n            fileName: match[2],\n            lineNumber: parseFloat(match[1])\n          })\n        );\n      }\n    }\n    return result;\n  },\n  // Opera 10.65+ Error.stack very similar to FF/Safari\n  parseOpera11: function(error) {\n    const filtered = error.stack.split(\"\\n\").filter(function(line) {\n      return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);\n    }, this);\n    return filtered.map(function(line) {\n      const tokens = line.split(\"@\");\n      const locationParts = this.extractLocation(tokens.pop());\n      const functionCall = tokens.shift() || \"\";\n      const functionName = functionCall.replace(/<anonymous function(: (\\w+))?>/, \"$2\").replace(/\\([^)]*\\)/g, \"\") || void 0;\n      return new StackFrame({\n        functionName,\n        fileName: locationParts[0],\n        lineNumber: locationParts[1],\n        columnNumber: locationParts[2]\n      });\n    }, this);\n  }\n};\nfunction pathToSelector(node) {\n  if (!node || !node.outerHTML) {\n    return \"\";\n  }\n  let path = \"\";\n  while (node.parentElement) {\n    let name = node.localName;\n    if (!name) {\n      break;\n    }\n    name = name.toLowerCase();\n    const parent = node.parentElement;\n    const domSiblings = [];\n    if (parent.children && parent.children.length > 0) {\n      for (let i = 0; i < parent.children.length; i++) {\n        const sibling = parent.children[i];\n        if (sibling.localName && sibling.localName.toLowerCase) {\n          if (sibling.localName.toLowerCase() === name) {\n            domSiblings.push(sibling);\n          }\n        }\n      }\n    }\n    if (domSiblings.length > 1) {\n      name += `:eq(${domSiblings.indexOf(node)})`;\n    }\n    path = name + (path ? \">\" + path : \"\");\n    node = parent;\n  }\n  return path;\n}\nfunction isArray(obj) {\n  return Array.isArray(obj);\n}\nfunction isObject(obj) {\n  return typeof obj === \"object\" && obj !== null && !isArray(obj);\n}\nfunction isObjTooDeep(obj, limit) {\n  if (limit === 0) {\n    return true;\n  }\n  const keys = Object.keys(obj);\n  for (const key of keys) {\n    if (isObject(obj[key]) && isObjTooDeep(obj[key], limit - 1)) {\n      return true;\n    }\n  }\n  return false;\n}\nfunction stringify(obj, stringifyOptions) {\n  const options = {\n    numOfKeysLimit: 50,\n    depthOfLimit: 4\n  };\n  Object.assign(options, stringifyOptions);\n  const stack = [];\n  const keys = [];\n  return JSON.stringify(\n    obj,\n    function(key, value) {\n      if (stack.length > 0) {\n        const thisPos = stack.indexOf(this);\n        ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n        ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n        if (~stack.indexOf(value)) {\n          if (stack[0] === value) {\n            value = \"[Circular ~]\";\n          } else {\n            value = \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\n          }\n        }\n      } else {\n        stack.push(value);\n      }\n      if (value === null) return value;\n      if (value === void 0) return \"undefined\";\n      if (shouldIgnore(value)) {\n        return toString(value);\n      }\n      if (typeof value === \"bigint\") {\n        return value.toString() + \"n\";\n      }\n      if (value instanceof Event) {\n        const eventResult = {};\n        for (const eventKey in value) {\n          const eventValue = value[eventKey];\n          if (isArray(eventValue)) {\n            eventResult[eventKey] = pathToSelector(\n              eventValue.length ? eventValue[0] : null\n            );\n          } else {\n            eventResult[eventKey] = eventValue;\n          }\n        }\n        return eventResult;\n      } else if (value instanceof Node) {\n        if (value instanceof HTMLElement) {\n          return value ? value.outerHTML : \"\";\n        }\n        return value.nodeName;\n      } else if (value instanceof Error) {\n        return value.stack ? value.stack + \"\\nEnd of stack for Error object\" : value.name + \": \" + value.message;\n      }\n      return value;\n    }\n  );\n  function shouldIgnore(_obj) {\n    if (isObject(_obj) && Object.keys(_obj).length > options.numOfKeysLimit) {\n      return true;\n    }\n    if (typeof _obj === \"function\") {\n      return true;\n    }\n    if (isObject(_obj) && isObjTooDeep(_obj, options.depthOfLimit)) {\n      return true;\n    }\n    return false;\n  }\n  function toString(_obj) {\n    let str = _obj.toString();\n    if (options.stringLengthLimit && str.length > options.stringLengthLimit) {\n      str = `${str.slice(0, options.stringLengthLimit)}...`;\n    }\n    return str;\n  }\n}\nconst defaultLogOptions = {\n  level: [\n    \"assert\",\n    \"clear\",\n    \"count\",\n    \"countReset\",\n    \"debug\",\n    \"dir\",\n    \"dirxml\",\n    \"error\",\n    \"group\",\n    \"groupCollapsed\",\n    \"groupEnd\",\n    \"info\",\n    \"log\",\n    \"table\",\n    \"time\",\n    \"timeEnd\",\n    \"timeLog\",\n    \"trace\",\n    \"warn\"\n  ],\n  lengthThreshold: 1e3,\n  logger: \"console\"\n};\nfunction initLogObserver(cb, win, options) {\n  const logOptions = options ? Object.assign({}, defaultLogOptions, options) : defaultLogOptions;\n  const loggerType = logOptions.logger;\n  if (!loggerType) {\n    return () => {\n    };\n  }\n  let logger;\n  if (typeof loggerType === \"string\") {\n    logger = win[loggerType];\n  } else {\n    logger = loggerType;\n  }\n  let logCount = 0;\n  let inStack = false;\n  const cancelHandlers = [];\n  if (logOptions.level.includes(\"error\")) {\n    const errorHandler = (event) => {\n      const message = event.message, error = event.error;\n      const trace = ErrorStackParser.parse(error).map(\n        (stackFrame) => stackFrame.toString()\n      );\n      const payload = [stringify(message, logOptions.stringifyOptions)];\n      cb({\n        level: \"error\",\n        trace,\n        payload\n      });\n    };\n    win.addEventListener(\"error\", errorHandler);\n    cancelHandlers.push(() => {\n      win.removeEventListener(\"error\", errorHandler);\n    });\n    const unhandledrejectionHandler = (event) => {\n      let error;\n      let payload;\n      if (event.reason instanceof Error) {\n        error = event.reason;\n        payload = [\n          stringify(\n            `Uncaught (in promise) ${error.name}: ${error.message}`,\n            logOptions.stringifyOptions\n          )\n        ];\n      } else {\n        error = new Error();\n        payload = [\n          stringify(\"Uncaught (in promise)\", logOptions.stringifyOptions),\n          stringify(event.reason, logOptions.stringifyOptions)\n        ];\n      }\n      const trace = ErrorStackParser.parse(error).map(\n        (stackFrame) => stackFrame.toString()\n      );\n      cb({\n        level: \"error\",\n        trace,\n        payload\n      });\n    };\n    win.addEventListener(\"unhandledrejection\", unhandledrejectionHandler);\n    cancelHandlers.push(() => {\n      win.removeEventListener(\"unhandledrejection\", unhandledrejectionHandler);\n    });\n  }\n  for (const levelType of logOptions.level) {\n    cancelHandlers.push(replace(logger, levelType));\n  }\n  return () => {\n    cancelHandlers.forEach((h) => h());\n  };\n  function replace(_logger, level) {\n    if (!_logger[level]) {\n      return () => {\n      };\n    }\n    return patch(\n      _logger,\n      level,\n      (original) => {\n        return (...args) => {\n          original.apply(this, args);\n          if (level === \"assert\" && !!args[0]) {\n            return;\n          }\n          if (inStack) {\n            return;\n          }\n          inStack = true;\n          try {\n            const trace = ErrorStackParser.parse(new Error()).map((stackFrame) => stackFrame.toString()).splice(1);\n            const argsForPayload = level === \"assert\" ? args.slice(1) : args;\n            const payload = argsForPayload.map(\n              (s) => stringify(s, logOptions.stringifyOptions)\n            );\n            logCount++;\n            if (logCount < logOptions.lengthThreshold) {\n              cb({\n                level,\n                trace,\n                payload\n              });\n            } else if (logCount === logOptions.lengthThreshold) {\n              cb({\n                level: \"warn\",\n                trace: [],\n                payload: [\n                  stringify(\"The number of log records reached the threshold.\")\n                ]\n              });\n            }\n          } catch (error) {\n            original(\"rrweb logger error:\", error, ...args);\n          } finally {\n            inStack = false;\n          }\n        };\n      }\n    );\n  }\n}\nconst PLUGIN_NAME = \"rrweb/console@1\";\nconst getRecordConsolePlugin = (options) => ({\n  name: PLUGIN_NAME,\n  observer: initLogObserver,\n  options\n});\nexport {\n  PLUGIN_NAME,\n  getRecordConsolePlugin\n};\n//# sourceMappingURL=rrweb-plugin-console-record.js.map\n","import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n    DeadClicksAutoCaptureConfig,\n    ExternalIntegrationKind,\n    Properties,\n    RemoteConfig,\n    SiteAppLoader,\n    SessionStartReason,\n} from '../types'\nimport type {\n    ConversationsRemoteConfig,\n    GetMessagesResponse,\n    GetTicketsOptions,\n    GetTicketsResponse,\n    MarkAsReadResponse,\n    RestoreFromTokenResponse,\n    RequestRestoreLinkResponse,\n    SendMessageResponse,\n    UserProvidedTraits,\n} from '../posthog-conversations-types'\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\nimport { eventWithTime } from '../extensions/replay/types/rrweb-types'\nimport { ErrorTracking } from '@posthog/core'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n    typeof globalThis & {\n        /*\n         * Main PostHog instance\n         */\n        posthog: any\n\n        /*\n         * This is our contract between (potentially) lazily loaded extensions and the SDK\n         */\n        __PosthogExtensions__?: PostHogExtensions\n\n        /**\n         * When loading remote config, we assign it to this global configuration\n         * for ease of sharing it with the rest of the SDK\n         */\n        _POSTHOG_REMOTE_CONFIG?: Record<\n            string,\n            {\n                config: RemoteConfig\n                siteApps: SiteAppLoader[]\n            }\n        >\n\n        /**\n         * If this is set on the window, our logger will log to the console\n         * for ease of debugging. Used for testing purposes only.\n         *\n         * @see {Config.DEBUG} from config.ts\n         */\n        POSTHOG_DEBUG: any\n\n        // Exposed by the browser\n        doNotTrack: any\n\n        // See entrypoints/customizations.full.ts\n        posthogCustomizations: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/exception-autocapture.ts\n         *\n         * @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead\n         */\n        posthogErrorWrappingFunctions: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/posthog-recorder.ts\n         *\n         * @deprecated use `__PosthogExtensions__.rrweb` instead\n         */\n        rrweb: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/posthog-recorder.ts\n         *\n         * @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead\n         */\n        rrwebConsoleRecord: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/posthog-recorder.ts\n         *\n         * @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead\n         */\n        getRecordNetworkPlugin: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/web-vitals.ts\n         *\n         * @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead\n         */\n        postHogWebVitalsCallbacks: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/tracing-headers.ts\n         *\n         * @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead\n         */\n        postHogTracingHeadersPatchFns: any\n\n        /**\n         * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n         * Can be removed once we drop support for 1.161.1\n         *\n         * See entrypoints/surveys.ts\n         *\n         * @deprecated use `__PosthogExtensions__.generateSurveys` instead\n         */\n        extendPostHogWithSurveys: any\n\n        /*\n         * These are used to handle our toolbar state.\n         * @see {Toolbar} from extensions/toolbar.ts\n         */\n        ph_load_toolbar: any\n        ph_load_editor: any\n        ph_toolbar_state: any\n    } & Record<`__$$ph_site_app_${string}`, any>\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration'\n\nexport type PostHogExtensionKind =\n    | 'toolbar'\n    | 'exception-autocapture'\n    | 'web-vitals'\n    | 'web-vitals-with-attribution'\n    | 'recorder'\n    | 'lazy-recorder'\n    | 'tracing-headers'\n    | 'surveys'\n    | 'logs'\n    | 'conversations'\n    | 'product-tours'\n    | 'dead-clicks-autocapture'\n    | 'remote-config'\n    | ExternalExtensionKind\n\nexport interface LazyLoadedSessionRecordingInterface {\n    start: (startReason?: SessionStartReason) => void\n    stop: () => void\n    discard: () => void\n    sessionId: string\n    status: SessionRecordingStatus\n    onRRwebEmit: (rawEvent: eventWithTime) => void\n    log: (message: string, level: 'log' | 'warn' | 'error') => void\n    sdkDebugProperties: Properties\n    overrideLinkedFlag: () => void\n    overrideSampling: () => void\n    overrideTrigger: (triggerType: TriggerType) => void\n    isStarted: boolean\n    tryAddCustomEvent(tag: string, payload: any): boolean\n}\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n    start: (observerTarget: Node) => void\n    stop: () => void\n}\n\nexport interface LazyLoadedConversationsInterface {\n    // Widget control\n    show: () => void\n    hide: () => void\n    isVisible: () => boolean\n\n    // Lifecycle\n    reset: () => void\n\n    // Identity verification\n    setIdentity: () => void\n    clearIdentity: () => void\n\n    // API methods\n    sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise<SendMessageResponse>\n    getMessages: (ticketId?: string, after?: string) => Promise<GetMessagesResponse>\n    markAsRead: (ticketId?: string) => Promise<MarkAsReadResponse>\n    getTickets: (options?: GetTicketsOptions) => Promise<GetTicketsResponse>\n    requestRestoreLink: (email: string) => Promise<RequestRestoreLinkResponse>\n    restoreFromToken: (restoreToken: string) => Promise<RestoreFromTokenResponse>\n    restoreFromUrlToken: () => Promise<RestoreFromTokenResponse | null>\n    getCurrentTicketId: () => string | null\n    getWidgetSessionId: () => string\n}\n\ninterface PostHogExtensions {\n    loadExternalDependency?: (\n        posthog: PostHog,\n        kind: PostHogExtensionKind,\n        callback: (error?: string | Event, event?: Event) => void\n    ) => void\n\n    loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n    errorWrappingFunctions?: {\n        wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n        wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n        wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n    }\n    rrweb?: { record: any; version: string; wasMaxDepthReached?: () => boolean; resetMaxDepthState?: () => void }\n    rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n    generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined\n    generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined\n    logs?: {\n        initializeLogs?: (posthog: PostHog) => any | undefined\n    }\n    postHogWebVitalsCallbacks?: {\n        onLCP: (metric: any) => void\n        onCLS: (metric: any) => void\n        onFCP: (metric: any) => void\n        onINP: (metric: any) => void\n    }\n    /**\n     * @deprecated\n     *\n     * this was introduced briefly, it is now always a no-op and only kept for backwards compatibility\n     */\n    loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks']\n    tracingHeadersPatchFns?: {\n        _patchFetch: (\n            hostnames: TracingHeadersHostnames,\n            distinctId: TracingHeadersDistinctId,\n            sessionManager?: SessionIdManager\n        ) => () => void\n        _patchXHR: (\n            hostnames: TracingHeadersHostnames,\n            distinctId: TracingHeadersDistinctId,\n            sessionManager?: SessionIdManager\n        ) => () => void\n    }\n    initDeadClicksAutocapture?: (\n        ph: PostHog,\n        config: DeadClicksAutoCaptureConfig\n    ) => LazyLoadedDeadClicksAutocaptureInterface\n    integrations?: {\n        [K in ExternalIntegrationKind]?: { start: (posthog: PostHog) => void; stop: () => void }\n    }\n    initSessionRecording?: (ph: PostHog) => LazyLoadedSessionRecordingInterface\n    initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\n// React Native polyfills for posthog-js compatibility\nif (typeof self === 'undefined') {\n    ;(global as any).self = global\n}\nif (typeof File === 'undefined') {\n    ;(global as any).File = function () {}\n}\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n    global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const CompressionStream = global?.CompressionStream\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport function isBrowserOnline(): boolean {\n    return !!(win && win.navigator.onLine !== false)\n}\n\nexport { win as window }\n","import { Compression } from \"./types.mjs\";\nfunction isGzipSupported() {\n    return 'CompressionStream' in globalThis && 'TextEncoder' in globalThis && 'Response' in globalThis && 'function' == typeof Response.prototype.blob;\n}\nconst NATIVE_GZIP_VALIDATION_ERROR = 'NativeGzipValidationError';\nconst GZIP_MAGIC_FIRST_BYTE = 0x1f;\nconst GZIP_MAGIC_SECOND_BYTE = 0x8b;\nconst GZIP_DEFLATE_METHOD = 0x08;\nconst hasGzipMagic = (bytes)=>bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;\nconst isGzipData = (body)=>{\n    if (body instanceof ArrayBuffer) return hasGzipMagic(new Uint8Array(body));\n    if (ArrayBuffer.isView(body)) return hasGzipMagic(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n    return false;\n};\nconst isGzipRequest = (compression, urlCompression)=>compression === Compression.GZipJS || urlCompression === Compression.GZipJS || 'gzip' === urlCompression;\nconst isNativeAsyncGzipReadError = (error)=>{\n    if (!error || 'object' != typeof error) return false;\n    const name = 'name' in error ? String(error.name) : '';\n    return 'NotReadableError' === name;\n};\nconst isNativeAsyncGzipError = (error)=>{\n    if (!error || 'object' != typeof error) return false;\n    const name = 'name' in error ? String(error.name) : '';\n    return isNativeAsyncGzipReadError(error) || name === NATIVE_GZIP_VALIDATION_ERROR;\n};\nlet crc32Table;\nconst getCrc32Table = ()=>{\n    if (crc32Table) return crc32Table;\n    crc32Table = [];\n    for(let i = 0; i < 256; i++){\n        let crc = i;\n        for(let j = 0; j < 8; j++)crc = 1 & crc ? 0xedb88320 ^ crc >>> 1 : crc >>> 1;\n        crc32Table[i] = crc >>> 0;\n    }\n    return crc32Table;\n};\nconst crc32 = (bytes)=>{\n    const table = getCrc32Table();\n    let crc = 0xffffffff;\n    for(let i = 0; i < bytes.length; i++)crc = table[(crc ^ bytes[i]) & 0xff] ^ crc >>> 8;\n    return (0xffffffff ^ crc) >>> 0;\n};\nconst throwNativeGzipValidationError = (reason)=>{\n    const error = new Error(`Native gzip produced invalid output: ${reason}`);\n    error.name = NATIVE_GZIP_VALIDATION_ERROR;\n    throw error;\n};\nconst validateNativeGzip = async (compressed, inputBytes)=>{\n    if (compressed.size < 18) throwNativeGzipValidationError('too-short');\n    const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());\n    if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD) throwNativeGzipValidationError('invalid-header');\n    const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());\n    if (trailer.getUint32(0, true) !== crc32(inputBytes)) throwNativeGzipValidationError('invalid-crc');\n    const inputSize = inputBytes.length >>> 0;\n    if (trailer.getUint32(4, true) !== inputSize) throwNativeGzipValidationError('invalid-size');\n};\nasync function gzipCompress(input, isDebug = true, options) {\n    try {\n        const inputBytes = new TextEncoder().encode(input);\n        const compressedStream = new globalThis.CompressionStream('gzip');\n        const writer = compressedStream.writable.getWriter();\n        const writePromise = writer.write(inputBytes).then(()=>writer.close()).catch(async (err)=>{\n            try {\n                await writer.abort(err);\n            } catch  {}\n            throw err;\n        });\n        const responsePromise = new Response(compressedStream.readable).blob();\n        const [compressed] = await Promise.all([\n            responsePromise,\n            writePromise\n        ]);\n        await validateNativeGzip(compressed, inputBytes);\n        return compressed;\n    } catch (error) {\n        if (options?.rethrow) throw error;\n        if (isDebug) console.error('Failed to gzip compress data', error);\n        return null;\n    }\n}\nexport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError };\n","function includes(str, needle) {\n    return -1 !== str.indexOf(needle);\n}\nconst trim = function(str) {\n    return str.trim();\n};\nconst stripLeadingDollar = function(s) {\n    return s.replace(/^\\$/, '');\n};\nfunction isDistinctIdStringLike(value) {\n    return [\n        'distinct_id',\n        'distinctid'\n    ].includes(value.toLowerCase());\n}\nfunction safeJsonStringify(value) {\n    const ancestors = [];\n    return JSON.stringify(value, function(_key, replacementValue) {\n        if ('bigint' == typeof replacementValue) return replacementValue.toString();\n        if ('function' == typeof replacementValue || 'symbol' == typeof replacementValue) return;\n        if (replacementValue instanceof Error) return {\n            name: replacementValue.name,\n            message: replacementValue.message,\n            stack: replacementValue.stack\n        };\n        if (replacementValue && 'object' == typeof replacementValue) {\n            while(ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)ancestors.pop();\n            if (ancestors.includes(replacementValue)) return '[Circular]';\n            ancestors.push(replacementValue);\n        }\n        return replacementValue;\n    }) ?? 'null';\n}\nfunction deepSortKeys(value) {\n    if (null === value || 'object' != typeof value) return value;\n    if (Array.isArray(value)) return value.map(deepSortKeys);\n    return Object.keys(value).sort().reduce((acc, key)=>{\n        acc[key] = deepSortKeys(value[key]);\n        return acc;\n    }, {});\n}\nfunction getPersonPropertiesHash(distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {\n    return JSON.stringify({\n        distinct_id,\n        userPropertiesToSet: userPropertiesToSet ? deepSortKeys(userPropertiesToSet) : void 0,\n        userPropertiesToSetOnce: userPropertiesToSetOnce ? deepSortKeys(userPropertiesToSetOnce) : void 0\n    });\n}\nexport { getPersonPropertiesHash, includes, isDistinctIdStringLike, safeJsonStringify, stripLeadingDollar, trim };\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n    return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n    if (isObject(x)) {\n        for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n        return true;\n    }\n    return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n    return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n    return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n    switch(Object.prototype.toString.call(candidate)){\n        case '[object Error]':\n        case '[object Exception]':\n        case '[object DOMException]':\n        case '[object DOMError]':\n        case '[object WebAssembly.Exception]':\n            return true;\n        default:\n            return isInstanceOf(candidate, Error);\n    }\n}\nfunction isErrorEvent(event) {\n    return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n    return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n    return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n    try {\n        return candidate instanceof base;\n    } catch  {\n        return false;\n    }\n}\nconst yesLikeValues = [\n    true,\n    'true',\n    1,\n    '1',\n    'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n    false,\n    'false',\n    0,\n    '0',\n    'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { isNumber } from \"./type-utils.mjs\";\nfunction clampToRange(value, min, max, logger, fallbackValue) {\n    if (min > max) {\n        logger.warn('min cannot be greater than max.');\n        min = max;\n    }\n    if (isNumber(value)) if (value > max) {\n        logger.warn(' cannot be  greater than max: ' + max + '. Using max value instead.');\n        return max;\n    } else {\n        if (!(value < min)) return value;\n        logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');\n        return min;\n    }\n    logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);\n    return clampToRange(fallbackValue || max, min, max, logger);\n}\nfunction getRemoteConfigBool(field, key, defaultValue = true) {\n    if (null == field) return defaultValue;\n    if ('boolean' == typeof field) return field;\n    if ('object' == typeof field) {\n        const value = field[key];\n        return 'boolean' == typeof value ? value : defaultValue;\n    }\n    return defaultValue;\n}\nfunction getRemoteConfigNumber(field, key) {\n    if (null == field || 'object' != typeof field) return;\n    const value = field[key];\n    if ('number' == typeof value && Number.isFinite(value)) return value;\n    if ('string' == typeof value) {\n        const trimmed = value.trim();\n        if ('' === trimmed) return;\n        const parsed = Number(trimmed);\n        return Number.isFinite(parsed) ? parsed : void 0;\n    }\n}\nfunction isValidSampleRate(value) {\n    return 'number' == typeof value && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nexport { clampToRange, getRemoteConfigBool, getRemoteConfigNumber, isValidSampleRate };\n","import { clampToRange } from \"./number-utils.mjs\";\nconst ONE_DAY_IN_MS = 86400000;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;\nfunction resolveExceptionRateLimiterConfig(config = {}) {\n    return {\n        refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,\n        bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE\n    };\n}\nclass BucketedRateLimiter {\n    constructor(options){\n        this._buckets = {};\n        this._onBucketRateLimited = options._onBucketRateLimited;\n        this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);\n        this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);\n        this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);\n    }\n    _applyRefill(bucket, now) {\n        const elapsedMs = now - bucket.lastAccess;\n        const refillIntervals = Math.floor(elapsedMs / this._refillInterval);\n        if (refillIntervals > 0) {\n            const tokensToAdd = refillIntervals * this._refillRate;\n            bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);\n            bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;\n        }\n    }\n    consumeRateLimit(key) {\n        const now = Date.now();\n        const keyStr = String(key);\n        let bucket = this._buckets[keyStr];\n        if (bucket) this._applyRefill(bucket, now);\n        else {\n            bucket = {\n                tokens: this._bucketSize,\n                lastAccess: now\n            };\n            this._buckets[keyStr] = bucket;\n        }\n        if (0 === bucket.tokens) return true;\n        bucket.tokens--;\n        if (0 === bucket.tokens) this._onBucketRateLimited?.(key);\n        return 0 === bucket.tokens;\n    }\n    stop() {\n        this._buckets = {};\n    }\n}\nexport { BucketedRateLimiter, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE, resolveExceptionRateLimiterConfig };\n","export * from \"./bot-detection.mjs\";\nexport * from \"./bucketed-rate-limiter.mjs\";\nexport * from \"./number-utils.mjs\";\nexport * from \"./string-utils.mjs\";\nexport * from \"./type-utils.mjs\";\nexport * from \"./promise-queue.mjs\";\nexport * from \"./logger.mjs\";\nexport * from \"./user-agent-utils.mjs\";\nconst STRING_FORMAT = 'utf8';\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nfunction isValidUUID(value) {\n    return 'string' == typeof value && UUID_REGEX.test(value);\n}\nfunction getEventUuid(uuid, generateUuid) {\n    return isValidUUID(uuid) ? uuid : generateUuid();\n}\nfunction assert(truthyValue, message) {\n    if (!truthyValue || 'string' != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);\n}\nfunction isEmpty(truthyValue) {\n    if (0 === truthyValue.trim().length) return true;\n    return false;\n}\nfunction removeTrailingSlash(url) {\n    return url?.replace(/\\/+$/, '');\n}\nfunction stripUrlHash(url) {\n    if (!url) return url;\n    return url.split('#')[0];\n}\nasync function retriable(fn, props) {\n    let lastError = null;\n    for(let i = 0; i < props.retryCount + 1; i++){\n        if (i > 0) await new Promise((r)=>setTimeout(r, props.retryDelay));\n        try {\n            const res = await fn();\n            return res;\n        } catch (e) {\n            lastError = e;\n            if (!props.retryCheck(e)) throw e;\n        }\n    }\n    throw lastError;\n}\nfunction currentTimestamp() {\n    return new Date().getTime();\n}\nfunction currentISOTime() {\n    return new Date().toISOString();\n}\nfunction safeSetTimeout(fn, timeout) {\n    const t = setTimeout(fn, timeout);\n    t?.unref && t?.unref();\n    return t;\n}\nconst isPromise = (obj)=>obj && 'function' == typeof obj.then;\nconst isError = (x)=>x instanceof Error;\nfunction getFetch() {\n    return 'undefined' != typeof fetch ? fetch : void 0 !== globalThis.fetch ? globalThis.fetch : void 0;\n}\nfunction allSettled(promises) {\n    return Promise.all(promises.map((p)=>(p ?? Promise.resolve()).then((value)=>({\n                status: 'fulfilled',\n                value\n            }), (reason)=>({\n                status: 'rejected',\n                reason\n            }))));\n}\nexport { STRING_FORMAT, UUID_REGEX, allSettled, assert, currentISOTime, currentTimestamp, getEventUuid, getFetch, isError, isPromise, isValidUUID, removeTrailingSlash, retriable, safeSetTimeout, stripUrlHash };\n","import { window } from './globals'\n\n// When angular patches functions they pass the above `isNativeFunction` check (at least the MutationObserver)\nexport const isAngularZonePresent = (): boolean => {\n    return !!(window as any).Zone\n}\n\nexport const isDocument = (x: unknown): x is Document => {\n    // eslint-disable-next-line posthog-js/no-direct-document-check\n    return x instanceof Document\n}\n","import packageInfo from '../package.json'\n\ntype SDKDistChannel = 'npm' | 'cdn'\n\n// overridden in posthog-core,\n// e.g.     Config.DEBUG = Config.DEBUG || instance.config.debug\nconst Config: {\n    DEBUG: boolean\n    LIB_VERSION: string\n    LIB_NAME: string\n    SDK_DIST_CHANNEL?: SDKDistChannel\n    JS_SDK_VERSION: string\n} = {\n    DEBUG: false,\n    LIB_VERSION: packageInfo.version,\n    LIB_NAME: 'web',\n    /** The actual JS SDK version, unaffected by _overrideSDKInfo. Used for the `ver` request param. */\n    JS_SDK_VERSION: packageInfo.version,\n}\n\nexport default Config\n","import Config from '../config'\nimport { isUndefined } from '@posthog/core'\nimport { assignableWindow, window } from './globals'\nimport type { Logger } from '@posthog/core'\n\ntype CreateLoggerOptions = {\n    debugEnabled?: boolean\n}\n\ntype PosthogJsLogger = Omit<Logger, 'createLogger'> & {\n    _log: (level: 'debug' | 'log' | 'warn' | 'error', ...args: any[]) => void\n    uninitializedWarning: (methodName: string) => void\n    createLogger: (prefix: string, options?: CreateLoggerOptions) => PosthogJsLogger\n}\n\nconst _createLogger = (prefix: string, { debugEnabled }: CreateLoggerOptions = {}): PosthogJsLogger => {\n    const logger: PosthogJsLogger = {\n        _log: (level: 'debug' | 'log' | 'warn' | 'error', ...args: any[]) => {\n            if (\n                window &&\n                (Config.DEBUG || assignableWindow.POSTHOG_DEBUG || debugEnabled) &&\n                !isUndefined(window.console) &&\n                window.console\n            ) {\n                const consoleLog =\n                    '__rrweb_original__' in window.console[level]\n                        ? (window.console[level] as any)['__rrweb_original__']\n                        : window.console[level]\n\n                consoleLog(prefix, ...args)\n            }\n        },\n\n        debug: (...args: any[]) => {\n            logger._log('debug', ...args)\n        },\n\n        info: (...args: any[]) => {\n            logger._log('log', ...args)\n        },\n\n        warn: (...args: any[]) => {\n            logger._log('warn', ...args)\n        },\n\n        error: (...args: any[]) => {\n            logger._log('error', ...args)\n        },\n\n        critical: (...args: any[]) => {\n            // Critical errors are always logged to the console\n            // eslint-disable-next-line no-console\n            console.error(prefix, ...args)\n        },\n\n        uninitializedWarning: (methodName: string) => {\n            logger.error(`You must initialize PostHog before calling ${methodName}`)\n        },\n\n        createLogger: (additionalPrefix: string, options?: CreateLoggerOptions) =>\n            _createLogger(`${prefix} ${additionalPrefix}`, options),\n    }\n    return logger\n}\n\nexport const logger = _createLogger('[PostHog.js]')\n\nexport const createLogger = logger.createLogger\n","import { PostHogConfig, Properties } from '../types'\nimport { logger } from './logger'\nimport { isFormData, isNullish, isNumber, isString, hasOwnProperty, isArray } from '@posthog/core'\n\nexport function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined {\n    for (let i = 0; i < value.length; i++) {\n        if (predicate(value[i])) {\n            return value[i]\n        }\n    }\n    return undefined\n}\n\nexport function eachArray<E = any>(obj: E[] | null | undefined, iterator: (value: E, key: number) => void): void {\n    if (isArray(obj)) {\n        obj.forEach(iterator)\n    }\n}\n\nexport function each(obj: any, iterator: (value: any, key: any) => void): void {\n    if (isNullish(obj)) {\n        return\n    }\n    if (isArray(obj)) {\n        obj.forEach(iterator)\n        return\n    }\n    if (isFormData(obj)) {\n        obj.forEach((val: any, key: any) => iterator(val, key))\n        return\n    }\n    for (const key in obj) {\n        if (hasOwnProperty.call(obj, key)) {\n            iterator(obj[key], key)\n        }\n    }\n}\n\nexport const extend = function (obj: Record<string, any>, ...args: Record<string, any>[]): Record<string, any> {\n    for (const source of args) {\n        for (const prop in source) {\n            if (source[prop] !== void 0) {\n                obj[prop] = source[prop]\n            }\n        }\n    }\n    return obj\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries<T = any>(obj: Record<string, T>): [string, T][] {\n    const ownProps = Object.keys(obj)\n    let i = ownProps.length\n    const resArray = new Array(i) // preallocate the Array\n\n    while (i--) {\n        resArray[i] = [ownProps[i], obj[ownProps[i]]]\n    }\n    return resArray\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n    try {\n        return fn()\n    } catch {\n        return undefined\n    }\n}\n\nexport const safewrap = function <F extends (...args: any[]) => any = (...args: any[]) => any>(f: F): F {\n    return function (...args) {\n        try {\n            // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n            // @ts-ignore\n            return f.apply(this, args)\n        } catch (e) {\n            logger.critical(\n                'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n            )\n            logger.critical(e)\n        }\n    } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n    for (let i = 0; i < functions.length; i++) {\n        klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n    }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n    const ret: Properties = {}\n    each(p, function (v, k) {\n        if ((isString(v) && v.length > 0) || isNumber(v)) {\n            ret[k] = v\n        }\n    })\n    return ret\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy<T extends Record<string, any> = Record<string, any>>(\n    value: T,\n    customizer?: <K extends keyof T = keyof T>(value: T[K], key?: K) => T[K]\n): T | undefined {\n    const COPY_IN_PROGRESS_SET = new Set()\n\n    function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n        if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n        if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n        COPY_IN_PROGRESS_SET.add(value)\n        let result: T\n\n        if (isArray(value)) {\n            result = [] as any as T\n            eachArray(value, (it) => {\n                result.push(internalDeepCircularCopy(it))\n            })\n        } else {\n            const copy: Record<string, any> = {}\n            each(value, (val, key) => {\n                if (!COPY_IN_PROGRESS_SET.has(val)) {\n                    copy[key] = internalDeepCircularCopy(val, key)\n                }\n            })\n            result = copy as T\n        }\n        return result\n    }\n    return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings<T extends Record<string, any> = Record<string, any>>(\n    object: T,\n    maxStringLength: number\n): T {\n    return deepCircularCopy(object, (value: any) => {\n        if (isString(value)) {\n            return (value as string).slice(0, maxStringLength)\n        }\n        return value\n    }) as T\n}\n\n// NOTE: Update PostHogConfig docs if you change this list\n// We will not try to catch all bullets here, but we should make an effort to catch the most common ones\n// You should be highly against adding more to this list, because ultimately customers can configure\n// their `cross_subdomain_cookie` setting to anything they want.\nconst EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app']\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n    const hostname = documentLocation?.hostname\n\n    if (!isString(hostname)) {\n        return false\n    }\n    // split and slice isn't a great way to match arbitrary domains,\n    // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n    // for the hostname\n    const lastTwoParts = hostname.split('.').slice(-2).join('.')\n\n    for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {\n        if (lastTwoParts === excluded) {\n            return false\n        }\n    }\n\n    return true\n}\n\n// Use this instead of element.addEventListener to avoid eslint errors\n// this properly implements the default options for passive event listeners\nexport function addEventListener(\n    element: Window | Document | Element | undefined,\n    event: string,\n    callback: EventListener,\n    options?: AddEventListenerOptions\n): void {\n    const { capture = false, passive = true } = options ?? {}\n\n    // This is the only place where we are allowed to call this function\n    // because the whole idea is that we should be calling this instead of the built-in one\n    // eslint-disable-next-line posthog-js/no-add-event-listener\n    element?.addEventListener(event, callback, { capture, passive })\n}\n\n/**\n * Helper to migrate deprecated config fields to new field names with appropriate warnings\n * @param config - The config object to check\n * @param newField - The new field name to use\n * @param oldField - The deprecated field name to check for\n * @param defaultValue - The default value if neither field is set\n * @param loggerInstance - Optional logger instance for deprecation warnings\n * @returns The value to use (new field takes precedence over old field)\n */\nexport function migrateConfigField<T>(\n    config: Record<string, any>,\n    newField: string,\n    oldField: string,\n    defaultValue: T,\n    loggerInstance?: { warn: (message: string) => void }\n): T {\n    const hasNewField = newField in config && !isNullish(config[newField])\n    const hasOldField = oldField in config && !isNullish(config[oldField])\n\n    if (hasNewField) {\n        return config[newField]\n    }\n\n    if (hasOldField) {\n        if (loggerInstance) {\n            loggerInstance.warn(\n                `Config field '${oldField}' is deprecated. Please use '${newField}' instead. ` +\n                    `The old field will be removed in a future major version.`\n            )\n        }\n        return config[oldField]\n    }\n\n    return defaultValue\n}\n\nconst TOOLBAR_INTERNAL_INSTANCE_NAME = 'ph_toolbar_internal'\n\nexport function isToolbarInstance(config: Pick<PostHogConfig, 'name'>): boolean {\n    return config.name === TOOLBAR_INTERNAL_INSTANCE_NAME\n}\n","import { each } from './'\n\nimport { isArray, isFile, isUndefined } from '@posthog/core'\nimport { logger } from './logger'\nimport { document, isBrowserOnline } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n    const location = document?.createElement('a')\n    if (isUndefined(location)) {\n        return null\n    }\n\n    location.href = url\n    return location\n}\n\nexport const formDataToQuery = function (formdata: Record<string, any> | FormData, arg_separator = '&'): string {\n    let use_val: string\n    let use_key: string\n    const tph_arr: string[] = []\n\n    each(formdata, function (val: File | string | undefined, key: string | undefined) {\n        // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n        if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n            return\n        }\n\n        use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n        use_key = encodeURIComponent(key)\n        tph_arr[tph_arr.length] = use_key + '=' + use_val\n    })\n\n    return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n    const withoutHash: string = url.split('#')[0] || ''\n\n    // Split only on the first ? to sort problem out for those with multiple ?s\n    // and then remove them\n    const queryParams: string = withoutHash.split(/\\?(.*)/)[1] || ''\n    const cleanedQueryParams = queryParams.replace(/^\\?+/g, '')\n\n    const queryParts = cleanedQueryParams.split('&')\n    let keyValuePair\n\n    for (let i = 0; i < queryParts.length; i++) {\n        const parts = queryParts[i].split('=')\n        if (parts[0] === param) {\n            keyValuePair = parts\n            break\n        }\n    }\n\n    if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n        return ''\n    } else {\n        let result = keyValuePair[1]\n        try {\n            result = decodeURIComponent(result)\n        } catch {\n            logger.error('Skipping decoding for malformed query param: ' + result)\n        }\n        return result.replace(/\\+/g, ' ')\n    }\n}\n\n// replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,\n// including preserving malformed text in most cases\nexport const maskQueryParams = function <T extends string | undefined>(\n    url: T,\n    maskedParams: string[] | undefined,\n    mask: string\n): T extends string ? string : undefined {\n    if (!url || !maskedParams || !maskedParams.length) {\n        return url as any\n    }\n\n    const splitHash = url.split('#')\n    const withoutHash: string = splitHash[0] || ''\n    const hash = splitHash[1]\n\n    const splitQuery: string[] = withoutHash.split('?')\n    const queryString: string = splitQuery[1]\n    const urlWithoutQueryAndHash: string = splitQuery[0]\n    const queryParts = (queryString || '').split('&')\n\n    // use an array of strings rather than an object to preserve ordering and duplicates\n    const paramStrings: string[] = []\n\n    for (let i = 0; i < queryParts.length; i++) {\n        const keyValuePair = queryParts[i].split('=')\n        if (!isArray(keyValuePair)) {\n            continue\n        } else if (maskedParams.includes(keyValuePair[0])) {\n            paramStrings.push(keyValuePair[0] + '=' + mask)\n        } else {\n            paramStrings.push(queryParts[i])\n        }\n    }\n\n    let result = urlWithoutQueryAndHash\n    if (queryString != null) {\n        result += '?' + paramStrings.join('&')\n    }\n    if (hash != null) {\n        result += '#' + hash\n    }\n\n    return result as any\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n    const matches = hash.match(new RegExp(param + '=([^&]*)'))\n    return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n    return localDomains.includes(location.hostname)\n}\n\nexport const isStatusZeroFailureCircuitBreakerTripped = (\n    consecutiveStatusZeroFailures: number,\n    maxConsecutiveStatusZeroFailures: number\n): boolean => {\n    return consecutiveStatusZeroFailures >= maxConsecutiveStatusZeroFailures && isBrowserOnline()\n}\n\nexport const updateStatusZeroFailureCount = (\n    statusCode: number,\n    consecutiveStatusZeroFailures: number,\n    maxConsecutiveStatusZeroFailures: number,\n    onCircuitBreakerTripped: () => void\n): number => {\n    if (statusCode === 0) {\n        if (isBrowserOnline()) {\n            const updatedConsecutiveStatusZeroFailures = consecutiveStatusZeroFailures + 1\n            if (updatedConsecutiveStatusZeroFailures === maxConsecutiveStatusZeroFailures) {\n                onCircuitBreakerTripped()\n            }\n            return updatedConsecutiveStatusZeroFailures\n        }\n        return consecutiveStatusZeroFailures\n    }\n\n    return 0\n}\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\nimport { isFunction } from '@posthog/core'\n\n// Each call to `patch` installs a \"layer\" in the wrapper chain. A wrapper calls\n// down through its layer's mutable `next` reference rather than closing over the\n// original directly, so that any layer can later be spliced out of the chain —\n// even when newer wrappers sit on top of it.\n//\n// Without this, restoring a patch only worked when it was still on top of the\n// chain (`source[name] === wrapped`). posthog-js wraps `window.fetch` in two\n// independent places (tracing headers and session-recording network capture),\n// so restores routinely ran out of order and silently no-op'd. Each leaked\n// wrapper stayed in the call path, and repeated start/stop cycles grew the chain\n// without bound until a real fetch walked a chain deep enough to overflow the\n// call stack (\"Maximum call stack size exceeded\" from recursive `window.fetch`).\ninterface PatchLayer {\n    next: (...args: any[]) => any\n}\n\nconst noop = () => {\n    //\n}\n\nexport function patch(\n    source: { [key: string]: any },\n    name: string,\n    replacement: (...args: unknown[]) => unknown\n): () => void {\n    try {\n        if (!(name in source)) {\n            return noop\n        }\n\n        const original = source[name] as (...args: any[]) => any\n\n        const layer: PatchLayer = {\n            next: original,\n        }\n\n        // The wrapper receives this stable delegate instead of `original`, so the\n        // function it actually calls can be re-pointed when a lower layer is removed.\n        const callNext = function (this: unknown, ...args: unknown[]) {\n            return layer.next.apply(this, args)\n        }\n\n        const wrapped = replacement(callNext)\n\n        // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n        // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n        if (isFunction(wrapped)) {\n            wrapped.prototype = wrapped.prototype || {}\n            Object.defineProperties(wrapped, {\n                __posthog_wrapped__: {\n                    enumerable: false,\n                    value: true,\n                },\n                __posthog_layer__: {\n                    enumerable: false,\n                    value: layer,\n                },\n            })\n        }\n\n        source[name] = wrapped\n\n        return () => {\n            // If we're still on top, hand back whatever we currently delegate to\n            // (lower layers may already have been removed, so this is not necessarily\n            // the `original` we captured at install time).\n            if (source[name] === wrapped) {\n                source[name] = layer.next\n                return\n            }\n\n            // Otherwise newer wrappers sit on top of us. Find the posthog layer directly\n            // above us and re-point it past us, removing our wrapper from the call path\n            // without disturbing the newer wrappers.\n            let current: any = source[name]\n            while (isFunction(current) && (current as any).__posthog_layer__) {\n                const currentLayer = (current as any).__posthog_layer__ as PatchLayer\n                if (currentLayer.next === wrapped) {\n                    currentLayer.next = layer.next\n                    return\n                }\n                current = currentLayer.next\n            }\n\n            // If we get here we're buried under a non-posthog wrapper that closed over\n            // us directly, or we've already been removed / replaced wholesale. There's\n            // nothing safe to do, so leave the chain untouched.\n        }\n    } catch {\n        return noop\n        // This can throw when multiple instrumentation layers try to wrap the same global object,\n        // such as XMLHttpRequest, and redefine the same non-configurable wrapper marker.\n    }\n}\n","import { NetworkRecordOptions } from '../../../types'\n\nfunction hostnameFromURL(url: string | URL | RequestInfo): string | null {\n    try {\n        if (typeof url === 'string') {\n            return new URL(url).hostname\n        }\n        if ('url' in url) {\n            return new URL(url.url).hostname\n        }\n        return url.hostname\n    } catch {\n        return null\n    }\n}\n\nexport function isHostOnDenyList(url: string | URL | Request, options: NetworkRecordOptions) {\n    const hostname = hostnameFromURL(url)\n    const defaultNotDenied = { hostname, isHostDenied: false }\n\n    if (!options.payloadHostDenyList?.length || !hostname?.trim().length) {\n        return defaultNotDenied\n    }\n\n    for (const deny of options.payloadHostDenyList) {\n        if (hostname.endsWith(deny)) {\n            return { hostname, isHostDenied: true }\n        }\n    }\n\n    return defaultNotDenied\n}\n","import type { PostHog } from '../posthog-core'\nimport { window } from './globals'\nimport { isFunction, isString, isUndefined } from '@posthog/core'\nimport { logger } from './logger'\n\n/**\n * Applies the `get_current_url` config hook to an already-resolved URL. Returns `defaultUrl`\n * unchanged when no override is configured, or if the override throws or returns a\n * non-string/empty value.\n *\n * Use this when the caller already has its own URL source (e.g. web experiments read\n * `window.location` via a mockable indirection); otherwise prefer `getTargetingUrl`.\n */\nexport function applyUrlTargetingOverride(instance: PostHog | undefined, defaultUrl: string): string {\n    const override = instance?.config?.get_current_url\n    if (!isFunction(override)) {\n        return defaultUrl\n    }\n\n    try {\n        const result = override(defaultUrl)\n        return isString(result) && result ? result : defaultUrl\n    } catch (e) {\n        logger.error('Error in get_current_url, falling back to window.location.href', e)\n        return defaultUrl\n    }\n}\n\n/**\n * Resolves the URL used for client-side URL targeting: session replay URL triggers, the\n * session replay URL blocklist, survey URL conditions, product tour URL conditions, and web\n * experiment URL conditions.\n *\n * Defaults to `window.location.href`, but honors the `get_current_url` config hook so apps\n * that rewrite their URL (e.g. Electron/desktop builds, or `$current_url` rewrites in\n * `before_send`) can make targeting match the logical URL instead of the raw browser URL.\n *\n * Returns `undefined` when there is no URL available (e.g. non-browser environments).\n *\n * Called on every rrweb event by the replay URL triggers/blocklist, so a configured\n * `get_current_url` override should stay cheap.\n */\nexport function getTargetingUrl(instance: PostHog | undefined): string | undefined {\n    const defaultUrl = window?.location?.href\n    return isUndefined(defaultUrl) ? undefined : applyUrlTargetingOverride(instance, defaultUrl)\n}\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DIST_CHANNEL = '$sdk_dist_channel'\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\n// How long the cached `$surveys` definitions are considered fresh. After this, the next\n// `getSurveys` call serves the cache immediately but kicks off a background refresh so\n// server-side changes (e.g. a survey switched from popover to API) propagate to a\n// long-lived tab without needing a page reload.\nexport const SURVEYS_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n// After a failed background refresh we back off for the same window as the cache TTL before\n// trying again. Aliased to make the shared duration intentional rather than coincidental.\nexport const SURVEYS_REFRESH_BACKOFF_MS = SURVEYS_CACHE_TTL_MS\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n","import { AutocaptureConfig, PostHogConfig, Properties } from './types'\nimport type { PostHog } from './posthog-core'\nimport { each, entries } from './utils'\n\nimport { isNullish, isString, isUndefined, isArray, isBoolean } from '@posthog/core'\nimport { logger } from './utils/logger'\nimport { window } from './utils/globals'\nimport { getTargetingUrl } from './utils/url-targeting-utils'\nimport { isElementNode, isShadowRoot, isTag, isTextNode } from './utils/element-utils'\nimport { includes, trim } from '@posthog/core'\n\n// Real DOM trees are at most a few hundred nodes deep; a patched parentNode\n// chain could otherwise trap ancestor walks in an unbounded loop.\nexport const MAX_DOM_ANCESTOR_DEPTH = 1000\n\nexport function splitClassString(s: string): string[] {\n    return s ? trim(s).split(/\\s+/) : []\n}\n\nfunction checkForURLMatches(urlsList: (string | RegExp)[], instance?: PostHog): boolean {\n    const url = getTargetingUrl(instance)\n    return !!(url && urlsList && urlsList.some((regex) => url.match(regex)))\n}\n\n/*\n * Get the className of an element, accounting for edge cases where element.className is an object\n *\n * Because this is a string it can contain unexpected characters\n * So, this method safely splits the className and returns that array.\n */\nexport function getClassNames(el: Element): string[] {\n    let className = ''\n    switch (typeof el.className) {\n        case 'string':\n            className = el.className\n            break\n        // TODO: when is this ever used?\n        case 'object': // handle cases where className might be SVGAnimatedString or some other type\n            className =\n                (el.className && 'baseVal' in el.className ? (el.className as any).baseVal : null) ||\n                el.getAttribute('class') ||\n                ''\n            break\n        default:\n            className = ''\n    }\n\n    return splitClassString(className)\n}\n\nexport function makeSafeText(s: string | null | undefined): string | null {\n    if (isNullish(s)) {\n        return null\n    }\n\n    return (\n        trim(s)\n            // scrub potentially sensitive values\n            .split(/(\\s+)/)\n            .filter((s) => shouldCaptureValue(s))\n            .join('')\n            // normalize whitespace\n            .replace(/[\\r\\n]/g, ' ')\n            .replace(/[ ]+/g, ' ')\n            // truncate\n            .substring(0, 255)\n    )\n}\n\n/*\n * Get the direct text content of an element, protecting against sensitive data collection.\n * Concats textContent of each of the element's text node children; this avoids potential\n * collection of sensitive data that could happen if we used element.textContent and the\n * element had sensitive child elements, since element.textContent includes child content.\n * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).\n * @param {Element} el - element to get the text of\n * @returns {string} the element's direct text content\n */\nexport function getSafeText(el: Element): string {\n    let elText = ''\n\n    if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {\n        each(el.childNodes, function (child) {\n            if (isTextNode(child) && child.textContent) {\n                elText += makeSafeText(child.textContent) ?? ''\n            }\n        })\n    }\n\n    return trim(elText)\n}\n\nexport function getEventTarget(e: Event): Element | null {\n    // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes\n    if (isUndefined(e.target)) {\n        return (e.srcElement as Element) || null\n    } else {\n        if ((e.target as HTMLElement)?.shadowRoot) {\n            return (e.composedPath()[0] as Element) || null\n        }\n        return (e.target as Element) || null\n    }\n}\n\nexport const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n\n/*\n if there is no config, then all elements are allowed\n if there is a config, and there is an allow list, then only elements in the allow list are allowed\n assumes that some other code is checking this element's parents\n */\nfunction checkIfElementTreePassesElementAllowList(\n    elements: Element[],\n    autocaptureConfig: AutocaptureConfig | undefined\n): boolean {\n    const allowlist = autocaptureConfig?.element_allowlist\n    if (isUndefined(allowlist)) {\n        // everything is allowed, when there is no allow list\n        return true\n    }\n\n    // check each element in the tree\n    // if any of the elements are in the allow list, then the tree is allowed\n    for (const el of elements) {\n        if (allowlist.some((elementType) => el.tagName.toLowerCase() === elementType)) {\n            return true\n        }\n    }\n\n    // otherwise there is an allow list and this element tree didn't match it\n    return false\n}\n\nfunction elementMatchesCSSSelector(el: Element, selector: string): boolean {\n    const matches =\n        el.matches ||\n        (el as any).matchesSelector ||\n        (el as any).msMatchesSelector ||\n        (el as any).mozMatchesSelector ||\n        (el as any).webkitMatchesSelector ||\n        (el as any).oMatchesSelector\n    try {\n        return matches ? matches.call(el, selector) : false\n    } catch {\n        return false\n    }\n}\n\n/*\n if there is no selector list (i.e. it is undefined), then any elements matches\n if there is an empty list, then no elements match\n if there is a selector list, then check it against each element provided\n */\nfunction checkIfElementsMatchCSSSelector(elements: Element[], selectorList: string[] | undefined): boolean {\n    if (isUndefined(selectorList)) {\n        // everything is allowed, when there is no selector list\n        return true\n    }\n\n    for (const el of elements) {\n        if (selectorList.some((selector) => elementMatchesCSSSelector(el, selector))) {\n            return true\n        }\n    }\n\n    return false\n}\n\nexport function getParentElement(curEl: Element): Element | false {\n    const parentNode = curEl.parentNode\n    if (!parentNode || !isElementNode(parentNode)) return false\n    return parentNode\n}\n\nconst DEFAULT_AUTOCAPTURE_IGNORE_LIST = ['.ph-no-autocapture', '[data-ph-no-autocapture]']\nconst DEFAULT_CONTENT_IGNORELIST = ['next', 'previous', 'prev', '>', '<']\n// +/- steppers are built to be clicked repeatedly; enabled from the 2026-05-30 config defaults\nexport const DEFAULT_CONTENT_IGNORELIST_WITH_STEPPERS = [...DEFAULT_CONTENT_IGNORELIST, '+', '-', '−', '–']\nconst MAX_CONTENT_IGNORELIST_ENTRIES = 10\n\ninterface ElementWithText {\n    safeText: string\n    ariaLabel: string\n}\n\n// symbol keywords (e.g. +, -, >) match exactly so we don't suppress \"sign-up\", \"5 > 3\", \"C++\", etc.\nconst matchesContentKeyword = (text: string, keyword: string): boolean =>\n    /[a-z0-9]/i.test(keyword) ? text.includes(keyword) : text === keyword\n\nfunction shouldIgnoreByContent(\n    contentIgnorelist: boolean | string[] | undefined,\n    elementsWithText: ElementWithText[]\n): boolean {\n    if (contentIgnorelist === false || isUndefined(contentIgnorelist)) {\n        return false\n    }\n\n    let keywords: string[]\n    if (contentIgnorelist === true) {\n        keywords = DEFAULT_CONTENT_IGNORELIST\n    } else if (isArray(contentIgnorelist)) {\n        if (contentIgnorelist.length > MAX_CONTENT_IGNORELIST_ENTRIES) {\n            logger.error(\n                `[PostHog] content_ignorelist array cannot exceed ${MAX_CONTENT_IGNORELIST_ENTRIES} items. Use css_selector_ignorelist for more complex matching.`\n            )\n            return false\n        }\n        keywords = contentIgnorelist.map((k) => k.toLowerCase())\n    } else {\n        return false\n    }\n\n    return elementsWithText.some(({ safeText, ariaLabel }) => {\n        return keywords.some(\n            (keyword) => matchesContentKeyword(safeText, keyword) || matchesContentKeyword(ariaLabel, keyword)\n        )\n    })\n}\n\n// dead click capture does not run through autocapture's ph-no-capture check,\n// so we include it here so that ph-no-capture also suppresses dead click capture\nconst DEFAULT_DEAD_CLICK_IGNORE_LIST = ['.ph-no-deadclick', '.ph-no-capture']\nexport function shouldCaptureDeadClick(el: Element | null, _config: PostHogConfig['capture_dead_clicks']) {\n    if (!window || cannotCheckForAutocapture(el)) {\n        return false\n    }\n\n    const selectorIgnoreList = isBoolean(_config)\n        ? DEFAULT_DEAD_CLICK_IGNORE_LIST\n        : (_config?.css_selector_ignorelist ?? DEFAULT_DEAD_CLICK_IGNORE_LIST)\n\n    const { targetElementList } = getElementAndParentsForElement(el, false)\n\n    // we don't capture if we match the ignore list\n    return !checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList)\n}\n\n// autocapture check will already filter for ph-no-capture,\n// but we include it here to protect against future changes accidentally removing that check\nconst DEFAULT_RAGE_CLICK_IGNORE_LIST = ['.ph-no-rageclick', '.ph-no-capture']\n\nconst TEXT_SELECTION_INPUT_TYPES = ['', 'text', 'search', 'email', 'password', 'url', 'tel', 'number']\n\nfunction isContentEditableTarget(el: Element): boolean {\n    if ((el as Partial<HTMLElement>).isContentEditable) {\n        return true\n    }\n    const contentEditable = el.getAttribute?.('contenteditable')\n    return contentEditable === 'true' || contentEditable === ''\n}\n\n// repeated fast clicks on a text-editing surface are double/triple-click text selection, not rage\nexport function isTextSelectionTarget(el: Element | null): boolean {\n    if (!el || !isElementNode(el)) {\n        return false\n    }\n    if (isTag(el, 'textarea')) {\n        return true\n    }\n    if (isTag(el, 'input')) {\n        return includes(TEXT_SELECTION_INPUT_TYPES, (el.getAttribute('type') || '').toLowerCase())\n    }\n    return isContentEditableTarget(el)\n}\n\nexport function shouldCaptureRageclick(el: Element | null, _config: PostHogConfig['rageclick']) {\n    if (!window || cannotCheckForAutocapture(el)) {\n        return false\n    }\n\n    let selectorIgnoreList: string[] | boolean\n    let contentIgnorelist: boolean | string[] | undefined\n    let ignoreTextSelection: boolean\n    if (isBoolean(_config)) {\n        selectorIgnoreList = _config ? DEFAULT_RAGE_CLICK_IGNORE_LIST : false\n        // For backward compatibility, don't enable content or text-selection filtering for rageclick: true\n        contentIgnorelist = undefined\n        ignoreTextSelection = false\n    } else {\n        selectorIgnoreList = _config?.css_selector_ignorelist ?? DEFAULT_RAGE_CLICK_IGNORE_LIST\n        contentIgnorelist = _config?.content_ignorelist\n        ignoreTextSelection = _config?.ignore_text_selection ?? false\n    }\n\n    if (selectorIgnoreList === false) {\n        return false\n    }\n\n    if (ignoreTextSelection && isTextSelectionTarget(el)) {\n        return false\n    }\n\n    // Traverse DOM once and cache element data to avoid redundant calls to getSafeText\n    const { targetElementList } = getElementAndParentsForElement(el, false)\n    const elementsWithText: ElementWithText[] = targetElementList.map((element) => ({\n        safeText: getSafeText(element).toLowerCase(),\n        ariaLabel: element.getAttribute('aria-label')?.toLowerCase().trim() || '',\n    }))\n\n    if (shouldIgnoreByContent(contentIgnorelist, elementsWithText)) {\n        return false\n    }\n\n    // we don't capture if we match the ignore list\n    return !checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList)\n}\n\nconst cannotCheckForAutocapture = (el: Element | null) => {\n    return !el || isTag(el, 'html') || !isElementNode(el)\n}\n\nconst getElementAndParentsForElement = (el: Element, captureOnAnyElement: false | true | undefined) => {\n    if (!window || cannotCheckForAutocapture(el)) {\n        return { parentIsUsefulElement: false, targetElementList: [] }\n    }\n\n    let parentIsUsefulElement = false\n    const targetElementList: Element[] = [el]\n    let curEl: Element = el\n    while (curEl.parentNode && !isTag(curEl, 'body')) {\n        if (isShadowRoot(curEl.parentNode)) {\n            targetElementList.push(curEl.parentNode.host)\n            curEl = curEl.parentNode.host\n            continue\n        }\n        const parentNode = getParentElement(curEl)\n        if (!parentNode) break\n        if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {\n            parentIsUsefulElement = true\n        } else {\n            try {\n                const compStyles = window.getComputedStyle(parentNode)\n                if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {\n                    parentIsUsefulElement = true\n                }\n            } catch {}\n        }\n\n        targetElementList.push(parentNode)\n        curEl = parentNode\n    }\n    return { parentIsUsefulElement, targetElementList }\n}\n\n// dead-click skips a click only when the click target is — or is inside — an <a>.\n// Anchors navigate / download / open a new window via the browser, and we have no\n// observable signal for those actions (no DOM mutation, no scroll). For every other\n// element (button, input, select, textarea, label, custom JS-handled divs, etc.) we\n// rely on the existing mutation / scroll / selection / visibility observers — if the\n// app's JS handler ran, those catch the effect; if it didn't, dead-click correctly\n// surfaces the bug. A click on a broken <button> with no handler should still flag.\nexport function shouldSkipDeadClick(el: Element | null): boolean {\n    if (!window || cannotCheckForAutocapture(el)) {\n        return false\n    }\n    const { targetElementList } = getElementAndParentsForElement(el, false)\n    return targetElementList.some((node) => isTag(node, 'a'))\n}\n\n/*\n * Check whether a DOM event should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @param {Event} event - event to check\n * @param {Object} autocaptureConfig - autocapture config\n * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to \"clickable\" elements\n * @param {string[]} allowedEventTypes - event types to capture, normally just 'click', but some autocapture types react to different events, some elements have fixed events (e.g., form has \"submit\")\n * @returns {boolean} whether the event should be captured\n */\nexport function shouldCaptureDomEvent(\n    el: Element,\n    event: Event,\n    autocaptureConfig: AutocaptureConfig | undefined = undefined,\n    captureOnAnyElement?: boolean,\n    allowedEventTypes?: string[],\n    instance?: PostHog\n): boolean {\n    if (!window || cannotCheckForAutocapture(el)) {\n        return false\n    }\n\n    if (autocaptureConfig?.url_allowlist) {\n        // if the current URL is not in the allow list, don't capture\n        if (!checkForURLMatches(autocaptureConfig.url_allowlist, instance)) {\n            return false\n        }\n    }\n\n    if (autocaptureConfig?.url_ignorelist) {\n        // if the current URL is in the ignore list, don't capture\n        if (checkForURLMatches(autocaptureConfig.url_ignorelist, instance)) {\n            return false\n        }\n    }\n\n    if (autocaptureConfig?.dom_event_allowlist) {\n        const allowlist = autocaptureConfig.dom_event_allowlist\n        if (allowlist && !allowlist.some((eventType) => event.type === eventType)) {\n            return false\n        }\n    }\n\n    const { parentIsUsefulElement, targetElementList } = getElementAndParentsForElement(el, captureOnAnyElement)\n\n    if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {\n        return false\n    }\n\n    if (!checkIfElementsMatchCSSSelector(targetElementList, autocaptureConfig?.css_selector_allowlist)) {\n        return false\n    }\n\n    const selectorIgnoreList = autocaptureConfig?.css_selector_ignorelist ?? DEFAULT_AUTOCAPTURE_IGNORE_LIST\n    if (checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList)) {\n        return false\n    }\n\n    try {\n        const compStyles = window.getComputedStyle(el)\n        if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {\n            return true\n        }\n    } catch {}\n\n    const tag = el.tagName.toLowerCase()\n    switch (tag) {\n        case 'html':\n            return false\n        case 'form':\n            return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0\n        case 'input':\n        case 'select':\n        case 'textarea':\n            return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0\n        default:\n            if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0\n            return (\n                (allowedEventTypes || ['click']).indexOf(event.type) >= 0 &&\n                (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true')\n            )\n    }\n}\n\n/*\n * Check whether a DOM element should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureElement(el: Element): boolean {\n    const seen = new Set<Node>()\n    let depth = 0\n    for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode as Element) {\n        // Abnormal (too deep or cyclic) chain: we can't finish the sensitivity\n        // checks, so fail closed and don't capture.\n        if (depth++ >= MAX_DOM_ANCESTOR_DEPTH || seen.has(curEl)) {\n            return false\n        }\n        seen.add(curEl)\n\n        const classes = getClassNames(curEl)\n        if (includes(classes, 'ph-sensitive') || includes(classes, 'ph-no-capture')) {\n            return false\n        }\n    }\n\n    if (includes(getClassNames(el), 'ph-include')) {\n        return true\n    }\n\n    // don't include hidden or password fields\n    const type = (el as HTMLInputElement).type || ''\n    if (isString(type)) {\n        // it's possible for el.type to be a DOM element if el is a form with a child input[name=\"type\"]\n        switch (type.toLowerCase()) {\n            case 'hidden':\n                return false\n            case 'password':\n                return false\n        }\n    }\n\n    // filter out data from fields that look like sensitive fields\n    const name = (el as HTMLInputElement).name || el.id || ''\n    // See https://github.com/posthog/posthog-js/issues/165\n    // Under specific circumstances a bug caused .replace to be called on a DOM element\n    // instead of a string, removing the element from the page. Ensure this issue is mitigated.\n    if (isString(name)) {\n        // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name=\"name\"]\n        const sensitiveNameRegex =\n            /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i\n        if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {\n            return false\n        }\n    }\n\n    return true\n}\n\n/*\n * Check whether a DOM element is 'sensitive' and we should only capture limited data\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function isSensitiveElement(el: Element): boolean {\n    // don't send data from inputs or similar elements since there will always be\n    // a risk of clientside javascript placing sensitive data in attributes\n    const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset']\n    if (\n        (isTag(el, 'input') && !allowedInputTypes.includes((el as HTMLInputElement).type)) ||\n        isTag(el, 'select') ||\n        isTag(el, 'textarea') ||\n        el.getAttribute('contenteditable') === 'true'\n    ) {\n        return true\n    }\n    return false\n}\n\n// Define the core pattern for matching credit card numbers\nconst coreCCPattern = `(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`)\n// The Unanchored version is essentially the core pattern, usable as is for partial matches\nconst unanchoredCCRegex = new RegExp(coreCCPattern)\n\n// Define the core pattern for matching SSNs with optional dashes\nconst coreSSNPattern = `\\\\d{3}-?\\\\d{2}-?\\\\d{4}`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`)\n// The Unanchored version is essentially the core pattern itself, usable for partial matches\nconst unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`)\n\n/*\n * Check whether a string value should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {string} value - string value to check\n * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureValue(value: string, anchorRegexes = true): boolean {\n    if (isNullish(value)) {\n        return false\n    }\n\n    if (isString(value)) {\n        value = trim(value)\n\n        // check to see if input value looks like a credit card number\n        // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html\n        const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex\n        if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {\n            return false\n        }\n\n        // check to see if input value looks like a social security number\n        const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex\n        if (ssnRegex.test(value)) {\n            return false\n        }\n    }\n\n    return true\n}\n\n/*\n * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)\n * These update on each build and lead to noise in the element chain\n * More details on the attributes here: https://angular.io/guide/view-encapsulation\n * @param {string} attributeName - string value to check\n * @returns {boolean} whether the element is an angular tag\n */\nexport function isAngularStyleAttr(attributeName: string): boolean {\n    if (isString(attributeName)) {\n        return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost'\n    }\n    return false\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces,\n * along with the direct text content of the target element\n * @param {Element} target - element to check\n * @returns {string} text content of the target element and its child span tags\n */\nexport function getDirectAndNestedSpanText(target: Element): string {\n    let text = getSafeText(target)\n    text = `${text} ${getNestedSpanText(target)}`.trim()\n    return shouldCaptureValue(text) ? text : ''\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces\n * @param {Element} target - element to check\n * @returns {string} text content of span tags\n */\nexport function getNestedSpanText(target: Element): string {\n    let text = ''\n    if (target && target.childNodes && target.childNodes.length) {\n        each(target.childNodes, function (child) {\n            if (child && child.tagName?.toLowerCase() === 'span') {\n                try {\n                    const spanText = getSafeText(child)\n                    text = `${text} ${spanText}`.trim()\n\n                    if (child.childNodes && child.childNodes.length) {\n                        text = `${text} ${getNestedSpanText(child)}`.trim()\n                    }\n                } catch (e) {\n                    logger.error('[AutoCapture]', e)\n                }\n            }\n        })\n    }\n    return text\n}\n\n/*\nBack in the day storing events in Postgres we use Elements for autocapture events.\nNow we're using elements_chain. We used to do this parsing/processing during ingestion.\nThis code is just copied over from ingestion, but we should optimize it\nto create elements_chain string directly.\n*/\nexport function getElementsChainString(elements: Properties[]): string {\n    return elementsToString(extractElements(elements))\n}\n\n// This interface is called 'Element' in plugin-scaffold https://github.com/PostHog/plugin-scaffold/blob/b07d3b879796ecc7e22deb71bf627694ba05386b/src/types.ts#L200\n// However 'Element' is a DOM Element when run in the browser, so we have to rename it\ninterface PHElement {\n    text?: string\n    tag_name?: string\n    href?: string\n    attr_id?: string\n    attr_class?: string[]\n    nth_child?: number\n    nth_of_type?: number\n    attributes?: Record<string, any>\n    event_id?: number\n    order?: number\n    group_id?: number\n}\n\nfunction escapeQuotes(input: string): string {\n    return input.replace(/\"|\\\\\"/g, '\\\\\"')\n}\n\nfunction elementsToString(elements: PHElement[]): string {\n    const ret = elements.map((element) => {\n        let el_string = ''\n        if (element.tag_name) {\n            el_string += element.tag_name\n        }\n        if (element.attr_class) {\n            element.attr_class.sort()\n            for (const single_class of element.attr_class) {\n                el_string += `.${single_class.replace(/\"/g, '')}`\n            }\n        }\n        const attributes: Record<string, any> = {\n            ...(element.text ? { text: element.text } : {}),\n            'nth-child': element.nth_child ?? 0,\n            'nth-of-type': element.nth_of_type ?? 0,\n            ...(element.href ? { href: element.href } : {}),\n            ...(element.attr_id ? { attr_id: element.attr_id } : {}),\n            ...element.attributes,\n        }\n        const sortedAttributes: Record<string, any> = {}\n        entries(attributes)\n            .sort(([a], [b]) => a.localeCompare(b))\n            .forEach(\n                ([key, value]) => (sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()))\n            )\n        el_string += ':'\n        el_string += entries(sortedAttributes)\n            .map(([key, value]) => `${key}=\"${value}\"`)\n            .join('')\n        return el_string\n    })\n    return ret.join(';')\n}\n\nfunction extractElements(elements: Properties[]): PHElement[] {\n    return elements.map((el) => {\n        const attributes: { [id: string]: any } = {}\n        const response = {\n            text: el['$el_text']?.slice(0, 400),\n            tag_name: el['tag_name'],\n            href: el['attr__href']?.slice(0, 2048),\n            attr_class: extractAttrClass(el),\n            attr_id: el['attr__id'],\n            nth_child: el['nth_child'],\n            nth_of_type: el['nth_of_type'],\n            attributes,\n        }\n\n        entries(el)\n            .filter(([key]) => key.indexOf('attr__') === 0)\n            .forEach(([key, value]) => (response.attributes[key] = value))\n        return response\n    })\n}\n\nfunction extractAttrClass(el: Properties): PHElement['attr_class'] {\n    const attr_class = el['attr__class']\n    if (!attr_class) {\n        return undefined\n    } else if (isArray(attr_class)) {\n        return attr_class\n    } else {\n        return splitClassString(attr_class)\n    }\n}\n","import { CapturedNetworkRequest, NetworkRecordOptions, PostHogConfig } from '../../../types'\nimport { isFunction, isNullish, isString, isUndefined } from '@posthog/core'\nimport { convertToURL } from '../../../utils/request-utils'\nimport { logger } from '../../../utils/logger'\nimport { shouldCaptureValue } from '../../../autocapture-utils'\nimport { each } from '../../../utils'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\n\nconst REDACTED = 'redacted'\n\n// the hard ceiling for a recorded request/response body — 1MB, even if a larger limit is configured\nexport const MAX_PAYLOAD_SIZE_BYTES = 1000000\n\n// the smallest of the 1MB ceiling or the configured limit if there is one\nexport function effectivePayloadLimitBytes(options: Pick<NetworkRecordOptions, 'payloadSizeLimitBytes'>): number {\n    return Math.min(MAX_PAYLOAD_SIZE_BYTES, options.payloadSizeLimitBytes ?? MAX_PAYLOAD_SIZE_BYTES)\n}\n\nexport const defaultNetworkOptions: Required<NetworkRecordOptions> = {\n    initiatorTypes: [\n        'audio',\n        'beacon',\n        'body',\n        'css',\n        'early-hint',\n        'embed',\n        'fetch',\n        'frame',\n        'iframe',\n        'icon',\n        'image',\n        'img',\n        'input',\n        'link',\n        'navigation',\n        'object',\n        'ping',\n        'script',\n        'track',\n        'video',\n        'xmlhttprequest',\n    ],\n    maskRequestFn: (data: CapturedNetworkRequest) => data,\n    recordHeaders: false,\n    recordBody: false,\n    recordInitialRequests: false,\n    recordPerformance: false,\n    performanceEntryTypeToObserve: [\n        // 'event', // This is too noisy as it covers all browser events\n        'first-input',\n        // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n        // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n        'navigation',\n        'paint',\n        'resource',\n    ],\n    payloadSizeLimitBytes: MAX_PAYLOAD_SIZE_BYTES,\n    payloadHostDenyList: [\n        '.lr-ingest.io',\n        '.ingest.sentry.io',\n        '.clarity.ms',\n        // NB no leading dot here\n        // GA4/gtag beacons go to *.google-analytics.com; with Google Signals on they also hit\n        // analytics.google.com (region1.analytics.google.com/g/collect), so deny both\n        'google-analytics.com',\n        'analytics.google.com',\n        // New Relic browser agent (bam + bam-cell)\n        'nr-data.net',\n        // Datadog browser RUM intake\n        'datadoghq.com',\n        'datadoghq.eu',\n        'ddog-gov.com',\n        // other third-party analytics / session-replay vendors whose telemetry has no replay value\n        'segment.io',\n        'rudderstack.com',\n        'amplitude.com',\n        'mixpanel.com',\n        // Hotjar uses both .com and .io for data collection\n        'hotjar.com',\n        'hotjar.io',\n        'fullstory.com',\n    ],\n    streamNetworkBody: false,\n}\n\nconst HEADER_DENY_LIST = [\n    'authorization',\n    'x-forwarded-for',\n    'authorization',\n    'cookie',\n    'set-cookie',\n    'x-api-key',\n    'x-real-ip',\n    'remote-addr',\n    'forwarded',\n    'proxy-authorization',\n    'x-csrf-token',\n    'x-csrftoken',\n    'x-xsrf-token',\n]\n\nconst PAYLOAD_CONTENT_DENY_LIST = [\n    'password',\n    'secret',\n    'passwd',\n    'api_key',\n    'apikey',\n    'auth',\n    'credentials',\n    'mysql_pwd',\n    'privatekey',\n    'private_key',\n    'token',\n]\n\n// substrings that mark a header as credential-bearing - catches custom names\n// (e.g. x-gist-encoded-user-token) that aren't in the exact deny list above\nconst HEADER_DENY_SUBSTRINGS = [\n    'auth',\n    'token',\n    'secret',\n    'session',\n    'api-key',\n    'apikey',\n    'api_key',\n    'credential',\n    'password',\n    'passwd',\n    'cookie',\n    'csrf',\n    'xsrf',\n]\n\nconst isDeniedHeader = (header: string): boolean => {\n    const lower = header.toLowerCase()\n    return HEADER_DENY_LIST.includes(lower) || HEADER_DENY_SUBSTRINGS.some((s) => lower.includes(s))\n}\n\nconst redactDeniedHeaders = (headers: CapturedNetworkRequest['requestHeaders']): void => {\n    if (!isNullish(headers)) {\n        each(Object.keys(headers), (header) => {\n            if (isDeniedHeader(header)) {\n                headers[header] = REDACTED\n            }\n        })\n    }\n}\n\n// we always remove headers on the deny list because we never want to capture this sensitive data.\n// applies to both request and response headers (e.g. set-cookie is a response header)\nconst removeAuthorizationHeader = (data: CapturedNetworkRequest): CapturedNetworkRequest => {\n    redactDeniedHeaders(data.requestHeaders)\n    redactDeniedHeaders(data.responseHeaders)\n    return data\n}\n\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', '/e/', '/i/']\n// want to ignore posthog paths when capturing requests, or we can get trapped in a loop\n// because calls to PostHog would be reported using a call to PostHog which would be reported....\nconst ignorePostHogPaths = (\n    data: CapturedNetworkRequest,\n    apiHostConfig: PostHogConfig['api_host']\n): CapturedNetworkRequest | undefined => {\n    const url = convertToURL(data.name)\n\n    // we need to account for api host config as e.g. pathname could be /ingest/s/ and we want to ignore that\n    let replaceValue = apiHostConfig.indexOf('http') === 0 ? convertToURL(apiHostConfig)?.pathname : apiHostConfig\n    if (replaceValue === '/') {\n        replaceValue = ''\n    }\n    const pathname = url?.pathname.replace(replaceValue || '', '')\n\n    if (url && pathname && POSTHOG_PATHS_TO_IGNORE.some((path) => pathname.indexOf(path) === 0)) {\n        return undefined\n    }\n    return data\n}\n\nfunction estimateBytes(payload: string): number {\n    return new Blob([payload]).size\n}\n\nfunction enforcePayloadSizeLimit(\n    payload: string | null | undefined,\n    headers: Record<string, any> | undefined,\n    limit: number,\n    description: string\n): string | null | undefined {\n    if (isNullish(payload)) {\n        return payload\n    }\n\n    let requestContentLength: string | number = headers?.['content-length'] || estimateBytes(payload)\n    if (isString(requestContentLength)) {\n        requestContentLength = parseInt(requestContentLength)\n    }\n\n    if (requestContentLength > limit) {\n        return LOGGER_PREFIX + ` ${description} body too large to record (${requestContentLength} bytes)`\n    }\n\n    return payload\n}\n\n// people can have arbitrarily large payloads on their site, but we don't want to ingest them\nconst limitPayloadSize = (\n    options: NetworkRecordOptions\n): ((data: CapturedNetworkRequest | undefined) => CapturedNetworkRequest | undefined) => {\n    const limit = effectivePayloadLimitBytes(options)\n\n    return (data) => {\n        if (data?.requestBody) {\n            data.requestBody = enforcePayloadSizeLimit(data.requestBody, data.requestHeaders, limit, 'Request')\n        }\n\n        if (data?.responseBody) {\n            data.responseBody = enforcePayloadSizeLimit(data.responseBody, data.responseHeaders, limit, 'Response')\n        }\n\n        return data\n    }\n}\n\nfunction scrubPayload(payload: string | null | undefined, label: 'Request' | 'Response'): string | null | undefined {\n    if (isNullish(payload)) {\n        return payload\n    }\n    let scrubbed = payload\n\n    if (!shouldCaptureValue(scrubbed, false)) {\n        scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED\n    }\n    each(PAYLOAD_CONTENT_DENY_LIST, (text) => {\n        if (scrubbed?.length && scrubbed?.indexOf(text) !== -1) {\n            scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED + ' as might contain: ' + text\n        }\n    })\n\n    return scrubbed\n}\n\nfunction scrubPayloads(capturedRequest: CapturedNetworkRequest | undefined): CapturedNetworkRequest | undefined {\n    if (isUndefined(capturedRequest)) {\n        return undefined\n    }\n\n    capturedRequest.requestBody = scrubPayload(capturedRequest.requestBody, 'Request')\n    capturedRequest.responseBody = scrubPayload(capturedRequest.responseBody, 'Response')\n\n    return capturedRequest\n}\n\n/**\n *  whether a maskRequestFn is provided or not,\n *  we ensure that we remove the denied header from requests\n *  we _never_ want to record that header by accident\n *  if someone complains then we'll add an opt-in to let them override it\n */\nexport const buildNetworkRequestOptions = (\n    instanceConfig: PostHogConfig,\n    remoteNetworkOptions: Pick<\n        NetworkRecordOptions,\n        'recordHeaders' | 'recordBody' | 'recordPerformance' | 'payloadHostDenyList'\n    >\n): NetworkRecordOptions => {\n    const config: NetworkRecordOptions = {\n        payloadSizeLimitBytes: defaultNetworkOptions.payloadSizeLimitBytes,\n        performanceEntryTypeToObserve: [...defaultNetworkOptions.performanceEntryTypeToObserve],\n        payloadHostDenyList: [\n            ...(remoteNetworkOptions.payloadHostDenyList || []),\n            ...defaultNetworkOptions.payloadHostDenyList,\n        ],\n    }\n    // client can always disable despite remote options\n    const canRecordHeaders =\n        instanceConfig.session_recording.recordHeaders === false ? false : remoteNetworkOptions.recordHeaders\n    const canRecordBody =\n        instanceConfig.session_recording.recordBody === false ? false : remoteNetworkOptions.recordBody\n    const canRecordPerformance =\n        instanceConfig.capture_performance === false ? false : remoteNetworkOptions.recordPerformance\n\n    const payloadLimiter = limitPayloadSize(config)\n\n    const enforcedCleaningFn: NetworkRecordOptions['maskRequestFn'] = (d: CapturedNetworkRequest) =>\n        payloadLimiter(ignorePostHogPaths(removeAuthorizationHeader(d), instanceConfig.api_host))\n\n    const hasDeprecatedMaskFunction = isFunction(instanceConfig.session_recording.maskNetworkRequestFn)\n\n    if (hasDeprecatedMaskFunction && isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)) {\n        logger.warn(\n            'Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.'\n        )\n    }\n\n    if (hasDeprecatedMaskFunction) {\n        instanceConfig.session_recording.maskCapturedNetworkRequestFn = (data: CapturedNetworkRequest) => {\n            const cleanedURL = instanceConfig.session_recording.maskNetworkRequestFn!({ url: data.name })\n            // the deprecated mask fn can suppress the URL, leaving `name` undefined on purpose\n            // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n            return {\n                ...data,\n                name: cleanedURL?.url,\n            } as CapturedNetworkRequest\n        }\n    }\n\n    config.maskRequestFn = isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)\n        ? (data) => {\n              const cleanedRequest = enforcedCleaningFn(data)\n              return cleanedRequest\n                  ? (instanceConfig.session_recording.maskCapturedNetworkRequestFn?.(cleanedRequest) ?? undefined)\n                  : undefined\n          }\n        : (data) => scrubPayloads(enforcedCleaningFn(data))\n\n    return {\n        ...defaultNetworkOptions,\n        ...config,\n        recordHeaders: canRecordHeaders,\n        recordBody: canRecordBody,\n        recordPerformance: canRecordPerformance,\n        recordInitialRequests: canRecordPerformance,\n        streamNetworkBody: instanceConfig.session_recording.streamNetworkBody === true,\n    }\n}\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n/// <reference lib=\"dom\" />\n\n// rrweb/network@1 code starts\n// most of what is below here will be removed when rrweb release their code for this\n// see https://github.com/rrweb-io/rrweb/pull/1105\n\n// NB adopted from https://github.com/rrweb-io/rrweb/pull/1105 which looks like it will be accepted into rrweb\n// however, in the PR, it throws when the performance observer data is not available\n// and assumes it is running in a browser with the Request API (i.e. not IE11)\n// copying here so that we can use it before rrweb adopt it\n\nimport type { IWindow, listenerHandler, RecordPlugin } from '../types/rrweb-types'\nimport { CapturedNetworkRequest, Headers, InitiatorType, NetworkRecordOptions } from '../../../types'\nimport {\n    isArray,\n    isBoolean,\n    isFormData,\n    isFunction,\n    isNull,\n    isNullish,\n    isString,\n    isUndefined,\n    isObject,\n} from '@posthog/core'\nimport { isDocument } from '../../../utils/type-utils'\nimport { createLogger } from '../../../utils/logger'\nimport { formDataToQuery } from '../../../utils/request-utils'\nimport { patch } from '../rrweb-plugins/patch'\nimport { isHostOnDenyList } from '../../../extensions/replay/external/denylist'\nimport { defaultNetworkOptions, effectivePayloadLimitBytes } from './config'\n\nconst logger = createLogger('[Recorder]')\n\nexport type NetworkData = {\n    requests: CapturedNetworkRequest[]\n    isInitial?: boolean\n}\n\ntype networkCallback = (data: NetworkData) => void\n\nconst isNavigationTiming = (entry: PerformanceEntry): entry is PerformanceNavigationTiming =>\n    entry.entryType === 'navigation'\nconst isResourceTiming = (entry: PerformanceEntry): entry is PerformanceResourceTiming => entry.entryType === 'resource'\n\ntype ObservedPerformanceEntry = (PerformanceNavigationTiming | PerformanceResourceTiming) & {\n    responseStatus?: number\n}\n\nexport function findLast<T>(array: Array<T>, predicate: (value: T) => boolean): T | undefined {\n    const length = array.length\n    for (let i = length - 1; i >= 0; i -= 1) {\n        if (predicate(array[i])) {\n            return array[i]\n        }\n    }\n    return undefined\n}\n\nfunction initPerformanceObserver(cb: networkCallback, win: IWindow, options: Required<NetworkRecordOptions>) {\n    // if we are only observing timings then we could have a single observer for all types, with buffer true,\n    // but we are going to filter by initiatorType _if we are wrapping fetch and xhr as the wrapped functions\n    // will deal with those.\n    // so we have a block which captures requests from before fetch/xhr is wrapped\n    // these are marked `isInitial` so playback can display them differently if needed\n    // they will never have method/status/headers/body because they are pre-wrapping that provides that\n    if (options.recordInitialRequests) {\n        const initialPerformanceEntries = win.performance\n            .getEntries()\n            .filter(\n                (entry): entry is ObservedPerformanceEntry =>\n                    isNavigationTiming(entry) ||\n                    (isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType as InitiatorType))\n            )\n        cb({\n            requests: initialPerformanceEntries.flatMap((entry) =>\n                prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {}, isInitial: true })\n            ),\n            isInitial: true,\n        })\n    }\n    const observer = new win.PerformanceObserver((entries) => {\n        // if recordBody or recordHeaders is true then we don't want to record fetch or xhr here\n        // as the wrapped functions will do that. Otherwise, this filter becomes a noop\n        // because we do want to record them here\n        const wrappedInitiatorFilter = (entry: ObservedPerformanceEntry) =>\n            options.recordBody || options.recordHeaders\n                ? entry.initiatorType !== 'xmlhttprequest' && entry.initiatorType !== 'fetch'\n                : true\n\n        const performanceEntries = entries.getEntries().filter(\n            (entry): entry is ObservedPerformanceEntry =>\n                isNavigationTiming(entry) ||\n                (isResourceTiming(entry) &&\n                    options.initiatorTypes.includes(entry.initiatorType as InitiatorType) &&\n                    // TODO if we are _only_ capturing timing we don't want to filter initiator here\n                    wrappedInitiatorFilter(entry))\n        )\n\n        cb({\n            requests: performanceEntries.flatMap((entry) =>\n                prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {} })\n            ),\n        })\n    })\n    // compat checked earlier\n    const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) =>\n        options.performanceEntryTypeToObserve.includes(x)\n    )\n    // initial records are gathered above, so we don't need to observe and buffer each type separately\n    observer.observe({ entryTypes })\n    return () => {\n        observer.disconnect()\n    }\n}\n\nfunction shouldRecordHeaders(type: 'request' | 'response', recordHeaders: NetworkRecordOptions['recordHeaders']) {\n    return !!recordHeaders && (isBoolean(recordHeaders) || recordHeaders[type])\n}\n\nfunction isRequest(value: unknown): value is Request {\n    if (typeof Request === 'undefined') {\n        return false\n    }\n    if (value instanceof Request) {\n        return true\n    }\n    try {\n        return Object.prototype.toString.call(value) === '[object Request]'\n    } catch {\n        return false\n    }\n}\n\n// binary/asset bodies are large and useless for replay debugging (and capturing an image body\n// duplicates what the recording already shows), so we never record them even when recordBody is on\nexport const NEVER_RECORD_BODY_CONTENT_TYPES = [\n    'image/',\n    'video/',\n    'audio/',\n    'font/',\n    'application/octet-stream',\n    'application/pdf',\n    'application/zip',\n    'application/wasm',\n]\n\nexport function shouldRecordBody({\n    type,\n    recordBody,\n    headers,\n    url,\n}: {\n    type: 'request' | 'response'\n    headers: Headers\n    url: string | URL | RequestInfo\n    recordBody: NetworkRecordOptions['recordBody']\n}) {\n    function matchesContentType(contentTypes: string[]) {\n        const contentTypeHeader = Object.keys(headers).find((key) => key.toLowerCase() === 'content-type')\n        const contentType = contentTypeHeader && headers[contentTypeHeader]\n        return contentTypes.some((ct) => contentType?.toLowerCase().includes(ct))\n    }\n\n    /**\n     * particularly in canvas applications we see many requests to blob URLs\n     * e.g. blob:https://video_url\n     * these blob/object URLs are local to the browser, we can never capture that body\n     * so we can just return false here\n     */\n    function isBlobURL(url: string | URL | RequestInfo) {\n        try {\n            if (typeof url === 'string') {\n                return url.startsWith('blob:')\n            }\n            if (url instanceof URL) {\n                return url.protocol === 'blob:'\n            }\n            if (isRequest(url)) {\n                return isBlobURL(url.url)\n            }\n            return false\n        } catch {\n            return false\n        }\n    }\n    if (!recordBody) return false\n    if (isBlobURL(url)) return false\n    // never record binary/asset bodies, regardless of the recordBody setting\n    if (matchesContentType(NEVER_RECORD_BODY_CONTENT_TYPES)) return false\n    if (isBoolean(recordBody)) return true\n    if (isArray(recordBody)) return matchesContentType(recordBody)\n    const recordBodyType = recordBody[type]\n    if (isBoolean(recordBodyType)) return recordBodyType\n    return matchesContentType(recordBodyType)\n}\n\nasync function getRequestPerformanceEntry(\n    win: IWindow,\n    initiatorType: string,\n    url: string,\n    start?: number,\n    end?: number,\n    attempt = 0\n): Promise<PerformanceResourceTiming | null> {\n    if (attempt > 10) {\n        logger.warn('Failed to get performance entry for request', { url, initiatorType })\n        return null\n    }\n    const urlPerformanceEntries = win.performance.getEntriesByName(url) as PerformanceResourceTiming[]\n    const performanceEntry = findLast(\n        urlPerformanceEntries,\n        (entry) =>\n            isResourceTiming(entry) &&\n            entry.initiatorType === initiatorType &&\n            (isUndefined(start) || entry.startTime >= start) &&\n            (isUndefined(end) || entry.startTime <= end)\n    )\n    if (!performanceEntry) {\n        await new Promise((resolve) => setTimeout(resolve, 50 * attempt))\n        return getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt + 1)\n    }\n    return performanceEntry\n}\n\n/**\n * According to MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response\n * xhr response is typed as any but can be an ArrayBuffer, a Blob, a Document, a JavaScript object,\n * or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.\n *\n * XHR request body is Document | XMLHttpRequestBodyInit | null | undefined\n */\nfunction _tryReadXHRBody({\n    body,\n    options,\n    url,\n}: {\n    body: Document | XMLHttpRequestBodyInit | any | null | undefined\n    options: NetworkRecordOptions\n    url: string | URL | RequestInfo\n}): string | null {\n    if (isNullish(body)) {\n        return null\n    }\n\n    const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n    if (isHostDenied) {\n        return hostname + ' is in deny list'\n    }\n\n    if (isString(body)) {\n        return body\n    }\n\n    if (isDocument(body)) {\n        return body.textContent\n    }\n\n    if (isFormData(body)) {\n        return formDataToQuery(body)\n    }\n\n    if (isObject(body)) {\n        try {\n            return JSON.stringify(body)\n        } catch {\n            return '[SessionReplay] Failed to stringify response object'\n        }\n    }\n\n    return '[SessionReplay] Cannot read body of type ' + toString.call(body)\n}\n\nfunction initXhrObserver(cb: networkCallback, win: IWindow, options: Required<NetworkRecordOptions>): listenerHandler {\n    if (!options.initiatorTypes.includes('xmlhttprequest')) {\n        return () => {\n            //\n        }\n    }\n    const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n    const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n    const restorePatch = patch(\n        win.XMLHttpRequest.prototype,\n        'open',\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        (originalOpen: typeof XMLHttpRequest.prototype.open) => {\n            return function (\n                method: string,\n                url: string | URL,\n                async = true,\n                username?: string | null,\n                password?: string | null\n            ) {\n                // because this function is returned in its actual context `this` _is_ an XMLHttpRequest\n                // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                // @ts-ignore\n                const xhr = this as XMLHttpRequest\n\n                // All of the capture instrumentation below runs _before_ we delegate to the original\n                // `open`. If any of it throws (e.g. `new Request(url)` rejecting a URL/method the host\n                // application would have handled), we must not let that exception escape into the host's\n                // `xhr.open()` call and misattribute a failure to session replay. Wrap it so that if\n                // instrumentation fails we degrade gracefully and the original request still proceeds.\n                try {\n                    // check IE earlier than this, we only initialize if Request is present\n                    const req = new Request(url)\n                    const networkRequest: Partial<CapturedNetworkRequest> = {}\n                    let start: number | undefined\n                    let end: number | undefined\n\n                    const requestHeaders: Headers = {}\n                    const originalSetRequestHeader = xhr.setRequestHeader.bind(xhr)\n                    xhr.setRequestHeader = (header: string, value: string) => {\n                        requestHeaders[header] = value\n                        return originalSetRequestHeader(header, value)\n                    }\n                    if (recordRequestHeaders) {\n                        networkRequest.requestHeaders = requestHeaders\n                    }\n\n                    const originalSend = xhr.send.bind(xhr)\n                    xhr.send = (body) => {\n                        if (\n                            shouldRecordBody({\n                                type: 'request',\n                                headers: requestHeaders,\n                                url,\n                                recordBody: options.recordBody,\n                            })\n                        ) {\n                            networkRequest.requestBody = _tryReadXHRBody({ body, options, url })\n                        }\n                        start = win.performance.now()\n                        return originalSend(body)\n                    }\n\n                    // Cleanup function to remove all event listeners and prevent memory leaks\n                    const cleanup = () => {\n                        xhr.removeEventListener('readystatechange', readyStateListener)\n                        xhr.removeEventListener('error', cleanup)\n                        xhr.removeEventListener('abort', cleanup)\n                        xhr.removeEventListener('timeout', cleanup)\n                    }\n\n                    const readyStateListener = () => {\n                        if (xhr.readyState !== xhr.DONE) {\n                            return\n                        }\n\n                        // Clean up all listeners immediately when done to prevent memory leaks\n                        cleanup()\n\n                        end = win.performance.now()\n                        const responseHeaders: Headers = {}\n                        const rawHeaders = xhr.getAllResponseHeaders()\n                        const headers = rawHeaders.trim().split(/[\\r\\n]+/)\n                        headers.forEach((line) => {\n                            const parts = line.split(': ')\n                            const header = parts.shift()\n                            const value = parts.join(': ')\n                            if (header) {\n                                responseHeaders[header] = value\n                            }\n                        })\n                        if (recordResponseHeaders) {\n                            networkRequest.responseHeaders = responseHeaders\n                        }\n                        if (\n                            shouldRecordBody({\n                                type: 'response',\n                                headers: responseHeaders,\n                                url,\n                                recordBody: options.recordBody,\n                            })\n                        ) {\n                            networkRequest.responseBody = _tryReadXHRBody({ body: xhr.response, options, url })\n                        }\n                        getRequestPerformanceEntry(win, 'xmlhttprequest', req.url, start, end)\n                            .then((entry) => {\n                                const requests = prepareRequest({\n                                    entry,\n                                    method: method,\n                                    status: xhr?.status,\n                                    networkRequest,\n                                    start,\n                                    end,\n                                    url: url.toString(),\n                                    initiatorType: 'xmlhttprequest',\n                                })\n                                cb({ requests })\n                            })\n                            .catch(() => {\n                                //\n                            })\n                    }\n\n                    // This is very tricky code, and making it passive won't bring many performance benefits,\n                    // so let's ignore the rule here.\n                    // eslint-disable-next-line posthog-js/no-add-event-listener\n                    xhr.addEventListener('readystatechange', readyStateListener)\n                    // Also clean up on error, abort, and timeout to prevent memory leaks\n                    // eslint-disable-next-line posthog-js/no-add-event-listener\n                    xhr.addEventListener('error', cleanup)\n                    // eslint-disable-next-line posthog-js/no-add-event-listener\n                    xhr.addEventListener('abort', cleanup)\n                    // eslint-disable-next-line posthog-js/no-add-event-listener\n                    xhr.addEventListener('timeout', cleanup)\n                } catch (e) {\n                    logger.error('Failed to instrument XHR for network capture', e)\n                }\n\n                originalOpen.call(xhr, method, url.toString(), async, username, password)\n            }\n        }\n    )\n    return () => {\n        restorePatch()\n    }\n}\n\n/**\n *  Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n *  NB PerformanceNavigationTiming extends PerformanceResourceTiming\n *  Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry | null): event is PerformanceResourceTiming =>\n    !isNull(event) && (event.entryType === 'navigation' || event.entryType === 'resource')\n\nfunction prepareRequest({\n    entry,\n    method,\n    status,\n    networkRequest,\n    isInitial,\n    start,\n    end,\n    url,\n    initiatorType,\n}: {\n    entry: PerformanceResourceTiming | null\n    method: string | undefined\n    status: number | undefined\n    networkRequest: Partial<CapturedNetworkRequest>\n    isInitial?: boolean\n    start?: number\n    end?: number\n    // if there is no performance observer entry, we still need to know the url\n    url?: string\n    // if there is no performance observer entry, we can provide the initiatorType\n    initiatorType?: string\n}): CapturedNetworkRequest[] {\n    start = entry ? entry.startTime : start\n    end = entry ? entry.responseEnd : end\n\n    // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n    // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n    // can't start observer if performance.now() is not available\n    // eslint-disable-next-line compat/compat\n    const timeOrigin = Math.floor(Date.now() - performance.now())\n    // clickhouse can't ingest timestamps that are floats\n    // (in this case representing fractions of a millisecond we don't care about anyway)\n    // use timeOrigin if we really can't gather a start time\n    const timestamp = Math.floor(timeOrigin + (start || 0))\n\n    const entryJSON = entry ? entry.toJSON() : { name: url }\n\n    const requests: CapturedNetworkRequest[] = [\n        {\n            ...entryJSON,\n            startTime: isUndefined(start) ? undefined : Math.round(start),\n            endTime: isUndefined(end) ? undefined : Math.round(end),\n            timeOrigin,\n            timestamp,\n            method: method,\n            initiatorType: initiatorType ? initiatorType : entry ? (entry.initiatorType as InitiatorType) : undefined,\n            status,\n            requestHeaders: networkRequest.requestHeaders,\n            requestBody: networkRequest.requestBody,\n            responseHeaders: networkRequest.responseHeaders,\n            responseBody: networkRequest.responseBody,\n            isInitial,\n        },\n    ]\n\n    if (exposesServerTiming(entry)) {\n        for (const timing of entry.serverTiming || []) {\n            requests.push({\n                timeOrigin,\n                timestamp,\n                startTime: Math.round(entry.startTime),\n                name: timing.name,\n                duration: timing.duration,\n                // the spec has a closed list of possible types\n                // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n                // but, we need to know this was a server timing so that we know to\n                // match it to the appropriate navigation or resource timing\n                // that matching will have to be on timestamp and $current_url\n                entryType: 'serverTiming',\n            })\n        }\n    }\n\n    return requests\n}\n\nconst contentTypePrefixDenyList = ['video/', 'audio/']\n\nfunction _checkForCannotReadResponseBody({\n    r,\n    options,\n    url,\n}: {\n    r: Response\n    options: NetworkRecordOptions\n    url: string | URL | RequestInfo\n}): string | null {\n    if (r.headers.get('Transfer-Encoding') === 'chunked') {\n        return 'Chunked Transfer-Encoding is not supported'\n    }\n\n    // `get` and `has` are case-insensitive\n    // but return the header value with the casing that was supplied\n    const contentType = r.headers.get('Content-Type')?.toLowerCase()\n    const contentTypeIsDenied = contentTypePrefixDenyList.some((prefix) => contentType?.startsWith(prefix))\n    if (contentType && contentTypeIsDenied) {\n        return `Content-Type ${contentType} is not supported`\n    }\n\n    const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n    if (isHostDenied) {\n        return hostname + ' is in deny list'\n    }\n\n    return null\n}\n\nfunction isReadableStreamBody(body: unknown): body is ReadableStream<Uint8Array> {\n    return isObject(body) && isFunction(body.getReader) && isFunction(body.tee)\n}\n\n// reading a body must never hold up the page's request for long, so we cap every read attempt\nconst BODY_READ_TIMEOUT_MS = 500\nconst BODY_READ_TIMEOUT_MESSAGE = '[SessionReplay] Timeout while trying to read body'\nconst BODY_READ_FAILED_MESSAGE = '[SessionReplay] Failed to read body'\n\nfunction bodyReadFailedMessage(reason: unknown): string {\n    return `${BODY_READ_FAILED_MESSAGE}: ${reason}`\n}\n\nfunction bodyTooLargeMessage(limitBytes: number): string {\n    return `[SessionReplay] Body too large to record (> ${limitBytes} bytes)`\n}\n\n// when the body declares a content-length over the limit we can skip reading it entirely.\n// this trusts content-length the same way config.ts enforcePayloadSizeLimit does.\n// known accepted risk: for a compressed response content-length is the compressed size while the\n// streaming reader counts decoded bytes, so a body that is over the limit compressed but under it\n// decoded is dropped to the placeholder rather than recorded. it never breaks the page, so we accept it.\nexport function _contentLengthExceedsLimit(r: Request | Response, limitBytes: number): boolean {\n    try {\n        const headerValue = r.headers?.get?.('content-length')\n        if (!headerValue) {\n            return false\n        }\n        const contentLength = parseInt(headerValue, 10)\n        return Number.isFinite(contentLength) && contentLength > limitBytes\n    } catch {\n        return false\n    }\n}\n\nexport function _readBody(r: Request | Response, options: NetworkRecordOptions): Promise<string> {\n    if (!options.streamNetworkBody) {\n        return _tryReadBody(r)\n    }\n    const limitBytes = effectivePayloadLimitBytes(options)\n    // skip the read for bodies the headers already tell us are over the limit\n    if (_contentLengthExceedsLimit(r, limitBytes)) {\n        return Promise.resolve(bodyTooLargeMessage(limitBytes))\n    }\n    return _tryReadBodyStreaming(r, limitBytes)\n}\n\nfunction _tryReadBody(r: Request | Response): Promise<string> {\n    // there are now already multiple places where we're using Promise...\n    // eslint-disable-next-line compat/compat\n    return new Promise((resolve) => {\n        const timeout = setTimeout(() => resolve(BODY_READ_TIMEOUT_MESSAGE), BODY_READ_TIMEOUT_MS)\n        try {\n            r.clone()\n                .text()\n                .then(\n                    (txt) => resolve(txt),\n                    (reason) => resolve(bodyReadFailedMessage(reason))\n                )\n                .finally(() => clearTimeout(timeout))\n        } catch {\n            clearTimeout(timeout)\n            resolve(BODY_READ_FAILED_MESSAGE)\n        }\n    })\n}\n\nfunction concatChunks(chunks: Uint8Array[], totalBytes: number): Uint8Array {\n    const merged = new Uint8Array(totalBytes)\n    let offset = 0\n    for (const chunk of chunks) {\n        merged.set(chunk, offset)\n        offset += chunk.byteLength\n    }\n    return merged\n}\n\n// Reads a clone of the body chunk by chunk, stopping as soon as the running total exceeds the\n// limit, so a very large body is never fully buffered. Like _tryReadBody it only ever reads a\n// clone (never the stream the page consumes) and is guaranteed to resolve, never reject.\nexport function _tryReadBodyStreaming(r: Request | Response, limitBytes: number): Promise<string> {\n    // eslint-disable-next-line compat/compat\n    return new Promise((resolve) => {\n        let settled = false\n        let reader: ReadableStreamDefaultReader<Uint8Array> | undefined\n\n        function cancel(): void {\n            try {\n                void reader?.cancel()\n            } catch {\n                // the reader may already be released; nothing to clean up\n            }\n        }\n\n        // resolving always releases the reader, so a slow/hung stream stops being pulled (and stops\n        // buffering the clone) the moment we settle — whether via success, the cap, an error, or the timeout\n        function done(value: string): void {\n            if (settled) {\n                return\n            }\n            settled = true\n            clearTimeout(timeout)\n            cancel()\n            resolve(value)\n        }\n\n        const timeout = setTimeout(() => done(BODY_READ_TIMEOUT_MESSAGE), BODY_READ_TIMEOUT_MS)\n\n        let clone: Request | Response\n        try {\n            clone = r.clone()\n        } catch {\n            done(BODY_READ_FAILED_MESSAGE)\n            return\n        }\n\n        const body = clone.body\n        // no readable stream (or no TextDecoder) available — fall back to the buffered read of the clone\n        if (!isReadableStreamBody(body) || typeof TextDecoder === 'undefined') {\n            try {\n                clone.text().then(\n                    (txt) => done(txt),\n                    (reason) => done(bodyReadFailedMessage(reason))\n                )\n            } catch {\n                done(BODY_READ_FAILED_MESSAGE)\n            }\n            return\n        }\n\n        try {\n            reader = body.getReader()\n        } catch {\n            done(BODY_READ_FAILED_MESSAGE)\n            return\n        }\n\n        const chunks: Uint8Array[] = []\n        let received = 0\n\n        function pump(): void {\n            reader!.read().then(\n                ({ done: streamDone, value }) => {\n                    // already resolved (e.g. the timeout fired) — stop reading and release the stream\n                    if (settled) {\n                        cancel()\n                        return\n                    }\n\n                    if (streamDone) {\n                        done(new TextDecoder().decode(concatChunks(chunks, received)))\n                        return\n                    }\n\n                    if (value) {\n                        if (received + value.byteLength > limitBytes) {\n                            done(bodyTooLargeMessage(limitBytes))\n                            return\n                        }\n                        received += value.byteLength\n                        chunks.push(value)\n                    }\n\n                    pump()\n                },\n                (reason) => done(bodyReadFailedMessage(reason))\n            )\n        }\n\n        pump()\n    })\n}\n\nasync function _tryReadRequestBody({\n    r,\n    options,\n    url,\n}: {\n    r: Request\n    options: NetworkRecordOptions\n    url: string | URL | RequestInfo\n}): Promise<string> {\n    const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n    if (isHostDenied) {\n        return Promise.resolve(hostname + ' is in deny list')\n    }\n\n    return _readBody(r, options)\n}\n\nasync function _tryReadResponseBody({\n    r,\n    options,\n    url,\n}: {\n    r: Response\n    options: NetworkRecordOptions\n    url: string | URL | RequestInfo\n}): Promise<string> {\n    const cannotReadBodyReason: string | null = _checkForCannotReadResponseBody({ r, options, url })\n    if (!isNull(cannotReadBodyReason)) {\n        return Promise.resolve(cannotReadBodyReason)\n    }\n\n    return _readBody(r, options)\n}\n\nfunction initFetchObserver(\n    cb: networkCallback,\n    win: IWindow,\n    options: Required<NetworkRecordOptions>\n): listenerHandler {\n    if (!options.initiatorTypes.includes('fetch')) {\n        return () => {\n            //\n        }\n    }\n    const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n    const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    const restorePatch = patch(win, 'fetch', (originalFetch: typeof fetch) => {\n        return async function (url: URL | RequestInfo, init?: RequestInit | undefined) {\n            // Constructing the capture Request happens _before_ we delegate to the original fetch, so\n            // if it throws (e.g. a URL/method the host application would have handled) we must not let\n            // that exception escape and misattribute a failure to session replay. Degrade gracefully and\n            // let the original request still proceed.\n            let req: Request\n            try {\n                // check IE earlier than this, we only initialize if Request is present\n                req = new Request(url, init)\n            } catch (e) {\n                logger.error('Failed to instrument fetch for network capture', e)\n                return originalFetch(url, init)\n            }\n            let res: Response | undefined\n            const networkRequest: Partial<CapturedNetworkRequest> = {}\n            let start: number | undefined\n            let end: number | undefined\n\n            try {\n                // Recording the request headers/body must never prevent the host's fetch from running,\n                // so failures here are swallowed and we fall through to the original request below.\n                try {\n                    const requestHeaders: Headers = {}\n                    req.headers.forEach((value: string, header: string | number) => {\n                        requestHeaders[header] = value\n                    })\n                    if (recordRequestHeaders) {\n                        networkRequest.requestHeaders = requestHeaders\n                    }\n                    // Check the caller-supplied body, not req.body: Request normalizes all non-null bodies\n                    // to a ReadableStream, but only an original ReadableStream would be locked by req.clone().text().\n                    const requestBodyIsReadableStream = isReadableStreamBody(init?.body)\n                    if (\n                        !requestBodyIsReadableStream &&\n                        shouldRecordBody({\n                            type: 'request',\n                            headers: requestHeaders,\n                            url,\n                            recordBody: options.recordBody,\n                        })\n                    ) {\n                        networkRequest.requestBody = await _tryReadRequestBody({ r: req, options, url })\n                    }\n                } catch (e) {\n                    logger.error('Failed to record fetch request for network capture', e)\n                }\n\n                start = win.performance.now()\n                // Use `req` for recording metadata/body only. For fetch(url, init), do not pass this internally-created\n                // Request downstream: it exposes request.body as a ReadableStream, and wrappers that forward that body\n                // can trigger Safari's \"ReadableStream uploading is not supported\" error. For fetch(Request), we must\n                // pass the cloned Request because constructing `req` may consume the original Request body.\n                res = isRequest(url) ? await originalFetch(req) : await originalFetch(url, init)\n                end = win.performance.now()\n\n                const responseHeaders: Headers = {}\n                res.headers.forEach((value: string, header: string | number) => {\n                    responseHeaders[header] = value\n                })\n                if (recordResponseHeaders) {\n                    networkRequest.responseHeaders = responseHeaders\n                }\n                if (\n                    shouldRecordBody({\n                        type: 'response',\n                        headers: responseHeaders,\n                        url,\n                        recordBody: options.recordBody,\n                    })\n                ) {\n                    networkRequest.responseBody = await _tryReadResponseBody({ r: res, options, url })\n                }\n\n                return res\n            } finally {\n                getRequestPerformanceEntry(win, 'fetch', req.url, start, end)\n                    .then((entry) => {\n                        const requests = prepareRequest({\n                            entry,\n                            method: req.method,\n                            status: res?.status,\n                            networkRequest,\n                            start,\n                            end,\n                            url: req.url,\n                            initiatorType: 'fetch',\n                        })\n                        cb({ requests })\n                    })\n                    .catch(() => {\n                        //\n                    })\n            }\n        }\n    })\n    return () => {\n        restorePatch()\n    }\n}\n\nlet initialisedHandler: listenerHandler | null = null\n\nfunction initNetworkObserver(\n    callback: networkCallback,\n    win: IWindow, // top window or in an iframe\n    options: NetworkRecordOptions\n): listenerHandler {\n    if (!('performance' in win)) {\n        return () => {\n            //\n        }\n    }\n\n    if (initialisedHandler) {\n        logger.warn('Network observer already initialised, doing nothing')\n        return () => {\n            // the first caller should already have this handler and will be responsible for teardown\n        }\n    }\n\n    const networkOptions = (\n        options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions\n    ) as Required<NetworkRecordOptions>\n\n    const cb: networkCallback = (data) => {\n        const requests: CapturedNetworkRequest[] = []\n        data.requests.forEach((request) => {\n            const maskedRequest = networkOptions.maskRequestFn(request)\n            if (maskedRequest) {\n                requests.push(maskedRequest)\n            }\n        })\n\n        if (requests.length > 0) {\n            callback({ ...data, requests })\n        }\n    }\n    const performanceObserver = initPerformanceObserver(cb, win, networkOptions)\n\n    // only wrap fetch and xhr if headers or body are being recorded\n    let xhrObserver: listenerHandler = () => {}\n    let fetchObserver: listenerHandler = () => {}\n    if (networkOptions.recordHeaders || networkOptions.recordBody) {\n        xhrObserver = initXhrObserver(cb, win, networkOptions)\n        fetchObserver = initFetchObserver(cb, win, networkOptions)\n    }\n\n    initialisedHandler = () => {\n        performanceObserver()\n        xhrObserver()\n        fetchObserver()\n        initialisedHandler = null\n    }\n    return initialisedHandler\n}\n\n// use the plugin name so that when this functionality is adopted into rrweb\n// we can remove this plugin and use the core functionality with the same data\nexport const NETWORK_PLUGIN_NAME = 'rrweb/network@1'\n\n// TODO how should this be typed?\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nexport const getRecordNetworkPlugin: (options?: NetworkRecordOptions) => RecordPlugin = (options) => {\n    return {\n        name: NETWORK_PLUGIN_NAME,\n        observer: initNetworkObserver,\n        options: options,\n    }\n}\n\n// rrweb/networ@1 ends\n","// Type definitions copied from the in-repo @posthog/rrweb-types and @posthog/rrweb-snapshot packages\n// (a fork of upstream @rrweb/types and rrweb-snapshot, both MIT licensed: https://github.com/rrweb-io/rrweb)\n//\n// These types are inlined here to avoid requiring users to install peer dependencies\n// solely for TypeScript type information.\n\n// ===== Types from rrweb-snapshot =====\n// These are needed by the rrweb types\n\nexport type DataURLOptions = Partial<{\n    type: string\n    quality: number\n}>\n\nexport interface INode extends Node {\n    __sn: serializedNodeWithId\n}\n\nexport interface IMirror<TNode> {\n    getId(n: TNode | undefined | null): number\n    getNode(id: number): TNode | null\n    getIds(): number[]\n    getMeta(n: TNode): serializedNodeWithId | null\n    removeNodeFromMap(n: TNode): void\n    has(id: number): boolean\n    hasNode(node: TNode): boolean\n    add(n: TNode, meta: serializedNodeWithId): void\n    replace(id: number, n: TNode): void\n    reset(): void\n}\n\nexport declare class Mirror implements IMirror<Node> {\n    // eslint-disable-next-line @typescript-eslint/naming-convention\n    private idNodeMap\n    // eslint-disable-next-line @typescript-eslint/naming-convention\n    private nodeMetaMap\n    getId(n: Node | undefined | null): number\n    getNode(id: number): Node | null\n    getIds(): number[]\n    getMeta(n: Node): serializedNodeWithId | null\n    removeNodeFromMap(n: Node): void\n    has(id: number): boolean\n    hasNode(node: Node): boolean\n    add(n: Node, meta: serializedNodeWithId): void\n    replace(id: number, n: Node): void\n    reset(): void\n}\n\nexport type attributes = {\n    [key: string]: string | number | true | null\n}\n\nexport const NodeType = {\n    Document: 0,\n    DocumentType: 1,\n    Element: 2,\n    Text: 3,\n    CDATA: 4,\n    Comment: 5,\n} as const\nexport type NodeType = (typeof NodeType)[keyof typeof NodeType]\n\nexport type documentNode = {\n    type: typeof NodeType.Document\n    childNodes: serializedNodeWithId[]\n    compatMode?: string\n}\n\nexport type documentTypeNode = {\n    type: typeof NodeType.DocumentType\n    name: string\n    publicId: string\n    systemId: string\n}\n\nexport type elementNode = {\n    type: typeof NodeType.Element\n    tagName: string\n    attributes: attributes\n    childNodes: serializedNodeWithId[]\n    isSVG?: true\n    needBlock?: boolean\n    isCustom?: true\n}\n\nexport type textNode = {\n    type: typeof NodeType.Text\n    textContent: string\n    isStyle?: true\n}\n\nexport type cdataNode = {\n    type: typeof NodeType.CDATA\n    textContent: ''\n}\n\nexport type commentNode = {\n    type: typeof NodeType.Comment\n    textContent: string\n}\n\nexport type serializedNode = (documentNode | documentTypeNode | elementNode | textNode | cdataNode | commentNode) & {\n    rootId?: number\n    isShadowHost?: boolean\n    isShadow?: boolean\n}\n\nexport type serializedNodeWithId = serializedNode & {\n    id: number\n}\n\n// ===== Types from rrweb-types =====\n\nexport type blockClass = string | RegExp\n\nexport type maskTextClass = string | RegExp\n\nexport type IWindow = Window & typeof globalThis\n\nexport type listenerHandler = () => void\n\nexport type KeepIframeSrcFn = (src: string) => boolean\n\nexport type PackFn = (event: eventWithTime) => string\n\nexport const EventType = {\n    DomContentLoaded: 0,\n    Load: 1,\n    FullSnapshot: 2,\n    IncrementalSnapshot: 3,\n    Meta: 4,\n    Custom: 5,\n    Plugin: 6,\n} as const\nexport type EventType = (typeof EventType)[keyof typeof EventType]\n\nexport const IncrementalSource = {\n    Mutation: 0,\n    MouseMove: 1,\n    MouseInteraction: 2,\n    Scroll: 3,\n    ViewportResize: 4,\n    Input: 5,\n    TouchMove: 6,\n    MediaInteraction: 7,\n    StyleSheetRule: 8,\n    CanvasMutation: 9,\n    Font: 10,\n    Log: 11,\n    Drag: 12,\n    StyleDeclaration: 13,\n    Selection: 14,\n    AdoptedStyleSheet: 15,\n    CustomElement: 16,\n} as const\nexport type IncrementalSource = (typeof IncrementalSource)[keyof typeof IncrementalSource]\n\nexport type domContentLoadedEvent = {\n    type: typeof EventType.DomContentLoaded\n    data: unknown\n}\n\nexport type loadedEvent = {\n    type: typeof EventType.Load\n    data: unknown\n}\n\nexport type fullSnapshotEvent = {\n    type: typeof EventType.FullSnapshot\n    data: {\n        node: serializedNodeWithId\n        initialOffset: {\n            top: number\n            left: number\n        }\n    }\n}\n\nexport type metaEvent = {\n    type: typeof EventType.Meta\n    data: {\n        href: string\n        width: number\n        height: number\n    }\n}\n\nexport type customEvent<T = unknown> = {\n    type: typeof EventType.Custom\n    data: {\n        tag: string\n        payload: T\n    }\n}\n\nexport type pluginEvent<T = unknown> = {\n    type: typeof EventType.Plugin\n    data: {\n        plugin: string\n        payload: T\n    }\n}\n\nexport type styleOMValue = {\n    [key: string]: styleValueWithPriority | string | false\n}\n\nexport type styleValueWithPriority = [string, string]\n\nexport type textMutation = {\n    id: number\n    value: string | null\n}\n\nexport type attributeMutation = {\n    id: number\n    attributes: {\n        [key: string]: string | styleOMValue | null\n    }\n}\n\nexport type removedNodeMutation = {\n    parentId: number\n    id: number\n    isShadow?: boolean\n}\n\nexport type addedNodeMutation = {\n    parentId: number\n    previousId?: number | null\n    nextId: number | null\n    node: serializedNodeWithId\n}\n\nexport type mutationCallbackParam = {\n    texts: textMutation[]\n    attributes: attributeMutation[]\n    removes: removedNodeMutation[]\n    adds: addedNodeMutation[]\n    isAttachIframe?: true\n}\n\nexport type mutationData = {\n    source: typeof IncrementalSource.Mutation\n} & mutationCallbackParam\n\nexport type mousePosition = {\n    x: number\n    y: number\n    id: number\n    timeOffset: number\n}\n\nexport const MouseInteractions = {\n    MouseUp: 0,\n    MouseDown: 1,\n    Click: 2,\n    ContextMenu: 3,\n    DblClick: 4,\n    Focus: 5,\n    Blur: 6,\n    TouchStart: 7,\n    TouchMove_Departed: 8,\n    TouchEnd: 9,\n    TouchCancel: 10,\n} as const\nexport type MouseInteractions = (typeof MouseInteractions)[keyof typeof MouseInteractions]\n\nexport const PointerTypes = {\n    Mouse: 0,\n    Pen: 1,\n    Touch: 2,\n} as const\nexport type PointerTypes = (typeof PointerTypes)[keyof typeof PointerTypes]\n\ntype mouseInteractionParam = {\n    type: MouseInteractions\n    id: number\n    x?: number\n    y?: number\n    pointerType?: PointerTypes\n}\n\nexport type mouseInteractionData = {\n    source: typeof IncrementalSource.MouseInteraction\n} & mouseInteractionParam\n\nexport type mousemoveData = {\n    source: typeof IncrementalSource.MouseMove | typeof IncrementalSource.TouchMove | typeof IncrementalSource.Drag\n    positions: mousePosition[]\n}\n\nexport type scrollPosition = {\n    id: number\n    x: number\n    y: number\n}\n\nexport type scrollData = {\n    source: typeof IncrementalSource.Scroll\n} & scrollPosition\n\nexport type viewportResizeDimension = {\n    width: number\n    height: number\n}\n\nexport type viewportResizeData = {\n    source: typeof IncrementalSource.ViewportResize\n} & viewportResizeDimension\n\nexport type inputValue = {\n    text: string\n    isChecked: boolean\n    userTriggered?: boolean\n}\n\nexport type inputData = {\n    source: typeof IncrementalSource.Input\n    id: number\n} & inputValue\n\nexport const MediaInteractions = {\n    Play: 0,\n    Pause: 1,\n    Seeked: 2,\n    VolumeChange: 3,\n    RateChange: 4,\n} as const\nexport type MediaInteractions = (typeof MediaInteractions)[keyof typeof MediaInteractions]\n\nexport type mediaInteractionParam = {\n    type: MediaInteractions\n    id: number\n    currentTime?: number\n    volume?: number\n    muted?: boolean\n    loop?: boolean\n    playbackRate?: number\n}\n\nexport type mediaInteractionData = {\n    source: typeof IncrementalSource.MediaInteraction\n} & mediaInteractionParam\n\nexport type styleSheetAddRule = {\n    rule: string\n    index?: number | number[]\n}\n\nexport type styleSheetDeleteRule = {\n    index: number | number[]\n}\n\nexport type styleSheetRuleParam = {\n    id?: number\n    styleId?: number\n    removes?: styleSheetDeleteRule[]\n    adds?: styleSheetAddRule[]\n    replace?: string\n    replaceSync?: string\n}\n\nexport type styleSheetRuleData = {\n    source: typeof IncrementalSource.StyleSheetRule\n} & styleSheetRuleParam\n\nexport const CanvasContext = {\n    '2D': 0,\n    WebGL: 1,\n    WebGL2: 2,\n} as const\nexport type CanvasContext = (typeof CanvasContext)[keyof typeof CanvasContext]\n\nexport type canvasMutationCommand = {\n    property: string\n    args: Array<unknown>\n    setter?: true\n}\n\nexport type canvasMutationParam =\n    | {\n          id: number\n          type: CanvasContext\n          commands: canvasMutationCommand[]\n      }\n    | ({\n          id: number\n          type: CanvasContext\n      } & canvasMutationCommand)\n\nexport type canvasMutationData = {\n    source: typeof IncrementalSource.CanvasMutation\n} & canvasMutationParam\n\nexport type fontParam = {\n    family: string\n    fontSource: string\n    buffer: boolean\n    descriptors?: FontFaceDescriptors\n}\n\nexport type fontData = {\n    source: typeof IncrementalSource.Font\n} & fontParam\n\nexport type SelectionRange = {\n    start: number\n    startOffset: number\n    end: number\n    endOffset: number\n}\n\nexport type selectionParam = {\n    ranges: Array<SelectionRange>\n}\n\nexport type selectionData = {\n    source: typeof IncrementalSource.Selection\n} & selectionParam\n\nexport type styleDeclarationParam = {\n    id?: number\n    styleId?: number\n    index: number[]\n    set?: {\n        property: string\n        value: string | null\n        priority: string | undefined\n    }\n    remove?: {\n        property: string\n    }\n}\n\nexport type styleDeclarationData = {\n    source: typeof IncrementalSource.StyleDeclaration\n} & styleDeclarationParam\n\nexport type adoptedStyleSheetParam = {\n    id: number\n    styles?: {\n        styleId: number\n        rules: styleSheetAddRule[]\n    }[]\n    styleIds: number[]\n}\n\nexport type adoptedStyleSheetData = {\n    source: typeof IncrementalSource.AdoptedStyleSheet\n} & adoptedStyleSheetParam\n\nexport type customElementParam = {\n    define?: {\n        name: string\n    }\n}\n\nexport type customElementData = {\n    source: typeof IncrementalSource.CustomElement\n} & customElementParam\n\nexport type incrementalData =\n    | mutationData\n    | mousemoveData\n    | mouseInteractionData\n    | scrollData\n    | viewportResizeData\n    | inputData\n    | mediaInteractionData\n    | styleSheetRuleData\n    | canvasMutationData\n    | fontData\n    | selectionData\n    | styleDeclarationData\n    | adoptedStyleSheetData\n    | customElementData\n\nexport type incrementalSnapshotEvent = {\n    type: typeof EventType.IncrementalSnapshot\n    data: incrementalData\n}\n\nexport type eventWithoutTime =\n    | domContentLoadedEvent\n    | loadedEvent\n    | fullSnapshotEvent\n    | incrementalSnapshotEvent\n    | metaEvent\n    | customEvent\n    | pluginEvent\n\nexport type eventWithTime = eventWithoutTime & {\n    timestamp: number\n    delay?: number\n}\n\nexport type mutationCallBack = (m: mutationCallbackParam) => void\n\nexport type mousemoveCallBack = (\n    p: mousePosition[],\n    source: typeof IncrementalSource.MouseMove | typeof IncrementalSource.TouchMove | typeof IncrementalSource.Drag\n) => void\n\nexport type mouseInteractionCallBack = (d: mouseInteractionParam) => void\n\nexport type scrollCallback = (p: scrollPosition) => void\n\nexport type viewportResizeCallback = (d: viewportResizeDimension) => void\n\nexport type inputCallback = (v: inputValue & { id: number }) => void\n\nexport type mediaInteractionCallback = (p: mediaInteractionParam) => void\n\nexport type styleSheetRuleCallback = (s: styleSheetRuleParam) => void\n\nexport type styleDeclarationCallback = (s: styleDeclarationParam) => void\n\nexport type canvasMutationCallback = (p: canvasMutationParam) => void\n\nexport type fontCallback = (p: fontParam) => void\n\nexport type selectionCallback = (p: selectionParam) => void\n\nexport type customElementCallback = (c: customElementParam) => void\n\nexport type adoptedStyleSheetCallback = (a: adoptedStyleSheetParam) => void\n\nexport type hooksParam = {\n    mutation?: mutationCallBack\n    mousemove?: mousemoveCallBack\n    mouseInteraction?: mouseInteractionCallBack\n    scroll?: scrollCallback\n    viewportResize?: viewportResizeCallback\n    input?: inputCallback\n    mediaInteaction?: mediaInteractionCallback\n    styleSheetRule?: styleSheetRuleCallback\n    styleDeclaration?: styleDeclarationCallback\n    canvasMutation?: canvasMutationCallback\n    font?: fontCallback\n    selection?: selectionCallback\n    customElement?: customElementCallback\n}\n\nexport type SamplingStrategy = Partial<{\n    mousemove: boolean | number\n    mousemoveCallback: number\n    mouseInteraction: boolean | Record<string, boolean | undefined>\n    scroll: number\n    media: number\n    input: 'all' | 'last'\n    canvas: 'all' | number\n}>\n\nexport interface ICrossOriginIframeMirror {\n    getId(\n        iframe: HTMLIFrameElement,\n        remoteId: number,\n        parentToRemoteMap?: Map<number, number>,\n        remoteToParentMap?: Map<number, number>\n    ): number\n    getIds(iframe: HTMLIFrameElement, remoteId: number[]): number[]\n    getRemoteId(iframe: HTMLIFrameElement, parentId: number, map?: Map<number, number>): number\n    getRemoteIds(iframe: HTMLIFrameElement, parentId: number[]): number[]\n    reset(iframe?: HTMLIFrameElement): void\n}\n\nexport type RecordPlugin<TOptions = unknown> = {\n    name: string\n    observer?: (cb: (...args: Array<unknown>) => void, win: IWindow, options: TOptions) => listenerHandler\n    eventProcessor?: <TExtend>(event: eventWithTime) => eventWithTime & TExtend\n    getMirror?: (mirrors: {\n        nodeMirror: Mirror\n        crossOriginIframeMirror: ICrossOriginIframeMirror\n        crossOriginIframeStyleMirror: ICrossOriginIframeMirror\n    }) => void\n    options: TOptions\n}\n","import {\n    SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS,\n    SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS,\n    SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS,\n    SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n    SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n    SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX,\n    SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX,\n} from '../../../constants'\nimport { PostHog } from '../../../posthog-core'\nimport { FlagVariant, RemoteConfig, SessionRecordingPersistedConfig, SessionRecordingUrlTrigger } from '../../../types'\nimport { isNullish, isBoolean, isString, isObject, isUndefined } from '@posthog/core'\nimport { logger } from '../../../utils/logger'\nimport { getTargetingUrl } from '../../../utils/url-targeting-utils'\n\nexport const DISABLED = 'disabled'\nexport const SAMPLED = 'sampled'\nexport const ACTIVE = 'active'\nexport const BUFFERING = 'buffering'\nexport const PAUSED = 'paused'\nexport const LAZY_LOADING = 'lazy_loading'\nexport const AWAITING_CONFIG = 'awaiting_config'\nexport const MISSING_CONFIG = 'missing_config'\nexport const RRWEB_ERROR = 'rrweb_error'\n\nconst TRIGGER = 'trigger'\nexport const TRIGGER_ACTIVATED = TRIGGER + '_activated'\nexport const TRIGGER_PENDING = TRIGGER + '_pending'\nexport const TRIGGER_DISABLED = TRIGGER + '_' + DISABLED\n\nexport interface RecordingTriggersStatus {\n    get receivedFlags(): boolean\n    get isRecordingEnabled(): false | true | undefined\n    get isSampled(): false | true | null\n    get rrwebError(): boolean\n    get urlTriggerMatching(): URLTriggerMatching\n    get eventTriggerMatching(): EventTriggerMatching\n    get linkedFlagMatching(): LinkedFlagMatching\n    get sessionId(): string\n}\n\n/**\n * Extended interface for V2 trigger groups\n */\nexport interface RecordingTriggersStatusV2 extends RecordingTriggersStatus {\n    get triggerGroupMatchers(): TriggerGroupMatching[]\n    get triggerGroupSamplingResults(): Map<string, boolean> // group id -> sampled decision\n    get minimumDuration(): number | null\n}\n\nexport type TriggerType = 'url' | 'event'\n/* \ntriggers can have one of three statuses:\n * - trigger_activated: the trigger met conditions to start recording\n * - trigger_pending: the trigger is present, but the conditions are not yet met\n * - trigger_disabled: the trigger is not present\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst triggerStatuses = [TRIGGER_ACTIVATED, TRIGGER_PENDING, TRIGGER_DISABLED] as const\nexport type TriggerStatus = (typeof triggerStatuses)[number]\n\nfunction persistedTriggerStatus(\n    instance: PostHog | undefined,\n    triggerCount: number,\n    groupId: string | undefined,\n    groupPrefix: string,\n    fallbackPersistenceKey: string,\n    sessionId: string\n): TriggerStatus {\n    if (triggerCount === 0) {\n        return TRIGGER_DISABLED\n    }\n\n    // V2: Use per-group persistence key if groupId is provided\n    const persistenceKey = groupId ? groupPrefix + groupId : fallbackPersistenceKey\n    const currentTriggerSession = instance?.get_property(persistenceKey)\n    return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING\n}\n\n/**\n * Session recording starts in buffering mode while waiting for \"flags response\".\n * Once the response is received, it might be disabled, active or sampled.\n * When \"sampled\" that means a sample rate is set, and the last time the session ID rotated\n * the sample rate determined this session should be sent to the server.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst sessionRecordingStatuses = [\n    DISABLED,\n    SAMPLED,\n    ACTIVE,\n    BUFFERING,\n    PAUSED,\n    LAZY_LOADING,\n    AWAITING_CONFIG,\n    MISSING_CONFIG,\n    RRWEB_ERROR,\n] as const\nexport type SessionRecordingStatus = (typeof sessionRecordingStatuses)[number]\n\n// while we have both lazy and eager loaded replay we might get either type of config\ntype ReplayConfigType = RemoteConfig | SessionRecordingPersistedConfig\n\n// Type for trigger group matching config - subset of SessionRecordingPersistedConfig properties\ntype TriggerMatchingConfig = Pick<\n    SessionRecordingPersistedConfig,\n    'urlTriggers' | 'urlBlocklist' | 'eventTriggers' | 'linkedFlag'\n>\n\nfunction sessionRecordingUrlTriggerMatches(\n    url: string,\n    triggers: SessionRecordingUrlTrigger[],\n    compiledRegexCache?: Map<string, RegExp>\n) {\n    return triggers.some((trigger) => {\n        switch (trigger.matching) {\n            case 'regex': {\n                const regex = compiledRegexCache?.get(trigger.url) ?? new RegExp(trigger.url)\n                return regex.test(url)\n            }\n            default:\n                return false\n        }\n    })\n}\n\nexport interface TriggerStatusMatching {\n    triggerStatus(sessionId: string): TriggerStatus\n    stop(): void\n}\nexport class OrTriggerMatching implements TriggerStatusMatching {\n    constructor(private readonly _matchers: TriggerStatusMatching[]) {}\n\n    triggerStatus(sessionId: string): TriggerStatus {\n        const statuses = this._matchers.map((m) => m.triggerStatus(sessionId))\n        if (statuses.includes(TRIGGER_ACTIVATED)) {\n            return TRIGGER_ACTIVATED\n        }\n        if (statuses.includes(TRIGGER_PENDING)) {\n            return TRIGGER_PENDING\n        }\n        return TRIGGER_DISABLED\n    }\n\n    stop(): void {\n        this._matchers.forEach((m) => m.stop())\n    }\n}\n\nexport class AndTriggerMatching implements TriggerStatusMatching {\n    constructor(private readonly _matchers: TriggerStatusMatching[]) {}\n\n    triggerStatus(sessionId: string): TriggerStatus {\n        const statuses = new Set<TriggerStatus>()\n        for (const matcher of this._matchers) {\n            statuses.add(matcher.triggerStatus(sessionId))\n        }\n\n        // trigger_disabled means no config\n        statuses.delete(TRIGGER_DISABLED)\n        switch (statuses.size) {\n            case 0:\n                return TRIGGER_DISABLED\n            case 1:\n                return Array.from(statuses)[0]\n            default:\n                return TRIGGER_PENDING\n        }\n    }\n\n    stop(): void {\n        this._matchers.forEach((m) => m.stop())\n    }\n}\n\nexport class PendingTriggerMatching implements TriggerStatusMatching {\n    triggerStatus(): TriggerStatus {\n        return TRIGGER_PENDING\n    }\n\n    stop(): void {\n        // no-op\n    }\n}\n\nexport class AlwaysActivatedTriggerMatching implements TriggerStatusMatching {\n    triggerStatus(): TriggerStatus {\n        return TRIGGER_ACTIVATED\n    }\n\n    stop(): void {\n        // no-op\n    }\n}\n\nconst isEagerLoadedConfig = (x: ReplayConfigType | TriggerMatchingConfig): x is RemoteConfig => {\n    return 'sessionRecording' in x\n}\n\nexport class URLTriggerMatching implements TriggerStatusMatching {\n    _urlTriggers: SessionRecordingUrlTrigger[] = []\n    _urlBlocklist: SessionRecordingUrlTrigger[] = []\n\n    private _compiledTriggerRegexes: Map<string, RegExp> = new Map()\n    private _compiledBlocklistRegexes: Map<string, RegExp> = new Map()\n\n    private _lastCheckedUrl: string = ''\n    private _groupId?: string // Optional group ID for V2 per-group persistence\n\n    urlBlocked: boolean = false\n\n    constructor(\n        private readonly _instance: PostHog,\n        groupId?: string\n    ) {\n        this._groupId = groupId\n    }\n\n    onConfig(config: ReplayConfigType | TriggerMatchingConfig) {\n        this._urlTriggers =\n            (isEagerLoadedConfig(config)\n                ? isObject(config.sessionRecording)\n                    ? config.sessionRecording?.urlTriggers\n                    : []\n                : config?.urlTriggers) || []\n        this._urlBlocklist =\n            (isEagerLoadedConfig(config)\n                ? isObject(config.sessionRecording)\n                    ? config.sessionRecording?.urlBlocklist\n                    : []\n                : config?.urlBlocklist) || []\n\n        this._compileRegexCache()\n    }\n\n    /**\n     * Compiles and caches RegExp objects from URL triggers and blocklist.\n     * This prevents recreating RegExp objects on every rrweb event\n     */\n    private _compileRegexCache(): void {\n        this._compiledTriggerRegexes.clear()\n        this._compiledBlocklistRegexes.clear()\n\n        for (const trigger of this._urlTriggers) {\n            if (trigger.matching === 'regex' && !this._compiledTriggerRegexes.has(trigger.url)) {\n                try {\n                    this._compiledTriggerRegexes.set(trigger.url, new RegExp(trigger.url))\n                } catch (e) {\n                    logger.error('Invalid URL trigger regex pattern:', trigger.url, e)\n                }\n            }\n        }\n\n        for (const trigger of this._urlBlocklist) {\n            if (trigger.matching === 'regex' && !this._compiledBlocklistRegexes.has(trigger.url)) {\n                try {\n                    this._compiledBlocklistRegexes.set(trigger.url, new RegExp(trigger.url))\n                } catch (e) {\n                    logger.error('Invalid URL blocklist regex pattern:', trigger.url, e)\n                }\n            }\n        }\n    }\n\n    /**\n     * @deprecated Use onConfig instead\n     */\n    onRemoteConfig(response: RemoteConfig) {\n        this.onConfig(response)\n    }\n\n    private _urlTriggerStatus(sessionId: string): TriggerStatus {\n        return persistedTriggerStatus(\n            this._instance,\n            this._urlTriggers.length,\n            this._groupId,\n            SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX,\n            SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n            sessionId\n        )\n    }\n\n    triggerStatus(sessionId: string): TriggerStatus {\n        const urlTriggerStatus = this._urlTriggerStatus(sessionId)\n        const eitherIsActivated = urlTriggerStatus === TRIGGER_ACTIVATED\n        const eitherIsPending = urlTriggerStatus === TRIGGER_PENDING\n\n        const result = eitherIsActivated ? TRIGGER_ACTIVATED : eitherIsPending ? TRIGGER_PENDING : TRIGGER_DISABLED\n        this._instance.register_for_session({\n            [SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS]: result,\n        })\n        return result\n    }\n\n    /**\n     * Check URL blocklist and pause/resume recording accordingly\n     * This is separate from trigger checking and is used by both V1 and V2\n     *\n     * Performance optimization: Only checks when URL changes to avoid redundant regex matching\n     */\n    checkUrlBlocklist(onPause: () => void, onResume: () => void): void {\n        const url = getTargetingUrl(this._instance)\n        if (!url) {\n            return\n        }\n\n        // Performance optimization: Skip if URL hasn't changed since last check\n        if (url === this._lastCheckedUrl) {\n            return\n        }\n        this._lastCheckedUrl = url\n\n        // Check blocklist and call onPause/onResume\n        // Note: DON'T set this.urlBlocked here - let the callbacks (_pauseRecording/_resumeRecording) set it\n        const wasBlocked = this.urlBlocked\n        const isNowBlocked = sessionRecordingUrlTriggerMatches(url, this._urlBlocklist, this._compiledBlocklistRegexes)\n\n        if (wasBlocked && isNowBlocked) {\n            return\n        }\n\n        if (isNowBlocked && !wasBlocked) {\n            onPause()\n        } else if (!isNowBlocked && wasBlocked) {\n            onResume()\n        }\n    }\n\n    checkUrlTriggerConditions(\n        onPause: () => void,\n        onResume: () => void,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n        sessionId: string\n    ) {\n        const url = getTargetingUrl(this._instance)\n        if (!url) {\n            return\n        }\n\n        // Performance optimization: Skip if URL hasn't changed since last check\n        // This prevents redundant checks on every rrweb event\n        if (url === this._lastCheckedUrl) {\n            return\n        }\n        this._lastCheckedUrl = url\n\n        // Check blocklist and call onPause/onResume\n        // Note: DON'T set this.urlBlocked here - let the callbacks (_pauseRecording/_resumeRecording) set it\n        const wasBlocked = this.urlBlocked\n        const isNowBlocked = sessionRecordingUrlTriggerMatches(url, this._urlBlocklist, this._compiledBlocklistRegexes)\n\n        if (isNowBlocked && !wasBlocked) {\n            onPause()\n        } else if (!isNowBlocked && wasBlocked) {\n            onResume()\n        }\n\n        // Check URL triggers\n        const isActivated = this._urlTriggerStatus(sessionId) === TRIGGER_ACTIVATED\n        const urlMatches = sessionRecordingUrlTriggerMatches(url, this._urlTriggers, this._compiledTriggerRegexes)\n\n        if (!isActivated && urlMatches) {\n            onActivate('url', url)\n        }\n    }\n\n    stop(): void {\n        this._lastCheckedUrl = ''\n    }\n}\n\nexport class LinkedFlagMatching implements TriggerStatusMatching {\n    linkedFlag: string | FlagVariant | null = null\n    linkedFlagSeen: boolean = false\n    private _flagListenerCleanup: () => void = () => {}\n    constructor(private readonly _instance: PostHog) {}\n\n    triggerStatus(): TriggerStatus {\n        let result = TRIGGER_PENDING\n        if (isNullish(this.linkedFlag)) {\n            result = TRIGGER_DISABLED\n        }\n        if (this.linkedFlagSeen) {\n            result = TRIGGER_ACTIVATED\n        }\n        this._instance.register_for_session({\n            [SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS]: result,\n        })\n        return result\n    }\n\n    onConfig(\n        config: ReplayConfigType | TriggerMatchingConfig,\n        onStarted: (flag: string, variant: string | null) => void\n    ) {\n        this.linkedFlag =\n            (isEagerLoadedConfig(config)\n                ? isObject(config.sessionRecording)\n                    ? config.sessionRecording?.linkedFlag\n                    : null\n                : config?.linkedFlag) || null\n\n        if (!isNullish(this.linkedFlag) && !this.linkedFlagSeen) {\n            const linkedFlag = isString(this.linkedFlag) ? this.linkedFlag : this.linkedFlag.flag\n            const linkedVariant = isString(this.linkedFlag) ? null : this.linkedFlag.variant\n            this._flagListenerCleanup = this._instance.onFeatureFlags((_flags, variants) => {\n                const flagIsPresent = isObject(variants) && linkedFlag in variants\n                let linkedFlagMatches = false\n                if (flagIsPresent) {\n                    const variantForFlagKey = variants[linkedFlag]\n                    if (isBoolean(variantForFlagKey)) {\n                        linkedFlagMatches = variantForFlagKey === true\n                    } else if (linkedVariant) {\n                        linkedFlagMatches = variantForFlagKey === linkedVariant\n                    } else {\n                        // then this is a variant flag and we want to match any string\n                        linkedFlagMatches = !!variantForFlagKey\n                    }\n                }\n                this.linkedFlagSeen = linkedFlagMatches\n                if (linkedFlagMatches) {\n                    onStarted(linkedFlag, linkedVariant)\n                }\n            })\n        }\n    }\n\n    /**\n     * @deprecated Use onConfig instead\n     */\n    onRemoteConfig(response: RemoteConfig, onStarted: (flag: string, variant: string | null) => void) {\n        this.onConfig(response, onStarted)\n    }\n\n    stop(): void {\n        this._flagListenerCleanup()\n    }\n}\n\nexport class EventTriggerMatching implements TriggerStatusMatching {\n    _eventTriggers: string[] = []\n    private _groupId?: string // Optional group ID for V2 per-group persistence\n\n    constructor(\n        private readonly _instance: PostHog,\n        groupId?: string\n    ) {\n        this._groupId = groupId\n    }\n\n    onConfig(config: ReplayConfigType | TriggerMatchingConfig) {\n        // Handle both RemoteConfig (nested) and SessionRecordingPersistedConfig (flattened) structures\n        this._eventTriggers =\n            (isEagerLoadedConfig(config)\n                ? isObject(config.sessionRecording)\n                    ? config.sessionRecording?.eventTriggers\n                    : []\n                : config?.eventTriggers) || []\n    }\n\n    /**\n     * @deprecated Use onConfig instead\n     */\n    onRemoteConfig(response: RemoteConfig) {\n        this.onConfig(response)\n    }\n\n    private _eventTriggerStatus(sessionId: string): TriggerStatus {\n        const triggerCount = this._eventTriggers.length\n        return persistedTriggerStatus(\n            this._instance,\n            triggerCount,\n            this._groupId,\n            SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX,\n            SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n            sessionId\n        )\n    }\n\n    triggerStatus(sessionId: string): TriggerStatus {\n        const eventTriggerStatus = this._eventTriggerStatus(sessionId)\n        const result =\n            eventTriggerStatus === TRIGGER_ACTIVATED\n                ? TRIGGER_ACTIVATED\n                : eventTriggerStatus === TRIGGER_PENDING\n                  ? TRIGGER_PENDING\n                  : TRIGGER_DISABLED\n        this._instance.register_for_session({\n            [SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS]: result,\n        })\n        return result\n    }\n\n    checkEventTriggerConditions(\n        eventName: string,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n        sessionId: string\n    ) {\n        if (this._eventTriggers.length === 0) {\n            return\n        }\n\n        const isActivated = this._eventTriggerStatus(sessionId) === TRIGGER_ACTIVATED\n        const includes = this._eventTriggers.includes(eventName)\n        if (!isActivated && includes) {\n            onActivate('event', eventName)\n        }\n    }\n\n    stop(): void {\n        // no-op\n    }\n}\n\n/**\n * V2 Trigger Group Matching - manages a single trigger group with its own conditions\n */\nexport class TriggerGroupMatching implements TriggerStatusMatching {\n    private _urlTriggerMatching: URLTriggerMatching\n    private _eventTriggerMatching: EventTriggerMatching\n    private _linkedFlagMatching: LinkedFlagMatching\n    private _combinedMatching: TriggerStatusMatching\n    public readonly group: import('../../../types').SessionRecordingTriggerGroup\n\n    constructor(\n        private readonly _instance: PostHog,\n        group: import('../../../types').SessionRecordingTriggerGroup,\n        onFlagStarted: (flag: string, variant: string | null) => void\n    ) {\n        this.group = group\n        // V2: Pass groupId to child matchers for per-group persistence\n        this._urlTriggerMatching = new URLTriggerMatching(_instance, group.id)\n        this._eventTriggerMatching = new EventTriggerMatching(_instance, group.id)\n        this._linkedFlagMatching = new LinkedFlagMatching(_instance)\n\n        // Check if all conditions are empty (no events, urls, or flags)\n        const hasEvents = group.conditions.events && group.conditions.events.length > 0\n        const hasUrls = group.conditions.urls && group.conditions.urls.length > 0\n        const hasFlag = !!group.conditions.flag\n\n        if (!hasEvents && !hasUrls && !hasFlag) {\n            // Empty conditions = trigger immediately on session start\n            this._combinedMatching = new AlwaysActivatedTriggerMatching()\n        } else {\n            // V2: Events arrive as objects {name, properties?} from the server.\n            // Extract just the names — property filter evaluation is handled by the strategy.\n            const eventNames = (group.conditions.events || []).map((e) => e.name)\n\n            // Convert group config to the format expected by the individual matchers\n            const config: TriggerMatchingConfig = {\n                urlTriggers: group.conditions.urls || [],\n                eventTriggers: eventNames,\n                linkedFlag: group.conditions.flag || null,\n                urlBlocklist: [],\n            }\n\n            this._urlTriggerMatching.onConfig(config)\n            this._eventTriggerMatching.onConfig(config)\n            this._linkedFlagMatching.onConfig(config, onFlagStarted)\n\n            // Combine matchers based on the group's matchType\n            const matchers = [this._eventTriggerMatching, this._urlTriggerMatching, this._linkedFlagMatching]\n            this._combinedMatching =\n                group.conditions.matchType === 'any'\n                    ? new OrTriggerMatching(matchers)\n                    : new AndTriggerMatching(matchers)\n        }\n    }\n\n    triggerStatus(sessionId: string): TriggerStatus {\n        return this._combinedMatching.triggerStatus(sessionId)\n    }\n\n    checkEventTriggerConditions(\n        eventName: string,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n        sessionId: string\n    ) {\n        this._eventTriggerMatching.checkEventTriggerConditions(eventName, onActivate, sessionId)\n    }\n\n    checkUrlTriggerConditions(\n        onPause: () => void,\n        onResume: () => void,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void,\n        sessionId: string\n    ) {\n        this._urlTriggerMatching.checkUrlTriggerConditions(onPause, onResume, onActivate, sessionId)\n    }\n\n    /**\n     * V2: Activate this group's trigger and persist to group-specific key\n     * This prevents cross-group contamination and survives page reloads\n     */\n    activateTrigger(triggerType: TriggerType, sessionId: string): void {\n        const persistenceKey =\n            triggerType === 'url'\n                ? SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX + this.group.id\n                : SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX + this.group.id\n\n        this._instance.persistence?.register({\n            [persistenceKey]: sessionId,\n        })\n    }\n\n    stop(): void {\n        this._urlTriggerMatching.stop()\n        this._eventTriggerMatching.stop()\n        this._linkedFlagMatching.stop()\n    }\n}\n\n// we need a no-op matcher before we can lazy-load the other matches, since all matchers wait on remote config anyway\nexport function nullMatchSessionRecordingStatus(triggersStatus: RecordingTriggersStatus): SessionRecordingStatus {\n    if (triggersStatus.rrwebError) {\n        return RRWEB_ERROR\n    }\n\n    if (!triggersStatus.isRecordingEnabled) {\n        return DISABLED\n    }\n\n    return BUFFERING\n}\n\nexport function anyMatchSessionRecordingStatus(triggersStatus: RecordingTriggersStatus): SessionRecordingStatus {\n    if (triggersStatus.rrwebError) {\n        return RRWEB_ERROR\n    }\n\n    if (!triggersStatus.receivedFlags) {\n        return BUFFERING\n    }\n\n    if (!triggersStatus.isRecordingEnabled) {\n        return DISABLED\n    }\n\n    if (triggersStatus.urlTriggerMatching.urlBlocked) {\n        return PAUSED\n    }\n\n    const sampledActive = triggersStatus.isSampled === true\n    const triggerMatches = new OrTriggerMatching([\n        triggersStatus.eventTriggerMatching,\n        triggersStatus.urlTriggerMatching,\n        triggersStatus.linkedFlagMatching,\n    ]).triggerStatus(triggersStatus.sessionId)\n\n    if (sampledActive) {\n        return SAMPLED\n    }\n\n    if (triggerMatches === TRIGGER_ACTIVATED) {\n        return ACTIVE\n    }\n\n    if (triggerMatches === TRIGGER_PENDING) {\n        // even if sampled active is false, we should still be buffering\n        // since a pending trigger could override it\n        return BUFFERING\n    }\n\n    // if sampling is set and the session is already decided to not be sampled\n    // then we should never be active\n    if (triggersStatus.isSampled === false) {\n        return DISABLED\n    }\n\n    return ACTIVE\n}\n\nexport function allMatchSessionRecordingStatus(triggersStatus: RecordingTriggersStatus): SessionRecordingStatus {\n    if (triggersStatus.rrwebError) {\n        return RRWEB_ERROR\n    }\n\n    if (!triggersStatus.receivedFlags) {\n        return BUFFERING\n    }\n\n    if (!triggersStatus.isRecordingEnabled) {\n        return DISABLED\n    }\n\n    if (triggersStatus.urlTriggerMatching.urlBlocked) {\n        return PAUSED\n    }\n\n    const andTriggerMatch = new AndTriggerMatching([\n        triggersStatus.eventTriggerMatching,\n        triggersStatus.urlTriggerMatching,\n        triggersStatus.linkedFlagMatching,\n    ])\n    const currentTriggerStatus = andTriggerMatch.triggerStatus(triggersStatus.sessionId)\n    const hasTriggersConfigured = currentTriggerStatus !== TRIGGER_DISABLED\n\n    const hasSamplingConfigured = isBoolean(triggersStatus.isSampled)\n\n    if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_PENDING) {\n        return BUFFERING\n    }\n\n    if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_DISABLED) {\n        return DISABLED\n    }\n\n    // sampling can't ever cause buffering, it's always determined right away or not configured\n    if (hasSamplingConfigured && !triggersStatus.isSampled) {\n        return DISABLED\n    }\n\n    // If sampling is configured and set to true, return sampled\n    if (triggersStatus.isSampled === true) {\n        return SAMPLED\n    }\n\n    return ACTIVE\n}\n\n/**\n * V2 Trigger Groups Status Matcher - implements union behavior:\n * 1. Evaluate ALL trigger groups\n * 2. For each matching group, check if its sample rate hits\n * 3. If ANY group's sample rate hits → record session\n */\nexport function triggerGroupsMatchSessionRecordingStatus(\n    triggersStatus: RecordingTriggersStatusV2\n): SessionRecordingStatus {\n    if (triggersStatus.rrwebError) {\n        return RRWEB_ERROR\n    }\n\n    if (!triggersStatus.receivedFlags) {\n        return BUFFERING\n    }\n\n    if (!triggersStatus.isRecordingEnabled) {\n        return DISABLED\n    }\n\n    // Check if any URL is blocked (url blocklist is global, not per-group)\n    if (triggersStatus.urlTriggerMatching.urlBlocked) {\n        return PAUSED\n    }\n\n    const groupMatchers = triggersStatus.triggerGroupMatchers\n    const samplingResults = triggersStatus.triggerGroupSamplingResults\n\n    if (groupMatchers.length === 0) {\n        // No V2 groups configured - should not happen, but treat as disabled\n        return DISABLED\n    }\n\n    // Evaluate all groups to determine overall status\n    let anyGroupPending = false\n    let anyGroupSampled = false\n\n    for (const matcher of groupMatchers) {\n        const groupStatus = matcher.triggerStatus(triggersStatus.sessionId)\n\n        if (groupStatus === TRIGGER_ACTIVATED) {\n            // Check if this group's sample rate hit\n            const groupId = matcher.group.id\n            const samplingResult = samplingResults.get(groupId)\n\n            if (isUndefined(samplingResult)) {\n                logger.warn('[V2 Triggers] Group activated but no sampling decision found', { groupId })\n            } else if (samplingResult === true) {\n                anyGroupSampled = true\n            }\n        } else if (groupStatus === TRIGGER_PENDING) {\n            anyGroupPending = true\n        }\n    }\n\n    // Union behavior: if ANY group hit its sample rate, record\n    if (anyGroupSampled) {\n        return SAMPLED\n    }\n\n    // If any group is pending, keep buffering\n    if (anyGroupPending) {\n        return BUFFERING\n    }\n\n    // All groups are either disabled, conditions not met, or sampled out\n    return DISABLED\n}\n","import type { eventWithTime, pluginEvent } from '../types/rrweb-types'\n\nimport { isArray, isNull, isObject, isUndefined } from '@posthog/core'\nimport type { SnapshotBuffer } from './lazy-loaded-session-recorder'\n\n// taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#circular_references\nexport function circularReferenceReplacer() {\n    const ancestors: any[] = []\n    return function (this: any, _key: string, value: any) {\n        // arrays must be tracked as ancestors too - isObject excludes them, and an\n        // untracked array in the path empties the ancestor stack, so a cycle passing\n        // through an array would be missed and JSON.stringify would throw\n        if (isObject(value) || isArray(value)) {\n            // `this` is the object that value is contained in,\n            // i.e., its direct parent.\n            while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {\n                ancestors.pop()\n            }\n            if (ancestors.includes(value)) {\n                return '[Circular]'\n            }\n            ancestors.push(value)\n            return value\n        } else {\n            return value\n        }\n    }\n}\n\nfunction estimateStringBytes(data: string): number {\n    return new Blob([data]).size\n}\n\nexport function estimateSize(sizeable: unknown): number {\n    const stringifiedData = JSON.stringify(sizeable, circularReferenceReplacer())\n    return stringifiedData ? estimateStringBytes(stringifiedData) : 0\n}\n\n// Lightweight size estimate for compressed events without allocating a JSON string.\n// Intentionally loose: does not account for JSON escaping of strings or keys.\n// This is fine because compressed event strings are base64 gzip output (safe alphabet)\n// and keys are known-safe identifiers. Used only for buffer threshold checks (~1MB)\n// and split-buffer decisions (~7MB) where a few bytes of drift don't matter.\nexport function estimateCompressedEventSize(value: unknown): number {\n    if (isNull(value)) {\n        return 4\n    }\n    if (isUndefined(value)) {\n        return 0\n    }\n    switch (typeof value) {\n        case 'string':\n            return value.length + 2\n        case 'number':\n            return String(value).length\n        case 'boolean':\n            return value ? 4 : 5\n        case 'object': {\n            if (isArray(value)) {\n                let size = 2\n                for (let i = 0; i < value.length; i++) {\n                    if (i > 0) size += 1\n                    const el = value[i]\n                    size += isUndefined(el) || isNull(el) ? 4 : estimateCompressedEventSize(el)\n                }\n                return size\n            }\n            const obj = value as Record<string, unknown>\n            let size = 2\n            let first = true\n            for (const key in obj) {\n                if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n                const val = obj[key]\n                if (isUndefined(val)) continue\n                if (!first) size += 1\n                first = false\n                size += key.length + 3 + estimateCompressedEventSize(val)\n            }\n            return size\n        }\n        default:\n            return 0\n    }\n}\n\nexport const replacementImageURI =\n    'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2IiBmaWxsPSJibGFjayIvPgo8cGF0aCBkPSJNOCAwSDE2TDAgMTZWOEw4IDBaIiBmaWxsPSIjMkQyRDJEIi8+CjxwYXRoIGQ9Ik0xNiA4VjE2SDhMMTYgOFoiIGZpbGw9IiMyRDJEMkQiLz4KPC9zdmc+Cg=='\n\nexport const FULL_SNAPSHOT_EVENT_TYPE = 2\nexport const META_EVENT_TYPE = 4\nexport const INCREMENTAL_SNAPSHOT_EVENT_TYPE = 3\nexport const PLUGIN_EVENT_TYPE = 6\nexport const MUTATION_SOURCE_TYPE = 0\n\nexport const MAX_MESSAGE_SIZE = 5000000 // ~5mb\n\n/*\n * Check whether a data payload is nearing 5mb. If it is, it checks the data for\n * data URIs (the likely culprit for large payloads). If it finds data URIs, it either replaces\n * it with a generic image (if it's an image) or removes it.\n * @data {object} the rr-web data object\n * @returns {object} the rr-web data object with data uris filtered out\n */\nexport function ensureMaxMessageSize(data: eventWithTime): { event: eventWithTime; size: number } {\n    let stringifiedData = JSON.stringify(data)\n    // Note: with compression, this limit may be able to be increased\n    // but we're assuming most of the size is from a data uri which\n    // is unlikely to be compressed further\n\n    let size = estimateStringBytes(stringifiedData)\n    if (size > MAX_MESSAGE_SIZE) {\n        // Regex that matches the pattern for a dataURI with the shape 'data:{mime type};{encoding},{data}'. It:\n        // 1) Checks if the pattern starts with 'data:' (potentially, not at the start of the string)\n        // 2) Extracts the mime type of the data uri in the first group\n        // 3) Determines when the data URI ends.Depending on if it's used in the src tag or css, it can end with a ) or \"\n        const dataURIRegex = /data:([\\w/\\-.]+);(\\w+),([^)\"]*)/gim\n        const matches = stringifiedData.matchAll(dataURIRegex)\n        const unfilteredStringifiedData = stringifiedData\n        for (const match of matches) {\n            if (match[1].toLocaleLowerCase().slice(0, 6) === 'image/') {\n                stringifiedData = stringifiedData.replace(match[0], replacementImageURI)\n            } else {\n                stringifiedData = stringifiedData.replace(match[0], '')\n            }\n        }\n        if (stringifiedData !== unfilteredStringifiedData) {\n            size = estimateStringBytes(stringifiedData)\n        }\n    }\n    return { event: JSON.parse(stringifiedData), size }\n}\n\nexport const CONSOLE_LOG_PLUGIN_NAME = 'rrweb/console@1' // The name of the rr-web plugin that emits console logs\n\n// Console logs can be really large. This function truncates large logs\n// It's a simple function that just truncates long strings.\n// TODO: Ideally this function would have better handling of objects + lists,\n// so they could still be rendered in a pretty way after truncation.\nexport function truncateLargeConsoleLogs(_event: eventWithTime) {\n    const event = _event as pluginEvent<{ payload: string[] }>\n\n    const MAX_STRING_SIZE = 2000 // Maximum number of characters allowed in a string\n    const MAX_STRINGS_PER_LOG = 10 // A log can consist of multiple strings (e.g. consol.log('string1', 'string2'))\n\n    if (\n        event &&\n        isObject(event) &&\n        event.type === PLUGIN_EVENT_TYPE &&\n        isObject(event.data) &&\n        event.data.plugin === CONSOLE_LOG_PLUGIN_NAME\n    ) {\n        // Note: event.data.payload.payload comes from rr-web, and is an array of strings\n        if (event.data.payload.payload.length > MAX_STRINGS_PER_LOG) {\n            event.data.payload.payload = event.data.payload.payload.slice(0, MAX_STRINGS_PER_LOG)\n            event.data.payload.payload.push('...[truncated]')\n        }\n        const updatedPayload = []\n        for (let i = 0; i < event.data.payload.payload.length; i++) {\n            if (\n                event.data.payload.payload[i] && // Value can be null\n                event.data.payload.payload[i].length > MAX_STRING_SIZE\n            ) {\n                updatedPayload.push(event.data.payload.payload[i].slice(0, MAX_STRING_SIZE) + '...[truncated]')\n            } else {\n                updatedPayload.push(event.data.payload.payload[i])\n            }\n        }\n        event.data.payload.payload = updatedPayload\n        // Return original type\n        return _event\n    }\n    return _event\n}\n\nexport const SEVEN_MEGABYTES = 1024 * 1024 * 7 * 0.9 // ~7mb (with some wiggle room)\n\n// recursively splits large buffers into smaller ones\n// uses a pretty high size limit to avoid splitting too much\nexport function splitBuffer(buffer: SnapshotBuffer, sizeLimit: number = SEVEN_MEGABYTES): SnapshotBuffer[] {\n    if (buffer.size >= sizeLimit && buffer.data.length > 1) {\n        const half = Math.floor(buffer.data.length / 2)\n        const firstHalfSizes = buffer.sizes.slice(0, half)\n        const secondHalfSizes = buffer.sizes.slice(half)\n        return [\n            splitBuffer({\n                size: firstHalfSizes.reduce((a, b) => a + b, 0),\n                data: buffer.data.slice(0, half),\n                sizes: firstHalfSizes,\n                sessionId: buffer.sessionId,\n                windowId: buffer.windowId,\n            }),\n            splitBuffer({\n                size: secondHalfSizes.reduce((a, b) => a + b, 0),\n                data: buffer.data.slice(half),\n                sizes: secondHalfSizes,\n                sessionId: buffer.sessionId,\n                windowId: buffer.windowId,\n            }),\n        ].flatMap((x) => x)\n    } else {\n        return [buffer]\n    }\n}\n","// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Much of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// Many optimizations have been made, so the bundle size is ultimately smaller but performance is similar.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n    var u = ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([c], { type: 'text/javascript' })));\n    var w = new Worker(u);\n    w.onerror = function (e) { return cb(e.error, null); };\n    w.onmessage = function (e) { return cb(null, e.data); };\n    w.postMessage(msg, transfer);\n    return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n    var b = new u16(31);\n    for (var i = 0; i < 31; ++i) {\n        b[i] = start += 1 << eb[i - 1];\n    }\n    // numbers here are at max 18 bits\n    var r = new u32(b[30]);\n    for (var i = 1; i < 30; ++i) {\n        for (var j = b[i]; j < b[i + 1]; ++j) {\n            r[j] = ((j - b[i]) << 5) | i;\n        }\n    }\n    return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n    // reverse table algorithm from SO\n    var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n    x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n    x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n    rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n    var s = cd.length;\n    // index\n    var i = 0;\n    // u16 \"map\": index -> # of codes with bit length = index\n    var l = new u16(mb);\n    // length of cd must be 288 (total # of codes)\n    for (; i < s; ++i)\n        ++l[cd[i] - 1];\n    // u16 \"map\": index -> minimum code for bit length = index\n    var le = new u16(mb);\n    for (i = 0; i < mb; ++i) {\n        le[i] = (le[i - 1] + l[i - 1]) << 1;\n    }\n    var co;\n    if (r) {\n        // u16 \"map\": index -> number of actual bits, symbol for code\n        co = new u16(1 << mb);\n        // bits to remove for reverser\n        var rvb = 15 - mb;\n        for (i = 0; i < s; ++i) {\n            // ignore 0 lengths\n            if (cd[i]) {\n                // num encoding both symbol and bits read\n                var sv = (i << 4) | cd[i];\n                // free bits\n                var r_1 = mb - cd[i];\n                // start value\n                var v = le[cd[i] - 1]++ << r_1;\n                // m is end value\n                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n                    // every 16 bit value starting with the code yields the same result\n                    co[rev[v] >>> rvb] = sv;\n                }\n            }\n        }\n    }\n    else {\n        co = new u16(s);\n        for (i = 0; i < s; ++i)\n            co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n    }\n    return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n    flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n    flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n    flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n    flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n    fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n    var m = a[0];\n    for (var i = 1; i < a.length; ++i) {\n        if (a[i] > m)\n            m = a[i];\n    }\n    return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n    var o = (p / 8) >> 0;\n    return ((d[o] | (d[o + 1] << 8)) >>> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n    var o = (p / 8) >> 0;\n    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p / 8) >> 0) + (p & 7 && 1); };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n    if (s == null || s < 0)\n        s = 0;\n    if (e == null || e > v.length)\n        e = v.length;\n    // can't use .constructor in case user-supplied\n    var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s);\n    n.set(v.subarray(s, e));\n    return n;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n    // source length\n    var sl = dat.length;\n    // have to estimate size\n    var noBuf = !buf || st;\n    // no state\n    var noSt = !st || st.i;\n    if (!st)\n        st = {};\n    // Assumes roughly 33% compression ratio average\n    if (!buf)\n        buf = new u8(sl * 3);\n    // ensure buffer can fit at least l elements\n    var cbuf = function (l) {\n        var bl = buf.length;\n        // need to increase size to fit\n        if (l > bl) {\n            // Double or set to necessary, whichever is greater\n            var nbuf = new u8(Math.max(bl * 2, l));\n            nbuf.set(buf);\n            buf = nbuf;\n        }\n    };\n    //  last chunk         bitpos           bytes\n    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n    // total bits\n    var tbts = sl * 8;\n    do {\n        if (!lm) {\n            // BFINAL - this is only 1 when last chunk is next\n            st.f = final = bits(dat, pos, 1);\n            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n            var type = bits(dat, pos + 1, 3);\n            pos += 3;\n            if (!type) {\n                // go to end of byte boundary\n                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n                if (t > sl) {\n                    if (noSt)\n                        throw 'unexpected EOF';\n                    break;\n                }\n                // ensure size\n                if (noBuf)\n                    cbuf(bt + l);\n                // Copy over uncompressed data\n                buf.set(dat.subarray(s, t), bt);\n                // Get new bitpos, update byte count\n                st.b = bt += l, st.p = pos = t * 8;\n                continue;\n            }\n            else if (type == 1)\n                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n            else if (type == 2) {\n                //  literal                            lengths\n                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n                var tl = hLit + bits(dat, pos + 5, 31) + 1;\n                pos += 14;\n                // length+distance tree\n                var ldt = new u8(tl);\n                // code length tree\n                var clt = new u8(19);\n                for (var i = 0; i < hcLen; ++i) {\n                    // use index map to get real code\n                    clt[clim[i]] = bits(dat, pos + i * 3, 7);\n                }\n                pos += hcLen * 3;\n                // code lengths bits\n                var clb = max(clt), clbmsk = (1 << clb) - 1;\n                if (!noSt && pos + tl * (clb + 7) > tbts)\n                    break;\n                // code lengths map\n                var clm = hMap(clt, clb, 1);\n                for (var i = 0; i < tl;) {\n                    var r = clm[bits(dat, pos, clbmsk)];\n                    // bits read\n                    pos += r & 15;\n                    // symbol\n                    var s = r >>> 4;\n                    // code length to copy\n                    if (s < 16) {\n                        ldt[i++] = s;\n                    }\n                    else {\n                        //  copy   count\n                        var c = 0, n = 0;\n                        if (s == 16)\n                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n                        else if (s == 17)\n                            n = 3 + bits(dat, pos, 7), pos += 3;\n                        else if (s == 18)\n                            n = 11 + bits(dat, pos, 127), pos += 7;\n                        while (n--)\n                            ldt[i++] = c;\n                    }\n                }\n                //    length tree                 distance tree\n                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n                // max length bits\n                lbt = max(lt);\n                // max dist bits\n                dbt = max(dt);\n                lm = hMap(lt, lbt, 1);\n                dm = hMap(dt, dbt, 1);\n            }\n            else\n                throw 'invalid block type';\n            if (pos > tbts)\n                throw 'unexpected EOF';\n        }\n        // Make sure the buffer can hold this + the largest possible addition\n        // Maximum chunk size (practically, theoretically infinite) is 2^17;\n        if (noBuf)\n            cbuf(bt + 131072);\n        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n        var mxa = lbt + dbt + 18;\n        while (noSt || pos + mxa < tbts) {\n            // bits read, code\n            var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n            pos += c & 15;\n            if (pos > tbts)\n                throw 'unexpected EOF';\n            if (!c)\n                throw 'invalid length/literal';\n            if (sym < 256)\n                buf[bt++] = sym;\n            else if (sym == 256) {\n                lm = null;\n                break;\n            }\n            else {\n                var add = sym - 254;\n                // no extra bits needed if less\n                if (sym > 264) {\n                    // index\n                    var i = sym - 257, b = fleb[i];\n                    add = bits(dat, pos, (1 << b) - 1) + fl[i];\n                    pos += b;\n                }\n                // dist\n                var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n                if (!d)\n                    throw 'invalid distance';\n                pos += d & 15;\n                var dt = fd[dsym];\n                if (dsym > 3) {\n                    var b = fdeb[dsym];\n                    dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n                }\n                if (pos > tbts)\n                    throw 'unexpected EOF';\n                if (noBuf)\n                    cbuf(bt + 131072);\n                var end = bt + add;\n                for (; bt < end; bt += 4) {\n                    buf[bt] = buf[bt - dt];\n                    buf[bt + 1] = buf[bt + 1 - dt];\n                    buf[bt + 2] = buf[bt + 2 - dt];\n                    buf[bt + 3] = buf[bt + 3 - dt];\n                }\n                bt = end;\n            }\n        }\n        st.l = lm, st.p = pos, st.b = bt;\n        if (lm)\n            final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n    } while (!final);\n    return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) >> 0;\n    d[o] |= v;\n    d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) >> 0;\n    d[o] |= v;\n    d[o + 1] |= v >>> 8;\n    d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n    // Need extra info to make a tree\n    var t = [];\n    for (var i = 0; i < d.length; ++i) {\n        if (d[i])\n            t.push({ s: i, f: d[i] });\n    }\n    var s = t.length;\n    var t2 = t.slice();\n    if (!s)\n        return [new u8(0), 0];\n    if (s == 1) {\n        var v = new u8(t[0].s + 1);\n        v[t[0].s] = 1;\n        return [v, 1];\n    }\n    t.sort(function (a, b) { return a.f - b.f; });\n    // after i2 reaches last ind, will be stopped\n    // freq must be greater than largest possible number of symbols\n    t.push({ s: -1, f: 25001 });\n    var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n    t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n    // efficient algorithm from UZIP.js\n    // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n    // symbols that combined have high freq, will start processing i2 (high-freq,\n    // non-composite) symbols instead\n    // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n    while (i1 != s - 1) {\n        l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n        r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n        t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n    }\n    var maxSym = t2[0].s;\n    for (var i = 1; i < s; ++i) {\n        if (t2[i].s > maxSym)\n            maxSym = t2[i].s;\n    }\n    // code lengths\n    var tr = new u16(maxSym + 1);\n    // max bits in tree\n    var mbt = ln(t[i1 - 1], tr, 0);\n    if (mbt > mb) {\n        // more algorithms from UZIP.js\n        // TODO: find out how this code works (debt)\n        //  ind    debt\n        var i = 0, dt = 0;\n        //    left            cost\n        var lft = mbt - mb, cst = 1 << lft;\n        t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n        for (; i < s; ++i) {\n            var i2_1 = t2[i].s;\n            if (tr[i2_1] > mb) {\n                dt += cst - (1 << (mbt - tr[i2_1]));\n                tr[i2_1] = mb;\n            }\n            else\n                break;\n        }\n        dt >>>= lft;\n        while (dt > 0) {\n            var i2_2 = t2[i].s;\n            if (tr[i2_2] < mb)\n                dt -= 1 << (mb - tr[i2_2]++ - 1);\n            else\n                ++i;\n        }\n        for (; i >= 0 && dt; --i) {\n            var i2_3 = t2[i].s;\n            if (tr[i2_3] == mb) {\n                --tr[i2_3];\n                ++dt;\n            }\n        }\n        mbt = mb;\n    }\n    return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n    return n.s == -1\n        ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n        : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n    var s = c.length;\n    // Note that the semicolon was intentional\n    while (s && !c[--s])\n        ;\n    var cl = new u16(++s);\n    //  ind      num         streak\n    var cli = 0, cln = c[0], cls = 1;\n    var w = function (v) { cl[cli++] = v; };\n    for (var i = 1; i <= s; ++i) {\n        if (c[i] == cln && i != s)\n            ++cls;\n        else {\n            if (!cln && cls > 2) {\n                for (; cls > 138; cls -= 138)\n                    w(32754);\n                if (cls > 2) {\n                    w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n                    cls = 0;\n                }\n            }\n            else if (cls > 3) {\n                w(cln), --cls;\n                for (; cls > 6; cls -= 6)\n                    w(8304);\n                if (cls > 2)\n                    w(((cls - 3) << 5) | 8208), cls = 0;\n            }\n            while (cls--)\n                w(cln);\n            cls = 1;\n            cln = c[i];\n        }\n    }\n    return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n    var l = 0;\n    for (var i = 0; i < cl.length; ++i)\n        l += cf[i] * cl[i];\n    return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n    // no need to write 00 as type: TypedArray defaults to 0\n    var s = dat.length;\n    var o = shft(pos + 2);\n    out[o] = s & 255;\n    out[o + 1] = s >>> 8;\n    out[o + 2] = out[o] ^ 255;\n    out[o + 3] = out[o + 1] ^ 255;\n    for (var i = 0; i < s; ++i)\n        out[o + i + 4] = dat[i];\n    return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n    wbits(out, p++, final);\n    ++lf[256];\n    var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n    var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n    var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n    var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n    var lcfreq = new u16(19);\n    for (var i = 0; i < lclt.length; ++i)\n        lcfreq[lclt[i] & 31]++;\n    for (var i = 0; i < lcdt.length; ++i)\n        lcfreq[lcdt[i] & 31]++;\n    var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n    var nlcc = 19;\n    for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n        ;\n    var flen = (bl + 5) << 3;\n    var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n    var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n    if (flen <= ftlen && flen <= dtlen)\n        return wfblk(out, p, dat.subarray(bs, bs + bl));\n    var lm, ll, dm, dl;\n    wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n    if (dtlen < ftlen) {\n        lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n        var llm = hMap(lct, mlcb, 0);\n        wbits(out, p, nlc - 257);\n        wbits(out, p + 5, ndc - 1);\n        wbits(out, p + 10, nlcc - 4);\n        p += 14;\n        for (var i = 0; i < nlcc; ++i)\n            wbits(out, p + 3 * i, lct[clim[i]]);\n        p += 3 * nlcc;\n        var lcts = [lclt, lcdt];\n        for (var it = 0; it < 2; ++it) {\n            var clct = lcts[it];\n            for (var i = 0; i < clct.length; ++i) {\n                var len = clct[i] & 31;\n                wbits(out, p, llm[len]), p += lct[len];\n                if (len > 15)\n                    wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n            }\n        }\n    }\n    else {\n        lm = flm, ll = flt, dm = fdm, dl = fdt;\n    }\n    for (var i = 0; i < li; ++i) {\n        if (syms[i] > 255) {\n            var len = (syms[i] >>> 18) & 31;\n            wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n            if (len > 7)\n                wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n            var dst = syms[i] & 31;\n            wbits16(out, p, dm[dst]), p += dl[dst];\n            if (dst > 3)\n                wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n        }\n        else {\n            wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n        }\n    }\n    wbits16(out, p, lm[256]);\n    return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n    var s = dat.length;\n    var o = new u8(pre + s + 5 * (1 + Math.floor(s / 7000)) + post);\n    // writing to this writes to the output buffer\n    var w = o.subarray(pre, o.length - post);\n    var pos = 0;\n    if (!lvl || s < 8) {\n        for (var i = 0; i <= s; i += 65535) {\n            // end\n            var e = i + 65535;\n            if (e < s) {\n                // write full block\n                pos = wfblk(w, pos, dat.subarray(i, e));\n            }\n            else {\n                // write final block\n                w[i] = lst;\n                pos = wfblk(w, pos, dat.subarray(i, s));\n            }\n        }\n    }\n    else {\n        var opt = deo[lvl - 1];\n        var n = opt >>> 13, c = opt & 8191;\n        var msk_1 = (1 << plvl) - 1;\n        //    prev 2-byte val map    curr 2-byte val map\n        var prev = new u16(32768), head = new u16(msk_1 + 1);\n        var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n        var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n        // 24576 is an arbitrary number of maximum symbols per block\n        // 424 buffer for last block\n        var syms = new u32(25000);\n        // length/literal freq   distance freq\n        var lf = new u16(288), df = new u16(32);\n        //  l/lcnt  exbits  index  l/lind  waitdx  bitpos\n        var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n        for (; i < s; ++i) {\n            // hash value\n            var hv = hsh(i);\n            // index mod 32768\n            var imod = i & 32767;\n            // previous index with this value\n            var pimod = head[hv];\n            prev[imod] = pimod;\n            head[hv] = imod;\n            // We always should modify head and prev, but only add symbols if\n            // this data is not yet processed (\"wait\" for wait index)\n            if (wi <= i) {\n                // bytes remaining\n                var rem = s - i;\n                if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n                    pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n                    li = lc_1 = eb = 0, bs = i;\n                    for (var j = 0; j < 286; ++j)\n                        lf[j] = 0;\n                    for (var j = 0; j < 30; ++j)\n                        df[j] = 0;\n                }\n                //  len    dist   chain\n                var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n                if (rem > 2 && hv == hsh(i - dif)) {\n                    var maxn = Math.min(n, rem) - 1;\n                    var maxd = Math.min(32767, i);\n                    // max possible length\n                    // not capped at dif because decompressors implement \"rolling\" index population\n                    var ml = Math.min(258, rem);\n                    while (dif <= maxd && --ch_1 && imod != pimod) {\n                        if (dat[i + l] == dat[i + l - dif]) {\n                            var nl = 0;\n                            for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n                                ;\n                            if (nl > l) {\n                                l = nl, d = dif;\n                                // break out early when we reach \"nice\" (we are satisfied enough)\n                                if (nl > maxn)\n                                    break;\n                                // now, find the rarest 2-byte sequence within this\n                                // length of literals and search for that instead.\n                                // Much faster than just using the start\n                                var mmd = Math.min(dif, nl - 2);\n                                var md = 0;\n                                for (var j = 0; j < mmd; ++j) {\n                                    var ti = (i - dif + j + 32768) & 32767;\n                                    var pti = prev[ti];\n                                    var cd = (ti - pti + 32768) & 32767;\n                                    if (cd > md)\n                                        md = cd, pimod = ti;\n                                }\n                            }\n                        }\n                        // check the previous match\n                        imod = pimod, pimod = prev[imod];\n                        dif += (imod - pimod + 32768) & 32767;\n                    }\n                }\n                // d will be nonzero only when a match was found\n                if (d) {\n                    // store both dist and len data in one Uint32\n                    // Make sure this is recognized as a len/dist with 28th bit (2^28)\n                    syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n                    var lin = revfl[l] & 31, din = revfd[d] & 31;\n                    eb += fleb[lin] + fdeb[din];\n                    ++lf[257 + lin];\n                    ++df[din];\n                    wi = i + l;\n                    ++lc_1;\n                }\n                else {\n                    syms[li++] = dat[i];\n                    ++lf[dat[i]];\n                }\n            }\n        }\n        pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n        // this is the easiest way to avoid needing to maintain state\n        if (!lst)\n            pos = wfblk(w, pos, et);\n    }\n    return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n    var t = new u32(256);\n    for (var i = 0; i < 256; ++i) {\n        var c = i, k = 9;\n        while (--k)\n            c = ((c & 1) && 0xEDB88320) ^ (c >>> 1);\n        t[i] = c;\n    }\n    return t;\n})();\n// CRC32\nvar crc = function () {\n    var c = 0xFFFFFFFF;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var cr = c;\n            for (var i = 0; i < d.length; ++i)\n                cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n            c = cr;\n        },\n        d: function () { return c ^ 0xFFFFFFFF; }\n    };\n};\n// Alder32\nvar adler = function () {\n    var a = 1, b = 0;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var n = a, m = b;\n            var l = d.length;\n            for (var i = 0; i != l;) {\n                var e = Math.min(i + 5552, l);\n                for (; i < e; ++i)\n                    n += d[i], m += n;\n                n %= 65521, m %= 65521;\n            }\n            a = n, b = m;\n        },\n        d: function () { return ((a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8)) + ((a & 255) << 23) * 2; }\n    };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n    return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n    var o = {};\n    for (var k in a)\n        o[k] = a[k];\n    for (var k in b)\n        o[k] = b[k];\n    return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n    var dt = fn();\n    var st = fn.toString();\n    var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/ /g, '').split(',');\n    for (var i = 0; i < dt.length; ++i) {\n        var v = dt[i], k = ks[i];\n        if (typeof v == 'function') {\n            fnStr += ';' + k + '=';\n            var st_1 = v.toString();\n            if (v.prototype) {\n                // for global objects\n                if (st_1.indexOf('[native code]') != -1) {\n                    var spInd = st_1.indexOf(' ', 8) + 1;\n                    fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n                }\n                else {\n                    fnStr += st_1;\n                    for (var t in v.prototype)\n                        fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n                }\n            }\n            else\n                fnStr += st_1;\n        }\n        else\n            td[k] = v;\n    }\n    return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n    var tl = [];\n    for (var k in v) {\n        if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32)\n            tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n    }\n    return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n    var _a;\n    if (!ch[id]) {\n        var fnStr = '', td_1 = {}, m = fns.length - 1;\n        for (var i = 0; i < m; ++i)\n            _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n        ch[id] = wcln(fns[m], fnStr, td_1);\n    }\n    var td = mrg({}, ch[id][1]);\n    return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n    var w = wrkr(fns, init, id, function (err, dat) {\n        w.terminate();\n        cb(err, dat);\n    });\n    if (!opts.consume)\n        dat = new u8(dat);\n    w.postMessage([dat, opts], [dat.buffer]);\n    return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n    strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n    return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n    var t;\n    var w = wrkr(fns, init, id, function (err, dat) {\n        if (err)\n            w.terminate(), strm.ondata.call(strm, err);\n        else {\n            if (dat[1])\n                w.terminate();\n            strm.ondata.call(strm, err, dat[0], dat[1]);\n        }\n    });\n    w.postMessage(opts);\n    strm.push = function (d, f) {\n        if (t)\n            throw 'stream finished';\n        if (!strm.ondata)\n            throw 'no stream handler';\n        w.postMessage([d, t = f], [d.buffer]);\n    };\n    strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16)) + (d[b + 3] << 23) * 2; };\n// write bytes\nvar wbytes = function (d, b, v) {\n    for (; v; ++b)\n        d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n    var fn = o.filename;\n    c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n    if (o.mtime != 0)\n        wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n    if (fn) {\n        c[3] = 8;\n        for (var i = 0; i <= fn.length; ++i)\n            c[i + 10] = fn.charCodeAt(i);\n    }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n    if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n        throw 'invalid gzip data';\n    var flg = d[3];\n    var st = 10;\n    if (flg & 4)\n        st += d[10] | (d[11] << 8) + 2;\n    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n        ;\n    return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n    var l = d.length;\n    return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) + (2 * (d[l - 1] << 23));\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n    var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n    c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n    if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n        throw 'invalid zlib data';\n    if (d[1] & 32)\n        throw 'invalid zlib data: preset dictionaries not supported';\n};\nfunction AsyncCmpStrm(opts, cb) {\n    if (!cb && typeof opts == 'function')\n        cb = opts, opts = {};\n    this.ondata = cb;\n    return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n    function Deflate(opts, cb) {\n        if (!cb && typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        this.o = opts || {};\n    }\n    Deflate.prototype.p = function (c, f) {\n        this.ondata(dopt(c, this.o, 0, 0, !f), f);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Deflate.prototype.push = function (chunk, final) {\n        if (this.d)\n            throw 'stream finished';\n        if (!this.ondata)\n            throw 'no stream handler';\n        this.d = final;\n        this.p(chunk, final || false);\n    };\n    return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n    function AsyncDeflate(opts, cb) {\n        astrmify([\n            bDflt,\n            function () { return [astrm, Deflate]; }\n        ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n            var strm = new Deflate(ev.data);\n            onmessage = astrm(strm);\n        }, 6);\n    }\n    return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return cbify(data, opts, [\n        bDflt,\n    ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n    if (opts === void 0) { opts = {}; }\n    return dopt(data, opts, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates an inflation stream\n     * @param cb The callback to call whenever data is inflated\n     */\n    function Inflate(cb) {\n        this.s = {};\n        this.p = new u8(0);\n        this.ondata = cb;\n    }\n    Inflate.prototype.e = function (c) {\n        if (this.d)\n            throw 'stream finished';\n        if (!this.ondata)\n            throw 'no stream handler';\n        var l = this.p.length;\n        var n = new u8(l + c.length);\n        n.set(this.p), n.set(c, l), this.p = n;\n    };\n    Inflate.prototype.c = function (final) {\n        this.d = this.s.i = final || false;\n        var bts = this.s.b;\n        var dt = inflt(this.p, this.o, this.s);\n        this.ondata(slc(dt, bts, this.s.b), this.d);\n        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n        this.p = slc(this.p, (this.s.p / 8) >> 0), this.s.p &= 7;\n    };\n    /**\n     * Pushes a chunk to be inflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the final chunk\n     */\n    Inflate.prototype.push = function (chunk, final) {\n        this.e(chunk), this.c(final);\n    };\n    return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates an asynchronous inflation stream\n     * @param cb The callback to call whenever data is deflated\n     */\n    function AsyncInflate(cb) {\n        this.ondata = cb;\n        astrmify([\n            bInflt,\n            function () { return [astrm, Inflate]; }\n        ], this, 0, function () {\n            var strm = new Inflate();\n            onmessage = astrm(strm);\n        }, 7);\n    }\n    return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return cbify(data, opts, [\n        bInflt\n    ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n    return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n    function Gzip(opts, cb) {\n        this.c = crc();\n        this.l = 0;\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gzip.prototype.push = function (chunk, final) {\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Gzip.prototype.p = function (c, f) {\n        this.c.p(c);\n        this.l += c.length;\n        var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n        if (this.v)\n            gzh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n        this.ondata(raw, f);\n    };\n    return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n    function AsyncGzip(opts, cb) {\n        astrmify([\n            bDflt,\n            gze,\n            function () { return [astrm, Deflate, Gzip]; }\n        ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n            var strm = new Gzip(ev.data);\n            onmessage = astrm(strm);\n        }, 8);\n    }\n    return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return cbify(data, opts, [\n        bDflt,\n        gze,\n        function () { return [gzipSync]; }\n    ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n    if (opts === void 0) { opts = {}; }\n    var c = crc(), l = data.length;\n    c.p(data);\n    var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n    return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n    /**\n     * Creates a GUNZIP stream\n     * @param cb The callback to call whenever data is inflated\n     */\n    function Gunzip(cb) {\n        this.v = 1;\n        Inflate.call(this, cb);\n    }\n    /**\n     * Pushes a chunk to be GUNZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gunzip.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        if (this.v) {\n            var s = gzs(this.p);\n            if (s >= this.p.length && !final)\n                return;\n            this.p = this.p.subarray(s), this.v = 0;\n        }\n        if (final) {\n            if (this.p.length < 8)\n                throw 'invalid gzip stream';\n            this.p = this.p.subarray(0, -8);\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n    };\n    return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n    /**\n     * Creates an asynchronous GUNZIP stream\n     * @param cb The callback to call whenever data is deflated\n     */\n    function AsyncGunzip(cb) {\n        this.ondata = cb;\n        astrmify([\n            bInflt,\n            guze,\n            function () { return [astrm, Inflate, Gunzip]; }\n        ], this, 0, function () {\n            var strm = new Gunzip();\n            onmessage = astrm(strm);\n        }, 9);\n    }\n    return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return cbify(data, opts, [\n        bInflt,\n        guze,\n        function () { return [gunzipSync]; }\n    ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n    return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n    function Zlib(opts, cb) {\n        this.c = adler();\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be zlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Zlib.prototype.push = function (chunk, final) {\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Zlib.prototype.p = function (c, f) {\n        this.c.p(c);\n        var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n        if (this.v)\n            zlh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 4, this.c.d());\n        this.ondata(raw, f);\n    };\n    return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n    function AsyncZlib(opts, cb) {\n        astrmify([\n            bDflt,\n            zle,\n            function () { return [astrm, Deflate, Zlib]; }\n        ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n            var strm = new Zlib(ev.data);\n            onmessage = astrm(strm);\n        }, 10);\n    }\n    return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return cbify(data, opts, [\n        bDflt,\n        zle,\n        function () { return [zlibSync]; }\n    ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n    if (opts === void 0) { opts = {}; }\n    var a = adler();\n    a.p(data);\n    var d = dopt(data, opts, 2, 4);\n    return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n    /**\n     * Creates a Zlib decompression stream\n     * @param cb The callback to call whenever data is inflated\n     */\n    function Unzlib(cb) {\n        this.v = 1;\n        Inflate.call(this, cb);\n    }\n    /**\n     * Pushes a chunk to be unzlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzlib.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        if (this.v) {\n            if (this.p.length < 2 && !final)\n                return;\n            this.p = this.p.subarray(2), this.v = 0;\n        }\n        if (final) {\n            if (this.p.length < 4)\n                throw 'invalid zlib stream';\n            this.p = this.p.subarray(0, -4);\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n    };\n    return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n    /**\n     * Creates an asynchronous Zlib decompression stream\n     * @param cb The callback to call whenever data is deflated\n     */\n    function AsyncUnzlib(cb) {\n        this.ondata = cb;\n        astrmify([\n            bInflt,\n            zule,\n            function () { return [astrm, Inflate, Unzlib]; }\n        ], this, 0, function () {\n            var strm = new Unzlib();\n            onmessage = astrm(strm);\n        }, 11);\n    }\n    return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return cbify(data, opts, [\n        bInflt,\n        zule,\n        function () { return [unzlibSync]; }\n    ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n    return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n    /**\n     * Creates a decompression stream\n     * @param cb The callback to call whenever data is decompressed\n     */\n    function Decompress(cb) {\n        this.G = Gunzip;\n        this.I = Inflate;\n        this.Z = Unzlib;\n        this.ondata = cb;\n    }\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Decompress.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            throw 'no stream handler';\n        if (!this.s) {\n            if (this.p && this.p.length) {\n                var n = new u8(this.p.length + chunk.length);\n                n.set(this.p), n.set(chunk, this.p.length);\n            }\n            else\n                this.p = chunk;\n            if (this.p.length > 2) {\n                var _this_1 = this;\n                var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n                this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n                    ? new this.G(cb)\n                    : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n                        ? new this.I(cb)\n                        : new this.Z(cb);\n                this.s.push(this.p, final);\n                this.p = null;\n            }\n        }\n        else\n            this.s.push(chunk, final);\n    };\n    return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n    /**\n   * Creates an asynchronous decompression stream\n   * @param cb The callback to call whenever data is decompressed\n   */\n    function AsyncDecompress(cb) {\n        this.G = AsyncGunzip;\n        this.I = AsyncInflate;\n        this.Z = AsyncUnzlib;\n        this.ondata = cb;\n    }\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncDecompress.prototype.push = function (chunk, final) {\n        Decompress.prototype.push.call(this, chunk, final);\n    };\n    return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzip(data, opts, cb)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflate(data, opts, cb)\n            : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzipSync(data, out)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflateSync(data, out)\n            : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n    for (var k in d) {\n        var val = d[k], n = p + k;\n        if (val instanceof u8)\n            t[n] = [val, o];\n        else if (Array.isArray(val))\n            t[n] = [val[0], mrg(o, val[1])];\n        else\n            fltn(val, n + '/', t, o);\n    }\n};\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n    var l = str.length;\n    if (!latin1 && typeof TextEncoder != 'undefined')\n        return new TextEncoder().encode(str);\n    var ar = new u8(str.length + (str.length >>> 1));\n    var ai = 0;\n    var w = function (v) { ar[ai++] = v; };\n    for (var i = 0; i < l; ++i) {\n        if (ai + 5 > ar.length) {\n            var n = new u8(ai + 8 + ((l - i) << 1));\n            n.set(ar);\n            ar = n;\n        }\n        var c = str.charCodeAt(i);\n        if (c < 128 || latin1)\n            w(c);\n        else if (c < 2048)\n            w(192 | (c >>> 6)), w(128 | (c & 63));\n        else if (c > 55295 && c < 57344)\n            c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n                w(240 | (c >>> 18)), w(128 | ((c >>> 12) & 63)), w(128 | ((c >>> 6) & 63)), w(128 | (c & 63));\n        else\n            w(224 | (c >>> 12)), w(128 | ((c >>> 6) & 63)), w(128 | (c & 63));\n    }\n    return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n    var r = '';\n    if (!latin1 && typeof TextDecoder != 'undefined')\n        return new TextDecoder().decode(dat);\n    for (var i = 0; i < dat.length;) {\n        var c = dat[i++];\n        if (c < 128 || latin1)\n            r += String.fromCharCode(c);\n        else if (c < 224)\n            r += String.fromCharCode((c & 31) << 6 | (dat[i++] & 63));\n        else if (c < 240)\n            r += String.fromCharCode((c & 15) << 12 | (dat[i++] & 63) << 6 | (dat[i++] & 63));\n        else\n            c = ((c & 15) << 18 | (dat[i++] & 63) << 12 | (dat[i++] & 63) << 6 | (dat[i++] & 63)) - 65536,\n                r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n    }\n    return r;\n}\n;\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n    var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;\n    var _a = z ? z64e(d, es) : [b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n    return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n    for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n        ;\n    return [b4(d, b + 12), b4(d, b + 4), b4(d, b + 20)];\n};\n// write zip header\nvar wzh = function (d, b, c, cmp, su, fn, u, o, ce, t) {\n    var fl = fn.length, l = cmp.length;\n    wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n    if (ce != null)\n        d[b] = 20, b += 2;\n    d[b] = 20, b += 2; // spec compliance? what's that?\n    d[b++] = (t == 8 && (o.level == 1 ? 6 : o.level < 6 ? 4 : o.level == 9 ? 2 : 0)), d[b++] = u && 8;\n    d[b] = t, b += 2;\n    var dt = new Date(o.mtime || Date.now()), y = dt.getFullYear() - 1980;\n    if (y < 0 || y > 119)\n        throw 'date not in range 1980-2099';\n    wbytes(d, b, ((y << 24) * 2) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1));\n    b += 4;\n    wbytes(d, b, c);\n    wbytes(d, b + 4, l);\n    wbytes(d, b + 8, su);\n    wbytes(d, b + 12, fl), b += 16; // skip extra field, comment\n    if (ce != null)\n        wbytes(d, b += 10, ce), b += 4;\n    d.set(fn, b);\n    b += fl;\n    if (ce == null)\n        d.set(cmp, b);\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n    wbytes(o, b, 0x6054B50); // skip disk\n    wbytes(o, b + 8, c);\n    wbytes(o, b + 10, c);\n    wbytes(o, b + 12, d);\n    wbytes(o, b + 16, e);\n};\nexport function zip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        throw 'no callback';\n    var r = {};\n    fltn(data, '', r, opts);\n    var k = Object.keys(r);\n    var lft = k.length, o = 0, tot = 0;\n    var slft = lft, files = new Array(lft);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var cbf = function () {\n        var out = new u8(tot + 22), oe = o, cdl = tot - o;\n        tot = 0;\n        for (var i = 0; i < slft; ++i) {\n            var f = files[i];\n            try {\n                wzh(out, tot, f.c, f.d, f.m, f.n, f.u, f.p, null, f.t);\n                wzh(out, o, f.c, f.d, f.m, f.n, f.u, f.p, tot, f.t), o += 46 + f.n.length, tot += 30 + f.n.length + f.d.length;\n            }\n            catch (e) {\n                return cb(e, null);\n            }\n        }\n        wzf(out, o, files.length, cdl, oe);\n        cb(null, out);\n    };\n    if (!lft)\n        cbf();\n    var _loop_1 = function (i) {\n        var fn = k[i];\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var c = crc(), m = file.length;\n        c.p(file);\n        var n = strToU8(fn), s = n.length;\n        var t = p.level == 0 ? 0 : 8;\n        var cbl = function (e, d) {\n            if (e) {\n                tAll();\n                cb(e, null);\n            }\n            else {\n                var l = d.length;\n                files[i] = {\n                    t: t,\n                    d: d,\n                    m: m,\n                    c: c.d(),\n                    u: fn.length != l,\n                    n: n,\n                    p: p\n                };\n                o += 30 + s + l;\n                tot += 76 + 2 * s + l;\n                if (!--lft)\n                    cbf();\n            }\n        };\n        if (n.length > 65535)\n            cbl('filename too long', null);\n        if (!t)\n            cbl(null, file);\n        else if (m < 160000) {\n            try {\n                cbl(null, deflateSync(file, p));\n            }\n            catch (e) {\n                cbl(e, null);\n            }\n        }\n        else\n            term.push(deflate(file, p, cbl));\n    };\n    // Cannot use lft because it can decrease\n    for (var i = 0; i < slft; ++i) {\n        _loop_1(i);\n    }\n    return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n    if (opts === void 0) { opts = {}; }\n    var r = {};\n    var files = [];\n    fltn(data, '', r, opts);\n    var o = 0;\n    var tot = 0;\n    for (var fn in r) {\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var t = p.level == 0 ? 0 : 8;\n        var n = strToU8(fn), s = n.length;\n        if (n.length > 65535)\n            throw 'filename too long';\n        var d = t ? deflateSync(file, p) : file, l = d.length;\n        var c = crc();\n        c.p(file);\n        files.push({\n            t: t,\n            d: d,\n            m: file.length,\n            c: c.d(),\n            u: fn.length != s,\n            n: n,\n            o: o,\n            p: p\n        });\n        o += 30 + s + l;\n        tot += 76 + 2 * s + l;\n    }\n    var out = new u8(tot + 22), oe = o, cdl = tot - o;\n    for (var i = 0; i < files.length; ++i) {\n        var f = files[i];\n        wzh(out, f.o, f.c, f.d, f.m, f.n, f.u, f.p, null, f.t);\n        wzh(out, o, f.c, f.d, f.m, f.n, f.u, f.p, f.o, f.t), o += 46 + f.n.length;\n    }\n    wzf(out, o, files.length, cdl, oe);\n    return out;\n}\n/**\n * Asynchronously decompresses a ZIP archive\n * @param data The raw compressed ZIP file\n * @param cb The callback to call with the decompressed files\n * @returns A function that can be used to immediately terminate the unzipping\n */\nexport function unzip(data, cb) {\n    if (typeof cb != 'function')\n        throw 'no callback';\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var files = {};\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558) {\n            cb('invalid zip file', null);\n            return;\n        }\n    }\n    ;\n    var lft = b2(data, e + 8);\n    if (!lft)\n        cb(null, {});\n    var c = lft;\n    var o = b4(data, e + 16);\n    var z = o == 4294967295;\n    if (z) {\n        e = b4(data, e - 12);\n        if (b4(data, e) != 0x6064B50)\n            throw 'invalid zip file';\n        c = lft = b4(data, e + 32);\n        o = b4(data, e + 48);\n    }\n    var _loop_2 = function (i) {\n        var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n        o = no;\n        var cbl = function (e, d) {\n            if (e) {\n                tAll();\n                cb(e, null);\n            }\n            else {\n                files[fn] = d;\n                if (!--lft)\n                    cb(null, files);\n            }\n        };\n        if (!c_1)\n            cbl(null, slc(data, b, b + sc));\n        else if (c_1 == 8) {\n            var infl = data.subarray(b, b + sc);\n            if (sc < 320000) {\n                try {\n                    cbl(null, inflateSync(infl, new u8(su)));\n                }\n                catch (e) {\n                    cbl(e, null);\n                }\n            }\n            else\n                term.push(inflate(infl, { size: su }, cbl));\n        }\n        else\n            cbl('unknown compression type ' + c_1, null);\n    };\n    for (var i = 0; i < c; ++i) {\n        _loop_2(i);\n    }\n    return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @returns The decompressed files\n */\nexport function unzipSync(data) {\n    var files = {};\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558)\n            throw 'invalid zip file';\n    }\n    ;\n    var c = b2(data, e + 8);\n    if (!c)\n        return {};\n    var o = b4(data, e + 16);\n    var z = o == 4294967295;\n    if (z) {\n        e = b4(data, e - 12);\n        if (b4(data, e) != 0x6064B50)\n            throw 'invalid zip file';\n        c = b4(data, e + 32);\n        o = b4(data, e + 48);\n    }\n    for (var i = 0; i < c; ++i) {\n        var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n        o = no;\n        if (!c_2)\n            files[fn] = slc(data, b, b + sc);\n        else if (c_2 == 8)\n            files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n        else\n            throw 'unknown compression type ' + c_2;\n    }\n    return files;\n}\n","import type { eventWithTime, mutationCallbackParam } from '../types/rrweb-types'\nimport { INCREMENTAL_SNAPSHOT_EVENT_TYPE, MUTATION_SOURCE_TYPE } from './sessionrecording-utils'\nimport type { rrwebRecord } from '../types/rrweb'\nimport { BucketedRateLimiter } from '@posthog/core'\nimport { logger } from '../../../utils/logger'\n\nexport class MutationThrottler {\n    private _loggedTracker: Record<string, boolean> = {}\n    private _rateLimiter: BucketedRateLimiter<number>\n\n    constructor(\n        private readonly _rrweb: rrwebRecord,\n        private readonly _options: {\n            bucketSize?: number\n            refillRate?: number\n            onBlockedNode?: (id: number, node: Node | null) => void\n        } = {}\n    ) {\n        this._rateLimiter = new BucketedRateLimiter({\n            bucketSize: this._options.bucketSize ?? 100,\n            refillRate: this._options.refillRate ?? 10,\n            refillInterval: 1000, // one second\n            _onBucketRateLimited: this._onNodeRateLimited,\n            _logger: logger,\n        })\n    }\n\n    private _onNodeRateLimited = (key: number) => {\n        if (!this._loggedTracker[key]) {\n            this._loggedTracker[key] = true\n            const node = this._getNode(key)\n            this._options.onBlockedNode?.(key, node)\n        }\n    }\n\n    private _getNodeOrRelevantParent = (id: number): [number, Node | null] => {\n        // For some nodes we know they are part of a larger tree such as an SVG.\n        // For those we want to block the entire node, not just the specific attribute\n\n        const node = this._getNode(id)\n\n        // Check if the node is an Element and then find the closest parent that is an SVG\n        if (node?.nodeName !== 'svg' && node instanceof Element) {\n            const closestSVG = node.closest('svg')\n\n            if (closestSVG) {\n                return [this._rrweb.mirror.getId(closestSVG), closestSVG]\n            }\n        }\n\n        return [id, node]\n    }\n\n    private _getNode = (id: number) => this._rrweb.mirror.getNode(id)\n\n    private _numberOfChanges = (data: Partial<mutationCallbackParam>) => {\n        return (\n            (data.removes?.length ?? 0) +\n            (data.attributes?.length ?? 0) +\n            (data.texts?.length ?? 0) +\n            (data.adds?.length ?? 0)\n        )\n    }\n\n    public throttleMutations = (event: eventWithTime) => {\n        if (event.type !== INCREMENTAL_SNAPSHOT_EVENT_TYPE || event.data.source !== MUTATION_SOURCE_TYPE) {\n            return event\n        }\n\n        const data = event.data as Partial<mutationCallbackParam>\n        const initialMutationCount = this._numberOfChanges(data)\n\n        if (data.attributes) {\n            // Most problematic mutations come from attrs where the style or minor properties are changed rapidly\n            data.attributes = data.attributes.filter((attr) => {\n                const [nodeId] = this._getNodeOrRelevantParent(attr.id)\n\n                const isRateLimited = this._rateLimiter.consumeRateLimit(nodeId)\n\n                if (isRateLimited) {\n                    return false\n                }\n\n                return attr\n            })\n        }\n\n        // Check if every part of the mutation is empty in which case there is nothing to do\n        const mutationCount = this._numberOfChanges(data)\n\n        if (mutationCount === 0 && initialMutationCount !== mutationCount) {\n            // If we have modified the mutation count and the remaining count is 0, then we don't need the event.\n            return\n        }\n        return event\n    }\n\n    public reset() {\n        this._loggedTracker = {}\n    }\n\n    public stop() {\n        this._rateLimiter.stop()\n        this.reset()\n    }\n}\n","import { isNumber, isObject, isString } from '@posthog/core'\nimport { SESSION_RECORDING_FLUSHED_SIZE } from '../../../constants'\nimport { PostHog } from '../../../posthog-core'\n\ninterface FlushedSize {\n    sessionId: string\n    size: number\n}\n\nfunction isFlushedSize(value: unknown): value is FlushedSize {\n    return isObject(value) && isString((value as FlushedSize).sessionId) && isNumber((value as FlushedSize).size)\n}\n\nexport class FlushedSizeTracker {\n    private readonly _getProperty: (property_name: string) => unknown\n    private readonly _setProperty: (prop: string, to: any) => void\n\n    constructor(posthog: PostHog) {\n        if (!posthog.persistence) {\n            throw new Error('it is not valid to not have persistence and be this far into setting up the application')\n        }\n\n        this._getProperty = posthog.get_property.bind(posthog)\n        this._setProperty = posthog.persistence.set_property.bind(posthog.persistence)\n    }\n\n    trackSize(sessionId: string, size: number) {\n        this._setProperty(SESSION_RECORDING_FLUSHED_SIZE, {\n            sessionId,\n            size: this.currentTrackedSize(sessionId) + size,\n        })\n    }\n\n    currentTrackedSize(sessionId: string): number {\n        const stored = this._getProperty(SESSION_RECORDING_FLUSHED_SIZE)\n        return isFlushedSize(stored) && stored.sessionId === sessionId ? stored.size : 0\n    }\n}\n","import { isArray, isUndefined, clampToRange } from '@posthog/core'\nimport { logger } from '../utils/logger'\n\nexport function appendArray(currentValue: string[] | undefined, sampleType: string | string[]): string[] {\n    return [...(currentValue ? currentValue : []), ...(isArray(sampleType) ? sampleType : [sampleType])]\n}\n\nexport function updateThreshold(currentValue: number | undefined, percent: number): number {\n    return (isUndefined(currentValue) ? 1 : currentValue) * percent\n}\n\nexport function simpleHash(str: string) {\n    let hash = 0\n    for (let i = 0; i < str.length; i++) {\n        hash = (hash << 5) - hash + str.charCodeAt(i) // (hash * 31) + char code\n        hash |= 0 // Convert to 32bit integer\n    }\n    return Math.abs(hash)\n}\n\n/*\n * receives percent as a number between 0 and 1\n */\nexport function sampleOnProperty(prop: string, percent: number): boolean {\n    return simpleHash(prop) % 100 < clampToRange(percent * 100, 0, 100, logger)\n}\n","export const isValidRegex = function (str: string): boolean {\n    try {\n        new RegExp(str)\n    } catch {\n        return false\n    }\n    return true\n}\n\nexport const isMatchingRegex = function (value: string, pattern: string): boolean {\n    if (!isValidRegex(pattern)) return false\n\n    try {\n        return new RegExp(pattern).test(value)\n    } catch {\n        return false\n    }\n}\n","import { isArray, isNull, isUndefined } from '@posthog/core'\nimport { jsonStringify } from '../request'\nimport { PropertyFilters, PropertyOperator } from '../posthog-surveys-types'\nimport type { Properties, SessionRecordingTriggerPropertyFilter } from '../types'\nimport { isMatchingRegex } from './regex-utils'\n\nexport function getPersonPropertiesHash(\n    distinct_id: string,\n    userPropertiesToSet?: Properties,\n    userPropertiesToSetOnce?: Properties\n): string {\n    return jsonStringify({ distinct_id, userPropertiesToSet, userPropertiesToSetOnce })\n}\n\nexport const propertyComparisons: Record<PropertyOperator, (targets: string[], values: string[]) => boolean> = {\n    exact: (targets, values) => values.some((value) => targets.some((target) => value === target)),\n    is_not: (targets, values) => values.every((value) => targets.every((target) => value !== target)),\n    regex: (targets, values) => values.some((value) => targets.some((target) => isMatchingRegex(value, target))),\n    not_regex: (targets, values) => values.every((value) => targets.every((target) => !isMatchingRegex(value, target))),\n    icontains: (targets, values) =>\n        values.map(toLowerCase).some((value) => targets.map(toLowerCase).some((target) => value.includes(target))),\n    not_icontains: (targets, values) =>\n        values.map(toLowerCase).every((value) => targets.map(toLowerCase).every((target) => !value.includes(target))),\n    gt: (targets, values) =>\n        values.some((value) => {\n            const numValue = parseFloat(value)\n            return !isNaN(numValue) && targets.some((t) => numValue > parseFloat(t))\n        }),\n    lt: (targets, values) =>\n        values.some((value) => {\n            const numValue = parseFloat(value)\n            return !isNaN(numValue) && targets.some((t) => numValue < parseFloat(t))\n        }),\n}\n\nconst toLowerCase = (v: string): string => v.toLowerCase()\n\n// Operators whose semantics mean \"property is not X\". When the property being\n// filtered on is missing or null, these match — absence of the property\n// satisfies a \"not equal to X\" check. This aligns with how PostHog's feature\n// flag matchers (posthog/queries/base.py, rust/feature-flags) treat missing\n// properties for negative operators.\nconst NEGATIVE_OPERATORS: ReadonlySet<string> = new Set(['is_not', 'not_icontains', 'not_regex'])\n\n/**\n * Evaluate trigger property filters (WHERE clauses) against event and person properties.\n * All filters must match (implicit AND). Returns true if no filters are present.\n */\nexport function matchTriggerPropertyFilters(\n    filters: SessionRecordingTriggerPropertyFilter[] | undefined,\n    eventProperties: Properties | undefined,\n    personProperties: Properties | undefined\n): boolean {\n    if (!filters || filters.length === 0) {\n        return true\n    }\n\n    return filters.every((filter) => {\n        const source = filter.type === 'person' ? personProperties : eventProperties\n        const propertyValue = source?.[filter.key]\n        const operator = filter.operator || 'exact'\n\n        // Missing or null property: for negative operators, absence counts as a\n        // match (nothing can't equal EU, so \"is_not EU\" is satisfied). For\n        // positive operators, we can't confirm a match without a value.\n        if (isUndefined(propertyValue) || isNull(propertyValue)) {\n            return NEGATIVE_OPERATORS.has(operator)\n        }\n\n        const comparisonFunction = propertyComparisons[operator as PropertyOperator]\n        if (!comparisonFunction) {\n            return false\n        }\n\n        if (isUndefined(filter.value) || isNull(filter.value)) {\n            return false\n        }\n\n        // Normalize filter value and property value to string arrays for comparison\n        const targetValues = isArray(filter.value) ? filter.value.map(String) : [String(filter.value)]\n        const actualValues = isArray(propertyValue) ? propertyValue.map(String) : [String(propertyValue)]\n\n        return comparisonFunction(targetValues, actualValues)\n    })\n}\n\nexport function matchPropertyFilters(\n    propertyFilters: PropertyFilters | undefined,\n    eventProperties: Properties | undefined\n): boolean {\n    // if there are no property filters, it means we're only matching on event name\n    if (!propertyFilters) {\n        return true\n    }\n\n    return Object.entries(propertyFilters).every(([propertyName, filter]) => {\n        const eventPropertyValue = eventProperties?.[propertyName]\n\n        if (isUndefined(eventPropertyValue) || isNull(eventPropertyValue)) {\n            return false\n        }\n\n        // convert event property to string array for comparison\n        const eventValues = [String(eventPropertyValue)]\n\n        const comparisonFunction = propertyComparisons[filter.operator]\n        if (!comparisonFunction) {\n            return false\n        }\n\n        return comparisonFunction(filter.values, eventValues)\n    })\n}\n","import { PostHog } from '../../../posthog-core'\nimport {\n    CaptureResult,\n    SessionRecordingPersistedConfig,\n    SessionRecordingTriggerGroup,\n    SessionStartReason,\n} from '../../../types'\nimport {\n    SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n    SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n    SESSION_RECORDING_IS_SAMPLED,\n    SESSION_RECORDING_SAMPLE_RATE,\n    SESSION_RECORDING_PAST_MINIMUM_DURATION,\n    SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX,\n    SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX,\n    SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX,\n    SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS,\n    SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG,\n    SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT,\n    STORED_PERSON_PROPERTIES_KEY,\n} from '../../../constants'\nimport {\n    EventTriggerMatching,\n    LinkedFlagMatching,\n    URLTriggerMatching,\n    TriggerGroupMatching,\n    SessionRecordingStatus,\n    allMatchSessionRecordingStatus,\n    anyMatchSessionRecordingStatus,\n    triggerGroupsMatchSessionRecordingStatus,\n    TriggerType,\n    AndTriggerMatching,\n    OrTriggerMatching,\n    TriggerStatusMatching,\n    TRIGGER_PENDING,\n} from './triggerMatching'\nimport { sampleOnProperty } from '../../sampling'\nimport { isBoolean, isNull, isNullish, isNumber, isObject, isUndefined } from '@posthog/core'\nimport { createLogger } from '../../../utils/logger'\nimport { matchTriggerPropertyFilters } from '../../../utils/property-utils'\n\nconst logger = createLogger('[SessionRecording]')\n\n/**\n * Decisions are stored as `sessionId` (sampled in) or `'!' + sessionId` (sampled out), so another\n * session can never inherit them. Anything else (legacy `true`/`false`, another session's decision)\n * decodes to null and is re-decided — safe, since `sampleOnProperty` is deterministic per session id.\n */\nconst NOT_SAMPLED_PREFIX = '!'\n\nexport function encodeSamplingDecision(sessionId: string, isSampled: boolean): string {\n    return isSampled ? sessionId : NOT_SAMPLED_PREFIX + sessionId\n}\n\nexport function decodeSamplingDecision(storedValue: unknown, sessionId: string): boolean | null {\n    if (storedValue === sessionId) {\n        return true\n    }\n    if (storedValue === NOT_SAMPLED_PREFIX + sessionId) {\n        return false\n    }\n    return null\n}\n\n/**\n * Shared context that strategies need to access from the recorder\n */\nexport interface RecordingStrategyContext {\n    instance: PostHog\n    sessionId: string\n    isSampled: boolean | null\n    rrwebError: boolean\n    urlTriggerMatching: URLTriggerMatching\n    eventTriggerMatching: EventTriggerMatching\n    linkedFlagMatching: LinkedFlagMatching\n    remoteConfig: SessionRecordingPersistedConfig | undefined\n}\n\n/**\n * Strategy interface for handling different recording trigger configurations\n */\nexport interface RecordingStrategy {\n    /**\n     * Initialize the strategy with remote config\n     */\n    onRemoteConfig(config: SessionRecordingPersistedConfig): void\n\n    /**\n     * Get the current recording status\n     */\n    getStatus(context: RecordingStrategyContext): SessionRecordingStatus\n\n    /**\n     * Get the minimum duration for this session (if any)\n     */\n    getMinimumDuration(sessionId: string): number | null\n\n    /**\n     * Check URL triggers on each navigation\n     * Note: URL is read from window.location.href internally\n     */\n    checkUrlTriggers(\n        sessionId: string,\n        onPause: () => void,\n        onResume: () => void,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n    ): void\n\n    /**\n     * Setup event trigger listeners\n     */\n    setupEventTriggerListeners(\n        onEvent: (callback: (event: CaptureResult) => void) => () => void,\n        sessionId: string,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n    ): (() => void) | undefined\n\n    /**\n     * Make sampling decisions for the session\n     */\n    makeSamplingDecisions(sessionId: string): void\n\n    /**\n     * Ensure a sampling decision exists for this session, re-deciding from the strategy's own\n     * config when it is missing (e.g. wiped by posthog.reset()). No-op when sampling isn't configured.\n     */\n    ensureSamplingDecision(sessionId: string): void\n\n    /**\n     * Called after the initial buffer flush (performance optimization hook)\n     */\n    onFlushComplete(): void\n\n    /**\n     * Clean up persistence keys for conditional recording\n     */\n    clearConditionalRecordingPersistence(): void\n\n    /**\n     * Update session properties with active trigger information\n     */\n    updateActiveTriggers(sessionId: string): void\n\n    /**\n     * Check if triggers are in pending state (waiting for activation)\n     */\n    hasPendingTriggers(sessionId: string): boolean\n\n    /**\n     * Stop and cleanup the strategy\n     */\n    stop(): void\n}\n\n/**\n * V1 Strategy: Legacy trigger matching with global URL/Event/Flag triggers\n */\nexport class V1RecordingStrategy implements RecordingStrategy {\n    private _triggerStatusMatcher: TriggerStatusMatching | undefined\n    private _removeEventTriggerCaptureHook: (() => void) | undefined\n    private _sampleRate: number | null = null\n    private _recordingStatusFunction: typeof anyMatchSessionRecordingStatus = allMatchSessionRecordingStatus\n\n    constructor(\n        private readonly _instance: PostHog,\n        private readonly _urlTriggerMatching: URLTriggerMatching,\n        private readonly _eventTriggerMatching: EventTriggerMatching,\n        private readonly _linkedFlagMatching: LinkedFlagMatching,\n        private readonly _reportStarted: (reason: SessionStartReason, payload?: Record<string, any>) => void,\n        private readonly _tryTakeFullSnapshot: () => void\n    ) {}\n\n    onRemoteConfig(config: SessionRecordingPersistedConfig): void {\n        this._sampleRate = isNumber(config.sampleRate) ? config.sampleRate : null\n\n        // Setup trigger matching strategy (AND vs OR)\n        if (config.triggerMatchType === 'any') {\n            this._triggerStatusMatcher = new OrTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching])\n            this._recordingStatusFunction = anyMatchSessionRecordingStatus\n        } else {\n            // either the setting is \"ALL\" or we default to the most restrictive\n            this._triggerStatusMatcher = new AndTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching])\n            this._recordingStatusFunction = allMatchSessionRecordingStatus\n        }\n\n        this._instance.register_for_session({\n            [SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG]: config.triggerMatchType,\n        })\n\n        this._urlTriggerMatching.onConfig(config)\n        this._eventTriggerMatching.onConfig(config)\n\n        this._linkedFlagMatching.onConfig(config, (flag, variant) => {\n            this._reportStarted('linked_flag_matched', { flag, variant })\n        })\n    }\n\n    getStatus(context: RecordingStrategyContext): SessionRecordingStatus {\n        return this._recordingStatusFunction({\n            receivedFlags: true,\n            isRecordingEnabled: true,\n            isSampled: context.isSampled,\n            rrwebError: context.rrwebError,\n            urlTriggerMatching: context.urlTriggerMatching,\n            eventTriggerMatching: context.eventTriggerMatching,\n            linkedFlagMatching: context.linkedFlagMatching,\n            sessionId: context.sessionId,\n        })\n    }\n\n    getMinimumDuration(sessionId: string): number | null {\n        // V1: Minimum duration is global from config, doesn't need sessionId\n        void sessionId\n        const config = this._instance.get_property('$session_recording_remote_config') as\n            | SessionRecordingPersistedConfig\n            | undefined\n        const duration = config?.minimumDurationMilliseconds\n        return isNumber(duration) ? duration : null\n    }\n\n    checkUrlTriggers(\n        sessionId: string,\n        onPause: () => void,\n        onResume: () => void,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n    ): void {\n        this._urlTriggerMatching.checkUrlTriggerConditions(onPause, onResume, onActivate, sessionId)\n    }\n\n    setupEventTriggerListeners(\n        onEvent: (callback: (event: CaptureResult) => void) => () => void,\n        sessionId: string,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n    ): (() => void) | undefined {\n        if (this._eventTriggerMatching._eventTriggers.length === 0 || !isNullish(this._removeEventTriggerCaptureHook)) {\n            return undefined\n        }\n\n        this._removeEventTriggerCaptureHook = onEvent((event: CaptureResult) => {\n            try {\n                this._eventTriggerMatching.checkEventTriggerConditions(event.event, onActivate, sessionId)\n            } catch (e) {\n                logger.error('Could not activate event trigger', e)\n            }\n        })\n\n        return this._removeEventTriggerCaptureHook\n    }\n\n    makeSamplingDecisions(sessionId: string): void {\n        const currentSampleRate = this._sampleRate\n\n        if (!isNumber(currentSampleRate)) {\n            this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n            this._instance.persistence?.unregister(SESSION_RECORDING_SAMPLE_RATE)\n            return\n        }\n\n        const storedValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n        const storedSampleRate = this._instance.get_property(SESSION_RECORDING_SAMPLE_RATE)\n\n        const storedIsSampled = decodeSamplingDecision(storedValue, sessionId)\n\n        // Re-decide when the rate changed, or a legacy sampled-in decision predates rate storage.\n        // An explicit override stores null as the rate, so only undefined means legacy missing-rate.\n        const sampleRateChanged = isNumber(storedSampleRate) && storedSampleRate !== currentSampleRate\n        const sampledInWithoutStoredRate = isUndefined(storedSampleRate) && storedValue === sessionId\n        const makeDecision = sampleRateChanged || sampledInWithoutStoredRate || !isBoolean(storedIsSampled)\n        const shouldSample = makeDecision ? sampleOnProperty(sessionId, currentSampleRate) : storedIsSampled!\n\n        if (makeDecision) {\n            if (shouldSample) {\n                this._reportStarted('sampled')\n            } else {\n                logger.warn(\n                    `Sample rate (${currentSampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n                )\n            }\n        }\n\n        this._instance.persistence?.register({\n            [SESSION_RECORDING_IS_SAMPLED]: encodeSamplingDecision(sessionId, shouldSample),\n            [SESSION_RECORDING_SAMPLE_RATE]:\n                isNull(storedSampleRate) && storedValue === sessionId ? null : currentSampleRate,\n        })\n    }\n\n    ensureSamplingDecision(sessionId: string): void {\n        if (!isNumber(this._sampleRate)) {\n            return\n        }\n        const storedValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n        if (!isBoolean(decodeSamplingDecision(storedValue, sessionId))) {\n            this.makeSamplingDecisions(sessionId)\n        }\n    }\n\n    onFlushComplete(): void {\n        // V1 doesn't use this optimization\n    }\n\n    clearConditionalRecordingPersistence(): void {\n        this._instance.persistence?.unregister(SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION)\n        this._instance.persistence?.unregister(SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION)\n        this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n        this._instance.persistence?.unregister(SESSION_RECORDING_SAMPLE_RATE)\n        this._instance.persistence?.unregister(SESSION_RECORDING_PAST_MINIMUM_DURATION)\n    }\n\n    updateActiveTriggers(sessionId: string): void {\n        void sessionId\n        // V1 doesn't track active triggers in session properties\n    }\n\n    hasPendingTriggers(sessionId: string): boolean {\n        return this._triggerStatusMatcher?.triggerStatus(sessionId) === TRIGGER_PENDING\n    }\n\n    stop(): void {\n        this._removeEventTriggerCaptureHook?.()\n        this._removeEventTriggerCaptureHook = undefined\n        this._eventTriggerMatching.stop()\n        this._urlTriggerMatching.stop()\n        this._linkedFlagMatching.stop()\n    }\n}\n\n/**\n * V2 Strategy: Trigger groups with per-group sampling and union behavior\n */\nexport class V2TriggerGroupStrategy implements RecordingStrategy {\n    private _triggerGroupMatchers: TriggerGroupMatching[] = []\n    private _triggerGroupSamplingResults: Map<string, boolean> = new Map()\n    private _hasCompletedInitialFlush: boolean = false\n    private _removeEventTriggerCaptureHook: (() => void) | undefined\n\n    constructor(\n        private readonly _instance: PostHog,\n        private readonly _urlTriggerMatching: URLTriggerMatching,\n        private readonly _reportStarted: (reason: SessionStartReason, payload?: Record<string, any>) => void,\n        private readonly _tryAddCustomEvent: (tag: string, payload: any) => void\n    ) {}\n\n    onRemoteConfig(config: SessionRecordingPersistedConfig): void {\n        if (!config.triggerGroups || config.triggerGroups.length === 0) {\n            logger.warn('[V2Strategy] No trigger groups configured')\n            return\n        }\n\n        // Setup trigger group matchers\n        this._setupTriggerGroups(config.triggerGroups)\n\n        this._instance.register_for_session({\n            [SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG]: 'v2_trigger_groups',\n            [SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT]: config.triggerGroups.length,\n        })\n\n        // V2 needs URL blocklist (but not URL triggers)\n        this._urlTriggerMatching.onConfig(config)\n    }\n\n    getStatus(context: RecordingStrategyContext): SessionRecordingStatus {\n        return triggerGroupsMatchSessionRecordingStatus({\n            receivedFlags: true,\n            isRecordingEnabled: true,\n            isSampled: context.isSampled,\n            rrwebError: context.rrwebError,\n            urlTriggerMatching: context.urlTriggerMatching,\n            eventTriggerMatching: context.eventTriggerMatching,\n            linkedFlagMatching: context.linkedFlagMatching,\n            sessionId: context.sessionId,\n            triggerGroupMatchers: this._triggerGroupMatchers,\n            triggerGroupSamplingResults: this._triggerGroupSamplingResults,\n            minimumDuration: this.getMinimumDuration(context.sessionId),\n        })\n    }\n\n    getMinimumDuration(sessionId: string): number | null {\n        let lowestDuration: number | null = null\n\n        for (const matcher of this._triggerGroupMatchers) {\n            const groupStatus = matcher.triggerStatus(sessionId)\n\n            // Only consider activated groups - pending groups haven't triggered yet\n            if (groupStatus === 'trigger_activated') {\n                const groupDuration = matcher.group.minDurationMs\n                if (isNumber(groupDuration)) {\n                    if (isNull(lowestDuration) || groupDuration < lowestDuration) {\n                        lowestDuration = groupDuration\n                    }\n                }\n            }\n        }\n\n        return lowestDuration\n    }\n\n    checkUrlTriggers(\n        sessionId: string,\n        onPause: () => void,\n        onResume: () => void,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n    ): void {\n        // V2 doesn't use the global onActivate callback - each group activates itself\n        void onActivate\n\n        // Check URL blocklist (global, not per-group)\n        this._urlTriggerMatching.checkUrlBlocklist(onPause, onResume)\n\n        // Check URL triggers for each group\n        for (const matcher of this._triggerGroupMatchers) {\n            matcher.checkUrlTriggerConditions(\n                onPause,\n                onResume,\n                (triggerType) => {\n                    // Check group-level property filters before activating\n                    if (!this._checkGroupLevelProperties(matcher, undefined)) {\n                        return\n                    }\n\n                    matcher.activateTrigger(triggerType, sessionId)\n                    this.updateActiveTriggers(sessionId)\n                },\n                sessionId\n            )\n        }\n    }\n\n    setupEventTriggerListeners(\n        onEvent: (callback: (event: CaptureResult) => void) => () => void,\n        sessionId: string,\n        onActivate: (triggerType: TriggerType, matchDetail?: string) => void\n    ): (() => void) | undefined {\n        // V2 doesn't use the global onActivate callback - each group activates itself\n        void onActivate\n\n        this._removeEventTriggerCaptureHook = onEvent((event: CaptureResult) => {\n            // Performance optimization: Stop checking triggers after initial buffer flush\n            if (this._hasCompletedInitialFlush) {\n                logger.info('[SessionRecorder] Stopping trigger checks - initial buffer flushed')\n                this._removeEventTriggerCaptureHook?.()\n                this._removeEventTriggerCaptureHook = undefined\n                return\n            }\n\n            try {\n                // V2: Each group activates its own trigger with per-group persistence\n                for (const matcher of this._triggerGroupMatchers) {\n                    matcher.checkEventTriggerConditions(\n                        event.event,\n                        (triggerType) => {\n                            // Check group-level property filters\n                            if (!this._checkGroupLevelProperties(matcher, event.properties)) {\n                                return\n                            }\n\n                            // Check per-event property filters.\n                            // A group may contain multiple entries for the same event name with\n                            // different property filters — e.g. \"purchase amount > 100\" OR\n                            // \"purchase by a VIP\". Treat same-name entries as a disjunction:\n                            // activate if *any* matching clause's filters pass. An entry with no\n                            // properties is treated as an unconditional match (matching V1).\n                            const matchedTriggers = (matcher.group.conditions.events || []).filter(\n                                (t) => t.name === event.event\n                            )\n                            const personProperties = this._instance.get_property(STORED_PERSON_PROPERTIES_KEY)\n                            const anyMatched = matchedTriggers.some(\n                                (t) =>\n                                    !t.properties ||\n                                    t.properties.length === 0 ||\n                                    matchTriggerPropertyFilters(t.properties, event.properties, personProperties)\n                            )\n                            if (!anyMatched) {\n                                return\n                            }\n\n                            matcher.activateTrigger(triggerType, sessionId)\n                            this.updateActiveTriggers(sessionId)\n                        },\n                        sessionId\n                    )\n                }\n            } catch (e) {\n                logger.error('Could not activate event trigger for trigger groups', e)\n            }\n        })\n\n        return this._removeEventTriggerCaptureHook\n    }\n\n    makeSamplingDecisions(sessionId: string): void {\n        for (const matcher of this._triggerGroupMatchers) {\n            const group = matcher.group\n            const groupId = group.id\n            const sampleRate = group.sampleRate\n\n            // Check if we have a stored decision for this group\n            const storageKey = SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX + groupId\n            const storedValue = this._instance.get_property(storageKey)\n\n            // Parse stored decision:\n            // - object = current format with session ID, sample rate, and decision\n            // - sessionId string = legacy sampled-in decision for that session\n            // - false = legacy sampled-out decision without session/rate context (re-decide)\n            // - undefined/null = no decision yet\n            let storedDecision: boolean | null = null\n            let sessionChanged = false\n            let sampleRateChanged = false\n            let sampledInWithoutStoredRate = false\n\n            if (isObject(storedValue)) {\n                const storedSessionId = storedValue.sessionId\n                const storedSampleRate = storedValue.sampleRate\n                const storedSampled = storedValue.sampled\n                sessionChanged = typeof storedSessionId === 'string' && storedSessionId !== sessionId\n                sampleRateChanged = isNumber(storedSampleRate) && storedSampleRate !== sampleRate\n                storedDecision =\n                    storedSessionId === sessionId &&\n                    isNumber(storedSampleRate) &&\n                    storedSampleRate === sampleRate &&\n                    isBoolean(storedSampled)\n                        ? storedSampled\n                        : null\n            } else {\n                storedDecision = storedValue === sessionId ? true : null\n                sessionChanged = typeof storedValue === 'string' && storedValue !== sessionId\n                sampledInWithoutStoredRate = storedValue === sessionId\n            }\n\n            // Make new decision only if:\n            // 1. No stored decision exists (storedDecision is null/undefined), OR\n            // 2. Session changed (stored sessionId doesn't match current), OR\n            // 3. Sample rate changed since the stored decision was made\n            const makeDecision =\n                sessionChanged || sampleRateChanged || sampledInWithoutStoredRate || !isBoolean(storedDecision)\n            const shouldSample = makeDecision ? sampleOnProperty(sessionId + groupId, sampleRate) : storedDecision!\n\n            if (makeDecision) {\n                this._tryAddCustomEvent('triggerGroupSamplingDecisionMade', {\n                    group_id: groupId,\n                    group_name: group.name,\n                    sampleRate: sampleRate,\n                    isSampled: shouldSample,\n                })\n            }\n\n            // Store the decision\n            this._triggerGroupSamplingResults.set(groupId, shouldSample)\n            this._instance.persistence?.register({\n                [storageKey]: {\n                    sessionId,\n                    sampleRate,\n                    sampled: shouldSample,\n                },\n            })\n        }\n\n        // After all sampling decisions, register which groups are actively recording\n        this.updateActiveTriggers(sessionId)\n    }\n\n    ensureSamplingDecision(sessionId: string): void {\n        // V2 sampling is per trigger group and safe by default — a missing group\n        // decision reads as not sampled, so it can never leak an undecided flush\n        void sessionId\n    }\n\n    onFlushComplete(): void {\n        this._hasCompletedInitialFlush = true\n    }\n\n    clearConditionalRecordingPersistence(): void {\n        this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED)\n        this._instance.persistence?.unregister(SESSION_RECORDING_SAMPLE_RATE)\n        this._instance.persistence?.unregister(SESSION_RECORDING_PAST_MINIMUM_DURATION)\n\n        // V2: Clear per-group trigger keys\n        for (const matcher of this._triggerGroupMatchers) {\n            const groupId = matcher.group.id\n            this._instance.persistence?.unregister(SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX + groupId)\n            this._instance.persistence?.unregister(SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX + groupId)\n            this._instance.persistence?.unregister(SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX + groupId)\n        }\n    }\n\n    updateActiveTriggers(sessionId: string): void {\n        const recordingGroups: Array<{ id: string; name: string; matched: boolean; sampled: boolean }> = []\n\n        for (const matcher of this._triggerGroupMatchers) {\n            const group = matcher.group\n            const groupId = group.id\n            const triggerStatus = matcher.triggerStatus(sessionId)\n            const isMatched = triggerStatus === 'trigger_activated'\n            const isSampled = this._triggerGroupSamplingResults.get(groupId) === true\n\n            if (isMatched) {\n                recordingGroups.push({\n                    id: groupId,\n                    name: group.name,\n                    matched: true,\n                    sampled: isSampled,\n                })\n            }\n        }\n\n        this._instance.register_for_session({\n            [SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS]: recordingGroups,\n        })\n    }\n\n    hasPendingTriggers(sessionId: string): boolean {\n        // V2: Check if any group has pending triggers\n        for (const matcher of this._triggerGroupMatchers) {\n            if (matcher.triggerStatus(sessionId) === TRIGGER_PENDING) {\n                return true\n            }\n        }\n        return false\n    }\n\n    stop(): void {\n        this._removeEventTriggerCaptureHook?.()\n        this._removeEventTriggerCaptureHook = undefined\n        this._triggerGroupMatchers.forEach((matcher) => matcher.stop())\n        this._triggerGroupMatchers = []\n        this._triggerGroupSamplingResults.clear()\n        this._urlTriggerMatching.stop()\n    }\n\n    private _checkGroupLevelProperties(\n        matcher: TriggerGroupMatching,\n        eventProperties: Record<string, any> | undefined\n    ): boolean {\n        const groupProperties = matcher.group.conditions.properties\n        if (!groupProperties || groupProperties.length === 0) {\n            return true\n        }\n        const personProperties = this._instance.get_property(STORED_PERSON_PROPERTIES_KEY)\n        return matchTriggerPropertyFilters(groupProperties, eventProperties, personProperties)\n    }\n\n    private _setupTriggerGroups(groups: SessionRecordingTriggerGroup[]) {\n        // Clean up existing matchers\n        this._triggerGroupMatchers.forEach((matcher) => matcher.stop())\n        this._triggerGroupMatchers = []\n        this._triggerGroupSamplingResults.clear()\n\n        // Create a matcher for each group\n        for (const group of groups) {\n            const matcher = new TriggerGroupMatching(this._instance, group, (flag, variant) => {\n                this._reportStarted('linked_flag_matched', {\n                    flag,\n                    variant,\n                    group_id: group.id,\n                    group_name: group.name,\n                })\n            })\n            this._triggerGroupMatchers.push(matcher)\n        }\n    }\n}\n","/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n *\n * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts\n */\n\n// polyfill for IE11\nimport { window } from './utils/globals'\n\nimport { isNumber, isUndefined } from '@posthog/core'\n\nif (!Math.trunc) {\n    Math.trunc = function (v) {\n        return v < 0 ? Math.ceil(v) : Math.floor(v)\n    }\n}\n\n// polyfill for IE11\nif (!Number.isInteger) {\n    Number.isInteger = function (value) {\n        return isNumber(value) && isFinite(value) && Math.floor(value) === value\n    }\n}\n\n/** Represents a UUID as a 16-byte byte array. */\nexport class UUID {\n    /** @param bytes - The 16-byte byte array representation. */\n    constructor(readonly bytes: Readonly<Uint8Array>) {\n        if (bytes.length !== 16) {\n            throw new TypeError('not 128-bit length')\n        }\n    }\n\n    /**\n     * Builds a byte array from UUIDv7 field values.\n     *\n     * @param unixTsMs - A 48-bit `unix_ts_ms` field value.\n     * @param randA - A 12-bit `rand_a` field value.\n     * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.\n     * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.\n     */\n    static fromFieldsV7(unixTsMs: number, randA: number, randBHi: number, randBLo: number): UUID {\n        if (\n            !Number.isInteger(unixTsMs) ||\n            !Number.isInteger(randA) ||\n            !Number.isInteger(randBHi) ||\n            !Number.isInteger(randBLo) ||\n            unixTsMs < 0 ||\n            randA < 0 ||\n            randBHi < 0 ||\n            randBLo < 0 ||\n            unixTsMs > 0xffff_ffff_ffff ||\n            randA > 0xfff ||\n            randBHi > 0x3fff_ffff ||\n            randBLo > 0xffff_ffff\n        ) {\n            throw new RangeError('invalid field value')\n        }\n\n        const bytes = new Uint8Array(16)\n        bytes[0] = unixTsMs / 2 ** 40\n        bytes[1] = unixTsMs / 2 ** 32\n        bytes[2] = unixTsMs / 2 ** 24\n        bytes[3] = unixTsMs / 2 ** 16\n        bytes[4] = unixTsMs / 2 ** 8\n        bytes[5] = unixTsMs\n        bytes[6] = 0x70 | (randA >>> 8)\n        bytes[7] = randA\n        bytes[8] = 0x80 | (randBHi >>> 24)\n        bytes[9] = randBHi >>> 16\n        bytes[10] = randBHi >>> 8\n        bytes[11] = randBHi\n        bytes[12] = randBLo >>> 24\n        bytes[13] = randBLo >>> 16\n        bytes[14] = randBLo >>> 8\n        bytes[15] = randBLo\n        return new UUID(bytes)\n    }\n\n    /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */\n    toString(): string {\n        let text = ''\n        for (let i = 0; i < this.bytes.length; i++) {\n            text = text + (this.bytes[i] >>> 4).toString(16) + (this.bytes[i] & 0xf).toString(16)\n            if (i === 3 || i === 5 || i === 7 || i === 9) {\n                text += '-'\n            }\n        }\n\n        if (text.length !== 36) {\n            // We saw one customer whose bundling code was mangling the UUID generation\n            // rather than accept a bad UUID, we throw an error here.\n            throw new Error('Invalid UUIDv7 was generated')\n        }\n        return text\n    }\n\n    /** Creates an object from `this`. */\n    clone(): UUID {\n        return new UUID(this.bytes.slice(0))\n    }\n\n    /** Returns true if `this` is equivalent to `other`. */\n    equals(other: UUID): boolean {\n        return this.compareTo(other) === 0\n    }\n\n    /**\n     * Returns a negative integer, zero, or positive integer if `this` is less\n     * than, equal to, or greater than `other`, respectively.\n     */\n    compareTo(other: UUID): number {\n        for (let i = 0; i < 16; i++) {\n            const diff = this.bytes[i] - other.bytes[i]\n            if (diff !== 0) {\n                return Math.sign(diff)\n            }\n        }\n        return 0\n    }\n}\n\n/** Encapsulates the monotonic counter state. */\nclass V7Generator {\n    private _timestamp = 0\n    private _counter = 0\n    private readonly _random = new DefaultRandom()\n\n    /**\n     * Generates a new UUIDv7 object from the current timestamp, or resets the\n     * generator upon significant timestamp rollback.\n     *\n     * This method returns monotonically increasing UUIDs unless the up-to-date\n     * timestamp is significantly (by ten seconds or more) smaller than the one\n     * embedded in the immediately preceding UUID. If such a significant clock\n     * rollback is detected, this method resets the generator and returns a new\n     * UUID based on the current timestamp.\n     */\n    generate(): UUID {\n        const value = this.generateOrAbort()\n        if (!isUndefined(value)) {\n            return value\n        } else {\n            // reset state and resume\n            this._timestamp = 0\n            const valueAfterReset = this.generateOrAbort()\n            if (isUndefined(valueAfterReset)) {\n                throw new Error('Could not generate UUID after timestamp reset')\n            }\n            return valueAfterReset\n        }\n    }\n\n    /**\n     * Generates a new UUIDv7 object from the current timestamp, or returns\n     * `undefined` upon significant timestamp rollback.\n     *\n     * This method returns monotonically increasing UUIDs unless the up-to-date\n     * timestamp is significantly (by ten seconds or more) smaller than the one\n     * embedded in the immediately preceding UUID. If such a significant clock\n     * rollback is detected, this method aborts and returns `undefined`.\n     */\n    generateOrAbort(): UUID | undefined {\n        const MAX_COUNTER = 0x3ff_ffff_ffff\n        const ROLLBACK_ALLOWANCE = 10_000 // 10 seconds\n\n        const ts = Date.now()\n        if (ts > this._timestamp) {\n            this._timestamp = ts\n            this._resetCounter()\n        } else if (ts + ROLLBACK_ALLOWANCE > this._timestamp) {\n            // go on with previous timestamp if new one is not much smaller\n            this._counter++\n            if (this._counter > MAX_COUNTER) {\n                // increment timestamp at counter overflow\n                this._timestamp++\n                this._resetCounter()\n            }\n        } else {\n            // abort if clock went backwards to unbearable extent\n            return undefined\n        }\n\n        return UUID.fromFieldsV7(\n            this._timestamp,\n            Math.trunc(this._counter / 2 ** 30),\n            this._counter & (2 ** 30 - 1),\n            this._random.nextUint32()\n        )\n    }\n\n    /** Initializes the counter at a 42-bit random integer. */\n    private _resetCounter(): void {\n        this._counter = this._random.nextUint32() * 0x400 + (this._random.nextUint32() & 0x3ff)\n    }\n}\n\n/** A global flag to force use of cryptographically strong RNG. */\ndeclare const UUIDV7_DENY_WEAK_RNG: boolean\n\n/** Stores `crypto.getRandomValues()` available in the environment. */\nlet getRandomValues: <T extends Uint8Array | Uint32Array>(buffer: T) => T = (buffer) => {\n    // fall back on Math.random() unless the flag is set to true\n    // TRICKY: don't use the isUndefined method here as can't pass the reference\n    if (typeof UUIDV7_DENY_WEAK_RNG !== 'undefined' && UUIDV7_DENY_WEAK_RNG) {\n        throw new Error('no cryptographically strong RNG available')\n    }\n\n    for (let i = 0; i < buffer.length; i++) {\n        buffer[i] = Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 + Math.trunc(Math.random() * 0x1_0000)\n    }\n    return buffer\n}\n\n// detect Web Crypto API\nif (window && !isUndefined(window.crypto) && crypto.getRandomValues) {\n    getRandomValues = (buffer) => crypto.getRandomValues(buffer)\n}\n\n/**\n * Wraps `crypto.getRandomValues()` and compatibles to enable buffering; this\n * uses a small buffer by default to avoid unbearable throughput decline in some\n * environments as well as the waste of time and space for unused values.\n */\nclass DefaultRandom {\n    private readonly _buffer = new Uint32Array(8)\n    private _cursor = Infinity\n    nextUint32(): number {\n        if (this._cursor >= this._buffer.length) {\n            getRandomValues(this._buffer)\n            this._cursor = 0\n        }\n        return this._buffer[this._cursor++]\n    }\n}\n\nlet defaultGenerator: V7Generator | undefined\n\n/**\n * Generates a UUIDv7 string.\n *\n * @returns The 8-4-4-4-12 canonical hexadecimal string representation\n * (\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\").\n */\nexport const uuidv7 = (): string => uuidv7obj().toString()\n\n/** Generates a UUIDv7 object. */\nconst uuidv7obj = (): UUID => (defaultGenerator || (defaultGenerator = new V7Generator())).generate()\n\nexport const uuid7ToTimestampMs = (uuid: string): number => {\n    // remove hyphens\n    const hex = uuid.replace(/-/g, '')\n    // ensure that it's a version 7 UUID\n    if (hex.length !== 32) {\n        throw new Error('Not a valid UUID')\n    }\n    if (hex[12] !== '7') {\n        throw new Error('Not a UUIDv7')\n    }\n    // the first 6 bytes are the timestamp, which means that we can read only the first 12 hex characters\n    return parseInt(hex.substring(0, 12), 16)\n}\n","import { convertToURL, getQueryParam, maskQueryParams } from './request-utils'\nimport { isNull, stripLeadingDollar, stripUrlHash } from '@posthog/core'\nimport { Properties } from '../types'\nimport Config from '../config'\nimport { SDK_DIST_CHANNEL } from '../constants'\nimport { each, extend, stripEmptyProperties } from './index'\nimport { document, location, userAgent, window } from './globals'\nimport {\n    BrowserDetectionHints,\n    detectBrowser,\n    detectBrowserVersion,\n    detectDevice,\n    detectDeviceType,\n    detectOS,\n} from '@posthog/core'\nimport { cookieStore } from '../storage'\n\nconst URL_REGEX_PREFIX = 'https?://(.*)'\n\n// CAMPAIGN_PARAMS and EVENT_TO_PERSON_PROPERTIES should be kept in sync with\n// https://github.com/PostHog/posthog/blob/master/plugin-server/src/utils/db/utils.ts#L60\n\n// The list of campaign parameters that could be considered personal data under e.g. GDPR.\n// These can be masked in URLs and properties before being sent to posthog.\nexport const PERSONAL_DATA_CAMPAIGN_PARAMS = [\n    'gclid', // google ads\n    'gclsrc', // google ads 360\n    'dclid', // google display ads\n    'gbraid', // google ads, web to app\n    'wbraid', // google ads, app to web\n    'fbclid', // facebook\n    'msclkid', // microsoft\n    'twclid', // twitter\n    'li_fat_id', // linkedin\n    'igshid', // instagram\n    'ttclid', // tiktok\n    'rdt_cid', // reddit\n    'epik', // pinterest\n    'qclid', // quora\n    'sccid', // snapchat\n    'irclid', // impact\n    '_kx', // klaviyo\n]\n\nexport const CAMPAIGN_PARAMS = [\n    'utm_source',\n    'utm_medium',\n    'utm_campaign',\n    'utm_content',\n    'utm_term',\n    'gad_source', // google ads source\n    'mc_cid', // mailchimp campaign id\n    ...PERSONAL_DATA_CAMPAIGN_PARAMS,\n]\n\nexport const EVENT_TO_PERSON_PROPERTIES = [\n    // mobile params\n    '$app_build',\n    '$app_name',\n    '$app_namespace',\n    '$app_version',\n    // web params\n    '$browser',\n    '$browser_version',\n    '$device_type',\n    '$current_url',\n    '$pathname',\n    '$os',\n    '$os_name', // $os_name is a special case, it's treated as an alias of $os!\n    '$os_version',\n    '$referring_domain',\n    '$referrer',\n    '$screen_height',\n    '$screen_width',\n    '$viewport_height',\n    '$viewport_width',\n    '$raw_user_agent',\n]\n\nexport const MASKED = '<masked>'\n\n// Campaign params that can be read from the cookie store\nexport const COOKIE_CAMPAIGN_PARAMS = [\n    'li_fat_id', // linkedin\n]\n\nexport function getCampaignParams(\n    customTrackedParams?: string[],\n    maskPersonalDataProperties?: boolean,\n    customPersonalDataProperties?: string[] | undefined\n): Record<string, string> {\n    if (!document) {\n        return {}\n    }\n\n    const paramsToMask = maskPersonalDataProperties\n        ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n        : []\n\n    // Initially get campaign params from the URL\n    const urlCampaignParams = _getCampaignParamsFromUrl(\n        maskQueryParams(document.URL, paramsToMask, MASKED),\n        customTrackedParams\n    )\n\n    // But we can also get some of them from the cookie store\n    // For example: https://learn.microsoft.com/en-us/linkedin/marketing/conversions/enabling-first-party-cookies?view=li-lms-2025-05#reading-li_fat_id-from-cookies\n    const cookieCampaignParams = _getCampaignParamsFromCookie()\n\n    // Prefer the values found in the urlCampaignParams if possible\n    // `extend` will override the values if found in the second argument\n    return extend(cookieCampaignParams, urlCampaignParams)\n}\n\nfunction _getCampaignParamsFromUrl(url: string, customParams?: string[]): Record<string, string> {\n    const campaign_keywords = CAMPAIGN_PARAMS.concat(customParams || [])\n\n    const params: Record<string, any> = {}\n    each(campaign_keywords, function (kwkey) {\n        const kw = getQueryParam(url, kwkey)\n        params[kwkey] = kw ? kw : null\n    })\n\n    return params\n}\n\nfunction _getCampaignParamsFromCookie(): Record<string, string> {\n    const params: Record<string, any> = {}\n    each(COOKIE_CAMPAIGN_PARAMS, function (kwkey) {\n        const kw = cookieStore._get(kwkey)\n        params[kwkey] = kw ? kw : null\n    })\n\n    return params\n}\n\nfunction _getSearchEngine(referrer: string): string | null {\n    if (!referrer) {\n        return null\n    } else {\n        if (referrer.search(URL_REGEX_PREFIX + 'google.([^/?]*)') === 0) {\n            return 'google'\n        } else if (referrer.search(URL_REGEX_PREFIX + 'bing.com') === 0) {\n            return 'bing'\n        } else if (referrer.search(URL_REGEX_PREFIX + 'yahoo.com') === 0) {\n            return 'yahoo'\n        } else if (referrer.search(URL_REGEX_PREFIX + 'duckduckgo.com') === 0) {\n            return 'duckduckgo'\n        } else {\n            return null\n        }\n    }\n}\n\nfunction _getSearchInfoFromReferrer(referrer: string): Record<string, any> {\n    const search = _getSearchEngine(referrer)\n    const param = search != 'yahoo' ? 'q' : 'p'\n    const ret: Record<string, any> = {}\n\n    if (!isNull(search)) {\n        ret['$search_engine'] = search\n\n        const keyword = document ? getQueryParam(document.referrer, param) : ''\n        if (keyword.length) {\n            ret['ph_keyword'] = keyword\n        }\n    }\n\n    return ret\n}\n\nexport function getSearchInfo(): Record<string, any> {\n    const referrer = document?.referrer\n    if (!referrer) {\n        return {}\n    }\n    return _getSearchInfoFromReferrer(referrer)\n}\n\nexport function getBrowserLanguage(): string | undefined {\n    return (\n        navigator.language || // Any modern browser\n        (navigator as Record<string, any>).userLanguage // IE11\n    )\n}\n\nexport function getBrowserLanguagePrefix(): string | undefined {\n    const lang = getBrowserLanguage()\n    return typeof lang === 'string' ? lang.split('-')[0] : undefined\n}\n\nconst DIRECT = '$direct'\n\nexport function getReferrer(): string {\n    return document?.referrer || DIRECT\n}\n\nexport function getReferringDomain(): string {\n    if (!document?.referrer) {\n        return DIRECT\n    }\n    return convertToURL(document.referrer)?.host || DIRECT\n}\n\nexport function getReferrerInfo(): Record<string, any> {\n    return {\n        $referrer: getReferrer(),\n        $referring_domain: getReferringDomain(),\n    }\n}\n\nexport function getPersonInfo(\n    maskPersonalDataProperties?: boolean,\n    customPersonalDataProperties?: string[],\n    disableCaptureUrlHashes: boolean = false\n) {\n    const paramsToMask = maskPersonalDataProperties\n        ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n        : []\n    const href = disableCaptureUrlHashes ? stripUrlHash(location?.href) : location?.href\n    const url = href?.substring(0, 1000)\n    // we're being a bit more economical with bytes here because this is stored in the cookie\n    return {\n        r: getReferrer().substring(0, 1000),\n        u: url ? maskQueryParams(url, paramsToMask, MASKED) : undefined,\n    }\n}\n\nexport function getPersonPropsFromInfo(\n    info: Record<string, any>,\n    disableCaptureUrlHashes: boolean = false\n): Record<string, any> {\n    const { r: referrer, u } = info\n    const url = disableCaptureUrlHashes ? stripUrlHash(u) : u\n    const referring_domain = referrer == null ? undefined : referrer == DIRECT ? DIRECT : convertToURL(referrer)?.host\n\n    const props: Record<string, string | undefined> = {\n        $referrer: referrer,\n        $referring_domain: referring_domain,\n    }\n    if (url) {\n        props['$current_url'] = url\n        const location = convertToURL(url)\n        props['$host'] = location?.host\n        props['$pathname'] = location?.pathname\n        const campaignParams = _getCampaignParamsFromUrl(url)\n        extend(props, campaignParams)\n    }\n    if (referrer) {\n        const searchInfo = _getSearchInfoFromReferrer(referrer)\n        extend(props, searchInfo)\n    }\n    return props\n}\n\nexport function getInitialPersonPropsFromInfo(\n    info: Record<string, any>,\n    disableCaptureUrlHashes: boolean = false\n): Record<string, any> {\n    const personProps = getPersonPropsFromInfo(info, disableCaptureUrlHashes)\n    const props: Record<string, any> = {}\n    each(personProps, function (val: any, key: string) {\n        props[`$initial_${stripLeadingDollar(key)}`] = val\n    })\n    return props\n}\n\nexport function getTimezone(): string | undefined {\n    try {\n        return Intl.DateTimeFormat().resolvedOptions().timeZone\n    } catch {\n        return undefined\n    }\n}\n\nexport function getTimezoneOffset(): number | undefined {\n    try {\n        return new Date().getTimezoneOffset()\n    } catch {\n        return undefined\n    }\n}\n\n// Gathers signals that aren't in the UA string. Desktop / Android Brave is\n// Chromium-based and exposes `navigator.brave` rather than a UA marker. (Brave\n// on iOS is picked up via the `Brave/` UA marker by `detectBrowser` itself, so\n// no hint is needed there.)\nexport function getBrowserDetectionHints(): BrowserDetectionHints {\n    const nav = typeof navigator !== 'undefined' ? (navigator as Record<string, any>) : undefined\n    return nav?.brave ? { brave: true } : {}\n}\n\nexport function getEventProperties(\n    maskPersonalDataProperties?: boolean,\n    customPersonalDataProperties?: string[],\n    detectGoogleSearchApp?: boolean,\n    disableCaptureUrlHashes: boolean = false\n): Properties {\n    if (!userAgent) {\n        return {}\n    }\n    const paramsToMask = maskPersonalDataProperties\n        ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(customPersonalDataProperties || [])]\n        : []\n    const [os_name, os_version] = detectOS(userAgent)\n    const browserHints = getBrowserDetectionHints()\n    const browserOptions = { detectGoogleSearchApp }\n\n    const properties = extend(\n        stripEmptyProperties({\n            $os: os_name,\n            $os_version: os_version,\n            $browser: detectBrowser(userAgent, navigator.vendor, browserHints, browserOptions),\n            $device: detectDevice(userAgent),\n            $device_type: detectDeviceType(userAgent, {\n                // eslint-disable-next-line compat/compat\n                userAgentDataPlatform: navigator?.userAgentData?.platform,\n                maxTouchPoints: navigator?.maxTouchPoints,\n                screenWidth: window?.screen?.width,\n                screenHeight: window?.screen?.height,\n                devicePixelRatio: window?.devicePixelRatio,\n            }),\n            $timezone: getTimezone(),\n            $timezone_offset: getTimezoneOffset(),\n        }),\n        {\n            $current_url: maskQueryParams(\n                disableCaptureUrlHashes ? stripUrlHash(location?.href) : location?.href,\n                paramsToMask,\n                MASKED\n            ),\n            $host: location?.host,\n            $pathname: location?.pathname,\n            $raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,\n            $browser_version: detectBrowserVersion(userAgent, navigator.vendor, browserHints, browserOptions),\n            $browser_language: getBrowserLanguage(),\n            $browser_language_prefix: getBrowserLanguagePrefix(),\n            $screen_height: window?.screen.height,\n            $screen_width: window?.screen.width,\n            $viewport_height: window?.innerHeight,\n            $viewport_width: window?.innerWidth,\n            $lib: Config.LIB_NAME,\n            $lib_version: Config.LIB_VERSION,\n            $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),\n            $time: Date.now() / 1000, // epoch time in seconds\n        }\n    )\n\n    if (Config.SDK_DIST_CHANNEL) {\n        properties[SDK_DIST_CHANNEL] = Config.SDK_DIST_CHANNEL\n    }\n\n    return properties\n}\n","import type { recordOptions, rrwebRecord as rrwebRecordType } from '../types/rrweb'\nimport {\n    type customEvent,\n    EventType,\n    eventWithTime,\n    type fullSnapshotEvent,\n    IncrementalSource,\n    type listenerHandler,\n    RecordPlugin,\n} from '../types/rrweb-types'\nimport { buildNetworkRequestOptions } from './config'\nimport {\n    ACTIVE,\n    BUFFERING,\n    DISABLED,\n    EventTriggerMatching,\n    LinkedFlagMatching,\n    PAUSED,\n    SessionRecordingStatus,\n    TriggerType,\n    URLTriggerMatching,\n} from './triggerMatching'\nimport {\n    circularReferenceReplacer,\n    estimateCompressedEventSize,\n    estimateSize,\n    INCREMENTAL_SNAPSHOT_EVENT_TYPE,\n    splitBuffer,\n    truncateLargeConsoleLogs,\n} from './sessionrecording-utils'\nexport { SEVEN_MEGABYTES, splitBuffer } from './sessionrecording-utils'\nimport { gzipSync, strFromU8, strToU8 } from 'fflate'\nimport { assignableWindow, LazyLoadedSessionRecordingInterface, window, document } from '../../../utils/globals'\nimport { addEventListener } from '../../../utils'\nimport { MutationThrottler } from './mutation-throttler'\nimport { createLogger } from '../../../utils/logger'\nimport {\n    clampToRange,\n    gzipCompress,\n    isArray,\n    isBoolean,\n    isFunction,\n    isGzipSupported,\n    isNull,\n    isNullish,\n    isNativeAsyncGzipError,\n    isNumber,\n    isObject,\n    isUndefined,\n    stripUrlHash,\n} from '@posthog/core'\nimport {\n    SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP,\n    SESSION_RECORDING_IS_SAMPLED,\n    SESSION_RECORDING_SAMPLE_RATE,\n    SESSION_RECORDING_OVERRIDE_SAMPLING,\n    SESSION_RECORDING_OVERRIDE_LINKED_FLAG,\n    SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER,\n    SESSION_RECORDING_OVERRIDE_URL_TRIGGER,\n    SESSION_RECORDING_PAST_MINIMUM_DURATION,\n    SESSION_RECORDING_REMOTE_CONFIG,\n    SESSION_RECORDING_START_REASON,\n    SDK_DEBUG_REPLAY_RRWEB_ATTACHED,\n    SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED,\n    SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,\n    SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION,\n} from '../../../constants'\nimport { PostHog } from '../../../posthog-core'\nimport {\n    NetworkRecordOptions,\n    PerformanceCaptureConfig,\n    Properties,\n    SessionIdChangedCallback,\n    SessionRecordingOptions,\n    SessionRecordingPersistedConfig,\n    SessionStartReason,\n} from '../../../types'\nimport { isLocalhost, maskQueryParams } from '../../../utils/request-utils'\nimport Config from '../../../config'\nimport { FlushedSizeTracker } from './flushed-size-tracker'\nimport {\n    RecordingStrategy,\n    V1RecordingStrategy,\n    V2TriggerGroupStrategy,\n    RecordingStrategyContext,\n    decodeSamplingDecision,\n} from './recording-strategies'\nimport { MASKED, PERSONAL_DATA_CAMPAIGN_PARAMS } from '../../../utils/event-utils'\n\nconst BASE_ENDPOINT = '/s/'\nconst DEFAULT_CANVAS_QUALITY = 0.4\nconst DEFAULT_CANVAS_FPS = 4\nconst MAX_CANVAS_FPS = 12\nconst MAX_CANVAS_QUALITY = 1\n\n// lower bound for session_recording.canvasCapture.resolutionScale, so a misconfiguration can't\n// capture at a degenerate resolution.\nconst MIN_CANVAS_SCALE = 0.1\nconst TWO_SECONDS = 2000\nconst ONE_KB = 1024\n\nconst ONE_MINUTE = 1000 * 60\nconst FIVE_MINUTES = ONE_MINUTE * 5\nconst ONE_HOUR = ONE_MINUTE * 60\n\n/**\n * Extracts the network_timing value from a capturePerformance config.\n * Returns `true`/`false` if explicitly set, or `undefined` if not specified.\n */\nfunction networkTimingFromConfig(config: boolean | PerformanceCaptureConfig | undefined): boolean | undefined {\n    return isObject(config) ? config.network_timing : config\n}\n\nexport const RECORDING_IDLE_THRESHOLD_MS = FIVE_MINUTES\nexport const RECORDING_REMOTE_CONFIG_TTL_MS = ONE_HOUR\nexport const RECORDING_MAX_EVENT_SIZE = ONE_KB * ONE_KB * 0.9 // ~1mb (with some wiggle room)\nexport const RECORDING_BUFFER_TIMEOUT = 2000 // 2 seconds\nexport const SESSION_RECORDING_BATCH_KEY = 'recordings'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\nconst logger = createLogger(LOGGER_PREFIX)\n\ninterface QueuedRRWebEvent {\n    rrwebMethod: () => void\n    attempt: number\n    // the timestamp this was first put into this queue\n    enqueuedAt: number\n}\n\ninterface QueuedCompressionEvent {\n    event: eventWithTime\n    compressionEnabled: boolean\n    targetSessionId: string\n    targetWindowId: string\n    generation: number\n    processed: boolean\n    counted: boolean\n}\n\ninterface SessionIdlePayload {\n    eventTimestamp: number\n    lastActivityTimestamp: number\n    threshold: number\n    bufferLength: number\n    bufferSize: number\n}\n\nexport interface SnapshotBuffer {\n    size: number\n    data: any[]\n    sizes: number[]\n    sessionId: string\n    windowId: string\n}\n\nconst ACTIVE_SOURCES: IncrementalSource[] = [\n    IncrementalSource.MouseMove,\n    IncrementalSource.MouseInteraction,\n    IncrementalSource.Scroll,\n    IncrementalSource.ViewportResize,\n    IncrementalSource.Input,\n    IncrementalSource.TouchMove,\n    IncrementalSource.MediaInteraction,\n    IncrementalSource.Drag,\n]\n\nconst newQueuedEvent = (rrwebMethod: () => void): QueuedRRWebEvent => ({\n    rrwebMethod,\n    enqueuedAt: Date.now(),\n    attempt: 1,\n})\n\nfunction getRRWeb() {\n    return assignableWindow?.__PosthogExtensions__?.rrweb\n}\n\nfunction getRRWebRecord(): rrwebRecordType | undefined {\n    return getRRWeb()?.record\n}\n\nexport type compressedFullSnapshotEvent = {\n    type: typeof EventType.FullSnapshot\n    data: string\n}\n\nexport type compressedIncrementalSnapshotEvent = {\n    type: typeof EventType.IncrementalSnapshot\n    data: {\n        source: IncrementalSource\n        texts: string\n        attributes: string\n        removes: string\n        adds: string\n    }\n}\n\nexport type compressedIncrementalStyleSnapshotEvent = {\n    type: typeof EventType.IncrementalSnapshot\n    data: {\n        source: typeof IncrementalSource.StyleSheetRule\n        id?: number\n        styleId?: number\n        replace?: string\n        replaceSync?: string\n        adds?: string\n        removes?: string\n    }\n}\n\nexport type compressedEvent =\n    | compressedIncrementalStyleSnapshotEvent\n    | compressedFullSnapshotEvent\n    | compressedIncrementalSnapshotEvent\nexport type compressedEventWithTime = compressedEvent & {\n    timestamp: number\n    delay?: number\n    // marker for compression version\n    cv: '2024-10'\n}\n\nfunction gzipStringToString(serializedData: string): string {\n    return strFromU8(gzipSync(strToU8(serializedData)), true)\n}\n\nfunction serializeForCompression(data: unknown): string {\n    try {\n        // fast path: plain native stringify, since a replacer callback is expensive on\n        // large snapshots and circular event data is rare\n        return JSON.stringify(data)\n    } catch {\n        // circular event data (e.g. a leaked instance graph) degrades gracefully to\n        // '[Circular]' markers instead of throwing, the same two-step approach as jsonStringify\n        return JSON.stringify(data, circularReferenceReplacer())\n    }\n}\n\nfunction gzipToString(data: unknown): string {\n    return gzipStringToString(serializeForCompression(data))\n}\n\nasync function gzipToStringAsync(data: unknown): Promise<string> {\n    const serializedData = serializeForCompression(data)\n    const compressed = await gzipCompress(serializedData, Config.DEBUG, { rethrow: true })\n    return strFromU8(new Uint8Array(await compressed!.arrayBuffer()), true)\n}\n\nlet _gzippedEmptyArray: string | undefined\nlet _gzippedEmptyArrayPromise: Promise<string> | undefined\nconst _isNativeAsyncSessionRecordingGzipSupported = typeof globalThis !== 'undefined' && isGzipSupported()\nlet _nativeAsyncSessionRecordingGzipDisabled = false\n\nfunction gzipField(data: unknown): string {\n    if (isArray(data) && data.length === 0) {\n        _gzippedEmptyArray = _gzippedEmptyArray ?? gzipToString([])\n        return _gzippedEmptyArray\n    }\n    return gzipToString(data)\n}\n\nasync function gzipFieldAsync(data: unknown): Promise<string> {\n    if (isArray(data) && data.length === 0) {\n        if (_gzippedEmptyArray) {\n            return _gzippedEmptyArray\n        }\n        _gzippedEmptyArrayPromise =\n            _gzippedEmptyArrayPromise ??\n            gzipToStringAsync([])\n                .then((compressed) => {\n                    _gzippedEmptyArray = compressed\n                    return compressed\n                })\n                .catch((error) => {\n                    _gzippedEmptyArray = undefined\n                    _gzippedEmptyArrayPromise = undefined\n                    throw error\n                })\n        return _gzippedEmptyArrayPromise\n    }\n    return gzipToStringAsync(data)\n}\n\nfunction shouldCompressEvent(event: eventWithTime): boolean {\n    return (\n        event.type === EventType.FullSnapshot ||\n        (event.type === EventType.IncrementalSnapshot &&\n            (event.data.source === IncrementalSource.Mutation ||\n                event.data.source === IncrementalSource.StyleSheetRule))\n    )\n}\n\nfunction shouldUseNativeAsyncSessionRecordingGzip(event: eventWithTime): boolean {\n    return (\n        _isNativeAsyncSessionRecordingGzipSupported &&\n        !_nativeAsyncSessionRecordingGzipDisabled &&\n        shouldCompressEvent(event)\n    )\n}\n\ntype CompressedEventResult = { event: eventWithTime | compressedEventWithTime; size: number }\n\ntype CompressedMutationFields = Pick<\n    compressedIncrementalSnapshotEvent['data'],\n    'texts' | 'attributes' | 'removes' | 'adds'\n>\ntype CompressedStyleFields = Pick<compressedIncrementalStyleSnapshotEvent['data'], 'adds' | 'removes'>\n\nfunction compressedResult(event: compressedEventWithTime): CompressedEventResult {\n    return { event, size: estimateCompressedEventSize(event) }\n}\n\nfunction buildCompressedFullSnapshotEvent(\n    event: fullSnapshotEvent & { timestamp: number; delay?: number },\n    data: string\n): compressedEventWithTime {\n    return {\n        ...event,\n        data,\n        cv: '2024-10',\n    }\n}\n\nfunction buildCompressedIncrementalEvent(\n    event: eventWithTime,\n    fields: CompressedMutationFields | CompressedStyleFields\n): compressedEventWithTime {\n    // reshapes rrweb incremental `data` into its compressed string-field variant — the\n    // compiler cannot relate the incoming union member to the matching compressed member\n    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n    return {\n        ...event,\n        cv: '2024-10' as const,\n        data: {\n            ...(event.data as Record<string, unknown>),\n            ...fields,\n        },\n    } as compressedEventWithTime\n}\n\n/**\n * rrweb's packer takes an event and returns a string or the reverse on `unpack`.\n * but we want to be able to inspect metadata during ingestion.\n * and don't want to compress the entire event,\n * so we have a custom packer that only compresses part of some events\n *\n * returns the compressed event and its estimated JSON size,\n * avoiding a redundant JSON.stringify for size estimation\n */\nfunction compressEventSync(event: eventWithTime): CompressedEventResult {\n    try {\n        if (event.type === EventType.FullSnapshot) {\n            return compressedResult(buildCompressedFullSnapshotEvent(event, gzipToString(event.data)))\n        }\n        if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.Mutation) {\n            return compressedResult(\n                buildCompressedIncrementalEvent(event, {\n                    texts: gzipField(event.data.texts),\n                    attributes: gzipField(event.data.attributes),\n                    removes: gzipField(event.data.removes),\n                    adds: gzipField(event.data.adds),\n                })\n            )\n        }\n        if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.StyleSheetRule) {\n            return compressedResult(\n                buildCompressedIncrementalEvent(event, {\n                    adds: event.data.adds ? gzipToString(event.data.adds) : undefined,\n                    removes: event.data.removes ? gzipToString(event.data.removes) : undefined,\n                })\n            )\n        }\n    } catch (e) {\n        logger.error('could not compress event - will use uncompressed event', e)\n    }\n    return { event, size: estimateSize(event) }\n}\n\nasync function compressEventAsync(event: eventWithTime): Promise<CompressedEventResult> {\n    try {\n        if (event.type === EventType.FullSnapshot) {\n            return compressedResult(buildCompressedFullSnapshotEvent(event, await gzipToStringAsync(event.data)))\n        }\n        if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.Mutation) {\n            const [texts, attributes, removes, adds] = await Promise.all([\n                gzipFieldAsync(event.data.texts),\n                gzipFieldAsync(event.data.attributes),\n                gzipFieldAsync(event.data.removes),\n                gzipFieldAsync(event.data.adds),\n            ])\n            return compressedResult(buildCompressedIncrementalEvent(event, { texts, attributes, removes, adds }))\n        }\n        if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.StyleSheetRule) {\n            const [adds, removes] = await Promise.all([\n                event.data.adds ? gzipToStringAsync(event.data.adds) : undefined,\n                event.data.removes ? gzipToStringAsync(event.data.removes) : undefined,\n            ])\n            return compressedResult(buildCompressedIncrementalEvent(event, { adds, removes }))\n        }\n    } catch (e) {\n        if (isNativeAsyncGzipError(e)) {\n            _nativeAsyncSessionRecordingGzipDisabled = true\n        }\n        logger.error('could not compress event asynchronously - trying synchronous compression', e)\n        return compressEventSync(event)\n    }\n    return { event, size: estimateSize(event) }\n}\n\nfunction isCustomEvent(e: eventWithTime, tag: string): e is eventWithTime & customEvent {\n    return e.type === EventType.Custom && e.data.tag === tag\n}\n\nfunction isSessionIdleEvent(e: eventWithTime): e is eventWithTime & customEvent {\n    return isCustomEvent(e, 'sessionIdle')\n}\n\ntype SessionEndingPayload = {\n    lastActivityTimestamp?: number\n    currentSessionId?: string\n    currentWindowId?: string\n}\n\nfunction isSessionEndingEvent(e: eventWithTime): e is eventWithTime & customEvent {\n    return isCustomEvent(e, '$session_ending')\n}\n\nfunction getSessionEndingPayload(e: eventWithTime): SessionEndingPayload | null {\n    return isSessionEndingEvent(e) ? (e.data.payload as SessionEndingPayload) : null\n}\n\ntype SessionStartingPayload = {\n    lastActivityTimestamp?: number\n    nextSessionId?: string\n    nextWindowId?: string\n}\n\nfunction isSessionStartingEvent(e: eventWithTime): e is eventWithTime & customEvent {\n    return isCustomEvent(e, '$session_starting')\n}\n\nfunction getSessionStartingPayload(e: eventWithTime): SessionStartingPayload | null {\n    return isSessionStartingEvent(e) ? (e.data.payload as SessionStartingPayload) : null\n}\n\nfunction isAllowedWhenIdle(e: eventWithTime): boolean {\n    return isSessionIdleEvent(e) || isSessionEndingEvent(e) || isSessionStartingEvent(e)\n}\n\n/** When we put the recording into a paused state, we add a custom event.\n *  However, in the paused state, events are dropped and never make it to the buffer,\n *  so we need to manually let this one through */\nfunction isRecordingPausedEvent(e: eventWithTime) {\n    return e.type === EventType.Custom && e.data.tag === 'recording paused'\n}\n\nexport class LazyLoadedSessionRecording implements LazyLoadedSessionRecordingInterface {\n    private _endpoint: string = BASE_ENDPOINT\n    private _mutationThrottler?: MutationThrottler\n    /**\n     * Util to help developers working on this feature manually override\n     */\n    private _forceAllowLocalhostNetworkCapture = false\n    private _stopRrweb: listenerHandler | undefined = undefined\n    private _lastActivityTimestamp: number = Date.now()\n    private _isActivatingTrigger: boolean = false\n    /**\n     * if pageview capture is disabled,\n     * then we can manually track href changes\n     */\n    private _lastHref?: string\n    /**\n     * and a queue - that contains rrweb events that we want to send to rrweb, but rrweb wasn't able to accept them yet\n     */\n    private _queuedRRWebEvents: QueuedRRWebEvent[] = []\n    private _isIdle: boolean | 'unknown' = 'unknown'\n    private _rrwebError = false\n    private _rrwebStartAttempted = false\n    private _maxDepthExceeded = false\n\n    private _linkedFlagMatching: LinkedFlagMatching\n    private _urlTriggerMatching: URLTriggerMatching\n    private _eventTriggerMatching: EventTriggerMatching\n    // Strategy pattern: V1 vs V2 trigger logic\n    private _strategy: RecordingStrategy | undefined\n    private _fullSnapshotTimer?: ReturnType<typeof setInterval>\n    private _fullSnapshotTimestamps: Array<[string, number]> = []\n    // ship-time FullSnapshot tracking for _ensureFullSnapshotForSession (unlike _fullSnapshotTimestamps, which records emit-time debug telemetry)\n    private _lastFullSnapshotSessionId: string | undefined = undefined\n    private _fullSnapshotHealAttemptedFor: string | undefined = undefined\n\n    private _windowId: string\n    private _sessionId: string\n    get sessionId(): string {\n        return this._sessionId\n    }\n\n    private _flushBufferTimer?: any\n    // we have a buffer - that contains PostHog snapshot events ready to be sent to the server\n    private _buffer: SnapshotBuffer\n    private _compressionQueue?: Promise<void>\n    private _pendingCompressionEvents: QueuedCompressionEvent[] = []\n    private _queuedCompressionEvents: number = 0\n    private _compressionQueueGeneration: number = 0\n    private _isStoppingAfterCompression: boolean = false\n\n    private _removePageViewCaptureHook: (() => void) | undefined = undefined\n\n    private _removeEventTriggerCaptureHook: (() => void) | undefined = undefined\n\n    private _flushedSizeTracker: FlushedSizeTracker\n\n    private get _sessionManager() {\n        if (!this._instance.sessionManager) {\n            throw new Error(LOGGER_PREFIX + ' must be started with a valid sessionManager.')\n        }\n\n        return this._instance.sessionManager\n    }\n\n    private get _sessionIdleThresholdMilliseconds(): number {\n        return this._instance.config.session_recording.session_idle_threshold_ms || RECORDING_IDLE_THRESHOLD_MS\n    }\n\n    private get _isSampled(): boolean | null {\n        const currentValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n        // anything but this session's own tagged decision decodes to null, forcing a fresh decision\n        return decodeSamplingDecision(currentValue, this.sessionId)\n    }\n\n    private get _sampleRate(): number | null {\n        const rate = this._remoteConfig?.sampleRate\n        return isNumber(rate) ? rate : null\n    }\n\n    private get _minimumDuration(): number | null {\n        return this._strategy?.getMinimumDuration(this.sessionId) ?? null\n    }\n\n    private _onSessionIdListener: (() => void) | undefined = undefined\n    private _onSessionIdleResetForcedListener: (() => void) | undefined = undefined\n    private _forceIdleSessionIdListener: (() => void) | undefined = undefined\n\n    constructor(private readonly _instance: PostHog) {\n        // we know there's a sessionManager, so don't need to start without a session id\n        const { sessionId, windowId } = this._sessionManager.checkAndGetSessionAndWindowId()\n        this._sessionId = sessionId\n        this._windowId = windowId\n\n        this._linkedFlagMatching = new LinkedFlagMatching(this._instance)\n        this._urlTriggerMatching = new URLTriggerMatching(this._instance)\n        this._eventTriggerMatching = new EventTriggerMatching(this._instance)\n\n        this._buffer = this._clearBuffer()\n\n        if (this._sessionIdleThresholdMilliseconds >= this._sessionManager.sessionTimeoutMs) {\n            logger.warn(\n                `session_idle_threshold_ms (${this._sessionIdleThresholdMilliseconds}) is greater than the session timeout (${this._sessionManager.sessionTimeoutMs}). Session will never be detected as idle`\n            )\n        }\n\n        this._flushedSizeTracker = new FlushedSizeTracker(this._instance)\n    }\n\n    private get _masking():\n        | Pick<SessionRecordingOptions, 'maskAllInputs' | 'maskTextSelector' | 'blockSelector'>\n        | undefined {\n        const masking_server_side = this._remoteConfig?.masking\n        const masking_client_side = {\n            maskAllInputs: this._instance.config.session_recording?.maskAllInputs,\n            maskTextSelector: this._instance.config.session_recording?.maskTextSelector,\n            blockSelector: this._instance.config.session_recording?.blockSelector,\n        }\n\n        const maskAllInputs = masking_client_side?.maskAllInputs ?? masking_server_side?.maskAllInputs\n        const maskTextSelector = masking_client_side?.maskTextSelector ?? masking_server_side?.maskTextSelector\n        const blockSelector = masking_client_side?.blockSelector ?? masking_server_side?.blockSelector\n\n        return !isUndefined(maskAllInputs) || !isUndefined(maskTextSelector) || !isUndefined(blockSelector)\n            ? {\n                  maskAllInputs: maskAllInputs ?? true,\n                  maskTextSelector,\n                  blockSelector,\n              }\n            : undefined\n    }\n\n    // (0,1] fraction of the canvas display size to capture frames at, from\n    // session_recording.canvasCapture.resolutionScale. clamped to [MIN_CANVAS_SCALE, 1]; defaults\n    // to 1 (full resolution) so capture only drops below full resolution when explicitly\n    // configured. replay upscales the frame back to its display size.\n    private get _canvasResolutionScale(): number {\n        return clampToRange(\n            this._instance.config.session_recording.canvasCapture?.resolutionScale,\n            MIN_CANVAS_SCALE,\n            1,\n            createLogger('canvas recording resolution scale'),\n            1\n        )\n    }\n\n    private get _canvasRecording(): { enabled: boolean; fps: number; quality: number } {\n        const canvasRecording_client_side = this._instance.config.session_recording.captureCanvas\n        const canvasRecording_server_side = this._remoteConfig?.canvasRecording\n\n        const enabled: boolean =\n            canvasRecording_client_side?.recordCanvas ?? canvasRecording_server_side?.enabled ?? false\n        const fps: number =\n            canvasRecording_client_side?.canvasFps ?? canvasRecording_server_side?.fps ?? DEFAULT_CANVAS_FPS\n        let quality: string | number =\n            canvasRecording_client_side?.canvasQuality ?? canvasRecording_server_side?.quality ?? DEFAULT_CANVAS_QUALITY\n        if (typeof quality === 'string') {\n            const parsed = parseFloat(quality)\n            quality = isNaN(parsed) ? 0.4 : parsed\n        }\n\n        return {\n            enabled,\n            fps: clampToRange(fps, 0, MAX_CANVAS_FPS, createLogger('canvas recording fps'), DEFAULT_CANVAS_FPS),\n            quality: clampToRange(\n                quality,\n                0,\n                MAX_CANVAS_QUALITY,\n                createLogger('canvas recording quality'),\n                DEFAULT_CANVAS_QUALITY\n            ),\n        }\n    }\n\n    private get _isConsoleLogCaptureEnabled() {\n        const enabled_server_side = !!this._remoteConfig?.consoleLogRecordingEnabled\n        const enabled_client_side = this._instance.config.enable_recording_console_log\n        return enabled_client_side ?? enabled_server_side\n    }\n\n    // network payload capture config has three parts\n    // each can be configured server side or client side\n    private get _networkPayloadCapture():\n        | Pick<NetworkRecordOptions, 'recordHeaders' | 'recordBody' | 'recordPerformance'>\n        | undefined {\n        const networkPayloadCapture_server_side = this._remoteConfig?.networkPayloadCapture\n        const networkPayloadCapture_client_side = {\n            recordHeaders: this._instance.config.session_recording?.recordHeaders,\n            recordBody: this._instance.config.session_recording?.recordBody,\n        }\n        const headersEnabled =\n            networkPayloadCapture_client_side?.recordHeaders || networkPayloadCapture_server_side?.recordHeaders\n        const bodyEnabled =\n            networkPayloadCapture_client_side?.recordBody || networkPayloadCapture_server_side?.recordBody\n        const clientNetworkTiming = networkTimingFromConfig(this._instance.config.capture_performance)\n        const serverNetworkTiming = networkTimingFromConfig(networkPayloadCapture_server_side?.capturePerformance)\n        const networkTimingEnabled = !!(isBoolean(clientNetworkTiming) ? clientNetworkTiming : serverNetworkTiming)\n\n        return headersEnabled || bodyEnabled || networkTimingEnabled\n            ? { recordHeaders: headersEnabled, recordBody: bodyEnabled, recordPerformance: networkTimingEnabled }\n            : undefined\n    }\n\n    private _gatherRRWebPlugins() {\n        const plugins: RecordPlugin[] = []\n\n        const recordConsolePlugin = assignableWindow.__PosthogExtensions__?.rrwebPlugins?.getRecordConsolePlugin\n        if (recordConsolePlugin && this._isConsoleLogCaptureEnabled) {\n            plugins.push(recordConsolePlugin())\n        }\n\n        const networkPlugin = assignableWindow.__PosthogExtensions__?.rrwebPlugins?.getRecordNetworkPlugin\n        if (!!this._networkPayloadCapture && isFunction(networkPlugin)) {\n            const canRecordNetwork = !isLocalhost() || this._forceAllowLocalhostNetworkCapture\n\n            if (canRecordNetwork) {\n                plugins.push(\n                    networkPlugin(buildNetworkRequestOptions(this._instance.config, this._networkPayloadCapture))\n                )\n            } else {\n                logger.info('NetworkCapture not started because we are on localhost.')\n            }\n        }\n\n        return plugins\n    }\n\n    private _stripUrlHash(url: string): string {\n        return this._instance.config.disable_capture_url_hashes ? stripUrlHash(url) : url\n    }\n\n    private _maskReplayUrl(url: string, forceStripHash: boolean = false): string | undefined {\n        const href = forceStripHash ? stripUrlHash(url) : this._stripUrlHash(url)\n        const paramsToMask = this._instance.config.mask_personal_data_properties\n            ? [...PERSONAL_DATA_CAMPAIGN_PARAMS, ...(this._instance.config.custom_personal_data_properties || [])]\n            : []\n\n        return this._maskUrl(maskQueryParams(href, paramsToMask, MASKED))\n    }\n\n    private _maskUrl(url: string): string | undefined {\n        const userSessionRecordingOptions = this._instance.config.session_recording\n\n        // userSessionRecordingOptions.maskNetworkRequestFn is deprecated, fallback to it\n        if (userSessionRecordingOptions.maskCapturedNetworkRequestFn) {\n            const result = userSessionRecordingOptions.maskCapturedNetworkRequestFn({\n                name: url,\n            } as any)\n            // CapturedNetworkRequest uses 'name' for URL, but also check 'url' for compatibility\n            return result?.name ?? (result as any)?.url\n        }\n\n        if (userSessionRecordingOptions.maskNetworkRequestFn) {\n            const result = userSessionRecordingOptions.maskNetworkRequestFn({\n                url,\n            })\n            return result?.url\n        }\n\n        return url\n    }\n\n    private _tryRRWebMethod(queuedRRWebEvent: QueuedRRWebEvent): boolean {\n        try {\n            queuedRRWebEvent.rrwebMethod()\n            return true\n        } catch (e) {\n            // Sometimes a race can occur where the recorder is not fully started yet\n            if (this._queuedRRWebEvents.length < 10) {\n                this._queuedRRWebEvents.push({\n                    enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),\n                    attempt: queuedRRWebEvent.attempt + 1,\n                    rrwebMethod: queuedRRWebEvent.rrwebMethod,\n                })\n            } else {\n                logger.warn('could not emit queued rrweb event.', e, queuedRRWebEvent)\n            }\n\n            return false\n        }\n    }\n\n    private _tryAddCustomEvent(tag: string, payload: any): boolean {\n        return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord()!.addCustomEvent(tag, payload)))\n    }\n\n    private _pageViewFallBack() {\n        try {\n            if (this._instance.config.capture_pageview || !window) {\n                return\n            }\n            // Preserve the previous normalization behavior for this fallback (e.g. https://test.com -> https://test.com/)\n            // while still applying query masking. This path was already hashless before disable_capture_url_hashes.\n            // eslint-disable-next-line compat/compat\n            const url = new URL(window.location.href)\n            const currentUrl = this._maskReplayUrl(url.origin + url.pathname + url.search)\n            if (this._lastHref !== currentUrl) {\n                this._lastHref = currentUrl\n                this._tryAddCustomEvent('$url_changed', { href: currentUrl })\n            }\n        } catch {\n            // If URL processing fails, don't capture anything\n        }\n    }\n\n    private _processQueuedEvents() {\n        if (this._queuedRRWebEvents.length) {\n            // if rrweb isn't ready to accept events earlier, then we queued them up.\n            // now that `emit` has been called rrweb should be ready to accept them.\n            // so, before we process this event, we try our queued events _once_ each\n            // we don't want to risk queuing more things and never exiting this loop!\n            // if they fail here, they'll be pushed into a new queue\n            // and tried on the next loop.\n            // there is a risk of this queue growing in an uncontrolled manner.\n            // so its length is limited elsewhere\n            // for now this is to help us ensure we can capture events that happen\n            // and try to identify more about when it is failing\n            const itemsToProcess = [...this._queuedRRWebEvents]\n            this._queuedRRWebEvents = []\n            itemsToProcess.forEach((queuedRRWebEvent) => {\n                if (Date.now() - queuedRRWebEvent.enqueuedAt <= TWO_SECONDS) {\n                    this._tryRRWebMethod(queuedRRWebEvent)\n                }\n            })\n        }\n    }\n\n    private _tryTakeFullSnapshot(): boolean {\n        return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord()!.takeFullSnapshot()))\n    }\n\n    private get _fullSnapshotIntervalMillis(): number {\n        if (this._strategy?.hasPendingTriggers(this.sessionId) && !['sampled', 'active'].includes(this.status)) {\n            return ONE_MINUTE\n        }\n\n        return this._instance.config.session_recording?.full_snapshot_interval_millis ?? FIVE_MINUTES\n    }\n\n    private _scheduleFullSnapshot(): void {\n        if (this._fullSnapshotTimer) {\n            clearInterval(this._fullSnapshotTimer)\n        }\n        // we don't schedule snapshots while idle\n        if (this._isIdle === true) {\n            return\n        }\n\n        const interval = this._fullSnapshotIntervalMillis\n        if (!interval) {\n            return\n        }\n\n        this._fullSnapshotTimer = setInterval(() => {\n            this._tryTakeFullSnapshot()\n        }, interval)\n    }\n\n    private _pauseRecording() {\n        // we check _urlBlocked not status, since more than one thing can affect status\n        if (this._urlTriggerMatching.urlBlocked) {\n            return\n        }\n\n        // we can't flush the buffer here since someone might be starting on a blocked page.\n        // and we need to be sure that we don't record that page,\n        // so we might not get the below custom event, but events will report the paused status.\n        // which will allow debugging of sessions that start on blocked pages\n        this._urlTriggerMatching.urlBlocked = true\n\n        // Clear the snapshot timer since we don't want new snapshots while paused\n        clearInterval(this._fullSnapshotTimer)\n\n        logger.info('recording paused due to URL blocker')\n        this._tryAddCustomEvent('recording paused', { reason: 'url blocker' })\n    }\n\n    private _resumeRecording() {\n        // we check _urlBlocked not status, since more than one thing can affect status\n        if (!this._urlTriggerMatching.urlBlocked) {\n            return\n        }\n\n        this._urlTriggerMatching.urlBlocked = false\n\n        this._tryTakeFullSnapshot()\n        this._scheduleFullSnapshot()\n\n        this._tryAddCustomEvent('recording resumed', { reason: 'left blocked url' })\n        logger.info('recording resumed')\n    }\n\n    private _activateTrigger(triggerType: TriggerType, matchDetail?: string) {\n        // V1 only: V2 uses per-group activation and never calls this method\n        // Prevent re-entry: if we're already activating a trigger, skip to avoid infinite recursion\n        // This can happen when _reportStarted emits custom events that match the trigger condition\n        if (this._isActivatingTrigger) {\n            return\n        }\n\n        if (!this._strategy?.hasPendingTriggers(this.sessionId)) {\n            return\n        }\n\n        this._isActivatingTrigger = true\n        try {\n            // V1: Write trigger activation to persistence\n            // (V2 handles this per-group via TriggerGroupMatching.activateTrigger)\n            const persistenceKey =\n                triggerType === 'url'\n                    ? SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION\n                    : SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION\n\n            this._instance.persistence?.register({\n                [persistenceKey]: this.sessionId,\n            })\n\n            this._strategy?.updateActiveTriggers(this.sessionId)\n\n            this._flushBuffer()\n            this._reportStarted((triggerType + '_trigger_matched') as SessionStartReason, {\n                [triggerType === 'url' ? 'matchedUrl' : 'matchedEvent']: matchDetail,\n            })\n        } finally {\n            this._isActivatingTrigger = false\n        }\n    }\n\n    get isStarted(): boolean {\n        return !!this._stopRrweb\n    }\n\n    get _remoteConfig(): SessionRecordingPersistedConfig | undefined {\n        const persistedConfig: any = this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG)\n        if (!persistedConfig) {\n            return undefined\n        }\n        let parsedConfig: SessionRecordingPersistedConfig\n        try {\n            parsedConfig = isObject(persistedConfig) ? persistedConfig : JSON.parse(persistedConfig)\n        } catch (e) {\n            // Do not unregister here: the SDK only registers structured configs, and this read path should\n            // ignore corrupt legacy/external values without mutating persistence.\n            logger.warn('persisted remote config for session recording is invalid and will be ignored', e)\n            return undefined\n        }\n\n        // Only check TTL if recording hasn't started yet\n        // Once started, trust the config until a hard page load\n        if (!this.isStarted) {\n            // default to now so that configs persisted by older SDK versions\n            // (which never set cache_timestamp) are treated as fresh\n            const cacheTimestamp = parsedConfig.cache_timestamp ?? Date.now()\n            if (Date.now() - cacheTimestamp > RECORDING_REMOTE_CONFIG_TTL_MS) {\n                logger.info('persisted remote config for session recording is stale and will be ignored', {\n                    cacheTimestamp,\n                    persistedConfig,\n                })\n                this._instance.persistence?.unregister(SESSION_RECORDING_REMOTE_CONFIG)\n                return undefined\n            }\n        }\n\n        return parsedConfig as SessionRecordingPersistedConfig\n    }\n\n    private _checkOverride(key: string, overrideFunction: () => void, clearOverride: () => void): void {\n        const overrideFlag: boolean = this._instance.get_property(key) as boolean\n        if (overrideFlag) {\n            overrideFunction()\n\n            // Clean up the override flag after applying it\n            clearOverride()\n        }\n    }\n\n    start(startReason?: SessionStartReason) {\n        const config = this._remoteConfig\n        if (!config) {\n            logger.info('remote config must be stored in persistence before recording can start')\n            return\n        }\n\n        // Invalidate any in-flight async cleanup queued by a prior stop(). On a session-id\n        // rotation, _updateWindowAndSessionIds calls stop() then start() synchronously; if\n        // stop() took the _stopAfterCompressionQueueDrains path (non-empty compression queue),\n        // its async cleanup would later call _teardown() and silently tear down THIS new\n        // recorder once the drain promise resolves. Bumping the generation here causes that\n        // pending cleanup to bail at its generation check, and resetting the rest of the\n        // compression-stop state means a future stop() of this new recorder is not mistaken\n        // for the still-in-progress old one (which would make it a silent no-op).\n        // Guarded on the stop-in-progress flag because start() is also called re-entrantly\n        // on a live recorder (e.g. opt-in flows) where the queue holds the current session's\n        // events and must survive.\n        // Discard the buffer too — the bailed-out cleanup would have cleared it. Otherwise the\n        // prior session's snapshots flush under the old session id with the new distinct_id,\n        // mis-attributing the recording (#3822).\n        if (this._isStoppingAfterCompression) {\n            this._invalidateCompressionQueue()\n            this._clearBuffer()\n        }\n\n        // We want to ensure the sessionManager is reset if necessary on loading the recorder\n        const { sessionId, windowId } = this._sessionManager.checkAndGetSessionAndWindowId()\n        this._sessionId = sessionId\n        this._windowId = windowId\n\n        // Reset first full snapshot tracking for the new session\n        this._instance.persistence?.unregister(SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP)\n\n        if (config?.endpoint) {\n            this._endpoint = config?.endpoint\n        }\n\n        // Initialize the appropriate strategy based on config version\n        const isV2 = config?.version === 2 && config?.triggerGroups && config.triggerGroups.length > 0\n\n        if (isV2) {\n            this._strategy = new V2TriggerGroupStrategy(\n                this._instance,\n                this._urlTriggerMatching,\n                this._reportStarted.bind(this),\n                this._tryAddCustomEvent.bind(this)\n            )\n        } else {\n            this._strategy = new V1RecordingStrategy(\n                this._instance,\n                this._urlTriggerMatching,\n                this._eventTriggerMatching,\n                this._linkedFlagMatching,\n                this._reportStarted.bind(this),\n                this._tryTakeFullSnapshot.bind(this)\n            )\n        }\n\n        // Let the strategy configure itself\n        this._strategy.onRemoteConfig(config)\n\n        // Setup event trigger listeners via strategy\n        this._removeEventTriggerCaptureHook?.()\n        this._removeEventTriggerCaptureHook = this._strategy.setupEventTriggerListeners(\n            this._instance.on.bind(this._instance, 'eventCaptured'),\n            this.sessionId,\n            (triggerType, matchDetail) => this._activateTrigger(triggerType, matchDetail)\n        )\n\n        this._checkOverride(\n            SESSION_RECORDING_OVERRIDE_SAMPLING,\n            () => {\n                this.overrideSampling()\n            },\n            () => this._instance.persistence?.unregister(SESSION_RECORDING_OVERRIDE_SAMPLING)\n        )\n        this._checkOverride(\n            SESSION_RECORDING_OVERRIDE_LINKED_FLAG,\n            () => {\n                this.overrideLinkedFlag()\n            },\n            () => this._instance.persistence?.unregister(SESSION_RECORDING_OVERRIDE_LINKED_FLAG)\n        )\n        this._checkOverride(\n            SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER,\n            () => {\n                this.overrideTrigger('event')\n            },\n            () => this._instance.persistence?.unregister(SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER)\n        )\n        this._checkOverride(\n            SESSION_RECORDING_OVERRIDE_URL_TRIGGER,\n            () => {\n                this.overrideTrigger('url')\n            },\n            () => this._instance.persistence?.unregister(SESSION_RECORDING_OVERRIDE_URL_TRIGGER)\n        )\n\n        // Let strategy make sampling decisions\n        this._strategy.makeSamplingDecisions(this.sessionId)\n        this._startRecorder()\n\n        if (this._rrwebError) {\n            return\n        }\n\n        // calling addEventListener multiple times is safe and will not add duplicates\n        addEventListener(window, 'beforeunload', this._onBeforeUnload)\n        addEventListener(window, 'offline', this._onOffline)\n        addEventListener(window, 'online', this._onOnline)\n        addEventListener(window, 'visibilitychange', this._onVisibilityChange)\n\n        if (!this._onSessionIdListener && isFunction(this._sessionManager.onSessionId)) {\n            this._onSessionIdListener = this._sessionManager.onSessionId(this._onSessionIdCallback)\n        }\n\n        // NB: SessionIdManager.on was only added in posthog-js 1.268.6. This recorder chunk is loaded\n        // from the CDN and can run against an older bundled core that has no `on` method, so guard the\n        // call to degrade gracefully (recording still starts, it just skips the forced-idle-reset listener)\n        // rather than throwing a TypeError during start().\n        if (!this._onSessionIdleResetForcedListener && isFunction(this._sessionManager.on)) {\n            this._onSessionIdleResetForcedListener = this._sessionManager.on('forcedIdleReset', () => {\n                // a session was forced to reset due to idle timeout and lack of activity\n                this._clearConditionalRecordingPersistence()\n                this._isIdle = 'unknown'\n                this.stop()\n                // then we want a session id listener to restart the recording when a new session starts\n                this._forceIdleSessionIdListener = this._sessionManager.onSessionId(\n                    (sessionId, windowId, changeReason) => {\n                        // this should first unregister itself\n                        this._forceIdleSessionIdListener?.()\n                        this._forceIdleSessionIdListener = undefined\n                        this._onSessionIdCallback(sessionId, windowId, changeReason)\n                    }\n                )\n            })\n        } else if (!isFunction(this._sessionManager.on)) {\n            logger.warn(\n                'bundled core has no SessionIdManager.on (requires posthog-js >= 1.268.6); ' +\n                    'recording will start but skip forced-idle-reset handling'\n            )\n        }\n\n        if (isNullish(this._removePageViewCaptureHook)) {\n            // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.\n            //   Dropping the initial event is fine (it's always captured by rrweb).\n            this._removePageViewCaptureHook = this._instance.on('eventCaptured', (event) => {\n                // If anything could go wrong here,\n                // it has the potential to block the main loop,\n                // so we catch all errors.\n                try {\n                    if (event.event === '$pageview') {\n                        const href = event?.properties.$current_url\n                            ? this._maskReplayUrl(event.properties.$current_url)\n                            : ''\n                        if (!href) {\n                            return\n                        }\n                        this._tryAddCustomEvent('$pageview', { href })\n                    }\n                } catch (e) {\n                    logger.error('Could not add $pageview to rrweb session', e)\n                }\n            })\n        }\n\n        if (this.status === ACTIVE) {\n            this._reportStarted(startReason || 'recording_initialized')\n        }\n    }\n\n    private _onSessionIdCallback: SessionIdChangedCallback = (sessionId, windowId, changeReason) => {\n        if (!changeReason) return\n\n        // Skip if session hasn't actually changed (callback might fire multiple times)\n        if (sessionId === this._sessionId && windowId === this._windowId) {\n            return\n        }\n\n        const wasLikelyReset = changeReason.noSessionId\n        const shouldLinkSessions =\n            !wasLikelyReset && (changeReason.activityTimeout || changeReason.sessionPastMaximumLength)\n\n        // Capture old IDs before start() updates them\n        const oldSessionId = this._sessionId\n        const oldWindowId = this._windowId\n\n        if (shouldLinkSessions) {\n            this._tryAddCustomEvent('$session_ending', {\n                currentSessionId: oldSessionId,\n                currentWindowId: oldWindowId,\n                nextSessionId: sessionId,\n                nextWindowId: windowId,\n                changeReason,\n                // we'll need to correct the time of this if it's captured when idle\n                // so we don't extend reported session time with a debug event\n                lastActivityTimestamp: this._lastActivityTimestamp,\n                flushed_size: this._flushedSizeTracker?.currentTrackedSize(oldSessionId),\n            })\n        }\n\n        // Reset first full snapshot timestamp for the new session\n        this._instance.persistence?.unregister(SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP)\n\n        this._maxDepthExceeded = false\n        getRRWeb()?.resetMaxDepthState?.()\n\n        this._tryAddCustomEvent('$session_id_change', { sessionId, windowId, changeReason })\n\n        this._clearConditionalRecordingPersistence()\n\n        // When rrweb isn't running _updateWindowAndSessionIds can't drive the restart,\n        // so we restart here. Otherwise it handles the restart after this callback returns.\n        if (this._isIdle === true || !this.isStarted) {\n            this._isIdle = 'unknown'\n            this.stop()\n            this.start('session_id_changed')\n        }\n\n        if (shouldLinkSessions) {\n            this._tryAddCustomEvent('$session_starting', {\n                previousSessionId: oldSessionId,\n                previousWindowId: oldWindowId,\n                nextSessionId: sessionId,\n                nextWindowId: windowId,\n                changeReason,\n                // we'll need to correct the time of this if it's captured when idle\n                // so we don't extend reported session time with a debug event\n                lastActivityTimestamp: this._lastActivityTimestamp,\n            })\n        }\n\n        // always re-decide for the new session — guarding on the persisted config here would skip\n        // V2 trigger groups and post-reset() sessions, leaving them undecided (= ACTIVE, unsampled)\n        this._strategy?.makeSamplingDecisions(sessionId)\n    }\n\n    private _teardown() {\n        window?.removeEventListener('beforeunload', this._onBeforeUnload)\n        window?.removeEventListener('offline', this._onOffline)\n        window?.removeEventListener('online', this._onOnline)\n        window?.removeEventListener('visibilitychange', this._onVisibilityChange)\n\n        clearInterval(this._fullSnapshotTimer)\n        this._clearFlushBufferTimer()\n\n        this._removePageViewCaptureHook?.()\n        this._removePageViewCaptureHook = undefined\n        this._removeEventTriggerCaptureHook?.()\n        this._removeEventTriggerCaptureHook = undefined\n        this._onSessionIdListener?.()\n        this._onSessionIdListener = undefined\n        this._onSessionIdleResetForcedListener?.()\n        this._onSessionIdleResetForcedListener = undefined\n        this._forceIdleSessionIdListener?.()\n        this._forceIdleSessionIdListener = undefined\n\n        this._strategy?.stop()\n\n        this._stopRecordingProducers()\n\n        this._invalidateCompressionQueue()\n    }\n\n    // Invalidate any in-flight async compression work so it does not capture events\n    // after stop()/discard() has cleared the buffer or after a future restart.\n    private _invalidateCompressionQueue() {\n        this._compressionQueueGeneration += 1\n        this._pendingCompressionEvents = []\n        this._queuedCompressionEvents = 0\n        this._compressionQueue = undefined\n        this._isStoppingAfterCompression = false\n    }\n\n    private _stopRecordingProducers() {\n        this._mutationThrottler?.stop()\n\n        // Clear any queued rrweb events to prevent memory leaks from closures\n        this._queuedRRWebEvents = []\n\n        this._stopRrweb?.()\n        this._stopRrweb = undefined\n    }\n\n    private _stopAfterCompressionQueueDrains(): boolean {\n        if (!this._compressionQueue || this._queuedCompressionEvents === 0) {\n            return false\n        }\n        if (this._isStoppingAfterCompression) {\n            return true\n        }\n\n        this._isStoppingAfterCompression = true\n        const generation = this._compressionQueueGeneration\n        this._clearFlushBufferTimer()\n        // Stop rrweb synchronously so it cannot keep producing events while we wait\n        // for the compression queue to drain and flush the already queued events.\n        this._stopRecordingProducers()\n        this._compressionQueue\n            .catch(() => undefined)\n            .then(() => {\n                if (generation !== this._compressionQueueGeneration) {\n                    return\n                }\n\n                this._isStoppingAfterCompression = false\n                this._flushBuffer()\n                this._clearBuffer()\n                this._teardown()\n                logger.info('stopped')\n            })\n            .catch(() => {\n                // Keep stop() best-effort. Compression errors are handled per event,\n                // but never let an unexpected queue failure block teardown.\n                this._isStoppingAfterCompression = false\n                this._teardown()\n                logger.info('stopped')\n            })\n\n        return true\n    }\n\n    stop() {\n        if (this._stopAfterCompressionQueueDrains()) {\n            return\n        }\n\n        this._flushBuffer()\n        this._clearBuffer()\n        this._teardown()\n        logger.info('stopped')\n    }\n\n    discard() {\n        this._clearBuffer()\n        this._teardown()\n        logger.info('discarded')\n    }\n\n    private _captureProcessedEvent(\n        event: eventWithTime,\n        eventToSend: eventWithTime | compressedEventWithTime,\n        size: number,\n        targetSessionId: string,\n        targetWindowId: string\n    ) {\n        const properties = {\n            $snapshot_bytes: size,\n            $snapshot_data: eventToSend,\n            $session_id: targetSessionId,\n            $window_id: targetWindowId,\n        }\n\n        if (event.type === EventType.FullSnapshot && getRRWeb()?.wasMaxDepthReached?.()) {\n            this._maxDepthExceeded = true\n        }\n\n        if (this.status === DISABLED) {\n            this._clearBuffer()\n            return\n        }\n\n        this._ensureFullSnapshotForSession(event, targetSessionId)\n\n        this._captureSnapshotBuffered(properties)\n    }\n\n    // A session whose incrementals ship before any FullSnapshot is unplayable until the next periodic snapshot, so request one from rrweb (once per session id, to avoid loops if taking one keeps failing).\n    private _ensureFullSnapshotForSession(event: eventWithTime, targetSessionId: string) {\n        if (event.type === EventType.FullSnapshot) {\n            this._lastFullSnapshotSessionId = targetSessionId\n            return\n        }\n\n        if (event.type !== EventType.IncrementalSnapshot) {\n            return\n        }\n\n        if (\n            // deliberately conservative: only heal after this recorder shipped a FullSnapshot to another session (the rotation signature), since on a fresh start rrweb's init snapshot is always ordered ahead of any incremental\n            isUndefined(this._lastFullSnapshotSessionId) ||\n            this._lastFullSnapshotSessionId === targetSessionId ||\n            this._fullSnapshotHealAttemptedFor === targetSessionId\n        ) {\n            return\n        }\n\n        this._fullSnapshotHealAttemptedFor = targetSessionId\n        logger.info('incremental snapshot for a session with no full snapshot - requesting one', {\n            sessionId: targetSessionId,\n        })\n        this._tryTakeFullSnapshot()\n    }\n\n    private _finishQueuedCompressionEvent(queuedEvent: QueuedCompressionEvent) {\n        if (queuedEvent.counted && queuedEvent.generation === this._compressionQueueGeneration) {\n            this._queuedCompressionEvents = Math.max(0, this._queuedCompressionEvents - 1)\n        }\n        queuedEvent.counted = false\n        this._pendingCompressionEvents = this._pendingCompressionEvents.filter((x) => x !== queuedEvent)\n    }\n\n    private _captureQueuedCompressionEvent(\n        queuedEvent: QueuedCompressionEvent,\n        eventToSend: eventWithTime | compressedEventWithTime,\n        size: number\n    ) {\n        if (queuedEvent.processed || queuedEvent.generation !== this._compressionQueueGeneration) {\n            return\n        }\n\n        queuedEvent.processed = true\n        this._captureProcessedEvent(\n            queuedEvent.event,\n            eventToSend,\n            size,\n            queuedEvent.targetSessionId,\n            queuedEvent.targetWindowId\n        )\n    }\n\n    private _processQueuedCompressionEventSync(queuedEvent: QueuedCompressionEvent) {\n        try {\n            const { event: eventToSend, size } = queuedEvent.compressionEnabled\n                ? compressEventSync(queuedEvent.event)\n                : { event: queuedEvent.event, size: estimateSize(queuedEvent.event) }\n\n            this._captureQueuedCompressionEvent(queuedEvent, eventToSend, size)\n        } finally {\n            this._finishQueuedCompressionEvent(queuedEvent)\n        }\n    }\n\n    private _drainCompressionQueueSync() {\n        const queuedEvents = [...this._pendingCompressionEvents]\n        queuedEvents.forEach((queuedEvent) => {\n            this._processQueuedCompressionEventSync(queuedEvent)\n        })\n    }\n\n    private _enqueueCompression(\n        event: eventWithTime,\n        compressionEnabled: boolean,\n        targetSessionId: string,\n        targetWindowId: string\n    ) {\n        const queuedEvent: QueuedCompressionEvent = {\n            event,\n            compressionEnabled,\n            targetSessionId,\n            targetWindowId,\n            generation: this._compressionQueueGeneration,\n            processed: false,\n            counted: true,\n        }\n        this._pendingCompressionEvents.push(queuedEvent)\n        this._queuedCompressionEvents += 1\n\n        const processEvent = async () => {\n            try {\n                if (queuedEvent.processed) {\n                    return\n                }\n\n                let eventToSend: eventWithTime | compressedEventWithTime\n                let size: number\n                try {\n                    const result = compressionEnabled\n                        ? shouldUseNativeAsyncSessionRecordingGzip(event)\n                            ? await compressEventAsync(event)\n                            : compressEventSync(event)\n                        : { event, size: estimateSize(event) }\n                    eventToSend = result.event\n                    size = result.size\n                } catch (e) {\n                    // a compression failure must never reject the queue promise chain, since the\n                    // rejection would surface as an unhandled rejection and drop the event\n                    logger.error('could not process queued compression event - will use uncompressed event', e)\n                    eventToSend = event\n                    size = estimateSize(event)\n                }\n\n                this._captureQueuedCompressionEvent(queuedEvent, eventToSend, size)\n            } finally {\n                this._finishQueuedCompressionEvent(queuedEvent)\n            }\n        }\n\n        this._compressionQueue = this._compressionQueue\n            ? this._compressionQueue.catch(() => undefined).then(processEvent)\n            : processEvent()\n    }\n\n    onRRwebEmit(rawEvent: eventWithTime) {\n        // late event after sessionManager teardown (e.g. cookieless opt-out) — _sessionManager would throw\n        if (!this._instance.sessionManager) {\n            return\n        }\n\n        this._processQueuedEvents()\n\n        if (!rawEvent || !isObject(rawEvent)) {\n            return\n        }\n\n        if (rawEvent.type === EventType.Meta) {\n            const href = this._maskReplayUrl(rawEvent.data.href)\n            this._lastHref = href\n            if (!href) {\n                return\n            }\n            rawEvent.data.href = href\n        } else {\n            this._pageViewFallBack()\n        }\n\n        // Check if the URL matches any trigger patterns - delegate to strategy\n        this._strategy?.checkUrlTriggers(\n            this.sessionId,\n            () => this._pauseRecording(),\n            () => this._resumeRecording(),\n            (triggerType, matchDetail) => this._activateTrigger(triggerType, matchDetail)\n        )\n\n        // always have to check if the URL is blocked really early,\n        // or you risk getting stuck in a loop\n        if (this._urlTriggerMatching.urlBlocked && !isRecordingPausedEvent(rawEvent)) {\n            return\n        }\n\n        // we're processing a full snapshot, so we should reset the timer\n        if (rawEvent.type === EventType.FullSnapshot) {\n            this._scheduleFullSnapshot()\n            // Full snapshots reset rrweb's node IDs, so clear any logged node tracking\n            this._mutationThrottler?.reset()\n\n            // Track the timestamp of the first full snapshot for this session\n            // This helps us detect session rotation issues where incremental snapshots\n            // are sent before the full snapshot\n            this._instance.persistence?.register_once(\n                {\n                    [SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP]: rawEvent.timestamp,\n                },\n                undefined\n            )\n        }\n\n        // Clear the buffer if waiting for a trigger and only keep data from after the current full snapshot\n        if (rawEvent.type === EventType.FullSnapshot && this._strategy?.hasPendingTriggers(this.sessionId)) {\n            this._clearBufferBeforeMostRecentMeta()\n        }\n\n        const throttledEvent = this._mutationThrottler ? this._mutationThrottler.throttleMutations(rawEvent) : rawEvent\n\n        if (!throttledEvent) {\n            return\n        }\n\n        // TODO: Re-add ensureMaxMessageSize once we are confident in it\n        const event = truncateLargeConsoleLogs(throttledEvent)\n\n        // Session lifecycle events ($session_ending, $session_starting) carry their target session ID\n        // in the payload. We must extract this BEFORE _updateWindowAndSessionIds runs, because that\n        // method triggers checkAndGetSessionAndWindowId() which would update this._sessionId.\n        // This is critical for $session_ending which must go to the OLD session, not the new one,\n        // and for $session_starting which must go to the NEW session.\n        const sessionEndingPayload = getSessionEndingPayload(event)\n        const sessionStartingPayload = getSessionStartingPayload(event)\n\n        if (sessionEndingPayload || sessionStartingPayload) {\n            // Adjust timestamp from payload to avoid artificially extending session duration\n            const payload = (sessionEndingPayload ?? sessionStartingPayload) as {\n                lastActivityTimestamp?: number\n            }\n            if (payload?.lastActivityTimestamp) {\n                event.timestamp = payload.lastActivityTimestamp\n            }\n        } else {\n            this._updateWindowAndSessionIds(event)\n        }\n\n        if (rawEvent.type === EventType.FullSnapshot) {\n            this._fullSnapshotTimestamps.push([this._sessionId, rawEvent.timestamp])\n            if (this._fullSnapshotTimestamps.length > 6) {\n                this._fullSnapshotTimestamps = this._fullSnapshotTimestamps.slice(-6)\n            }\n        }\n\n        // Route lifecycle events using their payload IDs:\n        // - $session_ending uses currentSessionId (the old session it's ending)\n        // - $session_starting uses nextSessionId (the new session it's starting)\n        // - All other events use the current session ID\n        const targetSessionId =\n            sessionEndingPayload?.currentSessionId ?? sessionStartingPayload?.nextSessionId ?? this._sessionId\n        const targetWindowId =\n            sessionEndingPayload?.currentWindowId ?? sessionStartingPayload?.nextWindowId ?? this._windowId\n\n        // When in an idle state we keep recording but don't capture the events,\n        // we don't want to return early if idle is 'unknown'\n        if (this._isIdle === true && !isAllowedWhenIdle(event)) {\n            return\n        }\n\n        if (isSessionIdleEvent(event)) {\n            // session idle events have a timestamp when rrweb sees them\n            // which can artificially lengthen a session\n            // we know when we detected it based on the payload and can correct the timestamp\n            const payload = event.data.payload as SessionIdlePayload\n            if (payload) {\n                const lastActivity = payload.lastActivityTimestamp\n                const threshold = payload.threshold\n                event.timestamp = lastActivity + threshold\n            }\n        }\n\n        const compressionEnabled = this._instance.config.session_recording.compress_events ?? true\n\n        if (\n            this._queuedCompressionEvents > 0 ||\n            (compressionEnabled && shouldUseNativeAsyncSessionRecordingGzip(event))\n        ) {\n            this._enqueueCompression(event, compressionEnabled, targetSessionId, targetWindowId)\n            return\n        }\n\n        const { event: eventToSend, size } = compressionEnabled\n            ? compressEventSync(event)\n            : { event, size: estimateSize(event) }\n        this._captureProcessedEvent(event, eventToSend, size, targetSessionId, targetWindowId)\n    }\n\n    get status(): SessionRecordingStatus {\n        if (!this._strategy) {\n            return DISABLED\n        }\n\n        const context: RecordingStrategyContext = {\n            instance: this._instance,\n            sessionId: this.sessionId,\n            isSampled: this._isSampled,\n            rrwebError: this._rrwebError,\n            urlTriggerMatching: this._urlTriggerMatching,\n            eventTriggerMatching: this._eventTriggerMatching,\n            linkedFlagMatching: this._linkedFlagMatching,\n            remoteConfig: this._remoteConfig,\n        }\n\n        return this._strategy.getStatus(context)\n    }\n\n    log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n        this._instance.sessionRecording?.onRRwebEmit({\n            type: 6,\n            data: {\n                plugin: 'rrweb/console@1',\n                payload: {\n                    level,\n                    trace: [],\n                    // Even though it is a string, we stringify it as that's what rrweb expects\n                    payload: [JSON.stringify(message)],\n                },\n            },\n            timestamp: Date.now(),\n        })\n    }\n\n    public overrideLinkedFlag() {\n        this._linkedFlagMatching.linkedFlagSeen = true\n        this._tryTakeFullSnapshot()\n        this._reportStarted('linked_flag_overridden')\n    }\n\n    /**\n     * this ignores the sampling config and (if other conditions are met) causes capture to start\n     *\n     * It is not usual to call this directly,\n     * instead call `posthog.startSessionRecording({sampling: true})`\n     * */\n    public overrideSampling() {\n        this._instance.persistence?.register({\n            // short-circuits the `makeSamplingDecision` function in the session recording module\n            [SESSION_RECORDING_IS_SAMPLED]: this.sessionId,\n            [SESSION_RECORDING_SAMPLE_RATE]: null,\n        })\n        this._tryTakeFullSnapshot()\n        this._reportStarted('sampling_overridden')\n    }\n\n    /**\n     * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start\n     *\n     * It is not usual to call this directly,\n     * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`\n     * */\n    public overrideTrigger(triggerType: TriggerType) {\n        this._activateTrigger(triggerType)\n    }\n\n    private _currentMaskedHostname(): string | undefined {\n        try {\n            const href = window?.location?.href\n            if (!href) {\n                return undefined\n            }\n            const maskedUrl = this._maskReplayUrl(href)\n            if (!maskedUrl) {\n                return undefined\n            }\n            // not convertToURL: it resolves invalid input (e.g. a masking fn returning \"REDACTED\")\n            // against the current page and would return the real hostname we're trying to mask.\n            // new URL throws instead, so bad input falls through to the catch and we omit the property.\n            // eslint-disable-next-line compat/compat\n            return new URL(maskedUrl).hostname || undefined\n        } catch {\n            return undefined\n        }\n    }\n\n    private _clearFlushBufferTimer() {\n        if (this._flushBufferTimer) {\n            clearTimeout(this._flushBufferTimer)\n            this._flushBufferTimer = undefined\n        }\n    }\n\n    private _flushBuffer(): SnapshotBuffer {\n        this._clearFlushBufferTimer()\n\n        // never flush while a sampling decision is missing (e.g. wiped by posthog.reset()) — an\n        // undecided session reads as ACTIVE and would leak a batch it then decides not to record\n        this._strategy?.ensureSamplingDecision(this.sessionId)\n\n        const isBelowMinimumDuration = this._isBelowMinimumDuration()\n\n        if (this.status === BUFFERING || this.status === PAUSED || this.status === DISABLED || isBelowMinimumDuration) {\n            this._flushBufferTimer = setTimeout(() => {\n                this._flushBuffer()\n            }, RECORDING_BUFFER_TIMEOUT)\n            return this._buffer\n        }\n\n        if (this._buffer.data.length > 0) {\n            const snapshotHostname = this._currentMaskedHostname()\n            const snapshotEvents = splitBuffer(this._buffer)\n            snapshotEvents.forEach((snapshotBuffer) => {\n                this._flushedSizeTracker?.trackSize(snapshotBuffer.sessionId, snapshotBuffer.size)\n                this._captureSnapshot({\n                    $snapshot_bytes: snapshotBuffer.size,\n                    $snapshot_data: snapshotBuffer.data,\n                    $session_id: snapshotBuffer.sessionId,\n                    $window_id: snapshotBuffer.windowId,\n                    $lib: Config.LIB_NAME,\n                    $lib_version: Config.LIB_VERSION,\n                    $snapshot_host: snapshotHostname,\n                })\n            })\n\n            // Notify strategy that initial flush is complete (performance optimization)\n            this._strategy?.onFlushComplete()\n        }\n\n        // buffer is empty, we clear it in case the session id has changed\n        return this._clearBuffer()\n    }\n\n    private _hasPassedMinimumDuration = (): boolean => {\n        const persistedSessionId = this._instance.persistence?.props[SESSION_RECORDING_PAST_MINIMUM_DURATION]\n        return persistedSessionId === this._sessionId\n    }\n\n    private _getBufferDuration = (): number | null => {\n        if (this._buffer.data.length === 0) {\n            return null\n        }\n\n        const firstTimestamp = this._buffer.data[0]?.timestamp\n        const lastTimestamp = this._buffer.data[this._buffer.data.length - 1]?.timestamp\n\n        if (!isNumber(firstTimestamp) || !isNumber(lastTimestamp)) {\n            return null\n        }\n\n        return lastTimestamp - firstTimestamp\n    }\n\n    private _isBelowMinimumDuration = (): boolean => {\n        const minimumDuration = this._minimumDuration\n        if (!isNumber(minimumDuration)) {\n            return false\n        }\n\n        const strictMode = this._instance.config.session_recording?.strictMinimumDuration ?? false\n\n        if (!strictMode) {\n            const sessionDuration = this._sessionDuration\n            const isPositiveSessionDuration = isNumber(sessionDuration) && sessionDuration >= 0\n            return isPositiveSessionDuration && sessionDuration < minimumDuration\n        }\n\n        if (this._hasPassedMinimumDuration()) {\n            return false\n        }\n\n        const bufferDuration = this._getBufferDuration()\n        if (isNull(bufferDuration)) {\n            return true\n        }\n\n        if (bufferDuration >= minimumDuration) {\n            this._instance.persistence?.register({\n                [SESSION_RECORDING_PAST_MINIMUM_DURATION]: this._sessionId,\n            })\n            return false\n        }\n\n        return true\n    }\n\n    private _captureSnapshotBuffered(properties: Properties) {\n        const additionalBytes = 2 + (this._buffer?.data.length || 0) // 2 bytes for the array brackets and 1 byte for each comma\n\n        // Extract target session ID from properties to ensure we flush when session changes\n        // This is critical for lifecycle events ($session_ending, $session_starting) which may\n        // have different target session IDs than this._sessionId\n        const targetSessionId = properties.$session_id as string\n\n        // A session-id mismatch must flush and rebind even while idle, or an idle rotation appends the new session's Meta and FullSnapshot to the old session's buffer and ships them under the old session id.\n        const sessionChanged = this._buffer.sessionId !== targetSessionId\n\n        if (\n            sessionChanged ||\n            // we never want to flush a healthy same-session buffer while idle\n            (!this._isIdle &&\n                this._buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE)\n        ) {\n            this._buffer = this._flushBuffer()\n            // A suppressed flush (e.g. buffering, paused, below minimum duration) returns the buffer un-drained, and relabeling the prior session's events would mis-attribute them, so discard them instead.\n            if (sessionChanged && this._buffer.data.length > 0) {\n                this._buffer = this._clearBuffer()\n            }\n            // After flushing, update buffer to use the new target session/window IDs\n            this._buffer.sessionId = targetSessionId\n            this._buffer.windowId = properties.$window_id as string\n        }\n\n        this._buffer.size += properties.$snapshot_bytes\n        this._buffer.data.push(properties.$snapshot_data)\n        this._buffer.sizes.push(properties.$snapshot_bytes)\n\n        if (!this._flushBufferTimer && !this._isIdle) {\n            this._flushBufferTimer = setTimeout(() => {\n                this._flushBuffer()\n            }, RECORDING_BUFFER_TIMEOUT)\n        }\n    }\n\n    private _captureSnapshot(properties: Properties) {\n        // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.\n        this._instance.capture('$snapshot', properties, {\n            _url: this._instance.requestRouter.endpointFor('api', this._endpoint),\n            _noTruncate: true,\n            _batchKey: SESSION_RECORDING_BATCH_KEY,\n            skip_client_rate_limiting: true,\n        })\n    }\n\n    private get _sessionDuration(): number | null {\n        const mostRecentSnapshot = this._buffer?.data[this._buffer?.data.length - 1]\n        const { sessionStartTimestamp } = this._sessionManager.checkAndGetSessionAndWindowId(true)\n        return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null\n    }\n\n    private _clearBufferBeforeMostRecentMeta(): SnapshotBuffer {\n        if (!this._buffer || this._buffer.data.length === 0) {\n            return this._clearBuffer()\n        }\n\n        // Find the last meta event index by iterating backwards\n        let lastMetaIndex = -1\n        for (let i = this._buffer.data.length - 1; i >= 0; i--) {\n            if (this._buffer.data[i].type === EventType.Meta) {\n                lastMetaIndex = i\n                break\n            }\n        }\n        if (lastMetaIndex >= 0) {\n            this._buffer.data = this._buffer.data.slice(lastMetaIndex)\n            this._buffer.sizes = this._buffer.sizes.slice(lastMetaIndex)\n            this._buffer.size = this._buffer.sizes.reduce((a, b) => a + b, 0)\n            return this._buffer\n        } else {\n            return this._clearBuffer()\n        }\n    }\n\n    private _clearBuffer(): SnapshotBuffer {\n        this._buffer = {\n            size: 0,\n            data: [],\n            sizes: [],\n            sessionId: this._sessionId,\n            windowId: this._windowId,\n        }\n        return this._buffer\n    }\n\n    private _onBeforeUnload = (): void => {\n        // If still buffering (waiting for triggers), discard the buffer\n        if (this.status === BUFFERING) {\n            this._clearBuffer()\n            return\n        }\n\n        // beforeunload cannot wait for async CompressionStream work. Synchronously\n        // compress any queued events so sendBeacon can include them in this flush.\n        this._drainCompressionQueueSync()\n        this._flushBuffer()\n    }\n\n    private _onOffline = (): void => {\n        this._tryAddCustomEvent('browser offline', {})\n    }\n\n    private _onOnline = (): void => {\n        this._tryAddCustomEvent('browser online', {})\n    }\n\n    private _onVisibilityChange = (): void => {\n        if (document?.visibilityState) {\n            const label = 'window ' + document.visibilityState\n            this._tryAddCustomEvent(label, {})\n        }\n    }\n\n    private _reportStarted(startReason: SessionStartReason, tagPayload?: Record<string, any>) {\n        this._instance.register_for_session({\n            [SESSION_RECORDING_START_REASON]: startReason,\n        })\n        logger.info(startReason.replace('_', ' '), tagPayload)\n        if (startReason !== 'session_id_changed') {\n            this._tryAddCustomEvent('$recording_started', {\n                reason: startReason,\n                ...tagPayload,\n            })\n        }\n    }\n\n    private _isInteractiveEvent(event: eventWithTime) {\n        return (\n            event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE &&\n            ACTIVE_SOURCES.indexOf(event.data?.source as IncrementalSource) !== -1\n        )\n    }\n\n    private _updateWindowAndSessionIds(event: eventWithTime) {\n        // Some recording events are triggered by non-user events (e.g. \"X minutes ago\" text updating on the screen).\n        // We don't want to extend the session or trigger a new session in these cases. These events are designated by event\n        // type -> incremental update, and source -> mutation.\n\n        const isUserInteraction = this._isInteractiveEvent(event)\n\n        if (!isUserInteraction && !this._isIdle) {\n            // We check if the lastActivityTimestamp is old enough to go idle\n            const timeSinceLastActivity = event.timestamp - this._lastActivityTimestamp\n            if (timeSinceLastActivity > this._sessionIdleThresholdMilliseconds) {\n                // we mark as idle right away,\n                // or else we get multiple idle events\n                // if there are lots of non-user activity events being emitted\n                this._isIdle = true\n\n                // don't take full snapshots while idle\n                clearInterval(this._fullSnapshotTimer)\n\n                this._tryAddCustomEvent('sessionIdle', {\n                    eventTimestamp: event.timestamp,\n                    lastActivityTimestamp: this._lastActivityTimestamp,\n                    threshold: this._sessionIdleThresholdMilliseconds,\n                    bufferLength: this._buffer.data.length,\n                    bufferSize: this._buffer.size,\n                })\n\n                // proactively flush the buffer in case the session is idle for a long time\n                this._flushBuffer()\n            }\n        }\n\n        let returningFromIdle = false\n        if (isUserInteraction) {\n            this._lastActivityTimestamp = event.timestamp\n            if (this._isIdle) {\n                const idleWasUnknown = this._isIdle === 'unknown'\n                // Remove the idle state\n                this._isIdle = false\n                // if the idle state was unknown, we don't want to add an event, since we're just in bootup\n                // whereas if it was true, we know we've been idle for a while, and we can mark ourselves as returning from idle\n                if (!idleWasUnknown) {\n                    this._tryAddCustomEvent('sessionNoLongerIdle', {\n                        reason: 'user activity',\n                        type: event.type,\n                    })\n                    returningFromIdle = true\n                }\n            }\n        }\n\n        if (this._isIdle) {\n            return\n        }\n\n        // We only want to extend the session if it is an interactive event.\n        const { windowId, sessionId } = this._sessionManager.checkAndGetSessionAndWindowId(\n            !isUserInteraction,\n            event.timestamp\n        )\n\n        const sessionIdChanged = this._sessionId !== sessionId\n        const windowIdChanged = this._windowId !== windowId\n\n        this._windowId = windowId\n        this._sessionId = sessionId\n\n        if (sessionIdChanged || windowIdChanged) {\n            this.stop()\n            this.start('session_id_changed')\n        } else if (returningFromIdle) {\n            this._scheduleFullSnapshot()\n        }\n    }\n\n    private _clearConditionalRecordingPersistence(): void {\n        this._strategy?.clearConditionalRecordingPersistence()\n    }\n\n    get sdkDebugProperties(): Properties {\n        const { sessionStartTimestamp } = this._sessionManager.checkAndGetSessionAndWindowId(true)\n\n        return {\n            $recording_status: this.status,\n            $sdk_debug_replay_internal_buffer_length: this._buffer.data.length,\n            $sdk_debug_replay_internal_buffer_size: this._buffer.size,\n            $sdk_debug_current_session_duration: this._sessionDuration,\n            $sdk_debug_session_start: sessionStartTimestamp,\n            $sdk_debug_replay_flushed_size: this._flushedSizeTracker?.currentTrackedSize(this.sessionId),\n            $sdk_debug_replay_full_snapshots: this._fullSnapshotTimestamps,\n            $snapshot_max_depth_exceeded: this._maxDepthExceeded,\n            $sdk_debug_replay_rrweb_error: this._rrwebError,\n            [SDK_DEBUG_REPLAY_RRWEB_ATTACHED]: !!this._stopRrweb,\n            [SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED]: this._rrwebStartAttempted,\n        }\n    }\n\n    private _startRecorder() {\n        if (this._stopRrweb) {\n            return\n        }\n        this._rrwebStartAttempted = true\n\n        // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28\n        const sessionRecordingOptions: recordOptions = {\n            // a limited set of the rrweb config options that we expose to our users.\n            // see https://github.com/rrweb-io/rrweb/blob/master/guide.md\n            blockClass: 'ph-no-capture',\n            blockSelector: undefined,\n            ignoreClass: 'ph-ignore-input',\n            maskTextClass: 'ph-mask',\n            maskTextSelector: undefined,\n            maskTextFn: undefined,\n            maskAllInputs: true,\n            maskInputOptions: { password: true },\n            maskInputFn: undefined,\n            slimDOMOptions: {},\n            collectFonts: false,\n            inlineStylesheet: true,\n            recordCrossOriginIframes: false,\n            attributeFilter: undefined,\n        }\n\n        // only allows user to set our allowlisted options\n        const userSessionRecordingOptions = this._instance.config.session_recording\n        for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {\n            if (key in sessionRecordingOptions) {\n                if (key === 'maskInputOptions') {\n                    // ensure password config is set if not included\n                    sessionRecordingOptions.maskInputOptions = { password: true, ...value }\n                } else {\n                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                    // @ts-ignore\n                    sessionRecordingOptions[key] = value\n                }\n            }\n        }\n\n        if (this._canvasRecording && this._canvasRecording.enabled) {\n            sessionRecordingOptions.recordCanvas = true\n            sessionRecordingOptions.sampling = { canvas: this._canvasRecording.fps }\n            sessionRecordingOptions.dataURLOptions = { type: 'image/webp', quality: this._canvasRecording.quality }\n            sessionRecordingOptions.canvasResolutionScale = this._canvasResolutionScale\n        }\n\n        if (this._masking) {\n            sessionRecordingOptions.maskAllInputs = this._masking.maskAllInputs ?? true\n            sessionRecordingOptions.maskTextSelector = this._masking.maskTextSelector ?? undefined\n            sessionRecordingOptions.blockSelector = this._masking.blockSelector ?? undefined\n        }\n\n        const rrwebRecord = getRRWebRecord()\n        if (!rrwebRecord) {\n            logger.error(\n                '_startRecorder was called but rrwebRecord is not available. This indicates something has gone wrong.'\n            )\n            return\n        }\n\n        this._mutationThrottler =\n            this._mutationThrottler ??\n            new MutationThrottler(rrwebRecord, {\n                refillRate: this._instance.config.session_recording.__mutationThrottlerRefillRate,\n                bucketSize: this._instance.config.session_recording.__mutationThrottlerBucketSize,\n                onBlockedNode: (id, node) => {\n                    const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`\n                    logger.info(message, {\n                        node: node,\n                    })\n\n                    this.log(LOGGER_PREFIX + ' ' + message, 'warn')\n                },\n            })\n\n        const activePlugins = this._gatherRRWebPlugins()\n        this._stopRrweb = rrwebRecord({\n            emit: (event) => {\n                this.onRRwebEmit(event)\n            },\n            plugins: activePlugins,\n            ...sessionRecordingOptions,\n        })\n\n        if (!this._stopRrweb) {\n            this._rrwebError = true\n            logger.error(\n                'rrweb failed to start - Loss of recording data is possible. Check the browser console for rrweb errors.'\n            )\n            return\n        }\n\n        this._rrwebError = false\n\n        // We reset the last activity timestamp, resetting the idle timer\n        this._lastActivityTimestamp = Date.now()\n        // stay unknown if we're not sure if we're idle or not\n        this._isIdle = isBoolean(this._isIdle) ? this._isIdle : 'unknown'\n\n        this.tryAddCustomEvent('$remote_config_received', this._remoteConfig)\n        this._tryAddCustomEvent('$session_options', {\n            sessionRecordingOptions,\n            activePlugins: activePlugins.map((p) => p?.name),\n        })\n\n        this._tryAddCustomEvent('$posthog_config', {\n            config: this._instance.config,\n        })\n    }\n\n    tryAddCustomEvent(tag: string, payload: any): boolean {\n        return this._tryAddCustomEvent(tag, payload)\n    }\n}\n","import { record as rrwebRecord, wasMaxDepthReached, resetMaxDepthState } from '@posthog/rrweb-record'\nimport { getRecordConsolePlugin } from '@posthog/rrweb-plugin-console-record'\nimport { assignableWindow } from '../utils/globals'\nimport { getRecordNetworkPlugin } from '../extensions/replay/external/network-plugin'\nimport { LazyLoadedSessionRecording } from '../extensions/replay/external/lazy-loaded-session-recorder'\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.rrwebPlugins = { getRecordConsolePlugin, getRecordNetworkPlugin }\nassignableWindow.__PosthogExtensions__.rrweb = {\n    record: rrwebRecord,\n    version: 'v2',\n    wasMaxDepthReached,\n    resetMaxDepthState,\n}\nassignableWindow.__PosthogExtensions__.initSessionRecording = (ph) => new LazyLoadedSessionRecording(ph)\n\nexport default rrwebRecord\n"],"names":["_a","EventType","EventType2","IncrementalSource","IncrementalSource2","MouseInteractions","MouseInteractions2","PointerTypes","PointerTypes2","CanvasContext","CanvasContext2","MediaInteractions","MediaInteractions2","NodeType","NodeType2","_a2","_b","_c","_d","_a3","source","name","replacement","original","layer","next","wrapped","_len","arguments","length","args","Array","_key","apply","this","prototype","Object","defineProperties","__rrweb_original__","enumerable","value","__rrweb_layer__","current","currentLayer","_unused","win","window","undefined","global","globalThis","self","File","document","XMLHttpRequest","crc32Table","assignableWindow","NATIVE_GZIP_VALIDATION_ERROR","throwNativeGzipValidationError","reason","error","Error","validateNativeGzip","_ref","_asyncToGenerator","compressed","inputBytes","size","bytes","header","Uint8Array","slice","arrayBuffer","trailer","DataView","getUint32","table","getCrc32Table","i","crc","j","crc32","inputSize","_x","_x2","_gzipCompress","input","isDebug","options","TextEncoder","encode","compressedStream","CompressionStream","writer","writable","getWriter","writePromise","write","then","close","catch","_ref2","err","abort","_x6","responsePromise","Response","readable","blob","Promise","all","rethrow","console","ObjProto","type_utils_hasOwnProperty","hasOwnProperty","type_utils_toString","toString","isArray","obj","call","isFunction","x","isObject","isUndefined","isString","isNull","isNullish","isNumber","isBoolean","isFormData","FormData","clampToRange","min","max","logger","fallbackValue","warn","BucketedRateLimiter","constructor","_buckets","_onBucketRateLimited","_bucketSize","bucketSize","_logger","_refillRate","refillRate","_refillInterval","refillInterval","_applyRefill","bucket","now","refillIntervals","Math","floor","lastAccess","tokens","consumeRateLimit","key","_this$_onBucketRateLi","Date","keyStr","String","stop","stripUrlHash","url","split","isDocument","Document","Config","DEBUG","LIB_VERSION","LIB_NAME","_createLogger","prefix","_temp","debugEnabled","_log","level","POSTHOG_DEBUG","consoleLog","debug","_len2","_key2","info","_len3","_key3","_len4","_key4","_len5","_key5","critical","_len6","_key6","uninitializedWarning","methodName","createLogger","additionalPrefix","each","iterator","forEach","val","addEventListener","element","event","callback","_ref$capture","capture","_ref$passive","passive","localDomains","convertToURL","location","createElement","href","formDataToQuery","formdata","arg_separator","use_val","use_key","tph_arr","encodeURIComponent","isFile","join","noop","patch","__posthog_wrapped__","__posthog_layer__","isHostOnDenyList","_options$payloadHostD","hostname","URL","hostnameFromURL","defaultNotDenied","isHostDenied","payloadHostDenyList","trim","deny","endsWith","getTargetingUrl","instance","_window$location","defaultUrl","_instance$config","override","config","get_current_url","result","e","applyUrlTargetingOverride","SESSION_RECORDING_REMOTE_CONFIG","SESSION_RECORDING_SAMPLE_RATE","SESSION_RECORDING_OVERRIDE_SAMPLING","SESSION_RECORDING_OVERRIDE_LINKED_FLAG","SESSION_RECORDING_OVERRIDE_URL_TRIGGER","SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER","SESSION_RECORDING_IS_SAMPLED","SESSION_RECORDING_PAST_MINIMUM_DURATION","SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION","SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION","SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX","SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX","SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX","SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP","SESSION_RECORDING_FLUSHED_SIZE","STORED_PERSON_PROPERTIES_KEY","SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG","unanchoredCCRegex","RegExp","unanchoredSSNRegex","LOGGER_PREFIX","REDACTED","MAX_PAYLOAD_SIZE_BYTES","effectivePayloadLimitBytes","_options$payloadSizeL","payloadSizeLimitBytes","defaultNetworkOptions","initiatorTypes","maskRequestFn","data","recordHeaders","recordBody","recordInitialRequests","recordPerformance","performanceEntryTypeToObserve","streamNetworkBody","HEADER_DENY_LIST","PAYLOAD_CONTENT_DENY_LIST","HEADER_DENY_SUBSTRINGS","redactDeniedHeaders","headers","keys","lower","toLowerCase","includes","some","s","isDeniedHeader","POSTHOG_PATHS_TO_IGNORE","enforcePayloadSizeLimit","payload","limit","description","requestContentLength","Blob","estimateBytes","parseInt","scrubPayload","label","scrubbed","anchorRegexes","test","replace","shouldCaptureValue","text","_scrubbed","_scrubbed2","indexOf","isNavigationTiming","entry","entryType","isResourceTiming","shouldRecordHeaders","type","isRequest","Request","NEVER_RECORD_BODY_CONTENT_TYPES","shouldRecordBody","matchesContentType","contentTypes","contentTypeHeader","find","contentType","ct","isBlobURL","startsWith","protocol","_unused2","recordBodyType","getRequestPerformanceEntry","_x3","_x4","_x5","_getRequestPerformanceEntry","initiatorType","start","end","attempt","performanceEntry","array","predicate","startTime","findLast","performance","getEntriesByName","resolve","setTimeout","_tryReadXHRBody","body","_isHostOnDenyList","textContent","JSON","stringify","_unused3","exposesServerTiming","prepareRequest","_ref3","method","status","networkRequest","isInitial","responseEnd","timeOrigin","timestamp","requests","_extends","toJSON","round","endTime","requestHeaders","requestBody","responseHeaders","responseBody","timing","serverTiming","push","duration","contentTypePrefixDenyList","isReadableStreamBody","getReader","tee","BODY_READ_TIMEOUT_MS","BODY_READ_TIMEOUT_MESSAGE","BODY_READ_FAILED_MESSAGE","bodyReadFailedMessage","bodyTooLargeMessage","limitBytes","_readBody","r","timeout","clone","txt","finally","clearTimeout","_unused5","_tryReadBody","_r$headers","headerValue","get","contentLength","Number","isFinite","_unused4","_contentLengthExceedsLimit","reader","settled","cancel","_reader","_unused6","done","_unused7","TextDecoder","_unused9","chunks","received","pump","read","_ref5","streamDone","decode","totalBytes","merged","offset","chunk","set","byteLength","concatChunks","_unused8","_tryReadBodyStreaming","_tryReadRequestBody2","_ref6","_isHostOnDenyList3","_tryReadResponseBody2","_ref7","cannotReadBodyReason","_ref4","_r$headers$get","contentTypeIsDenied","_isHostOnDenyList2","_checkForCannotReadResponseBody","initialisedHandler","initNetworkObserver","networkOptions","assign","cb","request","maskedRequest","performanceObserver","initialPerformanceEntries","getEntries","filter","flatMap","observer","PerformanceObserver","entries","performanceEntries","wrappedInitiatorFilter","entryTypes","supportedEntryTypes","observe","disconnect","initPerformanceObserver","xhrObserver","fetchObserver","recordRequestHeaders","recordResponseHeaders","restorePatch","originalOpen","async","username","password","xhr","req","originalSetRequestHeader","setRequestHeader","bind","originalSend","send","cleanup","removeEventListener","readyStateListener","readyState","DONE","getAllResponseHeaders","line","parts","shift","response","initXhrObserver","originalFetch","_ref8","init","res","_x7","_tryReadRequestBody","_x8","_tryReadResponseBody","_res","_x9","_x0","initFetchObserver","DomContentLoaded","Load","FullSnapshot","IncrementalSnapshot","Meta","Custom","Plugin","Mutation","MouseMove","MouseInteraction","Scroll","ViewportResize","Input","TouchMove","MediaInteraction","StyleSheetRule","CanvasMutation","Font","Log","Drag","StyleDeclaration","Selection","AdoptedStyleSheet","CustomElement","DISABLED","SAMPLED","ACTIVE","BUFFERING","PAUSED","RRWEB_ERROR","TRIGGER","TRIGGER_ACTIVATED","TRIGGER_PENDING","TRIGGER_DISABLED","persistedTriggerStatus","triggerCount","groupId","groupPrefix","fallbackPersistenceKey","sessionId","get_property","sessionRecordingUrlTriggerMatches","triggers","compiledRegexCache","trigger","_compiledRegexCache$g","matching","OrTriggerMatching","_matchers","triggerStatus","statuses","map","m","AndTriggerMatching","Set","matcher","add","delete","from","AlwaysActivatedTriggerMatching","isEagerLoadedConfig","URLTriggerMatching","_instance","_urlTriggers","_urlBlocklist","_compiledTriggerRegexes","Map","_compiledBlocklistRegexes","_lastCheckedUrl","urlBlocked","_groupId","onConfig","_config$sessionRecord","_config$sessionRecord2","sessionRecording","urlTriggers","urlBlocklist","_compileRegexCache","clear","has","onRemoteConfig","_urlTriggerStatus","urlTriggerStatus","register_for_session","$sdk_debug_replay_url_trigger_status","checkUrlBlocklist","onPause","onResume","wasBlocked","isNowBlocked","checkUrlTriggerConditions","onActivate","isActivated","urlMatches","LinkedFlagMatching","linkedFlag","linkedFlagSeen","_flagListenerCleanup","$sdk_debug_replay_linked_flag_trigger_status","onStarted","_config$sessionRecord3","flag","linkedVariant","variant","onFeatureFlags","_flags","variants","linkedFlagMatches","variantForFlagKey","EventTriggerMatching","_eventTriggers","_config$sessionRecord4","eventTriggers","_eventTriggerStatus","eventTriggerStatus","$sdk_debug_replay_event_trigger_status","checkEventTriggerConditions","eventName","TriggerGroupMatching","group","onFlagStarted","_urlTriggerMatching","id","_eventTriggerMatching","_linkedFlagMatching","conditions","events","urls","eventNames","matchers","_combinedMatching","matchType","activateTrigger","triggerType","_this$_instance$persi","persistence","register","anyMatchSessionRecordingStatus","triggersStatus","rrwebError","receivedFlags","isRecordingEnabled","urlTriggerMatching","sampledActive","isSampled","triggerMatches","eventTriggerMatching","linkedFlagMatching","allMatchSessionRecordingStatus","currentTriggerStatus","hasTriggersConfigured","hasSamplingConfigured","circularReferenceReplacer","ancestors","pop","estimateSize","sizeable","stringifiedData","estimateCompressedEventSize","el","first","splitBuffer","buffer","sizeLimit","half","firstHalfSizes","sizes","secondHalfSizes","reduce","a","b","windowId","u8","u16","Uint16Array","u32","Uint32Array","fleb","fdeb","clim","freb","eb","revfl","revfd","rev","hMap","cd","mb","l","co","le","rvb","sv","r_1","v","flt","fdt","flm","fdm","shft","p","slc","n","subarray","wbits","d","o","wbits16","hTree","t","f","t2","sort","i0","i1","i2","maxSym","tr","mbt","ln","dt","lft","cst","i2_1","i2_2","i2_3","lc","c","cl","cli","cln","cls","w","clen","cf","wfblk","out","pos","dat","wblk","final","syms","lf","df","li","bs","bl","dlt","mlb","ddt","mdb","lclt","nlc","lcdt","ndc","lcfreq","_e","lct","mlcb","nlcc","lm","ll","dm","dl","flen","ftlen","dtlen","llm","lcts","it","clct","len","dst","deo","crct","k","cr","dopt","opt","pre","post","st","lvl","plvl","lst","msk_1","prev","head","bs1_1","ceil","bs2_1","hsh","lc_1","wi","hv","imod","pimod","rem","ch_1","dif","maxn","maxd","ml","nl","mmd","md","ti","lin","din","dflt","mem","log","wbytes","gzh","fn","filename","mtime","charCodeAt","gzhl","strFromU8","latin1","fromCharCode","MutationThrottler","_rrweb","_options","_this$_options$bucket","_this$_options$refill","_loggedTracker","_onNodeRateLimited","_this$_options$onBloc","_this$_options","node","_getNode","onBlockedNode","_getNodeOrRelevantParent","nodeName","Element","closestSVG","closest","mirror","getId","getNode","_numberOfChanges","_data$removes$length","_data$removes","_data$attributes$leng","_data$attributes","_data$texts$length","_data$texts","_data$adds$length","_data$adds","removes","attributes","texts","adds","throttleMutations","initialMutationCount","attr","_this$_getNodeOrRelev","_rateLimiter","mutationCount","reset","FlushedSizeTracker","posthog","_getProperty","_setProperty","set_property","trackSize","currentTrackedSize","stored","sampleOnProperty","prop","percent","str","hash","abs","simpleHash","isMatchingRegex","pattern","isValidRegex","propertyComparisons","exact","targets","values","target","is_not","every","regex","not_regex","icontains","not_icontains","gt","numValue","parseFloat","isNaN","lt","NEGATIVE_OPERATORS","matchTriggerPropertyFilters","filters","eventProperties","personProperties","propertyValue","operator","comparisonFunction","encodeSamplingDecision","decodeSamplingDecision","storedValue","V1RecordingStrategy","_reportStarted","_tryTakeFullSnapshot","_sampleRate","_recordingStatusFunction","sampleRate","triggerMatchType","_triggerStatusMatcher","getStatus","context","getMinimumDuration","minimumDurationMilliseconds","checkUrlTriggers","setupEventTriggerListeners","onEvent","_removeEventTriggerCaptureHook","makeSamplingDecisions","_this$_instance$persi3","_this$_instance$persi2","currentSampleRate","unregister","storedSampleRate","storedIsSampled","sampleRateChanged","sampledInWithoutStoredRate","makeDecision","shouldSample","ensureSamplingDecision","onFlushComplete","clearConditionalRecordingPersistence","_this$_instance$persi4","_this$_instance$persi5","_this$_instance$persi6","_this$_instance$persi7","_this$_instance$persi8","updateActiveTriggers","hasPendingTriggers","_this$_triggerStatusM","_this$_removeEventTri","V2TriggerGroupStrategy","_tryAddCustomEvent","_triggerGroupMatchers","_triggerGroupSamplingResults","_hasCompletedInitialFlush","triggerGroups","_setupTriggerGroups","$sdk_debug_replay_trigger_groups_count","groupMatchers","triggerGroupMatchers","samplingResults","triggerGroupSamplingResults","anyGroupPending","anyGroupSampled","groupStatus","samplingResult","triggerGroupsMatchSessionRecordingStatus","minimumDuration","lowestDuration","groupDuration","minDurationMs","_this","_loop","_checkGroupLevelProperties","_this2","_this$_removeEventTri2","_loop2","properties","matchedTriggers","_this$_instance$persi9","storageKey","storedDecision","sessionChanged","storedSessionId","storedSampled","sampled","group_id","group_name","_this$_instance$persi0","_this$_instance$persi1","_this$_instance$persi10","_this$_instance$persi11","_this$_instance$persi12","_this$_instance$persi13","recordingGroups","isMatched","matched","$sdk_debug_replay_matched_recording_trigger_groups","_this$_removeEventTri3","groupProperties","groups","_this3","_loop3","trunc","isInteger","crypto","PERSONAL_DATA_CAMPAIGN_PARAMS","networkTimingFromConfig","network_timing","_gzippedEmptyArray","_gzippedEmptyArrayPromise","ACTIVE_SOURCES","newQueuedEvent","rrwebMethod","enqueuedAt","getRRWeb","_assignableWindow$__P","__PosthogExtensions__","rrweb","getRRWebRecord","_getRRWeb","record","serializeForCompression","gzipToString","opts","gzipSync","ar","ai","strToU8","gzipToStringAsync","_gzipToStringAsync","serializedData","gzipCompress","_isNativeAsyncSessionRecordingGzipSupported","_nativeAsyncSessionRecordingGzipDisabled","gzipField","gzipFieldAsync","_gzipFieldAsync","shouldUseNativeAsyncSessionRecordingGzip","shouldCompressEvent","compressedResult","buildCompressedFullSnapshotEvent","cv","buildCompressedIncrementalEvent","fields","compressEventSync","_compressEventAsync","_yield$Promise$all","_yield$Promise$all2","isNativeAsyncGzipReadError","isNativeAsyncGzipError","isCustomEvent","tag","isSessionIdleEvent","isSessionEndingEvent","isSessionStartingEvent","LazyLoadedSessionRecording","_sessionId","_sessionManager","sessionManager","_sessionIdleThresholdMilliseconds","session_recording","session_idle_threshold_ms","FIVE_MINUTES","_isSampled","_this$_remoteConfig","rate","_remoteConfig","_minimumDuration","_this$_strategy$getMi","_this$_strategy","_strategy","_endpoint","_forceAllowLocalhostNetworkCapture","_stopRrweb","_lastActivityTimestamp","_isActivatingTrigger","_queuedRRWebEvents","_isIdle","_rrwebError","_rrwebStartAttempted","_maxDepthExceeded","_fullSnapshotTimestamps","_lastFullSnapshotSessionId","_fullSnapshotHealAttemptedFor","_pendingCompressionEvents","_queuedCompressionEvents","_compressionQueueGeneration","_isStoppingAfterCompression","_removePageViewCaptureHook","_onSessionIdListener","_onSessionIdleResetForcedListener","_forceIdleSessionIdListener","_onSessionIdCallback","changeReason","_getRRWeb2","_this$_strategy2","_windowId","_this$_flushedSizeTra","shouldLinkSessions","noSessionId","activityTimeout","sessionPastMaximumLength","oldSessionId","oldWindowId","currentSessionId","currentWindowId","nextSessionId","nextWindowId","lastActivityTimestamp","flushed_size","_flushedSizeTracker","resetMaxDepthState","_clearConditionalRecordingPersistence","isStarted","previousSessionId","previousWindowId","_hasPassedMinimumDuration","props","_getBufferDuration","_this$_buffer$data$","_this$_buffer$data","_buffer","firstTimestamp","lastTimestamp","_isBelowMinimumDuration","_this$_instance$confi","_this$_instance$confi2","strictMinimumDuration","sessionDuration","_sessionDuration","bufferDuration","_onBeforeUnload","_drainCompressionQueueSync","_flushBuffer","_clearBuffer","_onOffline","_onOnline","_onVisibilityChange","visibilityState","_this$_sessionManager","checkAndGetSessionAndWindowId","sessionTimeoutMs","_masking","_this$_remoteConfig2","_this$_instance$confi3","_this$_instance$confi4","_this$_instance$confi5","_masking_client_side$","_masking_client_side$2","_masking_client_side$3","masking_server_side","masking","masking_client_side","maskAllInputs","maskTextSelector","blockSelector","_canvasResolutionScale","_this$_instance$confi6","canvasCapture","resolutionScale","_canvasRecording","_this$_remoteConfig3","_canvasRecording_clie","_canvasRecording_clie2","_canvasRecording_clie3","canvasRecording_client_side","captureCanvas","canvasRecording_server_side","canvasRecording","enabled","recordCanvas","fps","canvasFps","quality","canvasQuality","parsed","_isConsoleLogCaptureEnabled","_this$_remoteConfig4","enabled_server_side","consoleLogRecordingEnabled","enabled_client_side","enable_recording_console_log","_networkPayloadCapture","_this$_remoteConfig5","_this$_instance$confi7","_this$_instance$confi8","networkPayloadCapture_server_side","networkPayloadCapture","networkPayloadCapture_client_side","headersEnabled","bodyEnabled","clientNetworkTiming","capture_performance","serverNetworkTiming","capturePerformance","networkTimingEnabled","_gatherRRWebPlugins","_assignableWindow$__P2","_assignableWindow$__P3","plugins","recordConsolePlugin","rrwebPlugins","getRecordConsolePlugin","instanceConfig","remoteNetworkOptions","canRecordHeaders","canRecordBody","canRecordPerformance","payloadLimiter","enforcedCleaningFn","hasDeprecatedMaskFunction","networkPlugin","getRecordNetworkPlugin","ignorePostHogPaths","apiHostConfig","_convertToURL","replaceValue","pathname","path","api_host","maskNetworkRequestFn","maskCapturedNetworkRequestFn","cleanedURL","_instanceConfig$sessi","cleanedRequest","capturedRequest","scrubPayloads","_stripUrlHash","disable_capture_url_hashes","_maskReplayUrl","forceStripHash","paramsToMask","mask_personal_data_properties","custom_personal_data_properties","_maskUrl","maskedParams","mask","splitHash","splitQuery","queryString","urlWithoutQueryAndHash","queryParts","paramStrings","keyValuePair","maskQueryParams","userSessionRecordingOptions","_result$name","_tryRRWebMethod","queuedRRWebEvent","addCustomEvent","_pageViewFallBack","capture_pageview","currentUrl","origin","search","_lastHref","_processQueuedEvents","itemsToProcess","takeFullSnapshot","_fullSnapshotIntervalMillis","_this$_strategy3","_this$_instance$confi9","_this$_instance$confi0","full_snapshot_interval_millis","ONE_MINUTE","_scheduleFullSnapshot","_fullSnapshotTimer","clearInterval","interval","setInterval","_pauseRecording","_resumeRecording","_activateTrigger","matchDetail","_this$_strategy4","_this$_strategy5","persistedConfig","parsedConfig","parse","_parsedConfig$cache_t","cacheTimestamp","cache_timestamp","_checkOverride","overrideFunction","clearOverride","startReason","_invalidateCompressionQueue","_this$_sessionManager2","endpoint","version","on","overrideSampling","overrideLinkedFlag","overrideTrigger","_startRecorder","onSessionId","_this$_forceIdleSessi","$current_url","_teardown","_this$_removePageView","_this$_onSessionIdLis","_this$_onSessionIdleR","_this$_forceIdleSessi2","_this$_strategy6","_clearFlushBufferTimer","_stopRecordingProducers","_compressionQueue","_this$_mutationThrott","_this$_stopRrweb","_mutationThrottler","_stopAfterCompressionQueueDrains","generation","discard","_captureProcessedEvent","eventToSend","targetSessionId","targetWindowId","_getRRWeb3","$snapshot_bytes","$snapshot_data","$session_id","$window_id","wasMaxDepthReached","_ensureFullSnapshotForSession","_captureSnapshotBuffered","_finishQueuedCompressionEvent","queuedEvent","counted","_captureQueuedCompressionEvent","processed","_processQueuedCompressionEventSync","compressionEnabled","_enqueueCompression","processEvent","compressEventAsync","onRRwebEmit","rawEvent","_this$_strategy7","_this$_strategy8","_sessionEndingPayload","_sessionEndingPayload2","_this$_instance$confi1","_this$_mutationThrott2","register_once","_clearBufferBeforeMostRecentMeta","throttledEvent","_event","plugin","updatedPayload","truncateLargeConsoleLogs","sessionEndingPayload","getSessionEndingPayload","sessionStartingPayload","getSessionStartingPayload","_updateWindowAndSessionIds","isAllowedWhenIdle","threshold","compress_events","remoteConfig","message","_this$_instance$sessi","trace","_currentMaskedHostname","maskedUrl","_flushBufferTimer","_this$_strategy9","isBelowMinimumDuration","_this$_strategy0","snapshotHostname","snapshotBuffer","_this$_flushedSizeTra2","_captureSnapshot","$lib","$lib_version","$snapshot_host","_this$_buffer","additionalBytes","ONE_KB","_url","requestRouter","endpointFor","_noTruncate","_batchKey","skip_client_rate_limiting","_this$_buffer2","_this$_buffer3","mostRecentSnapshot","_this$_sessionManager3","sessionStartTimestamp","lastMetaIndex","tagPayload","$session_recording_start_reason","_isInteractiveEvent","_event$data","isUserInteraction","eventTimestamp","bufferLength","bufferSize","returningFromIdle","idleWasUnknown","_this$_sessionManager4","sessionIdChanged","windowIdChanged","_this$_strategy1","sdkDebugProperties","_this$_flushedSizeTra3","_this$_sessionManager5","$recording_status","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_internal_buffer_size","$sdk_debug_current_session_duration","$sdk_debug_session_start","$sdk_debug_replay_flushed_size","$sdk_debug_replay_full_snapshots","$snapshot_max_depth_exceeded","$sdk_debug_replay_rrweb_error","$sdk_debug_rrweb_attached","$sdk_debug_rrweb_start_attempted","_this$_mutationThrott3","_this$_masking$maskAl","_this$_masking$maskTe","_this$_masking$blockS","sessionRecordingOptions","blockClass","ignoreClass","maskTextClass","maskTextFn","maskInputOptions","maskInputFn","slimDOMOptions","collectFonts","inlineStylesheet","recordCrossOriginIframes","attributeFilter","_ref0","sampling","canvas","dataURLOptions","canvasResolutionScale","rrwebRecord","__mutationThrottlerRefillRate","__mutationThrottlerBucketSize","activePlugins","emit","tryAddCustomEvent","initSessionRecording","ph"],"mappings":"ijBAAAA,mKAAIC,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