var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function() {
  try {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  } catch (e) {
    throw mod = 0, e;
  }
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from == "object" || typeof from == "function")
    for (let key of __getOwnPropNames(from))
      !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
  mod
));

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js
var require_util = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports) {
    "use strict";
    var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040", nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*", regexName = new RegExp("^" + nameRegexp + "$"), getAllMatches = function(string, regex) {
      let matches = [], match = regex.exec(string);
      for (; match; ) {
        let allmatches = [];
        allmatches.startIndex = regex.lastIndex - match[0].length;
        let len = match.length;
        for (let index = 0; index < len; index++)
          allmatches.push(match[index]);
        matches.push(allmatches), match = regex.exec(string);
      }
      return matches;
    }, isName = function(string) {
      let match = regexName.exec(string);
      return !(match === null || typeof match > "u");
    };
    exports.isExist = function(v) {
      return typeof v < "u";
    };
    exports.isEmptyObject = function(obj) {
      return Object.keys(obj).length === 0;
    };
    exports.merge = function(target, a, arrayMode) {
      if (a) {
        let keys = Object.keys(a), len = keys.length;
        for (let i = 0; i < len; i++)
          arrayMode === "strict" ? target[keys[i]] = [a[keys[i]]] : target[keys[i]] = a[keys[i]];
      }
    };
    exports.getValue = function(v) {
      return exports.isExist(v) ? v : "";
    };
    exports.isName = isName;
    exports.getAllMatches = getAllMatches;
    exports.nameRegexp = nameRegexp;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js
var require_validator = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports) {
    "use strict";
    var util = require_util(), defaultOptions = {
      allowBooleanAttributes: !1,
      //A tag can have attributes without any value
      unpairedTags: []
    };
    exports.validate = function(xmlData, options) {
      options = Object.assign({}, defaultOptions, options);
      let tags = [], tagFound = !1, reachedRoot = !1;
      xmlData[0] === "\uFEFF" && (xmlData = xmlData.substr(1));
      for (let i = 0; i < xmlData.length; i++)
        if (xmlData[i] === "<" && xmlData[i + 1] === "?") {
          if (i += 2, i = readPI(xmlData, i), i.err) return i;
        } else if (xmlData[i] === "<") {
          let tagStartPos = i;
          if (i++, xmlData[i] === "!") {
            i = readCommentAndCDATA(xmlData, i);
            continue;
          } else {
            let closingTag = !1;
            xmlData[i] === "/" && (closingTag = !0, i++);
            let tagName = "";
            for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== "	" && xmlData[i] !== `
` && xmlData[i] !== "\r"; i++)
              tagName += xmlData[i];
            if (tagName = tagName.trim(), tagName[tagName.length - 1] === "/" && (tagName = tagName.substring(0, tagName.length - 1), i--), !validateTagName(tagName)) {
              let msg;
              return tagName.trim().length === 0 ? msg = "Invalid space after '<'." : msg = "Tag '" + tagName + "' is an invalid name.", getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i));
            }
            let result = readAttributeStr(xmlData, i);
            if (result === !1)
              return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
            let attrStr = result.value;
            if (i = result.index, attrStr[attrStr.length - 1] === "/") {
              let attrStrStart = i - attrStr.length;
              attrStr = attrStr.substring(0, attrStr.length - 1);
              let isValid = validateAttributeString(attrStr, options);
              if (isValid === !0)
                tagFound = !0;
              else
                return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
            } else if (closingTag)
              if (result.tagClosed) {
                if (attrStr.trim().length > 0)
                  return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
                if (tags.length === 0)
                  return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
                {
                  let otg = tags.pop();
                  if (tagName !== otg.tagName) {
                    let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
                    return getErrorObject(
                      "InvalidTag",
                      "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
                      getLineNumberForPosition(xmlData, tagStartPos)
                    );
                  }
                  tags.length == 0 && (reachedRoot = !0);
                }
              } else return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
            else {
              let isValid = validateAttributeString(attrStr, options);
              if (isValid !== !0)
                return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
              if (reachedRoot === !0)
                return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i));
              options.unpairedTags.indexOf(tagName) !== -1 || tags.push({ tagName, tagStartPos }), tagFound = !0;
            }
            for (i++; i < xmlData.length; i++)
              if (xmlData[i] === "<")
                if (xmlData[i + 1] === "!") {
                  i++, i = readCommentAndCDATA(xmlData, i);
                  continue;
                } else if (xmlData[i + 1] === "?") {
                  if (i = readPI(xmlData, ++i), i.err) return i;
                } else
                  break;
              else if (xmlData[i] === "&") {
                let afterAmp = validateAmpersand(xmlData, i);
                if (afterAmp == -1)
                  return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
                i = afterAmp;
              } else if (reachedRoot === !0 && !isWhiteSpace(xmlData[i]))
                return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i));
            xmlData[i] === "<" && i--;
          }
        } else {
          if (isWhiteSpace(xmlData[i]))
            continue;
          return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
        }
      if (tagFound) {
        if (tags.length == 1)
          return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
        if (tags.length > 0)
          return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
      } else return getErrorObject("InvalidXml", "Start tag expected.", 1);
      return !0;
    };
    function isWhiteSpace(char) {
      return char === " " || char === "	" || char === `
` || char === "\r";
    }
    function readPI(xmlData, i) {
      let start = i;
      for (; i < xmlData.length; i++)
        if (xmlData[i] == "?" || xmlData[i] == " ") {
          let tagname = xmlData.substr(start, i - start);
          if (i > 5 && tagname === "xml")
            return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i));
          if (xmlData[i] == "?" && xmlData[i + 1] == ">") {
            i++;
            break;
          } else
            continue;
        }
      return i;
    }
    function readCommentAndCDATA(xmlData, i) {
      if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") {
        for (i += 3; i < xmlData.length; i++)
          if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") {
            i += 2;
            break;
          }
      } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") {
        let angleBracketsCount = 1;
        for (i += 8; i < xmlData.length; i++)
          if (xmlData[i] === "<")
            angleBracketsCount++;
          else if (xmlData[i] === ">" && (angleBracketsCount--, angleBracketsCount === 0))
            break;
      } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") {
        for (i += 8; i < xmlData.length; i++)
          if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") {
            i += 2;
            break;
          }
      }
      return i;
    }
    var doubleQuote = '"', singleQuote = "'";
    function readAttributeStr(xmlData, i) {
      let attrStr = "", startChar = "", tagClosed = !1;
      for (; i < xmlData.length; i++) {
        if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote)
          startChar === "" ? startChar = xmlData[i] : startChar !== xmlData[i] || (startChar = "");
        else if (xmlData[i] === ">" && startChar === "") {
          tagClosed = !0;
          break;
        }
        attrStr += xmlData[i];
      }
      return startChar !== "" ? !1 : {
        value: attrStr,
        index: i,
        tagClosed
      };
    }
    var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
    function validateAttributeString(attrStr, options) {
      let matches = util.getAllMatches(attrStr, validAttrStrRegxp), attrNames = {};
      for (let i = 0; i < matches.length; i++) {
        if (matches[i][1].length === 0)
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]));
        if (matches[i][3] !== void 0 && matches[i][4] === void 0)
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i]));
        if (matches[i][3] === void 0 && !options.allowBooleanAttributes)
          return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
        let attrName = matches[i][2];
        if (!validateAttrName(attrName))
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
        if (!attrNames.hasOwnProperty(attrName))
          attrNames[attrName] = 1;
        else
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
      }
      return !0;
    }
    function validateNumberAmpersand(xmlData, i) {
      let re = /\d/;
      for (xmlData[i] === "x" && (i++, re = /[\da-fA-F]/); i < xmlData.length; i++) {
        if (xmlData[i] === ";")
          return i;
        if (!xmlData[i].match(re))
          break;
      }
      return -1;
    }
    function validateAmpersand(xmlData, i) {
      if (i++, xmlData[i] === ";")
        return -1;
      if (xmlData[i] === "#")
        return i++, validateNumberAmpersand(xmlData, i);
      let count = 0;
      for (; i < xmlData.length; i++, count++)
        if (!(xmlData[i].match(/\w/) && count < 20)) {
          if (xmlData[i] === ";")
            break;
          return -1;
        }
      return i;
    }
    function getErrorObject(code, message, lineNumber) {
      return {
        err: {
          code,
          msg: message,
          line: lineNumber.line || lineNumber,
          col: lineNumber.col
        }
      };
    }
    function validateAttrName(attrName) {
      return util.isName(attrName);
    }
    function validateTagName(tagname) {
      return util.isName(tagname);
    }
    function getLineNumberForPosition(xmlData, index) {
      let lines = xmlData.substring(0, index).split(/\r?\n/);
      return {
        line: lines.length,
        // column number is last line's length + 1, because column numbering starts at 1:
        col: lines[lines.length - 1].length + 1
      };
    }
    function getPositionFromMatch(match) {
      return match.startIndex + match[1].length;
    }
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var require_OptionsBuilder = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports) {
    var defaultOptions = {
      preserveOrder: !1,
      attributeNamePrefix: "@_",
      attributesGroupName: !1,
      textNodeName: "#text",
      ignoreAttributes: !0,
      removeNSPrefix: !1,
      // remove NS from tag name or attribute name if true
      allowBooleanAttributes: !1,
      //a tag can have attributes without any value
      //ignoreRootElement : false,
      parseTagValue: !0,
      parseAttributeValue: !1,
      trimValues: !0,
      //Trim string values of tag and attributes
      cdataPropName: !1,
      numberParseOptions: {
        hex: !0,
        leadingZeros: !0,
        eNotation: !0
      },
      tagValueProcessor: function(tagName, val2) {
        return val2;
      },
      attributeValueProcessor: function(attrName, val2) {
        return val2;
      },
      stopNodes: [],
      //nested tags will not be parsed even for errors
      alwaysCreateTextNode: !1,
      isArray: () => !1,
      commentPropName: !1,
      unpairedTags: [],
      processEntities: !0,
      htmlEntities: !1,
      ignoreDeclaration: !1,
      ignorePiTags: !1,
      transformTagName: !1,
      transformAttributeName: !1,
      updateTag: function(tagName, jPath, attrs) {
        return tagName;
      }
      // skipEmptyListItem: false
    }, buildOptions = function(options) {
      return Object.assign({}, defaultOptions, options);
    };
    exports.buildOptions = buildOptions;
    exports.defaultOptions = defaultOptions;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var require_xmlNode = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports, module) {
    "use strict";
    var XmlNode = class {
      constructor(tagname) {
        this.tagname = tagname, this.child = [], this[":@"] = {};
      }
      add(key, val2) {
        key === "__proto__" && (key = "#__proto__"), this.child.push({ [key]: val2 });
      }
      addChild(node) {
        node.tagname === "__proto__" && (node.tagname = "#__proto__"), node[":@"] && Object.keys(node[":@"]).length > 0 ? this.child.push({ [node.tagname]: node.child, ":@": node[":@"] }) : this.child.push({ [node.tagname]: node.child });
      }
    };
    module.exports = XmlNode;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
var require_DocTypeReader = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports, module) {
    var util = require_util();
    function readDocType(xmlData, i) {
      let entities = {};
      if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") {
        i = i + 9;
        let angleBracketsCount = 1, hasBody = !1, comment = !1, exp = "";
        for (; i < xmlData.length; i++)
          if (xmlData[i] === "<" && !comment) {
            if (hasBody && isEntity(xmlData, i))
              i += 7, [entityName, val, i] = readEntityExp(xmlData, i + 1), val.indexOf("&") === -1 && (entities[validateEntityName(entityName)] = {
                regx: RegExp(`&${entityName};`, "g"),
                val
              });
            else if (hasBody && isElement(xmlData, i)) i += 8;
            else if (hasBody && isAttlist(xmlData, i)) i += 8;
            else if (hasBody && isNotation(xmlData, i)) i += 9;
            else if (isComment) comment = !0;
            else throw new Error("Invalid DOCTYPE");
            angleBracketsCount++, exp = "";
          } else if (xmlData[i] === ">") {
            if (comment ? xmlData[i - 1] === "-" && xmlData[i - 2] === "-" && (comment = !1, angleBracketsCount--) : angleBracketsCount--, angleBracketsCount === 0)
              break;
          } else xmlData[i] === "[" ? hasBody = !0 : exp += xmlData[i];
        if (angleBracketsCount !== 0)
          throw new Error("Unclosed DOCTYPE");
      } else
        throw new Error("Invalid Tag instead of DOCTYPE");
      return { entities, i };
    }
    function readEntityExp(xmlData, i) {
      let entityName2 = "";
      for (; i < xmlData.length && xmlData[i] !== "'" && xmlData[i] !== '"'; i++)
        entityName2 += xmlData[i];
      if (entityName2 = entityName2.trim(), entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported");
      let startChar = xmlData[i++], val2 = "";
      for (; i < xmlData.length && xmlData[i] !== startChar; i++)
        val2 += xmlData[i];
      return [entityName2, val2, i];
    }
    function isComment(xmlData, i) {
      return xmlData[i + 1] === "!" && xmlData[i + 2] === "-" && xmlData[i + 3] === "-";
    }
    function isEntity(xmlData, i) {
      return xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "N" && xmlData[i + 4] === "T" && xmlData[i + 5] === "I" && xmlData[i + 6] === "T" && xmlData[i + 7] === "Y";
    }
    function isElement(xmlData, i) {
      return xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "L" && xmlData[i + 4] === "E" && xmlData[i + 5] === "M" && xmlData[i + 6] === "E" && xmlData[i + 7] === "N" && xmlData[i + 8] === "T";
    }
    function isAttlist(xmlData, i) {
      return xmlData[i + 1] === "!" && xmlData[i + 2] === "A" && xmlData[i + 3] === "T" && xmlData[i + 4] === "T" && xmlData[i + 5] === "L" && xmlData[i + 6] === "I" && xmlData[i + 7] === "S" && xmlData[i + 8] === "T";
    }
    function isNotation(xmlData, i) {
      return xmlData[i + 1] === "!" && xmlData[i + 2] === "N" && xmlData[i + 3] === "O" && xmlData[i + 4] === "T" && xmlData[i + 5] === "A" && xmlData[i + 6] === "T" && xmlData[i + 7] === "I" && xmlData[i + 8] === "O" && xmlData[i + 9] === "N";
    }
    function validateEntityName(name) {
      if (util.isName(name))
        return name;
      throw new Error(`Invalid entity name ${name}`);
    }
    module.exports = readDocType;
  }
});

// ../../node_modules/.pnpm/strnum@1.0.5/node_modules/strnum/strnum.js
var require_strnum = __commonJS({
  "../../node_modules/.pnpm/strnum@1.0.5/node_modules/strnum/strnum.js"(exports, module) {
    var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/, numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
    !Number.parseInt && window.parseInt && (Number.parseInt = window.parseInt);
    !Number.parseFloat && window.parseFloat && (Number.parseFloat = window.parseFloat);
    var consider = {
      hex: !0,
      leadingZeros: !0,
      decimalPoint: ".",
      eNotation: !0
      //skipLike: /regex/
    };
    function toNumber(str, options = {}) {
      if (options = Object.assign({}, consider, options), !str || typeof str != "string") return str;
      let trimmedStr = str.trim();
      if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
      if (options.hex && hexRegex.test(trimmedStr))
        return Number.parseInt(trimmedStr, 16);
      {
        let match = numRegex.exec(trimmedStr);
        if (match) {
          let sign = match[1], leadingZeros = match[2], numTrimmedByZeros = trimZeros(match[3]), eNotation = match[4] || match[6];
          if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str;
          if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str;
          {
            let num = Number(trimmedStr), numStr = "" + num;
            return numStr.search(/[eE]/) !== -1 || eNotation ? options.eNotation ? num : str : trimmedStr.indexOf(".") !== -1 ? numStr === "0" && numTrimmedByZeros === "" || numStr === numTrimmedByZeros || sign && numStr === "-" + numTrimmedByZeros ? num : str : leadingZeros ? numTrimmedByZeros === numStr || sign + numTrimmedByZeros === numStr ? num : str : trimmedStr === numStr || trimmedStr === sign + numStr ? num : str;
          }
        } else
          return str;
      }
    }
    function trimZeros(numStr) {
      return numStr && numStr.indexOf(".") !== -1 && (numStr = numStr.replace(/0+$/, ""), numStr === "." ? numStr = "0" : numStr[0] === "." ? numStr = "0" + numStr : numStr[numStr.length - 1] === "." && (numStr = numStr.substr(0, numStr.length - 1))), numStr;
    }
    module.exports = toNumber;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
var require_OrderedObjParser = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports, module) {
    "use strict";
    var util = require_util(), xmlNode = require_xmlNode(), readDocType = require_DocTypeReader(), toNumber = require_strnum(), OrderedObjParser = class {
      constructor(options) {
        this.options = options, this.currentNode = null, this.tagsNodeStack = [], this.docTypeEntities = {}, this.lastEntities = {
          apos: { regex: /&(apos|#39|#x27);/g, val: "'" },
          gt: { regex: /&(gt|#62|#x3E);/g, val: ">" },
          lt: { regex: /&(lt|#60|#x3C);/g, val: "<" },
          quot: { regex: /&(quot|#34|#x22);/g, val: '"' }
        }, this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }, this.htmlEntities = {
          space: { regex: /&(nbsp|#160);/g, val: " " },
          // "lt" : { regex: /&(lt|#60);/g, val: "<" },
          // "gt" : { regex: /&(gt|#62);/g, val: ">" },
          // "amp" : { regex: /&(amp|#38);/g, val: "&" },
          // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
          // "apos" : { regex: /&(apos|#39);/g, val: "'" },
          cent: { regex: /&(cent|#162);/g, val: "\xA2" },
          pound: { regex: /&(pound|#163);/g, val: "\xA3" },
          yen: { regex: /&(yen|#165);/g, val: "\xA5" },
          euro: { regex: /&(euro|#8364);/g, val: "\u20AC" },
          copyright: { regex: /&(copy|#169);/g, val: "\xA9" },
          reg: { regex: /&(reg|#174);/g, val: "\xAE" },
          inr: { regex: /&(inr|#8377);/g, val: "\u20B9" },
          num_dec: { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },
          num_hex: { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }
        }, this.addExternalEntities = addExternalEntities, this.parseXml = parseXml, this.parseTextData = parseTextData, this.resolveNameSpace = resolveNameSpace, this.buildAttributesMap = buildAttributesMap, this.isItStopNode = isItStopNode, this.replaceEntitiesValue = replaceEntitiesValue, this.readStopNodeData = readStopNodeData, this.saveTextToParentTag = saveTextToParentTag, this.addChild = addChild;
      }
    };
    function addExternalEntities(externalEntities) {
      let entKeys = Object.keys(externalEntities);
      for (let i = 0; i < entKeys.length; i++) {
        let ent = entKeys[i];
        this.lastEntities[ent] = {
          regex: new RegExp("&" + ent + ";", "g"),
          val: externalEntities[ent]
        };
      }
    }
    function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
      if (val2 !== void 0 && (this.options.trimValues && !dontTrim && (val2 = val2.trim()), val2.length > 0)) {
        escapeEntities || (val2 = this.replaceEntitiesValue(val2));
        let newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
        return newval == null ? val2 : typeof newval != typeof val2 || newval !== val2 ? newval : this.options.trimValues ? parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions) : val2.trim() === val2 ? parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions) : val2;
      }
    }
    function resolveNameSpace(tagname) {
      if (this.options.removeNSPrefix) {
        let tags = tagname.split(":"), prefix = tagname.charAt(0) === "/" ? "/" : "";
        if (tags[0] === "xmlns")
          return "";
        tags.length === 2 && (tagname = prefix + tags[1]);
      }
      return tagname;
    }
    var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
    function buildAttributesMap(attrStr, jPath, tagName) {
      if (!this.options.ignoreAttributes && typeof attrStr == "string") {
        let matches = util.getAllMatches(attrStr, attrsRegx), len = matches.length, attrs = {};
        for (let i = 0; i < len; i++) {
          let attrName = this.resolveNameSpace(matches[i][1]), oldVal = matches[i][4], aName = this.options.attributeNamePrefix + attrName;
          if (attrName.length)
            if (this.options.transformAttributeName && (aName = this.options.transformAttributeName(aName)), aName === "__proto__" && (aName = "#__proto__"), oldVal !== void 0) {
              this.options.trimValues && (oldVal = oldVal.trim()), oldVal = this.replaceEntitiesValue(oldVal);
              let newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
              newVal == null ? attrs[aName] = oldVal : typeof newVal != typeof oldVal || newVal !== oldVal ? attrs[aName] = newVal : attrs[aName] = parseValue(
                oldVal,
                this.options.parseAttributeValue,
                this.options.numberParseOptions
              );
            } else this.options.allowBooleanAttributes && (attrs[aName] = !0);
        }
        if (!Object.keys(attrs).length)
          return;
        if (this.options.attributesGroupName) {
          let attrCollection = {};
          return attrCollection[this.options.attributesGroupName] = attrs, attrCollection;
        }
        return attrs;
      }
    }
    var parseXml = function(xmlData) {
      xmlData = xmlData.replace(/\r\n?/g, `
`);
      let xmlObj = new xmlNode("!xml"), currentNode = xmlObj, textData = "", jPath = "";
      for (let i = 0; i < xmlData.length; i++)
        if (xmlData[i] === "<")
          if (xmlData[i + 1] === "/") {
            let closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed."), tagName = xmlData.substring(i + 2, closeIndex).trim();
            if (this.options.removeNSPrefix) {
              let colonIndex = tagName.indexOf(":");
              colonIndex !== -1 && (tagName = tagName.substr(colonIndex + 1));
            }
            this.options.transformTagName && (tagName = this.options.transformTagName(tagName)), currentNode && (textData = this.saveTextToParentTag(textData, currentNode, jPath));
            let lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
            if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1)
              throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
            let propIndex = 0;
            lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ? (propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1), this.tagsNodeStack.pop()) : propIndex = jPath.lastIndexOf("."), jPath = jPath.substring(0, propIndex), currentNode = this.tagsNodeStack.pop(), textData = "", i = closeIndex;
          } else if (xmlData[i + 1] === "?") {
            let tagData = readTagExp(xmlData, i, !1, "?>");
            if (!tagData) throw new Error("Pi Tag is not closed.");
            if (textData = this.saveTextToParentTag(textData, currentNode, jPath), !(this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags)) {
              let childNode = new xmlNode(tagData.tagName);
              childNode.add(this.options.textNodeName, ""), tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && (childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName)), this.addChild(currentNode, childNode, jPath);
            }
            i = tagData.closeIndex + 1;
          } else if (xmlData.substr(i + 1, 3) === "!--") {
            let endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.");
            if (this.options.commentPropName) {
              let comment = xmlData.substring(i + 4, endIndex - 2);
              textData = this.saveTextToParentTag(textData, currentNode, jPath), currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
            }
            i = endIndex;
          } else if (xmlData.substr(i + 1, 2) === "!D") {
            let result = readDocType(xmlData, i);
            this.docTypeEntities = result.entities, i = result.i;
          } else if (xmlData.substr(i + 1, 2) === "![") {
            let closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2, tagExp = xmlData.substring(i + 9, closeIndex);
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, !0, !1, !0, !0);
            val2 == null && (val2 = ""), this.options.cdataPropName ? currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]) : currentNode.add(this.options.textNodeName, val2), i = closeIndex + 2;
          } else {
            let result = readTagExp(xmlData, i, this.options.removeNSPrefix), tagName = result.tagName, rawTagName = result.rawTagName, tagExp = result.tagExp, attrExpPresent = result.attrExpPresent, closeIndex = result.closeIndex;
            this.options.transformTagName && (tagName = this.options.transformTagName(tagName)), currentNode && textData && currentNode.tagname !== "!xml" && (textData = this.saveTextToParentTag(textData, currentNode, jPath, !1));
            let lastTag = currentNode;
            if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 && (currentNode = this.tagsNodeStack.pop(), jPath = jPath.substring(0, jPath.lastIndexOf("."))), tagName !== xmlObj.tagname && (jPath += jPath ? "." + tagName : tagName), this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
              let tagContent = "";
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1)
                tagName[tagName.length - 1] === "/" ? (tagName = tagName.substr(0, tagName.length - 1), jPath = jPath.substr(0, jPath.length - 1), tagExp = tagName) : tagExp = tagExp.substr(0, tagExp.length - 1), i = result.closeIndex;
              else if (this.options.unpairedTags.indexOf(tagName) !== -1)
                i = result.closeIndex;
              else {
                let result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
                if (!result2) throw new Error(`Unexpected end of ${rawTagName}`);
                i = result2.i, tagContent = result2.tagContent;
              }
              let childNode = new xmlNode(tagName);
              tagName !== tagExp && attrExpPresent && (childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName)), tagContent && (tagContent = this.parseTextData(tagContent, tagName, jPath, !0, attrExpPresent, !0, !0)), jPath = jPath.substr(0, jPath.lastIndexOf(".")), childNode.add(this.options.textNodeName, tagContent), this.addChild(currentNode, childNode, jPath);
            } else {
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                tagName[tagName.length - 1] === "/" ? (tagName = tagName.substr(0, tagName.length - 1), jPath = jPath.substr(0, jPath.length - 1), tagExp = tagName) : tagExp = tagExp.substr(0, tagExp.length - 1), this.options.transformTagName && (tagName = this.options.transformTagName(tagName));
                let childNode = new xmlNode(tagName);
                tagName !== tagExp && attrExpPresent && (childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName)), this.addChild(currentNode, childNode, jPath), jPath = jPath.substr(0, jPath.lastIndexOf("."));
              } else {
                let childNode = new xmlNode(tagName);
                this.tagsNodeStack.push(currentNode), tagName !== tagExp && attrExpPresent && (childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName)), this.addChild(currentNode, childNode, jPath), currentNode = childNode;
              }
              textData = "", i = closeIndex;
            }
          }
        else
          textData += xmlData[i];
      return xmlObj.child;
    };
    function addChild(currentNode, childNode, jPath) {
      let result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
      result === !1 || (typeof result == "string" && (childNode.tagname = result), currentNode.addChild(childNode));
    }
    var replaceEntitiesValue = function(val2) {
      if (this.options.processEntities) {
        for (let entityName2 in this.docTypeEntities) {
          let entity = this.docTypeEntities[entityName2];
          val2 = val2.replace(entity.regx, entity.val);
        }
        for (let entityName2 in this.lastEntities) {
          let entity = this.lastEntities[entityName2];
          val2 = val2.replace(entity.regex, entity.val);
        }
        if (this.options.htmlEntities)
          for (let entityName2 in this.htmlEntities) {
            let entity = this.htmlEntities[entityName2];
            val2 = val2.replace(entity.regex, entity.val);
          }
        val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
      }
      return val2;
    };
    function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
      return textData && (isLeafNode === void 0 && (isLeafNode = Object.keys(currentNode.child).length === 0), textData = this.parseTextData(
        textData,
        currentNode.tagname,
        jPath,
        !1,
        currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : !1,
        isLeafNode
      ), textData !== void 0 && textData !== "" && currentNode.add(this.options.textNodeName, textData), textData = ""), textData;
    }
    function isItStopNode(stopNodes, jPath, currentTagName) {
      let allNodesExp = "*." + currentTagName;
      for (let stopNodePath in stopNodes) {
        let stopNodeExp = stopNodes[stopNodePath];
        if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return !0;
      }
      return !1;
    }
    function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
      let attrBoundary, tagExp = "";
      for (let index = i; index < xmlData.length; index++) {
        let ch = xmlData[index];
        if (attrBoundary)
          ch === attrBoundary && (attrBoundary = "");
        else if (ch === '"' || ch === "'")
          attrBoundary = ch;
        else if (ch === closingChar[0])
          if (closingChar[1]) {
            if (xmlData[index + 1] === closingChar[1])
              return {
                data: tagExp,
                index
              };
          } else
            return {
              data: tagExp,
              index
            };
        else ch === "	" && (ch = " ");
        tagExp += ch;
      }
    }
    function findClosingIndex(xmlData, str, i, errMsg) {
      let closingIndex = xmlData.indexOf(str, i);
      if (closingIndex === -1)
        throw new Error(errMsg);
      return closingIndex + str.length - 1;
    }
    function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
      let result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
      if (!result) return;
      let tagExp = result.data, closeIndex = result.index, separatorIndex = tagExp.search(/\s/), tagName = tagExp, attrExpPresent = !0;
      separatorIndex !== -1 && (tagName = tagExp.substring(0, separatorIndex), tagExp = tagExp.substring(separatorIndex + 1).trimStart());
      let rawTagName = tagName;
      if (removeNSPrefix) {
        let colonIndex = tagName.indexOf(":");
        colonIndex !== -1 && (tagName = tagName.substr(colonIndex + 1), attrExpPresent = tagName !== result.data.substr(colonIndex + 1));
      }
      return {
        tagName,
        tagExp,
        closeIndex,
        attrExpPresent,
        rawTagName
      };
    }
    function readStopNodeData(xmlData, tagName, i) {
      let startIndex = i, openTagCount = 1;
      for (; i < xmlData.length; i++)
        if (xmlData[i] === "<")
          if (xmlData[i + 1] === "/") {
            let closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
            if (xmlData.substring(i + 2, closeIndex).trim() === tagName && (openTagCount--, openTagCount === 0))
              return {
                tagContent: xmlData.substring(startIndex, i),
                i: closeIndex
              };
            i = closeIndex;
          } else if (xmlData[i + 1] === "?")
            i = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.");
          else if (xmlData.substr(i + 1, 3) === "!--")
            i = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.");
          else if (xmlData.substr(i + 1, 2) === "![")
            i = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
          else {
            let tagData = readTagExp(xmlData, i, ">");
            tagData && ((tagData && tagData.tagName) === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/" && openTagCount++, i = tagData.closeIndex);
          }
    }
    function parseValue(val2, shouldParse, options) {
      if (shouldParse && typeof val2 == "string") {
        let newval = val2.trim();
        return newval === "true" ? !0 : newval === "false" ? !1 : toNumber(val2, options);
      } else
        return util.isExist(val2) ? val2 : "";
    }
    module.exports = OrderedObjParser;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js
var require_node2json = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports) {
    "use strict";
    function prettify(node, options) {
      return compress(node, options);
    }
    function compress(arr, options, jPath) {
      let text, compressedObj = {};
      for (let i = 0; i < arr.length; i++) {
        let tagObj = arr[i], property = propName(tagObj), newJpath = "";
        if (jPath === void 0 ? newJpath = property : newJpath = jPath + "." + property, property === options.textNodeName)
          text === void 0 ? text = tagObj[property] : text += "" + tagObj[property];
        else {
          if (property === void 0)
            continue;
          if (tagObj[property]) {
            let val2 = compress(tagObj[property], options, newJpath), isLeaf = isLeafTag(val2, options);
            tagObj[":@"] ? assignAttributes(val2, tagObj[":@"], newJpath, options) : Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode ? val2 = val2[options.textNodeName] : Object.keys(val2).length === 0 && (options.alwaysCreateTextNode ? val2[options.textNodeName] = "" : val2 = ""), compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property) ? (Array.isArray(compressedObj[property]) || (compressedObj[property] = [compressedObj[property]]), compressedObj[property].push(val2)) : options.isArray(property, newJpath, isLeaf) ? compressedObj[property] = [val2] : compressedObj[property] = val2;
          }
        }
      }
      return typeof text == "string" ? text.length > 0 && (compressedObj[options.textNodeName] = text) : text !== void 0 && (compressedObj[options.textNodeName] = text), compressedObj;
    }
    function propName(obj) {
      let keys = Object.keys(obj);
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (key !== ":@") return key;
      }
    }
    function assignAttributes(obj, attrMap, jpath, options) {
      if (attrMap) {
        let keys = Object.keys(attrMap), len = keys.length;
        for (let i = 0; i < len; i++) {
          let atrrName = keys[i];
          options.isArray(atrrName, jpath + "." + atrrName, !0, !0) ? obj[atrrName] = [attrMap[atrrName]] : obj[atrrName] = attrMap[atrrName];
        }
      }
    }
    function isLeafTag(obj, options) {
      let { textNodeName } = options, propCount = Object.keys(obj).length;
      return !!(propCount === 0 || propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] == "boolean" || obj[textNodeName] === 0));
    }
    exports.prettify = prettify;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
var require_XMLParser = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports, module) {
    var { buildOptions } = require_OptionsBuilder(), OrderedObjParser = require_OrderedObjParser(), { prettify } = require_node2json(), validator = require_validator(), XMLParser2 = class {
      constructor(options) {
        this.externalEntities = {}, this.options = buildOptions(options);
      }
      /**
       * Parse XML dats to JS object 
       * @param {string|Buffer} xmlData 
       * @param {boolean|Object} validationOption 
       */
      parse(xmlData, validationOption) {
        if (typeof xmlData != "string")
          if (xmlData.toString)
            xmlData = xmlData.toString();
          else
            throw new Error("XML data is accepted in String or Bytes[] form.");
        if (validationOption) {
          validationOption === !0 && (validationOption = {});
          let result = validator.validate(xmlData, validationOption);
          if (result !== !0)
            throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
        }
        let orderedObjParser = new OrderedObjParser(this.options);
        orderedObjParser.addExternalEntities(this.externalEntities);
        let orderedResult = orderedObjParser.parseXml(xmlData);
        return this.options.preserveOrder || orderedResult === void 0 ? orderedResult : prettify(orderedResult, this.options);
      }
      /**
       * Add Entity which is not by default supported by this library
       * @param {string} key 
       * @param {string} value 
       */
      addEntity(key, value) {
        if (value.indexOf("&") !== -1)
          throw new Error("Entity value can't have '&'");
        if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1)
          throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
        if (value === "&")
          throw new Error("An entity with value '&' is not permitted");
        this.externalEntities[key] = value;
      }
    };
    module.exports = XMLParser2;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
var require_orderedJs2Xml = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports, module) {
    function toXml(jArray, options) {
      let indentation = "";
      return options.format && options.indentBy.length > 0 && (indentation = `
`), arrToStr(jArray, options, "", indentation);
    }
    function arrToStr(arr, options, jPath, indentation) {
      let xmlStr = "", isPreviousElementTag = !1;
      for (let i = 0; i < arr.length; i++) {
        let tagObj = arr[i], tagName = propName(tagObj);
        if (tagName === void 0) continue;
        let newJPath = "";
        if (jPath.length === 0 ? newJPath = tagName : newJPath = `${jPath}.${tagName}`, tagName === options.textNodeName) {
          let tagText = tagObj[tagName];
          isStopNode(newJPath, options) || (tagText = options.tagValueProcessor(tagName, tagText), tagText = replaceEntitiesValue(tagText, options)), isPreviousElementTag && (xmlStr += indentation), xmlStr += tagText, isPreviousElementTag = !1;
          continue;
        } else if (tagName === options.cdataPropName) {
          isPreviousElementTag && (xmlStr += indentation), xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`, isPreviousElementTag = !1;
          continue;
        } else if (tagName === options.commentPropName) {
          xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`, isPreviousElementTag = !0;
          continue;
        } else if (tagName[0] === "?") {
          let attStr2 = attr_to_str(tagObj[":@"], options), tempInd = tagName === "?xml" ? "" : indentation, piTextNodeName = tagObj[tagName][0][options.textNodeName];
          piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "", xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`, isPreviousElementTag = !0;
          continue;
        }
        let newIdentation = indentation;
        newIdentation !== "" && (newIdentation += options.indentBy);
        let attStr = attr_to_str(tagObj[":@"], options), tagStart = indentation + `<${tagName}${attStr}`, tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
        options.unpairedTags.indexOf(tagName) !== -1 ? options.suppressUnpairedNode ? xmlStr += tagStart + ">" : xmlStr += tagStart + "/>" : (!tagValue || tagValue.length === 0) && options.suppressEmptyNode ? xmlStr += tagStart + "/>" : tagValue && tagValue.endsWith(">") ? xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>` : (xmlStr += tagStart + ">", tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</")) ? xmlStr += indentation + options.indentBy + tagValue + indentation : xmlStr += tagValue, xmlStr += `</${tagName}>`), isPreviousElementTag = !0;
      }
      return xmlStr;
    }
    function propName(obj) {
      let keys = Object.keys(obj);
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (obj.hasOwnProperty(key) && key !== ":@")
          return key;
      }
    }
    function attr_to_str(attrMap, options) {
      let attrStr = "";
      if (attrMap && !options.ignoreAttributes)
        for (let attr in attrMap) {
          if (!attrMap.hasOwnProperty(attr)) continue;
          let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
          attrVal = replaceEntitiesValue(attrVal, options), attrVal === !0 && options.suppressBooleanAttributes ? attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}` : attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
        }
      return attrStr;
    }
    function isStopNode(jPath, options) {
      jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
      let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
      for (let index in options.stopNodes)
        if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return !0;
      return !1;
    }
    function replaceEntitiesValue(textValue, options) {
      if (textValue && textValue.length > 0 && options.processEntities)
        for (let i = 0; i < options.entities.length; i++) {
          let entity = options.entities[i];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      return textValue;
    }
    module.exports = toXml;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
var require_json2xml = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports, module) {
    "use strict";
    var buildFromOrderedJs = require_orderedJs2Xml(), defaultOptions = {
      attributeNamePrefix: "@_",
      attributesGroupName: !1,
      textNodeName: "#text",
      ignoreAttributes: !0,
      cdataPropName: !1,
      format: !1,
      indentBy: "  ",
      suppressEmptyNode: !1,
      suppressUnpairedNode: !0,
      suppressBooleanAttributes: !0,
      tagValueProcessor: function(key, a) {
        return a;
      },
      attributeValueProcessor: function(attrName, a) {
        return a;
      },
      preserveOrder: !1,
      commentPropName: !1,
      unpairedTags: [],
      entities: [
        { regex: new RegExp("&", "g"), val: "&amp;" },
        //it must be on top
        { regex: new RegExp(">", "g"), val: "&gt;" },
        { regex: new RegExp("<", "g"), val: "&lt;" },
        { regex: new RegExp("'", "g"), val: "&apos;" },
        { regex: new RegExp('"', "g"), val: "&quot;" }
      ],
      processEntities: !0,
      stopNodes: [],
      // transformTagName: false,
      // transformAttributeName: false,
      oneListGroup: !1
    };
    function Builder(options) {
      this.options = Object.assign({}, defaultOptions, options), this.options.ignoreAttributes || this.options.attributesGroupName ? this.isAttribute = function() {
        return !1;
      } : (this.attrPrefixLen = this.options.attributeNamePrefix.length, this.isAttribute = isAttribute), this.processTextOrObjNode = processTextOrObjNode, this.options.format ? (this.indentate = indentate, this.tagEndChar = `>
`, this.newLine = `
`) : (this.indentate = function() {
        return "";
      }, this.tagEndChar = ">", this.newLine = "");
    }
    Builder.prototype.build = function(jObj) {
      return this.options.preserveOrder ? buildFromOrderedJs(jObj, this.options) : (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1 && (jObj = {
        [this.options.arrayNodeName]: jObj
      }), this.j2x(jObj, 0).val);
    };
    Builder.prototype.j2x = function(jObj, level) {
      let attrStr = "", val2 = "";
      for (let key in jObj)
        if (Object.prototype.hasOwnProperty.call(jObj, key))
          if (typeof jObj[key] > "u")
            this.isAttribute(key) && (val2 += "");
          else if (jObj[key] === null)
            this.isAttribute(key) ? val2 += "" : key[0] === "?" ? val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar : val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
          else if (jObj[key] instanceof Date)
            val2 += this.buildTextValNode(jObj[key], key, "", level);
          else if (typeof jObj[key] != "object") {
            let attr = this.isAttribute(key);
            if (attr)
              attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
            else if (key === this.options.textNodeName) {
              let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
              val2 += this.replaceEntitiesValue(newval);
            } else
              val2 += this.buildTextValNode(jObj[key], key, "", level);
          } else if (Array.isArray(jObj[key])) {
            let arrLen = jObj[key].length, listTagVal = "", listTagAttr = "";
            for (let j = 0; j < arrLen; j++) {
              let item = jObj[key][j];
              if (!(typeof item > "u"))
                if (item === null)
                  key[0] === "?" ? val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar : val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
                else if (typeof item == "object")
                  if (this.options.oneListGroup) {
                    let result = this.j2x(item, level + 1);
                    listTagVal += result.val, this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName) && (listTagAttr += result.attrStr);
                  } else
                    listTagVal += this.processTextOrObjNode(item, key, level);
                else if (this.options.oneListGroup) {
                  let textValue = this.options.tagValueProcessor(key, item);
                  textValue = this.replaceEntitiesValue(textValue), listTagVal += textValue;
                } else
                  listTagVal += this.buildTextValNode(item, key, "", level);
            }
            this.options.oneListGroup && (listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level)), val2 += listTagVal;
          } else if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
            let Ks = Object.keys(jObj[key]), L = Ks.length;
            for (let j = 0; j < L; j++)
              attrStr += this.buildAttrPairStr(Ks[j], "" + jObj[key][Ks[j]]);
          } else
            val2 += this.processTextOrObjNode(jObj[key], key, level);
      return { attrStr, val: val2 };
    };
    Builder.prototype.buildAttrPairStr = function(attrName, val2) {
      return val2 = this.options.attributeValueProcessor(attrName, "" + val2), val2 = this.replaceEntitiesValue(val2), this.options.suppressBooleanAttributes && val2 === "true" ? " " + attrName : " " + attrName + '="' + val2 + '"';
    };
    function processTextOrObjNode(object, key, level) {
      let result = this.j2x(object, level + 1);
      return object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1 ? this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level) : this.buildObjectNode(result.val, key, result.attrStr, level);
    }
    Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
      if (val2 === "")
        return key[0] === "?" ? this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar : this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
      {
        let tagEndExp = "</" + key + this.tagEndChar, piClosingChar = "";
        return key[0] === "?" && (piClosingChar = "?", tagEndExp = ""), (attrStr || attrStr === "") && val2.indexOf("<") === -1 ? this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp : this.options.commentPropName !== !1 && key === this.options.commentPropName && piClosingChar.length === 0 ? this.indentate(level) + `<!--${val2}-->` + this.newLine : this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
      }
    };
    Builder.prototype.closeTag = function(key) {
      let closeTag = "";
      return this.options.unpairedTags.indexOf(key) !== -1 ? this.options.suppressUnpairedNode || (closeTag = "/") : this.options.suppressEmptyNode ? closeTag = "/" : closeTag = `></${key}`, closeTag;
    };
    Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
      if (this.options.cdataPropName !== !1 && key === this.options.cdataPropName)
        return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
      if (this.options.commentPropName !== !1 && key === this.options.commentPropName)
        return this.indentate(level) + `<!--${val2}-->` + this.newLine;
      if (key[0] === "?")
        return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
      {
        let textValue = this.options.tagValueProcessor(key, val2);
        return textValue = this.replaceEntitiesValue(textValue), textValue === "" ? this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar : this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
      }
    };
    Builder.prototype.replaceEntitiesValue = function(textValue) {
      if (textValue && textValue.length > 0 && this.options.processEntities)
        for (let i = 0; i < this.options.entities.length; i++) {
          let entity = this.options.entities[i];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      return textValue;
    };
    function indentate(level) {
      return this.options.indentBy.repeat(level);
    }
    function isAttribute(name) {
      return name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName ? name.substr(this.attrPrefixLen) : !1;
    }
    module.exports = Builder;
  }
});

// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js
var require_fxp = __commonJS({
  "../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports, module) {
    "use strict";
    var validator = require_validator(), XMLParser2 = require_XMLParser(), XMLBuilder2 = require_json2xml();
    module.exports = {
      XMLParser: XMLParser2,
      XMLValidator: validator,
      XMLBuilder: XMLBuilder2
    };
  }
});

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/middleware/cors/index.js
var cors = (options) => {
  let opts = {
    ...{
      origin: "*",
      allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
      allowHeaders: [],
      exposeHeaders: []
    },
    ...options
  }, findAllowOrigin = /* @__PURE__ */ ((optsOrigin) => typeof optsOrigin == "string" ? optsOrigin === "*" ? () => optsOrigin : (origin) => optsOrigin === origin ? origin : null : typeof optsOrigin == "function" ? optsOrigin : (origin) => optsOrigin.includes(origin) ? origin : null)(opts.origin), findAllowMethods = ((optsAllowMethods) => typeof optsAllowMethods == "function" ? optsAllowMethods : Array.isArray(optsAllowMethods) ? () => optsAllowMethods : () => [])(opts.allowMethods);
  return async function(c, next) {
    function set(key, value) {
      c.res.headers.set(key, value);
    }
    let allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
    if (allowOrigin && set("Access-Control-Allow-Origin", allowOrigin), opts.credentials && set("Access-Control-Allow-Credentials", "true"), opts.exposeHeaders?.length && set("Access-Control-Expose-Headers", opts.exposeHeaders.join(",")), c.req.method === "OPTIONS") {
      opts.origin !== "*" && set("Vary", "Origin"), opts.maxAge != null && set("Access-Control-Max-Age", opts.maxAge.toString());
      let allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
      allowMethods.length && set("Access-Control-Allow-Methods", allowMethods.join(","));
      let headers = opts.allowHeaders;
      if (!headers?.length) {
        let requestHeaders = c.req.header("Access-Control-Request-Headers");
        requestHeaders && (headers = requestHeaders.split(/\s*,\s*/));
      }
      return headers?.length && (set("Access-Control-Allow-Headers", headers.join(",")), c.res.headers.append("Vary", "Access-Control-Request-Headers")), c.res.headers.delete("Content-Length"), c.res.headers.delete("Content-Type"), new Response(null, {
        headers: c.res.headers,
        status: 204,
        statusText: "No Content"
      });
    }
    await next(), opts.origin !== "*" && c.header("Vary", "Origin", { append: !0 });
  };
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/compose.js
var compose = (middleware, onError, onNotFound) => (context, next) => {
  let index = -1;
  return dispatch2(0);
  async function dispatch2(i) {
    if (i <= index)
      throw new Error("next() called multiple times");
    index = i;
    let res, isError = !1, handler;
    if (middleware[i] ? (handler = middleware[i][0][0], context.req.routeIndex = i) : handler = i === middleware.length && next || void 0, handler)
      try {
        res = await handler(context, () => dispatch2(i + 1));
      } catch (err) {
        if (err instanceof Error && onError)
          context.error = err, res = await onError(err, context), isError = !0;
        else
          throw err;
      }
    else
      context.finalized === !1 && onNotFound && (res = await onNotFound(context));
    return res && (context.finalized === !1 || isError) && (context.res = res), context;
  }
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request/constants.js
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/body.js
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
  let { all = !1, dot = !1 } = options, contentType = (request instanceof HonoRequest ? request.raw.headers : request.headers).get("Content-Type");
  return contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded") ? parseFormData(request, { all, dot }) : {};
};
async function parseFormData(request, options) {
  let formData = await request.formData();
  return formData ? convertFormDataToBodyData(formData, options) : {};
}
function convertFormDataToBodyData(formData, options) {
  let form = /* @__PURE__ */ Object.create(null);
  return formData.forEach((value, key) => {
    options.all || key.endsWith("[]") ? handleParsingAllValues(form, key, value) : form[key] = value;
  }), options.dot && Object.entries(form).forEach(([key, value]) => {
    key.includes(".") && (handleParsingNestedValues(form, key, value), delete form[key]);
  }), form;
}
var handleParsingAllValues = (form, key, value) => {
  form[key] !== void 0 ? Array.isArray(form[key]) ? form[key].push(value) : form[key] = [form[key], value] : key.endsWith("[]") ? form[key] = [value] : form[key] = value;
}, handleParsingNestedValues = (form, key, value) => {
  let nestedForm = form, keys = key.split(".");
  keys.forEach((key2, index) => {
    index === keys.length - 1 ? nestedForm[key2] = value : ((!nestedForm[key2] || typeof nestedForm[key2] != "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) && (nestedForm[key2] = /* @__PURE__ */ Object.create(null)), nestedForm = nestedForm[key2]);
  });
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/url.js
var tryDecode = (str, decoder) => {
  try {
    return decoder(str);
  } catch {
    return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
      try {
        return decoder(match);
      } catch {
        return match;
      }
    });
  }
}, tryDecodeURI = (str) => tryDecode(str, decodeURI), getPath = (request) => {
  let url = request.url, start = url.indexOf("/", url.indexOf(":") + 4), i = start;
  for (; i < url.length; i++) {
    let charCode = url.charCodeAt(i);
    if (charCode === 37) {
      let queryIndex = url.indexOf("?", i), hashIndex = url.indexOf("#", i), end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex), path = url.slice(start, end);
      return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
    } else if (charCode === 63 || charCode === 35)
      break;
  }
  return url.slice(start, i);
};
var getPathNoStrict = (request) => {
  let result = getPath(request);
  return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
}, mergePath = (base, sub, ...rest) => (rest.length && (sub = mergePath(sub, ...rest)), `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`);
var _decodeURI = (value) => /[%+]/.test(value) ? (value.indexOf("+") !== -1 && (value = value.replace(/\+/g, " ")), value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value) : value, _getQueryParam = (url, key, multiple) => {
  let encoded;
  if (!multiple && key && !/[%+]/.test(key)) {
    let keyIndex2 = url.indexOf("?", 8);
    if (keyIndex2 === -1)
      return;
    for (url.startsWith(key, keyIndex2 + 1) || (keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1)); keyIndex2 !== -1; ) {
      let trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
      if (trailingKeyCode === 61) {
        let valueIndex = keyIndex2 + key.length + 2, endIndex = url.indexOf("&", valueIndex);
        return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
      } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode))
        return "";
      keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
    }
    if (encoded = /[%+]/.test(url), !encoded)
      return;
  }
  let results = {};
  encoded ??= /[%+]/.test(url);
  let keyIndex = url.indexOf("?", 8);
  for (; keyIndex !== -1; ) {
    let nextKeyIndex = url.indexOf("&", keyIndex + 1), valueIndex = url.indexOf("=", keyIndex);
    valueIndex > nextKeyIndex && nextKeyIndex !== -1 && (valueIndex = -1);
    let name = url.slice(
      keyIndex + 1,
      valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
    );
    if (encoded && (name = _decodeURI(name)), keyIndex = nextKeyIndex, name === "")
      continue;
    let value;
    valueIndex === -1 ? value = "" : (value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex), encoded && (value = _decodeURI(value))), multiple ? (results[name] && Array.isArray(results[name]) || (results[name] = []), results[name].push(value)) : results[name] ??= value;
  }
  return key ? results[key] : results;
}, getQueryParam = _getQueryParam, getQueryParams = (url, key) => _getQueryParam(url, key, !0), decodeURIComponent_ = decodeURIComponent;

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_), HonoRequest = class {
  /**
   * `.raw` can get the raw Request object.
   *
   * @see {@link https://hono.dev/docs/api/request#raw}
   *
   * @example
   * ```ts
   * // For Cloudflare Workers
   * app.post('/', async (c) => {
   *   const metadata = c.req.raw.cf?.hostMetadata?
   *   ...
   * })
   * ```
   */
  raw;
  #validatedData;
  // Short name of validatedData
  #matchResult;
  routeIndex = 0;
  /**
   * `.path` can get the pathname of the request.
   *
   * @see {@link https://hono.dev/docs/api/request#path}
   *
   * @example
   * ```ts
   * app.get('/about/me', (c) => {
   *   const pathname = c.req.path // `/about/me`
   * })
   * ```
   */
  path;
  bodyCache = {};
  constructor(request, path = "/", matchResult = [[]]) {
    this.raw = request, this.path = path, this.#matchResult = matchResult, this.#validatedData = {};
  }
  param(key) {
    return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
  }
  #getDecodedParam(key) {
    let paramKey = this.#matchResult[0][this.routeIndex][1][key], param = this.#getParamValue(paramKey);
    return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
  }
  #getAllDecodedParams() {
    let decoded = {}, keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
    for (let key of keys) {
      let value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
      value !== void 0 && (decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value);
    }
    return decoded;
  }
  #getParamValue(paramKey) {
    return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
  }
  query(key) {
    return getQueryParam(this.url, key);
  }
  queries(key) {
    return getQueryParams(this.url, key);
  }
  header(name) {
    if (name)
      return this.raw.headers.get(name) ?? void 0;
    let headerData = {};
    return this.raw.headers.forEach((value, key) => {
      headerData[key] = value;
    }), headerData;
  }
  async parseBody(options) {
    return this.bodyCache.parsedBody ??= await parseBody(this, options);
  }
  #cachedBody = (key) => {
    let { bodyCache, raw: raw2 } = this, cachedBody = bodyCache[key];
    if (cachedBody)
      return cachedBody;
    let anyCachedKey = Object.keys(bodyCache)[0];
    return anyCachedKey ? bodyCache[anyCachedKey].then((body) => (anyCachedKey === "json" && (body = JSON.stringify(body)), new Response(body)[key]())) : bodyCache[key] = raw2[key]();
  };
  /**
   * `.json()` can parse Request body of type `application/json`
   *
   * @see {@link https://hono.dev/docs/api/request#json}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.json()
   * })
   * ```
   */
  json() {
    return this.#cachedBody("text").then((text) => JSON.parse(text));
  }
  /**
   * `.text()` can parse Request body of type `text/plain`
   *
   * @see {@link https://hono.dev/docs/api/request#text}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.text()
   * })
   * ```
   */
  text() {
    return this.#cachedBody("text");
  }
  /**
   * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
   *
   * @see {@link https://hono.dev/docs/api/request#arraybuffer}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.arrayBuffer()
   * })
   * ```
   */
  arrayBuffer() {
    return this.#cachedBody("arrayBuffer");
  }
  /**
   * Parses the request body as a `Blob`.
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.blob();
   * });
   * ```
   * @see https://hono.dev/docs/api/request#blob
   */
  blob() {
    return this.#cachedBody("blob");
  }
  /**
   * Parses the request body as `FormData`.
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.formData();
   * });
   * ```
   * @see https://hono.dev/docs/api/request#formdata
   */
  formData() {
    return this.#cachedBody("formData");
  }
  /**
   * Adds validated data to the request.
   *
   * @param target - The target of the validation.
   * @param data - The validated data to add.
   */
  addValidatedData(target, data) {
    this.#validatedData[target] = data;
  }
  valid(target) {
    return this.#validatedData[target];
  }
  /**
   * `.url()` can get the request url strings.
   *
   * @see {@link https://hono.dev/docs/api/request#url}
   *
   * @example
   * ```ts
   * app.get('/about/me', (c) => {
   *   const url = c.req.url // `http://localhost:8787/about/me`
   *   ...
   * })
   * ```
   */
  get url() {
    return this.raw.url;
  }
  /**
   * `.method()` can get the method name of the request.
   *
   * @see {@link https://hono.dev/docs/api/request#method}
   *
   * @example
   * ```ts
   * app.get('/about/me', (c) => {
   *   const method = c.req.method // `GET`
   * })
   * ```
   */
  get method() {
    return this.raw.method;
  }
  get [GET_MATCH_RESULT]() {
    return this.#matchResult;
  }
  /**
   * `.matchedRoutes()` can return a matched route in the handler
   *
   * @deprecated
   *
   * Use matchedRoutes helper defined in "hono/route" instead.
   *
   * @see {@link https://hono.dev/docs/api/request#matchedroutes}
   *
   * @example
   * ```ts
   * app.use('*', async function logger(c, next) {
   *   await next()
   *   c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
   *     const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
   *     console.log(
   *       method,
   *       ' ',
   *       path,
   *       ' '.repeat(Math.max(10 - path.length, 0)),
   *       name,
   *       i === c.req.routeIndex ? '<- respond from here' : ''
   *     )
   *   })
   * })
   * ```
   */
  get matchedRoutes() {
    return this.#matchResult[0].map(([[, route]]) => route);
  }
  /**
   * `routePath()` can retrieve the path registered within the handler
   *
   * @deprecated
   *
   * Use routePath helper defined in "hono/route" instead.
   *
   * @see {@link https://hono.dev/docs/api/request#routepath}
   *
   * @example
   * ```ts
   * app.get('/posts/:id', (c) => {
   *   return c.json({ path: c.req.routePath })
   * })
   * ```
   */
  get routePath() {
    return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
  }
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/html.js
var HtmlEscapedCallbackPhase = {
  Stringify: 1,
  BeforeStream: 2,
  Stream: 3
}, raw = (value, callbacks) => {
  let escapedString = new String(value);
  return escapedString.isEscaped = !0, escapedString.callbacks = callbacks, escapedString;
};
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
  typeof str == "object" && !(str instanceof String) && (str instanceof Promise || (str = str.toString()), str instanceof Promise && (str = await str));
  let callbacks = str.callbacks;
  if (!callbacks?.length)
    return Promise.resolve(str);
  buffer ? buffer[0] += str : buffer = [str];
  let resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
    (res) => Promise.all(
      res.filter(Boolean).map((str2) => resolveCallback(str2, phase, !1, context, buffer))
    ).then(() => buffer[0])
  );
  return preserveCallbacks ? raw(await resStr, callbacks) : resStr;
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js
var TEXT_PLAIN = "text/plain; charset=UTF-8", setDefaultContentType = (contentType, headers) => ({
  "Content-Type": contentType,
  ...headers
}), createResponseInstance = (body, init) => new Response(body, init), Context = class {
  #rawRequest;
  #req;
  /**
   * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
   *
   * @see {@link https://hono.dev/docs/api/context#env}
   *
   * @example
   * ```ts
   * // Environment object for Cloudflare Workers
   * app.get('*', async c => {
   *   const counter = c.env.COUNTER
   * })
   * ```
   */
  env = {};
  #var;
  finalized = !1;
  /**
   * `.error` can get the error object from the middleware if the Handler throws an error.
   *
   * @see {@link https://hono.dev/docs/api/context#error}
   *
   * @example
   * ```ts
   * app.use('*', async (c, next) => {
   *   await next()
   *   if (c.error) {
   *     // do something...
   *   }
   * })
   * ```
   */
  error;
  #status;
  #executionCtx;
  #res;
  #layout;
  #renderer;
  #notFoundHandler;
  #preparedHeaders;
  #matchResult;
  #path;
  /**
   * Creates an instance of the Context class.
   *
   * @param req - The Request object.
   * @param options - Optional configuration options for the context.
   */
  constructor(req, options) {
    this.#rawRequest = req, options && (this.#executionCtx = options.executionCtx, this.env = options.env, this.#notFoundHandler = options.notFoundHandler, this.#path = options.path, this.#matchResult = options.matchResult);
  }
  /**
   * `.req` is the instance of {@link HonoRequest}.
   */
  get req() {
    return this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult), this.#req;
  }
  /**
   * @see {@link https://hono.dev/docs/api/context#event}
   * The FetchEvent associated with the current request.
   *
   * @throws Will throw an error if the context does not have a FetchEvent.
   */
  get event() {
    if (this.#executionCtx && "respondWith" in this.#executionCtx)
      return this.#executionCtx;
    throw Error("This context has no FetchEvent");
  }
  /**
   * @see {@link https://hono.dev/docs/api/context#executionctx}
   * The ExecutionContext associated with the current request.
   *
   * @throws Will throw an error if the context does not have an ExecutionContext.
   */
  get executionCtx() {
    if (this.#executionCtx)
      return this.#executionCtx;
    throw Error("This context has no ExecutionContext");
  }
  /**
   * @see {@link https://hono.dev/docs/api/context#res}
   * The Response object for the current request.
   */
  get res() {
    return this.#res ||= createResponseInstance(null, {
      headers: this.#preparedHeaders ??= new Headers()
    });
  }
  /**
   * Sets the Response object for the current request.
   *
   * @param _res - The Response object to set.
   */
  set res(_res) {
    if (this.#res && _res) {
      _res = createResponseInstance(_res.body, _res);
      for (let [k, v] of this.#res.headers.entries())
        if (k !== "content-type")
          if (k === "set-cookie") {
            let cookies = this.#res.headers.getSetCookie();
            _res.headers.delete("set-cookie");
            for (let cookie of cookies)
              _res.headers.append("set-cookie", cookie);
          } else
            _res.headers.set(k, v);
    }
    this.#res = _res, this.finalized = !0;
  }
  /**
   * `.render()` can create a response within a layout.
   *
   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
   *
   * @example
   * ```ts
   * app.get('/', (c) => {
   *   return c.render('Hello!')
   * })
   * ```
   */
  render = (...args) => (this.#renderer ??= (content) => this.html(content), this.#renderer(...args));
  /**
   * Sets the layout for the response.
   *
   * @param layout - The layout to set.
   * @returns The layout function.
   */
  setLayout = (layout) => this.#layout = layout;
  /**
   * Gets the current layout for the response.
   *
   * @returns The current layout function.
   */
  getLayout = () => this.#layout;
  /**
   * `.setRenderer()` can set the layout in the custom middleware.
   *
   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
   *
   * @example
   * ```tsx
   * app.use('*', async (c, next) => {
   *   c.setRenderer((content) => {
   *     return c.html(
   *       <html>
   *         <body>
   *           <p>{content}</p>
   *         </body>
   *       </html>
   *     )
   *   })
   *   await next()
   * })
   * ```
   */
  setRenderer = (renderer) => {
    this.#renderer = renderer;
  };
  /**
   * `.header()` can set headers.
   *
   * @see {@link https://hono.dev/docs/api/context#header}
   *
   * @example
   * ```ts
   * app.get('/welcome', (c) => {
   *   // Set headers
   *   c.header('X-Message', 'Hello!')
   *   c.header('Content-Type', 'text/plain')
   *
   *   return c.body('Thank you for coming')
   * })
   * ```
   */
  header = (name, value, options) => {
    this.finalized && (this.#res = createResponseInstance(this.#res.body, this.#res));
    let headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
    value === void 0 ? headers.delete(name) : options?.append ? headers.append(name, value) : headers.set(name, value);
  };
  status = (status) => {
    this.#status = status;
  };
  /**
   * `.set()` can set the value specified by the key.
   *
   * @see {@link https://hono.dev/docs/api/context#set-get}
   *
   * @example
   * ```ts
   * app.use('*', async (c, next) => {
   *   c.set('message', 'Hono is hot!!')
   *   await next()
   * })
   * ```
   */
  set = (key, value) => {
    this.#var ??= /* @__PURE__ */ new Map(), this.#var.set(key, value);
  };
  /**
   * `.get()` can use the value specified by the key.
   *
   * @see {@link https://hono.dev/docs/api/context#set-get}
   *
   * @example
   * ```ts
   * app.get('/', (c) => {
   *   const message = c.get('message')
   *   return c.text(`The message is "${message}"`)
   * })
   * ```
   */
  get = (key) => this.#var ? this.#var.get(key) : void 0;
  /**
   * `.var` can access the value of a variable.
   *
   * @see {@link https://hono.dev/docs/api/context#var}
   *
   * @example
   * ```ts
   * const result = c.var.client.oneMethod()
   * ```
   */
  // c.var.propName is a read-only
  get var() {
    return this.#var ? Object.fromEntries(this.#var) : {};
  }
  #newResponse(data, arg, headers) {
    let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
    if (typeof arg == "object" && "headers" in arg) {
      let argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
      for (let [key, value] of argHeaders)
        key.toLowerCase() === "set-cookie" ? responseHeaders.append(key, value) : responseHeaders.set(key, value);
    }
    if (headers)
      for (let [k, v] of Object.entries(headers))
        if (typeof v == "string")
          responseHeaders.set(k, v);
        else {
          responseHeaders.delete(k);
          for (let v2 of v)
            responseHeaders.append(k, v2);
        }
    let status = typeof arg == "number" ? arg : arg?.status ?? this.#status;
    return createResponseInstance(data, { status, headers: responseHeaders });
  }
  newResponse = (...args) => this.#newResponse(...args);
  /**
   * `.body()` can return the HTTP response.
   * You can set headers with `.header()` and set HTTP status code with `.status`.
   * This can also be set in `.text()`, `.json()` and so on.
   *
   * @see {@link https://hono.dev/docs/api/context#body}
   *
   * @example
   * ```ts
   * app.get('/welcome', (c) => {
   *   // Set headers
   *   c.header('X-Message', 'Hello!')
   *   c.header('Content-Type', 'text/plain')
   *   // Set HTTP status code
   *   c.status(201)
   *
   *   // Return the response body
   *   return c.body('Thank you for coming')
   * })
   * ```
   */
  body = (data, arg, headers) => this.#newResponse(data, arg, headers);
  /**
   * `.text()` can render text as `Content-Type:text/plain`.
   *
   * @see {@link https://hono.dev/docs/api/context#text}
   *
   * @example
   * ```ts
   * app.get('/say', (c) => {
   *   return c.text('Hello!')
   * })
   * ```
   */
  text = (text, arg, headers) => !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
    text,
    arg,
    setDefaultContentType(TEXT_PLAIN, headers)
  );
  /**
   * `.json()` can render JSON as `Content-Type:application/json`.
   *
   * @see {@link https://hono.dev/docs/api/context#json}
   *
   * @example
   * ```ts
   * app.get('/api', (c) => {
   *   return c.json({ message: 'Hello!' })
   * })
   * ```
   */
  json = (object, arg, headers) => this.#newResponse(
    JSON.stringify(object),
    arg,
    setDefaultContentType("application/json", headers)
  );
  html = (html, arg, headers) => {
    let res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
    return typeof html == "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, !1, {}).then(res) : res(html);
  };
  /**
   * `.redirect()` can Redirect, default status code is 302.
   *
   * @see {@link https://hono.dev/docs/api/context#redirect}
   *
   * @example
   * ```ts
   * app.get('/redirect', (c) => {
   *   return c.redirect('/')
   * })
   * app.get('/redirect-permanently', (c) => {
   *   return c.redirect('/', 301)
   * })
   * ```
   */
  redirect = (location, status) => {
    let locationString = String(location);
    return this.header(
      "Location",
      // Multibyes should be encoded
      // eslint-disable-next-line no-control-regex
      /[^\x00-\xFF]/.test(locationString) ? encodeURI(locationString) : locationString
    ), this.newResponse(null, status ?? 302);
  };
  /**
   * `.notFound()` can return the Not Found Response.
   *
   * @see {@link https://hono.dev/docs/api/context#notfound}
   *
   * @example
   * ```ts
   * app.get('/notfound', (c) => {
   *   return c.notFound()
   * })
   * ```
   */
  notFound = () => (this.#notFoundHandler ??= () => createResponseInstance(), this.#notFoundHandler(this));
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router.js
var METHOD_NAME_ALL = "ALL", METHOD_NAME_ALL_LOWERCASE = "all", METHODS = ["get", "post", "put", "delete", "options", "patch"];
var UnsupportedPathError = class extends Error {
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/constants.js
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js
var notFoundHandler = (c) => c.text("404 Not Found", 404), errorHandler = (err, c) => {
  if ("getResponse" in err) {
    let res = err.getResponse();
    return c.newResponse(res.body, res);
  }
  return console.error(err), c.text("Internal Server Error", 500);
}, Hono = class _Hono {
  get;
  post;
  put;
  delete;
  options;
  patch;
  all;
  on;
  use;
  /*
    This class is like an abstract class and does not have a router.
    To use it, inherit the class and implement router in the constructor.
  */
  router;
  getPath;
  // Cannot use `#` because it requires visibility at JavaScript runtime.
  _basePath = "/";
  #path = "/";
  routes = [];
  constructor(options = {}) {
    [...METHODS, METHOD_NAME_ALL_LOWERCASE].forEach((method) => {
      this[method] = (args1, ...args) => (typeof args1 == "string" ? this.#path = args1 : this.#addRoute(method, this.#path, args1), args.forEach((handler) => {
        this.#addRoute(method, this.#path, handler);
      }), this);
    }), this.on = (method, path, ...handlers) => {
      for (let p of [path].flat()) {
        this.#path = p;
        for (let m of [method].flat())
          handlers.map((handler) => {
            this.#addRoute(m.toUpperCase(), this.#path, handler);
          });
      }
      return this;
    }, this.use = (arg1, ...handlers) => (typeof arg1 == "string" ? this.#path = arg1 : (this.#path = "*", handlers.unshift(arg1)), handlers.forEach((handler) => {
      this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
    }), this);
    let { strict, ...optionsWithoutStrict } = options;
    Object.assign(this, optionsWithoutStrict), this.getPath = strict ?? !0 ? options.getPath ?? getPath : getPathNoStrict;
  }
  #clone() {
    let clone = new _Hono({
      router: this.router,
      getPath: this.getPath
    });
    return clone.errorHandler = this.errorHandler, clone.#notFoundHandler = this.#notFoundHandler, clone.routes = this.routes, clone;
  }
  #notFoundHandler = notFoundHandler;
  // Cannot use `#` because it requires visibility at JavaScript runtime.
  errorHandler = errorHandler;
  /**
   * `.route()` allows grouping other Hono instance in routes.
   *
   * @see {@link https://hono.dev/docs/api/routing#grouping}
   *
   * @param {string} path - base Path
   * @param {Hono} app - other Hono instance
   * @returns {Hono} routed Hono instance
   *
   * @example
   * ```ts
   * const app = new Hono()
   * const app2 = new Hono()
   *
   * app2.get("/user", (c) => c.text("user"))
   * app.route("/api", app2) // GET /api/user
   * ```
   */
  route(path, app2) {
    let subApp = this.basePath(path);
    return app2.routes.map((r) => {
      let handler;
      app2.errorHandler === errorHandler ? handler = r.handler : (handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, handler[COMPOSED_HANDLER] = r.handler), subApp.#addRoute(r.method, r.path, handler);
    }), this;
  }
  /**
   * `.basePath()` allows base paths to be specified.
   *
   * @see {@link https://hono.dev/docs/api/routing#base-path}
   *
   * @param {string} path - base Path
   * @returns {Hono} changed Hono instance
   *
   * @example
   * ```ts
   * const api = new Hono().basePath('/api')
   * ```
   */
  basePath(path) {
    let subApp = this.#clone();
    return subApp._basePath = mergePath(this._basePath, path), subApp;
  }
  /**
   * `.onError()` handles an error and returns a customized Response.
   *
   * @see {@link https://hono.dev/docs/api/hono#error-handling}
   *
   * @param {ErrorHandler} handler - request Handler for error
   * @returns {Hono} changed Hono instance
   *
   * @example
   * ```ts
   * app.onError((err, c) => {
   *   console.error(`${err}`)
   *   return c.text('Custom Error Message', 500)
   * })
   * ```
   */
  onError = (handler) => (this.errorHandler = handler, this);
  /**
   * `.notFound()` allows you to customize a Not Found Response.
   *
   * @see {@link https://hono.dev/docs/api/hono#not-found}
   *
   * @param {NotFoundHandler} handler - request handler for not-found
   * @returns {Hono} changed Hono instance
   *
   * @example
   * ```ts
   * app.notFound((c) => {
   *   return c.text('Custom 404 Message', 404)
   * })
   * ```
   */
  notFound = (handler) => (this.#notFoundHandler = handler, this);
  /**
   * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
   *
   * @see {@link https://hono.dev/docs/api/hono#mount}
   *
   * @param {string} path - base Path
   * @param {Function} applicationHandler - other Request Handler
   * @param {MountOptions} [options] - options of `.mount()`
   * @returns {Hono} mounted Hono instance
   *
   * @example
   * ```ts
   * import { Router as IttyRouter } from 'itty-router'
   * import { Hono } from 'hono'
   * // Create itty-router application
   * const ittyRouter = IttyRouter()
   * // GET /itty-router/hello
   * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
   *
   * const app = new Hono()
   * app.mount('/itty-router', ittyRouter.handle)
   * ```
   *
   * @example
   * ```ts
   * const app = new Hono()
   * // Send the request to another application without modification.
   * app.mount('/app', anotherApp, {
   *   replaceRequest: (req) => req,
   * })
   * ```
   */
  mount(path, applicationHandler, options) {
    let replaceRequest, optionHandler;
    options && (typeof options == "function" ? optionHandler = options : (optionHandler = options.optionHandler, options.replaceRequest === !1 ? replaceRequest = (request) => request : replaceRequest = options.replaceRequest));
    let getOptions = optionHandler ? (c) => {
      let options2 = optionHandler(c);
      return Array.isArray(options2) ? options2 : [options2];
    } : (c) => {
      let executionContext;
      try {
        executionContext = c.executionCtx;
      } catch {
      }
      return [c.env, executionContext];
    };
    replaceRequest ||= (() => {
      let mergedPath = mergePath(this._basePath, path), pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
      return (request) => {
        let url = new URL(request.url);
        return url.pathname = url.pathname.slice(pathPrefixLength) || "/", new Request(url, request);
      };
    })();
    let handler = async (c, next) => {
      let res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
      if (res)
        return res;
      await next();
    };
    return this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler), this;
  }
  #addRoute(method, path, handler) {
    method = method.toUpperCase(), path = mergePath(this._basePath, path);
    let r = { basePath: this._basePath, path, method, handler };
    this.router.add(method, path, [handler, r]), this.routes.push(r);
  }
  #handleError(err, c) {
    if (err instanceof Error)
      return this.errorHandler(err, c);
    throw err;
  }
  #dispatch(request, executionCtx, env, method) {
    if (method === "HEAD")
      return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
    let path = this.getPath(request, { env }), matchResult = this.router.match(method, path), c = new Context(request, {
      path,
      matchResult,
      env,
      executionCtx,
      notFoundHandler: this.#notFoundHandler
    });
    if (matchResult[0].length === 1) {
      let res;
      try {
        res = matchResult[0][0][0][0](c, async () => {
          c.res = await this.#notFoundHandler(c);
        });
      } catch (err) {
        return this.#handleError(err, c);
      }
      return res instanceof Promise ? res.then(
        (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
      ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
    }
    let composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
    return (async () => {
      try {
        let context = await composed(c);
        if (!context.finalized)
          throw new Error(
            "Context is not finalized. Did you forget to return a Response object or `await next()`?"
          );
        return context.res;
      } catch (err) {
        return this.#handleError(err, c);
      }
    })();
  }
  /**
   * `.fetch()` will be entry point of your app.
   *
   * @see {@link https://hono.dev/docs/api/hono#fetch}
   *
   * @param {Request} request - request Object of request
   * @param {Env} Env - env Object
   * @param {ExecutionContext} - context of execution
   * @returns {Response | Promise<Response>} response of request
   *
   */
  fetch = (request, ...rest) => this.#dispatch(request, rest[1], rest[0], request.method);
  /**
   * `.request()` is a useful method for testing.
   * You can pass a URL or pathname to send a GET request.
   * app will return a Response object.
   * ```ts
   * test('GET /hello is ok', async () => {
   *   const res = await app.request('/hello')
   *   expect(res.status).toBe(200)
   * })
   * ```
   * @see https://hono.dev/docs/api/hono#request
   */
  request = (input, requestInit, Env, executionCtx) => input instanceof Request ? this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx) : (input = input.toString(), this.fetch(
    new Request(
      /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
      requestInit
    ),
    Env,
    executionCtx
  ));
  /**
   * `.fire()` automatically adds a global fetch event listener.
   * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
   * @deprecated
   * Use `fire` from `hono/service-worker` instead.
   * ```ts
   * import { Hono } from 'hono'
   * import { fire } from 'hono/service-worker'
   *
   * const app = new Hono()
   * // ...
   * fire(app)
   * ```
   * @see https://hono.dev/docs/api/hono#fire
   * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
   * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
   */
  fire = () => {
    addEventListener("fetch", (event) => {
      event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
    });
  };
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/pattern-router/router.js
var emptyParams = /* @__PURE__ */ Object.create(null), PatternRouter = class {
  name = "PatternRouter";
  #routes = [];
  add(method, path, handler) {
    let endsWithWildcard = path.at(-1) === "*";
    endsWithWildcard && (path = path.slice(0, -2)), path.at(-1) === "?" && (path = path.slice(0, -1), this.add(method, path.replace(/\/[^/]+$/, ""), handler));
    let parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map(
      (part) => {
        let match = part.match(/^\/:([^{]+)(?:{(.*)})?/);
        return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&");
      }
    );
    try {
      this.#routes.push([
        new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
        method,
        handler
      ]);
    } catch {
      throw new UnsupportedPathError();
    }
  }
  match(method, path) {
    let handlers = [];
    for (let i = 0, len = this.#routes.length; i < len; i++) {
      let [pattern, routeMethod, handler] = this.#routes[i];
      if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {
        let match = pattern.exec(path);
        match && handlers.push([handler, match.groups || emptyParams]);
      }
    }
    return [handlers];
  }
};

// ../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/preset/tiny.js
var Hono2 = class extends Hono {
  constructor(options = {}) {
    super(options), this.router = new PatternRouter();
  }
};

// src/workers/core/constants.ts
var CorePaths = {
  /** Magic proxy used by getPlatformProxy */
  PLATFORM_PROXY: "/cdn-cgi/local/platform-proxy",
  /** Trigger scheduled event handlers */
  SCHEDULED: "/cdn-cgi/local/scheduled",
  /** Trigger email event handlers */
  EMAIL: "/cdn-cgi/local/email",
  /** Local explorer UI and API */
  EXPLORER: "/cdn-cgi/local/explorer",
  /** Stream video serving endpoint (outside /cdn-cgi/ for tunnel access) */
  STREAM_VIDEO: "/__cf_local/stream",
  /** Local image delivery endpoint (outside /cdn-cgi/ for tunnel access) */
  IMAGE_DELIVERY: "/__cf_local/imagedelivery",
  /** Public R2 bucket object serving endpoint */
  R2_PUBLIC: "/cdn-cgi/local/r2/public",
  /** S3-compatible API endpoint for local R2 buckets */
  R2_S3: "/cdn-cgi/local/r2/s3"
};

// src/workers/r2/s3/account.worker.ts
import assert2 from "node:assert";

// src/workers/r2/constants.ts
var R2S3Bindings = {
  /** JSON map of bucket id to `{ accessKeyId, secretAccessKey }` */
  JSON_CREDENTIALS: "MINIFLARE_R2_S3_CREDENTIALS",
  /** Prefix for per-bucket `R2Bucket` bindings (followed by the bucket id) */
  BUCKET_PREFIX: "MINIFLARE_R2_S3_BUCKET_"
};

// src/workers/r2/s3/auth.worker.ts
import assert from "node:assert";

// src/workers/r2/s3/common.worker.ts
var import_fast_xml_parser = __toESM(require_fxp());
import { Buffer as Buffer2 } from "node:buffer";
function stripBodyForHead(c, response) {
  return c.req.method === "HEAD" && response.body !== null ? new Response(null, response) : response;
}
var XMLNS = "http://s3.amazonaws.com/doc/2006-03-01/", MAX_LIST_KEYS = 1e3, MAX_DELETE_KEYS = 1e3, xmlBuilder = new import_fast_xml_parser.XMLBuilder({ ignoreAttributes: !1 }), xmlParser = new import_fast_xml_parser.XMLParser({
  ignoreAttributes: !0,
  parseTagValue: !1
});
function xmlResponse(root, content, status = 200) {
  let body = `<?xml version="1.0" encoding="UTF-8"?>${xmlBuilder.build({
    [root]: { "@_xmlns": XMLNS, ...content }
  })}`;
  return new Response(body, {
    status,
    headers: { "Content-Type": "application/xml" }
  });
}
function hex(bytes) {
  return Buffer2.from(bytes).toString("hex");
}
function coerceArray(value) {
  return value === void 0 ? [] : Array.isArray(value) ? value : [value];
}

// src/workers/r2/s3/errors.worker.ts
function xmlEscape(value) {
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
function errorResponse(status, code, message, extraFields = {}) {
  let extra = Object.entries(extraFields).map(([name, value]) => `<${name}>${xmlEscape(value)}</${name}>`).join(""), body = `<?xml version="1.0" encoding="UTF-8"?><Error><Code>${code}</Code><Message>${xmlEscape(message)}</Message>${extra}</Error>`;
  return new Response(body, {
    status,
    headers: { "Content-Type": "application/xml" }
  });
}
var noSuchBucket = () => errorResponse(404, "NoSuchBucket", "The specified bucket does not exist."), notImplemented = (message) => errorResponse(501, "NotImplemented", message), routeNotFound = () => errorResponse(404, "RouteNotFound", "No route matches this url.");

// src/workers/r2/s3/auth.worker.ts
var ALGORITHM = "AWS4-HMAC-SHA256", MAX_EXPIRES_SECONDS = 604800, MAX_SKEW_MILLIS = 900 * 1e3, encoder = new TextEncoder();
async function sha256Hex(data) {
  return hex(await crypto.subtle.digest("SHA-256", data));
}
async function hmac(key, data) {
  let cryptoKey = await crypto.subtle.importKey(
    "raw",
    key,
    { name: "HMAC", hash: "SHA-256" },
    !1,
    ["sign"]
  );
  return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(data));
}
function awsUriEncode(value) {
  return encodeURIComponent(value).replace(
    /[!'()*]/g,
    (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`
  );
}
var invalidArgument = (message) => errorResponse(400, "InvalidArgument", message), unauthorized = () => errorResponse(401, "Unauthorized", "Unauthorized");
function byteDump(value) {
  return Array.from(
    encoder.encode(value),
    (byte) => byte.toString(16).padStart(2, "0")
  ).join(" ");
}
function signatureDoesNotMatch(computed, provided) {
  return errorResponse(
    403,
    "SignatureDoesNotMatch",
    "The request signature we calculated does not match the signature you provided. Check your secret access key and signing method.",
    {
      StringToSign: computed.stringToSign,
      StringToSignBytes: byteDump(computed.stringToSign),
      CanonicalRequest: computed.canonicalRequest,
      CanonicalRequestBytes: byteDump(computed.canonicalRequest),
      SignatureProvided: provided
    }
  );
}
var unsupportedAlgorithm = () => errorResponse(400, "InvalidRequest", `Please use ${ALGORITHM}`);
function parseCredential(credential) {
  let parts = credential.split("/");
  if (parts.length < 5)
    return {
      error: invalidArgument(
        `Credential sigv4 header should have at least 5 slash-separated parts, not ${parts.length}`
      )
    };
  let accessKeyId = parts.slice(0, -4).join("/"), [date, region, service, terminator] = parts.slice(-4);
  return service !== "s3" ? {
    error: invalidArgument(`Credential service should be s3, not ${service}`)
  } : terminator !== "aws4_request" ? {
    error: invalidArgument(
      `Credential termination string should be aws4_request, not ${terminator}`
    )
  } : date === void 0 || region === void 0 ? { error: unauthorized() } : { accessKeyId, date, region, service };
}
function parseAmzDate(value) {
  let match = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(value);
  if (match === null)
    return;
  let [, year, month, day, hour, minute, second] = match, date = new Date(
    Date.UTC(
      Number(year),
      Number(month) - 1,
      Number(day),
      Number(hour),
      Number(minute),
      Number(second)
    )
  );
  return Number.isNaN(date.getTime()) ? void 0 : date;
}
function canonicalQueryString(url, excludeSignature) {
  let params = [];
  for (let [name, value] of url.searchParams)
    excludeSignature && name === "X-Amz-Signature" || params.push([awsUriEncode(name), awsUriEncode(value)]);
  return params.sort(([name1, value1], [name2, value2]) => name1 !== name2 ? name1 < name2 ? -1 : 1 : value1 < value2 ? -1 : value1 > value2 ? 1 : 0), params.map(([name, value]) => `${name}=${value}`).join("&");
}
function canonicalHeaders(request, url, signedHeaders) {
  let result = "";
  for (let name of signedHeaders) {
    let value = request.headers.get(name) ?? (name === "host" ? url.host : "");
    result += `${name}:${value.trim().replace(/ +/g, " ")}
`;
  }
  return result;
}
async function computeSignature(request, url, secretAccessKey, credential, amzDate, signedHeaders, payloadHash, presigned) {
  let canonicalRequest = [
    request.method,
    url.pathname,
    canonicalQueryString(url, presigned),
    canonicalHeaders(request, url, signedHeaders),
    signedHeaders.join(";"),
    payloadHash
  ].join(`
`), scope = `${credential.date}/${credential.region}/${credential.service}/aws4_request`, stringToSign = [
    ALGORITHM,
    amzDate,
    scope,
    await sha256Hex(encoder.encode(canonicalRequest))
  ].join(`
`), key = await hmac(
    encoder.encode(`AWS4${secretAccessKey}`),
    credential.date
  );
  return key = await hmac(key, credential.region), key = await hmac(key, credential.service), key = await hmac(key, "aws4_request"), {
    signature: hex(await hmac(key, stringToSign)),
    canonicalRequest,
    stringToSign
  };
}
function timingSafeStringsEqual(expected, actual) {
  let expectedBytes = encoder.encode(expected), actualBytes = encoder.encode(actual);
  return actualBytes.byteLength === expectedBytes.byteLength ? crypto.subtle.timingSafeEqual(expectedBytes, actualBytes) : !crypto.subtle.timingSafeEqual(expectedBytes, expectedBytes);
}
function checkCredentialScope(credentialField, amzDate, credentials) {
  let credential = parseCredential(credentialField);
  return "error" in credential ? credential : amzDate.startsWith(credential.date) ? credential.accessKeyId !== credentials.accessKeyId ? { error: unauthorized() } : credential : {
    error: invalidArgument(
      `Credential signed date ${credential.date} does not match ${amzDate.slice(0, 8)} from 'x-amz-date' header`
    )
  };
}
function parseSignedHeaders(field) {
  let signedHeaders = field.split(";").map((name) => name.toLowerCase());
  return signedHeaders.includes("host") ? signedHeaders : { error: unauthorized() };
}
async function checkSignature(request, url, credentials, credential, amzDate, signedHeaders, payloadHash, presigned, provided) {
  let computed = await computeSignature(
    request,
    url,
    credentials.secretAccessKey,
    credential,
    amzDate,
    signedHeaders,
    payloadHash,
    presigned
  );
  return timingSafeStringsEqual(computed.signature, provided) ? void 0 : signatureDoesNotMatch(computed, provided);
}
async function verifyAuthorizationHeader(request, url, credentials, authorization) {
  let payloadHash = request.headers.get("x-amz-content-sha256");
  if (payloadHash === null)
    return errorResponse(400, "InvalidRequest", "Missing x-amz-content-sha256");
  let amzDate = request.headers.get("x-amz-date"), dateSource = "'x-amz-date' header";
  if (amzDate === null && (amzDate = request.headers.get("date"), dateSource = "'date' header"), amzDate === null)
    return invalidArgument("No date provided in x-amz-date nor date header");
  let date = parseAmzDate(amzDate);
  if (date === void 0)
    return invalidArgument(
      `Date provided in ${dateSource} (${amzDate}) didn't parse successfully`
    );
  if (Math.abs(Date.now() - date.getTime()) > MAX_SKEW_MILLIS)
    return errorResponse(
      403,
      "RequestTimeTooSkewed",
      "The difference between the request time and the server's time is too large."
    );
  let fields = /* @__PURE__ */ new Map();
  if (authorization.startsWith(`${ALGORITHM} `))
    for (let component of authorization.slice(ALGORITHM.length).split(",")) {
      let separator = component.indexOf("=");
      separator !== -1 && fields.set(
        component.slice(0, separator).trim(),
        component.slice(separator + 1).trim()
      );
    }
  let credentialField = fields.get("Credential"), signedHeadersField = fields.get("SignedHeaders"), signatureField = fields.get("Signature");
  if (credentialField === void 0 || signedHeadersField === void 0 || signatureField === void 0)
    return unsupportedAlgorithm();
  let credential = checkCredentialScope(
    credentialField,
    amzDate,
    credentials
  );
  if ("error" in credential)
    return credential.error;
  let signedHeaders = parseSignedHeaders(signedHeadersField);
  if ("error" in signedHeaders)
    return signedHeaders.error;
  let mismatch = await checkSignature(
    request,
    url,
    credentials,
    credential,
    amzDate,
    signedHeaders,
    payloadHash,
    !1,
    signatureField
  );
  if (mismatch !== void 0)
    return mismatch;
  if (/^[0-9a-f]{64}$/.test(payloadHash)) {
    let body = await request.clone().arrayBuffer();
    if (await sha256Hex(body) !== payloadHash)
      return errorResponse(
        400,
        "XAmzContentSHA256Mismatch",
        "The provided 'x-amz-content-sha256' header does not match what was computed."
      );
  }
}
async function verifyPresigned(request, url, credentials) {
  let params = url.searchParams, missing = [
    "X-Amz-Algorithm",
    "X-Amz-Signature",
    "X-Amz-Date",
    "X-Amz-SignedHeaders",
    "X-Amz-Expires"
  ].filter((name) => !params.has(name));
  if (missing.length === 1)
    return invalidArgument(`Required search parameter ${missing[0]} missing`);
  if (missing.length > 1)
    return invalidArgument(
      `Required search parameters ${missing.join(",  ")} missing`
    );
  if (params.get("X-Amz-Algorithm") !== ALGORITHM)
    return unsupportedAlgorithm();
  let amzDate = params.get("X-Amz-Date"), expiresParam = params.get("X-Amz-Expires"), signedHeadersParam = params.get("X-Amz-SignedHeaders"), provided = params.get("X-Amz-Signature");
  assert(
    amzDate !== null && expiresParam !== null && signedHeadersParam !== null && provided !== null
  );
  let date = parseAmzDate(amzDate);
  if (date === void 0)
    return invalidArgument(
      `Date provided in X-Amz-Date (${amzDate}) didn't parse successfully`
    );
  let credentialParam = params.get("X-Amz-Credential");
  assert(credentialParam !== null);
  let credential = checkCredentialScope(
    credentialParam,
    amzDate,
    credentials
  );
  if ("error" in credential)
    return credential.error;
  let expires = expiresParam.trim() === "" ? Number.NaN : Number(expiresParam);
  if (Number.isNaN(expires))
    return invalidArgument("X-Amz-Expires should be a number");
  if (expires > MAX_EXPIRES_SECONDS)
    return invalidArgument(
      `X-Amz-Expires must be less than a week (in seconds); that is, the given X-Amz-Expires must be less than ${MAX_EXPIRES_SECONDS} seconds`
    );
  if (expires < 1 || Date.now() > date.getTime() + expires * 1e3)
    return errorResponse(403, "ExpiredRequest", "Request has expired");
  let signedHeaders = parseSignedHeaders(signedHeadersParam);
  return "error" in signedHeaders ? signedHeaders.error : checkSignature(
    request,
    url,
    credentials,
    credential,
    amzDate,
    signedHeaders,
    "UNSIGNED-PAYLOAD",
    !0,
    provided
  );
}
function credentialsEqual(expected, provided) {
  return timingSafeStringsEqual(expected.accessKeyId, provided.accessKeyId) && timingSafeStringsEqual(expected.secretAccessKey, provided.secretAccessKey);
}
function hasAuthentication(request, params) {
  return request.headers.get("Authorization") !== null || params.has("X-Amz-Credential");
}
async function verifyRequest(request, credentials) {
  let url = new URL(request.url), authorization = request.headers.get("Authorization");
  return authorization !== null ? verifyAuthorizationHeader(request, url, credentials, authorization) : url.searchParams.has("X-Amz-Credential") ? verifyPresigned(request, url, credentials) : invalidArgument("Authorization");
}

// src/workers/r2/s3/detect.worker.ts
var notImplementedOperation = (name) => notImplemented(`${name} not implemented`), OBJECT_SUBRESOURCES = {
  tagging: { GET: "GetObjectTagging", PUT: "PutObjectTagging" },
  acl: { GET: "GetObjectAcl", PUT: "PutObjectAcl" },
  attributes: { GET: "GetObjectAttributes" },
  torrent: { GET: "GetObjectTorrent" },
  retention: { GET: "GetObjectRetention", PUT: "PutObjectRetention" },
  "legal-hold": { GET: "GetObjectLegalHold", PUT: "PutObjectLegalHold" }
}, BUCKET_GET_NOT_IMPLEMENTED = {
  versions: "ListObjectVersions",
  policy: "GetBucketPolicy",
  website: "GetBucketWebsite",
  notification: "GetBucketNotificationConfiguration",
  requestPayment: "GetBucketRequestPayment",
  logging: "GetBucketLogging",
  accelerate: "GetBucketAccelerateConfiguration",
  publicAccessBlock: "GetPublicAccessBlock",
  ownershipControls: "GetBucketOwnershipControls",
  "intelligent-tiering": "GetBucketIntelligentTieringConfiguration",
  inventory: "GetBucketInventoryConfiguration",
  metrics: "GetBucketMetricsConfiguration",
  analytics: "GetBucketAnalyticsConfiguration",
  // R2's typo, reproduced verbatim
  policyStatus: "GetGetBucketPolicyStatus",
  acl: "GetBucketAcl",
  cors: "GetBucketCors",
  lifecycle: "GetBucketLifecycleConfiguration"
}, BUCKET_PUT_NOT_IMPLEMENTED = {
  accelerate: "PutBucketAccelerateConfiguration",
  acl: "PutBucketAcl",
  analytics: "PutBucketAnalyticsConfiguration",
  "intelligent-tiering": "PutBucketIntelligentTieringConfiguration",
  inventory: "PutBucketInventoryConfiguration",
  logging: "PutBucketLogging",
  metrics: "PutBucketMetricsConfiguration",
  notification: "PutBucketNotificationConfiguration",
  "object-lock": "PutObjectLockConfiguration",
  ownershipControls: "PutBucketOwnershipControls",
  policy: "PutBucketPolicy",
  publicAccessBlock: "PutPublicAccessBlock",
  replication: "PutBucketReplication",
  requestPayment: "PutBucketRequestPayment",
  tagging: "PutBucketTagging",
  website: "PutBucketWebsite",
  cors: "PutBucketCors",
  encryption: "PutBucketEncryption",
  lifecycle: "PutBucketLifecycleConfiguration",
  versioning: "PutBucketVersioning"
}, BUCKET_DELETE_NOT_IMPLEMENTED = {
  analytics: "DeleteBucketAnalyticsConfiguration",
  "intelligent-tiering": "DeleteBucketIntelligentTieringConfiguration",
  inventory: "DeleteBucketInventoryConfiguration",
  metrics: "DeleteBucketMetricsConfiguration",
  ownershipControls: "DeleteBucketOwnershipControls",
  policy: "DeleteBucketPolicy",
  replication: "DeleteBucketReplication",
  tagging: "DeleteBucketTagging",
  website: "DeleteBucketWebsite",
  cors: "DeleteBucketCors",
  encryption: "DeleteBucketEncryption",
  lifecycle: "DeleteBucketLifecycle"
}, BUCKET_GET_STATIC = {
  encryption: "GetBucketEncryption",
  versioning: "GetBucketVersioning",
  tagging: "GetBucketTagging",
  "object-lock": "GetObjectLockConfiguration",
  replication: "GetBucketReplication"
}, LIST_OBJECTS_PARAMS = /* @__PURE__ */ new Set([
  "prefix",
  "delimiter",
  "marker",
  "max-keys",
  "encoding-type"
]), LIST_OBJECTS_V2_PARAMS = /* @__PURE__ */ new Set([
  "list-type",
  "prefix",
  "delimiter",
  "continuation-token",
  "start-after",
  "max-keys",
  "encoding-type",
  "fetch-owner"
]);
function isScreenedParam(name) {
  return name.startsWith("X-Amz-") || name === "x-id";
}
function detectListOperation(params) {
  let listType = params.get("list-type");
  if (listType !== null && listType !== "2")
    return notImplementedOperation(`ListObjectsV${listType}`);
  let v2 = listType === "2";
  if (!v2 && params.has("continuation-token"))
    return errorResponse(
      400,
      "InvalidArgument",
      "continuation-token not supported in ListObjects"
    );
  let allowed = v2 ? LIST_OBJECTS_V2_PARAMS : LIST_OBJECTS_PARAMS;
  for (let name of params.keys())
    if (!allowed.has(name) && !isScreenedParam(name))
      return notImplemented(
        `ListObjectsV${v2 ? "2" : "1"} search parameter ${name} not implemented`
      );
  return v2 ? "ListObjectsV2" : "ListObjects";
}
function detectBucketMutation(method, params, subresources, bareOperation) {
  for (let name of params.keys()) {
    let operation = subresources[name];
    if (operation !== void 0)
      return notImplementedOperation(operation);
  }
  let unsupported = [...new Set(params.keys())].filter(
    (name) => !isScreenedParam(name)
  );
  return unsupported.length > 0 ? errorResponse(
    400,
    "InvalidArgument",
    `Unsupported search param(s) ${unsupported.map((name) => `"${name}"`).join(", ")} on a ${method} bucket route`
  ) : notImplementedOperation(bareOperation);
}
function detectBucketOperation(method, params) {
  switch (method) {
    case "HEAD":
      return "HeadBucket";
    case "PUT":
      return detectBucketMutation(
        "PUT",
        params,
        BUCKET_PUT_NOT_IMPLEMENTED,
        "CreateBucket"
      );
    case "DELETE":
      return detectBucketMutation(
        "DELETE",
        params,
        BUCKET_DELETE_NOT_IMPLEMENTED,
        "DeleteBucket"
      );
    case "POST":
      return params.has("delete") ? "DeleteObjects" : new Response(null, { status: 200 });
    case "GET": {
      if (params.has("uploads"))
        return notImplementedOperation("ListMultipartUploads");
      if (params.has("location")) {
        for (let name of params.keys())
          if (name !== "location" && !isScreenedParam(name))
            return errorResponse(
              400,
              "InvalidArgument",
              `Search param ${name} is unsupported for bucket location`
            );
        return "GetBucketLocation";
      }
      for (let name of params.keys()) {
        let staticOperation = BUCKET_GET_STATIC[name];
        if (staticOperation !== void 0)
          return staticOperation;
        let notImplementedName = BUCKET_GET_NOT_IMPLEMENTED[name];
        if (notImplementedName !== void 0)
          return notImplementedOperation(notImplementedName);
      }
      return detectListOperation(params);
    }
    default:
      return routeNotFound();
  }
}
function objectSubresourceError(params, method) {
  for (let name of params.keys()) {
    let subresource = OBJECT_SUBRESOURCES[name]?.[method];
    if (subresource !== void 0)
      return notImplementedOperation(subresource);
  }
}
function detectObjectOperation(c, params) {
  let method = c.req.method, uploadId = params.get("uploadId");
  if (uploadId !== null) {
    let partNumber = params.get("partNumber");
    if (partNumber !== null && !/^ *-?\d*$/.test(partNumber))
      return routeNotFound();
    switch (method) {
      case "GET":
        return notImplementedOperation("ListParts");
      case "PUT":
        if (partNumber === null)
          break;
        return {
          operation: c.req.header("x-amz-copy-source") !== void 0 ? "UploadPartCopy" : "UploadPart",
          uploadId
        };
      case "POST":
        return { operation: "CompleteMultipartUpload", uploadId };
      case "DELETE":
        return { operation: "AbortMultipartUpload", uploadId };
      case "HEAD":
        return "HeadObject";
      default:
        return routeNotFound();
    }
  }
  if (params.has("uploads")) {
    if (method === "POST")
      return "CreateMultipartUpload";
    if (method === "GET")
      return notImplementedOperation("ListMultipartUploads");
  }
  switch (method) {
    case "GET":
    case "HEAD":
      return params.has("partNumber") ? notImplementedOperation("partNumber") : method === "HEAD" ? "HeadObject" : objectSubresourceError(params, method) ?? "GetObject";
    case "PUT": {
      let subresource = objectSubresourceError(params, method);
      return subresource !== void 0 ? subresource : c.req.header("x-amz-copy-source") !== void 0 ? "CopyObject" : "PutObject";
    }
    case "POST":
      return "PutObject";
    case "DELETE":
      return "DeleteObject";
    default:
      return routeNotFound();
  }
}

// src/workers/r2/s3/account.worker.ts
async function verifyAgainstSome(c) {
  let error, seenPairs = /* @__PURE__ */ new Set();
  for (let credentials of Object.values(
    c.env[R2S3Bindings.JSON_CREDENTIALS]
  )) {
    let pair = `${credentials.accessKeyId}\0${credentials.secretAccessKey}`;
    if (seenPairs.has(pair))
      continue;
    seenPairs.add(pair);
    let result = await verifyRequest(c.req.raw, credentials);
    if (result === void 0)
      return { matched: credentials };
    (error === void 0 || error.status === 401) && (error = result);
  }
  return assert2(error !== void 0), { error };
}
async function listBuckets(c) {
  return stripBodyForHead(c, await listBucketsInner(c));
}
async function listBucketsInner(c) {
  if (c.req.method !== "GET")
    return routeNotFound();
  let credentialsById = c.env[R2S3Bindings.JSON_CREDENTIALS], verified = await verifyAgainstSome(c);
  if ("error" in verified)
    return verified.error;
  let matched = verified.matched;
  for (let name of new URL(c.req.url).searchParams.keys())
    if (!isScreenedParam(name))
      return notImplemented(
        `ListBuckets search parameter ${name} not implemented`
      );
  let buckets = Object.entries(credentialsById).filter(([, credentials]) => credentialsEqual(credentials, matched)).map(([id]) => ({ Name: id }));
  return xmlResponse("ListAllMyBucketsResult", {
    Buckets: buckets.length > 0 ? { Bucket: buckets } : {}
  });
}

// src/workers/r2/s3/dispatch.worker.ts
import assert4 from "node:assert";

// src/workers/r2/s3/operations.worker.ts
var import_fast_xml_parser2 = __toESM(require_fxp());
import assert3 from "node:assert";

// src/workers/r2/serve.worker.ts
var RANGE_HEADER = /^bytes=(?:(\d+)-(\d+)?|-(\d+))$/;
function parseRangeHeader(header) {
  let match = RANGE_HEADER.exec(header);
  if (match === null)
    return { error: "malformed" };
  let [, start, end, suffix] = match;
  return start === void 0 ? Number(suffix) === 0 ? { error: "unsatisfiable" } : {} : end !== void 0 && Number(start) > Number(end) ? { error: "inverted" } : { start: Number(start) };
}
function objectHeaders(object) {
  let headers = new Headers();
  return object.writeHttpMetadata(headers), headers.has("Content-Type") || headers.set("Content-Type", "application/octet-stream"), headers.set("ETag", object.httpEtag), headers.set("Last-Modified", object.uploaded.toUTCString()), headers.set("Accept-Ranges", "bytes"), headers;
}
async function serveR2Object(request, bucket, key, handlers, parsedRange) {
  let rangeHeader = request.headers.get("Range"), hasRange = rangeHeader !== null, object = await bucket.get(key, {
    onlyIf: request.headers,
    range: hasRange ? request.headers : void 0
  });
  if (object === null)
    return handlers.notFound();
  let headers = objectHeaders(object);
  if (handlers.decorateHeaders?.(object, headers), !("body" in object)) {
    let preconditions;
    for (let name of ["If-Match", "If-Unmodified-Since"]) {
      let value = request.headers.get(name);
      value !== null && (preconditions ??= new Headers(), preconditions.set(name, value));
    }
    if (preconditions !== void 0) {
      let recheck = await bucket.get(key, { onlyIf: preconditions });
      if (recheck === null)
        return handlers.notFound();
      if (!("body" in recheck))
        return handlers.preconditionFailed();
      recheck.body.cancel();
    }
    return new Response(null, { status: 304, headers });
  }
  let body = request.method === "HEAD" ? null : object.body;
  body === null && object.body.cancel();
  let range = object.range;
  if (hasRange && range !== void 0) {
    if (handlers.invalidRange !== void 0) {
      let parsed = parsedRange ?? parseRangeHeader(rangeHeader);
      if (!("error" in parsed) && (object.size === 0 || parsed.start !== void 0 && parsed.start >= object.size))
        return body !== null && body.cancel(), handlers.invalidRange();
    }
    let normalized = {
      ...range
    }, offset, length;
    return normalized.suffix !== void 0 ? (length = Math.min(normalized.suffix, object.size), offset = object.size - length) : (offset = normalized.offset ?? 0, length = normalized.length ?? object.size - offset), headers.set(
      "Content-Range",
      `bytes ${offset}-${offset + length - 1}/${object.size}`
    ), headers.set("Content-Length", `${length}`), new Response(body, { status: 206, headers });
  }
  return headers.set("Content-Length", `${object.size}`), new Response(body, { headers });
}

// src/workers/r2/s3/operations.worker.ts
var NO_SUCH_KEY = {
  status: 404,
  code: "NoSuchKey",
  message: "The specified key does not exist."
}, PRECONDITION_FAILED = {
  status: 412,
  code: "PreconditionFailed",
  message: "At least one of the pre-conditions you specified did not hold."
}, NO_SUCH_UPLOAD = {
  status: 404,
  code: "NoSuchUpload",
  message: "The specified multipart upload does not exist."
}, s3Error = (error) => errorResponse(error.status, error.code, error.message), noSuchKey = () => s3Error(NO_SUCH_KEY), preconditionFailed = () => s3Error(PRECONDITION_FAILED), malformedXml = () => errorResponse(
  400,
  "MalformedXML",
  "The XML you provided was not well formed or did not validate against our published schema."
), notImplementedHeader = (name, value) => errorResponse(
  501,
  "NotImplemented",
  `Header '${name}' with value '${value}' not implemented`
), BINDING_ERRORS = {
  // NO_SUCH_OBJECT_KEY
  10007: NO_SUCH_KEY,
  // ENTITY_TOO_SMALL
  10011: {
    status: 400,
    code: "EntityTooSmall",
    message: "Your proposed upload is smaller than the minimum allowed object size."
  },
  // NO_SUCH_UPLOAD
  10024: NO_SUCH_UPLOAD,
  // INVALID_PART
  10025: {
    status: 400,
    code: "InvalidPart",
    message: "One or more of the specified parts could not be found."
  },
  // PRECONDITION_FAILED
  10031: PRECONDITION_FAILED,
  // INVALID_RANGE
  10039: {
    status: 416,
    code: "InvalidRange",
    message: "The requested range is not satisfiable"
  }
};
function bindingError(e) {
  let message = e instanceof Error ? e.message : String(e), v4Code = /\((\d+)\)$/.exec(message), known = v4Code === null ? void 0 : BINDING_ERRORS[Number(v4Code[1])];
  return known !== void 0 ? s3Error(known) : errorResponse(500, "InternalError", message);
}
var BUCKET_OWNER = ["x-amz-expected-bucket-owner"], SOURCE_BUCKET_OWNER = ["x-amz-source-expected-bucket-owner"], MFA_AND_LOCK_BYPASS = ["x-amz-mfa", "x-amz-bypass-governance-retention"], COPY_SOURCE_CONDITIONALS = [
  "x-amz-copy-source-if-match",
  "x-amz-copy-source-if-none-match",
  "x-amz-copy-source-if-modified-since",
  "x-amz-copy-source-if-unmodified-since"
], WRITE_UNSUPPORTED = [
  ...BUCKET_OWNER,
  "x-amz-tagging",
  "x-amz-grant-full-control",
  "x-amz-grant-read",
  "x-amz-grant-read-acp",
  "x-amz-grant-write",
  "x-amz-grant-write-acp",
  "x-amz-website-redirect-location",
  "x-amz-object-lock-mode",
  "x-amz-object-lock-retain-until-date",
  "x-amz-object-lock-legal-hold",
  "x-amz-server-side-encryption-aws-kms-key-id",
  "x-amz-server-side-encryption-context",
  "x-amz-server-side-encryption-bucket-key-enabled"
], CANNED_ACLS = /* @__PURE__ */ new Set([
  "private",
  "public-read",
  "public-read-write",
  "authenticated-read",
  "aws-exec-read",
  "bucket-owner-read",
  "bucket-owner-full-control"
]);
function screenHeaders(c, operation, rules) {
  if (c.req.header("x-amz-security-token") !== void 0)
    return errorResponse(400, "InvalidArgument", "X-Amz-Security-Token");
  for (let name of rules.unsupportedHeaders) {
    let value = c.req.header(name);
    if (value !== void 0)
      return notImplementedHeader(name, value);
  }
  if (rules.validatesWriteHeaders === !0) {
    let sse = c.req.header("x-amz-server-side-encryption");
    if (sse !== void 0 && sse !== "AES256")
      return notImplementedHeader("x-amz-server-side-encryption", sse);
    let acl = c.req.header("x-amz-acl");
    if (acl !== void 0 && !CANNED_ACLS.has(acl))
      return notImplementedHeader("x-amz-acl", acl);
  }
  if (rules.ssec !== void 0)
    return screenSSECHeaders(c, operation, rules.ssec);
}
function screenSSECHeaders(c, operation, mode) {
  let prefixes = operation === "CopyObject" || operation === "UploadPartCopy" ? ["x-amz-", "x-amz-copy-source-"] : ["x-amz-"];
  for (let prefix of prefixes) {
    let algorithmName = `${prefix}server-side-encryption-customer-algorithm`, algorithm = c.req.header(algorithmName), key = c.req.header(`${prefix}server-side-encryption-customer-key`), keyMd5 = c.req.header(
      `${prefix}server-side-encryption-customer-key-MD5`
    );
    if (!(algorithm === void 0 && key === void 0 && keyMd5 === void 0))
      return key === void 0 ? errorResponse(
        400,
        "InvalidArgument",
        "Requests specifying Server Side Encryption with Customer provided keys must provide an appropriate secret key."
      ) : keyMd5 === void 0 ? errorResponse(
        400,
        "InvalidArgument",
        "Requests specifying Server Side Encryption with Customer provided keys must provide the client calculated MD5 of the secret key."
      ) : algorithm === void 0 ? errorResponse(
        400,
        "InvalidArgument",
        "Requests specifying Server Side Encryption with Customer provided keys must provide a valid encryption algorithm."
      ) : algorithm !== "AES256" ? errorResponse(
        400,
        "InvalidEncryptionAlgorithmError",
        "The encryption request that you specified is not valid. The valid value is AES256."
      ) : mode === "read" ? errorResponse(
        400,
        "InvalidRequest",
        "The encryption parameters are not applicable to this object."
      ) : notImplementedHeader(algorithmName, algorithm);
  }
}
var CONDITIONAL_HEADERS = [
  "If-Match",
  "If-None-Match",
  "If-Modified-Since",
  "If-Unmodified-Since"
];
async function verifiedRequestBody(c) {
  if (c.req.header("Content-MD5") === void 0)
    return c.req.raw.body ?? "";
  let buffered = await c.req.raw.arrayBuffer();
  return await verifyContentMD5(c, buffered) ?? buffered;
}
async function verifyContentMD5(c, body) {
  let contentMd5 = c.req.header("Content-MD5");
  if (contentMd5 === void 0)
    return;
  let provided;
  try {
    if (provided = Uint8Array.from(atob(contentMd5), (char) => char.charCodeAt(0)), provided.length !== 16)
      throw new Error("bad length");
  } catch {
    return errorResponse(
      400,
      "InvalidDigest",
      "The checksum or Content-MD5 you specified is not valid."
    );
  }
  let computed = hex(await crypto.subtle.digest("MD5", body));
  if (hex(provided) !== computed)
    return errorResponse(
      400,
      "BadDigest",
      `The MD5 checksum you specified did not match what we received.
You provided a MD5 checksum with value: ${hex(provided)}
Actual MD5 was: ${computed}`
    );
}
function parseStorageClass(c) {
  let header = c.req.header("x-amz-storage-class");
  switch (header) {
    case void 0:
      return;
    case "STANDARD":
      return "Standard";
    case "STANDARD_IA":
      return notImplementedHeader("x-amz-storage-class", header);
    default:
      return errorResponse(
        400,
        "InvalidStorageClass",
        "The storage class specified is not valid."
      );
  }
}
function collectCustomMetadata(c) {
  let customMetadata = {};
  for (let [name, value] of c.req.raw.headers)
    name.startsWith("x-amz-meta-") && (customMetadata[name.slice(11)] = value);
  return customMetadata;
}
function parseCopySource(c, bucketId) {
  let header = c.req.header("x-amz-copy-source");
  assert3(header !== void 0);
  let raw2 = decodeURIComponent(header), source = raw2.startsWith("/") ? raw2.slice(1) : raw2, separator = source.indexOf("/");
  if (separator === -1 || separator === source.length - 1)
    return errorResponse(400, "InvalidArgument", "copy source bucket name");
  let sourceBucketId = source.slice(0, separator), bucket = c.env[`${R2S3Bindings.BUCKET_PREFIX}${sourceBucketId}`];
  if (bucket === void 0)
    return noSuchBucket();
  let credentials = c.env[R2S3Bindings.JSON_CREDENTIALS], sourceCredentials = credentials[sourceBucketId], targetCredentials = credentials[bucketId];
  return assert3(sourceCredentials !== void 0 && targetCredentials !== void 0), credentialsEqual(sourceCredentials, targetCredentials) ? { bucket, key: source.slice(separator + 1) } : errorResponse(401, "Unauthorized", "Unauthorized");
}
function copySourceConditionals(c) {
  let headers;
  for (let standard of CONDITIONAL_HEADERS) {
    let value = c.req.header(`x-amz-copy-source-${standard.toLowerCase()}`);
    value !== void 0 && (headers ??= new Headers(), headers.set(standard, value));
  }
  return headers;
}
function serveObject(c, bucket, key) {
  let rangeHeader = c.req.header("Range"), range = rangeHeader === void 0 ? {} : parseRangeHeader(rangeHeader);
  if ("error" in range)
    switch (range.error) {
      case "malformed":
        return errorResponse(
          400,
          "InvalidArgument",
          "range must be in format 'bytes=start-end', 'bytes=start-' or 'bytes=-suffix'.'"
        );
      case "inverted":
        return errorResponse(400, "InvalidArgument", "range must be positive.");
      case "unsatisfiable":
        return errorResponse(
          416,
          "InvalidRange",
          "The requested range is not satisfiable"
        );
    }
  return serveR2Object(
    c.req.raw,
    bucket,
    key,
    {
      notFound: noSuchKey,
      preconditionFailed,
      invalidRange: () => errorResponse(
        416,
        "InvalidRange",
        "The requested range is not satisfiable"
      ),
      decorateHeaders(object, headers) {
        for (let [name, value] of Object.entries(
          object.customMetadata ?? {}
        ))
          headers.set(`x-amz-meta-${name}`, value);
      }
    },
    range
  );
}
async function listObjects(params, bucket, bucketId, v2) {
  let encodingType = params.get("encoding-type");
  if (encodingType !== null && encodingType !== "url")
    return notImplemented(
      `Unrecognized encoding-type "${encodingType}" not implemented`
    );
  let encode = (value) => encodingType === "url" ? awsUriEncode(value) : value, maxKeys = MAX_LIST_KEYS, maxKeysParam = params.get("max-keys");
  if (maxKeysParam !== null) {
    let value = maxKeysParam.trim() === "" ? Number.NaN : Number(maxKeysParam);
    if (!Number.isFinite(value) || value < 0)
      return errorResponse(
        400,
        "InvalidMaxKeys",
        "MaxKeys params must be positive integer <= 1000."
      );
    maxKeys = Math.floor(value);
  }
  let limit = Math.min(maxKeys, MAX_LIST_KEYS), prefix = params.get("prefix") ?? "", delimiter = params.get("delimiter") ?? void 0, marker = v2 ? void 0 : params.get("marker") ?? void 0, startAfter = v2 ? params.get("start-after") ?? void 0 : marker, continuationToken = v2 ? params.get("continuation-token") ?? void 0 : void 0, objects = [], delimitedPrefixes = [], truncated = !1, cursor, result;
  try {
    result = await bucket.list({
      prefix,
      delimiter,
      // For max-keys=0, list one key anyway: R2 reports IsTruncated based
      // on whether any matching keys exist
      limit: Math.max(limit, 1),
      startAfter,
      cursor: continuationToken
    });
  } catch (e) {
    return bindingError(e);
  }
  limit === 0 ? truncated = result.objects.length > 0 || result.delimitedPrefixes.length > 0 : (objects = result.objects, delimitedPrefixes = result.delimitedPrefixes, truncated = result.truncated, cursor = result.truncated ? result.cursor : void 0);
  let contents = objects.map((object) => ({
    Key: encode(object.key),
    Size: object.size,
    LastModified: object.uploaded.toISOString(),
    ETag: object.httpEtag,
    // The local simulator does not store storage classes
    StorageClass: "STANDARD"
  })), commonPrefixes = delimitedPrefixes.map((value) => ({
    Prefix: encode(value)
  })), lastObjectKey = objects[objects.length - 1]?.key, lastPrefix = delimitedPrefixes[delimitedPrefixes.length - 1], lastKey = lastPrefix !== void 0 && (lastObjectKey === void 0 || lastPrefix > lastObjectKey) ? lastPrefix : lastObjectKey;
  return xmlResponse("ListBucketResult", {
    Name: bucketId,
    ...contents.length > 0 ? { Contents: contents } : {},
    IsTruncated: truncated,
    ...commonPrefixes.length > 0 ? { CommonPrefixes: commonPrefixes } : {},
    Prefix: encode(prefix),
    ...delimiter !== void 0 ? { Delimiter: encode(delimiter) } : {},
    ...v2 ? {
      ...startAfter !== void 0 ? { StartAfter: encode(startAfter) } : {},
      ...continuationToken !== void 0 ? { ContinuationToken: continuationToken } : {},
      ...cursor !== void 0 ? { NextContinuationToken: cursor } : {}
    } : {
      Marker: encode(marker ?? ""),
      ...truncated && lastKey !== void 0 ? { NextMarker: encode(lastKey) } : {}
    },
    MaxKeys: maxKeys,
    ...v2 ? { KeyCount: contents.length + commonPrefixes.length } : {},
    ...encodingType !== null ? { EncodingType: encodingType } : {}
  });
}
function parsePartNumber(params) {
  let raw2 = params.get("partNumber");
  assert3(raw2 !== null);
  let partNumber = raw2.trim() === "" ? Number.NaN : Number(raw2);
  return !Number.isInteger(partNumber) || partNumber < 1 || partNumber > 1e4 ? errorResponse(
    400,
    "InvalidArgument",
    "Part number must be an integer between 1 and 10000, inclusive."
  ) : partNumber;
}
var OBJECT_OPERATIONS = {
  GetObject: {
    unsupportedHeaders: BUCKET_OWNER,
    ssec: "read",
    handle: ({ c, bucket, key }) => serveObject(c, bucket, key)
  },
  HeadObject: {
    unsupportedHeaders: BUCKET_OWNER,
    ssec: "read",
    handle: ({ c, bucket, key }) => serveObject(c, bucket, key)
  },
  PutObject: {
    unsupportedHeaders: WRITE_UNSUPPORTED,
    validatesWriteHeaders: !0,
    ssec: "write",
    async handle({ c, bucket, key }) {
      let storageClass = parseStorageClass(c);
      if (storageClass instanceof Response)
        return storageClass;
      let body = await verifiedRequestBody(c);
      if (body instanceof Response)
        return body;
      let hasConditional = CONDITIONAL_HEADERS.some(
        (name) => c.req.header(name) !== void 0
      ), object = await bucket.put(key, body, {
        httpMetadata: c.req.raw.headers,
        customMetadata: collectCustomMetadata(c),
        onlyIf: hasConditional ? c.req.raw.headers : void 0,
        storageClass
      });
      return object === null ? preconditionFailed() : c.body(null, { headers: { ETag: object.httpEtag } });
    }
  },
  CopyObject: {
    unsupportedHeaders: [
      ...WRITE_UNSUPPORTED,
      ...SOURCE_BUCKET_OWNER,
      "x-amz-tagging-directive",
      "x-amz-checksum-algorithm"
    ],
    validatesWriteHeaders: !0,
    ssec: "write",
    async handle({ c, bucket, bucketId, key }) {
      let directive = c.req.header("x-amz-metadata-directive") ?? "COPY";
      if (directive !== "COPY" && directive !== "REPLACE")
        return errorResponse(
          400,
          "InvalidArgument",
          `metadata directive ${directive}.`
        );
      let storageClass = parseStorageClass(c);
      if (storageClass instanceof Response)
        return storageClass;
      let source = parseCopySource(c, bucketId);
      if (source instanceof Response)
        return source;
      let sourceObject = await source.bucket.get(source.key, {
        onlyIf: copySourceConditionals(c)
      });
      if (sourceObject === null)
        return noSuchKey();
      if (!("body" in sourceObject))
        return preconditionFailed();
      let object = await bucket.put(key, sourceObject.body, {
        httpMetadata: directive === "COPY" ? sourceObject.httpMetadata : c.req.raw.headers,
        customMetadata: directive === "COPY" ? sourceObject.customMetadata : collectCustomMetadata(c),
        storageClass
      });
      return object === null ? preconditionFailed() : xmlResponse("CopyObjectResult", {
        ETag: object.httpEtag,
        LastModified: object.uploaded.toISOString()
      });
    }
  },
  DeleteObject: {
    unsupportedHeaders: [...BUCKET_OWNER, ...MFA_AND_LOCK_BYPASS],
    async handle({ c, bucket, key }) {
      return await bucket.delete(key), c.body(null, 204);
    }
  },
  CreateMultipartUpload: {
    unsupportedHeaders: WRITE_UNSUPPORTED,
    validatesWriteHeaders: !0,
    ssec: "write",
    async handle({ c, bucket, bucketId, key }) {
      let storageClass = parseStorageClass(c);
      if (storageClass instanceof Response)
        return storageClass;
      let upload = await bucket.createMultipartUpload(key, {
        httpMetadata: c.req.raw.headers,
        customMetadata: collectCustomMetadata(c),
        storageClass
      });
      return xmlResponse("InitiateMultipartUploadResult", {
        UploadId: upload.uploadId,
        Bucket: bucketId,
        Key: key
      });
    }
  }
}, MULTIPART_OPERATIONS = {
  UploadPart: {
    unsupportedHeaders: [...BUCKET_OWNER, "x-amz-server-side-encryption"],
    ssec: "write",
    async handle({ c, bucket, key, uploadId, params }) {
      let partNumber = parsePartNumber(params);
      if (partNumber instanceof Response)
        return partNumber;
      let body = await verifiedRequestBody(c);
      if (body instanceof Response)
        return body;
      let upload = bucket.resumeMultipartUpload(key, uploadId);
      try {
        let part = await upload.uploadPart(partNumber, body);
        return c.body(null, { headers: { ETag: `"${part.etag}"` } });
      } catch (e) {
        return bindingError(e);
      }
    }
  },
  UploadPartCopy: {
    unsupportedHeaders: [
      ...BUCKET_OWNER,
      ...SOURCE_BUCKET_OWNER,
      ...COPY_SOURCE_CONDITIONALS
    ],
    ssec: "write",
    async handle({ c, bucket, bucketId, key, uploadId, params }) {
      let partNumber = parsePartNumber(params);
      if (partNumber instanceof Response)
        return partNumber;
      let source = parseCopySource(c, bucketId);
      if (source instanceof Response)
        return source;
      let range, rangeHeader = c.req.header("x-amz-copy-source-range");
      if (rangeHeader !== void 0) {
        let match = /^bytes=(\d+)-(\d+)$/.exec(rangeHeader);
        if (match === null)
          return errorResponse(
            400,
            "InvalidArgument",
            `Invalid x-amz-copy-source-range: ${rangeHeader}`
          );
        let offset = Number(match[1]), end = Number(match[2]);
        if (end < offset)
          return errorResponse(
            400,
            "InvalidArgument",
            "x-amz-copy-source-range must be positive."
          );
        range = { offset, length: end - offset + 1 };
      }
      let sourceObject;
      try {
        sourceObject = await source.bucket.get(source.key, { range });
      } catch (e) {
        return bindingError(e);
      }
      if (sourceObject === null)
        return noSuchKey();
      let upload = bucket.resumeMultipartUpload(key, uploadId);
      try {
        let part = await upload.uploadPart(partNumber, sourceObject.body);
        return xmlResponse("CopyPartResult", {
          ETag: `"${part.etag}"`,
          LastModified: (/* @__PURE__ */ new Date()).toISOString()
        });
      } catch (e) {
        return bindingError(e);
      }
    }
  },
  CompleteMultipartUpload: {
    unsupportedHeaders: BUCKET_OWNER,
    async handle({ c, bucket, bucketId, key, uploadId }) {
      let text = await c.req.raw.text();
      if (import_fast_xml_parser2.XMLValidator.validate(text) !== !0)
        return malformedXml();
      let request = xmlParser.parse(text).CompleteMultipartUpload;
      if (request === void 0)
        return malformedXml();
      let parts = [], seenPartNumbers = /* @__PURE__ */ new Set();
      for (let part of coerceArray(request.Part)) {
        let { PartNumber, ETag } = part, partNumber = Number(PartNumber);
        if (!Number.isInteger(partNumber) || typeof ETag != "string")
          return malformedXml();
        if (partNumber < 1 || partNumber > 1e4)
          return errorResponse(
            400,
            "InvalidPart",
            "One or more of the specified parts could not be found."
          );
        if (seenPartNumbers.has(partNumber))
          return errorResponse(
            400,
            "InvalidPart",
            "There was a problem with the multipart upload."
          );
        seenPartNumbers.add(partNumber), parts.push({ partNumber, etag: ETag.replace(/^"|"$/g, "") });
      }
      if (parts.length === 0)
        return malformedXml();
      let upload = bucket.resumeMultipartUpload(key, uploadId);
      try {
        let object = await upload.complete(parts), url = new URL(c.req.url);
        return xmlResponse("CompleteMultipartUploadResult", {
          Bucket: bucketId,
          Key: key,
          ETag: object.httpEtag,
          Location: `${url.origin}${CorePaths.R2_S3}/${bucketId}/${awsUriEncode(key)}`
        });
      } catch (e) {
        let response = bindingError(e);
        return response.status === 500 ? s3Error(NO_SUCH_UPLOAD) : response;
      }
    }
  },
  AbortMultipartUpload: {
    unsupportedHeaders: [],
    async handle({ c, bucket, key, uploadId }) {
      let upload = bucket.resumeMultipartUpload(key, uploadId);
      try {
        await upload.abort();
      } catch (e) {
        let response = bindingError(e);
        return response.status === 500 ? s3Error(NO_SUCH_UPLOAD) : response;
      }
      return c.body(null, 204);
    }
  }
}, BUCKET_OPERATIONS = {
  HeadBucket: {
    unsupportedHeaders: BUCKET_OWNER,
    // The bucket exists, or routing would have 404ed already
    handle: ({ c }) => c.body(null, 200)
  },
  GetBucketLocation: {
    unsupportedHeaders: BUCKET_OWNER,
    // Real R2 reports the bucket's location hint (e.g. ENAM); local
    // buckets have no location
    handle: () => xmlResponse("LocationConstraint", { "#text": "auto" })
  },
  // R2 always encrypts at rest with AES256; there is no per-bucket config
  GetBucketEncryption: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: () => xmlResponse("ServerSideEncryptionConfiguration", {
      Rule: {
        ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" },
        BucketKeyEnabled: !0
      }
    })
  },
  // R2 has no bucket versioning, tagging, object lock, or replication;
  // these responses are identical for every bucket
  GetBucketVersioning: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: () => xmlResponse("VersioningConfiguration", {})
  },
  GetBucketTagging: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: () => errorResponse(404, "NoSuchTagSet", "The TagSet does not exist.")
  },
  GetObjectLockConfiguration: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: () => errorResponse(
      404,
      "ObjectLockConfigurationNotFoundError",
      "Object Lock configuration does not exist for this bucket."
    )
  },
  GetBucketReplication: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: () => errorResponse(
      404,
      "ReplicationConfigurationNotFoundError",
      "The replication configuration was not found."
    )
  },
  ListObjects: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: ({ params, bucket, bucketId }) => listObjects(params, bucket, bucketId, !1)
  },
  ListObjectsV2: {
    unsupportedHeaders: BUCKET_OWNER,
    handle: ({ params, bucket, bucketId }) => listObjects(params, bucket, bucketId, !0)
  },
  DeleteObjects: {
    unsupportedHeaders: [...BUCKET_OWNER, ...MFA_AND_LOCK_BYPASS],
    async handle({ c, bucket }) {
      let body = await c.req.raw.arrayBuffer(), digestError = await verifyContentMD5(c, body);
      if (digestError !== void 0)
        return digestError;
      let text = new TextDecoder().decode(body);
      if (import_fast_xml_parser2.XMLValidator.validate(text) !== !0)
        return malformedXml();
      let request = xmlParser.parse(text).Delete;
      if (request === void 0)
        return malformedXml();
      let keys = [];
      for (let object of coerceArray(request.Object)) {
        let key = object.Key;
        if (typeof key != "string")
          return malformedXml();
        keys.push(key);
      }
      return keys.length === 0 || keys.length > MAX_DELETE_KEYS || request.Quiet !== void 0 && request.Quiet !== "true" && request.Quiet !== "false" ? malformedXml() : (await bucket.delete(keys), xmlResponse("DeleteResult", {
        Deleted: keys.map((key) => ({ Key: key }))
      }));
    }
  }
};

// src/workers/r2/s3/dispatch.worker.ts
async function dispatch(c, key) {
  return stripBodyForHead(c, await dispatchInner(c, key));
}
async function dispatchInner(c, key) {
  let bucketId = c.req.param("bucketId");
  assert4(bucketId !== void 0);
  let credentials = c.env[R2S3Bindings.JSON_CREDENTIALS][bucketId];
  if (credentials === void 0)
    return noSuchBucket();
  let bucket = c.env[`${R2S3Bindings.BUCKET_PREFIX}${bucketId}`];
  assert4(bucket !== void 0);
  let params = new URL(c.req.url).searchParams;
  if (key === void 0 && c.req.method === "POST" && !params.has("delete") && !hasAuthentication(c.req.raw, params))
    return notImplemented(
      "Presigned post requests are not yet implemented not implemented"
    );
  let authError = await verifyRequest(c.req.raw, credentials);
  if (authError !== void 0)
    return authError;
  let detected = detectOperation(c, bucket, bucketId, key, params);
  if (detected instanceof Response)
    return detected;
  let screenError = screenHeaders(c, detected.operation, detected.rules);
  return screenError !== void 0 ? screenError : detected.run();
}
function detectOperation(c, bucket, bucketId, key, params) {
  if (key === void 0) {
    let detected2 = detectBucketOperation(c.req.method, params);
    return detected2 instanceof Response ? detected2 : bind(detected2, BUCKET_OPERATIONS, { c, bucket, bucketId, params });
  }
  let detected = detectObjectOperation(c, params);
  if (detected instanceof Response)
    return detected;
  let context = { c, bucket, bucketId, key, params };
  return typeof detected == "object" ? bind(detected.operation, MULTIPART_OPERATIONS, {
    ...context,
    uploadId: detected.uploadId
  }) : bind(detected, OBJECT_OPERATIONS, context);
}
function bind(operation, table, context) {
  let definition = table[operation];
  return {
    operation,
    rules: definition,
    run: () => definition.handle(context)
  };
}

// src/workers/r2/s3/index.worker.ts
var app = new Hono2().basePath(CorePaths.R2_S3);
app.use(
  cors({
    origin: "*",
    allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE"],
    exposeHeaders: ["*"]
  })
);
app.all("/:bucketId/:key{.+}", (c) => dispatch(c, c.req.param("key")));
app.all("/:bucketId", (c) => dispatch(c, void 0));
app.all("/", (c) => listBuckets(c));
var index_worker_default = app;
export {
  index_worker_default as default
};
//# sourceMappingURL=index.worker.js.map
