[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": ".gitignore",
    "content": "# build output\ndist/\n_worker.bundle\n\n# generated types\n.astro/\n.wrangler/\n\n# dependencies\nnode_modules/\n\n# logs\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\n\n# IDE files\n.idea/\n.vscode/\n\n# environment variables\n.env\n.env.production\n\n# macOS-specific files\n.DS_Store\n\n# others\n*.bak\n*.kate-swap\nwrangler.toml\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "astro.config.ts",
    "content": "import { defineConfig } from \"astro/config\";\n\n// astro integrations\nimport compress from \"astro-compress\";\nimport icon from \"astro-icon\";\n\n// vite plugins\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig({\n    prefetch: true,\n    integrations: [\n        compress(),\n        icon(),\n    ],\n    vite: {\n        css: {\n            preprocessorOptions: {\n                scss: {\n                    api: \"modern-compiler\"\n                }\n            }\n        },\n        plugins: [\n            tailwindcss(),\n        ],\n        // log dropping not enabled by default cuz this project will never be production ready lol\n        // esbuild: {\n        //     drop: [\"console\", \"debugger\"],\n        // },\n    },\n});\n"
  },
  {
    "path": "functions/_middleware.js",
    "content": "async function RequestInfo (context) {\n    const Path = (new URL(context.request.url)).pathname;\n    console.info(\"[Main] Processing request...\")\n    console.info(`[Main] Request type: ${Path}`)\n\n    return await context.next();\n}\n\nasync function PerformanceCounting (context) {\n    const __startTime = performance.now();\n\n    const response = await context.next();\n    \n    console.info(`[PerformanceCounting] we've done this glory, totally wasting ${performance.now() - __startTime}ms.`)\n\n    return response;\n}\n\nexport const onRequest = [RequestInfo, PerformanceCounting];"
  },
  {
    "path": "functions/internal/Converter/getClashMetaConfig.js",
    "content": "import { TrulyAssign } from \"../utils/TrulyAssign\";\nimport { parseYAML } from \"confbox\";\nimport ClashMetaDumper from \"../Dumpers/clash-meta.js\";\n\nconst BasicConfig = {\n    isUDP: true,\n    isSSUoT: false,\n    isInsecure: true,\n    RuleProvider: \"https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini\",\n    RuleProvidersProxy: false,\n    BaseConfig: \"http://localhost:4321/basic-config/mihomo.yaml\",\n    // BaseConfig: \"https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/basic-config/mihomo.yaml\",\n    isForcedRefresh: false\n}\n\n\nimport { RuleProviderReader } from \"../RuleProviderReader/main.js\";\n\nexport async function getClashMetaConfig (\n    Proxies, \n    EdgeSubDB, \n    PassedConfig = {},\n) {\n    const Config = TrulyAssign(BasicConfig, PassedConfig);\n\n    console.log(`[getClashMetaConfig] fetching base config from remote (${Config.BaseConfig})`)\n    const ClashConfig = parseYAML(await fetch(Config.BaseConfig).then(res => res.text()));\n    console.log(\"[getClashMetaConfig] fetched base config\", ClashConfig)\n\n    let RuleProvider = await (new RuleProviderReader(Config.RuleProvider)).Process(EdgeSubDB, Config.isForcedRefresh)\n\n    let Dumper = new ClashMetaDumper(Config.isUDP, Config.isSSUoT, Config.isInsecure)\n    \n    // validate proxies\n    Proxies = Proxies.map(i => {\n        if (Dumper.__validate(i)) {\n            i.Hostname = i.Hostname.replace(/(^\\[|\\]$)/g, \"\");\n            return i;\n        }\n    }).filter(i => !!i);\n    // append proxies\n    ClashConfig.proxies = Proxies.map(i => Dumper[i.__Type](i));\n\n    \n\n    // Append proxy groups.\n    ClashConfig[\"proxy-groups\"] = []\n    for (let i of RuleProvider.ProxyGroup) {\n\n        // get Matched Proxies\n        let MatchedProxies = [];\n        for (let t of i.RegExps) {\n            MatchedProxies = [ ...MatchedProxies, ...Proxies.filter( loc => loc.__Remark.match(new RegExp(t)) ) ]\n        }\n        // unique proxy\n        MatchedProxies = Array.from(new Set(MatchedProxies));\n\n\n\n        // generate proxies list \n        let GroupProxies = [];\n        for (let t of i.GroupSelectors) {\n            GroupProxies.push(t.replace(/^\\[\\]/, \"\"))\n        }\n        for (let t of MatchedProxies) {\n            GroupProxies.push(t.__Remark)\n        }\n        if (MatchedProxies.length + i.GroupSelectors.length === 0) {\n            // add fallback selector if no selector can be added\n            GroupProxies.push(\"DIRECT\")\n            GroupProxies.push(\"REJECT\")\n        }\n\n        //generate proxy group\n        let ProxyGroup = {}\n        ProxyGroup.name = i.name;\n        ProxyGroup.type = i.type;\n        if (i.type === \"url-test\" || i.type === \"load-balance\" || i.type === \"fallback\") {\n            ProxyGroup.url = i.TestConfig.TestURL;\n            ProxyGroup.interval = i.TestConfig.Interval;\n        }\n        if (i.type === \"url-test\") {\n            ProxyGroup.tolerance = i.TestConfig.Tolerance;\n        }\n        ProxyGroup.proxies = GroupProxies;\n\n        // append proxy group to config\n        ClashConfig[\"proxy-groups\"].push(ProxyGroup)\n    }\n\n    // append rule providers\n    ClashConfig[\"rule-providers\"] = {};\n    let RuleProvidersMapping = {}; // { URL: ID }[]\n    for (let i in RuleProvider.RuleProviders) {\n        for (let t in RuleProvider.RuleProviders[i]) {\n            const RuleProviderPayload = RuleProvider.RuleProviders[i][t];\n            const RuleProviderID = `${i}__${t}`;\n            RuleProvidersMapping[RuleProviderPayload] = RuleProviderID;\n            let RuleProviderURL;\n            if (Config.RuleProvidersProxy) {\n                let RuleProviderURLObject = new URL(Config.RuleProvidersProxy);\n                RuleProviderURLObject.pathname = \"/ruleset/proxy\"\n                RuleProviderURLObject.search = \"\"\n                RuleProviderURLObject.searchParams.append(\"target\", RuleProviderPayload)\n                RuleProviderURL = RuleProviderURLObject.toString()\n            } else {\n                RuleProviderURL = RuleProviderPayload;\n            }\n            ClashConfig[\"rule-providers\"][RuleProviderID] = {\n                type: \"http\",\n                behavior: \"classical\",\n                url: RuleProviderURL,\n                format: (RuleProviderPayload.endsWith(\".yaml\") || RuleProviderPayload.endsWith(\".yml\")) ? \"yaml\" : \"text\",\n                interval: 21600\n            }\n        }\n    }\n\n    // Append rule sets;\n    ClashConfig.rules = []\n    for (let i of RuleProvider.Rules) {\n        \n        const rulesetBreakdown = i.split(\",\")\n        const id = rulesetBreakdown[0];\n        let payload = rulesetBreakdown.slice(1).join(\",\");\n        if (payload.startsWith(\"http://\") || payload.startsWith(\"https://\")) {\n            payload = `RULE-SET,${RuleProvidersMapping[payload]}`;\n        }\n        ClashConfig.rules.push(`${payload},${id}`)\n    }\n\n    return ClashConfig;\n}\n"
  },
  {
    "path": "functions/internal/Converter/getSingBoxConfig.ts",
    "content": "import { TrulyAssign } from \"../utils/TrulyAssign\";\nimport SingBoxDumper from \"../Dumpers/sing-box.js\";\nimport { MetaToSingRuleMapping } from \"../data/rule/MetaToSingMapping.ts\";\nimport { MetaToSingLogicalRule } from \"../data/rule/MetaToSingLogicalRule.ts\";\nimport { transformGeoRef } from \"../data/ruleset/transformGeoRef.ts\";\nimport { parseJSON5 } from \"confbox\";\n\nconst BasicConfig = {\n    isUDP: true,\n    isSSUoT: true,\n    isInsecure: true,\n    RuleProvider: \"https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini\",\n    RuleProvidersProxy: true, // this is required\n    BaseConfig: \"https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/basic-config/sing-box.jsonc\",\n    isForcedRefresh: false\n}\n\n\nimport { RuleProviderReader } from \"../RuleProviderReader/main.js\";\nimport mod from \"astro/zod\";\n\nexport async function getSingBoxConfig (\n    Proxies, \n    EdgeSubDB, \n    PassedConfig = {},\n) {\n    const Config = TrulyAssign(BasicConfig, PassedConfig);\n    if (!Config.RuleProvidersProxy) {\n        throw new Error(\"RuleProvidersProxy is required for SingBox config generation.\");\n    }\n\n    console.log(`[getSingBoxConfig] fetching base config from remote (${Config.BaseConfig})`)\n    const SingBoxConfig = parseJSON5(await fetch(Config.BaseConfig).then(res => res.text())) as any;\n    console.log(\"[getSingBoxConfig] fetched base config\", SingBoxConfig)\n\n    // Process OutBounds\n    let Dumper = new SingBoxDumper(Config.isUDP, Config.isSSUoT, Config.isInsecure);\n    // validate proxies\n    Proxies = Proxies.map(i => {\n        if (Dumper.__validate(i)) {\n            return i;\n        }\n    }).filter(i => !!i);\n    // append proxies\n    SingBoxConfig.outbounds = SingBoxConfig.outbounds || [];\n    SingBoxConfig.outbounds = [\n        ...SingBoxConfig.outbounds, \n        ...Proxies.map(i => Dumper[i.__Type](i))\n    ]\n    // check for essential outbounds\n    if (!SingBoxConfig.outbounds.find(i => i.tag === \"DIRECT\")) {\n        SingBoxConfig.outbounds.push({\n            type: \"direct\",\n            tag: \"DIRECT\"\n        })\n    }\n    if (!SingBoxConfig.outbounds.find(i => i.tag === \"REJECT\")) {\n        SingBoxConfig.outbounds.push({\n            type: \"block\",\n            tag: \"REJECT\"\n        })\n    }\n\n    // proxy clash external ui archive\n    if (SingBoxConfig.experimental.clash_api.external_ui_download_url) {\n        let ClashWebUIURLObject = new URL(Config.RuleProvidersProxy);\n            ClashWebUIURLObject.pathname = \"/ruleset/proxy\";\n            ClashWebUIURLObject.search = \"\";\n            ClashWebUIURLObject.searchParams.append(\"target\", SingBoxConfig.experimental.clash_api.external_ui_download_url);\n        SingBoxConfig.experimental.clash_api.external_ui_download_url = ClashWebUIURLObject.toString();\n    }\n\n\n    // RULES!;\n    let RuleProvider = await (new RuleProviderReader(Config.RuleProvider)).Process(EdgeSubDB, Config.isForcedRefresh)\n    console.log(RuleProvider)\n\n    // Append proxy groups.\n    // SingBoxConfig.outbounds = []\n    // GLOBAL selector\n    SingBoxConfig.outbounds.push({\n        tag: \"GLOBAL\",\n        type: \"selector\",\n        outbounds: [ \"DIRECT\", \"REJECT\", ...Proxies.map(i => i.__Remark)]\n    })\n    // Respect RuleProvider\n    for (let i of RuleProvider.ProxyGroup) {\n\n        // get Matched Proxies\n        let MatchedProxies = [];\n        for (let t of i.RegExps) {\n            MatchedProxies = [ ...MatchedProxies, ...Proxies.filter( loc => loc.__Remark.match(new RegExp(t)) ) ]\n        }\n        // unique proxy\n        MatchedProxies = Array.from(new Set(MatchedProxies));\n\n\n        // generate proxies list \n        let GroupProxies = [];\n        for (let t of i.GroupSelectors) {\n            GroupProxies.push(t.replace(/^\\[\\]/, \"\"))\n        }\n        for (let t of MatchedProxies) {\n            GroupProxies.push(t.__Remark)\n        }\n        if (MatchedProxies.length + i.GroupSelectors.length === 0) {\n            // add fallback selector if no selector can be added\n            GroupProxies.push(\"DIRECT\")\n            GroupProxies.push(\"REJECT\")\n        }\n\n        //generate proxy group\n        let ProxyGroup: {\n            type: string,\n            tag: string,\n            outbounds: string[],\n            url?: string | URL, // for url-test onlly\n            interval?: string, // for url-test onlly\n            tolerance?: string, // for url-test onlly\n        } = {\n            tag: i.name,\n            type: \"\", // placeholder... change it later\n            outbounds: GroupProxies\n        }\n\n\n        if (i.type === \"select\") {\n            ProxyGroup.type = \"selector\"\n        } else if (i.type === \"url-test\" || i.type === \"load-balance\" || i.type === \"fallback\") {\n            ProxyGroup.type = \"urltest\"\n\n            ProxyGroup.url = i.TestConfig.TestURL;\n            ProxyGroup.interval = `${i.TestConfig.Interval}s`;\n\n            if (i.type === \"url-test\") {\n                ProxyGroup.tolerance = i.TestConfig.Tolerance;\n            }\n            if (i.type === \"load-balance\" || i.type === \"fallback\") {\n                console.log(`[getSingBoxConfig] ${i.name} fallback to urltest`)\n            }\n        }\n\n        // append proxy group to config\n        SingBoxConfig.outbounds.push(ProxyGroup)\n    }\n\n    // Append rule-sets\n    // SingBoxConfig.route.rule_set = [];\n    let RuleProvidersMapping = {}; // { URL: ID }[]\n    for (let i in RuleProvider.RuleProviders) {\n        for (let t in RuleProvider.RuleProviders[i]) {\n            const RuleProviderPayload = RuleProvider.RuleProviders[i][t];\n            const RuleProviderID = `${i}__${t}`;\n            RuleProvidersMapping[RuleProviderPayload] = RuleProviderID;\n\n            // construct RuleProviderURL\n            let RuleProviderURLObject = new URL(Config.RuleProvidersProxy);\n                RuleProviderURLObject.pathname = \"/ruleset/preprocessor/sing-box\"\n                RuleProviderURLObject.search = \"\"\n                RuleProviderURLObject.searchParams.append(\"target\", RuleProviderPayload)\n            const RuleProviderURL = RuleProviderURLObject.toString()\n            SingBoxConfig.route.rule_set.push({\n                type: \"remote\",\n                tag: RuleProviderID,\n                format: \"source\",\n                url: RuleProviderURL,\n                download_detour: \"DIRECT\"\n            })\n        }\n    }\n\n    // Append rules\n    // SingBoxConfig.route.rules = []\n    let FinalOutboundID;\n    for (let i of RuleProvider.Rules) {\n        const rulesetBreakdown = i.split(\",\").map(i => i.trim())\n        const outboundID = rulesetBreakdown[0];\n        // parse in simple rules <OUTBOUND>,<TYPE>,<PAYLOAD>\n        const type = MetaToSingRuleMapping[rulesetBreakdown[1]] as string;\n        const payload = rulesetBreakdown.slice(2).join(\",\") as string;\n        \n        // parse in rule-set route rules\n        const RuleSetPayload = rulesetBreakdown.slice(1).join(\",\");\n        if (RuleSetPayload.startsWith(\"http://\") || RuleSetPayload.startsWith(\"https://\")) {\n            SingBoxConfig.route.rules.push({\n                rule_set: RuleProvidersMapping[RuleSetPayload],\n                action: \"route\",\n                outbound: outboundID\n            });\n            continue;\n        }\n\n        // handle Match Type Rule (Final Ooutbound)\n        if (rulesetBreakdown[1] === \"MATCH\") {\n            FinalOutboundID = outboundID;\n            continue\n        }\n\n        // handle GEOIP and GEOSITE\n        if (type === \"geoip\" || type === \"geosite\") {\n            const { headlessRule, headlessRuleSet } = transformGeoRef(type, payload, Config.RuleProvidersProxy);\n\n            SingBoxConfig.route.rules.push({\n                ...headlessRule,\n                action: \"route\",\n                outbound: outboundID\n            });\n\n            // if we cant find rule set with same tag (ie append before), \n            if (headlessRuleSet && !(SingBoxConfig.route.rule_set.find(i => i.tag === headlessRuleSet.tag))) { \n                // append rule-set\n                SingBoxConfig.route.rule_set.push({\n                    ...headlessRuleSet,\n                    download_detour: \"DIRECT\"\n                })\n            }\n            continue;\n        }\n\n        // handle the types that payload need to be number\n        if (type === \"source_port\" || type === \"port\") {\n            let numPayload = Number(payload);\n            if (isNaN(numPayload)) {\n                console.warn(`[getSingBoxConfig] invalid port number: ${payload}, skiping rule ${i}`);\n                continue;\n            }\n            SingBoxConfig.route.rules.push({\n                [type]: numPayload,\n                action: \"route\",\n                outbound: outboundID\n            });\n            continue;\n        }\n\n        // handle AND | OR Logic rules\n        if (type === \"and\" || type === \"or\") {\n            let { headlessRule, headlessRuleSet } = MetaToSingLogicalRule(type, payload, Config.RuleProvidersProxy);\n            headlessRuleSet = headlessRuleSet.filter(i => !!i && !SingBoxConfig.route.rule_set.find(t => t.tag === i.tag));\n\n            SingBoxConfig.route.rule_set.push(...headlessRuleSet);\n            SingBoxConfig.route.rules.push({\n                ...headlessRule,\n                action: \"route\",\n                outbound: outboundID\n            });\n            continue;\n        }\n\n        // any other route rules else should works... not sure \n        SingBoxConfig.route.rules.push({\n            [type]: payload,\n            action: \"route\",\n            outbound: outboundID\n        });\n    }\n    // Append Final Outbound\n    SingBoxConfig.route.final = FinalOutboundID;\n\n    return SingBoxConfig;\n}\n"
  },
  {
    "path": "functions/internal/Dumpers/clash-meta.ts",
    "content": "import type { RealityConfig, TransportGRPC, TransportH2, TransportHTTP, TransportWS } from \"../types/ClashMetaConfig\";\n\nexport default class Dumper {\n    config = {\n        UDP: true,\n        SSUoT: true,\n        SkipCertVerify: true,\n        ClientFingerprint: \"chrome\"\n    }\n    constructor (\n        UDP = true,\n        SSUoT = true,\n        SkipCertVerify = true,\n        ClientFingerprint = \"chrome\"\n    ) {\n        this.config.UDP = UDP;\n        this.config.SSUoT = SSUoT;\n        this.config.SkipCertVerify = SkipCertVerify;\n        this.config.ClientFingerprint = ClientFingerprint;\n\n        return this;\n    }\n\n    // __appendCommonField () {}\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.__Type in this)) {\n            console.warn(`[Dumper: Clash Meta] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`)\n            return false;\n        }\n        return true;\n    }\n\n    http (HTTP) {\n        return {\n            name: HTTP.__Remark,\n            type: HTTP.__Type,\n            server: HTTP.Hostname,\n            port: HTTP.Port,\n            username: HTTP.Auth.username,\n            password: HTTP.Auth.password,\n            \"skip-cert-verify\": this.config.SkipCertVerify\n        }\n    }\n    socks5 (SOCKS5) {\n        return {\n            name: SOCKS5.__Remark,\n            type: SOCKS5.__Type,\n            server: SOCKS5.Hostname,\n            port: SOCKS5.Port,\n            username: SOCKS5.Auth.username,\n            password: SOCKS5.Auth.password,\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n            udp: this.config.UDP\n        }\n    }\n\n    hysteria (hyObject) {\n        return {\n            name: hyObject.__Remark,\n            type: hyObject.__Type,\n            server: hyObject.Hostname,\n            port: hyObject.Port,\n            ports: hyObject.Query.mport,\n            \"auth_str\": hyObject.Query.auth,\n            \"auth-str\": hyObject.Query.auth,\n            alpn: hyObject.Query.alpn ? [ hyObject.Query.alpn ] : undefined,\n            up: hyObject.Query.upmbps,\n            down: hyObject.Query.downmbps,\n            sni: hyObject.Query.peer,\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n            protocol: this.config.UDP ? \"UDP\" : \"wechat-video\",\n        }\n    }\n    hysteria2 (hy2Object) {\n        return {\n            name: hy2Object.__Remark,\n            type: hy2Object.__Type,\n            server: hy2Object.Hostname,\n            port: hy2Object.Port,\n            ports: hy2Object.Query.mport,\n            password: hy2Object.Auth,\n            sni: hy2Object.Query.sni,\n            obfs: hy2Object.Query.obfs,\n            \"obfs-password\": hy2Object.Query[\"obfs-password\"],\n            \"client-fingerprint\": this.config.ClientFingerprint,\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n            udp: this.config.UDP,\n        }\n    }\n    hy2 = this.hysteria2;\n\n    tuic (TUIC) {\n        return {\n            name: TUIC.__Remark,\n            type: TUIC.__Type,\n            server: TUIC.Hostname,\n            port: TUIC.Port,\n            uuid: TUIC.Auth.uuid,\n            password: TUIC.Auth.password,\n            alpn: TUIC.Query.alpn ? [ TUIC.Query.alpn ] : undefined,\n            \"disable-sni\": !!parseInt(TUIC.Query.disable_sni),\n            \"udp-relay-mode\": TUIC.Query.udp_relay_mode,\n            \"congestion-controller\": TUIC.Query.congestion_control,\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n            sni: TUIC.Query.sni,\n            // max-udp-relay-packet-size: 1500,\n            // fast-open: true,\n            // max-open-streams: 20,\n        }\n    }\n\n    vless (VLESS) {\n        return {\n            name: VLESS.__Remark,\n            type: VLESS.__Type,\n            server: VLESS.Hostname,\n            port: VLESS.Port,\n            uuid: VLESS.Auth,\n            flow: VLESS.Query.flow,\n            \"packet-encoding\": VLESS.Query.packetEncoding,\n            tls: !!VLESS.Query.sni,\n            servername: VLESS.Query.sni,\n            alpn: VLESS.Query.alpn ? [ VLESS.Query.alpn ] : undefined,\n            \"client-fingerprint\": VLESS.Query.fp,\n            network: VLESS.Query.type,\n\n            \"reality-opts\": __genRealityConfig(VLESS),\n\n            // transport layer config\n            \"ws-opts\": __genTransportWS(VLESS),\n            \"grpc-opts\": __genTransportGRPC(VLESS),\n            \"h2-opts\": __genTransportH2(VLESS),\n            \"http-opts\": __genTransportHTTP(VLESS),\n\n            udp: this.config.UDP,\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n        }\n    }\n    vmess (VMESS) {\n        return {\n            name: VMESS.__Remark,\n            type: VMESS.__Type,\n            server: VMESS.Hostname,\n            port: VMESS.Port,    \n            uuid: VMESS.Auth,\n            alterId: VMESS.Query.aid,\n            cipher: VMESS.Query.scy ? VMESS.Query.scy : \"auto\",\n            network: VMESS.Query.net,\n\n            protocol: VMESS.Query.type,\n            \n            \"client-fingerprint\": VMESS.Query.fp,\n\n            alpn: [\"h2\", \"http/1.1\"],\n\n            // tls\n            tls: VMESS.Query.tls === \"tls\",\n            servername: VMESS.Query.sni,\n            // \"reality-opts\": {\n            //     \"public-key\": \"xxxx\",\n            //     \"short-id\": \"xxxx\",\n            // },\n\n            // transport layer config\n            \"ws-opts\": __genTransportWS(VMESS),\n            \"grpc-opts\": __genTransportGRPC(VMESS),\n            \"h2-opts\": __genTransportH2(VMESS),\n            \"http-opts\": __genTransportHTTP(VMESS),\n\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n            udp: this.config.UDP,\n\n            // packet-encoding\n            // global-padding\n            // authenticated-length\n        }\n    }\n    vmess__shadowsocks_type (VMESS) {\n        return {\n            name: VMESS.__Remark,\n            type: \"vmess\",\n            server: VMESS.Hostname,\n            port: VMESS.Port,    \n            uuid: VMESS.Auth,\n            alterId: parseInt(VMESS.Query.alterId),\n            cipher: \"auto\",\n            network: VMESS.Query.obfs,\n            \n\n            // tls\n            tls: VMESS.Query.tls === \"1\",\n            servername: VMESS.Query.peer,\n\n            // transport layer config\n            \"ws-opts\": __genTransportWS(VMESS),\n            \"grpc-opts\": __genTransportGRPC(VMESS),\n            \"http-opts\": __genTransportHTTP(VMESS),\n            \"h2-opts\": __genTransportH2(VMESS),\n\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n            udp: this.config.UDP,\n\n            // packet-encoding\n            // global-padding\n            // authenticated-length\n        }\n    }\n\n    ss (SS) {\n        return {\n            name: SS.__Remark,\n            type: \"ss\",\n            server: SS.Hostname,\n            port: SS.Port,\n            cipher: SS.Auth.cipher,\n            password: SS.Auth.password,\n  \n            udp: this.config.UDP,\n            \"udp-over-tcp\": this.config.SSUoT,\n            \"udp-over-tcp-version\": this.config.SSUoT ? 2 : undefined,\n        }\n    }\n    trojan (TROJAN) {\n        return {\n            name: TROJAN.__Remark,\n            type: \"trojan\",\n            server: TROJAN.Hostname,\n            port: TROJAN.Port,\n            password: TROJAN.Auth,\n\n            network: TROJAN.Query.type ? TROJAN.Query.type : \"tcp\",\n            sni: TROJAN.Query.sni,\n            alpn: [\"h2\", \"http/1.1\"],\n\n            \"reality-opts\": __genRealityConfig(TROJAN),\n            \n            // transport layer config\n            \"ws-opts\": __genTransportWS(TROJAN),\n            \"grpc-opts\": __genTransportGRPC(TROJAN),\n            \"http-opts\": __genTransportHTTP(TROJAN),\n\n            \"client-fingerprint\": TROJAN.Query.fp,\n\n            udp: this.config.UDP,\n            \"skip-cert-verify\": this.config.SkipCertVerify,\n        }\n    }\n}\n\n\nfunction __genRealityConfig (Obj) : RealityConfig | undefined {\n    return Obj.Query.security === \"reality\" ? {\n        \"public-key\": Obj.Query.pbk ? Obj.Query.pbk : undefined,\n        \"short-id\": Obj.Query.sid ? Obj.Query.sid : undefined\n    } : undefined\n}\n\n\nfunction __genTransportWS (Obj) : TransportWS | undefined {\n    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;\n\n    if (PassedTransportType !== \"ws\") {\n        return undefined;\n    }\n\n    const host = Obj.Query.host || Obj.Query.obfsParam;\n    const PathObj = new URL(`path:${Obj.Query.path}`)\n    const ParsedMaxEarlyData = parseInt(Obj.Query.ed || PathObj.searchParams.get(\"ed\"));\n    \n    const MaxEarlyData = isNaN(ParsedMaxEarlyData) ? undefined : ParsedMaxEarlyData;\n    const EarlyDataHeaderName = Obj.Query.eh || (MaxEarlyData ? \"Sec-WebSocket-Protocol\" : undefined)\n\n    return {\n        path: PathObj.pathname,\n        headers: host ? { host } : undefined,\n        \"max-early-data\": MaxEarlyData,\n        \"early-data-header-name\": EarlyDataHeaderName,\n        //\"v2ray-http-upgrade\"?: unknown,\n        //\"v2ray-http-upgrade-fast-open\"?: unknown,\n    }\n}\nfunction __genTransportGRPC (Obj) : TransportGRPC | undefined {\n    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;\n    return PassedTransportType === \"grpc\" ? {\n        \"grpc-service-name\": Obj.Query.serviceName || Obj.Query.path\n    } : undefined;\n}\n\nfunction __genTransportHTTP (Obj) : TransportHTTP | undefined {\n    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;\n    const host = Obj.Query.host || Obj.Query.obfsParam;\n    return PassedTransportType === \"http\" ? {\n        method: Obj.Query.method,\n        path: Obj.Query.path ? [ Obj.Query.path ] : undefined,\n        headers: host ? { host } : undefined,\n    } : undefined;\n}\nfunction __genTransportH2 (Obj) : TransportH2 | undefined {\n    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;\n    return PassedTransportType === \"h2\" ? {\n        method: Obj.Query.method,\n        path: Obj.Query.path,\n    } : undefined;\n}\n"
  },
  {
    "path": "functions/internal/Dumpers/share-link.js",
    "content": "export class ShareLinkDumper {\n    constructor () {\n        return true;\n    }\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.__Type in this)) {\n            console.warn(`[Dumper: Share Link] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`)\n            return false\n        }\n        return true;\n    }\n\n    http (HTTP) {\n        return `http://${HTTP.Auth.username}:${HTTP.Auth.password}@${HTTP.Hostname}:${HTTP.Port}/#${encodeURIComponent(HTTP.__Remark)}`;\n    }\n    socks5 (SOCKS5) {\n        return `socks5://${SOCKS5.Auth.username}:${SOCKS5.Auth.password}@${SOCKS5.Hostname}:${SOCKS5.Port}/#${encodeURIComponent(SOCKS5.__Remark)}`;\n    }\n\n    hysteria (Obj) {\n        return `hysteria://${Obj.Hostname}:${Obj.Port}/${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`\n    }\n    hysteria2 (Obj) {\n        return `hysteria2://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`\n    }\n    hy2 = this.hysteria2;\n\n    tuic (Obj) {\n        return `tuic://${Obj.Auth.uuid}:${Obj.Auth.password}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`\n    }\n\n    vless (Obj) {\n        return `vless://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`\n    }\n    vmess (Obj) {\n        let VMESSObj = {\n            ps: unescape(encodeURIComponent(Obj.__Remark)) ,\n            add: Obj.Hostname,\n            port: Obj.Port,\n            id: Obj.Auth,\n            ...Obj.Query,\n        }\n\n        return `vmess://${btoa(JSON.stringify(VMESSObj))}`\n    }\n    vmess__shadowsocks_type (Obj) {\n        let VMESSObj = {\n            ps: unescape(encodeURIComponent(Obj.__Remark)) ,\n            add: Obj.Hostname,\n            port: Obj.Port,\n            id: Obj.Auth,\n            //...Obj.Query,\n            aid: Obj.Query.alterId,\n            scy: \"auto\",\n            net: Obj.Query.obfs,\n            tls: Obj.Query.tls === \"1\" ? \"tls\" : undefined,\n            sni: Obj.Query.peer,\n            host: Obj.Query.obfsParam,\n            path: Obj.Query.path\n        }\n        return `vmess://${btoa(JSON.stringify(VMESSObj))}`\n    }\n\n    ss (Obj) {\n        return `ss://${encodeURIComponent(btoa(`${Obj.Auth.cipher}:${Obj.Auth.password}`))}@${Obj.Hostname}:${Obj.Port}/#${encodeURIComponent(Obj.__Remark)}`\n    }\n    trojan (Obj) {\n        return `trojan://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`\n    }\n}\n\nfunction URLQueryWrapper (Obj) {\n    let Childs = [];\n    for (let i in Obj) {\n        let value = Obj[i];\n        if (value) {\n            Childs.push(`${i}=${encodeURIComponent(Obj[i])}`)\n        }\n    }\n    return Childs.join(\"&\");\n}\n"
  },
  {
    "path": "functions/internal/Dumpers/sing-box.js",
    "content": "export default class Dumper {\n    config = {}\n    constructor (\n        UDP = true,\n        SSUoT = false,\n        SkipCertVerify = true\n    ) {\n        this.config.UDP = UDP;\n        this.config.SSUoT = SSUoT;\n        this.config.SkipCertVerify = SkipCertVerify;\n\n        return true;\n    }\n\n    // __appendCommonField () {}\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.__Type in this)) {\n            console.warn(`[Dumper: Sing Box] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`)\n            return false;\n        }\n        if (ProxyObject.__Type === \"vmess__shadowsocks_type\" && ProxyObject.Query.obfs === \"none\") {\n            console.warn(`[Dumper: Sing Box] [WARN] ${ProxyObject.__Type} TCP-Transport is not supported by sing-box, ignoring...`)\n            return false;\n        }\n        return true;\n    }\n\n    http (HTTP) {\n        return {\n            tag: HTTP.__Remark,\n            type: \"http\",\n          \n            server: HTTP.Hostname,\n            server_port: HTTP.Port,\n            username: HTTP.Auth.username,\n            password: HTTP.Auth.password,\n            path: \"/\",\n            headers: {},\n            tls: {\n                insecure: this.config.SkipCertVerify\n            },\n        }\n    }\n    socks5 (SOCKS5) {\n        return {\n            tag: SOCKS5.__Remark,\n            type: \"socks\",\n            server: SOCKS5.Hostname,\n            server_port: SOCKS5.Port,\n            version: \"5\",\n            username: SOCKS5.Auth.username,\n            password: SOCKS5.Auth.password,\n            //udp_over_tcp: this.config.UDP ? \"udp\" : \"tcp\"\n        }\n    }\n\n    hysteria (hyObject) {\n        return {\n            type: \"hysteria\",\n            tag: hyObject.__Remark,\n          \n            server: hyObject.Hostname,\n            server_port: hyObject.Port,\n\n            server_ports: hyObject.Query.mport ? hyObject.Query.mport.replace(/\\-/g, \":\").split(\",\") : undefined,\n            up_mbps: parseInt(hyObject.Query.upmbps) || 250,\n            down_mbps: parseInt(hyObject.Query.downmbps) || 500,\n            obfs: hyObject.Query.obfsParam,\n            auth_str: hyObject.Query.auth,\n            \n            tls: {\n                enabled: true,\n                server_name: hyObject.Query.peer,\n                insecure: this.config.SkipCertVerify\n            },\n        }\n    }\n    hysteria2 (hy2Object) {\n        return {\n            type: \"hysteria2\",\n            tag: hy2Object.__Remark,\n          \n            server: hy2Object.Hostname,\n            server_port: hy2Object.Port,\n\n            server_ports: hy2Object.Query.mport ? hy2Object.Query.mport.replace(/\\-/g, \":\").split(\",\") : undefined,\n            up_mbps: parseInt(hy2Object.Query.upmbps) || 250,\n            down_mbps: parseInt(hy2Object.Query.downmbps) || 500,\n            obfs: (hy2Object.Query.obfs && hy2Object.Query[\"obfs-password\"] ) ? {\n                type: hy2Object.Query.obfs,\n                password: hy2Object.Query[\"obfs-password\"],\n            } : undefined,\n            password: hy2Object.Auth,\n            \n            tls: {\n                enabled: true,\n                server_name: hy2Object.Query.sni,\n                insecure: this.config.SkipCertVerify,\n                alpn: [\n                  \"h3\"\n                ]\n            },\n        }\n    }\n    hy2 = this.hysteria2;\n\n    tuic (TUIC) {\n        return {\n            type: \"tuic\",\n            tag: TUIC.__Remark,\n          \n            server: TUIC.Hostname,\n            server_port: TUIC.Port,\n            uuid: TUIC.Auth.uuid,\n            password: TUIC.Auth.password,\n\n            udp_relay_mode: TUIC.Query.udp_relay_mode,\n\n            congestion_control: TUIC.Query.congestion_control,\n\n            heartbeat: \"10s\",\n            tls: {\n                enabled: true,\n                disable_sni: !!parseInt(TUIC.Query.disable_sni),\n                alpn: TUIC.Query.alpn ? [ TUIC.Query.alpn ] : undefined,\n                insecure: this.config.SkipCertVerify,\n                server_name: TUIC.Query.sni,\n            }\n        }\n    }\n\n    vless (VLESS) {\n        return {\n            type: \"vless\",\n            tag: VLESS.__Remark,\n          \n            server: VLESS.Hostname,\n            server_port: VLESS.Port,\n            uuid: VLESS.Auth,\n            flow: VLESS.Query.flow,\n            packet_encoding: VLESS.Query.packetEncoding,\n            tls: !!VLESS.Query.sni ? {\n                enabled: true,\n                server_name: VLESS.Query.sni,\n                insecure: this.config.SkipCertVerify,\n                alpn: VLESS.Query.alpn ? [ VLESS.Query.alpn ] : undefined,\n\n                utls: {\n                    enabled: !!VLESS.Query.fp,\n                    fingerprint: VLESS.Query.fp\n                },\n                reality: __genRealityConfig(VLESS),\n            } : undefined,\n            //\"multiplex: {},\n            transport: __genTransportConfig(VLESS)\n\n        }\n    }\n    vmess__shadowsocks_type (VMess) {\n\n        let URITransportType = URIObject.Query.obfs;\n        const PathObject = new URL(`path:${URIObject.Query.path}`);\n\n        return {\n            type: \"vmess\",\n            tag: VMess.__Remark,\n            server: VMess.Hostname,\n            server_port: VMess.Port,\n            uuid: VMess.Auth,\n            security: \"auto\",\n            alter_id: parseInt(VMess.Query.alterId),\n\n            tls: VMess.Query.sni === \"1\" ? {\n                enabled: true,\n                server_name: VMess.Query.peer,\n                insecure: this.config.SkipCertVerify,\n            } : undefined,\n            //\"multiplex: {},\n            transport: {\n                type: URITransportType,\n\n                // http\n                headers: { \n                    Host: \n                        (URITransportType !== \"quic\" && URITransportType !== \"grpc\")\n                        ? URIObject.Query.obfsParam\n                        : undefined,\n                },\n                path: URITransportType !== \"grpc\" ? PathObject.path : undefined,\n\n                // max early data\n                early_data_header_name: PathObject.searchParams.has(\"ed\") ? \"Sec-WebSocket-Protocol\" : undefined,\n                max_early_data: PathObject.searchParams.has(\"ed\") ? parseInt(PathObject.searchParams.get(\"ed\")) : undefined,\n\n                // grpc\n                service_name: URITransportType === \"grpc\" ? ( URIObject.Query.path ) : undefined,\n            }\n        }\n    }\n    vmess (VMESS) {\n        return {\n            type: \"vmess\",\n            tag: VMESS.__Remark,\n          \n            server: VMESS.Hostname,\n            server_port: VMESS.Port,\n            uuid: VMESS.Auth,\n            security: VMESS.Query.scy ? VMESS.Query.scy : \"auto\",\n            alter_id: VMESS.Query.aid,\n            // global_padding: false, //??\n            // authenticated_length: true, //??\n            tls: (VMESS.Query.tls === \"tls\") ? {\n                enabled: true,\n                server_name: VMESS.Query.sni,\n                insecure: this.config.SkipCertVerify,\n                alpn: [\"h2\", \"http/1.1\"],\n                utls: {\n                    enabled: !!VMESS.Query.fp,\n                    fingerprint: VMESS.Query.fp\n                },\n                reality: __genRealityConfig(VMESS),\n            } : undefined,\n            transport: __genTransportConfig(VMESS)\n        }\n    }\n\n    ss (SS) {\n        return {\n            type: \"shadowsocks\",\n            tag: SS.__Remark,\n          \n            server: SS.Hostname,\n            server_port: SS.Port,\n            method: SS.Auth.cipher,\n            password: SS.Auth.password,\n            udp_over_tcp: this.config.SSUoT ? {\n                enabled: true,\n                version: 2\n            } : false,\n        }\n    }\n    trojan (TROJAN) {\n        return {\n\n            type: \"trojan\",\n            tag: TROJAN.__Remark,\n          \n            server: TROJAN.Hostname,\n            server_port: TROJAN.Port,\n            password: TROJAN.Auth,\n            network: TROJAN.Query.type ? TROJAN.Query.type : \"tcp\",\n            tls: !!TROJAN.Query.sni ? {\n                enabled: true,\n                server_name: TROJAN.Query.sni,\n                alpn: [\"h2\", \"http/1.1\"],\n                insecure: this.config.SkipCertVerify,\n                utls: {\n                    enabled: !!TROJAN.Query.fp,\n                    fingerprint: TROJAN.Query.fp\n                },\n                reality: __genRealityConfig(TROJAN),\n            } : undefined,\n            transport: __genTransportConfig(TROJAN)\n\n        }\n    }\n}\nfunction __genRealityConfig (URIObject) {\n    return (URIObject.Query.security === \"reality\") ? {\n        enabled: true,\n        public_key: URIObject.Query.pbk || undefined,\n        short_id: URIObject.Query.sid || undefined\n    } : undefined;\n}\nfunction __genTransportConfig (URIObject) {\n    const URITransportType = URIObject.Query.net || URIObject.Query.type;\n\n    const PathObject = new URL(`path:${URIObject.Query.path}`);\n    return (\n        URITransportType === \"http\" ||\n        URITransportType === \"ws\" ||\n        URITransportType === \"grpc\" ||\n        URITransportType === \"quic\" ||\n        URITransportType === \"httpupgrade\"\n    ) ? {\n        type: URITransportType,\n\n        // http\n        headers: { \n            Host: \n                (URITransportType !== \"quic\")\n                 ? URIObject.Query.host\n                 : undefined,\n        },\n        path: PathObject.pathname || \"\",\n        method: URIObject.Query.method,\n\n        // max early data\n        early_data_header_name: PathObject.searchParams.has(\"ed\") ? \"Sec-WebSocket-Protocol\" : undefined,\n        max_early_data: PathObject.searchParams.has(\"ed\") ? parseInt(PathObject.searchParams.get(\"ed\")) : undefined,\n\n        // grpc\n        service_name: URITransportType === \"grpc\" ? ( URIObject.Query.serviceName || URIObject.Query.path ) : undefined,\n    } : undefined;\n}"
  },
  {
    "path": "functions/internal/Parsers/clash-meta.js",
    "content": "export class ClashMetaParser {\n    constructor () {}\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.type in this)) {\n            console.warn(`[Parser: Clash Meta] [WARN] ${ProxyObject.__Type} is not supported to parse, ignoring...`)\n            return false;\n        }\n        return true;\n    }\n\n    http (Obj) {\n        return {\n            __Type: \"http\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: {\n                username: Obj.username,\n                password: Obj.password\n            }\n        }\n    }\n    socks5 (Obj) {\n        return {\n            __Type: \"socks5\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: {\n                username: Obj.username,\n                password: Obj.password\n            }\n        }\n    }\n    \n    hysteria (Obj) {\n        return {\n            __Type: \"hysteria\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Query: {\n                auth: (Obj[\"auth_str\"] || Obj[\"auth-str\"]),\n                alpn: Obj.alpn ? Obj.alpn.join(\",\") : undefined,\n                upmbps: Obj.up,\n                downmbps: Obj.down,\n                peer: Obj.sni,\n                mport: Obj.ports,\n            }\n        }\n    }\n    hysteria2 (Obj) {\n        return {\n            __Type: \"hysteria2\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: Obj.auth || Obj.password,\n            Query: {\n                objs: Obj.obfs,\n                \"obfs-password\": Obj[\"obfs-password\"],\n                insecure: Obj[\"skip-cert-verify\"] ? 1 : 0,\n                mport: Obj.ports,\n            }\n        }\n    }\n    hy2 = this.hysteria2;\n\n    tuic (Obj) {\n        return {\n            __Type: \"tuic\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: { uuid: Obj.uuid, password: Obj.password },\n            Query: {\n                alpn: Obj.alpn ? Obj.alpn.join(\",\") : undefined,\n                disable_sni: Obj[\"disable-sni\"],\n                udp_relay_mode: Obj[\"udp-relay-mode\"],\n                congestion_control: Obj[\"congestion-controller\"],\n                sni: Obj.sni,\n            }\n        }\n    }\n\n\n    vless (Obj) {\n        return {\n            __Type: \"vless\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: Obj.uuid,\n            Query: {\n                flow: Obj.flow,\n                packetEncoding: Obj[\"packet-encoding\"],\n                sni: Obj.servername,\n                alpn: Obj.alpn ? Obj.alpn.join(\",\") : undefined,\n                fp: Obj[\"client-fingerprint\"],\n                type: Obj.network,\n\n\n                // reality\n                security: !!Obj[\"reality-opts\"] ? \"reality\": undefined,\n                pbk: (Obj[\"reality-opts\"] || {})[\"public-key\"],\n                sid: (Obj[\"reality-opts\"] || {})[\"short-id\"],\n\n                \n                // transport layer config\n                \n                // - ws\n                ed: Obj[\"max-early-data\"],\n                eh: Obj[\"early-data-header-name\"],\n\n                // - grpc\n                serviceName: Obj[\"grpc-service-name\"],\n\n                // - http\n                method: Obj.method,\n\n                // - http & ws & h2\n                path: Obj[\"ws-path\"] || Obj.path,\n                host: Obj.host || (Obj[\"ws-headers\"] || Obj.headers || {}).Host,\n            }\n        }\n    }\n    vmess (Obj) {\n        return {\n            __Type: \"vmess\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: Obj.uuid,\n            Query: {\n                aid: Obj.alterId,\n                cipher: Obj.cipher,\n                net: Obj.network,\n                type: Obj.protocol,\n                fp: Obj[\"client-fingerprint\"],\n                alpn: Obj.alpn ? Obj.alpn.join(\",\") : undefined,\n                tls: Obj.tls ? \"tls\" : undefined,\n                sni: Obj.servername,\n\n                // transport layer config\n                // - http & ws & h2 \n                host: (Obj[\"ws-headers\"] || Obj.headers || {}).Host,\n                // - http & ws & h2 & grpc\n                path: \n                    Obj[\"ws-path\"] || \n                    ( Obj[\"ws-opts\"] || Obj[\"h2-opts\"] || {} ).path || \n                    ( (Obj[\"http-opts\"] || {}).path || [] )[0] || \n                    Obj[\"grpc-service-name\"] ||\n                    undefined,\n\n            }\n        }\n    }\n\n    ss (Obj) {\n        return {\n            __Type: \"ss\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: { cipher: Obj.cipher, password: Obj.password },\n        }\n    }\n\n    trojan (Obj) {\n        return {\n            __Type: \"trojan\",\n            __Remark: Obj.name,\n            Hostname: Obj.server,\n            Port: Obj.port,\n            Auth: Obj.password,\n            Query: {\n                type: Obj.network,\n                sni: Obj.sni,\n\n                // reality\n                security: !!Obj[\"reality-opts\"] ? \"reality\" : undefined,\n                pbk: Obj[\"public-key\"],\n                sid: Obj[\"short-id\"],\n\n\n                // transport layer config\n                \n                // - ws\n                ed: Obj[\"max-early-data\"],\n                eh: Obj[\"early-data-header-name\"],\n\n                // - grpc\n                serviceName: Obj[\"grpc-service-name\"],\n\n                // - http\n                method: Obj.method,\n\n                // - http & ws\n                path: Obj[\"ws-path\"] || Obj.path,\n                host: (Obj[\"ws-headers\"] || Obj.headers || {}).Host,\n            }\n        }\n    }\n}\n\nfunction __searchParamsMapper (searchParams) {\n    let Query = {}\n    for (const [key, value] of searchParams) {\n        Query[key] = value\n    }\n    return Query;\n}\n"
  },
  {
    "path": "functions/internal/Parsers/share-link.js",
    "content": "export class ShareLinkParser {\n    constructor () {}\n\n    __validate (URI) {\n        if (!(URI.split(\":\")[0] in this)) {\n            console.warn(`[Parser: Share Link] [WARN] ${URI.__Type} is not supported to parse, ignoring...`)\n            return false;\n        }\n        return true;\n    }\n\n    http (URI) {\n        let URIObject = new URL (URI);\n        return {\n            __Type: \"http\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Auth: {\n                username: URIObject.username,\n                password: URIObject.password\n            }\n        }\n    }\n    socks5 (URI) {\n        let URIObject = new URL (URI);\n        return {\n            __Type: \"socks5\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Auth: {\n                username: URIObject.username,\n                password: URIObject.password\n            }\n        }\n    }\n    \n    hysteria (HYURL) {\n        const URIObject = new URL (HYURL);\n\n        const HY = {\n            __Type: \"hysteria\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Query: __searchParamsMapper(URIObject.searchParams)\n        }\n        return HY;\n    }\n    hysteria2 (HY2URL) {\n        const URIObject = new URL (HY2URL);\n\n        const HY2 = {\n            __Type: \"hysteria2\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Auth: decodeURIComponent(URIObject.password || URIObject.username),\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Query: __searchParamsMapper(URIObject.searchParams)\n        }\n        return HY2;\n    }\n    hy2 = this.hysteria2;\n\n    tuic (TUICURI) {\n        let URIObject = new URL(TUICURI);\n\n        const TUIC = {\n            __Type: \"tuic\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Auth: { uuid: URIObject.username, password: URIObject.password},\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Query: __searchParamsMapper(URIObject.searchParams)\n        }\n        return TUIC;\n    }\n\n\n    vless (URI) {\n        let URIObject = new URL (URI);\n        let VLESS = {\n            __Type: \"vless\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Auth: URIObject.username,\n            Query: __searchParamsMapper(URIObject.searchParams)\n        }\n        return VLESS;\n    }\n    vmess (URI) {\n        let URIObject = new URL(URI);\n        let VMessRawData = atob(URIObject.host);\n        try {\n            let VMessRawObject = JSON.parse(VMessRawData);\n\n            let Remark;\n            try {\n                Remark = decodeURIComponent(escape(VMessRawObject.ps))\n            } catch (e) {\n                Remark = VMessRawObject.ps\n            }\n            let VMess =  {\n                __Type: \"vmess\",\n                __Remark: Remark || `${VMessRawObject.add}:${VMessRawObject.port}`,\n                Hostname: VMessRawObject.add,\n                Port: parseInt(VMessRawObject.port),\n                Auth: VMessRawObject.id,\n            }\n            delete VMessRawObject.ps\n            delete VMessRawObject.add\n            delete VMessRawObject.port\n            delete VMessRawObject.id\n\n            // am i doing right...\n            delete VMessRawObject.v // assume its version 2\n\n            // delete all the empty fields\n            for (let i in VMessRawObject) {\n                if (\n                    VMessRawObject[i] === \"\" || \n                    VMessRawObject[i] === null || \n                    VMessRawObject[i] === undefined\n                ) {\n                    delete VMessRawObject[i]\n                }\n            }\n\n            VMessRawObject.aid = parseInt(VMessRawObject.aid)\n\n            VMess.Query = VMessRawObject;\n\n            return VMess;\n        } catch (err) {\n            let StandardURIObj = new URL(`vmess://${VMessRawData}${URIObject.pathname}${URIObject.search}`)\n            let VMess =  {\n                //__Type: \"vmess\",\n                __Type: \"vmess__shadowsocks_type\",\n                __Remark: StandardURIObj.searchParams.get(\"remarks\") || StandardURIObj.host,\n                Hostname: StandardURIObj.hostname,\n                Port: parseInt(StandardURIObj.port),\n                Auth: StandardURIObj.password,\n                Query: __searchParamsMapper(URIObject.searchParams)\n            }\n            delete VMess.Query.remarks\n            if (VMess.Query.obfs === \"websocket\") { VMess.Query.obfs = \"ws\" }\n            return VMess\n        }\n    }\n\n    ss (URI) {\n        let StandardURI = (URI => {\n            let URIObject = new URL(URI);\n            try {\n                // base64-encoded cipher:uuid@host:port\n                return `ss://${encodeURIComponent(atob(decodeURIComponent(URIObject.host))).replace(/\\%3A/gi,\":\").replace(/\\%40/gi,\"@\")}${URIObject.search}${URIObject.hash}`;\n            } catch (e) {}\n            try {\n                // base64-encoded cipher:uuid\n                return `ss://${encodeURIComponent(atob(decodeURIComponent(URIObject.username))).replace(/\\%3A/i,\":\")}@${URIObject.host}${URIObject.search}${URIObject.hash}`;\n            } catch (e) {}\n            // plain\n            return URI;\n        })(URI)\n        \n        let URIObject = new URL(StandardURI);\n        \n\n        return {\n            __Type: \"ss\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Auth: { cipher: decodeURIComponent(URIObject.username), password: decodeURIComponent(URIObject.password) },\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port)\n        }\n\n    }\n\n    trojan (URI) {\n        let URIObject = new URL(URI);\n\n        const TROJAN = {\n            __Type: \"trojan\",\n            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, \"\")) || URIObject.host,\n            Auth: URIObject.username,\n            Hostname: URIObject.hostname,\n            Port: parseInt(URIObject.port),\n            Query: __searchParamsMapper(URIObject.searchParams)\n        }\n        return TROJAN;\n    }\n}\n\nfunction __searchParamsMapper (searchParams) {\n    let Query = {}\n    for (const [key, value] of searchParams) {\n        Query[key] = value\n    }\n    return Query;\n}"
  },
  {
    "path": "functions/internal/Parsers/sing-box.js",
    "content": "export class SingBoxParser {\n    constructor () {}\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.type in this)) {\n            console.warn(`[Parser: Sing-Box] [WARN] ${ProxyObject.__Type} is not supported to parse, ignoring...`)\n            return false;\n        }\n        if (ProxyObject.type === \"socks\" && ProxyObject.version != 5) {\n            console.warn(`[Parser: Sing-Box] [WARN] Only Socks version 5 is supported to parse, ignoring...`)\n            return false;\n        }\n        return true;\n    }\n\n    http (Obj) {\n        return {\n            __Type: \"http\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: {\n                username: Obj.username,\n                password: Obj.password\n            }\n        }\n    }\n    socks (Obj) {\n        return {\n            __Type: \"socks5\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: {\n                username: Obj.username,\n                password: Obj.password\n            }\n        }\n    }\n    \n    hysteria (Obj) {\n        return {\n            __Type: \"hysteria\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Query: {\n                auth: (Obj[\"auth_str\"] || Obj[\"auth\"]),\n                alpn: Obj.tls && Obj.tls.alpn ? Obj.tls.alpn.join(\",\") : undefined,\n                upmbps: Obj.up || Obj.up_mbps,\n                downmbps: Obj.down || Obj.down_mbps,\n                peer: Obj.tls && Obj.tls.server_name,\n                mport: Obj.server_ports ? Obj.server_ports.map(i=>i.replace(/\\:/gi, \"-\")).join(\",\") : undefined,\n            }\n        }\n    }\n    hysteria2 (Obj) {\n        return {\n            __Type: \"hysteria2\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: Obj.password,\n            Query: {\n                upmbps: Obj.up_mbps,\n                downmbps: Obj.down_mbps,\n                objs: Obj.obfs ? Obj.obfs.type : undefined,\n                \"obfs-password\": Obj.obfs ? Obj.obfs.password : undefined,\n                insecure: Obj.tls && Obj.tls.insecure ? 1 : 0,\n                mport: Obj.server_ports ? Obj.server_ports.map(i=>i.replace(/\\:/gi, \"-\")).join(\",\") : undefined,\n            }\n        }\n    }\n\n    tuic (Obj) {\n        return {\n            __Type: \"tuic\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: { uuid: Obj.uuid, password: Obj.password },\n            Query: {\n                alpn: Obj.alpn ? Obj.alpn.join(\",\") : undefined,\n                disable_sni: Obj.tls.disable_sni,\n                udp_relay_mode: Obj.udp_relay_mode,\n                congestion_control: Obj.congestion_control,\n                sni: Obj.tls && Obj.tls.server_name,\n            }\n        }\n    }\n\n\n    vless (Obj) {\n        return {\n            __Type: \"vless\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: Obj.uuid,\n            Query: {\n                flow: Obj.flow,\n                packetEncoding: Obj.packet_encoding,\n                sni: Obj.tls && Obj.tls.server_name,\n                alpn: Obj.tls && Obj.tls.alpn ? Obj.tls.alpn.join(\",\") : undefined,\n                fp: Obj.tls && Obj.tls.utls && Obj.tls.utls.enabled === true ? Obj.tls.utls.fingerprint: undefined,\n                type: Obj.network,\n\n                // reality\n                security: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? \"reality\" : undefined,\n                pbk: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality[\"public_key\"] : undefined,\n                sid: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality[\"short_id\"] : undefined,\n\n                // transport layer config\n                // - ws\n                ed: Obj.transport && Obj.transport[\"max_early_data\"],\n                eh: Obj.transport && Obj.transport[\"early_data_header_name\"],\n                // - grpc\n                serviceName: Obj.transport && Obj.transport[\"service_name\"],\n                // - http\n                method: Obj.method,\n                // - http & ws\n                path: Obj.transport && Obj.transport.path,\n                host: (Obj.transport && Obj.transport.headers || {}).Host,\n            }\n        }\n    }\n    vmess (Obj) {\n        return {\n            __Type: \"vmess\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: Obj.uuid,\n            Query: {\n                aid: Obj.alter_id,\n                cipher: Obj.security,\n                net: Obj.network,\n                type: Obj.protocol,\n                fp: Obj.tls && Obj.tls.utls ? Obj.tls.utls.fingerprint : undefined,\n                alpn: Obj.alpn ? Obj.alpn.join(\",\") : undefined,\n                tls: Obj.tls && Obj.tls.enabled ? \"tls\" : undefined,\n                sni: Obj.server_name,\n\n                // transport layer config\n                // - http & ws & h2 \n                host: (Obj.headers || {}).Host,\n                // - http & ws & h2 & grpc\n                path: Obj.path || undefined\n            }\n        }\n    }\n\n    shadowsocks (Obj) {\n        return {\n            __Type: \"ss\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: { cipher: Obj.method, password: Obj.password },\n        }\n    }\n\n    trojan (Obj) {\n        return {\n            __Type: \"trojan\",\n            __Remark: Obj.tag,\n            Hostname: Obj.server,\n            Port: Obj.server_port,\n            Auth: Obj.password,\n            Query: {\n                type: Obj.network,\n                sni: Obj.tls && Obj.tls.server_name,\n\n                // reality\n                security: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? \"reality\" : undefined,\n                pbk: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality[\"public_key\"] : undefined,\n                sid: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality[\"short_id\"] : undefined,\n\n\n                // transport layer config\n                // - ws\n                ed: Obj.transport && Obj.transport[\"max_early_data\"],\n                eh: Obj.transport && Obj.transport[\"early_data_header_name\"],\n                // - grpc\n                serviceName: Obj.transport && Obj.transport[\"service_name\"],\n                // - http\n                method: Obj.method,\n                // - http & ws\n                path: Obj.transport && Obj.transport[\"path\"] || Obj.path,\n                host: (Obj.transport && Obj.transport[\"headers\"] || Obj.headers || {}).Host,\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "functions/internal/RuleProviderReader/Readers/ini.js",
    "content": "import { parseINI } from \"confbox\";\n\nimport { fetchCached } from \"../../utils/fetchCached.js\";\n\nexport async function ini (RuleProviderURL, CacheDB, isForcedRefresh) {\n\n    let Config = {\n        RuleProviders: [],\n        Rules: [],\n        ProxyGroup: []\n    };\n\n    // get raw remote config.\n    let RuleProvider = \n        await fetchCached(RuleProviderURL, \"RuleProvider\", CacheDB, isForcedRefresh)\n        .then(\n            res => \n                res.replaceAll(\"ruleset=\", \"ruleset[]=\")\n                   .replaceAll(\"custom_proxy_group=\", \"custom_proxy_group[]=\")\n        )\n        .then(res => parseINI(res));\n\n\n    // process rules\n    for (let i of RuleProvider.custom.ruleset) {\n        const rulesetBreakdown = i.split(\",\").map(i=>i.trim())\n        const id = rulesetBreakdown[0];\n        const payload = rulesetBreakdown.slice(1).join(\",\");\n\n        // append rule providers\n        if (payload.startsWith(\"https://\") || payload.startsWith(\"http://\")) {\n            if (!Config.RuleProviders[id]) {\n                Config.RuleProviders[id] = [];\n            }\n            Config.RuleProviders[id].push(payload)\n        }\n\n        // append route rules\n        const postProcessedContent = \n            `${id},${payload\n                .replace(/^\\[\\]FINAL/i, \"MATCH\")\n                .replace(/^\\[\\]/g, \"\")\n            }`\n        Config.Rules.push(postProcessedContent)\n    }\n\n    // process proxy groups\n    for (let i of RuleProvider.custom.custom_proxy_group) {\n        // \"特殊筛选条件\" (starts with \"!!\") are not supported. #todo\n        const ConfigArr = i.split(\"`\").map(i => i.trim()).filter(t => !t.startsWith(\"!!\"));\n        const Args = ConfigArr.slice(2).filter(t => !t.startsWith(\"[]\"));\n        const type = ConfigArr[1];\n\n        let ProxyGroupConfig = {\n            name: ConfigArr[0],\n            type: type,\n            RegExps: Args,\n            GroupSelectors: ConfigArr.slice(2).filter(t => t.startsWith(\"[]\")),\n        }\n            \n        if (type === \"url-test\" || type === \"fallback\" || type === \"load-balance\") {\n            let TestURLIndex = Args.findIndex(loc => (loc.startsWith(\"https://\") || loc.startsWith(\"http://\")))\n            let TestArgs = [Args.slice(TestURLIndex)[0], ...Args.slice(TestURLIndex)[1].split(\",\").map(i => i.trim())];\n            ProxyGroupConfig.TestConfig = {\n                TestURL: TestArgs[0],\n                Interval: parseInt(TestArgs[1]),\n                Timeout: parseInt(TestArgs[2]),\n                Tolerance: parseInt(TestArgs[3]),\n            }\n        }\n\n        Config.ProxyGroup.push(ProxyGroupConfig)\n    }\n\n    return Config;\n\n}"
  },
  {
    "path": "functions/internal/RuleProviderReader/main.js",
    "content": "import { ini } from \"./Readers/ini.js\"\n\nexport class RuleProviderReader {\n    RuleProvider = {};\n    Reader = {\n        ini,\n    }\n    constructor (RuleProviderURL) {\n        this.RuleProvider.URL = RuleProviderURL;\n        const pathname = new URL(RuleProviderURL).pathname;\n        this.RuleProvider.Type = pathname.split(\".\").slice(-1)[0].toLowerCase();\n\n        console.info(`[Remote Config Reader] Inputed remote config type: ${this.RuleProvider.Type}`);\n\n        if (this.RuleProvider.Type in this.Reader) {\n            return true;\n        } else {\n            console.warn(\"[Remote Config Reader] [WARN] Inputed remote config type cannot be detected, assume as .ini.\");\n            this.RuleProvider.Type = \"ini\"\n            return true;\n        }\n    }\n\n    Process = async function (EdgeSubDB, isForcedRefresh) {\n        let __startTime = performance.now();\n        console.info(`[Remote Config Reader] started`);\n        const response = this.Reader[this.RuleProvider.Type](this.RuleProvider.URL, EdgeSubDB, isForcedRefresh);\n        //let RawConfig = await fetchRuleProvider(RuleProviderURL, isForcedRefresh);\n        console.info(`[Remote Config Reader] done, wasting ${performance.now() - __startTime}ms`);\n        return response\n    }\n\n}\n"
  },
  {
    "path": "functions/internal/configs.ts",
    "content": "export const DefaultRequestHeaders = {\n    \"Accept\": \"*/*\",\n    \"User-Agent\": \"EdgeSub-git/0.0.0 (Prefer ClashMeta / Mihomo Format)\",\n}"
  },
  {
    "path": "functions/internal/data/rule/MetaToSingLogicalRule.ts",
    "content": "import { MetaToSingRuleMapping } from \"./MetaToSingMapping\";\nimport { transformGeoRef } from \"../ruleset/transformGeoRef\";\nimport type { headlessRuleSet } from \"../ruleset/transformGeoRef\";\n\n/**\n * Parse Mihomo Logical rules, AND | OR\n * example:\n *  - AND,  ((DOMAIN,baidu.com),(NETWORK,UDP))\n *  - OR,   ((NETWORK,UDP),(DOMAIN,baidu.com))\n * Nesting supported!\n * example:\n *  - AND,  ( (DOMAIN,baidu.com), (OR, ( (NETWORK,UDP), (PORT,443) ) ) )\n * @param type Sing rule type \n * @returns Sing Headless rule\n */\nexport function MetaToSingLogicalRule (type: string, payload: string, EdgeSubInstanceBaseURL): { headlessRule: any, headlessRuleSet: headlessRuleSet[] } {\n    // console.log(payload)\n    const payloads = payload.replace(/(^\\(|\\)$)/g, \"\");\n    // console.log(payloads)\n    const ruleSets: headlessRuleSet[] = [];\n    const rules = parseParenthesizedItems(payloads).map(i => {\n        const itemBreakdown = i.split(\",\");\n        const itemType = MetaToSingRuleMapping[itemBreakdown[0]];\n        const itemPayload = itemBreakdown[1];\n        // handle GEOIP and GEOSITE\n        if (itemType === \"geoip\" || itemType === \"geosite\") {\n            const { headlessRule, headlessRuleSet } = transformGeoRef(itemType, itemPayload, EdgeSubInstanceBaseURL);\n            // if we cant find rule set with same tag (ie append before), \n            if (headlessRuleSet && !(ruleSets.find(i => i.tag === headlessRuleSet.tag))) { \n                ruleSets.push(headlessRuleSet);\n            }\n            return headlessRule;\n        }\n        if (itemType === \"and\" || itemType === \"or\") {\n            let { \n                headlessRule: RecrusivlyHeadlessRule, \n                headlessRuleSet: RecrusivlyHeadlessRuleSet \n            } = MetaToSingLogicalRule(itemType, itemBreakdown.slice(1).join(\",\"), EdgeSubInstanceBaseURL);\n\n            RecrusivlyHeadlessRuleSet = RecrusivlyHeadlessRuleSet.filter(i => !!i && !ruleSets.find(t => t.tag === i.tag));\n            ruleSets.push(...RecrusivlyHeadlessRuleSet);\n\n            return RecrusivlyHeadlessRule;\n        }\n        return {\n            [itemType]: itemPayload,\n        }\n    });\n    \n    return {\n        headlessRule: {\n            type: \"logical\",\n            mode: type,\n            rules: rules\n        },\n        headlessRuleSet: ruleSets\n    }\n}\n\n\n/**\n * Parses a string containing comma-separated, parenthesized items into an array of strings.\n * This version correctly handles nested parentheses by manually balancing them,\n * which is a task simple regular expressions cannot reliably perform.\n *\n * @param inputString The string to parse, e.g., \"(A,(B)),(C)\".\n * @returns An array containing the inner content of each top-level parenthesized item.\n * For example, [\"A,(B)\", \"C\"].\n * Returns an empty array if there are no matches.\n */\nfunction parseParenthesizedItems(inputString: string): string[] {\n    const result: string[] = [];\n    let parenCount = 0;\n    let itemStart = -1;\n\n    for (let i = 0; i < inputString.length; i++) {\n        const char = inputString[i];\n\n        if (char === '(') {\n        if (parenCount === 0) {\n            // This is the start of a top-level item.\n            // Mark the position right after the opening parenthesis.\n            itemStart = i + 1;\n        }\n        parenCount++;\n        } else if (char === ')') {\n        parenCount--;\n        if (parenCount === 0 && itemStart !== -1) {\n            // We've found the closing parenthesis of a top-level item.\n            // Extract the content from itemStart to the current position.\n            result.push(inputString.substring(itemStart, i));\n            itemStart = -1; // Reset for the next item.\n        }\n        }\n    }\n\n    // A final check: if parenCount is not 0, the input string had mismatched parentheses.\n    // You might want to throw an error here, but for now we'll return what we found.\n    if (parenCount !== 0) {\n        console.error(\"Warning: Mismatched parentheses in input string.\");\n    }\n\n    return result;\n}"
  },
  {
    "path": "functions/internal/data/rule/MetaToSingMapping.ts",
    "content": "// mihomo src rule syntax\n// <TYPE>, <PAYLOAD>, <OUTBOUND>, <Additional Parameters>\n// note: headless rule doesnt need to care bout outbound\n//       additional parameters is not handled by sing-box/route/rule:\n//       - \"no-resolve\"'s sing-box/dns/rule's work. \n//       - \"src\" is a crazy thing i don't even know why it exists (\nexport const MetaToSingRuleMapping = {\n    \"DOMAIN\": \"domain\",\n    \"DOMAIN-SUFFIX\": \"domain_suffix\",\n    \"DOMAIN-KEYWORD\": \"domain_keyword\",\n    \"DOMAIN-REGEX\": \"domain_regex\",\n\n    \"GEOSITE\": \"geosite\",\n    \"GEOIP\": \"geoip\",\n\n    \"IP-CIDR\": \"ip_cidr\",\n    \"IP-CIDR6\": \"ip_cidr\", // IP-CIDR6 is a alias for IP-CIDR in mihomo route rule\n    \"SRC-IP-CIDR\": \"source_ip_cidr\",\n    \"SRC-PORT\": \"source_port\",\n\n    \"DST-PORT\": \"port\",\n\n    \"PROCESS-PATH\": \"process_path\",\n    \"PROCESS-PATH-REGEX\": \"process_path_regex\",\n    \"PROCESS-NAME\": \"process_name\",\n\n    \"NETWORK\": \"network\",\n\n    \"UID\": \"user_id\",\n\n    \"IN_NAME\": \"inbound\",\n\n    \"Sing_PROTOCOL\": \"protocol\",\n\n\n    \"AND\": \"and\",\n    \"OR\": \"or\",\n    // \"NOT\": \"invert\", // #TBD: invert rules\n}\n\n// mihomo source route rule w/o matching or no need to convert\n\n// IP-SUFFIX IP-ASN // destination IP rules\n// SRC-GEOIP SRC-IP-ASN SRC-IP-SUFFIX // source IP rules\n// IN-PORT IN-TYPE IN-USER IN-NAME // inbound rules\n// PROCESS-NAME-REGEX\n// UID\n// DSCP\n\n// RULE-SET\n// SUB-RULE\n// MATCH\n"
  },
  {
    "path": "functions/internal/data/ruleset/transformGeoRef.ts",
    "content": "export type headlessRuleSet = {\n    type: \"remote\",\n    tag: string,\n    url: string,\n    format: \"binary\" | \"source\",\n}\n\n\nexport function transformGeoRef (\n    type: string, \n    payload: string, \n    EdgeSubInstanceBaseURL\n): { \n    headlessRule: any, \n    headlessRuleSet: headlessRuleSet | null\n} {\n    const RuleSetTag = `${type}-${payload.toLowerCase()}`;\n\n    if (RuleSetTag === \"geoip-lan\") {\n        return {\n            headlessRule: {\n                ip_is_private: true,\n        \n            },\n            headlessRuleSet: null\n        }\n    }\n\n    // let edge-sub preprocess the rule-set\n    // construct url\n        let RuleSetURLObject = new URL(EdgeSubInstanceBaseURL);\n            RuleSetURLObject.pathname = \"/ruleset/proxy\";\n            RuleSetURLObject.search = \"\";\n            RuleSetURLObject.searchParams.append(\"target\", `https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/${RuleSetTag}.srs`);\n    const RuleSetURL = RuleSetURLObject.toString();\n\n    return {\n        headlessRule: {\n            rule_set: RuleSetTag,\n        },\n        headlessRuleSet: {\n            type: \"remote\",\n            tag: RuleSetTag,\n            format: \"binary\",\n            url: RuleSetURL,\n        }\n    }\n}"
  },
  {
    "path": "functions/internal/getParsedSubData.ts",
    "content": "import type { ClashMetaConfig } from \"./types/ClashMetaConfig\";\n\nimport { DefaultRequestHeaders } from \"./configs\";\n\nimport { ShareLinkParser } from \"./Parsers/share-link\";\nimport { ClashMetaParser } from \"./Parsers/clash-meta\";\nimport { SingBoxParser } from \"./Parsers/sing-box\";\n\nimport { parseYAML } from \"confbox\";\nimport { TrulyAssign } from \"./utils/TrulyAssign\";\nimport { parseContentDisposition } from \"./utils/parseContentDisposition\";\n\ntype SubURL = string; // start with `short:`, `http(s)://`, or sth like `[proxy protocol]://`\ntype SubURLs = string; // contains SubURL a lot\ntype SubURLArr = SubURL[]; // usually it is some SubURLs squeeze into a Array.\ntype ParsedSubscription = {\n    data: any[];\n    SubscriptionUserInfo?: SubscriptionUserInfo;\n};\ntype SubscriptionUserInfo = {\n    traffic?: string; // e.g. 'upload=<bytes>; download=<bytes>; total=<bytes>; expire=<timestamp>', from `subscription-userinfo` header\n    name?: string; // e.g. 'Nexitally', from `content-disposition` header filename field.\n}\n\n/**\n * \n * @returns {Array}\n */\nexport default async function getParsedSubData (\n    SubURLs: SubURLs, \n    EdgeSubDB, \n    isShowHost = false as boolean,\n    CustomHTTPHeaders = {} as Headers,\n    ExcludeRegExpPattern = \"\" \n) {\n    let __startTime = performance.now();\n    console.info(\"[Fetch Sub Data] Job started\")\n    console.info(`[Fetch Sub Data] isShowHost: ${isShowHost.toString()}`)\n\n    const RequestHeaders = TrulyAssign(DefaultRequestHeaders, CustomHTTPHeaders);\n\n    let SubURLArr = SubURLs.replaceAll(\"\\r\", \"\\n\").split(\"\\n\").filter((i) => !!i).map(i => encodeURIComponent(i.trim())).map(i => decodeURIComponent(i)) as SubURLArr;\n    let Proxies = [],\n        SubscriptionUserInfos: SubscriptionUserInfo[] = [];\n    for (let i in SubURLArr) {\n        console.info(`[Fetch Sub Data] Fetching ${parseInt(i) + 1}/${SubURLArr.length}`)\n        const ParsedSubscription = await ParseSubData(SubURLArr[i], EdgeSubDB, RequestHeaders);\n        Proxies = [...Proxies, ...ParsedSubscription.data];\n        if (ParsedSubscription.SubscriptionUserInfo) {\n            SubscriptionUserInfos.push(ParsedSubscription.SubscriptionUserInfo);\n        }\n    }\n\n    if (isShowHost === true) {\n        Proxies = Proxies.map(i => {\n            i.__Remark = `${i.__Remark} - ${i.Hostname}:${i.Port}`\n            return i;\n        })\n    }\n\n    if (!!ExcludeRegExpPattern) {\n        const ExcludeRegExp = new RegExp(ExcludeRegExpPattern, \"g\")\n        console.log(\"[Fetch Sub Data] filtering out outbounds matched with\", ExcludeRegExp)\n        Proxies = Proxies.filter(i => !i.__Remark.match(ExcludeRegExp))\n    }\n\n    console.info(`[Fetch Sub Data] Job done, wasting ${performance.now() - __startTime}ms.`)\n    return {Proxies, SubscriptionUserInfos};\n}\nasync function ParseSubData (SubURL: SubURL, EdgeSubDB, RequestHeaders) : Promise<ParsedSubscription> {\n\n    // pre define SubscriptionUserInfo\n    let SubscriptionUserInfo: SubscriptionUserInfo;\n\n    // handle `short` here\n    if (SubURL.match(/^short:/i)) {\n        let ShortData: SubURLs = await EdgeSubDB.get(SubURL).then(res => JSON.parse(res).subdata);\n        console.info(`[Fetch Sub Data] starting sub task for ${SubURL}`)\n        let ParsedShortData = (await getParsedSubData(ShortData, EdgeSubDB, RequestHeaders)).Proxies;\n        console.info(`[Fetch Sub Data] sub task for ${SubURL} done`)\n        return { data: ParsedShortData };\n    }\n\n    let SubData;\n    // handle bundle share link (not starts with `http(s|)://` )\n    if (!SubURL.match(/^http(s|):\\/\\//i)) {\n        SubData = {\n            type: \"share-link\",\n            data: SubURL\n        }\n    } else {\n        SubData = await fetch(SubURL, { headers: RequestHeaders })\n            .then(async res => { \n                console.info(`[Fetch Sub Data] Response status code ${res.status}`);\n                return {\n                    data: await res.text(),\n                    headers: res.headers\n                }\n            })\n            .then(res => {\n                // fill out SubscriptionUserInfo\n                SubscriptionUserInfo = {\n                    traffic: res.headers.has(\"Subscription-UserInfo\") ? res.headers.get(\"Subscription-UserInfo\") : null,\n                    name: res.headers.has(\"Content-Disposition\") ? parseContentDisposition(res.headers.get(\"Content-Disposition\")) : null\n                };\n                // try decode as yaml, for clash-meta config\n                try {\n                    let YAMLData = parseYAML(res.data) as ClashMetaConfig;\n                    if (YAMLData.proxies) {\n                        return {\n                            type: \"clash-meta\",\n                            data: YAMLData\n                        }\n                    }\n                } catch (e) {\n                    console.warn(`[Fetch Sub Data] Err when try parse as yaml: ${e}, skipping...`)\n                }\n                // try decode as json, for sing-box config\n                try {\n                    let SingBoxConfig = JSON.parse(res.data);\n                    if (SingBoxConfig.outbounds) {\n                        return {\n                            type: \"sing-box\",\n                            data: SingBoxConfig\n                        }\n                    }\n                } catch (e) {\n                    console.warn(`[Fetch Sub Data] Err when try parse as JSON (sing-box): ${e}, skipping...`)\n                }\n\n                // try decode as base64 endoded share-links\n                try {\n                    let decodedData = atob(res.data.trim());\n                    if (!decodedData.match(/\\:\\/\\//gi)) {\n                        throw \"seems like base64 decoded data malformed\"\n                    }\n                    return {\n                        type: \"share-link\",\n                        data: decodedData\n                    }\n                } catch (e) {\n                    console.warn(`[Fetch Sub Data] try parse as base64: ${e}, skipping...`)\n                }\n\n                // final return as share-link\n                return {\n                    type: \"share-link\",\n                    data: res.data\n                }\n            })\n    }\n\n    let ParsedSubData = [];\n    if (SubData.type === \"share-link\") {\n        let links = SubData.data.replaceAll(\"\\r\", \"\\n\").split(\"\\n\").filter(loc => !!loc);\n        let Parser = new ShareLinkParser();\n        for (let i of links) {\n            let protocol = i.split(\":\")[0];\n            try {\n                if (Parser.__validate(i)) {\n                    ParsedSubData.push(Parser[protocol](i))\n                }\n            } catch (e) {\n                console.warn(`[Fetch Sub Data] this share-url doesn't seem right, ignoring... ('${i}')`)\n                console.warn(e)\n            }\n        }\n    } else if (SubData.type === \"clash-meta\") {\n        let { proxies } = SubData.data;\n        let Parser = new ClashMetaParser();\n        for (let i of proxies) {\n            if (Parser.__validate(i)) {\n                ParsedSubData.push(Parser[i.type](i))\n            }\n        }\n    } else if (SubData.type === \"sing-box\") {\n        let { outbounds } = SubData.data;\n        let Parser = new SingBoxParser();\n        for (let i of outbounds) {\n            if (Parser.__validate(i)) {\n                ParsedSubData.push(Parser[i.type](i))\n            }\n        }\n    }\n    \n    return {\n        data: ParsedSubData,\n        SubscriptionUserInfo,\n    };\n}"
  },
  {
    "path": "functions/internal/types/ClashMetaConfig.ts",
    "content": "// reference: https://wiki.metacubex.one/\n\ntype ClashMetaProxyGroup = {\n    name: string;\n    type: string; // head to https://wiki.metacubex.one/config/proxy-groups/\n    url?: string | URL;\n    interval?: number;\n    tolerance?: number;\n    proxies: string[]\n}\n\nexport type ClashMetaConfig = {\n    port: number;\n    \"socks-port\": number;\n    \"allow-lan\": boolean;\n    mode: \"Rule\" | \"Global\" | \"Direct\";\n    \"log-level\": \"silent\" | \"error\" | \"warning\" | \"info\" | \"debug\";\n    \"external-controller\": string; // start with \":\"\n    ipv6: boolean; // default true\n    dns: {\n        enabled: boolean; // default true\n        nameserver: string[];\n        fallback: string[];\n    };\n    proxies: []\n    \"proxy-groups\": ClashMetaProxyGroup[];\n    rules: string[] // head to https://wiki.metacubex.one/config/rules/\n}\n\n\n\n\n// for transport layers\nexport type TransportHTTP = {\n    method: string;\n    path: string[];\n    headers?: {\n        host?: string\n    };\n}\nexport type TransportH2 = {\n    method: string;\n    path: string;\n}\nexport type TransportGRPC = {\n    \"grpc-service-name\": string;\n}\nexport type TransportWS = {\n    path?: string;\n    headers?: {\n        host?: string\n    };\n    \"max-early-data\"?: number;\n    \"early-data-header-name\"?: \"Sec-WebSocket-Protocol\" | string;\n    \"v2ray-http-upgrade\"?: unknown;\n    \"v2ray-http-upgrade-fast-open\"?: unknown;\n}\n\n// for reality\nexport type RealityConfig = {\n    \"public-key\"?: string;\n    \"short-id\"?: string;\n}"
  },
  {
    "path": "functions/internal/utils/TrulyAssign.js",
    "content": "/**\n * Assign source to target, note that its only for the first frame. \n * You will not get the target modified, instead, the target you need is in the returns.\n * @param {Object} target \n * @param {Object} source \n * @returns {Object} Assigned Target\n */\nexport function TrulyAssign (target, source) {\n    let DeepCopiedTarget = JSON.parse(JSON.stringify(target))\n    for (let key in source) {\n        if (key in source && source[key] !== \"__DEFAULT\") {\n            DeepCopiedTarget[key] = source[key];\n        }\n    }\n    return DeepCopiedTarget;\n}\n"
  },
  {
    "path": "functions/internal/utils/fetchCached.ts",
    "content": "export async function fetchCached (URL: URL, Prefix = \"Cached\", CacheDB: KVNamespace, isForcedRefresh = false) {\n    // const CacheKey = `RuleProvider_${URL}`;\n    const CacheKey = `${Prefix}_${URL}`;\n    const CacheTTL =  6 * 60 * 60; // 6hrs for default\n\n    // check if data was cached\n    let CachedData: string | null;\n    if (!CacheDB) {\n        CachedData = null;\n        console.info(`[fetchCached] - CacheDB is not configured, fetching.`)\n    } else {\n        if (isForcedRefresh) {\n            CachedData = null;\n        } else {\n            CachedData = await CacheDB.get(CacheKey)\n        }\n    }\n\n    // return cached data when it exist\n    if (CachedData) {\n        return CachedData;\n    }\n\n    console.info(`[fetchCached] - \"${CacheKey}\" is not cached, fetching.`)\n    // only when CachedData == falsy\n    let data = await fetch (URL)\n        .then(res => {\n            if (res.status === 200 || res.status === 304) {\n                return res\n            } else {\n                throw \"Failed to fetch.\"\n            }\n        })\n        .then(res => res.text())\n        .catch(() => null);\n    // save it into CacheDB when success, and, whatever, when CacheDB exist.\n    if (data !== null && CacheDB) {\n        await CacheDB.put(CacheKey, data.toString(), { expirationTtl: CacheTTL })\n    }\n    // just return\n    return data;\n}\n"
  },
  {
    "path": "functions/internal/utils/parseContentDisposition.ts",
    "content": "export function parseContentDisposition(RawContentDispositionHeader: string): string {\n    if (!RawContentDispositionHeader || !RawContentDispositionHeader.toLowerCase().startsWith('attachment')) {\n        console.warn('Invalid Content-Disposition header');\n        return null;\n    }\n\n    // Match filename*= (RFC 5987)\n    const filenameStarMatch = RawContentDispositionHeader.match(/filename\\*\\s*=\\s*([^'\"]*)''([^;]+)/i);\n    if (filenameStarMatch) {\n        try {\n            const encoding = filenameStarMatch[1].toLowerCase();\n            const filenameEncoded = filenameStarMatch[2];\n            return decodeURIComponent(filenameEncoded);\n        } catch (err) {\n            return null;\n        }\n    }\n\n    // Match filename= (quoted or unquoted)\n    const filenameMatch = RawContentDispositionHeader.match(/filename\\s*=\\s*(\"?)([^\";]+)\\1/i);\n    if (filenameMatch) {\n        return filenameMatch[2];\n    }\n\n    return null; // No fucking filename found\n}\n"
  },
  {
    "path": "functions/internal/utils/removeUndefinedFields.ts",
    "content": "export function removeUndefinedFields (obj: object) : object {\n    for (const key in obj) {\n        if (typeof obj[key] === 'object' && obj[key] !== null) {\n            removeUndefinedFields(obj[key]);\n        }\n        if (obj[key] === undefined) {\n            delete obj[key];\n        }\n    }\n    return obj;\n}\n"
  },
  {
    "path": "functions/ruleset/preprocessor/sing-box.ts",
    "content": "import { fetchCached } from \"../../internal/utils/fetchCached.js\";\nimport { MetaToSingRuleMapping } from \"functions/internal/data/rule/MetaToSingMapping.js\";\n\nexport async function onRequest (context) {\n    const { request } = context;\n    const URLObject = new URL(request.url);\n\n    const targetURL = URLObject.searchParams.get(\"target\") as unknown as URL;\n    const isForcedRefresh = URLObject.searchParams.get(\"forced_refresh\") === \"true\" ? true : false;\n\n    if (!targetURL) {\n        return new Response(\"400 Bad Request. 'targetURL' required.\", {\n            status: 200,\n            headers: {\n                \"Content-Type\": \"text/plain; charset=utf-8\"\n            }\n        })\n    }\n\n\n    let RawData = await fetchCached(targetURL, \"RuleSet\", context.env.EdgeSubDB, isForcedRefresh);\n\n    let RulesList = RawData.split(\"\\n\").map(i => i.trim()).filter(i => i.length > 0 && !i.startsWith(\"#\")).map(i => i.split(\",\").map(j => j.trim()));\n\n    // merge up rules\n    let rules = {}; // ref: https://sing-box.sagernet.org/configuration/rule-set/headless-rule/\n    for (let i of RulesList) {\n        const type = MetaToSingRuleMapping[i[0]],\n              payload = i[1];\n        if (!type) {\n            continue\n        }\n        if (!(type in rules)) {\n            rules[type] = [];\n        }\n        rules[type].push(payload);\n    }\n\n\n    return new Response(JSON.stringify({ \"version\": 1, rules: [ rules ] }), {\n        status: 200,\n        headers: {\n            \"Content-Type\": \"application/json; charset=utf-8\",\n            \"Content-Length\": RawData.length\n        }\n    })\n}\n"
  },
  {
    "path": "functions/ruleset/proxy.ts",
    "content": "import { fetchCached } from \"../internal/utils/fetchCached.js\";\n\nexport async function onRequest (context) {\n    const { request } = context;\n    const URLObject = new URL(request.url);\n\n    const targetURL = URLObject.searchParams.get(\"target\") as unknown as URL;\n\n    if (!targetURL) {\n        return new Response(\"400 Bad Request. 'targetURL' required.\", {\n            status: 200,\n            headers: {\n                \"Content-Type\": \"text/plain; charset=utf-8\"\n            }\n        })\n    }\n\n    let RawData = await fetch(targetURL);\n    return new Response(RawData.body, {\n        status: 200,\n        headers: RawData.headers\n    })\n}\n"
  },
  {
    "path": "functions/short/admin-password/set.ts",
    "content": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\nimport { sha256 } from \"js-sha256\";\n\nexport async function onRequestPost (context) {\n    const { request } = context;\n    const url = new URL(request.url);\n    const defaultHeader = getDefaultHeader(url);\n\n    const EdgeSubDB = context.env.EdgeSubDB;\n    const { \n        oldPassword, // will be false is client thinks the password is not set\n        newPassword // new password, not hashed\n    } = await request.json()\n    const hashedOldPassword = sha256(oldPassword)\n    const hashedNewPassword = sha256(newPassword)\n\n    // security check?\n    if (url.hostname === \"localhost\") {\n        console.info(\"[setPassword - security check] in development, ignoring...\")\n    } else {\n        if (url.protocol === \"http:\") {\n            console.warn(\"[setPassword - security check] requested via http, upgrading to https\")\n            if (url.protocol === \"http:\") {\n                url.protocol = \"https:\"\n                return Response.redirect(url.toString(), 301)\n            }\n        }\n    }\n\n    if (!newPassword) {\n        return new Response (\n            JSON.stringify({\n                msg: \"new password cant be empty\",\n                passwordUpdated: false\n            }), {\n                status: 400,\n                headers: defaultHeader\n            }\n        )\n    }\n\n\n    let oldPasswordInDB = await EdgeSubDB.get(\"admin-password\");\n    if (\n        !oldPasswordInDB || // should be true when there isn't any old password\n        hashedOldPassword == oldPasswordInDB // should be true when there is an password in db and matched\n    ) {\n        await EdgeSubDB.put(\"admin-password\", hashedNewPassword);\n    } else {\n        return new Response (\n            JSON.stringify({\n                msg: \"the provided old password does not match with the old password in database.\",\n                passwordUpdated: false\n            }), {\n                status: 422,\n                headers: defaultHeader\n            }\n        )\n    }\n\n\n    return new Response (\n        JSON.stringify({\n            msg: \"OK\",\n            passwordUpdated: true\n        }), {\n            status: 200,\n            headers: defaultHeader\n        }\n    )\n\n}\nexport async function onRequestOptions (context) {\n    const url = new URL(context.request.url);\n    return new Response(\"OK\", {\n        status: 200,\n        headers: getOptionsHeader(url)\n    });\n}\n"
  },
  {
    "path": "functions/short/admin-password/status.ts",
    "content": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequest (context) {\n    const { request } = context;\n    const defaultHeader = getDefaultHeader(new URL(request.url));\n\n    const EdgeSubDB = context.env.EdgeSubDB;\n\n    let hashedPassword = await EdgeSubDB.get(\"admin-password\");\n    return new Response (\n        JSON.stringify({\n            msg: \"OK\",\n            isPasswordSet: !!hashedPassword\n        }), {\n            status: 200,\n            headers: defaultHeader\n        }\n    )\n}"
  },
  {
    "path": "functions/short/delete/[id].ts",
    "content": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequestDelete (context) {\n    const { id } = context.params;\n    const EdgeSubDB = context.env.EdgeSubDB;\n    const defaultHeader = getDefaultHeader(new URL(context.request.url));\n\n    let { token } = await context.request.json();\n\n    if (!token) {\n        return new Response(\n            JSON.stringify({\n                msg: \"400 Bad Request. token missing or empty.\"\n            }), {\n                status: 400,\n                headers: defaultHeader\n            }\n        )\n    }\n\n\n    let storedData = await EdgeSubDB.get(`short:${id}`);\n    if (storedData) {\n        // when data exists\n        let storedJSON = JSON.parse(storedData);\n        let storedToken = storedJSON.token ?? storedJSON.password;\n        if (storedToken !== token) { \n            // when token doesnt matchs\n            return new Response(\n                JSON.stringify({\n                    msg: \"401 Unauthorized. Incorrect short token.\"\n                }), {\n                    status: 401,\n                    headers: defaultHeader\n                }\n            )\n        }\n    } else {\n        return new Response(\n            JSON.stringify({\n                msg: \"404 Not Found. requested short not exist.\",\n            }), {\n                status: 404,\n                headers: defaultHeader\n            }\n        )\n    }\n\n    // when all the things seems right, eg: data not exist or token matches.\n    await EdgeSubDB.delete(`short:${id}`)\n    return new Response(\n        JSON.stringify({\n            msg: `200 OK. short:${id} has been deleted.`,\n        }), {\n            status: 200,\n            headers: defaultHeader\n        }\n    )\n}\nexport async function onRequestOptions (context) {\n    return new Response(\"OK\", {\n        status: 200,\n        headers: getOptionsHeader(new URL(context.request.url), [ \"DELETE\" ])\n    });\n}\n\n\n\n\n"
  },
  {
    "path": "functions/short/get/[id].ts",
    "content": "import { getDefaultHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequest (context) {\n    const { id } = context.params;\n    const EdgeSubDB = context.env.EdgeSubDB;\n    const defaultHeader = getDefaultHeader(new URL(context.request.url));\n\n    let storedData = await EdgeSubDB.get(`short:${id}`);\n    if (storedData) {\n        let { subdata } = JSON.parse(storedData);\n        return new Response(\n            JSON.stringify({\n                msg: \"OK\",\n                subdata,\n            }), {\n                status: 200,\n                headers: defaultHeader\n            }\n        )\n    } else {\n        return new Response(\n            JSON.stringify({\n                msg: \"Not Found\"\n            }), {\n                status: 404,\n                headers: defaultHeader\n            }\n        )\n    }\n}"
  },
  {
    "path": "functions/short/list.ts",
    "content": "import { getDefaultHeader, getOptionsHeader } from \"./utils/defaultHeader\";\nimport { sha256 } from \"js-sha256\";\n\nexport async function onRequestPost (context) {\n    const { request } = context;\n    const defaultHeader = getDefaultHeader(new URL(request.url));\n\n    const EdgeSubDB = context.env.EdgeSubDB;\n\n    const { password } = await request.json()\n    const hashedPassword = sha256(password)\n    const hashedPasswordInDB = await EdgeSubDB.get(\"admin-password\");\n\n    // check for password\n    if (hashedPassword !== hashedPasswordInDB) {\n        return new Response (\n            JSON.stringify({\n                msg: \"the provided old password does not match with the old password in database\",\n                success: false,\n                shortIDs: []\n            }), {\n                status: 401,\n                headers: defaultHeader\n            }\n        )\n    }\n\n    // const shortIDs = \n    //     ((await EdgeSubDB.list({ prefix: \"short:\" })).keys || [])\n    //         .map(i => { \n    //             return { \n    //                 name: i.name, \n    //                 timestamp: EdgeSubDB.get(i.name).then(res => JSON.parse(res).timestamp) // its needed to be\n    //             }\n    //         });\n    const shortIDs = await EdgeSubDB.list({ prefix: \"short:\" })\n        .then(async listResult => {\n            const keys = listResult.keys || [];\n            const shortIDs = [];\n            for (let i of keys) {\n                let ShortItem = await EdgeSubDB.get(i.name)\n                    .then(res => JSON.parse(res).timestamp)\n                    .then(timestamp => ({ name: i.name, timestamp }));\n                shortIDs.push(ShortItem)\n            }\n            return shortIDs\n        })\n        .catch(error => {\n            throw \"Error fetching short IDs:\" + error\n        });\n\n    return new Response (\n        JSON.stringify({\n            msg: \"OK\",\n            success: true,\n            shortIDs\n        }), {\n            status: 200,\n            headers: defaultHeader\n        }\n    )\n\n}\nexport async function onRequestOptions (context) {\n    const url = new URL(context.request.url);\n    return new Response(\"OK\", {\n        status: 200,\n        headers: getOptionsHeader(url)\n    });\n}\n"
  },
  {
    "path": "functions/short/put.ts",
    "content": "import { getDefaultHeader, getOptionsHeader } from \"./utils/defaultHeader\";\n\nexport async function onRequestPost (context) {\n    const { request } = context;\n    const defaultHeader = getDefaultHeader(new URL(request.url));\n    const timestamp = Date.now();\n\n    const EdgeSubDB = context.env.EdgeSubDB;\n    let { slug, token, subdata } = await request.json();\n\n    if (!slug && !token) {\n        slug = await generateToken(8, EdgeSubDB);\n        token = await generateToken(16);\n    }\n\n\n    let storedData = await EdgeSubDB.get(`short:${slug}`);\n    if (storedData) {\n        // when data exists\n        let storedJSON = JSON.parse(storedData);\n        let storedToken = storedJSON.token ?? storedJSON.password;\n        if (storedToken !== token) { \n            // when token doesnt matchs\n            return new Response(\n                JSON.stringify({\n                    msg: \"401 Unauthorized. Incorrect short token.\",\n                    slug,\n                }), {\n                    status: 401,\n                    headers: defaultHeader\n                }\n            )\n        }\n    }\n\n    // when all the things seems right, eg: data not exist or token matches.\n    await EdgeSubDB.put(`short:${slug}`, JSON.stringify({\n        token, subdata, timestamp\n    }))\n    return new Response(\n        JSON.stringify({\n            msg: \"OK\",\n            slug,\n            token\n        }), {\n            status: 200,\n            headers: defaultHeader\n        }\n    )\n}\nexport async function onRequestOptions (context) {\n    return new Response(\"OK\", {\n        status: 200,\n        headers: getOptionsHeader(new URL(context.request.url))\n    });\n}\n\n\nasync function generateToken (length, EdgeSubDB = undefined) {\n    const chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n    let strArr = [];\n    for (let i = 0, n = chars.length; i < length; i++) {\n        strArr.push(chars[Math.floor(Math.random() * n)])\n    }\n    let str =  strArr.join(\"\");\n    if ( EdgeSubDB && !!(await EdgeSubDB.get(`short:${str}`)) ) {\n        return generateToken(length, EdgeSubDB);\n    }\n    return str;\n}\n"
  },
  {
    "path": "functions/short/token-reset/[id].ts",
    "content": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequestPatch (context) {\n    const { id } = context.params;\n    const EdgeSubDB = context.env.EdgeSubDB;\n    const defaultHeader = getDefaultHeader(new URL(context.request.url));\n\n    let { oldToken, newToken } = await context.request.json();\n\n    if (!oldToken || !newToken) {\n        return new Response(\n            JSON.stringify({\n                msg: \"400 Bad Request. oldToken or newToken missing or empty.\"\n            }), {\n                status: 400,\n                headers: defaultHeader\n            }\n        )\n    }\n\n\n    let storedData = await EdgeSubDB.get(`short:${id}`);\n    let storedJSON = JSON.parse(storedData);\n    if (storedData) {\n        // when data exists\n        let storedToken = storedJSON.token ?? storedJSON.password;\n        if (storedToken !== oldToken) { \n            // when oldToken doesnt matchs\n            return new Response(\n                JSON.stringify({\n                    msg: \"401 Unauthorized. Incorrect short oldToken.\"\n                }), {\n                    status: 401,\n                    headers: defaultHeader\n                }\n            )\n        }\n    } else {\n        return new Response(\n            JSON.stringify({\n                msg: \"404 Not Found. requested short not exist.\",\n            }), {\n                status: 404,\n                headers: defaultHeader\n            }\n        )\n    }\n\n    // when all the things seems right, eg: data not exist or token matches.\n    storedJSON.token = newToken;\n    await EdgeSubDB.put(`short:${id}`, JSON.stringify(storedJSON))\n    return new Response(\n        JSON.stringify({\n            msg: `200 OK. short:${id}'s token has been changed.`,\n        }), {\n            status: 200,\n            headers: defaultHeader\n        }\n    )\n}\nexport async function onRequestOptions (context) {\n    return new Response(\"OK\", {\n        status: 200,\n        headers: getOptionsHeader(new URL(context.request.url), [ \"PATCH\" ])\n    });\n}\n"
  },
  {
    "path": "functions/short/utils/defaultHeader.ts",
    "content": "export const getDefaultHeader = (url: URL) => { \n    return {\n        \"Access-Control-Allow-Origin\": getAllowedOriginHeader(url),\n        \"content-type\": \"application/json, charset=utf-8\",\n        \"Access-Control-Allow-Credentials\": \"true\",\n    } as unknown as Headers;\n}\nexport const getOptionsHeader = (url: URL, Methods = [ \"POST\" ]) => { \n    Methods.push(\"OPTIONS\")\n    return {\n        //\"Access-Control-Allow-Origin\":  \"localhost:4321\")\n        \"Access-Control-Allow-Origin\": getAllowedOriginHeader(url),\n        \"Access-Control-Allow-Credentials\": \"true\",\n        \"Access-Control-Allow-Methods\": Methods.join(\", \"),\n    } as unknown as Headers;\n}\n\nconst getAllowedOriginHeader = (url: URL) => url.hostname === \"localhost\" ? \"*\" : `${url.protocol}//${url.host}`;"
  },
  {
    "path": "functions/sub/base64.js",
    "content": "import { onRequest as ShareLinkOnRequest } from \"./share-link.js\";\n\nexport async function onRequest (context) {\n    return await ShareLinkOnRequest(context, true)\n}\n"
  },
  {
    "path": "functions/sub/clash-meta.js",
    "content": "import { getClashMetaConfig } from \"../internal/Converter/getClashMetaConfig.js\";\nimport getParsedSubData from \"../internal/getParsedSubData.ts\";\nimport { stringifyYAML } from \"confbox\";\n\n\nexport async function onRequest (context) {\n    const { request } = context;\n    const URLObject = new URL(request.url);\n    let { Proxies, SubscriptionUserInfos } = await getParsedSubData(\n        URLObject.searchParams.get(\"url\"), \n        context.env.EdgeSubDB, \n        URLObject.searchParams.get(\"show_host\") === \"true\",\n        JSON.parse(URLObject.searchParams.get(\"http_headers\")),\n        URLObject.searchParams.get(\"ExcludeRegExpPattern\"),\n    );\n    // a javascript object !!! not YAML !!!\n    let ClashMetaConfigObject = await getClashMetaConfig (\n        Proxies,\n        context.env.EdgeSubDB,\n        {\n            isUDP: URLObject.searchParams.get(\"udp\") === \"true\",\n            isSSUoT: URLObject.searchParams.get(\"ss_uot\") === \"true\",\n            isInsecure: true,\n            RuleProvider: URLObject.searchParams.get(\"remote_config\") || \"__DEFAULT\",\n            RuleProvidersProxy: URLObject.searchParams.get(\"rule_providers_proxy\"),\n            BaseConfig: URLObject.searchParams.get(\"BaseConfig\"),\n            isForcedRefresh: URLObject.searchParams.get(\"forced_refresh\") === \"true\",\n        }\n    )\n\n    // handle forced ws 0-rtt\n    if (URLObject.searchParams.get(\"forced_ws0rtt\") === \"true\") {\n        console.info(\"[Main] ForcedWS0RTT enabled.\")\n        for (let i of ClashMetaConfigObject.proxies) {\n            if (!(\"ws-opts\" in i)) {\n                continue;\n            }\n            i[\"ws-opts\"][\"max-early-data\"] = 2560\n            i[\"ws-opts\"][\"early-data-header-name\"] = \"Sec-WebSocket-Protocol\"\n        }\n    }\n\n    const ResponseBody = stringifyYAML(ClashMetaConfigObject);\n    const response = new Response(\n        ResponseBody, \n        {\n            status: 200,\n            headers: {\n                \"Content-Type\": \"text/plain; charset=utf-8\",\n                \"Content-Length\": ResponseBody.length,\n                \"Cache-Control\": \"no-cache, no-store, must-revalidate\",\n                \"Pragma\": \"no-cache\",\n                \"Expires\": \"0\",\n            }\n        }\n    )\n\n    if (SubscriptionUserInfos.length > 0) {\n        let Names = SubscriptionUserInfos.map(i => i.name).filter(i => !!i);\n        // two name, then eclipse...\n        let NamesLimit = Names.length > 2 ? 2 : Names.length;\n        let Filename = `${Names.slice(0, NamesLimit).join(\", \")}, and ${SubscriptionUserInfos.length - NamesLimit} more`;\n        response.headers.set(\"Content-Disposition\", `attachment; filename*=UTF-8''${encodeURIComponent(Filename)}.yaml`);\n\n        let Traffic = SubscriptionUserInfos.map(i => i.traffic).filter(i => !!i)[0]; // first element of SubscriptionUserInfos\n        // if Names.length > 1, then we shouldn't use such per-profile specific traffic values.\n        if (Names.length === 1) {\n            response.headers.set(\"Subscription-UserInfo\", Traffic);\n        }\n    }\n    \n    return response;\n}"
  },
  {
    "path": "functions/sub/debug.js",
    "content": "import getParsedSubData from \"../internal/getParsedSubData.ts\";\n\nexport async function onRequest (context) {\n    const { request } = context;\n    const URLObject = new URL(request.url);\n    const { Proxies } = await getParsedSubData(\n        URLObject.searchParams.get(\"url\"), \n        context.env.EdgeSubDB, \n        URLObject.searchParams.get(\"show_host\") === \"true\",\n        JSON.parse(URLObject.searchParams.get(\"http_headers\")),\n        URLObject.searchParams.get(\"ExcludeRegExpPattern\"),\n    );\n    const ResponseBody = JSON.stringify(Proxies)\n    \n    return new Response(ResponseBody, {\n        status: 200,\n        headers: {\n            \"Content-Type\": \"application/json, charset=utf-8\",\n            \"Content-Length\": ResponseBody.length,\n        }\n    })\n}"
  },
  {
    "path": "functions/sub/share-link.js",
    "content": "import getParsedSubData from \"../internal/getParsedSubData.ts\";\nimport { ShareLinkDumper } from \"../internal/Dumpers/share-link.js\";\n\nexport async function onRequest (context, isBase64 = false) {\n    const { request } = context;\n    const URLObject = new URL(request.url);\n    // do convert\n    const { Proxies } = await getParsedSubData(\n        URLObject.searchParams.get(\"url\"), \n        context.env.EdgeSubDB, \n        URLObject.searchParams.get(\"show_host\") === \"true\",\n        JSON.parse(URLObject.searchParams.get(\"http_headers\")),\n        URLObject.searchParams.get(\"ExcludeRegExpPattern\"),\n    );\n    let Dumper = new ShareLinkDumper();\n    let ShareLinkArray = [];\n    for (let i of Proxies) {\n        if (Dumper[i.__Type]) {\n            ShareLinkArray.push(Dumper[i.__Type](i))\n        }\n    }\n    \n    // generate final response\n    let ShareLinkResponse = ShareLinkArray.join(\"\\n\");\n    if (isBase64 === true) {\n        ShareLinkResponse = btoa(ShareLinkResponse);\n    }\n\n    return new Response(ShareLinkResponse, {\n        status: 200,\n        headers: {\n            \"Content-Type\": \"text/plain, charset=utf-8\",\n            \"Content-Length\": ShareLinkResponse.length\n        }\n    })\n}\n"
  },
  {
    "path": "functions/sub/sing-box.js",
    "content": "import { getSingBoxConfig } from \"../internal/Converter/getSingBoxConfig.ts\";\nimport getParsedSubData from \"../internal/getParsedSubData.ts\";\n\nexport async function onRequest (context) {\n    const { request } = context;\n    const URLObject = new URL(request.url);\n    let { Proxies } = await getParsedSubData(\n        URLObject.searchParams.get(\"url\"), \n        context.env.EdgeSubDB, \n        URLObject.searchParams.get(\"show_host\") === \"true\",\n        JSON.parse(URLObject.searchParams.get(\"http_headers\")),\n        URLObject.searchParams.get(\"ExcludeRegExpPattern\"),\n    );\n\n    // a javascript object !!! not YAML !!!\n    let SingBoxConfigObject = await getSingBoxConfig (\n        Proxies,\n        context.env.EdgeSubDB,\n        {\n            isUDP: URLObject.searchParams.get(\"udp\") === \"true\",\n            isSSUoT: URLObject.searchParams.get(\"ss_uot\") === \"true\",\n            isInsecure: true,\n            RuleProvider: URLObject.searchParams.get(\"remote_config\") || \"__DEFAULT\",\n            RuleProvidersProxy: URLObject.searchParams.get(\"rule_providers_proxy\"),\n            BaseConfig: URLObject.searchParams.get(\"BaseConfig\"),\n            isForcedRefresh: URLObject.searchParams.get(\"forced_refresh\") === \"true\" ? true : false\n        }\n    )\n\n    // handle forced ws 0-rtt\n    if (URLObject.searchParams.get(\"forced_ws0rtt\") === \"true\") {\n        console.info(\"[Main] ForcedWS0RTT enabled.\")\n        for (let i of SingBoxConfigObject.outbounds) {\n            if (!(\"transport\" in i)) {\n                continue;\n            }\n            if (i.transport.type !== \"ws\") {\n                continue;\n            }\n            i.transport.max_early_data = 2560\n            i.transport.early_data_header_name = \"Sec-WebSocket-Protocol\"\n        }\n    }\n\n    const ResponseBody = JSON.stringify(SingBoxConfigObject)\n\n    return new Response(ResponseBody, {\n        status: 200,\n        headers: {\n            \"Content-Type\": \"application/json; charset=utf-8\",\n            \"Content-Length\": ResponseBody.length,\n        }\n    })\n}"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"edge-sub\",\n  \"type\": \"module\",\n  \"version\": \"1.0.0\",\n  \"license\": \"AGPL-3\",\n  \"author\": \"kobe-koto\",\n  \"homepage\": \"https://github.com/kobe-koto/EdgeSub\",\n  \"scripts\": {\n    \"build:frontend\": \"astro build\",\n    \"dev\": \"concurrently 'wrangler pages dev ./' 'astro dev'\",\n    \"dev:frontend\": \"astro dev\",\n    \"dev:backend\": \"wrangler pages dev ./\",\n    \"generate-types\": \"wrangler types ./types/worker-configuration.d.ts\",\n    \"type-check\": \"generate-types && tsc\"\n  },\n  \"dependencies\": {\n    \"@iconify-json/iconoir\": \"^1.2.7\",\n    \"@tailwindcss/vite\": \"^4.1.10\",\n    \"astro\": \"5.4.1\",\n    \"astro-compress\": \"^2.3.6\",\n    \"astro-icon\": \"^1.1.5\",\n    \"astro-seo\": \"^0.8.4\",\n    \"confbox\": \"^0.2.2\",\n    \"daisyui\": \"^5.0.43\",\n    \"generate-password\": \"^1.7.1\",\n    \"js-sha256\": \"^0.11.0\",\n    \"sass\": \"^1.85.1\",\n    \"tailwindcss\": \"^4.1.10\"\n  },\n  \"devDependencies\": {\n    \"concurrently\": \"^9.2.0\"\n  },\n  \"trustedDependencies\": [\n    \"@parcel/watcher\",\n    \"@tailwindcss/oxide\",\n    \"esbuild\",\n    \"sharp\"\n  ]\n}"
  },
  {
    "path": "public/basic-config/mihomo.yaml",
    "content": "auto-detect-interface: true\nlog-level: \"info\"\n\nport: 7890\nmixed-port: 7891\n\nmode: \"Rule\"\nexternal-controller: \":9090\"\n\n\ndns:\n  enable: true\n  ipv6: true\n  listen: 0.0.0.0:1053\n  cache-algorithm: arc\n  respect-rules: false\n  enhanced-mode: fake-ip\n  fake-ip-range: 198.18.0.1/16\n  fake-ip-filter-mode: blacklist\n  fake-ip-filter:\n    - '*'\n    - '.lan'\n    - lancache.steamcontent.com\n  default-nameserver:\n    - 119.29.29.29\n    - 223.5.5.5\n  nameserver:\n    - https://doh.pub/dns-query\n    - https://dns.alidns.com/dns-query\n  direct-nameserver:\n    - https://doh.pub/dns-query\n    - https://dns.alidns.com/dns-query\n  fallback:\n    - https://dns.google/dns-query\n    - https://cloudflare-dns.com/dns-query\n  fallback-filter:\n    geoip: true\n    geoip-code: CN\n    ipcidr:\n      - 240.0.0.0/4\n      - 0.0.0.0/24\n      - 127.0.0.1/24\n"
  },
  {
    "path": "public/basic-config/sing-box.jsonc",
    "content": "{\n    \"log\": {\n        \"disabled\": false,\n        \"level\": \"info\"\n    },\n    \"dns\": {\n        \"servers\": [\n            {\n                \"tag\": \"hosts\",\n                \"type\": \"hosts\"\n            },\n            {\n                \"tag\": \"google\",\n                \"type\": \"tls\",\n                \"server\": \"8.8.8.8\"\n            },\n            {\n                \"tag\": \"local\",\n                \"type\": \"udp\",\n                \"server\": \"223.5.5.5\"\n            },\n            {\n                \"tag\": \"remote\",\n                \"type\": \"fakeip\",\n                \"inet4_range\": \"198.18.0.0/15\",\n                \"inet6_range\": \"fc00::/18\"\n            }\n        ],\n        \"rules\": [\n            {\n                \"ip_accept_any\": true,\n                \"action\": \"route\",\n                \"server\": \"hosts\"\n            },\n            {\n                \"query_type\": [\n                \"A\",\n                \"AAAA\"\n                ],\n                \"server\": \"remote\"\n            }\n        ],\n        \"independent_cache\": true\n    },\n\n    \"inbounds\": [\n        {\n            \"type\": \"mixed\",\n            \"tag\": \"mixed-in\",\n            \"listen\": \"127.0.0.1\",\n            \"listen_port\": 7890\n        },\n        {\n            \"type\": \"tun\",\n            \"tag\": \"tun-in\",\n            \"address\": [\n                \"172.19.0.1/30\",\n                \"fdfe:dcba:9876::1/126\"\n            ],\n            \"auto_route\": true\n        }\n    ],\n    \"experimental\": {\n        \"clash_api\": {\n            \"external_controller\": \"127.0.0.1:9090\",\n            \"external_ui\": \"ui\",\n            \"secret\": \"\",\n            \"external_ui_download_url\": \"https://github.com/MetaCubeX/metacubexd/archive/refs/heads/gh-pages.zip\",\n            \"external_ui_download_detour\": \"DIRECT\",\n            \"default_mode\": \"rule\"\n        },\n        \"cache_file\": {\n            \"enabled\": true,\n            \"store_fakeip\": false\n        }\n    },\n    \"outbounds\": [\n        {\n            \"type\": \"direct\",\n            \"tag\": \"DIRECT\"\n        }, {\n            \"type\": \"block\",\n            \"tag\": \"REJECT\"\n        }\n    ],\n    \"route\": {\n        \"rules\": [\n            {\n                \"action\": \"sniff\"\n            }, {\n                \"protocol\": \"dns\",\n                \"action\": \"hijack-dns\"\n            }, {\n                \"ip_is_private\": true,\n                \"outbound\": \"direct\"\n            }, {\n                \"clash_mode\": \"direct\",\n                \"outbound\": \"DIRECT\"\n            }, {\n                \"clash_mode\": \"global\",\n                \"outbound\": \"GLOBAL\"\n            }\n        ],\n        \"rule_set\": [],\n        \"geosite\": {\n            \"download_detour\": \"DIRECT\"\n        },\n        \"geoip\": {\n            \"download_detour\": \"DIRECT\"\n        },\n        \"default_domain_resolver\": \"local\",\n        \"auto_detect_interface\": true\n    }\n}\n"
  },
  {
    "path": "public/minimal_remote_rules.ini",
    "content": ";https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini\n\n[custom]\nruleset=Proxies,[]DOMAIN-SUFFIX,googleapis.cn\nruleset=CN-Directed,[]GEOIP,CN\nruleset=CN-Directed,[]GEOSITE,CN\nruleset=Proxies,[]MATCH\n\ncustom_proxy_group=Proxies`select`[]DIRECT`[]REJECT`.*\ncustom_proxy_group=CN-Directed`select`[]DIRECT`[]REJECT`[]Proxies\n"
  },
  {
    "path": "readme.md",
    "content": "# Edge Sub\n\n在 CloudFlare 的全球網絡上轉換您的代理訂閱.\n\n請為我點一個 ⭐ Star!\n\n## 使用方式\n\n- ### UI\n  \n  在 Cloudflare Pages 部署後打開，並按提示操作。\n\n- ### Debug\n\n  > **⚠️ Warning**\n  > \n  > 該格式隨時可能發生變更, 僅供測試用途\n\n  Endpoint: `/sub/debug`\n\n  需要以下參數:\n\n  - `url`: 輸入的訂閱的遠程位址\n\n## 部署\n\n- ### 在 Cloudflare Pages 上部署\n\n  0. Fork 本項目\n  1. 打開 dash.cloudflare.com\n  2. 轉到側邊欄上的 **Workers & Pages** (Overview) 部分\n  3. 按下 **Create** 按鈕\n  4. 切換到 **Pages** 欄\n  5. 按 **Connect to Git**\n  6. 選擇你剛 Fork 下來的 EdgeSub 項目\n  7. 在 **Build settings > Framework preset** 中選擇 Astro\n  8. 編輯 **Build settings > Build command** 為 `pnpm build:frontend`\n  9. 按下 **Save and Deploy**\n  10. 部署完成後，你可能需要添加自訂網域，請前往 **項目 > Custom domains** 添加\n  \n  #### ✡️ 可選 - 為遠端規則添加緩存以加快處理速度:\n  \n  **需要注意的是，開發時會以假設緩存 KV 存在來開發，無緩存 KV 環境將作為低優先級來開發。**\n  \n  **因此，不添加緩存 KV 是不被推薦的行為。**\n  \n  1. 轉到 **Workers & Pages > KV**\n  2. 按 **Create a namespacce**，**輸入任意名字**，然後按 **Add**\n  3. 回到項目\n  4. 轉到 **Settings > Functions >  KV namespace bindings**\n  5. 按 **Add binding**\n  6. 在 **Variable name** 填寫 `EdgeSubDB`，**KV namespace** 選擇你剛建立的 KV 空間\n  7. 點按 **Save**\n  8. 轉到**項目 > Deployments**\n  9. 在 **All deployments** 中找到最近的一個 Deployment，然後點**右側三個點 > Retry Deployment**\n  10. 完成\n\n\n## 相容性表格\n\n- 節點類型\n\n  | 類型         | 支援 | 已經測試 | Notes                                 |\n  | ------------ | ---- | -------- | ------------------------------------- |\n  | HTTP         | 🗿  | 🚫        | 由於與 **遠端訂閱** 不相容, 請勿直接傳入 HTTP Proxy |\n  | Socks 5      | ✅    | 🚫        |                                       |\n  | Hysteria 1   | ✅    | ✅        |                                       |\n  | Hysteria 2   | ✅    | ✅        |                                       |\n  | TUIC v5      | ✅    | ✅        |                                       |\n  | Vmess        | ✅    | ☑️        | 未經完全測試                          |\n  | Vless        | ✅    | ☑️        | 未經完全測試                          |\n  | Shadowsocks  | ✅    | ✅        |  |\n  | Trojan       | ✅    | ✅        |                                    |\n  | WireGuard    | 🚫    | -        | 似乎沒有通用的 ShareLink 格式         |\n  | ShadowsocksR | 🚫    | -        | 暫無計劃實現                          |\n  | SSH          | 🚫    | -        | 暫無計劃實現                          |\n\n- 訂閱類型\n\n  | 類型                    | 輸入 | 輸出 | 輸出 Endpoint     |\n  | ----------------------- | ---- | ---- | ----------------- |\n  | 內部除錯用格式          | 🚫    | ✅    | `/sub/debug`      |\n  | ShareLink 集合          | ✅    | ✅    | `/sub/share-link` |\n  | ShareLink 集合 (Base64) | ✅    | ✅    | `/sub/base64`     |\n  | Clash Meta 配置         | ✅    | ✅    | `/sub/clash-meta` |\n  | Sing-Box 配置           | ✅    | ✅    | `/sub/sing-box`   |\n\n  Notes:\n  \n  - Legacy Clash config support has been dropped at `Commit 13df326`\n  \n  - **內部除錯用格式**: \n  \n    僅供除錯, 將會在未來的任意某個時間點做出破壞性改動或刪除.\n\n## Remote Rules Parsing\n\n**ONLY** support .ini with `ruleset=` `custom_proxy_group=` and comments.\n\n### Special Remote Rules\n\n- `Sing_PROTOCOL` see https://sing-box.sagernet.org/configuration/route/sniff/\n\n## Handling Traffic and Name Information\n\n**Note: This section's behavior description applies specifically to Clash Meta Config.**\n\nThis section describes how `traffic` and `name` information is processed from incoming data.\n\n1.  **Data Parsing:**\n    The `decodeURIComponent`-decoded URL (or \"subdata\") is parsed line by line. Each non-empty and valid line is treated as either a `Subscription` or a `Proxy`.\n    \n    *   A `Subscription` object may contain a `SubscriptionUserInfo` attribute.\n    *   A `Proxy` object does not contain `SubscriptionUserInfo`.\n    *   The `SubscriptionUserInfo` attribute, if present, contains `traffic` and `name` fields. Both `traffic` and `name` can be empty or absent within `SubscriptionUserInfo`.\n    \n2.  **Name Processing and Display:**\n    Names that are extracted and considered \"visible\" (i.e., non-empty) are aggregated for display. If multiple visible names exist, they will be presented in a summarized format, for example: `Name1, Name2, and <N> more` (where `<N>` represents the count of additional subscriptions and proxies with visible names).\n\n    *Note: A `name` might not be explicitly present or might be empty within a `SubscriptionUserInfo` object, even if `SubscriptionUserInfo` itself exists.*\n\n3.  **Traffic Data Handling:**\n    Traffic data is processed based on the number of unique \"visible\" names found:\n    \n    *   If only **one** visible `name` is identified across all parsed Subscriptions and Proxies, the first available `traffic` value will be displayed or passed through. The **order in which the lines are parsed** determines which `traffic` value is considered \"first.\"\n    *   If **more than one** visible `name` is identified, traffic data will be ignored.\n\n## Subscription Requesting\n\nWhen requesting subscriptions based on user-provided data, the following HTTP headers are used:\n\n1.  **Default HTTP Headers:**\n    The application sends a set of default HTTP headers, as defined in `/functions/internal/configs.ts`. These include:\n    \n    ```json\n    {\n        \"Accept\": \"*/*\",\n        \"User-Agent\": \"EdgeSub-git/0.0.0 (Prefer ClashMeta / Mihomo Format)\"\n    }\n    ```\n    \n2.  **User-Provided HTTP Headers:**\n    Users can provide additional HTTP headers. The processing of these headers is as follows:\n    \n    *   Any non-empty and valid user-provided header that shares a key with a default HTTP header will **overwrite** the corresponding default header.\n    *   Any non-conflicting user-provided headers (i.e., those with unique keys not present in the default set) will be **appended** to the request.\n\n## Shorter Feature Security Overview\n\nShorts data is **stored remotely** is **unencrypted**.\n\n*   Each short is uniquely identified by a **Short ID**.\n*   **Short IDs** provide **read-only access** to a specific short.\n*   A corresponding **Short Token** grants **write access** to a specific short. These tokens are for access control only and are **not encryption keys**.\n\nThe **Shorter Admin Password** allows viewing all Short IDs. If this password is forgotten, you will need to delete the \"admin-password\" key in the KV database and then setting a new one.\n"
  },
  {
    "path": "src/components/NavBar.astro",
    "content": "---\nimport { Icon } from \"astro-icon/components\";\n---\n\n<div class=\"navbar bg-base-100 shadow-sm mx-auto max-w-5xl rounded-b-box\">\n    <div class=\"flex-1\">\n        <a class=\"btn btn-ghost text-xl\" href=\"/\">EdgeSub</a>\n    </div>\n    <div class=\"flex-none\">\n        <ul class=\"menu menu-horizontal px-1\">\n            <li>\n                <details>\n                    <summary><Icon name=\"iconoir:compress-lines\" /> Shorter</summary>\n                    <ul class=\"bg-base-100 rounded-t-none p-2\">\n                        <li><a href=\"/shorter/create/\">\n                            <Icon class=\"inline\" name=\"iconoir:add-circle\" />\n                            <span>Create</span>\n                        </a></li>\n                        <li><a href=\"/shorter/edit/\">\n                            <Icon class=\"inline\" name=\"iconoir:edit\" />\n                            <span>Edit</span>\n                        </a></li>\n                        <li><a href=\"/shorter/destory/\">\n                            <Icon class=\"inline\" name=\"iconoir:trash\" />\n                            <span>Delete</span>\n                        </a></li>\n                        <li><a href=\"/shorter/reset-token/\">\n                            <Icon class=\"inline\" name=\"iconoir:refresh-double\" />\n                            <span>Reset Token</span>\n                        </a></li>\n                        <li><a href=\"/shorter/list/\">\n                            <Icon class=\"inline\" name=\"iconoir:list\" />\n                            <span>List</span>\n                        </a></li>\n                        <li><a href=\"/shorter/admin/\">\n                            <Icon class=\"inline\" name=\"iconoir:plus\" />\n                            <span>Admin</span>\n                        </a></li>\n                    </ul>\n                </details>\n            </li>\n\n            <li>\n                <a\n                    title=\"GitHub Project\"\n                    href=\"https://github.com/kobe-koto/EdgeSub\"\n                    >\n                    <Icon name=\"iconoir:github\" /> GitHub\n                </a>\n            </li>\n        </ul>\n    </div>\n</div>\n"
  },
  {
    "path": "src/components/backendIndicator.astro",
    "content": "---\nimport { Icon } from \"astro-icon/components\";\n---\n\n<div role=\"alert\" class=\"alert bg-base-300 my-4\">\n    <Icon name=\"iconoir:info-circle\" />\n    <span>\n        Current backend: \n        <code id=\"backend\">\n            <span class=\"skeleton h-6 w-28 inline-block align-[-0.45rem] ml-1\"></span>\n        </code>\n    </span>\n</div>\n\n<script>\n    addEventListener(\"DOMContentLoaded\", () => {\n        const backendIndicator = document.querySelector(\"#backend\") as HTMLElement;\n        backendIndicator.innerText = document.body.dataset.defaultBackend;\n    });\n</script>\n"
  },
  {
    "path": "src/components/data-input.astro",
    "content": "---\nimport type { DropdownItemPrototype } from \"@components/k-dropdown.astro\";\nimport KDropdown from \"@components/k-dropdown.astro\";\n\ninterface Props {\n    slug: string;\n    desc: string;\n    detail?: string;\n    optional?: boolean;\n    type: \"input\" | \"textarea\" | \"k-dropdown\" | \"toggle\";\n    DropdownDefault?: DropdownItemPrototype;\n    DropdownItems?: DropdownItemPrototype[];\n    SwitchDefault?: boolean;\n}\n\nconst { \n    slug, \n    desc, \n    detail = \"<暂未设定 detail 属性>\", \n    type,\n    optional = false,\n    DropdownDefault, \n    DropdownItems, \n    SwitchDefault = false,\n} = Astro.props;\n---\n\n<data-input id={slug} data-type={type}>\n\n    <!-- <label class=\"fieldset-legend\">{desc}</label> -->\n\n    { type === \"input\" && (\n        <fieldset class=\"fieldset\">\n            <legend class=\"fieldset-legend\">\n                {desc}\n                { optional && <span class=\"label\">可选</span> }\n            </legend>\n            <input type=\"text\" class=\"input\" placeholder={detail} />\n        </fieldset>\n    ) }\n\n    { type === \"textarea\" && (\n        <label class=\"fieldset-legend\">\n            {desc}\n            { optional && <span class=\"label\">可选</span> }\n        </label>\n        <textarea class=\"textarea h-24 w-full p-4\" placeholder={detail} />\n    ) }\n\n    { type === \"k-dropdown\" && (\n        <label class=\"fieldset-legend\">{desc}</label>\n        <KDropdown \n            Default={DropdownDefault} \n            Items={DropdownItems}\n        />\n    ) }\n\n    { type === \"toggle\" && (\n        <fieldset class=\"fieldset bg-base-100 border-base-300 rounded-box w-64 border p-4\">\n            <legend class=\"fieldset-legend\">{desc}</legend>\n            <label class=\"label\">\n                <input type=\"checkbox\" checked={SwitchDefault ? \"checked\" : \"\"} class=\"toggle\" />\n                {detail}\n            </label>\n        </fieldset>\n    ) }\n    \n</data-input>\n\n<script src=\"@scripts/components/data-input\"></script>\n<!-- \n<style lang=\"scss\">\n    data-input {\n        margin: 12px 0;\n    }\n</style> -->\n"
  },
  {
    "path": "src/components/index/SubURLGenerator.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\nimport type { DropdownItemPrototype } from \"@components/k-dropdown.astro\";\nimport { RuleProviders } from \"@config/RuleProviders\";\nimport { Endpoints } from \"@config/AvalibleOptoutFormat.js\"\n---\n\n<k-suburl-generator data-endpoints={JSON.stringify(Endpoints)} class=\"flex-contents\">\n    <h1 class=\"text-2xl font-bold\">EdgeSub 订阅转换</h1>\n    <div role=\"alert\" class=\"alert bg-base-300 my-4\">\n        <Icon name=\"iconoir:info-circle\" />\n        <span>\n            如果实例并非您自己的，请谨慎使用。<br />\n            您输入的所有数据将<b>在请求订阅时进行远程处理</b>。<br />\n            与 Shorter 功能相关的数据将<b>以非加密形式远程存储</b>，并且 Short Token 仅用于访问控制，而非加密密码。<br />\n            <b>我们建议您按照 GitHub 上的文档进行自行部署。</b>\n        </span>\n    </div>\n    <DataInput\n        slug=\"SubURL\"\n        desc=\"订阅链接\"\n        detail=\"仅支持 http(s):// 和 short: 开头的订阅链接, 类似于 vless:// 开头的分享链接。以换行分割。\"\n        type=\"textarea\"\n    />\n    <DataInput\n        slug=\"Endpoint\"\n        desc=\"输出格式\"\n        type=\"k-dropdown\"\n        DropdownDefault={{ key: \"Clash Meta (默认)\", value: \"/sub/clash-meta\" }}\n        DropdownItems={Endpoints as DropdownItemPrototype[]}\n    />\n\n    \n    <DataInput\n        slug=\"RuleProvider\"\n        desc=\"远程配置 (Rule Providers)\"\n        type=\"k-dropdown\"\n        DropdownDefault={{ key: \"最小配置 (默认)\", value: \"__DEFAULT\" }}\n        DropdownItems={RuleProviders as DropdownItemPrototype[]}\n    />\n\n\n    <h2 class=\"text-lg font-bold\">高级选项</h2>\n    <div class=\"flex flex-row gap-2 flex-wrap\">\n        <DataInput\n            slug=\"RuleProvidersProxy\"\n            desc=\"让 EdgeSub 缓存和代理 Rule Providers\"\n            detail=\"对于 Sing-Box 始终为 true\"\n            type=\"toggle\"\n            SwitchDefault={true}\n        />\n        <DataInput\n            slug=\"isUDP\"\n            desc=\"开启 UDP\"\n            detail=\"在配置中开启原生 UDP 支持\"\n            type=\"toggle\"\n            SwitchDefault={true}\n        />\n        <DataInput\n            slug=\"isSSUoT\"\n            desc=\"开启 SS UoT\"\n            detail=\"仅对 Shadowsocks 开启 UDP over TCP 支持. 不可与原生 UDP 同时开启.\"\n            type=\"toggle\"\n            SwitchDefault={false}\n        />\n        <DataInput\n            slug=\"isShowHost\"\n            desc=\"在节点名称后添加 Host 字段\"\n            detail=\"不知道的别开\"\n            type=\"toggle\"\n            SwitchDefault={false}\n        />\n        <DataInput\n            slug=\"ForcedWS0RTT\"\n            desc=\"强制打开 WS 0-RTT\"\n            detail=\"强制打开 WebSocket 0-RTT 支持, 可能会导致部分节点无法连接.\"\n            type=\"toggle\"\n            SwitchDefault={false}\n        />\n        <DataInput\n            slug=\"Backend\"\n            desc=\"后端地址\"\n            detail=\"默认为当前站点\"\n            type=\"input\"\n            optional={true}\n        />\n        <DataInput\n            slug=\"RuleProviderUserspec\"\n            desc=\"自订远程配置 (将覆写已选择的远程配置)\"\n            detail=\"仅不完善地支持 ini 格式\"\n            type=\"input\"\n            optional={true}\n        />\n        <DataInput\n            slug=\"BaseConfig\"\n            desc=\"Custom Base Config URL\"\n            detail=\"JSON(C|5) for Sing-Box, YAML for Mihomo\"\n            type=\"textarea\"\n            optional={true}\n        />\n    </div>\n\n\n\n    <DataInput\n        slug=\"ExcludeRegExpPattern\"\n        desc=\"Custom RegExp Pattern to Exclude\"\n        detail=\"Any outbound name matched with this RegExp Pattern will be ignored. This pattern is case-sensitive, and global mode only\"\n        type=\"textarea\"\n        optional={true}\n    />\n\n    <DataInput\n        slug=\"HTTPHeaders\"\n        desc=\"HTTP Headers\"\n        detail=\"请求远端订阅位址时使用的 HTTP Headers, 请务必使用 JSON 格式书写.\"\n        type=\"textarea\"\n    />\n    \n    <div class=\"divider\"></div>\n\n    <div class=\"mockup-code w-full\">\n        <pre data-prefix=\"~\"><code>https://OpenWrt.lan/luci/123\" OR \"\"==\" </code></pre>\n    </div>\n\n    <div class=\"flex gap-4\">\n        <button class=\"btn\" id=\"generate\"><Icon name=\"iconoir:refresh-circle\" />  Generate</button>\n        <button class=\"btn\" id=\"copy\"><Icon name=\"iconoir:copy\" />  Copy</button>\n    </div>\n\n</k-suburl-generator>\n\n<script src=\"@scripts/components/k-suburl-generator.ts\"></script>\n\n<style lang=\"scss\">\n    .botton-con {\n        display: flex;\n        gap: 8px;\n    }\n</style>"
  },
  {
    "path": "src/components/k-dropdown.astro",
    "content": "---\nimport { Icon } from \"astro-icon/components\";\n\nexport type DropdownItemPrototype = { key: string; value: string };\n\ninterface Props {\n    Items: DropdownItemPrototype[];\n    Default?: DropdownItemPrototype;\n}\nconst {\n    Items,\n    Default = {\n        key: \"还未选择\",\n        value: \"__NULL__\",\n    },\n} = Astro.props;\n---\n\n<k-dropdown class=\"dropdown\" data-selected-value={Default.value}>\n    <div tabindex=\"0\" role=\"button\" class=\"btn m-1\">\n        <span>{Default.key}</span>\n        <Icon name=\"iconoir:arrow-down-tag\" />\n    </div>\n\n    <ul\n        tabindex=\"0\"\n        class=\"dropdown-content menu bg-base-100 rounded-box z-1 w-52 p-2 shadow-sm\"\n    >\n        {\n            Items.map((i) => {\n                return (\n                    <li>\n                        <a data-value={i.value}>{i.key}</a>\n                    </li>\n                );\n            })\n        }\n    </ul>\n</k-dropdown>\n\n<script src=\"@scripts/components/k-dropdown\"></script>\n"
  },
  {
    "path": "src/components/layouts/SEOComponent.astro",
    "content": "---\nimport { SEO } from \"astro-seo\";\n\ninterface Props {\n    Title?: string;\n    Desc?: string;\n    noindex?: boolean;\n}\nconst { \n    Title = \"EdgeSub\",\n    Desc = \"A proxy toolchain config converter, KISS and privacy on.\",\n    noindex = false \n} = Astro.props;\n---\n\n<SEO\n    title={Title}\n    noindex={noindex}\n    nofollow={noindex}\n    description={Desc}\n    charset=\"UTF-8\"\n    extend={{\n        link: [\n            { rel: \"sitemap\", href: \"/sitemap-index.xml\" },\n            { rel: \"icon\", type: \"image/png\", href: \"/favicon.svg\" },\n        ],\n        meta: [\n            { name: \"viewport\", content: \"width=device-width\" },\n            { name: \"author\", content: \"EdgeSub Project\" },\n        ]\n    }}\n    openGraph={{\n        basic: {\n            type: \"website\",\n            title: Title,\n            image: \"/favicon.svg\"\n        },\n        optional: {\n            description: Desc,\n            siteName: Title,\n        }\n    }}\n/>\n\n"
  },
  {
    "path": "src/components/shorter/k-shorter.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<k-shorter class=\"flex-contents\">\n    <DataInput\n        slug=\"SubURL\"\n        desc=\"订阅链接\"\n        detail=\"仅支持 http(s):// 和 short: 开头的订阅链接, 类似于 vless:// 开头的分享链接。以换行分割。\"\n        type=\"textarea\"\n    />\n\n    <div class=\"flex flex-row gap-2 flex-wrap\">\n        <DataInput\n            slug=\"short-slug\"\n            desc=\"Short ID\"\n            detail=\"默认随机\"\n            type=\"input\"\n        />\n        <DataInput\n            slug=\"short-token\"\n            desc=\"Short Token\"\n            detail=\"默认随机\"\n            type=\"input\"\n        />\n    </div>\n\n    <div class=\"mockup-code w-full my-2\">\n        <pre data-prefix=\"~\"><code>请先提交</code></pre>\n    </div>\n\n    <p>可将以上内容作为本程式内专用的 订阅链接</p>\n\n    <div class=\"flex gap-4\">\n        <button class=\"btn\" id=\"shorter\">\n            <label class=\"swap swap-rotate\">\n                <div class=\"swap-on\">\n                    <!-- loading -->\n                    <span class=\"loading loading-spinner loading-md\"></span>\n                </div>\n                <div class=\"swap-off\">\n                    <!-- not loading -->\n                    <Icon name=\"iconoir:send\" class=\"text-xl inline\" />\n                </div>\n            </label>\n            <span>Submit</span>\n        </button>\n\n        <button class=\"btn\" id=\"copy\">\n            <Icon name=\"iconoir:copy\" />\n            <span>Copy</span>\n        </button>\n    </div>\n</k-shorter>\n\n<script src=\"@scripts/components/shorter/k-shorter\"></script>\n"
  },
  {
    "path": "src/components/shorter/short-destroyer.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<short-destroyer class=\"flex-contents\">\n    <DataInput slug=\"slug\" desc=\"Short ID\" detail=\"Short ID\" type=\"input\" />\n    <DataInput slug=\"token\" desc=\"token\" detail=\"Short token\" type=\"input\" />\n\n    <div class=\"mockup-code w-full my-2\">\n        <pre data-prefix=\"~\"><code>请先提交</code></pre>\n    </div>\n\n    <button class=\"btn\" id=\"submit\">\n        <label class=\"swap swap-rotate\">\n            <div class=\"swap-on\">\n                <!-- loading -->\n                <span class=\"loading loading-spinner loading-md\"></span>\n            </div>\n            <div class=\"swap-off\">\n                <!-- not loading -->\n                <Icon name=\"iconoir:send\" class=\"text-xl inline\" />\n            </div>\n        </label>\n        <span>Submit</span>\n    </button>\n</short-destroyer>\n\n<script src=\"@scripts/components/shorter/short-destroyer.ts\"></script>\n"
  },
  {
    "path": "src/components/shorter/short-editor.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<short-editor class=\"flex-contents\">\n    <DataInput\n        slug=\"short-id\"\n        desc=\"Short ID\"\n        detail=\"Short ID\"\n        type=\"input\"\n    />\n    <button class=\"btn\" id=\"editor-fetch\">\n        <label class=\"swap swap-rotate\">\n            <div class=\"swap-on\">\n                <!-- loading -->\n                <span class=\"loading loading-spinner loading-md\"></span>\n            </div>\n            <div class=\"swap-off\">\n                <!-- not loading -->\n                <Icon name=\"iconoir:send\" class=\"text-xl inline\" />\n            </div>\n        </label>\n        <span>Fetch</span>\n    </button>\n    <DataInput\n        slug=\"short-data\"\n        desc=\"订阅链接\"\n        detail=\"请先拉取数据。仅支持 http(s):// 或 short: 开头的订阅链接、类似于 vless:// 开头的分享链接。以换行分割。\"\n        type=\"textarea\"\n    />\n    <DataInput\n        slug=\"short-password\"\n        desc=\"Short password\"\n        detail=\"Short password\"\n        type=\"input\"\n    />\n\n    <div class=\"mockup-code w-full my-2\">\n        <pre data-prefix=\"~\"><code>请先提交</code></pre>\n    </div>\n    <p>可将以上内容作为本程式内专用的 订阅链接</p>\n\n    <button class=\"btn\" id=\"editor-submit\">\n        <label class=\"swap swap-rotate\">\n            <div class=\"swap-on\">\n                <!-- loading -->\n                <span class=\"loading loading-spinner loading-md\"></span>\n            </div>\n            <div class=\"swap-off\">\n                <!-- not loading -->\n                <Icon name=\"iconoir:send\" class=\"text-xl inline\" />\n            </div>\n        </label>\n        <span>Submit</span>\n    </button>\n\n</short-editor>\n\n<script src=\"@scripts/components/shorter/short-editor.ts\"></script>\n"
  },
  {
    "path": "src/components/shorter/short-token-reset.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<short-token-reset class=\"flex-contents\">\n    <DataInput\n        slug=\"slug\"\n        desc=\"Short ID\"\n        detail=\"Short ID\"\n        type=\"input\"\n    />\n    <DataInput\n        slug=\"old-token\"\n        desc=\"Old Token\"\n        detail=\"OLD Short token\"\n        type=\"input\"\n    />\n    <DataInput\n        slug=\"new-token\"\n        desc=\"New Token\"\n        detail=\"NEW Short token\"\n        type=\"input\"\n    />\n    \n    <div class=\"mockup-code w-full my-2\">\n        <pre data-prefix=\"~\"><code>请先提交</code></pre>\n    </div>\n\n    <button class=\"btn\" id=\"submit\">\n        <label class=\"swap swap-rotate\">\n            <div class=\"swap-on\">\n                <!-- loading -->\n                <span class=\"loading loading-spinner loading-md\"></span>\n            </div>\n            <div class=\"swap-off\">\n                <!-- not loading -->\n                <Icon name=\"iconoir:send\" class=\"text-xl inline\" />\n            </div>\n        </label>\n        <span>Submit</span>\n    </button>\n\n</short-token-reset>\n\n<script src=\"@scripts/components/shorter/short-token-reset.ts\"></script>\n"
  },
  {
    "path": "src/components/shorter/shorter-list.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<shorter-list class=\"flex-contents\">\n    <DataInput\n        slug=\"password\"\n        desc=\"Admin password\"\n        detail=\"Admin password\"\n        type=\"input\"\n    />\n\n    <button class=\"btn\" id=\"list-submit\">\n        <label class=\"swap swap-rotate\">\n            <div class=\"swap-on\">\n                <!-- loading -->\n                <span class=\"loading loading-spinner loading-md\"></span>\n            </div>\n            <div class=\"swap-off\">\n                <!-- not loading -->\n                <Icon name=\"iconoir:send-diagonal\" class=\"text-xl inline\" />\n            </div>\n        </label>\n        <span>Fetch</span>\n    </button>\n\n    <div id=\"list-items\" class=\"flex flex-row flex-wrap gap-4 justify-center\">\n        <list-item class=\"hidden\">\n            <div class=\"card bg-neutral text-neutral-content w-96\">\n                <div class=\"card-body items-center text-center\">\n                    <p>\n                        <Icon class=\"inline\" name=\"iconoir:info-circle\" /> Short\n                        ID: <code class=\"item-id\">cry_me_a_r1ver</code>\n                    </p>\n                    <p>\n                        <Icon class=\"inline\" name=\"iconoir:edit\" /> Last modified:\n                        <span class=\"item-date\">11011111101010010</span>\n                    </p>\n\n                    <div class=\"card-actions justify-end\">\n                        <button class=\"btn item-edit\">\n                            <Icon name=\"iconoir:edit\" /> Edit\n                        </button>\n                        <button class=\"btn item-copy\">\n                            <Icon name=\"iconoir:copy\" /> Copy ID\n                        </button>\n                    </div>\n                </div>\n            </div>\n        </list-item>\n    </div>\n</shorter-list>\n\n<script src=\"@scripts/components/shorter/shorter-list\"></script>"
  },
  {
    "path": "src/components/shorter/shorter-password.astro",
    "content": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<shorter-password class=\"flex-contents\">\n    <DataInput\n        slug=\"old-password\"\n        desc=\"Old admin password\"\n        detail=\"Old admin password (leave it empty if 'Password undefined')\"\n        type=\"input\"\n    />\n    <DataInput\n        slug=\"new-password\"\n        desc=\"New admin password\"\n        detail=\"New admin password\"\n        type=\"input\"\n    />\n\n    <div class=\"mockup-code w-full my-2\">\n        <pre data-prefix=\"~\"><code>请先提交</code></pre>\n    </div>\n\n    <button class=\"btn\" id=\"password-submit\">\n        <label class=\"swap swap-rotate\">\n            <div class=\"swap-on\">\n                <!-- loading -->\n                <span class=\"loading loading-spinner loading-md\"></span>\n            </div>\n            <div class=\"swap-off\">\n                <!-- not loading -->\n                <Icon name=\"iconoir:send\" class=\"text-xl inline\" />\n            </div>\n        </label>\n        <span>Submit</span>\n    </button>\n\n</shorter-password>\n\n<script src=\"@scripts/components/shorter/shorter-password.ts\"></script>\n"
  },
  {
    "path": "src/config/AvalibleOptoutFormat.ts",
    "content": "import { readdirSync } from \"node:fs\";\nexport type EndpointExtendConfigPrototype = \"RuleProvider\" | \"RuleProvidersProxy\" | \"BaseConfig\" | \"isUDP\" | \"isSSUoT\" | \"RuleProviderUserspec\" | \"ForcedWS0RTT\"\n\nexport type EndpointPrototype = {\n    key: string;\n    value: string;\n    ExtendConfig?: EndpointExtendConfigPrototype[]\n}\n\nconst AvalibleEndpoints: EndpointPrototype[] = [\n    {\n        key: \"Sing Box\",\n        value: \"/sub/sing-box\",\n        ExtendConfig: [\"RuleProvider\", \"RuleProviderUserspec\", \"RuleProvidersProxy\", \"BaseConfig\", \"isUDP\", \"isSSUoT\", \"ForcedWS0RTT\"]\n    },\n    {\n        key: \"Clash Meta\",\n        value: \"/sub/clash-meta\",\n        ExtendConfig: [\"RuleProvider\", \"RuleProviderUserspec\", \"RuleProvidersProxy\", \"BaseConfig\", \"isUDP\", \"isSSUoT\", \"ForcedWS0RTT\"]\n    },\n    {\n        key: \"Base 64\",\n        value: \"/sub/base64\"\n    },\n    {\n        key: \"Share Link 集合\",\n        value: \"/sub/share-link\"\n    }\n]\n\nconst AvalibleEndpointsPath = AvalibleEndpoints.map(i => i.value);\nconst TestingEndpointsPath = readdirSync(\"./functions/sub/\").map(i => `/sub/${i.replace(/\\.js$/, \"\")}`).filter(i => !AvalibleEndpointsPath.includes(i));\nlet TestingEndpoints: EndpointPrototype[] = [];\nfor (let i of TestingEndpointsPath) {\n    TestingEndpoints.push({\n        key: `${i} (Experimental)`,\n        value: i\n    })\n}\n\nexport const Endpoints: EndpointPrototype[] = [...AvalibleEndpoints, ...TestingEndpoints]\n"
  },
  {
    "path": "src/config/RuleProviders.ts",
    "content": "type RuleProvider = {\n    key: string;\n    value: string | URL;\n}\n\nexport const RuleProviders: RuleProvider[] = [\n    {\n        key: \"最小配置\", \n        value: \"__DEFAULT\"\n    },\n    {\n        key: \"ACL_默认版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini\"\n    },\n    {\n        key: \"ACL_无测速版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoAuto.ini\"\n    },\n    {\n        key: \"ACL_去广告版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_AdblockPlus.ini\"\n    },\n    {\n        key: \"ACL_多国家版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_MultiCountry.ini\"\n    },\n    {\n        key: \"ACL_无Reject版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoReject.ini\"\n    },\n    {\n        key: \"ACL_无测速精简版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_NoAuto.ini\"\n    },\n    {\n        key: \"ACL_全分组版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full.ini\"\n    },\n    {\n        key: \"ACL_全分组谷歌版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Google.ini\"\n    },\n    {\n        key: \"ACL_全分组多模式版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_MultiMode.ini\"\n    },\n    {\n        key: \"ACL_全分组奈飞版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Netflix.ini\"\n    },\n    {\n        key: \"ACL_精简版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini.ini\"\n    },\n    {\n        key: \"ACL_去广告精简版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_AdblockPlus.ini\"\n    },\n    {\n        key: \"ACL_Fallback精简版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_Fallback.ini\"\n    },\n    {\n        key: \"ACL_多国家精简版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiCountry.ini\"\n    },\n    {\n        key: \"ACL_多模式精简版\",\n        value: \"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiMode.ini\"\n    }\n];\n"
  },
  {
    "path": "src/env.d.ts",
    "content": "/// <reference path=\"../.astro/types.d.ts\" />\n/// <reference types=\"astro/client\" />"
  },
  {
    "path": "src/layouts/base.astro",
    "content": "---\nimport \"@styles/import.css\";\nimport SEOComponent from \"@components/layouts/SEOComponent.astro\";\ninterface Props {\n\tnoindex?: boolean;\n}\nconst { noindex = false } = Astro.props;\n//import \"@styles/main.scss\";\n//import \"@styles/index.scss\";\n\nimport NavBar from \"@components/NavBar.astro\";\n---\n\n<html lang=\"en\" data-theme=\"Light Mint\" class=\"bg-base-200\">\n\t<head>\n\t\t<SEOComponent noindex={noindex} />\n\t</head>\n\t<body>\n\t\t<NavBar />\n\n\t\t<div class=\"my-8 mx-auto max-w-5xl px-6\">\n\t\t\t<div class=\"main-card\">\n\t\t\t\t<div class=\"contents\">\n\t\t\t\t\t<slot />\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t</body>\n</html>\n\n\n<script>\n    // update the backend\n    import { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n    document.body.dataset.defaultBackend = getDefaultBackend();\n</script>\n"
  },
  {
    "path": "src/pages/index.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\n\nimport SubURLGenerator from \"@components/index/SubURLGenerator.astro\";\n//import KShorter from \"@components/index/k-shorter.astro\";\n---\n<Base>\n    <SubURLGenerator />\n</Base>"
  },
  {
    "path": "src/pages/shorter/admin.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\nimport { Icon } from \"astro-icon/components\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport ShorterPassword from \"@components/shorter/shorter-password.astro\";\n---\n\n<Base>\n    <h1 class=\"text-2xl font-bold\">Administration</h1>\n    <p>\n        <Icon class=\"inline\" name=\"iconoir:info-circle\" /> Please ensure that you\n        have binded a KV correctly to the project.\n    </p>\n\n    <BackendIndicator />\n\n    <div role=\"alert\" class=\"alert my-4 alert-warning\">\n        <Icon class=\"inline\" name=\"iconoir:info-circle\" />\n        <span\n            >Warning: The following content is intended only for instance\n            owners.</span\n        >\n    </div>\n\n    <div data-role=\"passwordStatus\" data-status=\"checking\">\n        <h2>Admin password status</h2>\n\n        <div role=\"alert\" class=\"alert my-4 alert-success\" data-status=\"true\">\n            <Icon class=\"inline\" name=\"iconoir:check-circle\" />\n            <span>Admin password defined</span>\n        </div>\n\n        <div role=\"alert\" class=\"alert my-4 alert-error\" data-status=\"false\">\n            <Icon class=\"inline\" name=\"iconoir:warning-triangle\" />\n            <span>Admin password undefined</span>\n        </div>\n\n        <div role=\"alert\" class=\"alert my-4 alert-success\" data-status=\"fail\">\n            <Icon class=\"inline\" name=\"iconoir:xmark-circle\" />\n            <span>Check failed, open console to get more information.</span>\n        </div>\n\n        <div\n            role=\"alert\"\n            class=\"alert my-4 alert-success\"\n            data-status=\"checking\"\n        >\n            <span class=\"loading loading-spinner loading-md\"></span>\n            <span>Checking....</span>\n        </div>\n    </div>\n    <div role=\"alert\" class=\"alert my-4 bg-base-300\" data-status=\"checking\">\n        <Icon name=\"iconoir:question-mark-circle\" />\n        <span\n            >If you forget your admin password, you have to delete the key\n            \"admin-password\" in the KV database and set a new one.</span\n        >\n    </div>\n    <h2 class=\"text-xl font-bold\">Set / Change Admin Password</h2>\n    <ShorterPassword />\n</Base>\n\n<style lang=\"scss\">\n    div[data-role=\"passwordStatus\"] {\n        > * {\n            display: none;\n        }\n        &[data-status=\"true\"] > [data-status=\"true\"] {\n            display: block;\n        }\n        &[data-status=\"false\"] > [data-status=\"false\"] {\n            display: block;\n        }\n        &[data-status=\"checking\"] > [data-status=\"checking\"] {\n            display: block;\n        }\n        &[data-status=\"fail\"] > [data-status=\"fail\"] {\n            display: block;\n        }\n    }\n</style>\n\n<script>\n    addEventListener(\"DOMContentLoaded\", () => {\n        // check for the admin password status\n        const adminPasswordStatus = document.querySelector(\n            '[data-role=\"passwordStatus\"]',\n        ) as HTMLElement;\n        fetch(`${document.body.dataset.defaultBackend}/short/admin-password/status`)\n            .then((res) => res.json())\n            .then((res) => {\n                adminPasswordStatus.dataset.status =\n                    res.isPasswordSet.toString();\n            })\n            .catch(() => {\n                adminPasswordStatus.dataset.status = \"fail\";\n            });\n    });\n</script>\n"
  },
  {
    "path": "src/pages/shorter/create.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport KShorter from \"@components/shorter/k-shorter.astro\";\n---\n<Base>\n    <h1 class=\"text-2xl font-bold\">Create a new Short</h1>\n\n    <BackendIndicator />\n\n    <KShorter />\n</Base>\n\n"
  },
  {
    "path": "src/pages/shorter/destory.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport ShortDestroyer from \"@components/shorter/short-destroyer.astro\";\n---\n<Base>\n    <h1 class=\"text-2xl font-bold\">Destory a existing Short</h1>\n\n    <BackendIndicator />\n\n    <ShortDestroyer />\n</Base>\n\n"
  },
  {
    "path": "src/pages/shorter/edit.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport ShortEditor from \"@components/shorter/short-editor.astro\"\n---\n<Base>\n    <h1 class=\"text-2xl font-bold\">Short Editior</h1>\n    <BackendIndicator />\n\n    <ShortEditor />\n</Base>\n"
  },
  {
    "path": "src/pages/shorter/list.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport ShorterList from \"@components/shorter/shorter-list.astro\"\n---\n<Base>\n    <h1 class=\"text-2xl font-bold\">List all the Shorts</h1>\n    \n    <BackendIndicator />\n\n    <ShorterList />\n</Base>\n"
  },
  {
    "path": "src/pages/shorter/reset-token.astro",
    "content": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport ShortTokenReset from \"@components/shorter/short-token-reset.astro\";\n---\n<Base>\n    <h1 class=\"text-2xl font-bold\">Reset Access Token for a existing Short</h1>\n\n    <BackendIndicator />\n\n    <ShortTokenReset />\n</Base>\n\n"
  },
  {
    "path": "src/scripts/components/data-input.ts",
    "content": "import type { Dropdown } from \"@scripts/components/k-dropdown\";\n\nexport class DataInput extends HTMLElement {\n    type = this.dataset.type;\n    \n    constructor () {\n        super ();\n    }\n\n    get () { // boolean if toggle, string if any otherwise\n        if (this.type === \"textarea\") {\n            return this.querySelector(\"textarea\").value.trim();\n        } else if (this.type === \"input\") {\n            return this.querySelector(\"input\").value.trim();\n        } else if (this.type === \"k-dropdown\") {\n            const DropdownElement = this.querySelector(\"k-dropdown\") as Dropdown;\n            return DropdownElement.dataset.selectedValue;\n        } else if (this.type === \"toggle\") {\n            const ToggleElement = this.querySelector(\"input.toggle\") as HTMLInputElement;\n            return ToggleElement.checked;\n        }\n    }\n    \n    set (value: string) {\n        if (this.type === \"textarea\") {\n            this.querySelector(\"textarea\").value = value.trim();\n        } else if (this.type === \"input\") {\n            this.querySelector(\"input\").value = value.trim();\n        } else if (this.type === \"k-dropdown\") {\n            const DropdownElement = this.querySelector(\"k-dropdown\") as Dropdown;\n            DropdownElement.select(value);\n        } else if (this.type === \"toggle\") {\n            const SwitchElement = this.querySelector(\"toggle\") as HTMLInputElement;\n            SwitchElement.checked = value == \"true\"; // \"true\" or true or whatever.... it should be boolean\n        }\n    }\n\n    setDetail(value: string) {\n        if (this.type === \"textarea\") {\n            this.querySelector(\"textarea\").placeholder = value;\n            return true;\n        } else if (this.type === \"input\") {\n            this.querySelector(\"input\").placeholder = value;\n            return true;\n        }\n        return false;\n    }\n\n    getDetail() {\n        if (this.type === \"textarea\") {\n            return this.querySelector(\"textarea\").placeholder;\n        } else if (this.type === \"input\") {\n            return this.querySelector(\"input\").placeholder;\n        }\n    }\n}\n\n\nfunction maybeWaitFor(tag) {\n    return customElements.get(tag) || document.querySelector(tag)\n      ? customElements.whenDefined(tag)\n      : Promise.resolve(); // No need to wait\n  }\n  \nPromise.all([\n    maybeWaitFor(\"toggle\"),\n    maybeWaitFor(\"k-dropdown\")\n]).then(() => {\n    console.log(\"[data-input] dependency elements toggle and k-dropdown registered, initializing\");\n    customElements.define(\"data-input\", DataInput);\n    console.info(\"[data-input] registered\")\n});\n\n// Promise.all([\n//     customElements.whenDefined(\"toggle\"),\n//     customElements.whenDefined(\"k-dropdown\")\n// ]).then(() => {\n//     console.log(\"[data-input] dependency toggle and k-dropdown registration detected, initializing\");\n//     customElements.define(\"data-input\", DataInput);\n//     console.info(\"[data-input] registered\")\n// });\n"
  },
  {
    "path": "src/scripts/components/k-dropdown.ts",
    "content": "export class Dropdown extends HTMLElement {\n    constructor () {\n        super();\n        \n        this.initializeElements();\n        this.setupEventListeners();\n    }\n\n    private initializeElements() {\n        this.Elements = {\n            DropdownBotton: this.querySelector(\"div.btn\") as HTMLElement,\n            DropdownBottonText: this.querySelector(\"div.btn > span\") as HTMLElement,\n            Items: this.querySelectorAll(\".dropdown-content > li > a\") as NodeListOf<HTMLButtonElement>\n        };\n    }\n\n    private setupEventListeners() {\n        this.Elements.Items.forEach(item => {\n            item.addEventListener(\"click\", (event) => {\n                const targetElement = event.target as HTMLElement;\n                this.select(targetElement.dataset.value);\n            });\n        });\n    }\n\n    public select(value: string) {\n        if (!value) {\n            console.error(\"[k-dropdown.select] value is required\")\n            return false;\n        };\n\n        this.dataset.selectedValue = value;\n        \n        // mark the selected\n        this.Elements.Items.forEach(item => {\n            if (item.dataset.value === value) {\n                item.classList.add(\"menu-active\")\n                this.Elements.DropdownBottonText.innerText = item.innerText;\n            } else {\n                // cancel non-targets out\n                item.classList.remove(\"menu-active\")\n            }\n        });\n\n        // dispatch custom event to notify\n        this.dispatchEvent(new CustomEvent(\"dropdown-select\", {\n            bubbles: true,\n            composed: true,\n            detail: {\n                value,\n            }\n        }));\n    }\n\n    Elements: {\n        DropdownBotton: HTMLElement;\n        DropdownBottonText: HTMLElement;\n        Items: NodeListOf<HTMLButtonElement>;\n    }\n}\n\ncustomElements.define(\"k-dropdown\", Dropdown);\nconsole.info(\"[k-dropdown] registered\")"
  },
  {
    "path": "src/scripts/components/k-suburl-generator.ts",
    "content": "import type { DataInput } from \"@scripts/components/data-input\";\nimport type { EndpointExtendConfigPrototype, EndpointPrototype } from \"@config/AvalibleOptoutFormat\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\nimport { copyToClipboard } from \"@scripts/utils/copy\";\nimport filterObject from \"@scripts/utils/filterObject\";\n\nclass SubURLGenerator extends HTMLElement {\n    Endpoints: EndpointPrototype[] = JSON.parse(this.dataset.endpoints);\n    defaultBackend = getDefaultBackend();\n\n    constructor () {\n        super()\n        \n        this.setupEventListeners();\n\n        customElements.whenDefined(\"data-input\").then(() => {\n            this.Elements.Config.Basic.Backend.setDetail(`${this.Elements.Config.Basic.Backend.getDetail()} (${this.defaultBackend})`);\n            console.info(\"[k-sub-url-generator] data-input registration detected, default backend modified\")\n        })\n    }\n\n    private setupEventListeners () {\n        this.Elements.Action.Generate.addEventListener(\"click\", () => {this.CheckAndGenerate()});\n        this.Elements.Action.Copy.addEventListener(\"click\", () => {\n            copyToClipboard(this.Elements.Action.MsgBlock.innerText)\n                .then(() => {\n                    alert(\"已将连接复制到剪贴板\");\n                })\n                .catch((err) => {\n                    console.error(\"[k-suburl-generator] copy failed\", err);\n                    alert(\"复制失败, 请检查浏览器权限设置, 版本, 或尝试手动复制.\");\n                });\n        });\n        this.Elements.Config.Basic.Endpoint.addEventListener(\"dropdown-select\", (event: CustomEvent) => {\n            const SelectedEndpointPath: string = event.detail.selectedValue;\n            let Endpoint: EndpointPrototype = this.GetEndpoint(SelectedEndpointPath);\n            let NeededExtendConfig = Endpoint.ExtendConfig || [];\n\n            for (let i in this.Elements.Config.Extended) {\n                if (NeededExtendConfig.includes(i as EndpointExtendConfigPrototype)) {\n                    this.Elements.Config.Extended[i].style.removeProperty(\"display\")\n                } else {\n                    this.Elements.Config.Extended[i].style.setProperty(\"display\", \"none\")\n                }\n            }\n        });\n    }\n\n    private Elements = {\n        Action: {\n            Generate: this.querySelector(\"button#generate\") as HTMLButtonElement,\n            Copy: this.querySelector(\"button#copy\") as HTMLButtonElement,\n            MsgBlock: this.querySelector(\"code\") as HTMLElement,\n        },\n        Config: {\n            Basic: {\n                SubURL: this.querySelector(\"data-input#SubURL\") as DataInput,\n                Backend: this.querySelector(\"data-input#Backend\") as DataInput,\n                Endpoint: this.querySelector(\"data-input#Endpoint\") as DataInput,\n            },\n            UniversalExtended: {\n                isShowHost: this.querySelector(\"data-input#isShowHost\") as DataInput,\n                HTTPHeaders: this.querySelector(\"data-input#HTTPHeaders\") as DataInput,\n                ExcludeRegExpPattern: this.querySelector(\"data-input#ExcludeRegExpPattern\") as DataInput,\n            },\n            Extended: {\n                RuleProviderUserspec: this.querySelector(\"data-input#RuleProviderUserspec\") as DataInput,\n                RuleProvider: this.querySelector(\"data-input#RuleProvider\") as DataInput,\n                RuleProvidersProxy: this.querySelector(\"data-input#RuleProvidersProxy\") as DataInput,\n                BaseConfig: this.querySelector(\"data-input#BaseConfig\") as DataInput,\n                isUDP: this.querySelector(\"data-input#isUDP\") as DataInput,\n                isSSUoT: this.querySelector(\"data-input#isSSUoT\") as DataInput,\n                ForcedWS0RTT: this.querySelector(\"data-input#ForcedWS0RTT\") as DataInput,\n            }\n        }\n    }\n\n    private GetEndpoint (EndpointPath: string = String(this.Elements.Config.Basic.Endpoint.get())) {\n        for (let i of this.Endpoints) {\n            if (i.value === EndpointPath) {\n                return i as EndpointPrototype;\n            }\n        }\n        throw `no targeted endpoint found, expected value ${EndpointPath}`\n    }\n\n    private getConfig () {\n        const Backend = new URL(String(this.Elements.Config.Basic.Backend.get() || this.defaultBackend));\n        return {\n            Basic: {\n                SubURL: this.Elements.Config.Basic.SubURL.get() as string,\n                Backend: Backend.toString() as string,\n                Endpoint: this.Elements.Config.Basic.Endpoint.get() as string,\n            },\n            UniversalExtended: {\n                isShowHost: this.Elements.Config.UniversalExtended.isShowHost.get() as boolean,\n                ExcludeRegExpPattern: this.Elements.Config.UniversalExtended.ExcludeRegExpPattern.get() as string,\n                HTTPHeaders: JSON.stringify(JSON.parse(String(this.Elements.Config.UniversalExtended.HTTPHeaders.get()) || \"{}\")) as string,\n            },\n            Extended: {\n                RuleProvider: (this.Elements.Config.Extended.RuleProviderUserspec.get() || this.Elements.Config.Extended.RuleProvider.get()) as string,\n                RuleProvidersProxy: (this.Elements.Config.Extended.RuleProvidersProxy.get() && this.Elements.Config.Basic.Backend.get() || this.defaultBackend) as string,\n                BaseConfig: this.Elements.Config.Extended.BaseConfig.get() || \"__DEFAULT\" as String,\n                isUDP: this.Elements.Config.Extended.isUDP.get() as boolean,\n                isSSUoT: this.Elements.Config.Extended.isSSUoT.get() as boolean,\n                ForcedWS0RTT: this.Elements.Config.Extended.ForcedWS0RTT.get() as boolean,\n            }\n        }\n    }\n\n\n\n    CheckAndGenerate () {\n        // Get config\n        const Config = this.getConfig();\n        \n        // non-empty check for basic configs \n        let ErrorOccurred = false;\n        for (let [key, value] of Object.entries(Config.Basic)) {\n            if (typeof value === \"string\" && value.length === 0) {\n                alert(`${key} can't be empty`);\n                ErrorOccurred = true;\n                continue;\n            }\n        }\n        if (ErrorOccurred === true) {\n            return;\n        }\n\n        // now we do some real works! con---gra---tu---la--tion---s---!\n\n        // grab the backend\n        let URLObj = new URL(Config.Basic.Backend);\n        URLObj.pathname = Config.Basic.Endpoint;\n        URLObj.search = \"\";\n        URLObj.hash = \"\";\n\n        // append inputed data (subdata)\n        URLObj.searchParams.append(\"url\", Config.Basic.SubURL)\n\n        // append extended config\n        // - currently we do this mapping on client side, \n        //   but in the future we may want to do this on server side, \n        //   just to keep the URL clean and uniform.\n        let Mapping = {\n            \"RuleProvider\": \"remote_config\",\n            \"RuleProvidersProxy\": \"rule_providers_proxy\",\n            \"isUDP\": \"udp\",\n            \"isSSUoT\": \"ss_uot\",\n            \"ForcedWS0RTT\": \"forced_ws0rtt\",\n            \"isShowHost\": \"show_host\",\n            \"HTTPHeaders\": \"http_headers\"\n        }\n\n        for (let [key, value] of Object.entries({\n            ...filterObject(Config.Extended, (key) => (this.GetEndpoint().ExtendConfig || []).includes(key)),\n            ...Config.UniversalExtended,\n        })) {\n            if (!String(value)) {\n                continue;\n            }\n            URLObj.searchParams.append(Mapping[key] || key, String(value));\n        }\n\n        this.Elements.Action.MsgBlock.innerText = URLObj.toString();\n\n    }\n}\n\ncustomElements.define(\"k-suburl-generator\", SubURLGenerator)\nconsole.info(\"[k-suburl-generator] registered\")\n"
  },
  {
    "path": "src/scripts/components/shorter/k-shorter.ts",
    "content": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\nexport class Shorter extends HTMLElement {\n    defaultBackend = getDefaultBackend();\n    constructor () {\n        super();\n        this.setupEventListeners()\n    }\n    private setupEventListeners () {\n        this.Elements.SubmitButton.addEventListener(\"click\", () => {this.Submit()});\n        this.Elements.CopyButton.addEventListener(\"click\", () => {this.Copy()});\n    }\n    private Copy () {\n        // copy slug and token to clipboard\n        let slug = `short:${String(this.Elements.slug.get())}`;\n        navigator.clipboard.writeText(slug).then(() => {\n            alert(`已复制: ${slug}`);\n        }).catch(err => {\n            alert(`复制失败: ${err}`);\n        });\n    }\n    private async Submit () {\n        this.Elements.SubmitButton.disabled = true;\n        this.Elements.Msg.innerText = \"正在提交...\";\n        this.Elements.SubmitButton.querySelector(\".swap\").classList.add(\"swap-active\");\n\n        // build request body\n        let requestBody = {\n            subdata: this.Elements.subdata.get(),\n            slug: this.Elements.slug.get(),\n            token: this.Elements.token.get(),\n        }\n\n        // build api Endpoint\n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = \"/short/put\";\n\n        await fetch(requestURL, {\n            body: JSON.stringify(requestBody),\n            method: \"POST\"\n        }).then(async res => {\n            // handle non-success request\n            if (res.status !== 200) throw await res.text();\n            // parse returned data as json\n            return res.json()\n        }).then(res => {\n            this.Elements.Msg.innerText = `short:${res.slug}`;\n            // sync slug and token with reponse\n            this.Elements.slug.set(res.slug);\n            this.Elements.token.set(res.token);\n\n\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        }).catch((err) => {\n            this.Elements.Msg.innerText = `提交失败: ${err}`;\n\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        })\n    }\n    Elements = {\n        subdata: this.querySelector(\"data-input#SubURL\") as DataInput,\n\n        slug: this.querySelector(\"data-input#short-slug\") as DataInput,\n        token: this.querySelector(\"data-input#short-token\") as DataInput,\n\n        Msg: this.querySelector(\"code\"),\n        SubmitButton: this.querySelector(\"button#shorter\") as HTMLButtonElement,\n        CopyButton: this.querySelector(\"button#copy\") as HTMLButtonElement,\n    }\n}\n\ncustomElements.define(\"k-shorter\", Shorter);\nconsole.info(\"[k-shorter] registered\")\n\n"
  },
  {
    "path": "src/scripts/components/shorter/short-destroyer.ts",
    "content": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\nexport class Shorter extends HTMLElement {\n    defaultBackend = getDefaultBackend();\n    constructor () {\n        super();\n        this.Elements.SubmitButton.addEventListener(\"click\", () => {this.Submit()})\n    }\n    async Submit () {\n\n        this.Elements.SubmitButton.disabled = true;\n        this.Elements.SubmitButton.querySelector(\".swap\").classList.add(\"swap-active\");\n\n        // build api Endpoint\n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = `/short/delete/${this.Elements.slug.get()}`;\n\n        await fetch(requestURL, {\n            body: JSON.stringify({\n                token: this.Elements.token.get()\n            }),\n            method: \"DELETE\"\n        }).then(async res => {\n            // handle non-success request\n            if (res.status !== 200) throw await res.text();\n            // parse returned data as json\n            return res.json()\n        }).then(res => {\n            this.Elements.Msg.innerText = res.msg;\n        }).catch((err) => {\n            this.Elements.Msg.innerText = `提交失败: ${err}`;\n        }).finally(() => {\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        })\n    }\n    Elements = {\n        slug: this.querySelector(\"data-input#slug\") as DataInput,\n        token: this.querySelector(\"data-input#token\") as DataInput,\n\n        Msg: this.querySelector(\"code\"),\n        SubmitButton: this.querySelector(\"#submit\") as HTMLButtonElement,\n    }\n}\n\ncustomElements.define(\"short-destroyer\", Shorter);\nconsole.info(\"[short-destroyer] registered\")\n\n"
  },
  {
    "path": "src/scripts/components/shorter/short-editor.ts",
    "content": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\nexport class ShortEditor extends HTMLElement {\n    defaultBackend = getDefaultBackend()\n    constructor () {\n        super();\n        this.Elements.SubmitButton.addEventListener(\"click\", () => {this.Submit()})\n        this.Elements.FetchButton.addEventListener(\"click\", () => {this.Fetch()})\n        let PassedID = new URL(location.href).searchParams.get(\"id\");\n        if (PassedID) {\n            this.Elements.ShortID.set(PassedID)\n            this.Fetch()\n        }\n    }\n    Fetch () {\n\n        this.Elements.FetchButton.disabled = true;\n        this.Elements.FetchButton.querySelector(\".swap\").classList.add(\"swap-active\");\n\n        this.Elements.ShortData.set(\"fetching...\")\n        \n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = `/short/get/${this.Elements.ShortID.get()}`;\n\n\n        fetch(requestURL)\n        .then(res => res.json())\n        .then(res => {\n            this.Elements.ShortData.set(res.subdata)\n        }).catch((err) => {\n            alert(`Error: ${err}`);\n        }).finally(() => {\n            this.Elements.FetchButton.disabled = false;\n            this.Elements.FetchButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        })\n    }\n    Submit () {\n\n        this.Elements.SubmitButton.disabled = true;\n        this.Elements.SubmitButton.querySelector(\".swap\").classList.add(\"swap-active\");\n\n        // build request body\n        let requestBody = {\n            subdata: this.Elements.ShortData.get(),\n            slug: this.Elements.ShortID.get(),\n            token: this.Elements.ShortPassword.get(),\n        }\n\n        // build api Endpoint\n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = \"/short/put\";\n\n        fetch(requestURL, {\n            body: JSON.stringify(requestBody),\n            method: \"POST\"\n        }).then(async res => {\n            // handle non-success request\n            if (res.status !== 200) throw await res.text();\n            // parse returned data as json\n            return res.json()\n        }).then(res => {\n            this.Elements.Msg.innerText = `short:${res.slug}`;\n        }).catch((err) => {\n            this.Elements.Msg.innerText = `提交失败: ${err}`;\n        }).finally(() => {\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        })\n    }\n    Elements = {\n        ShortID: this.querySelector(\"#short-id\") as DataInput,\n        ShortPassword: this.querySelector(\"#short-password\") as DataInput,\n\n        ShortData: this.querySelector(\"#short-data\") as DataInput,\n\n        Msg: this.querySelector(\"code\") as HTMLElement,\n        \n        FetchButton: this.querySelector(\"#editor-fetch\") as HTMLButtonElement,\n        SubmitButton: this.querySelector(\"#editor-submit\") as HTMLButtonElement,\n    }\n}\n\ncustomElements.define(\"short-editor\", ShortEditor);\nconsole.info(\"[short-editor] registered\")\n\n\n"
  },
  {
    "path": "src/scripts/components/shorter/short-token-reset.ts",
    "content": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\nexport class ShortTokenResetter extends HTMLElement {\n    defaultBackend = getDefaultBackend();\n    constructor () {\n        super();\n        this.Elements.SubmitButton.addEventListener(\"click\", () => {this.Submit()})\n    }\n    async Submit () {\n\n        this.Elements.SubmitButton.disabled = true;\n        this.Elements.SubmitButton.querySelector(\".swap\").classList.add(\"swap-active\");\n\n        // build api Endpoint\n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = `/short/token-reset/${this.Elements.slug.get()}`;\n\n        await fetch(requestURL, {\n            body: JSON.stringify({\n                oldToken: this.Elements.oldToken.get(),\n                newToken: this.Elements.newToken.get()\n            }),\n            method: \"PATCH\"\n        }).then(async res => {\n            // handle non-success request\n            if (res.status !== 200) throw await res.text();\n            // parse returned data as json\n            return res.json()\n        }).then(res => {\n            this.Elements.Msg.innerText = res.msg;\n        }).catch((err) => {\n            this.Elements.Msg.innerText = `提交失败: ${err}`;\n        }).finally(() => {\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        })\n    }\n    Elements = {\n        slug: this.querySelector(\"data-input#slug\") as DataInput,\n        oldToken: this.querySelector(\"data-input#old-token\") as DataInput,\n        newToken: this.querySelector(\"data-input#new-token\") as DataInput,\n\n        Msg: this.querySelector(\"code\"),\n        SubmitButton: this.querySelector(\"#submit\") as HTMLButtonElement,\n    }\n}\n\ncustomElements.define(\"short-token-reset\", ShortTokenResetter);\nconsole.info(\"[short-token-reset] registered\")\n\n"
  },
  {
    "path": "src/scripts/components/shorter/shorter-list.ts",
    "content": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\nexport class ShorterList extends HTMLElement {\n    defaultBackend = getDefaultBackend()\n    constructor () {\n        super();\n        this.Elements.SubmitButton.addEventListener(\"click\", () => {this.Submit()})\n    }\n    async Submit () {\n        this.Elements.SubmitButton.disabled = true;\n        this.Elements.SubmitButton.querySelector(\".swap\").classList.add(\"swap-active\");\n        // build request body\n        let requestBody = {\n            password: this.Elements.password.get()\n        }\n\n        // build api Endpoint\n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = \"/short/list\";\n\n        await fetch(requestURL, {\n            body: JSON.stringify(requestBody),\n            method: \"POST\"\n        }).then(async res => {\n            const resText = await res.text();\n            try {\n                return JSON.parse(resText)\n            } catch (e) {\n                throw resText\n            }\n        }).then(res => {\n            if (res.success) {\n                if (res.shortIDs.length === 0) {\n                    alert(\"no shorts to see, add some and try again :)\");\n                }\n                Array.from(this.Elements.ListItems.querySelectorAll(\"list-item:not(.hidden)\")).map(i=>i.remove())\n                for (let i of res.shortIDs) {\n                    let t = this.Elements.ListItemPrototype.cloneNode(true) as ListItem;\n                    t.update(i.name.replace(/^short\\:/, \"\"), i.timestamp || 0)\n                    t.classList.remove(\"hidden\")\n                    this.Elements.ListItems.appendChild(t)\n                }\n            } else {\n                alert(`Error due to: ${res.msg}`);\n            }\n        }).catch((err) => {\n            alert(`Error: ${err}`);\n        }).finally(() => {\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        })\n    }\n    Elements = {\n        password: this.querySelector(\"#password\") as DataInput,\n        SubmitButton: this.querySelector(\"#list-submit\") as HTMLButtonElement,\n        ListItemPrototype: this.querySelector(\"list-item.hidden\") as ListItem,\n        ListItems: this.querySelector(\"#list-items\") as HTMLElement,\n    }\n}\n\ncustomElements.define(\"shorter-list\", ShorterList);\nconsole.info(\"[shorter-list] registered\")\n\n\n\nexport class ListItem extends HTMLElement {\n    defaultBackend = getDefaultBackend()\n    constructor () {\n        super();\n        \n        this.Elements.CopyButton.addEventListener(\"click\", () => {this.CopyID()})\n        this.Elements.EditButton.addEventListener(\"click\", () => {this.JumpToEdit()})\n    }\n    CopyID () {\n        if (!navigator.clipboard) {\n            alert(\"navigator.clipboard API not found on your drowser\")\n            return;\n        }\n        navigator.clipboard.writeText(`short:${this.Elements.IDInfo.innerText}`).then( () => {\n            alert(\"已将 Short ID 复制到剪贴板\");\n        }).catch(function(err) {\n            alert(`err: ${err}`);\n        });\n    }\n    JumpToEdit () {\n        location.assign(`/shorter/edit/?id=${this.Elements.IDInfo.innerText}`)\n    }\n    update (ShortID, EditTimestamp) {\n        this.Elements.IDInfo.innerText = ShortID;\n        let EditDate = new Date(EditTimestamp);\n        this.Elements.DateInfo.innerText = `${EditDate.toLocaleDateString()} ${EditDate.toLocaleTimeString()}`;\n    }\n    Elements = {\n        EditButton: this.querySelector(\".item-edit\") as HTMLButtonElement,\n        CopyButton: this.querySelector(\".item-copy\") as HTMLButtonElement,\n        IDInfo: this.querySelector(\".item-id\") as HTMLElement,\n        DateInfo: this.querySelector(\".item-date\") as HTMLSpanElement,\n    }\n}\n\ncustomElements.define(\"list-item\", ListItem);\nconsole.info(\"[shorter-list: list-item] registered\")\n"
  },
  {
    "path": "src/scripts/components/shorter/shorter-password.ts",
    "content": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\nexport class ShorterPassword extends HTMLElement {\n    defaultBackend = getDefaultBackend()\n    constructor () {\n        super();\n        this.Elements.SubmitButton.addEventListener(\"click\", () => {this.Submit()})\n    }\n    async Submit () {\n\n        this.Elements.SubmitButton.disabled = true;\n        this.Elements.SubmitButton.querySelector(\".swap\").classList.add(\"swap-active\");\n\n        this.Elements.Msg.innerText = \"submitting..\";\n        // build request body\n        let requestBody = {\n            newPassword: this.Elements.newPassword.get(),\n            oldPassword: this.Elements.oldPassword.get()\n        }\n\n        // build api Endpoint\n        let requestURL = new URL(this.defaultBackend);\n        requestURL.pathname = \"/short/admin-password/set\";\n\n        await fetch(requestURL, {\n            body: JSON.stringify(requestBody),\n            method: \"POST\"\n        }).then(async res => {\n            const resText = await res.text();\n            try {\n                return JSON.parse(resText)\n            } catch (e) {\n                throw resText\n            }\n        }).then(res => {\n            if (res.passwordUpdated) {\n                this.Elements.Msg.innerText = \"Password updated.\";\n            } else {\n                this.Elements.Msg.innerText = `Cannot update password due to: ${res.msg}`;\n            }\n        }).catch((err) => {\n            this.Elements.Msg.innerText = `Error: ${err}`;\n        }).finally(() => {\n            this.Elements.SubmitButton.disabled = false;\n            this.Elements.SubmitButton.querySelector(\".swap\").classList.remove(\"swap-active\");\n        });\n    }\n    Elements = {\n        oldPassword: this.querySelector(\"#old-password\") as DataInput,\n        newPassword: this.querySelector(\"#new-password\") as DataInput,\n\n        Msg: this.querySelector(\"code\") as HTMLElement,\n        SubmitButton: this.querySelector(\"#password-submit\") as HTMLButtonElement,\n    }\n}\n\ncustomElements.define(\"shorter-password\", ShorterPassword);\nconsole.info(\"[shorter-password] registered\")\n"
  },
  {
    "path": "src/scripts/utils/copy.ts",
    "content": "export function copyToClipboard(text: string) {\n    return new Promise((resolve, reject) => {\n        if (!navigator.clipboard) {\n            reject(new Error(\"Clipboard API not supported\"));\n            return;\n        }\n        navigator.clipboard.writeText(text)\n            .then(() => resolve(void 0))\n            .catch(err => reject(err));\n    });\n}"
  },
  {
    "path": "src/scripts/utils/filterObject.ts",
    "content": "/**\n * Generic “object filter”.  Works exactly like Array.filter,\n * but the callback receives (key, value) instead of (value, index).\n *\n * @param obj        The source object.\n * @param predicate  (key, value) => boolean – return true to keep the entry.\n *\n * @returns a new object typed as a *partial* of the original (because we\n *          don't know at compile time which keys survive).\n */\nexport default function filterObject <T extends object> (\n  obj: T,\n  predicate: (key: keyof T, value: T[keyof T]) => boolean\n): Partial<T> {\n  const result: Partial<T> = {};\n\n  // `Object.keys` returns string[], so we cast it to the proper key type.\n  const keys = Object.keys(obj) as (keyof T)[];\n\n  for (const k of keys) {\n    const v = obj[k];\n    if (predicate(k, v)) {\n      // This cast is safe – we only ever assign a known property.\n      (result as any)[k] = v;\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "src/scripts/utils/getDefaultBackend.ts",
    "content": "export function getDefaultBackend () {\n    let URLObj = new URL(location.href);\n    URLObj.pathname = \"\";\n    URLObj.search = \"\";\n    URLObj.hash = \"\";\n\n    return URLObj.host === \"localhost:4321\" ? \"http://localhost:8788\" : URLObj.toString();\n}\n"
  },
  {
    "path": "src/styles/app.scss",
    "content": "@import \"tailwindcss\";\n@plugin \"daisyui\";\n"
  },
  {
    "path": "src/styles/import.css",
    "content": "@import \"tailwindcss\";\n@plugin \"daisyui\" {\n    themes: \"LightMint\" --default;/* dark --prefersdark;*/\n}\n\n\n@plugin \"daisyui/theme\" {\n    name: \"LightMint\";\n    default: true;\n    prefersdark: false;\n    color-scheme: \"light\";\n    --color-base-100: oklch(98% 0.018 155.826);\n    --color-base-200: oklch(96% 0.044 156.743);\n    --color-base-300: oklch(92% 0.084 155.995);\n    --color-base-content: oklch(39% 0.095 152.535);\n    --color-primary: oklch(67% 0.182 276.935);\n    --color-primary-content: oklch(25% 0.09 281.288);\n    --color-secondary: oklch(67% 0.182 276.935);\n    --color-secondary-content: oklch(25% 0.09 281.288);\n    --color-accent: oklch(74% 0.16 232.661);\n    --color-accent-content: oklch(29% 0.066 243.157);\n    --color-neutral: oklch(26% 0.065 152.934);\n    --color-neutral-content: oklch(98% 0.018 155.826);\n    --color-info: oklch(70% 0.165 254.624);\n    --color-info-content: oklch(28% 0.091 267.935);\n    --color-success: oklch(76% 0.177 163.223);\n    --color-success-content: oklch(26% 0.051 172.552);\n    --color-warning: oklch(75% 0.183 55.934);\n    --color-warning-content: oklch(26% 0.079 36.259);\n    --color-error: oklch(71% 0.194 13.428);\n    --color-error-content: oklch(27% 0.105 12.094);\n    --radius-selector: 2rem;\n    --radius-field: 2rem;\n    --radius-box: 1rem;\n    --size-selector: 0.25rem;\n    --size-field: 0.25rem;\n    --border: 1px;\n    --depth: 1;\n    --noise: 1;\n}"
  },
  {
    "path": "src/styles/index.scss",
    "content": ".main-card-con {\n    box-sizing: border-box;\n    width: 100%;\n    min-height: 100vh;\n    padding: 20px 0;\n    background-color: #121317;\n    color: #e3dfe6;\n    .main-card {\n        background-color: #292a2e;\n        margin: 0 auto;\n        width: 80%;\n        max-width: 1000px;\n        border-radius: 14px;\n    }\n}\n\n.contents {\n    padding: 24px 30px;\n}\n.flex-contents {\n    display: flex;\n    flex-wrap: wrap;\n    flex-flow: column;\n    gap: 12px\n}\n\n@media screen and (max-width: 512px) {\n    .main-card-con {\n        padding: 0;\n        background-color: #292a2e;\n        .main-card {\n            margin: 0;\n            width: 100%;\n            border-radius: 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/styles/main.scss",
    "content": "\n\n// body {\n//     margin: 0;\n//     font-family: \"Roboto\", sans-serif, system-ui;\n// }\n// button {\n//     width: 100%;\n//     border: none;\n//     background-color: #bbc5e8;\n//     color: #25304c;\n//     padding: 12px 18px;\n//     border-radius: 25px;\n//     &:active {\n//         filter: brightness(0.85);\n//     }\n//     [data-icon] {\n//         color: #25304c;\n//         fill: #25304c;\n//         height: 1.25rem;\n//         width: 1.25rem;\n//         vertical-align: -0.3rem;\n//     }\n// }\n// code {\n//     background-color: #1f2229;\n//     padding: 12px 18px;\n//     border-radius: 8px;\n//     word-break: break-all;\n// }\n\n\n// a:link, a:visited {\n//     color: white;\n//     text-decoration: underline;\n//     text-decoration-thickness: 1px;\n//     text-decoration-style: dashed;\n//     &:hover {\n//         text-decoration-style: solid;\n//     }    \n// }\n\n// [data-icon] {\n//     vertical-align: -0.125rem;\n// }"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"extends\": \"astro/tsconfigs/base\",\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"typeRoots\": [\"./types\", \"./node_modules/@types\"],\n    \"paths\": {\n      \"@components/*\": [\"src/components/*\"],\n      \"@contents/*\": [\"src/content/*\"],\n      \"@layouts/*\": [\"src/layouts/*\"],\n      \"@scripts/*\": [\"src/scripts/*\"],\n      \"@styles/*\": [\"src/styles/*\"],\n      \"@config/*\": [\"src/config/*\"]\n    }\n  }\n}\n"
  },
  {
    "path": "types/worker-configuration.d.ts",
    "content": "// Generated by Wrangler by running `wrangler types ./types/worker-configuration.d.ts` (hash: 2569fdb35d6c7f3f62093f7ff8102897)\n// Runtime types generated with workerd@1.20250408.0 2023-10-10 \ndeclare namespace Cloudflare {\n\tinterface Env {\n\t\tEdgeSubDB: KVNamespace;\n\t}\n}\ninterface Env extends Cloudflare.Env {}\n\n// Begin runtime types\n/*! *****************************************************************************\nCopyright (c) Cloudflare. All rights reserved.\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n/* eslint-disable */\n// noinspection JSUnusedGlobalSymbols\ndeclare var onmessage: never;\n/**\n * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)\n */\ndeclare class DOMException extends Error {\n    constructor(message?: string, name?: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */\n    readonly message: string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */\n    readonly name: string;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)\n     */\n    readonly code: number;\n    static readonly INDEX_SIZE_ERR: number;\n    static readonly DOMSTRING_SIZE_ERR: number;\n    static readonly HIERARCHY_REQUEST_ERR: number;\n    static readonly WRONG_DOCUMENT_ERR: number;\n    static readonly INVALID_CHARACTER_ERR: number;\n    static readonly NO_DATA_ALLOWED_ERR: number;\n    static readonly NO_MODIFICATION_ALLOWED_ERR: number;\n    static readonly NOT_FOUND_ERR: number;\n    static readonly NOT_SUPPORTED_ERR: number;\n    static readonly INUSE_ATTRIBUTE_ERR: number;\n    static readonly INVALID_STATE_ERR: number;\n    static readonly SYNTAX_ERR: number;\n    static readonly INVALID_MODIFICATION_ERR: number;\n    static readonly NAMESPACE_ERR: number;\n    static readonly INVALID_ACCESS_ERR: number;\n    static readonly VALIDATION_ERR: number;\n    static readonly TYPE_MISMATCH_ERR: number;\n    static readonly SECURITY_ERR: number;\n    static readonly NETWORK_ERR: number;\n    static readonly ABORT_ERR: number;\n    static readonly URL_MISMATCH_ERR: number;\n    static readonly QUOTA_EXCEEDED_ERR: number;\n    static readonly TIMEOUT_ERR: number;\n    static readonly INVALID_NODE_TYPE_ERR: number;\n    static readonly DATA_CLONE_ERR: number;\n    get stack(): any;\n    set stack(value: any);\n}\ntype WorkerGlobalScopeEventMap = {\n    fetch: FetchEvent;\n    scheduled: ScheduledEvent;\n    queue: QueueEvent;\n    unhandledrejection: PromiseRejectionEvent;\n    rejectionhandled: PromiseRejectionEvent;\n};\ndeclare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {\n    EventTarget: typeof EventTarget;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */\ninterface Console {\n    \"assert\"(condition?: boolean, ...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */\n    clear(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */\n    count(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countreset_static) */\n    countReset(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */\n    debug(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */\n    dir(item?: any, options?: any): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */\n    dirxml(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */\n    error(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */\n    group(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupcollapsed_static) */\n    groupCollapsed(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupend_static) */\n    groupEnd(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */\n    info(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */\n    log(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */\n    table(tabularData?: any, properties?: string[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */\n    time(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeend_static) */\n    timeEnd(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timelog_static) */\n    timeLog(label?: string, ...data: any[]): void;\n    timeStamp(label?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */\n    trace(...data: any[]): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */\n    warn(...data: any[]): void;\n}\ndeclare const console: Console;\ntype BufferSource = ArrayBufferView | ArrayBuffer;\ntype TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;\ndeclare namespace WebAssembly {\n    class CompileError extends Error {\n        constructor(message?: string);\n    }\n    class RuntimeError extends Error {\n        constructor(message?: string);\n    }\n    type ValueType = \"anyfunc\" | \"externref\" | \"f32\" | \"f64\" | \"i32\" | \"i64\" | \"v128\";\n    interface GlobalDescriptor {\n        value: ValueType;\n        mutable?: boolean;\n    }\n    class Global {\n        constructor(descriptor: GlobalDescriptor, value?: any);\n        value: any;\n        valueOf(): any;\n    }\n    type ImportValue = ExportValue | number;\n    type ModuleImports = Record<string, ImportValue>;\n    type Imports = Record<string, ModuleImports>;\n    type ExportValue = Function | Global | Memory | Table;\n    type Exports = Record<string, ExportValue>;\n    class Instance {\n        constructor(module: Module, imports?: Imports);\n        readonly exports: Exports;\n    }\n    interface MemoryDescriptor {\n        initial: number;\n        maximum?: number;\n        shared?: boolean;\n    }\n    class Memory {\n        constructor(descriptor: MemoryDescriptor);\n        readonly buffer: ArrayBuffer;\n        grow(delta: number): number;\n    }\n    type ImportExportKind = \"function\" | \"global\" | \"memory\" | \"table\";\n    interface ModuleExportDescriptor {\n        kind: ImportExportKind;\n        name: string;\n    }\n    interface ModuleImportDescriptor {\n        kind: ImportExportKind;\n        module: string;\n        name: string;\n    }\n    abstract class Module {\n        static customSections(module: Module, sectionName: string): ArrayBuffer[];\n        static exports(module: Module): ModuleExportDescriptor[];\n        static imports(module: Module): ModuleImportDescriptor[];\n    }\n    type TableKind = \"anyfunc\" | \"externref\";\n    interface TableDescriptor {\n        element: TableKind;\n        initial: number;\n        maximum?: number;\n    }\n    class Table {\n        constructor(descriptor: TableDescriptor, value?: any);\n        readonly length: number;\n        get(index: number): any;\n        grow(delta: number, value?: any): number;\n        set(index: number, value?: any): void;\n    }\n    function instantiate(module: Module, imports?: Imports): Promise<Instance>;\n    function validate(bytes: BufferSource): boolean;\n}\n/**\n * This ServiceWorker API interface represents the global execution context of a service worker.\n * Available only in secure contexts.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)\n */\ninterface ServiceWorkerGlobalScope extends WorkerGlobalScope {\n    DOMException: typeof DOMException;\n    WorkerGlobalScope: typeof WorkerGlobalScope;\n    btoa(data: string): string;\n    atob(data: string): string;\n    setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;\n    setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n    clearTimeout(param1: number | null): void;\n    setInterval(callback: (...args: any[]) => void, msDelay?: number): number;\n    setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n    clearInterval(param1: number | null): void;\n    queueMicrotask(task: Function): void;\n    structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;\n    reportError(error: any): void;\n    fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;\n    self: ServiceWorkerGlobalScope;\n    crypto: Crypto;\n    caches: CacheStorage;\n    scheduler: Scheduler;\n    performance: Performance;\n    Cloudflare: Cloudflare;\n    readonly origin: string;\n    Event: typeof Event;\n    ExtendableEvent: typeof ExtendableEvent;\n    CustomEvent: typeof CustomEvent;\n    PromiseRejectionEvent: typeof PromiseRejectionEvent;\n    FetchEvent: typeof FetchEvent;\n    TailEvent: typeof TailEvent;\n    TraceEvent: typeof TailEvent;\n    ScheduledEvent: typeof ScheduledEvent;\n    MessageEvent: typeof MessageEvent;\n    CloseEvent: typeof CloseEvent;\n    ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;\n    ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;\n    ReadableStream: typeof ReadableStream;\n    WritableStream: typeof WritableStream;\n    WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;\n    TransformStream: typeof TransformStream;\n    ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;\n    CountQueuingStrategy: typeof CountQueuingStrategy;\n    ErrorEvent: typeof ErrorEvent;\n    EventSource: typeof EventSource;\n    ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;\n    ReadableStreamDefaultController: typeof ReadableStreamDefaultController;\n    ReadableByteStreamController: typeof ReadableByteStreamController;\n    WritableStreamDefaultController: typeof WritableStreamDefaultController;\n    TransformStreamDefaultController: typeof TransformStreamDefaultController;\n    CompressionStream: typeof CompressionStream;\n    DecompressionStream: typeof DecompressionStream;\n    TextEncoderStream: typeof TextEncoderStream;\n    TextDecoderStream: typeof TextDecoderStream;\n    Headers: typeof Headers;\n    Body: typeof Body;\n    Request: typeof Request;\n    Response: typeof Response;\n    WebSocket: typeof WebSocket;\n    WebSocketPair: typeof WebSocketPair;\n    WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;\n    AbortController: typeof AbortController;\n    AbortSignal: typeof AbortSignal;\n    TextDecoder: typeof TextDecoder;\n    TextEncoder: typeof TextEncoder;\n    navigator: Navigator;\n    Navigator: typeof Navigator;\n    URL: typeof URL;\n    URLSearchParams: typeof URLSearchParams;\n    URLPattern: typeof URLPattern;\n    Blob: typeof Blob;\n    File: typeof File;\n    FormData: typeof FormData;\n    Crypto: typeof Crypto;\n    SubtleCrypto: typeof SubtleCrypto;\n    CryptoKey: typeof CryptoKey;\n    CacheStorage: typeof CacheStorage;\n    Cache: typeof Cache;\n    FixedLengthStream: typeof FixedLengthStream;\n    IdentityTransformStream: typeof IdentityTransformStream;\n    HTMLRewriter: typeof HTMLRewriter;\n}\ndeclare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;\ndeclare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;\n/**\n * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)\n */\ndeclare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */\ndeclare function btoa(data: string): string;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */\ndeclare function atob(data: string): string;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */\ndeclare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */\ndeclare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */\ndeclare function clearTimeout(param1: number | null): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */\ndeclare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */\ndeclare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */\ndeclare function clearInterval(param1: number | null): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */\ndeclare function queueMicrotask(task: Function): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */\ndeclare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */\ndeclare function reportError(error: any): void;\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */\ndeclare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;\ndeclare const self: ServiceWorkerGlobalScope;\n/**\n* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.\n* The Workers runtime implements the full surface of this API, but with some differences in\n* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)\n* compared to those implemented in most browsers.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)\n*/\ndeclare const crypto: Crypto;\n/**\n* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)\n*/\ndeclare const caches: CacheStorage;\ndeclare const scheduler: Scheduler;\n/**\n* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,\n* as well as timing of subrequests and other operations.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)\n*/\ndeclare const performance: Performance;\ndeclare const Cloudflare: Cloudflare;\ndeclare const origin: string;\ndeclare const navigator: Navigator;\ninterface TestController {\n}\ninterface ExecutionContext {\n    waitUntil(promise: Promise<any>): void;\n    passThroughOnException(): void;\n    props: any;\n}\ntype ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext) => Response | Promise<Response>;\ntype ExportedHandlerTailHandler<Env = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerTraceHandler<Env = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerTailStreamHandler<Env = unknown> = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;\ntype ExportedHandlerScheduledHandler<Env = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ntype ExportedHandlerTestHandler<Env = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ninterface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown> {\n    fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>;\n    tail?: ExportedHandlerTailHandler<Env>;\n    trace?: ExportedHandlerTraceHandler<Env>;\n    tailStream?: ExportedHandlerTailStreamHandler<Env>;\n    scheduled?: ExportedHandlerScheduledHandler<Env>;\n    test?: ExportedHandlerTestHandler<Env>;\n    email?: EmailExportedHandler<Env>;\n    queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>;\n}\ninterface StructuredSerializeOptions {\n    transfer?: any[];\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */\ndeclare abstract class PromiseRejectionEvent extends Event {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */\n    readonly promise: Promise<any>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */\n    readonly reason: any;\n}\ndeclare abstract class Navigator {\n    sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean;\n    readonly userAgent: string;\n    readonly hardwareConcurrency: number;\n}\n/**\n* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,\n* as well as timing of subrequests and other operations.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)\n*/\ninterface Performance {\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */\n    readonly timeOrigin: number;\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */\n    now(): number;\n}\ninterface AlarmInvocationInfo {\n    readonly isRetry: boolean;\n    readonly retryCount: number;\n}\ninterface Cloudflare {\n    readonly compatibilityFlags: Record<string, boolean>;\n}\ninterface DurableObject {\n    fetch(request: Request): Response | Promise<Response>;\n    alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;\n    webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;\n    webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;\n    webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;\n}\ntype DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, \"alarm\" | \"webSocketMessage\" | \"webSocketClose\" | \"webSocketError\"> & {\n    readonly id: DurableObjectId;\n    readonly name?: string;\n};\ninterface DurableObjectId {\n    toString(): string;\n    equals(other: DurableObjectId): boolean;\n    readonly name?: string;\n}\ninterface DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {\n    newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;\n    idFromName(name: string): DurableObjectId;\n    idFromString(id: string): DurableObjectId;\n    get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;\n    jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;\n}\ntype DurableObjectJurisdiction = \"eu\" | \"fedramp\";\ninterface DurableObjectNamespaceNewUniqueIdOptions {\n    jurisdiction?: DurableObjectJurisdiction;\n}\ntype DurableObjectLocationHint = \"wnam\" | \"enam\" | \"sam\" | \"weur\" | \"eeur\" | \"apac\" | \"oc\" | \"afr\" | \"me\";\ninterface DurableObjectNamespaceGetDurableObjectOptions {\n    locationHint?: DurableObjectLocationHint;\n}\ninterface DurableObjectState {\n    waitUntil(promise: Promise<any>): void;\n    readonly id: DurableObjectId;\n    readonly storage: DurableObjectStorage;\n    container?: Container;\n    blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;\n    acceptWebSocket(ws: WebSocket, tags?: string[]): void;\n    getWebSockets(tag?: string): WebSocket[];\n    setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;\n    getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;\n    getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;\n    setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;\n    getHibernatableWebSocketEventTimeout(): number | null;\n    getTags(ws: WebSocket): string[];\n    abort(reason?: string): void;\n}\ninterface DurableObjectTransaction {\n    get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;\n    get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;\n    list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;\n    put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;\n    put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;\n    delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;\n    delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;\n    rollback(): void;\n    getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;\n    setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;\n    deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;\n}\ninterface DurableObjectStorage {\n    get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;\n    get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;\n    list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;\n    put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;\n    put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;\n    delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;\n    delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;\n    deleteAll(options?: DurableObjectPutOptions): Promise<void>;\n    transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;\n    getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;\n    setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;\n    deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;\n    sync(): Promise<void>;\n    sql: SqlStorage;\n    transactionSync<T>(closure: () => T): T;\n    getCurrentBookmark(): Promise<string>;\n    getBookmarkForTime(timestamp: number | Date): Promise<string>;\n    onNextSessionRestoreBookmark(bookmark: string): Promise<string>;\n}\ninterface DurableObjectListOptions {\n    start?: string;\n    startAfter?: string;\n    end?: string;\n    prefix?: string;\n    reverse?: boolean;\n    limit?: number;\n    allowConcurrency?: boolean;\n    noCache?: boolean;\n}\ninterface DurableObjectGetOptions {\n    allowConcurrency?: boolean;\n    noCache?: boolean;\n}\ninterface DurableObjectGetAlarmOptions {\n    allowConcurrency?: boolean;\n}\ninterface DurableObjectPutOptions {\n    allowConcurrency?: boolean;\n    allowUnconfirmed?: boolean;\n    noCache?: boolean;\n}\ninterface DurableObjectSetAlarmOptions {\n    allowConcurrency?: boolean;\n    allowUnconfirmed?: boolean;\n}\ndeclare class WebSocketRequestResponsePair {\n    constructor(request: string, response: string);\n    get request(): string;\n    get response(): string;\n}\ninterface AnalyticsEngineDataset {\n    writeDataPoint(event?: AnalyticsEngineDataPoint): void;\n}\ninterface AnalyticsEngineDataPoint {\n    indexes?: ((ArrayBuffer | string) | null)[];\n    doubles?: number[];\n    blobs?: ((ArrayBuffer | string) | null)[];\n}\n/**\n * An event which takes place in the DOM.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)\n */\ndeclare class Event {\n    constructor(type: string, init?: EventInit);\n    /**\n     * Returns the type of event, e.g. \"click\", \"hashchange\", or \"submit\".\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)\n     */\n    get type(): string;\n    /**\n     * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)\n     */\n    get eventPhase(): number;\n    /**\n     * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)\n     */\n    get composed(): boolean;\n    /**\n     * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)\n     */\n    get bubbles(): boolean;\n    /**\n     * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)\n     */\n    get cancelable(): boolean;\n    /**\n     * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)\n     */\n    get defaultPrevented(): boolean;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)\n     */\n    get returnValue(): boolean;\n    /**\n     * Returns the object whose event listener's callback is currently being invoked.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)\n     */\n    get currentTarget(): EventTarget | undefined;\n    /**\n     * Returns the object to which event is dispatched (its target).\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)\n     */\n    get target(): EventTarget | undefined;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)\n     */\n    get srcElement(): EventTarget | undefined;\n    /**\n     * Returns the event's timestamp as the number of milliseconds measured relative to the time origin.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)\n     */\n    get timeStamp(): number;\n    /**\n     * Returns true if event was dispatched by the user agent, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)\n     */\n    get isTrusted(): boolean;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)\n     */\n    get cancelBubble(): boolean;\n    /**\n     * @deprecated\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)\n     */\n    set cancelBubble(value: boolean);\n    /**\n     * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)\n     */\n    stopImmediatePropagation(): void;\n    /**\n     * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)\n     */\n    preventDefault(): void;\n    /**\n     * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)\n     */\n    stopPropagation(): void;\n    /**\n     * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is \"closed\" that are not reachable from event's currentTarget.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)\n     */\n    composedPath(): EventTarget[];\n    static readonly NONE: number;\n    static readonly CAPTURING_PHASE: number;\n    static readonly AT_TARGET: number;\n    static readonly BUBBLING_PHASE: number;\n}\ninterface EventInit {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    composed?: boolean;\n}\ntype EventListener<EventType extends Event = Event> = (event: EventType) => void;\ninterface EventListenerObject<EventType extends Event = Event> {\n    handleEvent(event: EventType): void;\n}\ntype EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;\n/**\n * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)\n */\ndeclare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {\n    constructor();\n    /**\n     * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.\n     *\n     * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.\n     *\n     * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.\n     *\n     * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.\n     *\n     * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.\n     *\n     * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.\n     *\n     * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)\n     */\n    addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;\n    /**\n     * Removes the event listener in target's event listener list with the same type, callback, and options.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)\n     */\n    removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;\n    /**\n     * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)\n     */\n    dispatchEvent(event: EventMap[keyof EventMap]): boolean;\n}\ninterface EventTargetEventListenerOptions {\n    capture?: boolean;\n}\ninterface EventTargetAddEventListenerOptions {\n    capture?: boolean;\n    passive?: boolean;\n    once?: boolean;\n    signal?: AbortSignal;\n}\ninterface EventTargetHandlerObject {\n    handleEvent: (event: Event) => any | undefined;\n}\n/**\n * A controller object that allows you to abort one or more DOM requests as and when desired.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)\n */\ndeclare class AbortController {\n    constructor();\n    /**\n     * Returns the AbortSignal object associated with this object.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)\n     */\n    get signal(): AbortSignal;\n    /**\n     * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)\n     */\n    abort(reason?: any): void;\n}\n/**\n * A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)\n */\ndeclare abstract class AbortSignal extends EventTarget {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */\n    static abort(reason?: any): AbortSignal;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */\n    static timeout(delay: number): AbortSignal;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */\n    static any(signals: AbortSignal[]): AbortSignal;\n    /**\n     * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)\n     */\n    get aborted(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */\n    get reason(): any;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */\n    get onabort(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */\n    set onabort(value: any | null);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */\n    throwIfAborted(): void;\n}\ninterface Scheduler {\n    wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;\n}\ninterface SchedulerWaitOptions {\n    signal?: AbortSignal;\n}\n/**\n * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)\n */\ndeclare abstract class ExtendableEvent extends Event {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */\n    waitUntil(promise: Promise<any>): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */\ndeclare class CustomEvent<T = any> extends Event {\n    constructor(type: string, init?: CustomEventCustomEventInit);\n    /**\n     * Returns any custom data event was created with. Typically used for synthetic events.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)\n     */\n    get detail(): T;\n}\ninterface CustomEventCustomEventInit {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    composed?: boolean;\n    detail?: any;\n}\n/**\n * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)\n */\ndeclare class Blob {\n    constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n    get size(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n    get type(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n    slice(start?: number, end?: number, type?: string): Blob;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */\n    arrayBuffer(): Promise<ArrayBuffer>;\n    bytes(): Promise<Uint8Array>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n    text(): Promise<string>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */\n    stream(): ReadableStream;\n}\ninterface BlobOptions {\n    type?: string;\n}\n/**\n * Provides information about files and allows JavaScript in a web page to access their content.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)\n */\ndeclare class File extends Blob {\n    constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n    get name(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n    get lastModified(): number;\n}\ninterface FileOptions {\n    type?: string;\n    lastModified?: number;\n}\n/**\n* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)\n*/\ndeclare abstract class CacheStorage {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */\n    open(cacheName: string): Promise<Cache>;\n    readonly default: Cache;\n}\n/**\n* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)\n*/\ndeclare abstract class Cache {\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */\n    delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */\n    match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;\n    /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */\n    put(request: RequestInfo | URL, response: Response): Promise<void>;\n}\ninterface CacheQueryOptions {\n    ignoreMethod?: boolean;\n}\n/**\n* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.\n* The Workers runtime implements the full surface of this API, but with some differences in\n* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)\n* compared to those implemented in most browsers.\n*\n* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)\n*/\ndeclare abstract class Crypto {\n    /**\n     * Available only in secure contexts.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)\n     */\n    get subtle(): SubtleCrypto;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */\n    getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;\n    /**\n     * Available only in secure contexts.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)\n     */\n    randomUUID(): string;\n    DigestStream: typeof DigestStream;\n}\n/**\n * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto).\n * Available only in secure contexts.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)\n */\ndeclare abstract class SubtleCrypto {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */\n    encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */\n    decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */\n    sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */\n    verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */\n    digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */\n    generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */\n    deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */\n    deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */\n    importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */\n    exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */\n    wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */\n    unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;\n    timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;\n}\n/**\n * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.\n * Available only in secure contexts.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)\n */\ndeclare abstract class CryptoKey {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */\n    readonly type: string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */\n    readonly extractable: boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */\n    readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */\n    readonly usages: string[];\n}\ninterface CryptoKeyPair {\n    publicKey: CryptoKey;\n    privateKey: CryptoKey;\n}\ninterface JsonWebKey {\n    kty: string;\n    use?: string;\n    key_ops?: string[];\n    alg?: string;\n    ext?: boolean;\n    crv?: string;\n    x?: string;\n    y?: string;\n    d?: string;\n    n?: string;\n    e?: string;\n    p?: string;\n    q?: string;\n    dp?: string;\n    dq?: string;\n    qi?: string;\n    oth?: RsaOtherPrimesInfo[];\n    k?: string;\n}\ninterface RsaOtherPrimesInfo {\n    r?: string;\n    d?: string;\n    t?: string;\n}\ninterface SubtleCryptoDeriveKeyAlgorithm {\n    name: string;\n    salt?: (ArrayBuffer | ArrayBufferView);\n    iterations?: number;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    $public?: CryptoKey;\n    info?: (ArrayBuffer | ArrayBufferView);\n}\ninterface SubtleCryptoEncryptAlgorithm {\n    name: string;\n    iv?: (ArrayBuffer | ArrayBufferView);\n    additionalData?: (ArrayBuffer | ArrayBufferView);\n    tagLength?: number;\n    counter?: (ArrayBuffer | ArrayBufferView);\n    length?: number;\n    label?: (ArrayBuffer | ArrayBufferView);\n}\ninterface SubtleCryptoGenerateKeyAlgorithm {\n    name: string;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    modulusLength?: number;\n    publicExponent?: (ArrayBuffer | ArrayBufferView);\n    length?: number;\n    namedCurve?: string;\n}\ninterface SubtleCryptoHashAlgorithm {\n    name: string;\n}\ninterface SubtleCryptoImportKeyAlgorithm {\n    name: string;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    length?: number;\n    namedCurve?: string;\n    compressed?: boolean;\n}\ninterface SubtleCryptoSignAlgorithm {\n    name: string;\n    hash?: (string | SubtleCryptoHashAlgorithm);\n    dataLength?: number;\n    saltLength?: number;\n}\ninterface CryptoKeyKeyAlgorithm {\n    name: string;\n}\ninterface CryptoKeyAesKeyAlgorithm {\n    name: string;\n    length: number;\n}\ninterface CryptoKeyHmacKeyAlgorithm {\n    name: string;\n    hash: CryptoKeyKeyAlgorithm;\n    length: number;\n}\ninterface CryptoKeyRsaKeyAlgorithm {\n    name: string;\n    modulusLength: number;\n    publicExponent: ArrayBuffer | ArrayBufferView;\n    hash?: CryptoKeyKeyAlgorithm;\n}\ninterface CryptoKeyEllipticKeyAlgorithm {\n    name: string;\n    namedCurve: string;\n}\ninterface CryptoKeyArbitraryKeyAlgorithm {\n    name: string;\n    hash?: CryptoKeyKeyAlgorithm;\n    namedCurve?: string;\n    length?: number;\n}\ndeclare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {\n    constructor(algorithm: string | SubtleCryptoHashAlgorithm);\n    readonly digest: Promise<ArrayBuffer>;\n    get bytesWritten(): number | bigint;\n}\n/**\n * A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)\n */\ndeclare class TextDecoder {\n    constructor(label?: string, options?: TextDecoderConstructorOptions);\n    /**\n     * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments.\n     *\n     * ```\n     * var string = \"\", decoder = new TextDecoder(encoding), buffer;\n     * while(buffer = next_chunk()) {\n     *   string += decoder.decode(buffer, {stream:true});\n     * }\n     * string += decoder.decode(); // end-of-queue\n     * ```\n     *\n     * If the error mode is \"fatal\" and encoding's decoder returns error, throws a TypeError.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)\n     */\n    decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;\n    get encoding(): string;\n    get fatal(): boolean;\n    get ignoreBOM(): boolean;\n}\n/**\n * TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)\n */\ndeclare class TextEncoder {\n    constructor();\n    /**\n     * Returns the result of running UTF-8's encoder.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)\n     */\n    encode(input?: string): Uint8Array;\n    /**\n     * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)\n     */\n    encodeInto(input: string, buffer: ArrayBuffer | ArrayBufferView): TextEncoderEncodeIntoResult;\n    get encoding(): string;\n}\ninterface TextDecoderConstructorOptions {\n    fatal: boolean;\n    ignoreBOM: boolean;\n}\ninterface TextDecoderDecodeOptions {\n    stream: boolean;\n}\ninterface TextEncoderEncodeIntoResult {\n    read: number;\n    written: number;\n}\n/**\n * Events providing information related to errors in scripts or in files.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)\n */\ndeclare class ErrorEvent extends Event {\n    constructor(type: string, init?: ErrorEventErrorEventInit);\n    get filename(): string;\n    get message(): string;\n    get lineno(): number;\n    get colno(): number;\n    get error(): any;\n}\ninterface ErrorEventErrorEventInit {\n    message?: string;\n    filename?: string;\n    lineno?: number;\n    colno?: number;\n    error?: any;\n}\n/**\n * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to \"multipart/form-data\".\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)\n */\ndeclare class FormData {\n    constructor();\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */\n    append(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */\n    append(name: string, value: Blob, filename?: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */\n    delete(name: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */\n    get(param1: string): (File | string) | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */\n    getAll(param1: string): (File | string)[];\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */\n    has(name: string): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */\n    set(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */\n    set(name: string, value: Blob, filename?: string): void;\n    /* Returns an array of key, value pairs for every entry in the list. */\n    entries(): IterableIterator<[\n        key: string,\n        value: File | string\n    ]>;\n    /* Returns a list of keys in the list. */\n    keys(): IterableIterator<string>;\n    /* Returns a list of values in the list. */\n    values(): IterableIterator<(File | string)>;\n    forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;\n    [Symbol.iterator](): IterableIterator<[\n        key: string,\n        value: File | string\n    ]>;\n}\ninterface ContentOptions {\n    html?: boolean;\n}\ndeclare class HTMLRewriter {\n    constructor();\n    on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;\n    onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;\n    transform(response: Response): Response;\n}\ninterface HTMLRewriterElementContentHandlers {\n    element?(element: Element): void | Promise<void>;\n    comments?(comment: Comment): void | Promise<void>;\n    text?(element: Text): void | Promise<void>;\n}\ninterface HTMLRewriterDocumentContentHandlers {\n    doctype?(doctype: Doctype): void | Promise<void>;\n    comments?(comment: Comment): void | Promise<void>;\n    text?(text: Text): void | Promise<void>;\n    end?(end: DocumentEnd): void | Promise<void>;\n}\ninterface Doctype {\n    readonly name: string | null;\n    readonly publicId: string | null;\n    readonly systemId: string | null;\n}\ninterface Element {\n    tagName: string;\n    readonly attributes: IterableIterator<string[]>;\n    readonly removed: boolean;\n    readonly namespaceURI: string;\n    getAttribute(name: string): string | null;\n    hasAttribute(name: string): boolean;\n    setAttribute(name: string, value: string): Element;\n    removeAttribute(name: string): Element;\n    before(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    after(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    append(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    remove(): Element;\n    removeAndKeepContent(): Element;\n    setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;\n    onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;\n}\ninterface EndTag {\n    name: string;\n    before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;\n    after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;\n    remove(): EndTag;\n}\ninterface Comment {\n    text: string;\n    readonly removed: boolean;\n    before(content: string, options?: ContentOptions): Comment;\n    after(content: string, options?: ContentOptions): Comment;\n    replace(content: string, options?: ContentOptions): Comment;\n    remove(): Comment;\n}\ninterface Text {\n    readonly text: string;\n    readonly lastInTextNode: boolean;\n    readonly removed: boolean;\n    before(content: string | ReadableStream | Response, options?: ContentOptions): Text;\n    after(content: string | ReadableStream | Response, options?: ContentOptions): Text;\n    replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;\n    remove(): Text;\n}\ninterface DocumentEnd {\n    append(content: string, options?: ContentOptions): DocumentEnd;\n}\n/**\n * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)\n */\ndeclare abstract class FetchEvent extends ExtendableEvent {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */\n    readonly request: Request;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */\n    respondWith(promise: Response | Promise<Response>): void;\n    passThroughOnException(): void;\n}\ntype HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;\n/**\n * This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)\n */\ndeclare class Headers {\n    constructor(init?: HeadersInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */\n    get(param1: string): string | null;\n    getAll(name: string): string[];\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */\n    getSetCookie(): string[];\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */\n    has(name: string): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */\n    set(value: string, param2: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */\n    append(value: string, param2: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */\n    delete(name: string): void;\n    forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;\n    /* Returns an iterator allowing to go through all key/value pairs contained in this object. */\n    entries(): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n    /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */\n    keys(): IterableIterator<string>;\n    /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */\n    values(): IterableIterator<string>;\n    [Symbol.iterator](): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n}\ntype BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData;\ndeclare abstract class Body {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */\n    get body(): ReadableStream | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */\n    get bodyUsed(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */\n    arrayBuffer(): Promise<ArrayBuffer>;\n    bytes(): Promise<Uint8Array>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */\n    text(): Promise<string>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */\n    json<T>(): Promise<T>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */\n    formData(): Promise<FormData>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */\n    blob(): Promise<Blob>;\n}\n/**\n * This Fetch API interface represents the response to a request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)\n */\ndeclare var Response: {\n    prototype: Response;\n    new (body?: BodyInit | null, init?: ResponseInit): Response;\n    error(): Response;\n    redirect(url: string, status?: number): Response;\n    json(any: any, maybeInit?: (ResponseInit | Response)): Response;\n};\n/**\n * This Fetch API interface represents the response to a request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)\n */\ninterface Response extends Body {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */\n    clone(): Response;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */\n    status: number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */\n    statusText: string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */\n    headers: Headers;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */\n    ok: boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */\n    redirected: boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */\n    url: string;\n    webSocket: WebSocket | null;\n    cf: any | undefined;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) */\n    type: \"default\" | \"error\";\n}\ninterface ResponseInit {\n    status?: number;\n    statusText?: string;\n    headers?: HeadersInit;\n    cf?: any;\n    webSocket?: (WebSocket | null);\n    encodeBody?: \"automatic\" | \"manual\";\n}\ntype RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;\n/**\n * This Fetch API interface represents a resource request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)\n */\ndeclare var Request: {\n    prototype: Request;\n    new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;\n};\n/**\n * This Fetch API interface represents a resource request.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)\n */\ninterface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */\n    clone(): Request<CfHostMetadata, Cf>;\n    /**\n     * Returns request's HTTP method, which is \"GET\" by default.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)\n     */\n    method: string;\n    /**\n     * Returns the URL of request as a string.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)\n     */\n    url: string;\n    /**\n     * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the \"Host\" header.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)\n     */\n    headers: Headers;\n    /**\n     * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)\n     */\n    redirect: string;\n    fetcher: Fetcher | null;\n    /**\n     * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)\n     */\n    signal: AbortSignal;\n    cf: Cf | undefined;\n    /**\n     * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)\n     */\n    integrity: string;\n    /* Returns a boolean indicating whether or not request can outlive the global in which it was created. */\n    keepalive: boolean;\n}\ninterface RequestInit<Cf = CfProperties> {\n    /* A string to set request's method. */\n    method?: string;\n    /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */\n    headers?: HeadersInit;\n    /* A BodyInit object or null to set request's body. */\n    body?: BodyInit | null;\n    /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */\n    redirect?: string;\n    fetcher?: (Fetcher | null);\n    cf?: Cf;\n    /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */\n    integrity?: string;\n    /* An AbortSignal to set request's signal. */\n    signal?: (AbortSignal | null);\n    encodeResponseBody?: \"automatic\" | \"manual\";\n}\ntype Service<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T>;\ntype Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | \"fetch\" | \"connect\"> : unknown) & {\n    fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n    connect(address: SocketAddress | string, options?: SocketOptions): Socket;\n};\ninterface FetcherPutOptions {\n    expiration?: number;\n    expirationTtl?: number;\n}\ninterface KVNamespaceListKey<Metadata, Key extends string = string> {\n    name: Key;\n    expiration?: number;\n    metadata?: Metadata;\n}\ntype KVNamespaceListResult<Metadata, Key extends string = string> = {\n    list_complete: false;\n    keys: KVNamespaceListKey<Metadata, Key>[];\n    cursor: string;\n    cacheStatus: string | null;\n} | {\n    list_complete: true;\n    keys: KVNamespaceListKey<Metadata, Key>[];\n    cacheStatus: string | null;\n};\ninterface KVNamespace<Key extends string = string> {\n    get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;\n    get(key: Key, type: \"text\"): Promise<string | null>;\n    get<ExpectedValue = unknown>(key: Key, type: \"json\"): Promise<ExpectedValue | null>;\n    get(key: Key, type: \"arrayBuffer\"): Promise<ArrayBuffer | null>;\n    get(key: Key, type: \"stream\"): Promise<ReadableStream | null>;\n    get(key: Key, options?: KVNamespaceGetOptions<\"text\">): Promise<string | null>;\n    get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<\"json\">): Promise<ExpectedValue | null>;\n    get(key: Key, options?: KVNamespaceGetOptions<\"arrayBuffer\">): Promise<ArrayBuffer | null>;\n    get(key: Key, options?: KVNamespaceGetOptions<\"stream\">): Promise<ReadableStream | null>;\n    get(key: Array<Key>, type: \"text\"): Promise<Map<string, string | null>>;\n    get<ExpectedValue = unknown>(key: Array<Key>, type: \"json\"): Promise<Map<string, ExpectedValue | null>>;\n    get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;\n    get(key: Array<Key>, options?: KVNamespaceGetOptions<\"text\">): Promise<Map<string, string | null>>;\n    get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<\"json\">): Promise<Map<string, ExpectedValue | null>>;\n    list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;\n    put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;\n    getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, type: \"text\"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: \"json\"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, type: \"arrayBuffer\"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, type: \"stream\"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"text\">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"json\">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"arrayBuffer\">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<\"stream\">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;\n    getWithMetadata<Metadata = unknown>(key: Array<Key>, type: \"text\"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: \"json\"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;\n    getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;\n    getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<\"text\">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;\n    getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<\"json\">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;\n    delete(key: Key): Promise<void>;\n}\ninterface KVNamespaceListOptions {\n    limit?: number;\n    prefix?: (string | null);\n    cursor?: (string | null);\n}\ninterface KVNamespaceGetOptions<Type> {\n    type: Type;\n    cacheTtl?: number;\n}\ninterface KVNamespacePutOptions {\n    expiration?: number;\n    expirationTtl?: number;\n    metadata?: (any | null);\n}\ninterface KVNamespaceGetWithMetadataResult<Value, Metadata> {\n    value: Value | null;\n    metadata: Metadata | null;\n    cacheStatus: string | null;\n}\ntype QueueContentType = \"text\" | \"bytes\" | \"json\" | \"v8\";\ninterface Queue<Body = unknown> {\n    send(message: Body, options?: QueueSendOptions): Promise<void>;\n    sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<void>;\n}\ninterface QueueSendOptions {\n    contentType?: QueueContentType;\n    delaySeconds?: number;\n}\ninterface QueueSendBatchOptions {\n    delaySeconds?: number;\n}\ninterface MessageSendRequest<Body = unknown> {\n    body: Body;\n    contentType?: QueueContentType;\n    delaySeconds?: number;\n}\ninterface QueueRetryOptions {\n    delaySeconds?: number;\n}\ninterface Message<Body = unknown> {\n    readonly id: string;\n    readonly timestamp: Date;\n    readonly body: Body;\n    readonly attempts: number;\n    retry(options?: QueueRetryOptions): void;\n    ack(): void;\n}\ninterface QueueEvent<Body = unknown> extends ExtendableEvent {\n    readonly messages: readonly Message<Body>[];\n    readonly queue: string;\n    retryAll(options?: QueueRetryOptions): void;\n    ackAll(): void;\n}\ninterface MessageBatch<Body = unknown> {\n    readonly messages: readonly Message<Body>[];\n    readonly queue: string;\n    retryAll(options?: QueueRetryOptions): void;\n    ackAll(): void;\n}\ninterface R2Error extends Error {\n    readonly name: string;\n    readonly code: number;\n    readonly message: string;\n    readonly action: string;\n    readonly stack: any;\n}\ninterface R2ListOptions {\n    limit?: number;\n    prefix?: string;\n    cursor?: string;\n    delimiter?: string;\n    startAfter?: string;\n    include?: (\"httpMetadata\" | \"customMetadata\")[];\n}\ndeclare abstract class R2Bucket {\n    head(key: string): Promise<R2Object | null>;\n    get(key: string, options: R2GetOptions & {\n        onlyIf: R2Conditional | Headers;\n    }): Promise<R2ObjectBody | R2Object | null>;\n    get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;\n    put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {\n        onlyIf: R2Conditional | Headers;\n    }): Promise<R2Object | null>;\n    put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;\n    createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;\n    resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;\n    delete(keys: string | string[]): Promise<void>;\n    list(options?: R2ListOptions): Promise<R2Objects>;\n}\ninterface R2MultipartUpload {\n    readonly key: string;\n    readonly uploadId: string;\n    uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;\n    abort(): Promise<void>;\n    complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;\n}\ninterface R2UploadedPart {\n    partNumber: number;\n    etag: string;\n}\ndeclare abstract class R2Object {\n    readonly key: string;\n    readonly version: string;\n    readonly size: number;\n    readonly etag: string;\n    readonly httpEtag: string;\n    readonly checksums: R2Checksums;\n    readonly uploaded: Date;\n    readonly httpMetadata?: R2HTTPMetadata;\n    readonly customMetadata?: Record<string, string>;\n    readonly range?: R2Range;\n    readonly storageClass: string;\n    readonly ssecKeyMd5?: string;\n    writeHttpMetadata(headers: Headers): void;\n}\ninterface R2ObjectBody extends R2Object {\n    get body(): ReadableStream;\n    get bodyUsed(): boolean;\n    arrayBuffer(): Promise<ArrayBuffer>;\n    text(): Promise<string>;\n    json<T>(): Promise<T>;\n    blob(): Promise<Blob>;\n}\ntype R2Range = {\n    offset: number;\n    length?: number;\n} | {\n    offset?: number;\n    length: number;\n} | {\n    suffix: number;\n};\ninterface R2Conditional {\n    etagMatches?: string;\n    etagDoesNotMatch?: string;\n    uploadedBefore?: Date;\n    uploadedAfter?: Date;\n    secondsGranularity?: boolean;\n}\ninterface R2GetOptions {\n    onlyIf?: (R2Conditional | Headers);\n    range?: (R2Range | Headers);\n    ssecKey?: (ArrayBuffer | string);\n}\ninterface R2PutOptions {\n    onlyIf?: (R2Conditional | Headers);\n    httpMetadata?: (R2HTTPMetadata | Headers);\n    customMetadata?: Record<string, string>;\n    md5?: (ArrayBuffer | string);\n    sha1?: (ArrayBuffer | string);\n    sha256?: (ArrayBuffer | string);\n    sha384?: (ArrayBuffer | string);\n    sha512?: (ArrayBuffer | string);\n    storageClass?: string;\n    ssecKey?: (ArrayBuffer | string);\n}\ninterface R2MultipartOptions {\n    httpMetadata?: (R2HTTPMetadata | Headers);\n    customMetadata?: Record<string, string>;\n    storageClass?: string;\n    ssecKey?: (ArrayBuffer | string);\n}\ninterface R2Checksums {\n    readonly md5?: ArrayBuffer;\n    readonly sha1?: ArrayBuffer;\n    readonly sha256?: ArrayBuffer;\n    readonly sha384?: ArrayBuffer;\n    readonly sha512?: ArrayBuffer;\n    toJSON(): R2StringChecksums;\n}\ninterface R2StringChecksums {\n    md5?: string;\n    sha1?: string;\n    sha256?: string;\n    sha384?: string;\n    sha512?: string;\n}\ninterface R2HTTPMetadata {\n    contentType?: string;\n    contentLanguage?: string;\n    contentDisposition?: string;\n    contentEncoding?: string;\n    cacheControl?: string;\n    cacheExpiry?: Date;\n}\ntype R2Objects = {\n    objects: R2Object[];\n    delimitedPrefixes: string[];\n} & ({\n    truncated: true;\n    cursor: string;\n} | {\n    truncated: false;\n});\ninterface R2UploadPartOptions {\n    ssecKey?: (ArrayBuffer | string);\n}\ndeclare abstract class ScheduledEvent extends ExtendableEvent {\n    readonly scheduledTime: number;\n    readonly cron: string;\n    noRetry(): void;\n}\ninterface ScheduledController {\n    readonly scheduledTime: number;\n    readonly cron: string;\n    noRetry(): void;\n}\ninterface QueuingStrategy<T = any> {\n    highWaterMark?: (number | bigint);\n    size?: (chunk: T) => number | bigint;\n}\ninterface UnderlyingSink<W = any> {\n    type?: string;\n    start?: (controller: WritableStreamDefaultController) => void | Promise<void>;\n    write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;\n    abort?: (reason: any) => void | Promise<void>;\n    close?: () => void | Promise<void>;\n}\ninterface UnderlyingByteSource {\n    type: \"bytes\";\n    autoAllocateChunkSize?: number;\n    start?: (controller: ReadableByteStreamController) => void | Promise<void>;\n    pull?: (controller: ReadableByteStreamController) => void | Promise<void>;\n    cancel?: (reason: any) => void | Promise<void>;\n}\ninterface UnderlyingSource<R = any> {\n    type?: \"\" | undefined;\n    start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;\n    pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;\n    cancel?: (reason: any) => void | Promise<void>;\n    expectedLength?: (number | bigint);\n}\ninterface Transformer<I = any, O = any> {\n    readableType?: string;\n    writableType?: string;\n    start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;\n    transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;\n    flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;\n    cancel?: (reason: any) => void | Promise<void>;\n    expectedLength?: number;\n}\ninterface StreamPipeOptions {\n    /**\n     * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.\n     *\n     * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n     *\n     * Errors and closures of the source and destination streams propagate as follows:\n     *\n     * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.\n     *\n     * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.\n     *\n     * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.\n     *\n     * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.\n     *\n     * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.\n     */\n    preventClose?: boolean;\n    preventAbort?: boolean;\n    preventCancel?: boolean;\n    signal?: AbortSignal;\n}\ntype ReadableStreamReadResult<R = any> = {\n    done: false;\n    value: R;\n} | {\n    done: true;\n    value?: undefined;\n};\n/**\n * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)\n */\ninterface ReadableStream<R = any> {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */\n    get locked(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */\n    cancel(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */\n    getReader(): ReadableStreamDefaultReader<R>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */\n    getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */\n    pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */\n    pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */\n    tee(): [\n        ReadableStream<R>,\n        ReadableStream<R>\n    ];\n    values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;\n    [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;\n}\n/**\n * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)\n */\ndeclare const ReadableStream: {\n    prototype: ReadableStream;\n    new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;\n    new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;\n};\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */\ndeclare class ReadableStreamDefaultReader<R = any> {\n    constructor(stream: ReadableStream);\n    get closed(): Promise<void>;\n    cancel(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */\n    read(): Promise<ReadableStreamReadResult<R>>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */\n    releaseLock(): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */\ndeclare class ReadableStreamBYOBReader {\n    constructor(stream: ReadableStream);\n    get closed(): Promise<void>;\n    cancel(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */\n    read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */\n    releaseLock(): void;\n    readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;\n}\ninterface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {\n    min?: number;\n}\ninterface ReadableStreamGetReaderOptions {\n    /**\n     * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.\n     *\n     * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation.\n     */\n    mode: \"byob\";\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */\ndeclare abstract class ReadableStreamBYOBRequest {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */\n    get view(): Uint8Array | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */\n    respond(bytesWritten: number): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */\n    respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;\n    get atLeast(): number | null;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */\ndeclare abstract class ReadableStreamDefaultController<R = any> {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */\n    close(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */\n    enqueue(chunk?: R): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */\n    error(reason: any): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */\ndeclare abstract class ReadableByteStreamController {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */\n    get byobRequest(): ReadableStreamBYOBRequest | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */\n    close(): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */\n    enqueue(chunk: ArrayBuffer | ArrayBufferView): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */\n    error(reason: any): void;\n}\n/**\n * This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)\n */\ndeclare abstract class WritableStreamDefaultController {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */\n    get signal(): AbortSignal;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */\n    error(reason?: any): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */\ndeclare abstract class TransformStreamDefaultController<O = any> {\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */\n    enqueue(chunk?: O): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */\n    error(reason: any): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */\n    terminate(): void;\n}\ninterface ReadableWritablePair<R = any, W = any> {\n    /**\n     * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.\n     *\n     * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n     */\n    writable: WritableStream<W>;\n    readable: ReadableStream<R>;\n}\n/**\n * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)\n */\ndeclare class WritableStream<W = any> {\n    constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */\n    get locked(): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */\n    abort(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */\n    close(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */\n    getWriter(): WritableStreamDefaultWriter<W>;\n}\n/**\n * This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)\n */\ndeclare class WritableStreamDefaultWriter<W = any> {\n    constructor(stream: WritableStream);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */\n    get closed(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */\n    get ready(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */\n    get desiredSize(): number | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */\n    abort(reason?: any): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */\n    close(): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */\n    write(chunk?: W): Promise<void>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */\n    releaseLock(): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */\ndeclare class TransformStream<I = any, O = any> {\n    constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */\n    get readable(): ReadableStream<O>;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */\n    get writable(): WritableStream<I>;\n}\ndeclare class FixedLengthStream extends IdentityTransformStream {\n    constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);\n}\ndeclare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {\n    constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);\n}\ninterface IdentityTransformStreamQueuingStrategy {\n    highWaterMark?: (number | bigint);\n}\ninterface ReadableStreamValuesOptions {\n    preventCancel?: boolean;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */\ndeclare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {\n    constructor(format: \"gzip\" | \"deflate\" | \"deflate-raw\");\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */\ndeclare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {\n    constructor(format: \"gzip\" | \"deflate\" | \"deflate-raw\");\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */\ndeclare class TextEncoderStream extends TransformStream<string, Uint8Array> {\n    constructor();\n    get encoding(): string;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */\ndeclare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {\n    constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);\n    get encoding(): string;\n    get fatal(): boolean;\n    get ignoreBOM(): boolean;\n}\ninterface TextDecoderStreamTextDecoderStreamInit {\n    fatal?: boolean;\n    ignoreBOM?: boolean;\n}\n/**\n * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)\n */\ndeclare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {\n    constructor(init: QueuingStrategyInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */\n    get highWaterMark(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */\n    get size(): (chunk?: any) => number;\n}\n/**\n * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)\n */\ndeclare class CountQueuingStrategy implements QueuingStrategy {\n    constructor(init: QueuingStrategyInit);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */\n    get highWaterMark(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */\n    get size(): (chunk?: any) => number;\n}\ninterface QueuingStrategyInit {\n    /**\n     * Creates a new ByteLengthQueuingStrategy with the provided high water mark.\n     *\n     * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.\n     */\n    highWaterMark: number;\n}\ninterface ScriptVersion {\n    id?: string;\n    tag?: string;\n    message?: string;\n}\ndeclare abstract class TailEvent extends ExtendableEvent {\n    readonly events: TraceItem[];\n    readonly traces: TraceItem[];\n}\ninterface TraceItem {\n    readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;\n    readonly eventTimestamp: number | null;\n    readonly logs: TraceLog[];\n    readonly exceptions: TraceException[];\n    readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];\n    readonly scriptName: string | null;\n    readonly entrypoint?: string;\n    readonly scriptVersion?: ScriptVersion;\n    readonly dispatchNamespace?: string;\n    readonly scriptTags?: string[];\n    readonly outcome: string;\n    readonly executionModel: string;\n    readonly truncated: boolean;\n    readonly cpuTime: number;\n    readonly wallTime: number;\n}\ninterface TraceItemAlarmEventInfo {\n    readonly scheduledTime: Date;\n}\ninterface TraceItemCustomEventInfo {\n}\ninterface TraceItemScheduledEventInfo {\n    readonly scheduledTime: number;\n    readonly cron: string;\n}\ninterface TraceItemQueueEventInfo {\n    readonly queue: string;\n    readonly batchSize: number;\n}\ninterface TraceItemEmailEventInfo {\n    readonly mailFrom: string;\n    readonly rcptTo: string;\n    readonly rawSize: number;\n}\ninterface TraceItemTailEventInfo {\n    readonly consumedEvents: TraceItemTailEventInfoTailItem[];\n}\ninterface TraceItemTailEventInfoTailItem {\n    readonly scriptName: string | null;\n}\ninterface TraceItemFetchEventInfo {\n    readonly response?: TraceItemFetchEventInfoResponse;\n    readonly request: TraceItemFetchEventInfoRequest;\n}\ninterface TraceItemFetchEventInfoRequest {\n    readonly cf?: any;\n    readonly headers: Record<string, string>;\n    readonly method: string;\n    readonly url: string;\n    getUnredacted(): TraceItemFetchEventInfoRequest;\n}\ninterface TraceItemFetchEventInfoResponse {\n    readonly status: number;\n}\ninterface TraceItemJsRpcEventInfo {\n    readonly rpcMethod: string;\n}\ninterface TraceItemHibernatableWebSocketEventInfo {\n    readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;\n}\ninterface TraceItemHibernatableWebSocketEventInfoMessage {\n    readonly webSocketEventType: string;\n}\ninterface TraceItemHibernatableWebSocketEventInfoClose {\n    readonly webSocketEventType: string;\n    readonly code: number;\n    readonly wasClean: boolean;\n}\ninterface TraceItemHibernatableWebSocketEventInfoError {\n    readonly webSocketEventType: string;\n}\ninterface TraceLog {\n    readonly timestamp: number;\n    readonly level: string;\n    readonly message: any;\n}\ninterface TraceException {\n    readonly timestamp: number;\n    readonly message: string;\n    readonly name: string;\n    readonly stack?: string;\n}\ninterface TraceDiagnosticChannelEvent {\n    readonly timestamp: number;\n    readonly channel: string;\n    readonly message: any;\n}\ninterface TraceMetrics {\n    readonly cpuTime: number;\n    readonly wallTime: number;\n}\ninterface UnsafeTraceMetrics {\n    fromTrace(item: TraceItem): TraceMetrics;\n}\n/**\n * The URL interface represents an object providing static methods used for creating object URLs.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)\n */\ndeclare class URL {\n    constructor(url: string | URL, base?: string | URL);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */\n    get origin(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */\n    get href(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */\n    set href(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */\n    get protocol(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */\n    set protocol(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */\n    get username(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */\n    set username(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */\n    get password(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */\n    set password(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */\n    get host(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */\n    set host(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */\n    get hostname(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */\n    set hostname(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */\n    get port(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */\n    set port(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */\n    get pathname(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */\n    set pathname(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */\n    get search(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */\n    set search(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */\n    get hash(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */\n    set hash(value: string);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */\n    get searchParams(): URLSearchParams;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */\n    toJSON(): string;\n    /*function toString() { [native code] }*/\n    toString(): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */\n    static canParse(url: string, base?: string): boolean;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */\n    static parse(url: string, base?: string): URL | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */\n    static createObjectURL(object: File | Blob): string;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */\n    static revokeObjectURL(object_url: string): void;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */\ndeclare class URLSearchParams {\n    constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */\n    get size(): number;\n    /**\n     * Appends a specified key/value pair as a new search parameter.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)\n     */\n    append(name: string, value: string): void;\n    /**\n     * Deletes the given search parameter, and its associated value, from the list of all search parameters.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)\n     */\n    delete(name: string, value?: string): void;\n    /**\n     * Returns the first value associated to the given search parameter.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)\n     */\n    get(name: string): string | null;\n    /**\n     * Returns all the values association with a given search parameter.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)\n     */\n    getAll(name: string): string[];\n    /**\n     * Returns a Boolean indicating if such a search parameter exists.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)\n     */\n    has(name: string, value?: string): boolean;\n    /**\n     * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)\n     */\n    set(name: string, value: string): void;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */\n    sort(): void;\n    /* Returns an array of key, value pairs for every entry in the search params. */\n    entries(): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n    /* Returns a list of keys in the search params. */\n    keys(): IterableIterator<string>;\n    /* Returns a list of values in the search params. */\n    values(): IterableIterator<string>;\n    forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;\n    /*function toString() { [native code] } Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */\n    toString(): string;\n    [Symbol.iterator](): IterableIterator<[\n        key: string,\n        value: string\n    ]>;\n}\ndeclare class URLPattern {\n    constructor(input?: (string | URLPatternURLPatternInit), baseURL?: (string | URLPatternURLPatternOptions), patternOptions?: URLPatternURLPatternOptions);\n    get protocol(): string;\n    get username(): string;\n    get password(): string;\n    get hostname(): string;\n    get port(): string;\n    get pathname(): string;\n    get search(): string;\n    get hash(): string;\n    test(input?: (string | URLPatternURLPatternInit), baseURL?: string): boolean;\n    exec(input?: (string | URLPatternURLPatternInit), baseURL?: string): URLPatternURLPatternResult | null;\n}\ninterface URLPatternURLPatternInit {\n    protocol?: string;\n    username?: string;\n    password?: string;\n    hostname?: string;\n    port?: string;\n    pathname?: string;\n    search?: string;\n    hash?: string;\n    baseURL?: string;\n}\ninterface URLPatternURLPatternComponentResult {\n    input: string;\n    groups: Record<string, string>;\n}\ninterface URLPatternURLPatternResult {\n    inputs: (string | URLPatternURLPatternInit)[];\n    protocol: URLPatternURLPatternComponentResult;\n    username: URLPatternURLPatternComponentResult;\n    password: URLPatternURLPatternComponentResult;\n    hostname: URLPatternURLPatternComponentResult;\n    port: URLPatternURLPatternComponentResult;\n    pathname: URLPatternURLPatternComponentResult;\n    search: URLPatternURLPatternComponentResult;\n    hash: URLPatternURLPatternComponentResult;\n}\ninterface URLPatternURLPatternOptions {\n    ignoreCase?: boolean;\n}\n/**\n * A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)\n */\ndeclare class CloseEvent extends Event {\n    constructor(type: string, initializer?: CloseEventInit);\n    /**\n     * Returns the WebSocket connection close code provided by the server.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)\n     */\n    readonly code: number;\n    /**\n     * Returns the WebSocket connection close reason provided by the server.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)\n     */\n    readonly reason: string;\n    /**\n     * Returns true if the connection closed cleanly; false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)\n     */\n    readonly wasClean: boolean;\n}\ninterface CloseEventInit {\n    code?: number;\n    reason?: string;\n    wasClean?: boolean;\n}\n/**\n * A message received by a target object.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)\n */\ndeclare class MessageEvent extends Event {\n    constructor(type: string, initializer: MessageEventInit);\n    /**\n     * Returns the data of the message.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)\n     */\n    readonly data: ArrayBuffer | string;\n}\ninterface MessageEventInit {\n    data: ArrayBuffer | string;\n}\ntype WebSocketEventMap = {\n    close: CloseEvent;\n    message: MessageEvent;\n    open: Event;\n    error: ErrorEvent;\n};\n/**\n * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)\n */\ndeclare var WebSocket: {\n    prototype: WebSocket;\n    new (url: string, protocols?: (string[] | string)): WebSocket;\n    readonly READY_STATE_CONNECTING: number;\n    readonly CONNECTING: number;\n    readonly READY_STATE_OPEN: number;\n    readonly OPEN: number;\n    readonly READY_STATE_CLOSING: number;\n    readonly CLOSING: number;\n    readonly READY_STATE_CLOSED: number;\n    readonly CLOSED: number;\n};\n/**\n * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)\n */\ninterface WebSocket extends EventTarget<WebSocketEventMap> {\n    accept(): void;\n    /**\n     * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)\n     */\n    send(message: (ArrayBuffer | ArrayBufferView) | string): void;\n    /**\n     * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)\n     */\n    close(code?: number, reason?: string): void;\n    serializeAttachment(attachment: any): void;\n    deserializeAttachment(): any | null;\n    /**\n     * Returns the state of the WebSocket object's connection. It can have the values described below.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)\n     */\n    readyState: number;\n    /**\n     * Returns the URL that was used to establish the WebSocket connection.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)\n     */\n    url: string | null;\n    /**\n     * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)\n     */\n    protocol: string | null;\n    /**\n     * Returns the extensions selected by the server, if any.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)\n     */\n    extensions: string | null;\n}\ndeclare const WebSocketPair: {\n    new (): {\n        0: WebSocket;\n        1: WebSocket;\n    };\n};\ninterface SqlStorage {\n    exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;\n    get databaseSize(): number;\n    Cursor: typeof SqlStorageCursor;\n    Statement: typeof SqlStorageStatement;\n}\ndeclare abstract class SqlStorageStatement {\n}\ntype SqlStorageValue = ArrayBuffer | string | number | null;\ndeclare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {\n    next(): {\n        done?: false;\n        value: T;\n    } | {\n        done: true;\n        value?: never;\n    };\n    toArray(): T[];\n    one(): T;\n    raw<U extends SqlStorageValue[]>(): IterableIterator<U>;\n    columnNames: string[];\n    get rowsRead(): number;\n    get rowsWritten(): number;\n    [Symbol.iterator](): IterableIterator<T>;\n}\ninterface Socket {\n    get readable(): ReadableStream;\n    get writable(): WritableStream;\n    get closed(): Promise<void>;\n    get opened(): Promise<SocketInfo>;\n    close(): Promise<void>;\n    startTls(options?: TlsOptions): Socket;\n}\ninterface SocketOptions {\n    secureTransport?: string;\n    allowHalfOpen: boolean;\n    highWaterMark?: (number | bigint);\n}\ninterface SocketAddress {\n    hostname: string;\n    port: number;\n}\ninterface TlsOptions {\n    expectedServerHostname?: string;\n}\ninterface SocketInfo {\n    remoteAddress?: string;\n    localAddress?: string;\n}\n/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */\ndeclare class EventSource extends EventTarget {\n    constructor(url: string, init?: EventSourceEventSourceInit);\n    /**\n     * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)\n     */\n    close(): void;\n    /**\n     * Returns the URL providing the event stream.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)\n     */\n    get url(): string;\n    /**\n     * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to \"include\", and false otherwise.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)\n     */\n    get withCredentials(): boolean;\n    /**\n     * Returns the state of this EventSource object's connection. It can have the values described below.\n     *\n     * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)\n     */\n    get readyState(): number;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n    get onopen(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n    set onopen(value: any | null);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n    get onmessage(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n    set onmessage(value: any | null);\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n    get onerror(): any | null;\n    /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n    set onerror(value: any | null);\n    static readonly CONNECTING: number;\n    static readonly OPEN: number;\n    static readonly CLOSED: number;\n    static from(stream: ReadableStream): EventSource;\n}\ninterface EventSourceEventSourceInit {\n    withCredentials?: boolean;\n    fetcher?: Fetcher;\n}\ninterface Container {\n    get running(): boolean;\n    start(options?: ContainerStartupOptions): void;\n    monitor(): Promise<void>;\n    destroy(error?: any): Promise<void>;\n    signal(signo: number): void;\n    getTcpPort(port: number): Fetcher;\n}\ninterface ContainerStartupOptions {\n    entrypoint?: string[];\n    enableInternet: boolean;\n    env?: Record<string, string>;\n}\ntype AiImageClassificationInput = {\n    image: number[];\n};\ntype AiImageClassificationOutput = {\n    score?: number;\n    label?: string;\n}[];\ndeclare abstract class BaseAiImageClassification {\n    inputs: AiImageClassificationInput;\n    postProcessedOutputs: AiImageClassificationOutput;\n}\ntype AiImageToTextInput = {\n    image: number[];\n    prompt?: string;\n    max_tokens?: number;\n    temperature?: number;\n    top_p?: number;\n    top_k?: number;\n    seed?: number;\n    repetition_penalty?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    raw?: boolean;\n    messages?: RoleScopedChatInput[];\n};\ntype AiImageToTextOutput = {\n    description: string;\n};\ndeclare abstract class BaseAiImageToText {\n    inputs: AiImageToTextInput;\n    postProcessedOutputs: AiImageToTextOutput;\n}\ntype AiImageTextToTextInput = {\n    image: string;\n    prompt?: string;\n    max_tokens?: number;\n    temperature?: number;\n    ignore_eos?: boolean;\n    top_p?: number;\n    top_k?: number;\n    seed?: number;\n    repetition_penalty?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    raw?: boolean;\n    messages?: RoleScopedChatInput[];\n};\ntype AiImageTextToTextOutput = {\n    description: string;\n};\ndeclare abstract class BaseAiImageTextToText {\n    inputs: AiImageTextToTextInput;\n    postProcessedOutputs: AiImageTextToTextOutput;\n}\ntype AiObjectDetectionInput = {\n    image: number[];\n};\ntype AiObjectDetectionOutput = {\n    score?: number;\n    label?: string;\n}[];\ndeclare abstract class BaseAiObjectDetection {\n    inputs: AiObjectDetectionInput;\n    postProcessedOutputs: AiObjectDetectionOutput;\n}\ntype AiSentenceSimilarityInput = {\n    source: string;\n    sentences: string[];\n};\ntype AiSentenceSimilarityOutput = number[];\ndeclare abstract class BaseAiSentenceSimilarity {\n    inputs: AiSentenceSimilarityInput;\n    postProcessedOutputs: AiSentenceSimilarityOutput;\n}\ntype AiAutomaticSpeechRecognitionInput = {\n    audio: number[];\n};\ntype AiAutomaticSpeechRecognitionOutput = {\n    text?: string;\n    words?: {\n        word: string;\n        start: number;\n        end: number;\n    }[];\n    vtt?: string;\n};\ndeclare abstract class BaseAiAutomaticSpeechRecognition {\n    inputs: AiAutomaticSpeechRecognitionInput;\n    postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;\n}\ntype AiSummarizationInput = {\n    input_text: string;\n    max_length?: number;\n};\ntype AiSummarizationOutput = {\n    summary: string;\n};\ndeclare abstract class BaseAiSummarization {\n    inputs: AiSummarizationInput;\n    postProcessedOutputs: AiSummarizationOutput;\n}\ntype AiTextClassificationInput = {\n    text: string;\n};\ntype AiTextClassificationOutput = {\n    score?: number;\n    label?: string;\n}[];\ndeclare abstract class BaseAiTextClassification {\n    inputs: AiTextClassificationInput;\n    postProcessedOutputs: AiTextClassificationOutput;\n}\ntype AiTextEmbeddingsInput = {\n    text: string | string[];\n};\ntype AiTextEmbeddingsOutput = {\n    shape: number[];\n    data: number[][];\n};\ndeclare abstract class BaseAiTextEmbeddings {\n    inputs: AiTextEmbeddingsInput;\n    postProcessedOutputs: AiTextEmbeddingsOutput;\n}\ntype RoleScopedChatInput = {\n    role: \"user\" | \"assistant\" | \"system\" | \"tool\" | (string & NonNullable<unknown>);\n    content: string;\n    name?: string;\n};\ntype AiTextGenerationToolLegacyInput = {\n    name: string;\n    description: string;\n    parameters?: {\n        type: \"object\" | (string & NonNullable<unknown>);\n        properties: {\n            [key: string]: {\n                type: string;\n                description?: string;\n            };\n        };\n        required: string[];\n    };\n};\ntype AiTextGenerationToolInput = {\n    type: \"function\" | (string & NonNullable<unknown>);\n    function: {\n        name: string;\n        description: string;\n        parameters?: {\n            type: \"object\" | (string & NonNullable<unknown>);\n            properties: {\n                [key: string]: {\n                    type: string;\n                    description?: string;\n                };\n            };\n            required: string[];\n        };\n    };\n};\ntype AiTextGenerationFunctionsInput = {\n    name: string;\n    code: string;\n};\ntype AiTextGenerationResponseFormat = {\n    type: string;\n    json_schema?: any;\n};\ntype AiTextGenerationInput = {\n    prompt?: string;\n    raw?: boolean;\n    stream?: boolean;\n    max_tokens?: number;\n    temperature?: number;\n    top_p?: number;\n    top_k?: number;\n    seed?: number;\n    repetition_penalty?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    messages?: RoleScopedChatInput[];\n    response_format?: AiTextGenerationResponseFormat;\n    tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);\n    functions?: AiTextGenerationFunctionsInput[];\n};\ntype AiTextGenerationOutput = {\n    response?: string;\n    tool_calls?: {\n        name: string;\n        arguments: unknown;\n    }[];\n} | ReadableStream;\ndeclare abstract class BaseAiTextGeneration {\n    inputs: AiTextGenerationInput;\n    postProcessedOutputs: AiTextGenerationOutput;\n}\ntype AiTextToSpeechInput = {\n    prompt: string;\n    lang?: string;\n};\ntype AiTextToSpeechOutput = Uint8Array | {\n    audio: string;\n};\ndeclare abstract class BaseAiTextToSpeech {\n    inputs: AiTextToSpeechInput;\n    postProcessedOutputs: AiTextToSpeechOutput;\n}\ntype AiTextToImageInput = {\n    prompt: string;\n    negative_prompt?: string;\n    height?: number;\n    width?: number;\n    image?: number[];\n    image_b64?: string;\n    mask?: number[];\n    num_steps?: number;\n    strength?: number;\n    guidance?: number;\n    seed?: number;\n};\ntype AiTextToImageOutput = ReadableStream<Uint8Array>;\ndeclare abstract class BaseAiTextToImage {\n    inputs: AiTextToImageInput;\n    postProcessedOutputs: AiTextToImageOutput;\n}\ntype AiTranslationInput = {\n    text: string;\n    target_lang: string;\n    source_lang?: string;\n};\ntype AiTranslationOutput = {\n    translated_text?: string;\n};\ndeclare abstract class BaseAiTranslation {\n    inputs: AiTranslationInput;\n    postProcessedOutputs: AiTranslationOutput;\n}\ntype Ai_Cf_Openai_Whisper_Input = string | {\n    /**\n     * An array of integers that represent the audio data constrained to 8-bit unsigned integer values\n     */\n    audio: number[];\n};\ninterface Ai_Cf_Openai_Whisper_Output {\n    /**\n     * The transcription\n     */\n    text: string;\n    word_count?: number;\n    words?: {\n        word?: string;\n        /**\n         * The second this word begins in the recording\n         */\n        start?: number;\n        /**\n         * The ending second when the word completes\n         */\n        end?: number;\n    }[];\n    vtt?: string;\n}\ndeclare abstract class Base_Ai_Cf_Openai_Whisper {\n    inputs: Ai_Cf_Openai_Whisper_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;\n}\ntype Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt?: string;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n    image: number[] | (string & NonNullable<unknown>);\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n};\ninterface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {\n    description?: string;\n}\ndeclare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {\n    inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;\n    postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;\n}\ntype Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {\n    /**\n     * An array of integers that represent the audio data constrained to 8-bit unsigned integer values\n     */\n    audio: number[];\n};\ninterface Ai_Cf_Openai_Whisper_Tiny_En_Output {\n    /**\n     * The transcription\n     */\n    text: string;\n    word_count?: number;\n    words?: {\n        word?: string;\n        /**\n         * The second this word begins in the recording\n         */\n        start?: number;\n        /**\n         * The ending second when the word completes\n         */\n        end?: number;\n    }[];\n    vtt?: string;\n}\ndeclare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {\n    inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;\n}\ninterface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {\n    /**\n     * Base64 encoded value of the audio data.\n     */\n    audio: string;\n    /**\n     * Supported tasks are 'translate' or 'transcribe'.\n     */\n    task?: string;\n    /**\n     * The language of the audio being transcribed or translated.\n     */\n    language?: string;\n    /**\n     * Preprocess the audio with a voice activity detection model.\n     */\n    vad_filter?: string;\n    /**\n     * A text prompt to help provide context to the model on the contents of the audio.\n     */\n    initial_prompt?: string;\n    /**\n     * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result.\n     */\n    prefix?: string;\n}\ninterface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {\n    transcription_info?: {\n        /**\n         * The language of the audio being transcribed or translated.\n         */\n        language?: string;\n        /**\n         * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.\n         */\n        language_probability?: number;\n        /**\n         * The total duration of the original audio file, in seconds.\n         */\n        duration?: number;\n        /**\n         * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.\n         */\n        duration_after_vad?: number;\n    };\n    /**\n     * The complete transcription of the audio.\n     */\n    text: string;\n    /**\n     * The total number of words in the transcription.\n     */\n    word_count?: number;\n    segments?: {\n        /**\n         * The starting time of the segment within the audio, in seconds.\n         */\n        start?: number;\n        /**\n         * The ending time of the segment within the audio, in seconds.\n         */\n        end?: number;\n        /**\n         * The transcription of the segment.\n         */\n        text?: string;\n        /**\n         * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.\n         */\n        temperature?: number;\n        /**\n         * The average log probability of the predictions for the words in this segment, indicating overall confidence.\n         */\n        avg_logprob?: number;\n        /**\n         * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.\n         */\n        compression_ratio?: number;\n        /**\n         * The probability that the segment contains no speech, represented as a decimal between 0 and 1.\n         */\n        no_speech_prob?: number;\n        words?: {\n            /**\n             * The individual word transcribed from the audio.\n             */\n            word?: string;\n            /**\n             * The starting time of the word within the audio, in seconds.\n             */\n            start?: number;\n            /**\n             * The ending time of the word within the audio, in seconds.\n             */\n            end?: number;\n        }[];\n    }[];\n    /**\n     * The transcription in WebVTT format, which includes timing and text information for use in subtitles.\n     */\n    vtt?: string;\n}\ndeclare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {\n    inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;\n    postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;\n}\ntype Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding;\ninterface BGEM3InputQueryAndContexts {\n    /**\n     * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts\n     */\n    query?: string;\n    /**\n     * List of provided contexts. Note that the index in this array is important, as the response will refer to it.\n     */\n    contexts: {\n        /**\n         * One of the provided context content\n         */\n        text?: string;\n    }[];\n    /**\n     * When provided with too long context should the model error out or truncate the context to fit?\n     */\n    truncate_inputs?: boolean;\n}\ninterface BGEM3InputEmbedding {\n    text: string | string[];\n    /**\n     * When provided with too long context should the model error out or truncate the context to fit?\n     */\n    truncate_inputs?: boolean;\n}\ntype Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding;\ninterface BGEM3OuputQuery {\n    response?: {\n        /**\n         * Index of the context in the request\n         */\n        id?: number;\n        /**\n         * Score of the context under the index.\n         */\n        score?: number;\n    }[];\n}\ninterface BGEM3OutputEmbeddingForContexts {\n    response?: number[][];\n    shape?: number[];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n}\ninterface BGEM3OuputEmbedding {\n    shape?: number[];\n    /**\n     * Embeddings of the requested text values\n     */\n    data?: number[][];\n    /**\n     * The pooling method used in the embedding process.\n     */\n    pooling?: \"mean\" | \"cls\";\n}\ndeclare abstract class Base_Ai_Cf_Baai_Bge_M3 {\n    inputs: Ai_Cf_Baai_Bge_M3_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;\n}\ninterface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {\n    /**\n     * A text description of the image you want to generate.\n     */\n    prompt: string;\n    /**\n     * The number of diffusion steps; higher values can improve quality but take longer.\n     */\n    steps?: number;\n}\ninterface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {\n    /**\n     * The generated image in Base64 format.\n     */\n    image?: string;\n}\ndeclare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {\n    inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;\n    postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;\n}\ntype Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages;\ninterface Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    image?: number[] | (string & NonNullable<unknown>);\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n    /**\n     * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.\n     */\n    lora?: string;\n}\ninterface Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role: string;\n        /**\n         * The content of the message as a string.\n         */\n        content: string;\n    }[];\n    image?: number[] | string;\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    /**\n     * If true, the response will be streamed back incrementally.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response?: string;\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n} | ReadableStream;\ndeclare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {\n    inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;\n}\ninterface Ai_Cf_Meta_Llama_Guard_3_8B_Input {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender must alternate between 'user' and 'assistant'.\n         */\n        role: \"user\" | \"assistant\";\n        /**\n         * The content of the message as a string.\n         */\n        content: string;\n    }[];\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Dictate the output format of the generated response.\n     */\n    response_format?: {\n        /**\n         * Set to json_object to process and output generated text as JSON.\n         */\n        type?: string;\n    };\n}\ninterface Ai_Cf_Meta_Llama_Guard_3_8B_Output {\n    response?: string | {\n        /**\n         * Whether the conversation is safe or not.\n         */\n        safe?: boolean;\n        /**\n         * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.\n         */\n        categories?: string[];\n    };\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n}\ndeclare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {\n    inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;\n}\ninterface Ai_Cf_Baai_Bge_Reranker_Base_Input {\n    /**\n     * A query you wish to perform against the provided contexts.\n     */\n    /**\n     * Number of returned results starting with the best score.\n     */\n    top_k?: number;\n    /**\n     * List of provided contexts. Note that the index in this array is important, as the response will refer to it.\n     */\n    contexts: {\n        /**\n         * One of the provided context content\n         */\n        text?: string;\n    }[];\n}\ninterface Ai_Cf_Baai_Bge_Reranker_Base_Output {\n    response?: {\n        /**\n         * Index of the context in the request\n         */\n        id?: number;\n        /**\n         * Score of the context under the index.\n         */\n        score?: number;\n    }[];\n}\ndeclare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {\n    inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;\n    postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;\n}\ntype Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages;\ninterface Ai_Cf_Meta_Llama_4_Prompt {\n    /**\n     * The input text prompt for the model to generate a response.\n     */\n    prompt: string;\n    /**\n     * JSON schema that should be fulfilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ninterface Ai_Cf_Meta_Llama_4_Messages {\n    /**\n     * An array of message objects representing the conversation history.\n     */\n    messages: {\n        /**\n         * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').\n         */\n        role?: string;\n        /**\n         * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001\n         */\n        tool_call_id?: string;\n        content?: string | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        }[] | {\n            /**\n             * Type of the content provided\n             */\n            type?: string;\n            text?: string;\n            image_url?: {\n                /**\n                 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted\n                 */\n                url?: string;\n            };\n        };\n    }[];\n    functions?: {\n        name: string;\n        code: string;\n    }[];\n    /**\n     * A list of tools available for the assistant to use.\n     */\n    tools?: ({\n        /**\n         * The name of the tool. More descriptive the better.\n         */\n        name: string;\n        /**\n         * A brief description of what the tool does.\n         */\n        description: string;\n        /**\n         * Schema defining the parameters accepted by the tool.\n         */\n        parameters: {\n            /**\n             * The type of the parameters object (usually 'object').\n             */\n            type: string;\n            /**\n             * List of required parameter names.\n             */\n            required?: string[];\n            /**\n             * Definitions of each parameter.\n             */\n            properties: {\n                [k: string]: {\n                    /**\n                     * The data type of the parameter.\n                     */\n                    type: string;\n                    /**\n                     * A description of the expected parameter.\n                     */\n                    description: string;\n                };\n            };\n        };\n    } | {\n        /**\n         * Specifies the type of tool (e.g., 'function').\n         */\n        type: string;\n        /**\n         * Details of the function tool.\n         */\n        function: {\n            /**\n             * The name of the function.\n             */\n            name: string;\n            /**\n             * A brief description of what the function does.\n             */\n            description: string;\n            /**\n             * Schema defining the parameters accepted by the function.\n             */\n            parameters: {\n                /**\n                 * The type of the parameters object (usually 'object').\n                 */\n                type: string;\n                /**\n                 * List of required parameter names.\n                 */\n                required?: string[];\n                /**\n                 * Definitions of each parameter.\n                 */\n                properties: {\n                    [k: string]: {\n                        /**\n                         * The data type of the parameter.\n                         */\n                        type: string;\n                        /**\n                         * A description of the expected parameter.\n                         */\n                        description: string;\n                    };\n                };\n            };\n        };\n    })[];\n    /**\n     * JSON schema that should be fufilled for the response.\n     */\n    guided_json?: object;\n    /**\n     * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.\n     */\n    raw?: boolean;\n    /**\n     * If true, the response will be streamed back incrementally using SSE, Server Sent Events.\n     */\n    stream?: boolean;\n    /**\n     * The maximum number of tokens to generate in the response.\n     */\n    max_tokens?: number;\n    /**\n     * Controls the randomness of the output; higher values produce more random results.\n     */\n    temperature?: number;\n    /**\n     * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.\n     */\n    top_p?: number;\n    /**\n     * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.\n     */\n    top_k?: number;\n    /**\n     * Random seed for reproducibility of the generation.\n     */\n    seed?: number;\n    /**\n     * Penalty for repeated tokens; higher values discourage repetition.\n     */\n    repetition_penalty?: number;\n    /**\n     * Decreases the likelihood of the model repeating the same lines verbatim.\n     */\n    frequency_penalty?: number;\n    /**\n     * Increases the likelihood of the model introducing new topics.\n     */\n    presence_penalty?: number;\n}\ntype Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {\n    /**\n     * The generated text response from the model\n     */\n    response: string;\n    /**\n     * Usage statistics for the inference request\n     */\n    usage?: {\n        /**\n         * Total number of tokens in input\n         */\n        prompt_tokens?: number;\n        /**\n         * Total number of tokens in output\n         */\n        completion_tokens?: number;\n        /**\n         * Total number of input and output tokens\n         */\n        total_tokens?: number;\n    };\n    /**\n     * An array of tool calls requests made during the response generation\n     */\n    tool_calls?: {\n        /**\n         * The arguments passed to be passed to the tool call request\n         */\n        arguments?: object;\n        /**\n         * The name of the tool to be called\n         */\n        name?: string;\n    }[];\n} | string;\ndeclare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {\n    inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;\n    postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;\n}\ninterface AiModels {\n    \"@cf/huggingface/distilbert-sst-2-int8\": BaseAiTextClassification;\n    \"@cf/stabilityai/stable-diffusion-xl-base-1.0\": BaseAiTextToImage;\n    \"@cf/runwayml/stable-diffusion-v1-5-inpainting\": BaseAiTextToImage;\n    \"@cf/runwayml/stable-diffusion-v1-5-img2img\": BaseAiTextToImage;\n    \"@cf/lykon/dreamshaper-8-lcm\": BaseAiTextToImage;\n    \"@cf/bytedance/stable-diffusion-xl-lightning\": BaseAiTextToImage;\n    \"@cf/myshell-ai/melotts\": BaseAiTextToSpeech;\n    \"@cf/baai/bge-base-en-v1.5\": BaseAiTextEmbeddings;\n    \"@cf/baai/bge-small-en-v1.5\": BaseAiTextEmbeddings;\n    \"@cf/baai/bge-large-en-v1.5\": BaseAiTextEmbeddings;\n    \"@cf/microsoft/resnet-50\": BaseAiImageClassification;\n    \"@cf/facebook/detr-resnet-50\": BaseAiObjectDetection;\n    \"@cf/meta/llama-2-7b-chat-int8\": BaseAiTextGeneration;\n    \"@cf/mistral/mistral-7b-instruct-v0.1\": BaseAiTextGeneration;\n    \"@cf/meta/llama-2-7b-chat-fp16\": BaseAiTextGeneration;\n    \"@hf/thebloke/llama-2-13b-chat-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/mistral-7b-instruct-v0.1-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/zephyr-7b-beta-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/openhermes-2.5-mistral-7b-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/neural-chat-7b-v3-1-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/llamaguard-7b-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/deepseek-coder-6.7b-base-awq\": BaseAiTextGeneration;\n    \"@hf/thebloke/deepseek-coder-6.7b-instruct-awq\": BaseAiTextGeneration;\n    \"@cf/deepseek-ai/deepseek-math-7b-instruct\": BaseAiTextGeneration;\n    \"@cf/defog/sqlcoder-7b-2\": BaseAiTextGeneration;\n    \"@cf/openchat/openchat-3.5-0106\": BaseAiTextGeneration;\n    \"@cf/tiiuae/falcon-7b-instruct\": BaseAiTextGeneration;\n    \"@cf/thebloke/discolm-german-7b-v1-awq\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-0.5b-chat\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-7b-chat-awq\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-14b-chat-awq\": BaseAiTextGeneration;\n    \"@cf/tinyllama/tinyllama-1.1b-chat-v1.0\": BaseAiTextGeneration;\n    \"@cf/microsoft/phi-2\": BaseAiTextGeneration;\n    \"@cf/qwen/qwen1.5-1.8b-chat\": BaseAiTextGeneration;\n    \"@cf/mistral/mistral-7b-instruct-v0.2-lora\": BaseAiTextGeneration;\n    \"@hf/nousresearch/hermes-2-pro-mistral-7b\": BaseAiTextGeneration;\n    \"@hf/nexusflow/starling-lm-7b-beta\": BaseAiTextGeneration;\n    \"@hf/google/gemma-7b-it\": BaseAiTextGeneration;\n    \"@cf/meta-llama/llama-2-7b-chat-hf-lora\": BaseAiTextGeneration;\n    \"@cf/google/gemma-2b-it-lora\": BaseAiTextGeneration;\n    \"@cf/google/gemma-7b-it-lora\": BaseAiTextGeneration;\n    \"@hf/mistral/mistral-7b-instruct-v0.2\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3-8b-instruct\": BaseAiTextGeneration;\n    \"@cf/fblgit/una-cybertron-7b-v2-bf16\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3-8b-instruct-awq\": BaseAiTextGeneration;\n    \"@hf/meta-llama/meta-llama-3-8b-instruct\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.1-8b-instruct\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.1-8b-instruct-fp8\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.1-8b-instruct-awq\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.2-3b-instruct\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.2-1b-instruct\": BaseAiTextGeneration;\n    \"@cf/meta/llama-3.3-70b-instruct-fp8-fast\": BaseAiTextGeneration;\n    \"@cf/deepseek-ai/deepseek-r1-distill-qwen-32b\": BaseAiTextGeneration;\n    \"@cf/meta/m2m100-1.2b\": BaseAiTranslation;\n    \"@cf/facebook/bart-large-cnn\": BaseAiSummarization;\n    \"@cf/llava-hf/llava-1.5-7b-hf\": BaseAiImageToText;\n    \"@cf/openai/whisper\": Base_Ai_Cf_Openai_Whisper;\n    \"@cf/unum/uform-gen2-qwen-500m\": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;\n    \"@cf/openai/whisper-tiny-en\": Base_Ai_Cf_Openai_Whisper_Tiny_En;\n    \"@cf/openai/whisper-large-v3-turbo\": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;\n    \"@cf/baai/bge-m3\": Base_Ai_Cf_Baai_Bge_M3;\n    \"@cf/black-forest-labs/flux-1-schnell\": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;\n    \"@cf/meta/llama-3.2-11b-vision-instruct\": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;\n    \"@cf/meta/llama-guard-3-8b\": Base_Ai_Cf_Meta_Llama_Guard_3_8B;\n    \"@cf/baai/bge-reranker-base\": Base_Ai_Cf_Baai_Bge_Reranker_Base;\n    \"@cf/meta/llama-4-scout-17b-16e-instruct\": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;\n}\ntype AiOptions = {\n    gateway?: GatewayOptions;\n    returnRawResponse?: boolean;\n    prefix?: string;\n    extraHeaders?: object;\n};\ntype ConversionResponse = {\n    name: string;\n    mimeType: string;\n    format: \"markdown\";\n    tokens: number;\n    data: string;\n};\ntype AiModelsSearchParams = {\n    author?: string;\n    hide_experimental?: boolean;\n    page?: number;\n    per_page?: number;\n    search?: string;\n    source?: number;\n    task?: string;\n};\ntype AiModelsSearchObject = {\n    id: string;\n    source: number;\n    name: string;\n    description: string;\n    task: {\n        id: string;\n        name: string;\n        description: string;\n    };\n    tags: string[];\n    properties: {\n        property_id: string;\n        value: string;\n    }[];\n};\ninterface InferenceUpstreamError extends Error {\n}\ninterface AiInternalError extends Error {\n}\ntype AiModelListType = Record<string, any>;\ndeclare abstract class Ai<AiModelList extends AiModelListType = AiModels> {\n    aiGatewayLogId: string | null;\n    gateway(gatewayId: string): AiGateway;\n    autorag(autoragId: string): AutoRAG;\n    run<Name extends keyof AiModelList, Options extends AiOptions>(model: Name, inputs: AiModelList[Name][\"inputs\"], options?: Options): Promise<Options extends {\n        returnRawResponse: true;\n    } ? Response : AiModelList[Name][\"postProcessedOutputs\"]>;\n    models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;\n    toMarkdown(files: {\n        name: string;\n        blob: Blob;\n    }[], options?: {\n        gateway?: GatewayOptions;\n        extraHeaders?: object;\n    }): Promise<ConversionResponse[]>;\n    toMarkdown(files: {\n        name: string;\n        blob: Blob;\n    }, options?: {\n        gateway?: GatewayOptions;\n        extraHeaders?: object;\n    }): Promise<ConversionResponse>;\n}\ntype GatewayOptions = {\n    id: string;\n    cacheKey?: string;\n    cacheTtl?: number;\n    skipCache?: boolean;\n    metadata?: Record<string, number | string | boolean | null | bigint>;\n    collectLog?: boolean;\n};\ntype AiGatewayPatchLog = {\n    score?: number | null;\n    feedback?: -1 | 1 | null;\n    metadata?: Record<string, number | string | boolean | null | bigint> | null;\n};\ntype AiGatewayLog = {\n    id: string;\n    provider: string;\n    model: string;\n    model_type?: string;\n    path: string;\n    duration: number;\n    request_type?: string;\n    request_content_type?: string;\n    status_code: number;\n    response_content_type?: string;\n    success: boolean;\n    cached: boolean;\n    tokens_in?: number;\n    tokens_out?: number;\n    metadata?: Record<string, number | string | boolean | null | bigint>;\n    step?: number;\n    cost?: number;\n    custom_cost?: boolean;\n    request_size: number;\n    request_head?: string;\n    request_head_complete: boolean;\n    response_size: number;\n    response_head?: string;\n    response_head_complete: boolean;\n    created_at: Date;\n};\ntype AIGatewayProviders = \"workers-ai\" | \"anthropic\" | \"aws-bedrock\" | \"azure-openai\" | \"google-vertex-ai\" | \"huggingface\" | \"openai\" | \"perplexity-ai\" | \"replicate\" | \"groq\" | \"cohere\" | \"google-ai-studio\" | \"mistral\" | \"grok\" | \"openrouter\" | \"deepseek\" | \"cerebras\" | \"cartesia\" | \"elevenlabs\" | \"adobe-firefly\";\ntype AIGatewayHeaders = {\n    \"cf-aig-metadata\": Record<string, number | string | boolean | null | bigint> | string;\n    \"cf-aig-custom-cost\": {\n        per_token_in?: number;\n        per_token_out?: number;\n    } | {\n        total_cost?: number;\n    } | string;\n    \"cf-aig-cache-ttl\": number | string;\n    \"cf-aig-skip-cache\": boolean | string;\n    \"cf-aig-cache-key\": string;\n    \"cf-aig-collect-log\": boolean | string;\n    Authorization: string;\n    \"Content-Type\": string;\n    [key: string]: string | number | boolean | object;\n};\ntype AIGatewayUniversalRequest = {\n    provider: AIGatewayProviders | string; // eslint-disable-line\n    endpoint: string;\n    headers: Partial<AIGatewayHeaders>;\n    query: unknown;\n};\ninterface AiGatewayInternalError extends Error {\n}\ninterface AiGatewayLogNotFound extends Error {\n}\ndeclare abstract class AiGateway {\n    patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;\n    getLog(logId: string): Promise<AiGatewayLog>;\n    run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[]): Promise<Response>;\n    getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line\n}\ninterface AutoRAGInternalError extends Error {\n}\ninterface AutoRAGNotFoundError extends Error {\n}\ninterface AutoRAGUnauthorizedError extends Error {\n}\ntype AutoRagSearchRequest = {\n    query: string;\n    max_num_results?: number;\n    ranking_options?: {\n        ranker?: string;\n        score_threshold?: number;\n    };\n    rewrite_query?: boolean;\n};\ntype AutoRagSearchResponse = {\n    object: \"vector_store.search_results.page\";\n    search_query: string;\n    data: {\n        file_id: string;\n        filename: string;\n        score: number;\n        attributes: Record<string, string | number | boolean | null>;\n        content: {\n            type: \"text\";\n            text: string;\n        }[];\n    }[];\n    has_more: boolean;\n    next_page: string | null;\n};\ntype AutoRagAiSearchResponse = AutoRagSearchResponse & {\n    response: string;\n};\ndeclare abstract class AutoRAG {\n    search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;\n    aiSearch(params: AutoRagSearchRequest): Promise<AutoRagAiSearchResponse>;\n}\ninterface BasicImageTransformations {\n    /**\n     * Maximum width in image pixels. The value must be an integer.\n     */\n    width?: number;\n    /**\n     * Maximum height in image pixels. The value must be an integer.\n     */\n    height?: number;\n    /**\n     * Resizing mode as a string. It affects interpretation of width and height\n     * options:\n     *  - scale-down: Similar to contain, but the image is never enlarged. If\n     *    the image is larger than given width or height, it will be resized.\n     *    Otherwise its original size will be kept.\n     *  - contain: Resizes to maximum size that fits within the given width and\n     *    height. If only a single dimension is given (e.g. only width), the\n     *    image will be shrunk or enlarged to exactly match that dimension.\n     *    Aspect ratio is always preserved.\n     *  - cover: Resizes (shrinks or enlarges) to fill the entire area of width\n     *    and height. If the image has an aspect ratio different from the ratio\n     *    of width and height, it will be cropped to fit.\n     *  - crop: The image will be shrunk and cropped to fit within the area\n     *    specified by width and height. The image will not be enlarged. For images\n     *    smaller than the given dimensions it's the same as scale-down. For\n     *    images larger than the given dimensions, it's the same as cover.\n     *    See also trim.\n     *  - pad: Resizes to the maximum size that fits within the given width and\n     *    height, and then fills the remaining area with a background color\n     *    (white by default). Use of this mode is not recommended, as the same\n     *    effect can be more efficiently achieved with the contain mode and the\n     *    CSS object-fit: contain property.\n     *  - squeeze: Stretches and deforms to the width and height given, even if it\n     *    breaks aspect ratio\n     */\n    fit?: \"scale-down\" | \"contain\" | \"cover\" | \"crop\" | \"pad\" | \"squeeze\";\n    /**\n     * When cropping with fit: \"cover\", this defines the side or point that should\n     * be left uncropped. The value is either a string\n     * \"left\", \"right\", \"top\", \"bottom\", \"auto\", or \"center\" (the default),\n     * or an object {x, y} containing focal point coordinates in the original\n     * image expressed as fractions ranging from 0.0 (top or left) to 1.0\n     * (bottom or right), 0.5 being the center. {fit: \"cover\", gravity: \"top\"} will\n     * crop bottom or left and right sides as necessary, but won’t crop anything\n     * from the top. {fit: \"cover\", gravity: {x:0.5, y:0.2}} will crop each side to\n     * preserve as much as possible around a point at 20% of the height of the\n     * source image.\n     */\n    gravity?: 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;\n    /**\n     * Background color to add underneath the image. Applies only to images with\n     * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),\n     * hsl(…), etc.)\n     */\n    background?: string;\n    /**\n     * Number of degrees (90, 180, 270) to rotate the image by. width and height\n     * options refer to axes after rotation.\n     */\n    rotate?: 0 | 90 | 180 | 270 | 360;\n}\ninterface BasicImageTransformationsGravityCoordinates {\n    x?: number;\n    y?: number;\n    mode?: 'remainder' | 'box-center';\n}\n/**\n * In addition to the properties you can set in the RequestInit dict\n * that you pass as an argument to the Request constructor, you can\n * set certain properties of a `cf` object to control how Cloudflare\n * features are applied to that new Request.\n *\n * Note: Currently, these properties cannot be tested in the\n * playground.\n */\ninterface RequestInitCfProperties extends Record<string, unknown> {\n    cacheEverything?: boolean;\n    /**\n     * A request's cache key is what determines if two requests are\n     * \"the same\" for caching purposes. If a request has the same cache key\n     * as some previous request, then we can serve the same cached response for\n     * both. (e.g. 'some-key')\n     *\n     * Only available for Enterprise customers.\n     */\n    cacheKey?: string;\n    /**\n     * This allows you to append additional Cache-Tag response headers\n     * to the origin response without modifications to the origin server.\n     * This will allow for greater control over the Purge by Cache Tag feature\n     * utilizing changes only in the Workers process.\n     *\n     * Only available for Enterprise customers.\n     */\n    cacheTags?: string[];\n    /**\n     * Force response to be cached for a given number of seconds. (e.g. 300)\n     */\n    cacheTtl?: number;\n    /**\n     * Force response to be cached for a given number of seconds based on the Origin status code.\n     * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })\n     */\n    cacheTtlByStatus?: Record<string, number>;\n    scrapeShield?: boolean;\n    apps?: boolean;\n    image?: RequestInitCfPropertiesImage;\n    minify?: RequestInitCfPropertiesImageMinify;\n    mirage?: boolean;\n    polish?: \"lossy\" | \"lossless\" | \"off\";\n    r2?: RequestInitCfPropertiesR2;\n    /**\n     * Redirects the request to an alternate origin server. You can use this,\n     * for example, to implement load balancing across several origins.\n     * (e.g.us-east.example.com)\n     *\n     * Note - For security reasons, the hostname set in resolveOverride must\n     * be proxied on the same Cloudflare zone of the incoming request.\n     * Otherwise, the setting is ignored. CNAME hosts are allowed, so to\n     * resolve to a host under a different domain or a DNS only domain first\n     * declare a CNAME record within your own zone’s DNS mapping to the\n     * external hostname, set proxy on Cloudflare, then set resolveOverride\n     * to point to that CNAME record.\n     */\n    resolveOverride?: string;\n}\ninterface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {\n    /**\n     * Absolute URL of the image file to use for the drawing. It can be any of\n     * the supported file formats. For drawing of watermarks or non-rectangular\n     * overlays we recommend using PNG or WebP images.\n     */\n    url: string;\n    /**\n     * Floating-point number between 0 (transparent) and 1 (opaque).\n     * For example, opacity: 0.5 makes overlay semitransparent.\n     */\n    opacity?: number;\n    /**\n     * - If set to true, the overlay image will be tiled to cover the entire\n     *   area. This is useful for stock-photo-like watermarks.\n     * - If set to \"x\", the overlay image will be tiled horizontally only\n     *   (form a line).\n     * - If set to \"y\", the overlay image will be tiled vertically only\n     *   (form a line).\n     */\n    repeat?: true | \"x\" | \"y\";\n    /**\n     * Position of the overlay image relative to a given edge. Each property is\n     * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10\n     * positions left side of the overlay 10 pixels from the left edge of the\n     * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom\n     * of the background image.\n     *\n     * Setting both left & right, or both top & bottom is an error.\n     *\n     * If no position is specified, the image will be centered.\n     */\n    top?: number;\n    left?: number;\n    bottom?: number;\n    right?: number;\n}\ninterface RequestInitCfPropertiesImage extends BasicImageTransformations {\n    /**\n     * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it\n     * easier to specify higher-DPI sizes in <img srcset>.\n     */\n    dpr?: number;\n    /**\n     * Allows you to trim your image. Takes dpr into account and is performed before\n     * resizing or rotation.\n     *\n     * It can be used as:\n     * - left, top, right, bottom - it will specify the number of pixels to cut\n     *   off each side\n     * - width, height - the width/height you'd like to end up with - can be used\n     *   in combination with the properties above\n     * - border - this will automatically trim the surroundings of an image based on\n     *   it's color. It consists of three properties:\n     *    - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)\n     *    - tolerance: difference from color to treat as color\n     *    - keep: the number of pixels of border to keep\n     */\n    trim?: \"border\" | {\n        top?: number;\n        bottom?: number;\n        left?: number;\n        right?: number;\n        width?: number;\n        height?: number;\n        border?: boolean | {\n            color?: string;\n            tolerance?: number;\n            keep?: number;\n        };\n    };\n    /**\n     * Quality setting from 1-100 (useful values are in 60-90 range). Lower values\n     * make images look worse, but load faster. The default is 85. It applies only\n     * to JPEG and WebP images. It doesn’t have any effect on PNG.\n     */\n    quality?: number | \"low\" | \"medium-low\" | \"medium-high\" | \"high\";\n    /**\n     * Output format to generate. It can be:\n     *  - avif: generate images in AVIF format.\n     *  - webp: generate images in Google WebP format. Set quality to 100 to get\n     *    the WebP-lossless format.\n     *  - json: instead of generating an image, outputs information about the\n     *    image, in JSON format. The JSON object will contain image size\n     *    (before and after resizing), source image’s MIME type, file size, etc.\n     * - jpeg: generate images in JPEG format.\n     * - png: generate images in PNG format.\n     */\n    format?: \"avif\" | \"webp\" | \"json\" | \"jpeg\" | \"png\" | \"baseline-jpeg\" | \"png-force\" | \"svg\";\n    /**\n     * Whether to preserve animation frames from input files. Default is true.\n     * Setting it to false reduces animations to still images. This setting is\n     * recommended when enlarging images or processing arbitrary user content,\n     * because large GIF animations can weigh tens or even hundreds of megabytes.\n     * It is also useful to set anim:false when using format:\"json\" to get the\n     * response quicker without the number of frames.\n     */\n    anim?: boolean;\n    /**\n     * What EXIF data should be preserved in the output image. Note that EXIF\n     * rotation and embedded color profiles are always applied (\"baked in\" into\n     * the image), and aren't affected by this option. Note that if the Polish\n     * feature is enabled, all metadata may have been removed already and this\n     * option may have no effect.\n     *  - keep: Preserve most of EXIF metadata, including GPS location if there's\n     *    any.\n     *  - copyright: Only keep the copyright tag, and discard everything else.\n     *    This is the default behavior for JPEG files.\n     *  - none: Discard all invisible EXIF metadata. Currently WebP and PNG\n     *    output formats always discard metadata.\n     */\n    metadata?: \"keep\" | \"copyright\" | \"none\";\n    /**\n     * Strength of sharpening filter to apply to the image. Floating-point\n     * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a\n     * recommended value for downscaled images.\n     */\n    sharpen?: number;\n    /**\n     * Radius of a blur filter (approximate gaussian). Maximum supported radius\n     * is 250.\n     */\n    blur?: number;\n    /**\n     * Overlays are drawn in the order they appear in the array (last array\n     * entry is the topmost layer).\n     */\n    draw?: RequestInitCfPropertiesImageDraw[];\n    /**\n     * Fetching image from authenticated origin. Setting this property will\n     * pass authentication headers (Authorization, Cookie, etc.) through to\n     * the origin.\n     */\n    \"origin-auth\"?: \"share-publicly\";\n    /**\n     * Adds a border around the image. The border is added after resizing. Border\n     * width takes dpr into account, and can be specified either using a single\n     * width property, or individually for each side.\n     */\n    border?: {\n        color: string;\n        width: number;\n    } | {\n        color: string;\n        top: number;\n        right: number;\n        bottom: number;\n        left: number;\n    };\n    /**\n     * Increase brightness by a factor. A value of 1.0 equals no change, a value\n     * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.\n     * 0 is ignored.\n     */\n    brightness?: number;\n    /**\n     * Increase contrast by a factor. A value of 1.0 equals no change, a value of\n     * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is\n     * ignored.\n     */\n    contrast?: number;\n    /**\n     * Increase exposure by a factor. A value of 1.0 equals no change, a value of\n     * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.\n     */\n    gamma?: number;\n    /**\n     * Increase contrast by a factor. A value of 1.0 equals no change, a value of\n     * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is\n     * ignored.\n     */\n    saturation?: number;\n    /**\n     * Flips the images horizontally, vertically, or both. Flipping is applied before\n     * rotation, so if you apply flip=h,rotate=90 then the image will be flipped\n     * horizontally, then rotated by 90 degrees.\n     */\n    flip?: 'h' | 'v' | 'hv';\n    /**\n     * Slightly reduces latency on a cache miss by selecting a\n     * quickest-to-compress file format, at a cost of increased file size and\n     * lower image quality. It will usually override the format option and choose\n     * JPEG over WebP or AVIF. We do not recommend using this option, except in\n     * unusual circumstances like resizing uncacheable dynamically-generated\n     * images.\n     */\n    compression?: \"fast\";\n}\ninterface RequestInitCfPropertiesImageMinify {\n    javascript?: boolean;\n    css?: boolean;\n    html?: boolean;\n}\ninterface RequestInitCfPropertiesR2 {\n    /**\n     * Colo id of bucket that an object is stored in\n     */\n    bucketColoId?: number;\n}\n/**\n * Request metadata provided by Cloudflare's edge.\n */\ntype IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;\ninterface IncomingRequestCfPropertiesBase extends Record<string, unknown> {\n    /**\n     * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.\n     *\n     * @example 395747\n     */\n    asn: number;\n    /**\n     * The organization which owns the ASN of the incoming request.\n     *\n     * @example \"Google Cloud\"\n     */\n    asOrganization: string;\n    /**\n     * The original value of the `Accept-Encoding` header if Cloudflare modified it.\n     *\n     * @example \"gzip, deflate, br\"\n     */\n    clientAcceptEncoding?: string;\n    /**\n     * The number of milliseconds it took for the request to reach your worker.\n     *\n     * @example 22\n     */\n    clientTcpRtt?: number;\n    /**\n     * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)\n     * airport code of the data center that the request hit.\n     *\n     * @example \"DFW\"\n     */\n    colo: string;\n    /**\n     * Represents the upstream's response to a\n     * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)\n     * from cloudflare.\n     *\n     * For workers with no upstream, this will always be `1`.\n     *\n     * @example 3\n     */\n    edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;\n    /**\n     * The HTTP Protocol the request used.\n     *\n     * @example \"HTTP/2\"\n     */\n    httpProtocol: string;\n    /**\n     * The browser-requested prioritization information in the request object.\n     *\n     * If no information was set, defaults to the empty string `\"\"`\n     *\n     * @example \"weight=192;exclusive=0;group=3;group-weight=127\"\n     * @default \"\"\n     */\n    requestPriority: string;\n    /**\n     * The TLS version of the connection to Cloudflare.\n     * In requests served over plaintext (without TLS), this property is the empty string `\"\"`.\n     *\n     * @example \"TLSv1.3\"\n     */\n    tlsVersion: string;\n    /**\n     * The cipher for the connection to Cloudflare.\n     * In requests served over plaintext (without TLS), this property is the empty string `\"\"`.\n     *\n     * @example \"AEAD-AES128-GCM-SHA256\"\n     */\n    tlsCipher: string;\n    /**\n     * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake.\n     *\n     * If the incoming request was served over plaintext (without TLS) this field is undefined.\n     */\n    tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;\n}\ninterface IncomingRequestCfPropertiesBotManagementBase {\n    /**\n     * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,\n     * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).\n     *\n     * @example 54\n     */\n    score: number;\n    /**\n     * A boolean value that is true if the request comes from a good bot, like Google or Bing.\n     * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots).\n     */\n    verifiedBot: boolean;\n    /**\n     * A boolean value that is true if the request originates from a\n     * Cloudflare-verified proxy service.\n     */\n    corporateProxy: boolean;\n    /**\n     * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources.\n     */\n    staticResource: boolean;\n    /**\n     * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request).\n     */\n    detectionIds: number[];\n}\ninterface IncomingRequestCfPropertiesBotManagement {\n    /**\n     * Results of Cloudflare's Bot Management analysis\n     */\n    botManagement: IncomingRequestCfPropertiesBotManagementBase;\n    /**\n     * Duplicate of `botManagement.score`.\n     *\n     * @deprecated\n     */\n    clientTrustScore: number;\n}\ninterface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {\n    /**\n     * Results of Cloudflare's Bot Management analysis\n     */\n    botManagement: IncomingRequestCfPropertiesBotManagementBase & {\n        /**\n         * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients\n         * across different destination IPs, Ports, and X509 certificates.\n         */\n        ja3Hash: string;\n    };\n}\ninterface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {\n    /**\n     * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).\n     *\n     * This field is only present if you have Cloudflare for SaaS enabled on your account\n     * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).\n     */\n    hostMetadata: HostMetadata;\n}\ninterface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {\n    /**\n     * Information about the client certificate presented to Cloudflare.\n     *\n     * This is populated when the incoming request is served over TLS using\n     * either Cloudflare Access or API Shield (mTLS)\n     * and the presented SSL certificate has a valid\n     * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)\n     * (i.e., not `null` or `\"\"`).\n     *\n     * Otherwise, a set of placeholder values are used.\n     *\n     * The property `certPresented` will be set to `\"1\"` when\n     * the object is populated (i.e. the above conditions were met).\n     */\n    tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;\n}\n/**\n * Metadata about the request's TLS handshake\n */\ninterface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {\n    /**\n     * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal\n     *\n     * @example \"44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d\"\n     */\n    clientHandshake: string;\n    /**\n     * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal\n     *\n     * @example \"44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d\"\n     */\n    serverHandshake: string;\n    /**\n     * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal\n     *\n     * @example \"084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b\"\n     */\n    clientFinished: string;\n    /**\n     * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal\n     *\n     * @example \"084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b\"\n     */\n    serverFinished: string;\n}\n/**\n * Geographic data about the request's origin.\n */\ninterface IncomingRequestCfPropertiesGeographicInformation {\n    /**\n     * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.\n     *\n     * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `\"T1\"`, indicating a request that originated over TOR.\n     *\n     * If Cloudflare is unable to determine where the request originated this property is omitted.\n     *\n     * The country code `\"T1\"` is used for requests originating on TOR.\n     *\n     * @example \"GB\"\n     */\n    country?: Iso3166Alpha2Code | \"T1\";\n    /**\n     * If present, this property indicates that the request originated in the EU\n     *\n     * @example \"1\"\n     */\n    isEUCountry?: \"1\";\n    /**\n     * A two-letter code indicating the continent the request originated from.\n     *\n     * @example \"AN\"\n     */\n    continent?: ContinentCode;\n    /**\n     * The city the request originated from\n     *\n     * @example \"Austin\"\n     */\n    city?: string;\n    /**\n     * Postal code of the incoming request\n     *\n     * @example \"78701\"\n     */\n    postalCode?: string;\n    /**\n     * Latitude of the incoming request\n     *\n     * @example \"30.27130\"\n     */\n    latitude?: string;\n    /**\n     * Longitude of the incoming request\n     *\n     * @example \"-97.74260\"\n     */\n    longitude?: string;\n    /**\n     * Timezone of the incoming request\n     *\n     * @example \"America/Chicago\"\n     */\n    timezone?: string;\n    /**\n     * If known, the ISO 3166-2 name for the first level region associated with\n     * the IP address of the incoming request\n     *\n     * @example \"Texas\"\n     */\n    region?: string;\n    /**\n     * If known, the ISO 3166-2 code for the first-level region associated with\n     * the IP address of the incoming request\n     *\n     * @example \"TX\"\n     */\n    regionCode?: string;\n    /**\n     * Metro code (DMA) of the incoming request\n     *\n     * @example \"635\"\n     */\n    metroCode?: string;\n}\n/** Data about the incoming request's TLS certificate */\ninterface IncomingRequestCfPropertiesTLSClientAuth {\n    /** Always `\"1\"`, indicating that the certificate was presented */\n    certPresented: \"1\";\n    /**\n     * Result of certificate verification.\n     *\n     * @example \"FAILED:self signed certificate\"\n     */\n    certVerified: Exclude<CertVerificationStatus, \"NONE\">;\n    /** The presented certificate's revokation status.\n     *\n     * - A value of `\"1\"` indicates the certificate has been revoked\n     * - A value of `\"0\"` indicates the certificate has not been revoked\n     */\n    certRevoked: \"1\" | \"0\";\n    /**\n     * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)\n     *\n     * @example \"CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certIssuerDN: string;\n    /**\n     * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)\n     *\n     * @example \"CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certSubjectDN: string;\n    /**\n     * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)\n     *\n     * @example \"CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certIssuerDNRFC2253: string;\n    /**\n     * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)\n     *\n     * @example \"CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare\"\n     */\n    certSubjectDNRFC2253: string;\n    /** The certificate issuer's distinguished name (legacy policies) */\n    certIssuerDNLegacy: string;\n    /** The certificate subject's distinguished name (legacy policies) */\n    certSubjectDNLegacy: string;\n    /**\n     * The certificate's serial number\n     *\n     * @example \"00936EACBE07F201DF\"\n     */\n    certSerial: string;\n    /**\n     * The certificate issuer's serial number\n     *\n     * @example \"2489002934BDFEA34\"\n     */\n    certIssuerSerial: string;\n    /**\n     * The certificate's Subject Key Identifier\n     *\n     * @example \"BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4\"\n     */\n    certSKI: string;\n    /**\n     * The certificate issuer's Subject Key Identifier\n     *\n     * @example \"BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4\"\n     */\n    certIssuerSKI: string;\n    /**\n     * The certificate's SHA-1 fingerprint\n     *\n     * @example \"6b9109f323999e52259cda7373ff0b4d26bd232e\"\n     */\n    certFingerprintSHA1: string;\n    /**\n     * The certificate's SHA-256 fingerprint\n     *\n     * @example \"acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea\"\n     */\n    certFingerprintSHA256: string;\n    /**\n     * The effective starting date of the certificate\n     *\n     * @example \"Dec 22 19:39:00 2018 GMT\"\n     */\n    certNotBefore: string;\n    /**\n     * The effective expiration date of the certificate\n     *\n     * @example \"Dec 22 19:39:00 2018 GMT\"\n     */\n    certNotAfter: string;\n}\n/** Placeholder values for TLS Client Authorization */\ninterface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {\n    certPresented: \"0\";\n    certVerified: \"NONE\";\n    certRevoked: \"0\";\n    certIssuerDN: \"\";\n    certSubjectDN: \"\";\n    certIssuerDNRFC2253: \"\";\n    certSubjectDNRFC2253: \"\";\n    certIssuerDNLegacy: \"\";\n    certSubjectDNLegacy: \"\";\n    certSerial: \"\";\n    certIssuerSerial: \"\";\n    certSKI: \"\";\n    certIssuerSKI: \"\";\n    certFingerprintSHA1: \"\";\n    certFingerprintSHA256: \"\";\n    certNotBefore: \"\";\n    certNotAfter: \"\";\n}\n/** Possible outcomes of TLS verification */\ndeclare type CertVerificationStatus = \n/** Authentication succeeded */\n\"SUCCESS\"\n/** No certificate was presented */\n | \"NONE\"\n/** Failed because the certificate was self-signed */\n | \"FAILED:self signed certificate\"\n/** Failed because the certificate failed a trust chain check */\n | \"FAILED:unable to verify the first certificate\"\n/** Failed because the certificate not yet valid */\n | \"FAILED:certificate is not yet valid\"\n/** Failed because the certificate is expired */\n | \"FAILED:certificate has expired\"\n/** Failed for another unspecified reason */\n | \"FAILED\";\n/**\n * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.\n */\ndeclare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */\n/** ISO 3166-1 Alpha-2 codes */\ndeclare type Iso3166Alpha2Code = \"AD\" | \"AE\" | \"AF\" | \"AG\" | \"AI\" | \"AL\" | \"AM\" | \"AO\" | \"AQ\" | \"AR\" | \"AS\" | \"AT\" | \"AU\" | \"AW\" | \"AX\" | \"AZ\" | \"BA\" | \"BB\" | \"BD\" | \"BE\" | \"BF\" | \"BG\" | \"BH\" | \"BI\" | \"BJ\" | \"BL\" | \"BM\" | \"BN\" | \"BO\" | \"BQ\" | \"BR\" | \"BS\" | \"BT\" | \"BV\" | \"BW\" | \"BY\" | \"BZ\" | \"CA\" | \"CC\" | \"CD\" | \"CF\" | \"CG\" | \"CH\" | \"CI\" | \"CK\" | \"CL\" | \"CM\" | \"CN\" | \"CO\" | \"CR\" | \"CU\" | \"CV\" | \"CW\" | \"CX\" | \"CY\" | \"CZ\" | \"DE\" | \"DJ\" | \"DK\" | \"DM\" | \"DO\" | \"DZ\" | \"EC\" | \"EE\" | \"EG\" | \"EH\" | \"ER\" | \"ES\" | \"ET\" | \"FI\" | \"FJ\" | \"FK\" | \"FM\" | \"FO\" | \"FR\" | \"GA\" | \"GB\" | \"GD\" | \"GE\" | \"GF\" | \"GG\" | \"GH\" | \"GI\" | \"GL\" | \"GM\" | \"GN\" | \"GP\" | \"GQ\" | \"GR\" | \"GS\" | \"GT\" | \"GU\" | \"GW\" | \"GY\" | \"HK\" | \"HM\" | \"HN\" | \"HR\" | \"HT\" | \"HU\" | \"ID\" | \"IE\" | \"IL\" | \"IM\" | \"IN\" | \"IO\" | \"IQ\" | \"IR\" | \"IS\" | \"IT\" | \"JE\" | \"JM\" | \"JO\" | \"JP\" | \"KE\" | \"KG\" | \"KH\" | \"KI\" | \"KM\" | \"KN\" | \"KP\" | \"KR\" | \"KW\" | \"KY\" | \"KZ\" | \"LA\" | \"LB\" | \"LC\" | \"LI\" | \"LK\" | \"LR\" | \"LS\" | \"LT\" | \"LU\" | \"LV\" | \"LY\" | \"MA\" | \"MC\" | \"MD\" | \"ME\" | \"MF\" | \"MG\" | \"MH\" | \"MK\" | \"ML\" | \"MM\" | \"MN\" | \"MO\" | \"MP\" | \"MQ\" | \"MR\" | \"MS\" | \"MT\" | \"MU\" | \"MV\" | \"MW\" | \"MX\" | \"MY\" | \"MZ\" | \"NA\" | \"NC\" | \"NE\" | \"NF\" | \"NG\" | \"NI\" | \"NL\" | \"NO\" | \"NP\" | \"NR\" | \"NU\" | \"NZ\" | \"OM\" | \"PA\" | \"PE\" | \"PF\" | \"PG\" | \"PH\" | \"PK\" | \"PL\" | \"PM\" | \"PN\" | \"PR\" | \"PS\" | \"PT\" | \"PW\" | \"PY\" | \"QA\" | \"RE\" | \"RO\" | \"RS\" | \"RU\" | \"RW\" | \"SA\" | \"SB\" | \"SC\" | \"SD\" | \"SE\" | \"SG\" | \"SH\" | \"SI\" | \"SJ\" | \"SK\" | \"SL\" | \"SM\" | \"SN\" | \"SO\" | \"SR\" | \"SS\" | \"ST\" | \"SV\" | \"SX\" | \"SY\" | \"SZ\" | \"TC\" | \"TD\" | \"TF\" | \"TG\" | \"TH\" | \"TJ\" | \"TK\" | \"TL\" | \"TM\" | \"TN\" | \"TO\" | \"TR\" | \"TT\" | \"TV\" | \"TW\" | \"TZ\" | \"UA\" | \"UG\" | \"UM\" | \"US\" | \"UY\" | \"UZ\" | \"VA\" | \"VC\" | \"VE\" | \"VG\" | \"VI\" | \"VN\" | \"VU\" | \"WF\" | \"WS\" | \"YE\" | \"YT\" | \"ZA\" | \"ZM\" | \"ZW\";\n/** The 2-letter continent codes Cloudflare uses */\ndeclare type ContinentCode = \"AF\" | \"AN\" | \"AS\" | \"EU\" | \"NA\" | \"OC\" | \"SA\";\ntype CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;\ninterface D1Meta {\n    duration: number;\n    size_after: number;\n    rows_read: number;\n    rows_written: number;\n    last_row_id: number;\n    changed_db: boolean;\n    changes: number;\n    /**\n     * The region of the database instance that executed the query.\n     */\n    served_by_region?: string;\n    /**\n     * True if-and-only-if the database instance that executed the query was the primary.\n     */\n    served_by_primary?: boolean;\n    timings?: {\n        /**\n         * The duration of the SQL query execution by the database instance. It doesn't include any network time.\n         */\n        sql_duration_ms: number;\n    };\n}\ninterface D1Response {\n    success: true;\n    meta: D1Meta & Record<string, unknown>;\n    error?: never;\n}\ntype D1Result<T = unknown> = D1Response & {\n    results: T[];\n};\ninterface D1ExecResult {\n    count: number;\n    duration: number;\n}\ntype D1SessionConstraint = \n// Indicates that the first query should go to the primary, and the rest queries\n// using the same D1DatabaseSession will go to any replica that is consistent with\n// the bookmark maintained by the session (returned by the first query).\n\"first-primary\"\n// Indicates that the first query can go anywhere (primary or replica), and the rest queries\n// using the same D1DatabaseSession will go to any replica that is consistent with\n// the bookmark maintained by the session (returned by the first query).\n | \"first-unconstrained\";\ntype D1SessionBookmark = string;\ndeclare abstract class D1Database {\n    prepare(query: string): D1PreparedStatement;\n    batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;\n    exec(query: string): Promise<D1ExecResult>;\n    /**\n     * Creates a new D1 Session anchored at the given constraint or the bookmark.\n     * All queries executed using the created session will have sequential consistency,\n     * meaning that all writes done through the session will be visible in subsequent reads.\n     *\n     * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.\n     */\n    withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;\n    /**\n     * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.\n     */\n    dump(): Promise<ArrayBuffer>;\n}\ndeclare abstract class D1DatabaseSession {\n    prepare(query: string): D1PreparedStatement;\n    batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;\n    /**\n     * @returns The latest session bookmark across all executed queries on the session.\n     *          If no query has been executed yet, `null` is returned.\n     */\n    getBookmark(): D1SessionBookmark | null;\n}\ndeclare abstract class D1PreparedStatement {\n    bind(...values: unknown[]): D1PreparedStatement;\n    first<T = unknown>(colName: string): Promise<T | null>;\n    first<T = Record<string, unknown>>(): Promise<T | null>;\n    run<T = Record<string, unknown>>(): Promise<D1Result<T>>;\n    all<T = Record<string, unknown>>(): Promise<D1Result<T>>;\n    raw<T = unknown[]>(options: {\n        columnNames: true;\n    }): Promise<[\n        string[],\n        ...T[]\n    ]>;\n    raw<T = unknown[]>(options?: {\n        columnNames?: false;\n    }): Promise<T[]>;\n}\n// `Disposable` was added to TypeScript's standard lib types in version 5.2.\n// To support older TypeScript versions, define an empty `Disposable` interface.\n// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,\n// but this will ensure type checking on older versions still passes.\n// TypeScript's interface merging will ensure our empty interface is effectively\n// ignored when `Disposable` is included in the standard lib.\ninterface Disposable {\n}\n/**\n * An email message that can be sent from a Worker.\n */\ninterface EmailMessage {\n    /**\n     * Envelope From attribute of the email message.\n     */\n    readonly from: string;\n    /**\n     * Envelope To attribute of the email message.\n     */\n    readonly to: string;\n}\n/**\n * An email message that is sent to a consumer Worker and can be rejected/forwarded.\n */\ninterface ForwardableEmailMessage extends EmailMessage {\n    /**\n     * Stream of the email message content.\n     */\n    readonly raw: ReadableStream<Uint8Array>;\n    /**\n     * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).\n     */\n    readonly headers: Headers;\n    /**\n     * Size of the email message content.\n     */\n    readonly rawSize: number;\n    /**\n     * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.\n     * @param reason The reject reason.\n     * @returns void\n     */\n    setReject(reason: string): void;\n    /**\n     * Forward this email message to a verified destination address of the account.\n     * @param rcptTo Verified destination address.\n     * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).\n     * @returns A promise that resolves when the email message is forwarded.\n     */\n    forward(rcptTo: string, headers?: Headers): Promise<void>;\n    /**\n     * Reply to the sender of this email message with a new EmailMessage object.\n     * @param message The reply message.\n     * @returns A promise that resolves when the email message is replied.\n     */\n    reply(message: EmailMessage): Promise<void>;\n}\n/**\n * A binding that allows a Worker to send email messages.\n */\ninterface SendEmail {\n    send(message: EmailMessage): Promise<void>;\n}\ndeclare abstract class EmailEvent extends ExtendableEvent {\n    readonly message: ForwardableEmailMessage;\n}\ndeclare type EmailExportedHandler<Env = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise<void>;\ndeclare module \"cloudflare:email\" {\n    let _EmailMessage: {\n        prototype: EmailMessage;\n        new (from: string, to: string, raw: ReadableStream | string): EmailMessage;\n    };\n    export { _EmailMessage as EmailMessage };\n}\ninterface Hyperdrive {\n    /**\n     * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.\n     *\n     * Calling this method returns an idential socket to if you call\n     * `connect(\"host:port\")` using the `host` and `port` fields from this object.\n     * Pick whichever approach works better with your preferred DB client library.\n     *\n     * Note that this socket is not yet authenticated -- it's expected that your\n     * code (or preferably, the client library of your choice) will authenticate\n     * using the information in this class's readonly fields.\n     */\n    connect(): Socket;\n    /**\n     * A valid DB connection string that can be passed straight into the typical\n     * client library/driver/ORM. This will typically be the easiest way to use\n     * Hyperdrive.\n     */\n    readonly connectionString: string;\n    /*\n     * A randomly generated hostname that is only valid within the context of the\n     * currently running Worker which, when passed into `connect()` function from\n     * the \"cloudflare:sockets\" module, will connect to the Hyperdrive instance\n     * for your database.\n     */\n    readonly host: string;\n    /*\n     * The port that must be paired the the host field when connecting.\n     */\n    readonly port: number;\n    /*\n     * The username to use when authenticating to your database via Hyperdrive.\n     * Unlike the host and password, this will be the same every time\n     */\n    readonly user: string;\n    /*\n     * The randomly generated password to use when authenticating to your\n     * database via Hyperdrive. Like the host field, this password is only valid\n     * within the context of the currently running Worker instance from which\n     * it's read.\n     */\n    readonly password: string;\n    /*\n     * The name of the database to connect to.\n     */\n    readonly database: string;\n}\n// Copyright (c) 2024 Cloudflare, Inc.\n// Licensed under the Apache 2.0 license found in the LICENSE file or at:\n//     https://opensource.org/licenses/Apache-2.0\ntype ImageInfoResponse = {\n    format: 'image/svg+xml';\n} | {\n    format: string;\n    fileSize: number;\n    width: number;\n    height: number;\n};\ntype ImageTransform = {\n    width?: number;\n    height?: number;\n    background?: string;\n    blur?: number;\n    border?: {\n        color?: string;\n        width?: number;\n    } | {\n        top?: number;\n        bottom?: number;\n        left?: number;\n        right?: number;\n    };\n    brightness?: number;\n    contrast?: number;\n    fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';\n    flip?: 'h' | 'v' | 'hv';\n    gamma?: number;\n    gravity?: 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {\n        x?: number;\n        y?: number;\n        mode: 'remainder' | 'box-center';\n    };\n    rotate?: 0 | 90 | 180 | 270;\n    saturation?: number;\n    sharpen?: number;\n    trim?: \"border\" | {\n        top?: number;\n        bottom?: number;\n        left?: number;\n        right?: number;\n        width?: number;\n        height?: number;\n        border?: boolean | {\n            color?: string;\n            tolerance?: number;\n            keep?: number;\n        };\n    };\n};\ntype ImageDrawOptions = {\n    opacity?: number;\n    repeat?: boolean | string;\n    top?: number;\n    left?: number;\n    bottom?: number;\n    right?: number;\n};\ntype ImageOutputOptions = {\n    format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';\n    quality?: number;\n    background?: string;\n};\ninterface ImagesBinding {\n    /**\n     * Get image metadata (type, width and height)\n     * @throws {@link ImagesError} with code 9412 if input is not an image\n     * @param stream The image bytes\n     */\n    info(stream: ReadableStream<Uint8Array>): Promise<ImageInfoResponse>;\n    /**\n     * Begin applying a series of transformations to an image\n     * @param stream The image bytes\n     * @returns A transform handle\n     */\n    input(stream: ReadableStream<Uint8Array>): ImageTransformer;\n}\ninterface ImageTransformer {\n    /**\n     * Apply transform next, returning a transform handle.\n     * You can then apply more transformations, draw, or retrieve the output.\n     * @param transform\n     */\n    transform(transform: ImageTransform): ImageTransformer;\n    /**\n     * Draw an image on this transformer, returning a transform handle.\n     * You can then apply more transformations, draw, or retrieve the output.\n     * @param image The image (or transformer that will give the image) to draw\n     * @param options The options configuring how to draw the image\n     */\n    draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;\n    /**\n     * Retrieve the image that results from applying the transforms to the\n     * provided input\n     * @param options Options that apply to the output e.g. output format\n     */\n    output(options: ImageOutputOptions): Promise<ImageTransformationResult>;\n}\ninterface ImageTransformationResult {\n    /**\n     * The image as a response, ready to store in cache or return to users\n     */\n    response(): Response;\n    /**\n     * The content type of the returned image\n     */\n    contentType(): string;\n    /**\n     * The bytes of the response\n     */\n    image(): ReadableStream<Uint8Array>;\n}\ninterface ImagesError extends Error {\n    readonly code: number;\n    readonly message: string;\n    readonly stack?: string;\n}\ntype Params<P extends string = any> = Record<P, string | string[]>;\ntype EventContext<Env, P extends string, Data> = {\n    request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n    functionPath: string;\n    waitUntil: (promise: Promise<any>) => void;\n    passThroughOnException: () => void;\n    next: (input?: Request | string, init?: RequestInit) => Promise<Response>;\n    env: Env & {\n        ASSETS: {\n            fetch: typeof fetch;\n        };\n    };\n    params: Params<P>;\n    data: Data;\n};\ntype PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;\ntype EventPluginContext<Env, P extends string, Data, PluginArgs> = {\n    request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n    functionPath: string;\n    waitUntil: (promise: Promise<any>) => void;\n    passThroughOnException: () => void;\n    next: (input?: Request | string, init?: RequestInit) => Promise<Response>;\n    env: Env & {\n        ASSETS: {\n            fetch: typeof fetch;\n        };\n    };\n    params: Params<P>;\n    data: Data;\n    pluginArgs: PluginArgs;\n};\ntype PagesPluginFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>, PluginArgs = unknown> = (context: EventPluginContext<Env, Params, Data, PluginArgs>) => Response | Promise<Response>;\ndeclare module \"assets:*\" {\n    export const onRequest: PagesFunction;\n}\n// Copyright (c) 2022-2023 Cloudflare, Inc.\n// Licensed under the Apache 2.0 license found in the LICENSE file or at:\n//     https://opensource.org/licenses/Apache-2.0\ndeclare module \"cloudflare:pipelines\" {\n    export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {\n        protected env: Env;\n        protected ctx: ExecutionContext;\n        constructor(ctx: ExecutionContext, env: Env);\n        /**\n         * run recieves an array of PipelineRecord which can be\n         * transformed and returned to the pipeline\n         * @param records Incoming records from the pipeline to be transformed\n         * @param metadata Information about the specific pipeline calling the transformation entrypoint\n         * @returns A promise containing the transformed PipelineRecord array\n         */\n        public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;\n    }\n    export type PipelineRecord = Record<string, unknown>;\n    export type PipelineBatchMetadata = {\n        pipelineId: string;\n        pipelineName: string;\n    };\n    export interface Pipeline<T extends PipelineRecord = PipelineRecord> {\n        /**\n         * The Pipeline interface represents the type of a binding to a Pipeline\n         *\n         * @param records The records to send to the pipeline\n         */\n        send(records: T[]): Promise<void>;\n    }\n}\n// PubSubMessage represents an incoming PubSub message.\n// The message includes metadata about the broker, the client, and the payload\n// itself.\n// https://developers.cloudflare.com/pub-sub/\ninterface PubSubMessage {\n    // Message ID\n    readonly mid: number;\n    // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT\n    readonly broker: string;\n    // The MQTT topic the message was sent on.\n    readonly topic: string;\n    // The client ID of the client that published this message.\n    readonly clientId: string;\n    // The unique identifier (JWT ID) used by the client to authenticate, if token\n    // auth was used.\n    readonly jti?: string;\n    // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker\n    // received the message from the client.\n    readonly receivedAt: number;\n    // An (optional) string with the MIME type of the payload, if set by the\n    // client.\n    readonly contentType: string;\n    // Set to 1 when the payload is a UTF-8 string\n    // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063\n    readonly payloadFormatIndicator: number;\n    // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.\n    // You can use payloadFormatIndicator to inspect this before decoding.\n    payload: string | Uint8Array;\n}\n// JsonWebKey extended by kid parameter\ninterface JsonWebKeyWithKid extends JsonWebKey {\n    // Key Identifier of the JWK\n    readonly kid: string;\n}\ninterface RateLimitOptions {\n    key: string;\n}\ninterface RateLimitOutcome {\n    success: boolean;\n}\ninterface RateLimit {\n    /**\n     * Rate limit a request based on the provided options.\n     * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/\n     * @returns A promise that resolves with the outcome of the rate limit.\n     */\n    limit(options: RateLimitOptions): Promise<RateLimitOutcome>;\n}\n// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need\n// to referenced by `Fetcher`. This is included in the \"importable\" version of the types which\n// strips all `module` blocks.\ndeclare namespace Rpc {\n    // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.\n    // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.\n    // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to\n    // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)\n    export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';\n    export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';\n    export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';\n    export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';\n    export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';\n    export interface RpcTargetBranded {\n        [__RPC_TARGET_BRAND]: never;\n    }\n    export interface WorkerEntrypointBranded {\n        [__WORKER_ENTRYPOINT_BRAND]: never;\n    }\n    export interface DurableObjectBranded {\n        [__DURABLE_OBJECT_BRAND]: never;\n    }\n    export interface WorkflowEntrypointBranded {\n        [__WORKFLOW_ENTRYPOINT_BRAND]: never;\n    }\n    export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;\n    // Types that can be used through `Stub`s\n    export type Stubable = RpcTargetBranded | ((...args: any[]) => any);\n    // Types that can be passed over RPC\n    // The reason for using a generic type here is to build a serializable subset of structured\n    //   cloneable composite types. This allows types defined with the \"interface\" keyword to pass the\n    //   serializable check as well. Otherwise, only types defined with the \"type\" keyword would pass.\n    type Serializable<T> = \n    // Structured cloneables\n    BaseType\n    // Structured cloneable composites\n     | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {\n        [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;\n    }\n    // Special types\n     | Stub<Stubable>\n    // Serialized as stubs, see `Stubify`\n     | Stubable;\n    // Base type for all RPC stubs, including common memory management methods.\n    // `T` is used as a marker type for unwrapping `Stub`s later.\n    interface StubBase<T extends Stubable> extends Disposable {\n        [__RPC_STUB_BRAND]: T;\n        dup(): this;\n    }\n    export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;\n    // This represents all the types that can be sent as-is over an RPC boundary\n    type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;\n    // Recursively rewrite all `Stubable` types with `Stub`s\n    // prettier-ignore\n    type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {\n        [key: string | number]: any;\n    } ? {\n        [K in keyof T]: Stubify<T[K]>;\n    } : T;\n    // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.\n    // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:\n    // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.\n    // prettier-ignore\n    type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {\n        [key: string | number]: unknown;\n    } ? {\n        [K in keyof T]: Unstubify<T[K]>;\n    } : T;\n    type UnstubifyAll<A extends any[]> = {\n        [I in keyof A]: Unstubify<A[I]>;\n    };\n    // Utility type for adding `Provider`/`Disposable`s to `object` types only.\n    // Note `unknown & T` is equivalent to `T`.\n    type MaybeProvider<T> = T extends object ? Provider<T> : unknown;\n    type MaybeDisposable<T> = T extends object ? Disposable : unknown;\n    // Type for method return or property on an RPC interface.\n    // - Stubable types are replaced by stubs.\n    // - Serializable types are passed by value, with stubable types replaced by stubs\n    //   and a top-level `Disposer`.\n    // Everything else can't be passed over PRC.\n    // Technically, we use custom thenables here, but they quack like `Promise`s.\n    // Intersecting with `(Maybe)Provider` allows pipelining.\n    // prettier-ignore\n    type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;\n    // Type for method or property on an RPC interface.\n    // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.\n    // Unwrapping `Stub`s allows calling with `Stubable` arguments.\n    // For properties, rewrite types to be `Result`s.\n    // In each case, unwrap `Promise`s.\n    type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;\n    // Type for the callable part of an `Provider` if `T` is callable.\n    // This is intersected with methods/properties.\n    type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;\n    // Base type for all other types providing RPC-like interfaces.\n    // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.\n    // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.\n    export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & {\n        [K in Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]>;\n    };\n}\ndeclare namespace Cloudflare {\n    interface Env {\n    }\n}\ndeclare module 'cloudflare:workers' {\n    export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;\n    export const RpcStub: {\n        new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;\n    };\n    export abstract class RpcTarget implements Rpc.RpcTargetBranded {\n        [Rpc.__RPC_TARGET_BRAND]: never;\n    }\n    // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC\n    export abstract class WorkerEntrypoint<Env = unknown> implements Rpc.WorkerEntrypointBranded {\n        [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;\n        protected ctx: ExecutionContext;\n        protected env: Env;\n        constructor(ctx: ExecutionContext, env: Env);\n        fetch?(request: Request): Response | Promise<Response>;\n        tail?(events: TraceItem[]): void | Promise<void>;\n        trace?(traces: TraceItem[]): void | Promise<void>;\n        scheduled?(controller: ScheduledController): void | Promise<void>;\n        queue?(batch: MessageBatch<unknown>): void | Promise<void>;\n        test?(controller: TestController): void | Promise<void>;\n    }\n    export abstract class DurableObject<Env = unknown> implements Rpc.DurableObjectBranded {\n        [Rpc.__DURABLE_OBJECT_BRAND]: never;\n        protected ctx: DurableObjectState;\n        protected env: Env;\n        constructor(ctx: DurableObjectState, env: Env);\n        fetch?(request: Request): Response | Promise<Response>;\n        alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;\n        webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;\n        webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;\n        webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;\n    }\n    export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';\n    export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;\n    export type WorkflowDelayDuration = WorkflowSleepDuration;\n    export type WorkflowTimeoutDuration = WorkflowSleepDuration;\n    export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';\n    export type WorkflowStepConfig = {\n        retries?: {\n            limit: number;\n            delay: WorkflowDelayDuration | number;\n            backoff?: WorkflowBackoff;\n        };\n        timeout?: WorkflowTimeoutDuration | number;\n    };\n    export type WorkflowEvent<T> = {\n        payload: Readonly<T>;\n        timestamp: Date;\n        instanceId: string;\n    };\n    export type WorkflowStepEvent<T> = {\n        payload: Readonly<T>;\n        timestamp: Date;\n        type: string;\n    };\n    export abstract class WorkflowStep {\n        do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;\n        do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: () => Promise<T>): Promise<T>;\n        sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;\n        sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;\n        waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {\n            type: string;\n            timeout?: WorkflowTimeoutDuration | number;\n        }): Promise<WorkflowStepEvent<T>>;\n    }\n    export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {\n        [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;\n        protected ctx: ExecutionContext;\n        protected env: Env;\n        constructor(ctx: ExecutionContext, env: Env);\n        run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;\n    }\n    export const env: Cloudflare.Env;\n}\ninterface SecretsStoreSecret {\n    /**\n     * Get a secret from the Secrets Store, returning a string of the secret value\n     * if it exists, or throws an error if it does not exist\n     */\n    get(): Promise<string>;\n}\ndeclare module \"cloudflare:sockets\" {\n    function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;\n    export { _connect as connect };\n}\ndeclare namespace TailStream {\n    interface Header {\n        readonly name: string;\n        readonly value: string;\n    }\n    interface FetchEventInfo {\n        readonly type: \"fetch\";\n        readonly method: string;\n        readonly url: string;\n        readonly cfJson: string;\n        readonly headers: Header[];\n    }\n    interface JsRpcEventInfo {\n        readonly type: \"jsrpc\";\n        readonly methodName: string;\n    }\n    interface ScheduledEventInfo {\n        readonly type: \"scheduled\";\n        readonly scheduledTime: Date;\n        readonly cron: string;\n    }\n    interface AlarmEventInfo {\n        readonly type: \"alarm\";\n        readonly scheduledTime: Date;\n    }\n    interface QueueEventInfo {\n        readonly type: \"queue\";\n        readonly queueName: string;\n        readonly batchSize: number;\n    }\n    interface EmailEventInfo {\n        readonly type: \"email\";\n        readonly mailFrom: string;\n        readonly rcptTo: string;\n        readonly rawSize: number;\n    }\n    interface TraceEventInfo {\n        readonly type: \"trace\";\n        readonly traces: (string | null)[];\n    }\n    interface HibernatableWebSocketEventInfoMessage {\n        readonly type: \"message\";\n    }\n    interface HibernatableWebSocketEventInfoError {\n        readonly type: \"error\";\n    }\n    interface HibernatableWebSocketEventInfoClose {\n        readonly type: \"close\";\n        readonly code: number;\n        readonly wasClean: boolean;\n    }\n    interface HibernatableWebSocketEventInfo {\n        readonly type: \"hibernatableWebSocket\";\n        readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;\n    }\n    interface Resume {\n        readonly type: \"resume\";\n        readonly attachment?: any;\n    }\n    interface CustomEventInfo {\n        readonly type: \"custom\";\n    }\n    interface FetchResponseInfo {\n        readonly type: \"fetch\";\n        readonly statusCode: number;\n    }\n    type EventOutcome = \"ok\" | \"canceled\" | \"exception\" | \"unknown\" | \"killSwitch\" | \"daemonDown\" | \"exceededCpu\" | \"exceededMemory\" | \"loadShed\" | \"responseStreamDisconnected\" | \"scriptNotFound\";\n    interface ScriptVersion {\n        readonly id: string;\n        readonly tag?: string;\n        readonly message?: string;\n    }\n    interface Trigger {\n        readonly traceId: string;\n        readonly invocationId: string;\n        readonly spanId: string;\n    }\n    interface Onset {\n        readonly type: \"onset\";\n        readonly dispatchNamespace?: string;\n        readonly entrypoint?: string;\n        readonly scriptName?: string;\n        readonly scriptTags?: string[];\n        readonly scriptVersion?: ScriptVersion;\n        readonly trigger?: Trigger;\n        readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | Resume | CustomEventInfo;\n    }\n    interface Outcome {\n        readonly type: \"outcome\";\n        readonly outcome: EventOutcome;\n        readonly cpuTime: number;\n        readonly wallTime: number;\n    }\n    interface Hibernate {\n        readonly type: \"hibernate\";\n    }\n    interface SpanOpen {\n        readonly type: \"spanOpen\";\n        readonly op?: string;\n        readonly info?: FetchEventInfo | JsRpcEventInfo | Attribute[];\n    }\n    interface SpanClose {\n        readonly type: \"spanClose\";\n        readonly outcome: EventOutcome;\n    }\n    interface DiagnosticChannelEvent {\n        readonly type: \"diagnosticChannel\";\n        readonly channel: string;\n        readonly message: any;\n    }\n    interface Exception {\n        readonly type: \"exception\";\n        readonly name: string;\n        readonly message: string;\n        readonly stack?: string;\n    }\n    interface Log {\n        readonly type: \"log\";\n        readonly level: \"debug\" | \"error\" | \"info\" | \"log\" | \"warn\";\n        readonly message: string;\n    }\n    interface Return {\n        readonly type: \"return\";\n        readonly info?: FetchResponseInfo | Attribute[];\n    }\n    interface Link {\n        readonly type: \"link\";\n        readonly label?: string;\n        readonly traceId: string;\n        readonly invocationId: string;\n        readonly spanId: string;\n    }\n    interface Attribute {\n        readonly type: \"attribute\";\n        readonly name: string;\n        readonly value: string | string[] | boolean | boolean[] | number | number[];\n    }\n    type Mark = DiagnosticChannelEvent | Exception | Log | Return | Link | Attribute[];\n    interface TailEvent {\n        readonly traceId: string;\n        readonly invocationId: string;\n        readonly spanId: string;\n        readonly timestamp: Date;\n        readonly sequence: number;\n        readonly event: Onset | Outcome | Hibernate | SpanOpen | SpanClose | Mark;\n    }\n    type TailEventHandler = (event: TailEvent) => void | Promise<void>;\n    type TailEventHandlerName = \"onset\" | \"outcome\" | \"hibernate\" | \"spanOpen\" | \"spanClose\" | \"diagnosticChannel\" | \"exception\" | \"log\" | \"return\" | \"link\" | \"attribute\";\n    type TailEventHandlerObject = Record<TailEventHandlerName, TailEventHandler>;\n    type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;\n}\n// Copyright (c) 2022-2023 Cloudflare, Inc.\n// Licensed under the Apache 2.0 license found in the LICENSE file or at:\n//     https://opensource.org/licenses/Apache-2.0\n/**\n * Data types supported for holding vector metadata.\n */\ntype VectorizeVectorMetadataValue = string | number | boolean | string[];\n/**\n * Additional information to associate with a vector.\n */\ntype VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;\ntype VectorFloatArray = Float32Array | Float64Array;\ninterface VectorizeError {\n    code?: number;\n    error: string;\n}\n/**\n * Comparison logic/operation to use for metadata filtering.\n *\n * This list is expected to grow as support for more operations are released.\n */\ntype VectorizeVectorMetadataFilterOp = \"$eq\" | \"$ne\";\n/**\n * Filter criteria for vector metadata used to limit the retrieved query result set.\n */\ntype VectorizeVectorMetadataFilter = {\n    [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {\n        [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;\n    };\n};\n/**\n * Supported distance metrics for an index.\n * Distance metrics determine how other \"similar\" vectors are determined.\n */\ntype VectorizeDistanceMetric = \"euclidean\" | \"cosine\" | \"dot-product\";\n/**\n * Metadata return levels for a Vectorize query.\n *\n * Default to \"none\".\n *\n * @property all      Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data.\n * @property indexed  Return all metadata fields configured for indexing in the vector return set. This level of retrieval is \"free\" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings).\n * @property none     No indexed metadata will be returned.\n */\ntype VectorizeMetadataRetrievalLevel = \"all\" | \"indexed\" | \"none\";\ninterface VectorizeQueryOptions {\n    topK?: number;\n    namespace?: string;\n    returnValues?: boolean;\n    returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;\n    filter?: VectorizeVectorMetadataFilter;\n}\n/**\n * Information about the configuration of an index.\n */\ntype VectorizeIndexConfig = {\n    dimensions: number;\n    metric: VectorizeDistanceMetric;\n} | {\n    preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity\n};\n/**\n * Metadata about an existing index.\n *\n * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.\n * See {@link VectorizeIndexInfo} for its post-beta equivalent.\n */\ninterface VectorizeIndexDetails {\n    /** The unique ID of the index */\n    readonly id: string;\n    /** The name of the index. */\n    name: string;\n    /** (optional) A human readable description for the index. */\n    description?: string;\n    /** The index configuration, including the dimension size and distance metric. */\n    config: VectorizeIndexConfig;\n    /** The number of records containing vectors within the index. */\n    vectorsCount: number;\n}\n/**\n * Metadata about an existing index.\n */\ninterface VectorizeIndexInfo {\n    /** The number of records containing vectors within the index. */\n    vectorCount: number;\n    /** Number of dimensions the index has been configured for. */\n    dimensions: number;\n    /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */\n    processedUpToDatetime: number;\n    /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */\n    processedUpToMutation: number;\n}\n/**\n * Represents a single vector value set along with its associated metadata.\n */\ninterface VectorizeVector {\n    /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */\n    id: string;\n    /** The vector values */\n    values: VectorFloatArray | number[];\n    /** The namespace this vector belongs to. */\n    namespace?: string;\n    /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */\n    metadata?: Record<string, VectorizeVectorMetadata>;\n}\n/**\n * Represents a matched vector for a query along with its score and (if specified) the matching vector information.\n */\ntype VectorizeMatch = Pick<Partial<VectorizeVector>, \"values\"> & Omit<VectorizeVector, \"values\"> & {\n    /** The score or rank for similarity, when returned as a result */\n    score: number;\n};\n/**\n * A set of matching {@link VectorizeMatch} for a particular query.\n */\ninterface VectorizeMatches {\n    matches: VectorizeMatch[];\n    count: number;\n}\n/**\n * Results of an operation that performed a mutation on a set of vectors.\n * Here, `ids` is a list of vectors that were successfully processed.\n *\n * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.\n * See {@link VectorizeAsyncMutation} for its post-beta equivalent.\n */\ninterface VectorizeVectorMutation {\n    /* List of ids of vectors that were successfully processed. */\n    ids: string[];\n    /* Total count of the number of processed vectors. */\n    count: number;\n}\n/**\n * Result type indicating a mutation on the Vectorize Index.\n * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.\n */\ninterface VectorizeAsyncMutation {\n    /** The unique identifier for the async mutation operation containing the changeset. */\n    mutationId: string;\n}\n/**\n * A Vectorize Vector Search Index for querying vectors/embeddings.\n *\n * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.\n * See {@link Vectorize} for its new implementation.\n */\ndeclare abstract class VectorizeIndex {\n    /**\n     * Get information about the currently bound index.\n     * @returns A promise that resolves with information about the current index.\n     */\n    public describe(): Promise<VectorizeIndexDetails>;\n    /**\n     * Use the provided vector to perform a similarity search across the index.\n     * @param vector Input vector that will be used to drive the similarity search.\n     * @param options Configuration options to massage the returned data.\n     * @returns A promise that resolves with matched and scored vectors.\n     */\n    public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;\n    /**\n     * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.\n     * @param vectors List of vectors that will be inserted.\n     * @returns A promise that resolves with the ids & count of records that were successfully processed.\n     */\n    public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;\n    /**\n     * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.\n     * @param vectors List of vectors that will be upserted.\n     * @returns A promise that resolves with the ids & count of records that were successfully processed.\n     */\n    public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;\n    /**\n     * Delete a list of vectors with a matching id.\n     * @param ids List of vector ids that should be deleted.\n     * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).\n     */\n    public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;\n    /**\n     * Get a list of vectors with a matching id.\n     * @param ids List of vector ids that should be returned.\n     * @returns A promise that resolves with the raw unscored vectors matching the id set.\n     */\n    public getByIds(ids: string[]): Promise<VectorizeVector[]>;\n}\n/**\n * A Vectorize Vector Search Index for querying vectors/embeddings.\n *\n * Mutations in this version are async, returning a mutation id.\n */\ndeclare abstract class Vectorize {\n    /**\n     * Get information about the currently bound index.\n     * @returns A promise that resolves with information about the current index.\n     */\n    public describe(): Promise<VectorizeIndexInfo>;\n    /**\n     * Use the provided vector to perform a similarity search across the index.\n     * @param vector Input vector that will be used to drive the similarity search.\n     * @param options Configuration options to massage the returned data.\n     * @returns A promise that resolves with matched and scored vectors.\n     */\n    public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;\n    /**\n     * Use the provided vector-id to perform a similarity search across the index.\n     * @param vectorId Id for a vector in the index against which the index should be queried.\n     * @param options Configuration options to massage the returned data.\n     * @returns A promise that resolves with matched and scored vectors.\n     */\n    public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;\n    /**\n     * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.\n     * @param vectors List of vectors that will be inserted.\n     * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.\n     */\n    public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;\n    /**\n     * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.\n     * @param vectors List of vectors that will be upserted.\n     * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.\n     */\n    public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;\n    /**\n     * Delete a list of vectors with a matching id.\n     * @param ids List of vector ids that should be deleted.\n     * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.\n     */\n    public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;\n    /**\n     * Get a list of vectors with a matching id.\n     * @param ids List of vector ids that should be returned.\n     * @returns A promise that resolves with the raw unscored vectors matching the id set.\n     */\n    public getByIds(ids: string[]): Promise<VectorizeVector[]>;\n}\n/**\n * The interface for \"version_metadata\" binding\n * providing metadata about the Worker Version using this binding.\n */\ntype WorkerVersionMetadata = {\n    /** The ID of the Worker Version using this binding */\n    id: string;\n    /** The tag of the Worker Version using this binding */\n    tag: string;\n    /** The timestamp of when the Worker Version was uploaded */\n    timestamp: string;\n};\ninterface DynamicDispatchLimits {\n    /**\n     * Limit CPU time in milliseconds.\n     */\n    cpuMs?: number;\n    /**\n     * Limit number of subrequests.\n     */\n    subRequests?: number;\n}\ninterface DynamicDispatchOptions {\n    /**\n     * Limit resources of invoked Worker script.\n     */\n    limits?: DynamicDispatchLimits;\n    /**\n     * Arguments for outbound Worker script, if configured.\n     */\n    outbound?: {\n        [key: string]: any;\n    };\n}\ninterface DispatchNamespace {\n    /**\n    * @param name Name of the Worker script.\n    * @param args Arguments to Worker script.\n    * @param options Options for Dynamic Dispatch invocation.\n    * @returns A Fetcher object that allows you to send requests to the Worker script.\n    * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.\n    */\n    get(name: string, args?: {\n        [key: string]: any;\n    }, options?: DynamicDispatchOptions): Fetcher;\n}\ndeclare module 'cloudflare:workflows' {\n    /**\n     * NonRetryableError allows for a user to throw a fatal error\n     * that makes a Workflow instance fail immediately without triggering a retry\n     */\n    export class NonRetryableError extends Error {\n        public constructor(message: string, name?: string);\n    }\n}\ndeclare abstract class Workflow<PARAMS = unknown> {\n    /**\n     * Get a handle to an existing instance of the Workflow.\n     * @param id Id for the instance of this Workflow\n     * @returns A promise that resolves with a handle for the Instance\n     */\n    public get(id: string): Promise<WorkflowInstance>;\n    /**\n     * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.\n     * @param options Options when creating an instance including id and params\n     * @returns A promise that resolves with a handle for the Instance\n     */\n    public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;\n    /**\n     * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.\n     * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.\n     * @param batch List of Options when creating an instance including name and params\n     * @returns A promise that resolves with a list of handles for the created instances.\n     */\n    public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;\n}\ninterface WorkflowInstanceCreateOptions<PARAMS = unknown> {\n    /**\n     * An id for your Workflow instance. Must be unique within the Workflow.\n     */\n    id?: string;\n    /**\n     * The event payload the Workflow instance is triggered with\n     */\n    params?: PARAMS;\n}\ntype InstanceStatus = {\n    status: 'queued' // means that instance is waiting to be started (see concurrency limits)\n     | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running\n     | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish\n     | 'waitingForPause' // instance is finishing the current work to pause\n     | 'unknown';\n    error?: string;\n    output?: object;\n};\ninterface WorkflowError {\n    code?: number;\n    message: string;\n}\ndeclare abstract class WorkflowInstance {\n    public id: string;\n    /**\n     * Pause the instance.\n     */\n    public pause(): Promise<void>;\n    /**\n     * Resume the instance. If it is already running, an error will be thrown.\n     */\n    public resume(): Promise<void>;\n    /**\n     * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.\n     */\n    public terminate(): Promise<void>;\n    /**\n     * Restart the instance.\n     */\n    public restart(): Promise<void>;\n    /**\n     * Returns the current status of the instance.\n     */\n    public status(): Promise<InstanceStatus>;\n    /**\n     * Send an event to this instance.\n     */\n    public sendEvent({ type, payload, }: {\n        type: string;\n        payload: unknown;\n    }): Promise<void>;\n}\n"
  }
]