import { createMirror, rebuild, createCache } from '@chromaui/rrweb-snapshot';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

// ../../node_modules/@rrweb/types/dist/types.js
var NodeType = /* @__PURE__ */ ((NodeType2) => {
  NodeType2[NodeType2["Document"] = 0] = "Document";
  NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
  NodeType2[NodeType2["Element"] = 2] = "Element";
  NodeType2[NodeType2["Text"] = 3] = "Text";
  NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
  NodeType2[NodeType2["Comment"] = 5] = "Comment";
  return NodeType2;
})(NodeType || {});
var pageUrl = new URL(window.location.href);
pageUrl.pathname = "";
pageUrl.search = "";
var strippedUrl = pageUrl.toString().replace(/\/$/, "");
var findHtmlNode = /* @__PURE__ */ __name((node) => {
  if (node.type === NodeType.Element && node.tagName === "html") {
    return node;
  }
  if ("childNodes" in node) {
    return node.childNodes.find((childNode) => {
      return findHtmlNode(childNode);
    });
  }
  return void 0;
}, "findHtmlNode");
function snapshotFileName(snapshotId, viewport) {
  const fileNameParts = [
    snapshotId,
    viewport,
    "snapshot.json"
  ];
  return fileNameParts.join(".");
}
__name(snapshotFileName, "snapshotFileName");
async function fetchSnapshot(context) {
  const { url, id } = context.storyContext.parameters.server;
  const { viewport } = context.storyContext.globals;
  let viewportName;
  if (typeof viewport === "string") {
    viewportName = viewport;
  } else {
    viewportName = `w${viewport.width}h${viewport.height}`;
  }
  let response = await fetch(`${url}/${snapshotFileName(id, viewportName)}`);
  if (!response.ok) {
    const { defaultViewport } = context.storyContext.parameters.viewport;
    response = await fetch(`${url}/${snapshotFileName(id, defaultViewport)}`);
  }
  return response.json();
}
__name(fetchSnapshot, "fetchSnapshot");
var renderToCanvas = /* @__PURE__ */ __name(async (context) => {
  const { snapshot, pseudoClassIds } = await fetchSnapshot(context);
  const htmlNode = findHtmlNode(snapshot);
  const mirror = createMirror();
  const html = rebuild(htmlNode, {
    doc: document,
    mirror,
    cache: createCache()
  });
  for (const [className, ids] of Object.entries(pseudoClassIds)) {
    for (const id of ids) {
      const el = mirror.getNode(id);
      if (el?.classList) {
        el.classList.add(className);
      }
    }
  }
  document.replaceChild(html, document.children[0]);
  document.head.innerHTML += '<script id="storybook-root"><\/script><script id="storybook-docs"><\/script>';
  context.showMain();
  return () => {
  };
}, "renderToCanvas");
var preview_default = {
  renderToCanvas,
  parameters: {
    server: {
      url: strippedUrl
    },
    layout: "fullscreen"
  }
};

export { preview_default as default };
