(function injectDomWrapScript() {
  const script = document.createElement("script");
  script.textContent = `(() => {
    const wrappedMarker = "rrWrappedByTest";
    const errorPatterns = /error applying batch|unhandled exception on the current circuit/i;
    const errors = [];

    window.__rrDomWrapTestErrors = errors;

    const originalConsoleError = console.error.bind(console);
    console.error = (...args) => {
      const text = args.map((arg) => String(arg)).join(" ");
      if (errorPatterns.test(text)) {
        errors.push(text);
      }

      originalConsoleError(...args);
    };

    window.addEventListener("error", (event) => {
      const text = [event.message, event.filename, event.lineno, event.colno].filter(Boolean).join(" ");
      if (errorPatterns.test(text)) {
        errors.push(text);
      }
    });

    window.addEventListener("unhandledrejection", (event) => {
      const reason = event.reason ? String(event.reason) : "";
      if (errorPatterns.test(reason)) {
        errors.push(reason);
      }
    });

    function wrapControl(element) {
      if (!(element instanceof HTMLElement) || !element.isConnected || element.dataset[wrappedMarker] === "1") {
        return;
      }

      const parent = element.parentNode;
      if (!parent) {
        return;
      }

      const wrapper = document.createElement("span");
      wrapper.dataset[wrappedMarker] = "1";
      element.dataset[wrappedMarker] = "1";
      parent.insertBefore(wrapper, element);
      wrapper.appendChild(element);
    }

    function queueWrap(node) {
      if (!(node instanceof Element)) {
        return;
      }

      if (node.matches("input, select")) {
        queueMicrotask(() => wrapControl(node));
      }

      node.querySelectorAll("input, select").forEach((element) => {
        queueMicrotask(() => wrapControl(element));
      });
    }

    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach(queueWrap);
      });
    });

    observer.observe(document.documentElement, { childList: true, subtree: true });
    document.querySelectorAll("input, select").forEach((element) => queueWrap(element));
  })();`;

  (document.documentElement || document).appendChild(script);
  script.remove();
})();
