"use strict";
const util = newUtil();
const inliner = newInliner();
const fontFaces = newFontFaces();
const images = newImages();
const defaultOptions = {
  imagePlaceholder: void 0,
  cacheBust: false
};
const domtoimage = {
  toSvg,
  toPng,
  toJpeg,
  toBlob,
  toPixelData,
  impl: {
    fontFaces,
    images,
    util,
    inliner,
    options: {}
  }
};
function toSvg(node, options = {}) {
  copyOptions(options);
  return Promise.resolve(node).then((node2) => cloneNode(node2, options.filter, true)).then(embedFonts).then(inlineImages).then(applyOptions).then((clone) => {
    return makeSvgDataUri(
      clone,
      options.width || util.width(clone),
      options.height || util.height(clone)
    );
  });
  function applyOptions(clone) {
    if (options.bgcolor) clone.style.backgroundColor = options.bgcolor;
    if (options.width) clone.style.width = options.width + "px";
    if (options.height) clone.style.height = options.height + "px";
    if (options.style) {
      Object.keys(options.style).forEach((property) => {
        clone.style[property] = options.style[property];
      });
    }
    return clone;
  }
}
function toPixelData(node, options = {}) {
  return draw(node, options).then((canvas) => {
    return canvas.getContext("2d").getImageData(
      0,
      0,
      util.width(node),
      util.height(node)
    ).data;
  });
}
function toPng(node, options = {}) {
  return draw(node, options).then((canvas) => {
    return canvas.toDataURL();
  });
}
function toJpeg(node, options = {}) {
  return draw(node, options).then((canvas) => {
    return canvas.toDataURL("image/jpeg", options.quality || 1);
  });
}
function toBlob(node, options = {}) {
  return draw(node, options).then(util.canvasToBlob);
}
function copyOptions(options) {
  if (typeof options.imagePlaceholder === "undefined") {
    domtoimage.impl.options.imagePlaceholder = defaultOptions.imagePlaceholder;
  } else {
    domtoimage.impl.options.imagePlaceholder = options.imagePlaceholder;
  }
  if (typeof options.cacheBust === "undefined") {
    domtoimage.impl.options.cacheBust = defaultOptions.cacheBust;
  } else {
    domtoimage.impl.options.cacheBust = options.cacheBust;
  }
}
function draw(domNode, options) {
  const { scale = 1 } = options;
  return toSvg(domNode, options).then(util.makeImage).then(util.delay(100)).then((image) => {
    const { canvas, ctx } = newCanvas(domNode, options);
    ctx.drawImage(image, 0, 0, canvas.width / scale, canvas.height / scale);
    return canvas;
  });
  function newCanvas(domNode2, options2) {
    const canvas = document.createElement("canvas");
    const { scale: scale2 = 1 } = options2;
    canvas.width = (options2.width || util.width(domNode2)) * scale2;
    canvas.height = (options2.height || util.height(domNode2)) * scale2;
    const ctx = canvas.getContext("2d");
    ctx.scale(scale2, scale2);
    if (options2.bgcolor) {
      ctx.fillStyle = options2.bgcolor;
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
    return { canvas, ctx };
  }
}
function cloneNode(node, filter, root) {
  if (!root && filter && !filter(node)) return Promise.resolve(void 0);
  return Promise.resolve(node).then(makeNodeCopy).then((clone) => cloneChildren(node, clone, filter)).then((clone) => processClone(node, clone));
  function makeNodeCopy(node2) {
    if (node2 instanceof HTMLCanvasElement) {
      return util.makeImage(node2.toDataURL());
    }
    return node2.cloneNode(false);
  }
  function cloneChildren(original, clone, filter2) {
    const children = original.childNodes;
    if (children.length === 0) return Promise.resolve(clone);
    return cloneChildrenInOrder(clone, util.asArray(children), filter2).then(() => clone);
    function cloneChildrenInOrder(parent, children2, filter3) {
      let done = Promise.resolve();
      children2.forEach((child) => {
        done = done.then(() => cloneNode(child, filter3)).then((childClone) => {
          if (childClone) parent.appendChild(childClone);
        });
      });
      return done;
    }
  }
  function processClone(original, clone) {
    if (!(clone instanceof Element)) return Promise.resolve(clone);
    return Promise.resolve().then(cloneStyle).then(clonePseudoElements).then(copyUserInput).then(fixSvg).then(() => clone);
    function cloneStyle() {
      copyStyle(window.getComputedStyle(original), clone.style);
      function copyStyle(source, target) {
        if (source.cssText) {
          target.cssText = source.cssText;
        } else {
          copyProperties(source, target);
        }
        function copyProperties(source2, target2) {
          util.asArray(source2).forEach((name) => {
            target2.setProperty(
              name,
              source2.getPropertyValue(name),
              source2.getPropertyPriority(name)
            );
          });
        }
      }
    }
    function clonePseudoElements() {
      [":before", ":after"].forEach((element) => {
        clonePseudoElement(element);
      });
      function clonePseudoElement(element) {
        const style = window.getComputedStyle(original, element);
        const content = style.getPropertyValue("content");
        if (content === "" || content === "none") return;
        const className = util.uid();
        clone.className = clone.className + " " + className;
        const styleElement = document.createElement("style");
        styleElement.appendChild(formatPseudoElementStyle(className, element, style));
        clone.appendChild(styleElement);
        function formatPseudoElementStyle(className2, element2, style2) {
          const selector = "." + className2 + ":" + element2;
          const cssText = style2.cssText ? formatCssText(style2) : formatCssProperties(style2);
          return document.createTextNode(selector + "{" + cssText + "}");
          function formatCssText(style3) {
            const content2 = style3.getPropertyValue("content");
            return style3.cssText + " content: " + content2 + ";";
          }
          function formatCssProperties(style3) {
            return util.asArray(style3).map(formatProperty).join("; ") + ";";
            function formatProperty(name) {
              return name + ": " + style3.getPropertyValue(name) + (style3.getPropertyPriority(name) ? " !important" : "");
            }
          }
        }
      }
    }
    function copyUserInput() {
      if (original instanceof HTMLTextAreaElement) {
        clone.innerHTML = original.value;
      }
      if (original instanceof HTMLInputElement) {
        clone.setAttribute("value", original.value);
      }
    }
    function fixSvg() {
      if (!(clone instanceof SVGElement)) return;
      clone.setAttribute("xmlns", "http://www.w3.org/2000/svg");
      if (!(clone instanceof SVGRectElement)) return;
      ["width", "height"].forEach((attribute) => {
        const value = clone.getAttribute(attribute);
        if (!value) return;
        clone.style.setProperty(attribute, value);
      });
    }
  }
}
function embedFonts(node) {
  return fontFaces.resolveAll().then((cssText) => {
    const styleNode = document.createElement("style");
    node.appendChild(styleNode);
    styleNode.appendChild(document.createTextNode(cssText));
    return node;
  });
}
function inlineImages(node) {
  return images.inlineAll(node).then(() => node);
}
function makeSvgDataUri(node, width, height) {
  return Promise.resolve(node).then((node2) => {
    node2.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
    return new XMLSerializer().serializeToString(node2);
  }).then(util.escapeXhtml).then((xhtml) => {
    return '<foreignObject x="0" y="0" width="100%" height="100%">' + xhtml + "</foreignObject>";
  }).then((foreignObject) => {
    return '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' + foreignObject + "</svg>";
  }).then((svg) => {
    return "data:image/svg+xml;charset=utf-8," + svg;
  });
}
function newUtil() {
  return {
    escape,
    parseExtension,
    mimeType,
    dataAsUrl,
    isDataUrl,
    canvasToBlob,
    resolveUrl,
    getAndEncode,
    uid: uid(),
    delay,
    asArray,
    escapeXhtml,
    makeImage,
    width,
    height
  };
  function mimes() {
    const WOFF = "application/font-woff";
    const JPEG = "image/jpeg";
    return {
      "woff": WOFF,
      "woff2": WOFF,
      "ttf": "application/font-truetype",
      "eot": "application/vnd.ms-fontobject",
      "png": "image/png",
      "jpg": JPEG,
      "jpeg": JPEG,
      "gif": "image/gif",
      "tiff": "image/tiff",
      "svg": "image/svg+xml"
    };
  }
  function parseExtension(url) {
    const match = /\.([^\.\/]*?)$/g.exec(url);
    if (match) return match[1];
    else return "";
  }
  function mimeType(url) {
    const extension = parseExtension(url).toLowerCase();
    return mimes()[extension] || "";
  }
  function isDataUrl(url) {
    return url.search(/^(data:)/) !== -1;
  }
  function toBlob2(canvas) {
    return new Promise((resolve) => {
      const binaryString = window.atob(canvas.toDataURL().split(",")[1]);
      const length = binaryString.length;
      const binaryArray = new Uint8Array(length);
      for (let i = 0; i < length; i++)
        binaryArray[i] = binaryString.charCodeAt(i);
      resolve(new Blob([binaryArray], {
        type: "image/png"
      }));
    });
  }
  function canvasToBlob(canvas) {
    if (canvas.toBlob) {
      return new Promise((resolve) => {
        canvas.toBlob(resolve);
      });
    }
    return toBlob2(canvas);
  }
  function resolveUrl(url, baseUrl) {
    const doc = document.implementation.createHTMLDocument();
    const base = doc.createElement("base");
    doc.head.appendChild(base);
    const a = doc.createElement("a");
    doc.body.appendChild(a);
    base.href = baseUrl;
    a.href = url;
    return a.href;
  }
  function uid() {
    let index = 0;
    return function() {
      return "u" + fourRandomChars() + index++;
      function fourRandomChars() {
        return ("0000" + (Math.random() * Math.pow(36, 4) << 0).toString(36)).slice(-4);
      }
    };
  }
  function makeImage(uri) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.onload = () => resolve(image);
      image.onerror = reject;
      image.src = uri;
    });
  }
  function getAndEncode(url) {
    const TIMEOUT = 3e4;
    if (domtoimage.impl.options.cacheBust) {
      url += (/\?/.test(url) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime();
    }
    return new Promise((resolve) => {
      const request = new XMLHttpRequest();
      request.onreadystatechange = done;
      request.ontimeout = timeout;
      request.responseType = "blob";
      request.timeout = TIMEOUT;
      request.open("GET", url, true);
      request.send();
      let placeholder;
      if (domtoimage.impl.options.imagePlaceholder) {
        const split = domtoimage.impl.options.imagePlaceholder.split(/,/);
        if (split && split[1]) {
          placeholder = split[1];
        }
      }
      function done() {
        if (request.readyState !== 4) return;
        if (request.status !== 200) {
          if (placeholder) {
            resolve(placeholder);
          } else {
            fail("cannot fetch resource: " + url + ", status: " + request.status);
          }
          return;
        }
        const encoder = new FileReader();
        encoder.onloadend = () => {
          const content = encoder.result.split(/,/)[1];
          resolve(content);
        };
        encoder.readAsDataURL(request.response);
      }
      function timeout() {
        if (placeholder) {
          resolve(placeholder);
        } else {
          fail("timeout of " + TIMEOUT + "ms occured while fetching resource: " + url);
        }
      }
      function fail(message) {
        console.error(message);
        resolve("");
      }
    });
  }
  function dataAsUrl(content, type) {
    return "data:" + type + ";base64," + content;
  }
  function escape(string) {
    return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
  }
  function delay(ms) {
    return function(arg) {
      return new Promise((resolve) => {
        setTimeout(() => resolve(arg), ms);
      });
    };
  }
  function asArray(arrayLike) {
    const array = [];
    const length = arrayLike.length;
    for (let i = 0; i < length; i++) array.push(arrayLike[i]);
    return array;
  }
  function escapeXhtml(string) {
    return string.replace(/#/g, "%23").replace(/\n/g, "%0A");
  }
  function width(node) {
    const leftBorder = px(node, "border-left-width");
    const rightBorder = px(node, "border-right-width");
    return node.scrollWidth + leftBorder + rightBorder;
  }
  function height(node) {
    const topBorder = px(node, "border-top-width");
    const bottomBorder = px(node, "border-bottom-width");
    return node.scrollHeight + topBorder + bottomBorder;
  }
  function px(node, styleProperty) {
    const value = window.getComputedStyle(node).getPropertyValue(styleProperty);
    return parseFloat(value.replace("px", ""));
  }
}
function newInliner() {
  const URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/g;
  return {
    inlineAll,
    shouldProcess,
    impl: {
      readUrls,
      inline
    }
  };
  function shouldProcess(string) {
    return string.search(URL_REGEX) !== -1;
  }
  function readUrls(string) {
    const result = [];
    let match;
    while ((match = URL_REGEX.exec(string)) !== null) {
      result.push(match[1]);
    }
    return result.filter((url) => !util.isDataUrl(url));
  }
  function inline(string, url, baseUrl, get) {
    return Promise.resolve(url).then((url2) => baseUrl ? util.resolveUrl(url2, baseUrl) : url2).then(get || util.getAndEncode).then((data) => util.dataAsUrl(data, util.mimeType(url))).then((dataUrl) => string.replace(urlAsRegex(url), "$1" + dataUrl + "$3"));
    function urlAsRegex(url2) {
      return new RegExp(`(url\\(['"]?)(` + util.escape(url2) + `)(['"]?\\))`, "g");
    }
  }
  function inlineAll(string, baseUrl, get) {
    if (nothingToInline()) return Promise.resolve(string);
    return Promise.resolve(string).then(readUrls).then((urls) => {
      let done = Promise.resolve(string);
      urls.forEach((url) => {
        done = done.then((string2) => inline(string2, url, baseUrl, get));
      });
      return done;
    });
    function nothingToInline() {
      return !shouldProcess(string);
    }
  }
}
function newFontFaces() {
  return {
    resolveAll,
    impl: {
      readAll
    }
  };
  function resolveAll() {
    return readAll(document).then((webFonts) => {
      return Promise.all(
        webFonts.map((webFont) => webFont.resolve())
      );
    }).then((cssStrings) => cssStrings.join("\n"));
  }
  function readAll() {
    return Promise.resolve(util.asArray(document.styleSheets)).then(getCssRules).then(selectWebFontRules).then((rules) => rules.map(newWebFont));
    function selectWebFontRules(cssRules) {
      return cssRules.filter((rule) => rule.type === CSSRule.FONT_FACE_RULE).filter((rule) => inliner.shouldProcess(rule.style.getPropertyValue("src")));
    }
    function getCssRules(styleSheets) {
      const cssRules = [];
      styleSheets.forEach((sheet) => {
        try {
          util.asArray(sheet.cssRules || []).forEach(cssRules.push.bind(cssRules));
        } catch (e) {
          console.log("Error while reading CSS rules from " + sheet.href, e.toString());
        }
      });
      return cssRules;
    }
    function newWebFont(webFontRule) {
      return {
        resolve: function resolve() {
          const baseUrl = webFontRule.parentStyleSheet?.href;
          return inliner.inlineAll(webFontRule.cssText, baseUrl);
        },
        src: function() {
          return webFontRule.style.getPropertyValue("src");
        }
      };
    }
  }
}
function newImages() {
  return {
    inlineAll,
    impl: {
      newImage
    }
  };
  function newImage(element) {
    return {
      inline
    };
    function inline(get) {
      if (util.isDataUrl(element.src)) return Promise.resolve();
      return Promise.resolve(element.src).then(get || util.getAndEncode).then((data) => util.dataAsUrl(data, util.mimeType(element.src))).then((dataUrl) => {
        return new Promise((resolve, reject) => {
          element.onload = () => resolve();
          element.onerror = reject;
          element.src = dataUrl;
        });
      });
    }
  }
  function inlineAll(node) {
    if (!(node instanceof Element)) return Promise.resolve(node);
    return inlineBackground(node).then(
      // @ts-ignore
      () => {
        if (node instanceof HTMLImageElement) {
          return newImage(node).inline();
        } else {
          return Promise.all(
            util.asArray(node.childNodes).map((child) => inlineAll(child))
          );
        }
      }
    ).then(() => node);
    function inlineBackground(node2) {
      const background = node2.style.getPropertyValue("background");
      if (!background) return Promise.resolve(node2);
      return inliner.inlineAll(background).then((inlined) => {
        node2.style.setProperty(
          "background",
          inlined,
          node2.style.getPropertyPriority("background")
        );
      }).then(() => node2);
    }
  }
}

export { domtoimage as default };
//# sourceMappingURL=dom-to-image.mjs.map
