import {
  BaseException,
  FeatureTest,
  OPS,
  Util,
  shadow,
  stringToBytes,
  unreachable,
  updateUrlHash,
  warn
} from "./chunk-T2JWSGAF.js";
import {
  __privateAdd,
  __privateGet,
  __privateMethod,
  __privateSet,
  __privateWrapper,
  __publicField
} from "./chunk-ZFIGV5OT.js";

// src/lib/NodeUtils.ts
import {
  DOMMatrix as NodeDOMMatrix,
  DOMPoint as NodeDOMPoint,
  ImageData as NodeImageData,
  Path2D as NodePath2D
} from "skia-canvas";

// src/pdf.js/src/display/xfa_text.js
var XfaText = class _XfaText {
  /**
   * Walk an XFA tree and create an array of text nodes that is compatible
   * with a regular PDFs TextContent. Currently, only TextItem.str is supported,
   * all other fields and styles haven't been implemented.
   *
   * @param {Object} xfa - An XFA fake DOM object.
   *
   * @returns {TextContent}
   */
  static textContent(xfa) {
    const items = [];
    const output = {
      items,
      styles: /* @__PURE__ */ Object.create(null)
    };
    function walk(node) {
      if (!node) {
        return;
      }
      let str = null;
      const name = node.name;
      if (name === "#text") {
        str = node.value;
      } else if (!_XfaText.shouldBuildText(name)) {
        return;
      } else if (node?.attributes?.textContent) {
        str = node.attributes.textContent;
      } else if (node.value) {
        str = node.value;
      }
      if (str !== null) {
        items.push({
          str
        });
      }
      if (!node.children) {
        return;
      }
      for (const child of node.children) {
        walk(child);
      }
    }
    walk(xfa);
    return output;
  }
  /**
   * @param {string} name - DOM node name. (lower case)
   *
   * @returns {boolean} true if the DOM node should have a corresponding text
   * node.
   */
  static shouldBuildText(name) {
    return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  }
};

// src/pdf.js/src/display/xfa_layer.js
var XfaLayer = class {
  static setupStorage(html, id, element, storage, intent) {
    const storedData = storage.getValue(id, { value: null });
    switch (element.name) {
      case "textarea":
        if (storedData.value !== null) {
          html.textContent = storedData.value;
        }
        if (intent === "print") {
          break;
        }
        html.addEventListener("input", (event) => {
          storage.setValue(id, { value: event.target.value });
        });
        break;
      case "input":
        if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
          if (storedData.value === element.attributes.xfaOn) {
            html.setAttribute("checked", true);
          } else if (storedData.value === element.attributes.xfaOff) {
            html.removeAttribute("checked");
          }
          if (intent === "print") {
            break;
          }
          html.addEventListener("change", (event) => {
            storage.setValue(id, {
              value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
            });
          });
        } else {
          if (storedData.value !== null) {
            html.setAttribute("value", storedData.value);
          }
          if (intent === "print") {
            break;
          }
          html.addEventListener("input", (event) => {
            storage.setValue(id, { value: event.target.value });
          });
        }
        break;
      case "select":
        if (storedData.value !== null) {
          html.setAttribute("value", storedData.value);
          for (const option of element.children) {
            if (option.attributes.value === storedData.value) {
              option.attributes.selected = true;
            } else if (option.attributes.hasOwnProperty("selected")) {
              delete option.attributes.selected;
            }
          }
        }
        html.addEventListener("input", (event) => {
          const options = event.target.options;
          const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
          storage.setValue(id, { value });
        });
        break;
    }
  }
  static setAttributes({ html, element, storage = null, intent, linkService }) {
    const { attributes } = element;
    const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
    if (attributes.type === "radio") {
      attributes.name = `${attributes.name}-${intent}`;
    }
    for (const [key, value] of Object.entries(attributes)) {
      if (value === null || value === void 0) {
        continue;
      }
      switch (key) {
        case "class":
          if (value.length) {
            html.setAttribute(key, value.join(" "));
          }
          break;
        case "dataId":
          break;
        case "id":
          html.setAttribute("data-element-id", value);
          break;
        case "style":
          Object.assign(html.style, value);
          break;
        case "textContent":
          html.textContent = value;
          break;
        default:
          if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
            html.setAttribute(key, value);
          }
      }
    }
    if (isHTMLAnchorElement) {
      linkService.addLinkAttributes(
        html,
        attributes.href,
        attributes.newWindow
      );
    }
    if (storage && attributes.dataId) {
      this.setupStorage(html, attributes.dataId, element, storage);
    }
  }
  /**
   * Render the XFA layer.
   *
   * @param {XfaLayerParameters} parameters
   */
  static render(parameters) {
    const storage = parameters.annotationStorage;
    const linkService = parameters.linkService;
    const root = parameters.xfaHtml;
    const intent = parameters.intent || "display";
    const rootHtml = document.createElement(root.name);
    if (root.attributes) {
      this.setAttributes({
        html: rootHtml,
        element: root,
        intent,
        linkService
      });
    }
    const isNotForRichText = intent !== "richText";
    const rootDiv = parameters.div;
    rootDiv.append(rootHtml);
    if (parameters.viewport) {
      const transform = `matrix(${parameters.viewport.transform.join(",")})`;
      rootDiv.style.transform = transform;
    }
    if (isNotForRichText) {
      rootDiv.setAttribute("class", "xfaLayer xfaFont");
    }
    const textDivs = [];
    if (root.children.length === 0) {
      if (root.value) {
        const node = document.createTextNode(root.value);
        rootHtml.append(node);
        if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
          textDivs.push(node);
        }
      }
      return { textDivs };
    }
    const stack = [[root, -1, rootHtml]];
    while (stack.length > 0) {
      const [parent, i, html] = stack.at(-1);
      if (i + 1 === parent.children.length) {
        stack.pop();
        continue;
      }
      const child = parent.children[++stack.at(-1)[1]];
      if (child === null) {
        continue;
      }
      const { name } = child;
      if (name === "#text") {
        const node = document.createTextNode(child.value);
        textDivs.push(node);
        html.append(node);
        continue;
      }
      const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
      html.append(childHtml);
      if (child.attributes) {
        this.setAttributes({
          html: childHtml,
          element: child,
          storage,
          intent,
          linkService
        });
      }
      if (child.children?.length > 0) {
        stack.push([child, -1, childHtml]);
      } else if (child.value) {
        const node = document.createTextNode(child.value);
        if (isNotForRichText && XfaText.shouldBuildText(name)) {
          textDivs.push(node);
        }
        childHtml.append(node);
      }
    }
    for (const el of rootDiv.querySelectorAll(
      ".xfaNonInteractive input, .xfaNonInteractive textarea"
    )) {
      el.setAttribute("readOnly", true);
    }
    return {
      textDivs
    };
  }
  /**
   * Update the XFA layer.
   *
   * @param {XfaLayerParameters} parameters
   */
  static update(parameters) {
    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
    parameters.div.style.transform = transform;
    parameters.div.hidden = false;
  }
};

// src/pdf.js/src/display/display_utils.js
var SVG_NS = "http://www.w3.org/2000/svg";
var _PixelsPerInch = class _PixelsPerInch {
};
__publicField(_PixelsPerInch, "CSS", 96);
__publicField(_PixelsPerInch, "PDF", 72);
__publicField(_PixelsPerInch, "PDF_TO_CSS_UNITS", _PixelsPerInch.CSS / _PixelsPerInch.PDF);
var PixelsPerInch = _PixelsPerInch;
async function fetchData(url, type = "text") {
  if (isValidFetchUrl(url, document.baseURI)) {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    switch (type) {
      case "arraybuffer":
        return response.arrayBuffer();
      case "blob":
        return response.blob();
      case "json":
        return response.json();
    }
    return response.text();
  }
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open(
      "GET",
      url,
      /* async = */
      true
    );
    request.responseType = type;
    request.onreadystatechange = () => {
      if (request.readyState !== XMLHttpRequest.DONE) {
        return;
      }
      if (request.status === 200 || request.status === 0) {
        switch (type) {
          case "arraybuffer":
          case "blob":
          case "json":
            resolve(request.response);
            return;
        }
        resolve(request.responseText);
        return;
      }
      reject(new Error(request.statusText));
    };
    request.send(null);
  });
}
var PageViewport = class _PageViewport {
  /**
   * @param {PageViewportParameters}
   */
  constructor({
    viewBox,
    userUnit,
    scale,
    rotation,
    offsetX = 0,
    offsetY = 0,
    dontFlip = false
  }) {
    this.viewBox = viewBox;
    this.userUnit = userUnit;
    this.scale = scale;
    this.rotation = rotation;
    this.offsetX = offsetX;
    this.offsetY = offsetY;
    scale *= userUnit;
    const centerX = (viewBox[2] + viewBox[0]) / 2;
    const centerY = (viewBox[3] + viewBox[1]) / 2;
    let rotateA, rotateB, rotateC, rotateD;
    rotation %= 360;
    if (rotation < 0) {
      rotation += 360;
    }
    switch (rotation) {
      case 180:
        rotateA = -1;
        rotateB = 0;
        rotateC = 0;
        rotateD = 1;
        break;
      case 90:
        rotateA = 0;
        rotateB = 1;
        rotateC = 1;
        rotateD = 0;
        break;
      case 270:
        rotateA = 0;
        rotateB = -1;
        rotateC = -1;
        rotateD = 0;
        break;
      case 0:
        rotateA = 1;
        rotateB = 0;
        rotateC = 0;
        rotateD = -1;
        break;
      default:
        throw new Error(
          "PageViewport: Invalid rotation, must be a multiple of 90 degrees."
        );
    }
    if (dontFlip) {
      rotateC = -rotateC;
      rotateD = -rotateD;
    }
    let offsetCanvasX, offsetCanvasY;
    let width, height;
    if (rotateA === 0) {
      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
      width = (viewBox[3] - viewBox[1]) * scale;
      height = (viewBox[2] - viewBox[0]) * scale;
    } else {
      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
      width = (viewBox[2] - viewBox[0]) * scale;
      height = (viewBox[3] - viewBox[1]) * scale;
    }
    this.transform = [
      rotateA * scale,
      rotateB * scale,
      rotateC * scale,
      rotateD * scale,
      offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
      offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
    ];
    this.width = width;
    this.height = height;
  }
  /**
   * The original, un-scaled, viewport dimensions.
   * @type {Object}
   */
  get rawDims() {
    const dims = this.viewBox;
    return shadow(this, "rawDims", {
      pageWidth: dims[2] - dims[0],
      pageHeight: dims[3] - dims[1],
      pageX: dims[0],
      pageY: dims[1]
    });
  }
  /**
   * Clones viewport, with optional additional properties.
   * @param {PageViewportCloneParameters} [params]
   * @returns {PageViewport} Cloned viewport.
   */
  clone({
    scale = this.scale,
    rotation = this.rotation,
    offsetX = this.offsetX,
    offsetY = this.offsetY,
    dontFlip = false
  } = {}) {
    return new _PageViewport({
      viewBox: this.viewBox.slice(),
      userUnit: this.userUnit,
      scale,
      rotation,
      offsetX,
      offsetY,
      dontFlip
    });
  }
  /**
   * Converts PDF point to the viewport coordinates. For examples, useful for
   * converting PDF location into canvas pixel coordinates.
   * @param {number} x - The x-coordinate.
   * @param {number} y - The y-coordinate.
   * @returns {Array} Array containing `x`- and `y`-coordinates of the
   *   point in the viewport coordinate space.
   * @see {@link convertToPdfPoint}
   * @see {@link convertToViewportRectangle}
   */
  convertToViewportPoint(x, y) {
    const p = [x, y];
    Util.applyTransform(p, this.transform);
    return p;
  }
  /**
   * Converts PDF rectangle to the viewport coordinates.
   * @param {Array} rect - The xMin, yMin, xMax and yMax coordinates.
   * @returns {Array} Array containing corresponding coordinates of the
   *   rectangle in the viewport coordinate space.
   * @see {@link convertToViewportPoint}
   */
  convertToViewportRectangle(rect) {
    const topLeft = [rect[0], rect[1]];
    Util.applyTransform(topLeft, this.transform);
    const bottomRight = [rect[2], rect[3]];
    Util.applyTransform(bottomRight, this.transform);
    return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  }
  /**
   * Converts viewport coordinates to the PDF location. For examples, useful
   * for converting canvas pixel location into PDF one.
   * @param {number} x - The x-coordinate.
   * @param {number} y - The y-coordinate.
   * @returns {Array} Array containing `x`- and `y`-coordinates of the
   *   point in the PDF coordinate space.
   * @see {@link convertToViewportPoint}
   */
  convertToPdfPoint(x, y) {
    const p = [x, y];
    Util.applyInverseTransform(p, this.transform);
    return p;
  }
};
var RenderingCancelledException = class extends BaseException {
  constructor(msg, extraDelay = 0) {
    super(msg, "RenderingCancelledException");
    this.extraDelay = extraDelay;
  }
};
function isDataScheme(url) {
  const ii = url.length;
  let i = 0;
  while (i < ii && url[i].trim() === "") {
    i++;
  }
  return url.substring(i, i + 5).toLowerCase() === "data:";
}
function isPdfFile(filename) {
  return typeof filename === "string" && /\.pdf$/i.test(filename);
}
function getFilenameFromUrl(url) {
  [url] = url.split(/[#?]/, 1);
  return url.substring(url.lastIndexOf("/") + 1);
}
function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  if (typeof url !== "string") {
    return defaultFilename;
  }
  if (isDataScheme(url)) {
    warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
    return defaultFilename;
  }
  const getURL = (urlString) => {
    try {
      return new URL(urlString);
    } catch {
      try {
        return new URL(decodeURIComponent(urlString));
      } catch {
        try {
          return new URL(urlString, "https://foo.bar");
        } catch {
          try {
            return new URL(decodeURIComponent(urlString), "https://foo.bar");
          } catch {
            return null;
          }
        }
      }
    }
  };
  const newURL = getURL(url);
  if (!newURL) {
    return defaultFilename;
  }
  const decode = (name) => {
    try {
      let decoded = decodeURIComponent(name);
      if (decoded.includes("/")) {
        decoded = decoded.split("/").at(-1);
        if (decoded.test(/^\.pdf$/i)) {
          return decoded;
        }
        return name;
      }
      return decoded;
    } catch {
      return name;
    }
  };
  const pdfRegex = /\.pdf$/i;
  const filename = newURL.pathname.split("/").at(-1);
  if (pdfRegex.test(filename)) {
    return decode(filename);
  }
  if (newURL.searchParams.size > 0) {
    const values = Array.from(newURL.searchParams.values()).reverse();
    for (const value of values) {
      if (pdfRegex.test(value)) {
        return decode(value);
      }
    }
    const keys = Array.from(newURL.searchParams.keys()).reverse();
    for (const key of keys) {
      if (pdfRegex.test(key)) {
        return decode(key);
      }
    }
  }
  if (newURL.hash) {
    const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
    const hashFilename = reFilename.exec(newURL.hash);
    if (hashFilename) {
      return decode(hashFilename[0]);
    }
  }
  return defaultFilename;
}
var StatTimer = class {
  constructor() {
    __publicField(this, "started", /* @__PURE__ */ Object.create(null));
    __publicField(this, "times", []);
  }
  time(name) {
    if (name in this.started) {
      warn(`Timer is already running for ${name}`);
    }
    this.started[name] = Date.now();
  }
  timeEnd(name) {
    if (!(name in this.started)) {
      warn(`Timer has not been started for ${name}`);
    }
    this.times.push({
      name,
      start: this.started[name],
      end: Date.now()
    });
    delete this.started[name];
  }
  toString() {
    const outBuf = [];
    let longest = 0;
    for (const { name } of this.times) {
      longest = Math.max(name.length, longest);
    }
    for (const { name, start, end } of this.times) {
      outBuf.push(`${name.padEnd(longest)} ${end - start}ms
`);
    }
    return outBuf.join("");
  }
};
function isValidFetchUrl(url, baseUrl) {
  if (false) {
    throw new Error("Not implemented: isValidFetchUrl");
  }
  const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
  return res?.protocol === "http:" || res?.protocol === "https:";
}
function noContextMenu(e) {
  e.preventDefault();
}
function stopEvent(e) {
  e.preventDefault();
  e.stopPropagation();
}
function deprecated(details) {
  console.log("Deprecated API usage: " + details);
}
var _regex;
var PDFDateString = class {
  /**
   * Convert a PDF date string to a JavaScript `Date` object.
   *
   * The PDF date string format is described in section 7.9.4 of the official
   * PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth
   * edition) Adobe describes the same format including a trailing apostrophe.
   * This syntax in incorrect, but Adobe Acrobat creates PDF files that contain
   * them. We ignore all apostrophes as they are not necessary for date parsing.
   *
   * Moreover, Adobe Acrobat doesn't handle changing the date to universal time
   * and doesn't use the user's time zone (effectively ignoring the HH' and mm'
   * parts of the date string).
   *
   * @param {string} input
   * @returns {Date|null}
   */
  static toDateObject(input) {
    if (input instanceof Date) {
      return input;
    }
    if (!input || typeof input !== "string") {
      return null;
    }
    __privateGet(this, _regex) || __privateSet(this, _regex, new RegExp(
      "^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"
      // Trailing apostrophe (optional)
    ));
    const matches = __privateGet(this, _regex).exec(input);
    if (!matches) {
      return null;
    }
    const year = parseInt(matches[1], 10);
    let month = parseInt(matches[2], 10);
    month = month >= 1 && month <= 12 ? month - 1 : 0;
    let day = parseInt(matches[3], 10);
    day = day >= 1 && day <= 31 ? day : 1;
    let hour = parseInt(matches[4], 10);
    hour = hour >= 0 && hour <= 23 ? hour : 0;
    let minute = parseInt(matches[5], 10);
    minute = minute >= 0 && minute <= 59 ? minute : 0;
    let second = parseInt(matches[6], 10);
    second = second >= 0 && second <= 59 ? second : 0;
    const universalTimeRelation = matches[7] || "Z";
    let offsetHour = parseInt(matches[8], 10);
    offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
    let offsetMinute = parseInt(matches[9], 10) || 0;
    offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
    if (universalTimeRelation === "-") {
      hour += offsetHour;
      minute += offsetMinute;
    } else if (universalTimeRelation === "+") {
      hour -= offsetHour;
      minute -= offsetMinute;
    }
    return new Date(Date.UTC(year, month, day, hour, minute, second));
  }
};
_regex = new WeakMap();
__privateAdd(PDFDateString, _regex);
function getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) {
  const { width, height } = xfaPage.attributes.style;
  const viewBox = [0, 0, parseInt(width), parseInt(height)];
  return new PageViewport({
    viewBox,
    userUnit: 1,
    scale,
    rotation
  });
}
function getRGB(color) {
  if (color.startsWith("#")) {
    const colorRGB = parseInt(color.slice(1), 16);
    return [
      (colorRGB & 16711680) >> 16,
      (colorRGB & 65280) >> 8,
      colorRGB & 255
    ];
  }
  if (color.startsWith("rgb(")) {
    return color.slice(
      /* "rgb(".length */
      4,
      -1
    ).split(",").map((x) => parseInt(x));
  }
  if (color.startsWith("rgba(")) {
    return color.slice(
      /* "rgba(".length */
      5,
      -1
    ).split(",").map((x) => parseInt(x)).slice(0, 3);
  }
  warn(`Not a valid color format: "${color}"`);
  return [0, 0, 0];
}
function getColorValues(colors) {
  const span = document.createElement("span");
  span.style.visibility = "hidden";
  span.style.colorScheme = "only light";
  document.body.append(span);
  for (const name of colors.keys()) {
    span.style.color = name;
    const computedColor = window.getComputedStyle(span).color;
    colors.set(name, getRGB(computedColor));
  }
  span.remove();
}
function getCurrentTransform(ctx) {
  const { a, b, c, d, e, f } = ctx.getTransform();
  return [a, b, c, d, e, f];
}
function getCurrentTransformInverse(ctx) {
  const { a, b, c, d, e, f } = ctx.getTransform().invertSelf();
  return [a, b, c, d, e, f];
}
function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  if (viewport instanceof PageViewport) {
    const { pageWidth, pageHeight } = viewport.rawDims;
    const { style } = div;
    const useRound = FeatureTest.isCSSRoundSupported;
    const w = `var(--total-scale-factor) * ${pageWidth}px`, h = `var(--total-scale-factor) * ${pageHeight}px`;
    const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`, heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`;
    if (!mustFlip || viewport.rotation % 180 === 0) {
      style.width = widthStr;
      style.height = heightStr;
    } else {
      style.width = heightStr;
      style.height = widthStr;
    }
  }
  if (mustRotate) {
    div.setAttribute("data-main-rotation", viewport.rotation);
  }
}
var OutputScale = class _OutputScale {
  constructor() {
    const { pixelRatio } = _OutputScale;
    this.sx = pixelRatio;
    this.sy = pixelRatio;
  }
  /**
   * @type {boolean} Returns `true` when scaling is required, `false` otherwise.
   */
  get scaled() {
    return this.sx !== 1 || this.sy !== 1;
  }
  /**
   * @type {boolean} Returns `true` when scaling is symmetric,
   *   `false` otherwise.
   */
  get symmetric() {
    return this.sx === this.sy;
  }
  /**
   * @returns {boolean} Returns `true` if scaling was limited,
   *   `false` otherwise.
   */
  limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {
    let maxAreaScale = Infinity, maxWidthScale = Infinity, maxHeightScale = Infinity;
    maxPixels = _OutputScale.capPixels(maxPixels, capAreaFactor);
    if (maxPixels > 0) {
      maxAreaScale = Math.sqrt(maxPixels / (width * height));
    }
    if (maxDim !== -1) {
      maxWidthScale = maxDim / width;
      maxHeightScale = maxDim / height;
    }
    const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);
    if (this.sx > maxScale || this.sy > maxScale) {
      this.sx = maxScale;
      this.sy = maxScale;
      return true;
    }
    return false;
  }
  static get pixelRatio() {
    return globalThis.devicePixelRatio || 1;
  }
  static capPixels(maxPixels, capAreaFactor) {
    if (capAreaFactor >= 0) {
      const winPixels = Math.ceil(
        (false ? window.innerWidth * window.innerHeight : window.screen.availWidth * window.screen.availHeight) * this.pixelRatio ** 2 * (1 + capAreaFactor / 100)
      );
      return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;
    }
    return maxPixels;
  }
};
var SupportedImageMimeTypes = [
  "image/apng",
  "image/avif",
  "image/bmp",
  "image/gif",
  "image/jpeg",
  "image/png",
  "image/svg+xml",
  "image/webp",
  "image/x-icon"
];
var ColorScheme = class {
  static get isDarkMode() {
    return shadow(
      this,
      "isDarkMode",
      !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches
    );
  }
};
var CSSConstants = class {
  static get commentForegroundColor() {
    const element = document.createElement("span");
    element.classList.add("comment", "sidebar");
    const { style } = element;
    style.width = style.height = "0";
    style.display = "none";
    style.color = "var(--comment-fg-color)";
    document.body.append(element);
    const { color } = window.getComputedStyle(element);
    element.remove();
    return shadow(this, "commentForegroundColor", getRGB(color));
  }
};
function applyOpacity(r, g, b, opacity) {
  opacity = Math.min(Math.max(opacity ?? 1, 0), 1);
  const white = 255 * (1 - opacity);
  r = Math.round(r * opacity + white);
  g = Math.round(g * opacity + white);
  b = Math.round(b * opacity + white);
  return [r, g, b];
}
function RGBToHSL(rgb, output) {
  const r = rgb[0] / 255;
  const g = rgb[1] / 255;
  const b = rgb[2] / 255;
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const l = (max + min) / 2;
  if (max === min) {
    output[0] = output[1] = 0;
  } else {
    const d = max - min;
    output[1] = l < 0.5 ? d / (max + min) : d / (2 - max - min);
    switch (max) {
      case r:
        output[0] = ((g - b) / d + (g < b ? 6 : 0)) * 60;
        break;
      case g:
        output[0] = ((b - r) / d + 2) * 60;
        break;
      case b:
        output[0] = ((r - g) / d + 4) * 60;
        break;
    }
  }
  output[2] = l;
}
function HSLToRGB(hsl, output) {
  const h = hsl[0];
  const s = hsl[1];
  const l = hsl[2];
  const c = (1 - Math.abs(2 * l - 1)) * s;
  const x = c * (1 - Math.abs(h / 60 % 2 - 1));
  const m = l - c / 2;
  switch (Math.floor(h / 60)) {
    case 0:
      output[0] = c + m;
      output[1] = x + m;
      output[2] = m;
      break;
    case 1:
      output[0] = x + m;
      output[1] = c + m;
      output[2] = m;
      break;
    case 2:
      output[0] = m;
      output[1] = c + m;
      output[2] = x + m;
      break;
    case 3:
      output[0] = m;
      output[1] = x + m;
      output[2] = c + m;
      break;
    case 4:
      output[0] = x + m;
      output[1] = m;
      output[2] = c + m;
      break;
    case 5:
    case 6:
      output[0] = c + m;
      output[1] = m;
      output[2] = x + m;
      break;
  }
}
function computeLuminance(x) {
  return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
}
function contrastRatio(hsl1, hsl2, output) {
  HSLToRGB(hsl1, output);
  output.map(computeLuminance);
  const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
  HSLToRGB(hsl2, output);
  output.map(computeLuminance);
  const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
  return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
}
var contrastCache = /* @__PURE__ */ new Map();
function findContrastColor(baseColor, fixedColor) {
  const key = baseColor[0] + baseColor[1] * 256 + baseColor[2] * 65536 + fixedColor[0] * 16777216 + fixedColor[1] * 4294967296 + fixedColor[2] * 1099511627776;
  let cachedValue = contrastCache.get(key);
  if (cachedValue) {
    return cachedValue;
  }
  const array = new Float32Array(9);
  const output = array.subarray(0, 3);
  const baseHSL = array.subarray(3, 6);
  RGBToHSL(baseColor, baseHSL);
  const fixedHSL = array.subarray(6, 9);
  RGBToHSL(fixedColor, fixedHSL);
  const isFixedColorDark = fixedHSL[2] < 0.5;
  const minContrast = isFixedColorDark ? 12 : 4.5;
  baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]);
  if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
    let start, end;
    if (isFixedColorDark) {
      start = baseHSL[2];
      end = 1;
    } else {
      start = 0;
      end = baseHSL[2];
    }
    const PRECISION = 5e-3;
    while (end - start > PRECISION) {
      const mid = baseHSL[2] = (start + end) / 2;
      if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
        start = mid;
      } else {
        end = mid;
      }
    }
    baseHSL[2] = isFixedColorDark ? end : start;
  }
  HSLToRGB(baseHSL, output);
  cachedValue = Util.makeHexColor(
    Math.round(output[0] * 255),
    Math.round(output[1] * 255),
    Math.round(output[2] * 255)
  );
  contrastCache.set(key, cachedValue);
  return cachedValue;
}
function renderRichText({ html, dir, className }, container) {
  const fragment = document.createDocumentFragment();
  if (typeof html === "string") {
    const p = document.createElement("p");
    p.dir = dir || "auto";
    const lines = html.split(/(?:\r\n?|\n)/);
    for (let i = 0, ii = lines.length; i < ii; ++i) {
      const line = lines[i];
      p.append(document.createTextNode(line));
      if (i < ii - 1) {
        p.append(document.createElement("br"));
      }
    }
    fragment.append(p);
  } else {
    XfaLayer.render({
      xfaHtml: html,
      div: fragment,
      intent: "richText"
    });
  }
  fragment.firstChild.classList.add("richText", className);
  container.append(fragment);
}

// src/pdf.js/src/display/cmap_reader_factory.js
var BaseCMapReaderFactory = class {
  constructor({ baseUrl = null, isCompressed = true }) {
    if (false) {
      unreachable("Cannot initialize BaseCMapReaderFactory.");
    }
    this.baseUrl = baseUrl;
    this.isCompressed = isCompressed;
  }
  async fetch({ name }) {
    if (!this.baseUrl) {
      throw new Error(
        "Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."
      );
    }
    if (!name) {
      throw new Error("CMap name must be specified.");
    }
    const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
    return this._fetch(url).then((cMapData) => ({ cMapData, isCompressed: this.isCompressed })).catch((reason) => {
      throw new Error(
        `Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`
      );
    });
  }
  /**
   * @ignore
   * @returns {Promise<Uint8Array>}
   */
  async _fetch(url) {
    unreachable("Abstract method `_fetch` called.");
  }
};
var DOMCMapReaderFactory = class extends BaseCMapReaderFactory {
  /**
   * @ignore
   */
  async _fetch(url) {
    const data = await fetchData(
      url,
      /* type = */
      this.isCompressed ? "arraybuffer" : "text"
    );
    return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
  }
};

// src/pdf.js/src/display/standard_fontdata_factory.js
var BaseStandardFontDataFactory = class {
  constructor({ baseUrl = null }) {
    if (false) {
      unreachable("Cannot initialize BaseStandardFontDataFactory.");
    }
    this.baseUrl = baseUrl;
  }
  async fetch({ filename }) {
    if (!this.baseUrl) {
      throw new Error(
        "Ensure that the `standardFontDataUrl` API parameter is provided."
      );
    }
    if (!filename) {
      throw new Error("Font filename must be specified.");
    }
    const url = `${this.baseUrl}${filename}`;
    return this._fetch(url).catch((reason) => {
      throw new Error(`Unable to load font data at: ${url}`);
    });
  }
  /**
   * @ignore
   * @returns {Promise<Uint8Array>}
   */
  async _fetch(url) {
    unreachable("Abstract method `_fetch` called.");
  }
};
var DOMStandardFontDataFactory = class extends BaseStandardFontDataFactory {
  /**
   * @ignore
   */
  async _fetch(url) {
    const data = await fetchData(
      url,
      /* type = */
      "arraybuffer"
    );
    return new Uint8Array(data);
  }
};

// src/pdf.js/src/display/wasm_factory.js
var BaseWasmFactory = class {
  constructor({ baseUrl = null }) {
    if (false) {
      unreachable("Cannot initialize BaseWasmFactory.");
    }
    this.baseUrl = baseUrl;
  }
  async fetch({ filename }) {
    if (!this.baseUrl) {
      throw new Error("Ensure that the `wasmUrl` API parameter is provided.");
    }
    if (!filename) {
      throw new Error("Wasm filename must be specified.");
    }
    const url = `${this.baseUrl}${filename}`;
    return this._fetch(url).catch((reason) => {
      throw new Error(`Unable to load wasm data at: ${url}`);
    });
  }
  /**
   * @ignore
   * @returns {Promise<Uint8Array>}
   */
  async _fetch(url) {
    unreachable("Abstract method `_fetch` called.");
  }
};
var DOMWasmFactory = class extends BaseWasmFactory {
  /**
   * @ignore
   */
  async _fetch(url) {
    const data = await fetchData(
      url,
      /* type = */
      "arraybuffer"
    );
    return new Uint8Array(data);
  }
};

// src/lib/NodeCanvasFactory.ts
import { Canvas } from "skia-canvas";

// src/pdf.js/src/display/canvas_factory.js
var _enableHWA;
var BaseCanvasFactory = class {
  constructor({ enableHWA = false }) {
    __privateAdd(this, _enableHWA, false);
    if (false) {
      unreachable("Cannot initialize BaseCanvasFactory.");
    }
    __privateSet(this, _enableHWA, enableHWA);
  }
  create(width, height) {
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    const canvas = this._createCanvas(width, height);
    return {
      canvas,
      context: canvas.getContext("2d", {
        willReadFrequently: !__privateGet(this, _enableHWA)
      })
    };
  }
  reset(canvasAndContext, width, height) {
    if (!canvasAndContext.canvas) {
      throw new Error("Canvas is not specified");
    }
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    canvasAndContext.canvas.width = width;
    canvasAndContext.canvas.height = height;
  }
  destroy(canvasAndContext) {
    if (!canvasAndContext.canvas) {
      throw new Error("Canvas is not specified");
    }
    canvasAndContext.canvas.width = 0;
    canvasAndContext.canvas.height = 0;
    canvasAndContext.canvas = null;
    canvasAndContext.context = null;
  }
  /**
   * @ignore
   */
  _createCanvas(width, height) {
    unreachable("Abstract method `_createCanvas` called.");
  }
};
_enableHWA = new WeakMap();
var DOMCanvasFactory = class extends BaseCanvasFactory {
  constructor({ ownerDocument = globalThis.document, enableHWA = false }) {
    super({ enableHWA });
    this._document = ownerDocument;
  }
  /**
   * @ignore
   */
  _createCanvas(width, height) {
    const canvas = this._document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }
};

// src/pdf.js/src/display/filter_factory.js
var BaseFilterFactory = class {
  constructor() {
    if (false) {
      unreachable("Cannot initialize BaseFilterFactory.");
    }
  }
  addFilter(maps) {
    return "none";
  }
  addHCMFilter(fgColor, bgColor) {
    return "none";
  }
  addAlphaFilter(map) {
    return "none";
  }
  addLuminosityFilter(map) {
    return "none";
  }
  addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
    return "none";
  }
  destroy(keepHCM = false) {
  }
};
var _baseUrl, __cache, __defs, _docId, _document, __hcmCache, _id, _DOMFilterFactory_instances, cache_get, hcmCache_get, defs_get, createTables_fn, createUrl_fn, addLuminosityConversion_fn, addGrayConversion_fn, createFilter_fn, appendFeFunc_fn, addTransferMapConversion_fn, addTransferMapAlphaConversion_fn, getRGB_fn;
var DOMFilterFactory = class extends BaseFilterFactory {
  constructor({ docId, ownerDocument = globalThis.document }) {
    super();
    __privateAdd(this, _DOMFilterFactory_instances);
    __privateAdd(this, _baseUrl);
    __privateAdd(this, __cache);
    __privateAdd(this, __defs);
    __privateAdd(this, _docId);
    __privateAdd(this, _document);
    __privateAdd(this, __hcmCache);
    __privateAdd(this, _id, 0);
    __privateSet(this, _docId, docId);
    __privateSet(this, _document, ownerDocument);
  }
  addFilter(maps) {
    if (!maps) {
      return "none";
    }
    let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(maps);
    if (value) {
      return value;
    }
    const [tableR, tableG, tableB] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, maps);
    const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
    value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
    if (value) {
      __privateGet(this, _DOMFilterFactory_instances, cache_get).set(maps, value);
      return value;
    }
    const id = `g_${__privateGet(this, _docId)}_transfer_map_${__privateWrapper(this, _id)._++}`;
    const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
    __privateGet(this, _DOMFilterFactory_instances, cache_get).set(maps, url);
    __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
    const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
    __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, tableR, tableG, tableB, filter);
    return url;
  }
  addHCMFilter(fgColor, bgColor) {
    const key = `${fgColor}-${bgColor}`;
    const filterName = "base";
    let info = __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).get(filterName);
    if (info?.key === key) {
      return info.url;
    }
    if (info) {
      info.filter?.remove();
      info.key = key;
      info.url = "none";
      info.filter = null;
    } else {
      info = {
        key,
        url: "none",
        filter: null
      };
      __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).set(filterName, info);
    }
    if (!fgColor || !bgColor) {
      return info.url;
    }
    const fgRGB = __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).call(this, fgColor);
    fgColor = Util.makeHexColor(...fgRGB);
    const bgRGB = __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).call(this, bgColor);
    bgColor = Util.makeHexColor(...bgRGB);
    __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = "";
    if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
      return info.url;
    }
    const map = new Array(256);
    for (let i = 0; i <= 255; i++) {
      const x = i / 255;
      map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
    }
    const table = map.join(",");
    const id = `g_${__privateGet(this, _docId)}_hcm_filter`;
    const filter = info.filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
    __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, table, table, table, filter);
    __privateMethod(this, _DOMFilterFactory_instances, addGrayConversion_fn).call(this, filter);
    const getSteps = (c, n) => {
      const start = fgRGB[c] / 255;
      const end = bgRGB[c] / 255;
      const arr = new Array(n + 1);
      for (let i = 0; i <= n; i++) {
        arr[i] = start + i / n * (end - start);
      }
      return arr.join(",");
    };
    __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
    info.url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
    return info.url;
  }
  addAlphaFilter(map) {
    let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(map);
    if (value) {
      return value;
    }
    const [tableA] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, [map]);
    const key = `alpha_${tableA}`;
    value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
    if (value) {
      __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, value);
      return value;
    }
    const id = `g_${__privateGet(this, _docId)}_alpha_map_${__privateWrapper(this, _id)._++}`;
    const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
    __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, url);
    __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
    const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
    __privateMethod(this, _DOMFilterFactory_instances, addTransferMapAlphaConversion_fn).call(this, tableA, filter);
    return url;
  }
  addLuminosityFilter(map) {
    let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(map || "luminosity");
    if (value) {
      return value;
    }
    let tableA, key;
    if (map) {
      [tableA] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, [map]);
      key = `luminosity_${tableA}`;
    } else {
      key = "luminosity";
    }
    value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
    if (value) {
      __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, value);
      return value;
    }
    const id = `g_${__privateGet(this, _docId)}_luminosity_map_${__privateWrapper(this, _id)._++}`;
    const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
    __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, url);
    __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
    const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
    __privateMethod(this, _DOMFilterFactory_instances, addLuminosityConversion_fn).call(this, filter);
    if (map) {
      __privateMethod(this, _DOMFilterFactory_instances, addTransferMapAlphaConversion_fn).call(this, tableA, filter);
    }
    return url;
  }
  addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
    const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
    let info = __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).get(filterName);
    if (info?.key === key) {
      return info.url;
    }
    if (info) {
      info.filter?.remove();
      info.key = key;
      info.url = "none";
      info.filter = null;
    } else {
      info = {
        key,
        url: "none",
        filter: null
      };
      __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).set(filterName, info);
    }
    if (!fgColor || !bgColor) {
      return info.url;
    }
    const [fgRGB, bgRGB] = [fgColor, bgColor].map(__privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).bind(this));
    let fgGray = Math.round(
      0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]
    );
    let bgGray = Math.round(
      0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]
    );
    let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(
      __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).bind(this)
    );
    if (bgGray < fgGray) {
      [fgGray, bgGray, newFgRGB, newBgRGB] = [
        bgGray,
        fgGray,
        newBgRGB,
        newFgRGB
      ];
    }
    __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = "";
    const getSteps = (fg, bg, n) => {
      const arr = new Array(256);
      const step = (bgGray - fgGray) / n;
      const newStart = fg / 255;
      const newStep = (bg - fg) / (255 * n);
      let prev = 0;
      for (let i = 0; i <= n; i++) {
        const k = Math.round(fgGray + i * step);
        const value = newStart + i * newStep;
        for (let j = prev; j <= k; j++) {
          arr[j] = value;
        }
        prev = k + 1;
      }
      for (let i = prev; i < 256; i++) {
        arr[i] = arr[prev - 1];
      }
      return arr.join(",");
    };
    const id = `g_${__privateGet(this, _docId)}_hcm_${filterName}_filter`;
    const filter = info.filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
    __privateMethod(this, _DOMFilterFactory_instances, addGrayConversion_fn).call(this, filter);
    __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
    info.url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
    return info.url;
  }
  destroy(keepHCM = false) {
    if (keepHCM && __privateGet(this, __hcmCache)?.size) {
      return;
    }
    __privateGet(this, __defs)?.parentNode.parentNode.remove();
    __privateSet(this, __defs, null);
    __privateGet(this, __cache)?.clear();
    __privateSet(this, __cache, null);
    __privateGet(this, __hcmCache)?.clear();
    __privateSet(this, __hcmCache, null);
    __privateSet(this, _id, 0);
  }
};
_baseUrl = new WeakMap();
__cache = new WeakMap();
__defs = new WeakMap();
_docId = new WeakMap();
_document = new WeakMap();
__hcmCache = new WeakMap();
_id = new WeakMap();
_DOMFilterFactory_instances = new WeakSet();
cache_get = function() {
  return __privateGet(this, __cache) || __privateSet(this, __cache, /* @__PURE__ */ new Map());
};
hcmCache_get = function() {
  return __privateGet(this, __hcmCache) || __privateSet(this, __hcmCache, /* @__PURE__ */ new Map());
};
defs_get = function() {
  if (!__privateGet(this, __defs)) {
    const div = __privateGet(this, _document).createElement("div");
    const { style } = div;
    style.visibility = "hidden";
    style.contain = "strict";
    style.width = style.height = 0;
    style.position = "absolute";
    style.top = style.left = 0;
    style.zIndex = -1;
    const svg = __privateGet(this, _document).createElementNS(SVG_NS, "svg");
    svg.setAttribute("width", 0);
    svg.setAttribute("height", 0);
    __privateSet(this, __defs, __privateGet(this, _document).createElementNS(SVG_NS, "defs"));
    div.append(svg);
    svg.append(__privateGet(this, __defs));
    __privateGet(this, _document).body.append(div);
  }
  return __privateGet(this, __defs);
};
createTables_fn = function(maps) {
  if (maps.length === 1) {
    const mapR2 = maps[0];
    const buffer = new Array(256);
    for (let i = 0; i < 256; i++) {
      buffer[i] = mapR2[i] / 255;
    }
    const table = buffer.join(",");
    return [table, table, table];
  }
  const [mapR, mapG, mapB] = maps;
  const bufferR = new Array(256);
  const bufferG = new Array(256);
  const bufferB = new Array(256);
  for (let i = 0; i < 256; i++) {
    bufferR[i] = mapR[i] / 255;
    bufferG[i] = mapG[i] / 255;
    bufferB[i] = mapB[i] / 255;
  }
  return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
};
createUrl_fn = function(id) {
  if (__privateGet(this, _baseUrl) === void 0) {
    __privateSet(this, _baseUrl, "");
    const url = __privateGet(this, _document).URL;
    if (url !== __privateGet(this, _document).baseURI) {
      if (isDataScheme(url)) {
        warn('#createUrl: ignore "data:"-URL for performance reasons.');
      } else {
        __privateSet(this, _baseUrl, updateUrlHash(url, ""));
      }
    }
  }
  return `url(${__privateGet(this, _baseUrl)}#${id})`;
};
addLuminosityConversion_fn = function(filter) {
  const feColorMatrix = __privateGet(this, _document).createElementNS(
    SVG_NS,
    "feColorMatrix"
  );
  feColorMatrix.setAttribute("type", "matrix");
  feColorMatrix.setAttribute(
    "values",
    "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"
  );
  filter.append(feColorMatrix);
};
addGrayConversion_fn = function(filter) {
  const feColorMatrix = __privateGet(this, _document).createElementNS(
    SVG_NS,
    "feColorMatrix"
  );
  feColorMatrix.setAttribute("type", "matrix");
  feColorMatrix.setAttribute(
    "values",
    "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"
  );
  filter.append(feColorMatrix);
};
createFilter_fn = function(id) {
  const filter = __privateGet(this, _document).createElementNS(SVG_NS, "filter");
  filter.setAttribute("color-interpolation-filters", "sRGB");
  filter.setAttribute("id", id);
  __privateGet(this, _DOMFilterFactory_instances, defs_get).append(filter);
  return filter;
};
appendFeFunc_fn = function(feComponentTransfer, func, table) {
  const feFunc = __privateGet(this, _document).createElementNS(SVG_NS, func);
  feFunc.setAttribute("type", "discrete");
  feFunc.setAttribute("tableValues", table);
  feComponentTransfer.append(feFunc);
};
addTransferMapConversion_fn = function(rTable, gTable, bTable, filter) {
  const feComponentTransfer = __privateGet(this, _document).createElementNS(
    SVG_NS,
    "feComponentTransfer"
  );
  filter.append(feComponentTransfer);
  __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncR", rTable);
  __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncG", gTable);
  __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncB", bTable);
};
addTransferMapAlphaConversion_fn = function(aTable, filter) {
  const feComponentTransfer = __privateGet(this, _document).createElementNS(
    SVG_NS,
    "feComponentTransfer"
  );
  filter.append(feComponentTransfer);
  __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncA", aTable);
};
getRGB_fn = function(color) {
  __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = color;
  return getRGB(getComputedStyle(__privateGet(this, _DOMFilterFactory_instances, defs_get)).getPropertyValue("color"));
};

// src/lib/utils.ts
async function canvasToData(canvas) {
  if ("toBlob" in canvas) {
    const blob = await new Promise(
      (resolve) => canvas.toBlob((data) => resolve(data))
    );
    if (!blob) {
      throw new Error("Failed to generate graphics");
    }
    return new Uint8Array(await blob.arrayBuffer());
  }
  const buffer = await canvas.toBuffer("png");
  return new Uint8Array(buffer);
}
async function toDataUrl(data, type = "image/png") {
  if (typeof FileReader !== "undefined") {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = () => {
        resolve(reader.result);
      };
      reader.readAsDataURL(new Blob([data], { type }));
    });
  }
  return `data:${type};base64,${Buffer.from(data).toString("base64")}`;
}
function colorToRgb(color) {
  if (color.startsWith("#")) {
    const hex = color.slice(1);
    if (hex.length === 3) {
      return [
        Number.parseInt(hex[0] + hex[0], 16),
        Number.parseInt(hex[1] + hex[1], 16),
        Number.parseInt(hex[2] + hex[2], 16)
      ];
    }
    if (hex.length === 6) {
      return [
        Number.parseInt(hex.slice(0, 2), 16),
        Number.parseInt(hex.slice(2, 4), 16),
        Number.parseInt(hex.slice(4, 6), 16)
      ];
    }
  }
  throw new Error(`Invalid color format: ${color}`);
}
function rgbToHex(r, g, b) {
  const toHex = (value) => value.toString(16).padStart(2, "0");
  if (Array.isArray(r)) {
    return `#${toHex(r[0])}${toHex(r[1])}${toHex(r[2])}`;
  }
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function parseRgbaColor(color) {
  const match = color.match(
    /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/
  );
  if (!match) {
    return { r: 0, g: 0, b: 0, a: 1 };
  }
  return {
    r: Number.parseInt(match[1], 10),
    g: Number.parseInt(match[2], 10),
    b: Number.parseInt(match[3], 10),
    a: match[4] ? Number.parseFloat(match[4]) : 1
  };
}
function randomUUID() {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
    return crypto.randomUUID();
  }
  const hex = [...Array(36)].map(
    () => Math.floor(Math.random() * 16).toString(16)
  );
  hex[14] = "4";
  hex[19] = (Number.parseInt(hex[19], 16) & 3 | 8).toString(16);
  hex[8] = hex[13] = hex[18] = hex[23] = "-";
  return hex.join("");
}
var OPS_DICT = Object.fromEntries(
  Object.entries(OPS).map(([key, value]) => [value, key])
);

// src/lib/NodeFilterFactory.ts
var filtersRegistry = /* @__PURE__ */ new Map();
function createTables(maps) {
  if (maps.length === 1) {
    const mapR2 = maps[0];
    const buffer = new Array(256);
    for (let i = 0; i < 256; i++) {
      buffer[i] = mapR2[i] / 255;
    }
    return [buffer, buffer, buffer];
  }
  const [mapR, mapG, mapB] = maps;
  const bufferR = new Array(256);
  const bufferG = new Array(256);
  const bufferB = new Array(256);
  for (let i = 0; i < 256; i++) {
    bufferR[i] = mapR[i] / 255;
    bufferG[i] = mapG[i] / 255;
    bufferB[i] = mapB[i] / 255;
  }
  return [bufferR, bufferG, bufferB];
}
function createTransferMapAlphaConversion(aTable) {
  return (ctx) => {
    const imageData = ctx.getImageData(
      0,
      0,
      ctx.canvas.width,
      ctx.canvas.height
    );
    const data = imageData.data;
    const tableSize = aTable.length;
    for (let i = 0; i < data.length; i += 4) {
      const alpha = data[i + 3] / 255;
      const index = alpha * (tableSize - 1);
      const lower = Math.floor(index);
      const upper = Math.min(lower + 1, tableSize - 1);
      const t = index - lower;
      const newAlpha = (1 - t) * aTable[lower] + t * aTable[upper];
      data[i + 3] = newAlpha * 255;
    }
    ctx.putImageData(imageData, 0, 0);
  };
}
function createTransferMapConversion(rTable, gTable, bTable) {
  return (ctx) => {
    const imageData = ctx.getImageData(
      0,
      0,
      ctx.canvas.width,
      ctx.canvas.height
    );
    const data = imageData.data;
    const rSize = rTable.length;
    const gSize = gTable.length;
    const bSize = bTable.length;
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i] / 255;
      const g = data[i + 1] / 255;
      const b = data[i + 2] / 255;
      const rIndex = r * (rSize - 1);
      const rLower = Math.floor(rIndex);
      const rUpper = Math.min(rLower + 1, rSize - 1);
      const rT = rIndex - rLower;
      const newR = (1 - rT) * rTable[rLower] + rT * rTable[rUpper];
      const gIndex = g * (gSize - 1);
      const gLower = Math.floor(gIndex);
      const gUpper = Math.min(gLower + 1, gSize - 1);
      const gT = gIndex - gLower;
      const newG = (1 - gT) * gTable[gLower] + gT * gTable[gUpper];
      const bIndex = b * (bSize - 1);
      const bLower = Math.floor(bIndex);
      const bUpper = Math.min(bLower + 1, bSize - 1);
      const bT = bIndex - bLower;
      const newB = (1 - bT) * bTable[bLower] + bT * bTable[bUpper];
      data[i] = newR * 255;
      data[i + 1] = newG * 255;
      data[i + 2] = newB * 255;
    }
    ctx.putImageData(imageData, 0, 0);
  };
}
function createLuminosityConversion() {
  return (ctx) => {
    const imageData = ctx.getImageData(
      0,
      0,
      ctx.canvas.width,
      ctx.canvas.height
    );
    const data = imageData.data;
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      data[i] = data[i + 1] = data[i + 2] = 0;
      data[i + 3] = r * 0.3 + g * 0.59 + b * 0.11;
    }
    ctx.putImageData(imageData, 0, 0);
  };
}
function createGrayConversion() {
  return (ctx) => {
    const imageData = ctx.getImageData(
      0,
      0,
      ctx.canvas.width,
      ctx.canvas.height
    );
    const data = imageData.data;
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      const gray = r * 0.2126 + g * 0.7152 + b * 0.0722;
      data[i] = data[i + 1] = data[i + 2] = gray;
    }
    ctx.putImageData(imageData, 0, 0);
  };
}
var NodeFilterFactory = class extends BaseFilterFactory {
  addFilter(maps) {
    if (!maps) {
      return "none";
    }
    const [rTable, gTable, bTable] = createTables(maps);
    const url = `url(#filter_${maps.length === 1 ? rTable.join("_") : `${rTable.join("_")}_${gTable.join("_")}_${bTable.join("_")}`})`;
    if (!filtersRegistry.has(url)) {
      filtersRegistry.set(
        url,
        createTransferMapConversion(rTable, gTable, bTable)
      );
    }
    return url;
  }
  addHCMFilter(fgColor, bgColor) {
    const fgRGB = colorToRgb(fgColor);
    const bgRGB = colorToRgb(bgColor);
    const url = `url(#hcm_${rgbToHex(fgRGB)}_${rgbToHex(bgRGB)})`;
    if (!filtersRegistry.has(url)) {
      const table = new Array(256);
      for (let i = 0; i <= 255; i++) {
        const x = i / 255;
        table[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
      }
      const transferMapFilter = createTransferMapConversion(
        table,
        table,
        table
      );
      const grayFilter = createGrayConversion();
      const getSteps = (c, n) => {
        const start = fgRGB[c] / 255;
        const end = bgRGB[c] / 255;
        const arr = new Array(n + 1);
        for (let i = 0; i <= n; i++) {
          arr[i] = start + i / n * (end - start);
        }
        return arr;
      };
      const finalTransferMap = createTransferMapConversion(
        getSteps(0, 5),
        getSteps(1, 5),
        getSteps(2, 5)
      );
      filtersRegistry.set(url, (ctx) => {
        transferMapFilter(ctx);
        grayFilter(ctx);
        finalTransferMap(ctx);
      });
    }
    return url;
  }
  addAlphaFilter(map) {
    const [tableA] = createTables([map]);
    const url = `url(#alpha_${tableA.join("_")})`;
    if (!filtersRegistry.has(url)) {
      filtersRegistry.set(url, createTransferMapAlphaConversion(map));
    }
    return url;
  }
  addLuminosityFilter(map) {
    const url = `url(#luminosity${map ? `_${map.join("_")}` : ""})`;
    if (!filtersRegistry.has(url)) {
      const tables = map ? createTables([map]) : null;
      const alphaFilter = tables ? createTransferMapAlphaConversion(tables[0]) : null;
      const luminosityFilter = createLuminosityConversion();
      filtersRegistry.set(url, (ctx) => {
        luminosityFilter(ctx);
        alphaFilter?.(ctx);
      });
    }
    return url;
  }
  addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
    const fgRGB = colorToRgb(fgColor);
    const bgRGB = colorToRgb(bgColor);
    let newFgRGB = colorToRgb(newFgColor);
    let newBgRGB = colorToRgb(newBgColor);
    const url = `url(#highlight_hcm_${filterName}_${rgbToHex(fgRGB)}_${rgbToHex(bgRGB)}_${rgbToHex(newFgRGB)}_${rgbToHex(newBgRGB)})`;
    if (!filtersRegistry.has(url)) {
      let fgGray = Math.round(
        0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]
      );
      let bgGray = Math.round(
        0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]
      );
      if (bgGray < fgGray) {
        [fgGray, bgGray, newFgRGB, newBgRGB] = [
          bgGray,
          fgGray,
          newBgRGB,
          newFgRGB
        ];
      }
      const grayFilter = createGrayConversion();
      const getSteps = (fg, bg, n) => {
        const arr = new Array(256);
        const step = (bgGray - fgGray) / n;
        const newStart = fg / 255;
        const newStep = (bg - fg) / (255 * n);
        let prev = 0;
        for (let i = 0; i <= n; i++) {
          const k = Math.round(fgGray + i * step);
          const value = newStart + i * newStep;
          for (let j = prev; j <= k; j++) {
            arr[j] = value;
          }
          prev = k + 1;
        }
        for (let i = prev; i < 256; i++) {
          arr[i] = arr[prev - 1];
        }
        return arr;
      };
      const transferMapFilter = createTransferMapConversion(
        getSteps(newFgRGB[0], newBgRGB[0], 5),
        getSteps(newFgRGB[1], newBgRGB[1], 5),
        getSteps(newFgRGB[2], newBgRGB[2], 5)
      );
      filtersRegistry.set(url, (ctx) => {
        grayFilter(ctx);
        transferMapFilter(ctx);
      });
    }
    return url;
  }
};

// src/lib/NodeCanvasFactory.ts
var NodeCanvasFactory = class extends BaseCanvasFactory {
  _createCanvas(width, height) {
    return new Canvas(width, height);
  }
  create(width, height) {
    const factory = this;
    const { canvas, context } = super.create(width, height);
    const drawImage = context.drawImage;
    let currentFilter = "none";
    Object.defineProperty(context, "filter", {
      get() {
        if (currentFilter.startsWith("url(")) {
          return "none";
        }
        return currentFilter;
      },
      set(value) {
        currentFilter = value;
      },
      configurable: true
    });
    context.drawImage = function(src, ...args) {
      const filter = filtersRegistry.get(currentFilter);
      if (!filter) {
        drawImage.call(this, src, ...args);
        return;
      }
      const { canvas: canvas2, context: context2 } = factory.create(src.width, src.height);
      context2.drawImage(src, 0, 0, src.width, src.height);
      filter(context2);
      drawImage.call(this, canvas2, ...args);
      factory.destroy({
        canvas: canvas2,
        context: context2
      });
    };
    return {
      canvas,
      context
    };
  }
};

// src/lib/NodeUtils.ts
if (!globalThis.DOMMatrix) {
  globalThis.DOMMatrix = NodeDOMMatrix;
}
if (!globalThis.DOMPoint) {
  globalThis.DOMPoint = NodeDOMPoint;
}
if (!globalThis.ImageData) {
  globalThis.ImageData = NodeImageData;
}
if (!globalThis.Path2D) {
  globalThis.Path2D = NodePath2D;
}
if (!globalThis.navigator?.language) {
  globalThis.navigator = {
    language: "en-US",
    platform: "",
    userAgent: ""
  };
}
async function fetchData2(url) {
  const { readFile } = await import("node:fs/promises");
  const data = await readFile(url);
  return new Uint8Array(data);
}
var NodeCMapReaderFactory = class extends BaseCMapReaderFactory {
  /**
   * @ignore
   */
  async _fetch(url) {
    return fetchData2(url);
  }
};
var NodeStandardFontDataFactory = class extends BaseStandardFontDataFactory {
  /**
   * @ignore
   */
  async _fetch(url) {
    return fetchData2(url);
  }
};
var NodeWasmFactory = class extends BaseWasmFactory {
  /**
   * @ignore
   */
  async _fetch(url) {
    return fetchData2(url);
  }
};

export {
  XfaText,
  XfaLayer,
  SVG_NS,
  PixelsPerInch,
  fetchData,
  PageViewport,
  RenderingCancelledException,
  isDataScheme,
  isPdfFile,
  getFilenameFromUrl,
  getPdfFilenameFromUrl,
  StatTimer,
  isValidFetchUrl,
  noContextMenu,
  stopEvent,
  deprecated,
  PDFDateString,
  getXfaPageViewport,
  getRGB,
  getColorValues,
  getCurrentTransform,
  getCurrentTransformInverse,
  setLayerDimensions,
  OutputScale,
  SupportedImageMimeTypes,
  ColorScheme,
  CSSConstants,
  applyOpacity,
  findContrastColor,
  renderRichText,
  DOMCMapReaderFactory,
  BaseStandardFontDataFactory,
  DOMStandardFontDataFactory,
  DOMWasmFactory,
  DOMCanvasFactory,
  DOMFilterFactory,
  canvasToData,
  toDataUrl,
  colorToRgb,
  rgbToHex,
  parseRgbaColor,
  randomUUID,
  OPS_DICT,
  filtersRegistry,
  NodeFilterFactory,
  NodeCanvasFactory,
  fetchData2,
  NodeCMapReaderFactory,
  NodeStandardFontDataFactory,
  NodeWasmFactory
};
