'use strict';

var rrwebSnapshot = require('@chromaui/rrweb-snapshot');

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var takeSnapshot = /* @__PURE__ */ __name((doc, viewport, isManualSnapshot) => {
  return new Promise((resolve) => {
    if (!isManualSnapshot && Cypress.env("disableAutoSnapshot")) {
      resolve(null);
    }
    const mirror = rrwebSnapshot.createMirror();
    const domSnapshot = rrwebSnapshot.snapshot(doc, {
      recordCanvas: true,
      mirror
    });
    const pseudoClassIds = {};
    for (const className of [
      ":hover",
      ":focus",
      ":focus-visible",
      ":active"
    ]) {
      const elements = doc.querySelectorAll(className);
      const ids = Array.from(elements, (el) => mirror.getId(el)).filter((id) => id !== -1);
      pseudoClassIds[className] = ids;
    }
    const toDataURL = /* @__PURE__ */ __name(async (url) => {
      const response = await fetch(url);
      const blob = await response.blob();
      return new Promise((resolveFileRead, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolveFileRead(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    }, "toDataURL");
    const replaceBlobUrls = /* @__PURE__ */ __name(async (node) => {
      await Promise.all(
        // @ts-expect-error we assume childNodes will be on there
        node.childNodes.map(async (childNode) => {
          if (childNode.tagName === "img" && childNode.attributes.src?.startsWith("blob:")) {
            const base64Url = await toDataURL(childNode.attributes.src);
            childNode.attributes.src = base64Url;
          }
          if (childNode.childNodes?.length) {
            await replaceBlobUrls(childNode);
          }
        })
      );
    }, "replaceBlobUrls");
    replaceBlobUrls(domSnapshot).then(() => {
      resolve({
        snapshot: domSnapshot,
        viewport,
        pseudoClassIds
      });
    });
  });
}, "takeSnapshot");

// src/commands.ts
Cypress.Commands.add("takeSnapshot", (name) => {
  if (!Cypress.config("isTextTerminal")) {
    return;
  }
  cy.window().then((win) => {
    const viewport = {
      width: win.innerWidth,
      height: win.innerHeight
    };
    cy.document().then((doc) => {
      cy.wrap(takeSnapshot(doc, viewport, true)).then((manualSnapshot) => {
        cy.get("@manualSnapshots").then((snapshots) => {
          return [
            ...snapshots,
            {
              ...manualSnapshot,
              name
            }
          ];
        }).as("manualSnapshots");
      });
    });
  });
});

// src/support.ts
var buildChromaticParams = /* @__PURE__ */ __name((env) => ({
  ...env("diffThreshold") && {
    diffThreshold: env("diffThreshold")
  },
  ...env("delay") && {
    delay: env("delay")
  },
  ...env("diffIncludeAntiAliasing") && {
    diffIncludeAntiAliasing: env("diffIncludeAntiAliasing")
  },
  ...env("diffThreshold") && {
    diffThreshold: env("diffThreshold")
  },
  ...env("forcedColors") && {
    forcedColors: env("forcedColors")
  },
  ...env("pauseAnimationAtEnd") && {
    pauseAnimationAtEnd: env("pauseAnimationAtEnd")
  },
  ...env("prefersReducedMotion") && {
    prefersReducedMotion: env("prefersReducedMotion")
  },
  ...env("cropToViewport") && {
    cropToViewport: env("cropToViewport")
  },
  ...env("ignoreSelectors") && {
    ignoreSelectors: env("ignoreSelectors")
  }
}), "buildChromaticParams");
beforeEach(() => {
  if (!Cypress.config("isTextTerminal")) {
    return;
  }
  cy.wrap([]).as("manualSnapshots");
  cy.task("prepareArchives", {
    action: "setup-network-listener",
    payload: {
      allowedDomains: Cypress.env("assetDomains")
    }
  });
});
afterEach(() => {
  if (!Cypress.config("isTextTerminal")) {
    return;
  }
  cy.window().then((win) => {
    const viewport = {
      width: win.innerWidth,
      height: win.innerHeight
    };
    cy.document().then((doc) => {
      cy.wrap(takeSnapshot(doc, viewport)).then((automaticSnapshot) => {
        cy.get("@manualSnapshots").then((manualSnapshots = []) => {
          cy.url().then((url) => {
            cy.task("prepareArchives", {
              action: "save-archives",
              payload: {
                testTitlePath: [
                  // @ts-expect-error relativeToCommonRoot is on spec (but undocumented)
                  Cypress.spec.relativeToCommonRoot,
                  ...Cypress.currentTest.titlePath
                ],
                domSnapshots: [
                  ...manualSnapshots,
                  ...automaticSnapshot ? [
                    automaticSnapshot
                  ] : []
                ],
                chromaticStorybookParams: buildChromaticParams(Cypress.env),
                pageUrl: url,
                outputDir: Cypress.config("downloadsFolder")
              }
            });
          });
        });
      });
    });
  });
});
